Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I reloaded an old project, and tried to run it only to run into the Binding Failure MDA Assistant: ``` BindingFailure was detected Message: The assembly with display name 'SoapTest.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.Fi...
actually yes , i went to the propensities window and set the option of "Generate serialization assembly" to "on" , by this you insure every time you build the project , i guess that error happens when you edit the assmbly info of the class library you are referencing without re building it
In VS.NET you can go to the project settings and try different settings for XmlSerialization - I believe there is a setting for auto that you may want to disable.
How do I fix a Binding Failure in Soap?
[ "", "c#", ".net", "soap", "" ]
We're reviewing one of the company's system's exception handling and found a couple of interesting things. Most of the code blocks (if not all of them) are inside a try/catch block, and inside the catch block a new BaseApplicationException is being thrown - which seems to be coming from the Enterprise Libraries. I'm i...
**Never**1 `catch (Exception ex)`. Period2. There is no way you can handle all the different kinds of errors that you may catch. Never3 catch an Exception-derived type if you can't handle it or provide additional information (to be used by subsequent exception handlers). Displaying an error message is **not** the same...
If I am reading the question correctly, I would say that implementing a try / catch which intercept exceptions (you don't mention - is it catching all exceptions, or just a specific one?) and throws a different exception is generally a bad thing. ## Disadvantages: At the very least you will lose stack trace informati...
Exception handling using an HttpModule
[ "", "c#", "asp.net", "exception", "httpmodule", "" ]
[open\_basedir](http://www.php.net/features.safe-mode) limits the files that can be opened by PHP within a directory-tree. I am storing several class libraries and configuration files outside of my web root directory. This way the web server does not make them publicly accessible. However when I try to include them fr...
You can also do this easily on a per-directory basis using the Apache (assuming this is your web server) configuration file (e.g. httpd.conf) ``` <Directory /var/www/vhosts/domain.tld/httpdocs> php_admin_value open_basedir "/var/www/vhosts/domain.tld/httpdocs:/var/www/vhosts/domain.tld/zend" </Directory> ``` you can ...
add the paths you need to access to (/var/www/vhosts/domain.tld/zend) to your open\_basedir directive (you can specify several paths using the path separator ':' or ';' in windows) note that the values in the open\_basedir are prefixes, which means that anything under the /var/www/vhosts/domain.tld/zend will be access...
How can I relax PHP's open_basedir restriction?
[ "", "php", "security", "apache", "" ]
I have a set of Word documents which I want to publish using a PHP tool I've written. I copy and paste the Word documents into a text box and then save them into MySQL using the PHP program. The problem I Have arises from all the non-standard characters that Word documents have, like curly quotes and ellipses ("..."). ...
A better solution would be to ensure that your database is set-up to support UTF-8 characters. The additional characters available in the extended set should cover all the "non-standard" characters that you're talking about. Otherwise, if you really must convert these characters into HTML entities, use [htmlentities()...
This has served me well in the past: ``` $str = mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8') ```
Converting a Word document into usable HTML in PHP
[ "", "php", "ms-word", "" ]
We have PHP 5.2.6 deployed to c:\php and in that folder there is the php.ini file. On Windows, can a website override these settings similar to the way that apache has .htaccess? e.g. ``` DirectoryIndex index.php index.html <IfModule mod_php5.c> php_flag magic_quotes_gpc off php_flag register_globals off </IfModule>...
I would recommend doing all you can to avoid changing r`egister_globals` to on as it's a major security hole. But you can try using `init_set()` to change the settings within your PHP code, although some settings cannot be changed once PHP has started running. (These are somewhat server dependent I believe.)
You can override the directives in the php.ini file several ways, but not all directives can be changed by each method. See the [php.ini directives](http://www.php.net/manual/en/ini.php) page in the manual for a list of the directives and the methods that will work on each one. The last column in the table lists the m...
Can php.ini settings be overridden in by a website using PHP + IIS6?
[ "", "php", "windows", "iis", "configuration", "" ]
I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server. One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200. So basically I should be able to navigate to withi...
Just use HEAD. No need to download the entire image if you don't need it. Here some boilerplate code. ``` HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url"); request.Method = "HEAD"; bool exists; try { request.GetResponse(); exists = true; } catch { exists = false; } ```
You might want to also check that you got an OK status code (ie HTTP 200) and that the mime type from the response object matches what you're expecting. You could extend that along the lines of, ``` public bool doesImageExistRemotely(string uriToImage, string mimeType) { HttpWebRequest request = (HttpWebRequest)We...
Test to see if an image exists in C#
[ "", "c#", ".net", "iis", "" ]
Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++? ``` MyObject object; // ok - default ctor MyObject object(blah); // ok MyObject object(); // error ``` I seem to type "()" automatically everytime. Is there a good reason this isn't...
**Most vexing parse** This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration. Another instance of the same problem: ``` std::ifstream ifs("file.txt"); std::vector<T> v(std::istr...
Because it is treated as the declaration for a function: ``` int MyFunction(); // clearly a function MyObject object(); // also a function declaration ```
Why can't the default constructor be called with empty brackets?
[ "", "c++", "constructor", "default-constructor", "c++-faq", "most-vexing-parse", "" ]
I have data that looks like > ``` > CUSTOMER, CUSTOMER_ID, PRODUCT > ABC INC 1 XYX > ABC INC 1 ZZZ > DEF CO 2 XYX > DEF CO 2 ZZZ > DEF CO 2 WWW > GHI LLC 3 ZYX > ``` I'd like to write a query that'd make the data look like this: ...
[This link](http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php) refers to a number of examples of different ways to do this on Oracle. See if there's something there that you have permissions on your database to do.
I think LISTAGG is the best aggregate group by function to use in this situation: ``` SELECT CUSTOMER, CUSTOMER_ID, LISTAGG(PRODUCT, ', ') WITHIN GROUP (ORDER BY PRODUCT) FROM SOME_TABLE GROUP BY CUSTOMER, CUSTOMER_ID ORDER BY 1, 2 ```
SQL - Multiple Values comma separated when using GROUP BY
[ "", "sql", "oracle", "oracle10g", "" ]
So what I'm looking for here is something like PHP's [print\_r](https://www.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You are really mixing together two different things. Use [`dir()`](https://docs.python.org/3/library/functions.html#dir), [`vars()`](https://docs.python.org/3/library/functions.html#vars) or the [`inspect`](https://docs.python.org/3/library/inspect.html) module to get what you are interested in (I use `__builtins__` a...
You want `vars()` mixed with `pprint()`: ``` from pprint import pprint pprint(vars(your_object)) ```
Is there a built-in function to print all the current properties and values of an object?
[ "", "python", "debugging", "introspection", "pretty-print", "python-datamodel", "" ]
In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible? (EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.) ``` function foo1...
PHP handles callbacks as strings, not function pointers. The reason your first test works is because the PHP interpreter assumes **foo1** as a string. If you have E\_NOTICE level error enabled, you should see proof of that. "Use of undefined constant foo1 - assumed 'foo1'" You can't call static methods this way, unfo...
In php 5.2, you can use a variable as the method name in a static call, but to use a variable as the class name, you'll have to use callbacks as described by BaileyP. However, from php 5.3, you **can** use a variable as the class name in a static call. So: ``` class Bar { public static function foo2($a,$b) { retu...
Reference to static method in PHP?
[ "", "php", "syntax", "" ]
I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this: ``` DateTime? d; bool success = DateTime.TryParse("some date text", out (DateTime)d); ``` the compiler tells me > 'out' argument is not classified as a variable Not sure what I need to do here. I'v...
``` DateTime? d=null; DateTime d2; bool success = DateTime.TryParse("some date text", out d2); if (success) d=d2; ``` (There might be more elegant solutions, but why don't you simply do something as above?)
As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method: ``` public static DateTime? TryParse(string text) { DateTime date; if (DateTime.TryParse(text, out date)) { return date; } else { return null; } } `...
How do I use DateTime.TryParse with a Nullable<DateTime>?
[ "", "c#", "datetime", "nullable", "" ]
This may seem a bit trivial, but I have not been able to figure it out. I am opening up a SPSite and then trying to open up a SPWeb under that SPSite. This is working fine on the VPC, which has the same Site Collection/Site hierarchy, but on production, I get an exception telling me that the URL is invalid when I try t...
Looks at the examples table at the bottom of [this page](http://msdn.microsoft.com/en-us/library/ms955307.aspx). Try not sending any parameters into the OpenWeb() method (2nd row).
Try getting the SPWeb object for "Internal" first. then get the SubWeb SPWebCollection for that and object. From that, try to get the SPWeb object for "ScheduleTool" using the GetSubwebsForCurrentUser() Method.
MOSS 2007 -- Invalid URL Exception SPSite.OpenWeb(...)
[ "", "c#", "sharepoint", "sharepoint-2007", "moss", "wss", "" ]
Is it possible to run both debuggers within the same PHP installation simultaneously. They both use different ports so communication with the client IDEs/other apps wouldn't be an issue. I ask only because using the Zend Debugger with ZendStudio has proven to be much easier (fewer steps to start/stop debugging from th...
<http://www.suspekt.org/2008/08/04/xdebug-203-stealth-patch/> (in particular the last comment) seems to indicate that the profiling parts of Xedebug will work fine alongside Zend Debugger, with the patch installed.
It is possible - the simplest way on a development web server would be to run 2 different apache processes with different php.ini files referencing the different debugger modules
Using Xdebug & Zend Debugger Simultaneously?
[ "", "php", "profiling", "xdebug", "zend-studio", "zend-debugger", "" ]
Take this non-compiling code for instance: ``` public string GetPath(string basefolder, string[] extraFolders) { string version = Versioner.GetBuildAndDotNetVersions(); string callingModule = StackCrawler.GetCallingModuleName(); return AppendFolders(basefolder, version, callingModule, extraFolders); } priv...
One option is to make the `params` parameter an `object[]`: ``` static string appendFolders(params object[] folders) { return (string) folders.Aggregate("",(output, f) => Path.Combine( (string)output ,(f is string[]) ? ...
Just pass it. The folders parameter is an array first. the "params" functionality is a little bit of compiler magic, but it's not required. ``` AppendFolders(extraFolders); ``` Now, it this particulat instance, you'll have to add some things to that array, first. ``` List<string> lstFolders = new List<string>(extraF...
Is it possible to explode an array so that its elements can be passed to a method with the params keyword?
[ "", "c#", "parameters", "keyword", "variadic-functions", "params-keyword", "" ]
I need to run a JNDI provider without the overhead of a J2EE container. I've tried to follow the directions in this [article](http://www.javaworld.com/javaworld/jw-04-2002/jw-0419-jndi.html), which describes (on page 3) exactly what I want to do. Unfortunately, these directions fail. I had to add the jboss-common.jar t...
[Apache ActiveMQ](http://activemq.apache.org/) already comes with an integrated lightweight JNDI provider. See [these instructions on using it](http://activemq.apache.org/jndi-support.html). Basically you just add the jndi.properties file to the classpath and you're done. ``` java.naming.factory.initial = org.apache....
Use a jndi.properties file like this: ``` java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory # use the following property to configure the default connector java.naming.provider.url=tcp://jmshost:61616 # use the following property to specify the JNDI name the connection factory # shou...
JNDI without a J2EE Container (with JNP? Maybe some other provider?)
[ "", "java", "jakarta-ee", "jboss", "jms", "jndi", "" ]
Assume you have a flat table that stores an ordered tree hierarchy: ``` Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 20 4 'Node 1.1.1' 2 10 5 'Node 2.1' 3 10 6 'Node 1.2' 1 20 ``...
Now that [MySQL 8.0 supports recursive queries](https://dev.mysql.com/doc/refman/8.0/en/with.html), we can say that [all popular SQL databases support recursive queries](https://stackoverflow.com/questions/324935/mysql-with-clause/325243#325243) in standard syntax. ``` WITH RECURSIVE MyTree AS ( SELECT * FROM MyTa...
If you use nested sets (sometimes referred to as Modified Pre-order Tree Traversal) you can extract the entire tree structure or any subtree within it in tree order with a single query, at the cost of inserts being more expensive, as you need to manage columns which describe an in-order path through thee tree structure...
What is the most efficient/elegant way to parse a flat table into a tree?
[ "", "sql", "algorithm", "recursion", "tree", "hierarchical-data", "" ]
Using something like this: ``` try: # Something... except Exception as excep: logger = logging.getLogger("component") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) ``` I would rather not have it on the error-level cause in my special case ...
From the [logging documentation](http://docs.python.org/library/logging.html#logging.Logger.debug): > There are three keyword arguments in `kwargs` which are inspected: `exc_info`, `stack_info`, and `extra`. > > If `exc_info` does not evaluate as false, it causes exception information to be added to the logging messag...
Here is one that works (python 2.6.5). ``` logger.critical("caught exception, traceback =", exc_info=True) ```
How do I log an exception at warning- or info-level with traceback using the python logging framework?
[ "", "python", "exception", "logging", "python-logging", "" ]
I'm writing a Windows Forms Application in C#.NET On startup, the application displays a splash screen which is running in a separate thread. Whilst the splash screen is showing, the main application is initialising. Once the main application has finished initialising, the main form of the application is displayed, a...
Try calling .Activate() on your main window when your thread closes. It's never been active, and thus has low Z-Order, so whatever is higher will naturally be above it. I had to fix this exact scenario in our app. Don't forget! You may need to marshal the call to the correct thread using an Invoke()!
I've had this happen at times too. Bob's response is the easiest and works for me in the majority of cases. However, there have been some times where I need to use brute force. Do this via interop like this: [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
Application window sent behind other windows on closing different thread (C#)
[ "", "c#", "winforms", "multithreading", "splash-screen", "" ]
I have found that when I execute the show() method for a contextmenustrip (a right click menu), if the position is outside that of the form it belongs to, it shows up on the taskbar also. I am trying to create a right click menu for when clicking on the notifyicon, but as the menu hovers above the system tray and not ...
Try assigning your menu to the ContextMenuStrip property of NotifyIcon rather than showing it in the mouse click handler.
The best and right way, without Reflection is: ``` { UnsafeNativeMethods.SetForegroundWindow(new HandleRef(notifyIcon.ContextMenuStrip, notifyIcon.ContextMenuStrip.Handle)); notifyIcon.ContextMenuStrip.Show(Cursor.Position); } ``` where **UnsafeNativeMethods.SetForegroundWindow** is: ``` public static class Unsa...
Show a ContextMenuStrip without it showing in the taskbar
[ "", ".net", "c++", "winforms", "" ]
I have boiled down an issue I'm seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there's something amiss or something I'm missing. Anyway, below is the code. The behavior is that the code runs and steadily grows in memory until it crashes with an OutOfMemoryException. Tha...
I was able to reproduce your problem using the code you provided. Memory keeps growing because the Canvas objects are never released; a memory profiler indicates that the Dispatcher's ContextLayoutManager is holding on to them all (so that it can invoke OnRenderSizeChanged when necessary). It seems that a simple worka...
WPF in .NET 3 and 3.5 has an internal memory leak. It only triggers under certain situations. We could never figure out exactly what triggers it, but we had it in our app. Apparently it's fixed in .NET 4. I think it's the same as the one mentioned in [this blog post](http://wesaday.wordpress.com/tag/cmilchannel-hwndso...
Simple WPF sample causes uncontrolled memory growth
[ "", "c#", "wpf", "memory-leaks", "" ]
What I am looking for is a way to call a method after another method has been invoked but before it is entered. Example: ``` public class Test { public void Tracer ( ... ) { } public int SomeFunction( string str ) { return 0; } public void TestFun() { SomeFunction( "" ); } } ``` In the e...
You can use a dynamic proxy ([Castle's DynamicProxy](http://www.castleproject.org/dynamicproxy/index.html) for example) to intercept the call, run whatever code you wish, and then either invoke your method or not, depending on your needs.
**Use delegates!** ``` delegate void SomeFunctionDelegate(string s); void Start() { TraceAndThenCallMethod(SomeFunction, "hoho"); } void SomeFunction(string str) { //Do stuff with str } void TraceAndThenCallMethod(SomeFunctionDelegate sfd, string parameter) { Trace(); sfd(parameter); } ```
Is there a way in .NET to have a method called automatically after another method has been invoked but before it is entered
[ "", "c#", ".net", "" ]
I have the following two models: ``` class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.no...
What you want to look into is [Django's signals](http://docs.djangoproject.com/en/dev/ref/signals/) (check out [this page](http://docs.djangoproject.com/en/dev/topics/signals/) too), specifically the model signals--more specifically, the **post\_save** signal. Signals are Django's version of a plugin/hook system. The p...
What's wrong with the following? ``` class Cancellation( models.Model ): blah blah def save( self, **kw ): for a in self.activity_set.all(): a.somethingChanged( self ) super( Cancellation, self ).save( **kw ) ``` It would allow you to to control the notification among models ve...
In Django how do I notify a parent when a child is saved in a foreign key relationship?
[ "", "python", "django", "django-models", "" ]
I am selecting from a table that has an XML column using T-SQL. I would like to select a certain type of node and have a row created for each one. For instance, suppose I am selecting from a *people* table. This table has an XML column for *addresses*. The XML is formated similar to the following: ``` <address> <st...
Here is your solution: ``` /* TEST TABLE */ DECLARE @PEOPLE AS TABLE ([Name] VARCHAR(20), [Address] XML ) INSERT INTO @PEOPLE SELECT 'Joel', '<address> <street>Street 1</street> <city>City 1</city> <state>State 1</state> <zipcode>Zip Code 1</zipcode> </address> <address> ...
Here's how I do it generically: I shred the source XML via a call such as ``` DECLARE @xmlEntityList xml SET @xmlEntityList = ' <ArbitrarilyNamedXmlListElement> <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>1</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement> <Arbitrar...
Select XML nodes as rows
[ "", "sql", "xml", "t-sql", "xpath", "" ]
What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C. ``` unsigned char buffer[256]; for (int i = 0; i < 256; i++) buffer[i]=i; int size = 1; int count = 256; ``` Binary mode: ``` FILE *fp_binary = fopen(filename, "wb"); fwrite(b...
I believe that most platforms will ignore the "t" option or the "text-mode" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: [MSDN](http://msdn.microsoft.com/en-us/library/yeby3zcb(vs.71).aspx), you will see that specifying th...
In text mode, a newline "\n" may be converted to a carriage return + newline "\r\n" Usually you'll want to open in binary mode. Trying to read any binary data in text mode won't work, it will be corrupted. You can read text ok in binary mode though - it just won't do automatic translations of "\n" to "\r\n". See [fop...
Difference between files written in binary and text mode
[ "", "c++", "c", "file-io", "" ]
Using the following code I get a nice formatted string: ``` Request.QueryString.ToString ``` Gives me something like: &hello=world&microsoft=sucks But when I use this code to clone the collection to another object (of the same type) I get the Type() back from the ToString() method instead. ``` System.Collections.Sp...
You can also use Reflector to extract the `HttpValueCollection` class into your own, and use it then.
HttpValueCollection is internal, but you can use "var" to declare it without extract it with reflector. ``` var query = HttpUtility.ParseQueryString(Request.Url.Query); query["Lang"] = myLanguage; // Add or replace param string myNewUrl = Request.Url.AbsolutePath + "?" + query; ```
Outputting a manipulated QueryString in C#
[ "", "c#", "asp.net", "collections", "query-string", "" ]
OK, first for context look at the Windows desktop; You can take items (folders, files) on the desktop and drag them around to different places and they "stay" where you dragged them. This seems to be a pretty useful feature to offer users so as to allow them to create their own "groupings" of items. My question is thu...
You can do this with a standard ListView control by implementing drag-and-drop. Here's a sample control that does this: ``` using System; using System.Drawing; using System.Windows.Forms; public class MyListView : ListView { private Point mItemStartPos; private Point mMouseStartPos; public MyListView() { t...
I think the closest would the ListView control, but even that is more like an explorer window. You might be able to create your own view that does what you want, but you'd need to manually persist icon locations somewhere.
.NET: is there a Click-and-drag "Desktop-Like" control?
[ "", "c#", ".net", "forms", "controls", "user-interface", "" ]
Is it possible to use `request.setAttribute` on a JSP page and then on HTML Submit get the same request attribute in the `Servlet`?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere. If you want to persist attributes through requests you need to either: 1. Have a hidden input in your form, such as `<input type="hidden" name...
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which *really* need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a...
Using request.setAttribute in a JSP page
[ "", "java", "jakarta-ee", "setattribute", "request-object", "" ]
Consider this: ``` var query = from r in this._db.Recipes where r.RecipesID == recipeID select new { r.RecipesID, r.RecipesName }; ``` How would i get individual columns in my `query` object without using a for-loop? Basicly: how do I translate `DataTable.Rows[0]["ColumnName"]` into Linq synt...
This is the way to go about it: ``` DataContext dc = new DataContext(); var recipe = (from r in dc.Recipes where r.RecipesID == 1 select r).FirstOrDefault(); if (recipe != null) { id = recipe.RecipesID; name = recipe.RecipesName; } ```
It's really unclear what you are looking for, as your two samples are compatible. As close as I can figure, what you want is: ``` var rows = query.ToList(); string name = rows[0].RecipesName; ```
Linq to SQL: DataTable.Rows[0]["ColumnName"] equivalent
[ "", "c#", "linq", "c#-3.0", "" ]
How would I reset the primary key counter on a sql table and update each row with a new primary key?
I would add another column to the table first, populate that with the new PK. Then I'd use update statements to update the new fk fields in all related tables. Then you can drop the old PK and old fk fields. **EDIT:** Yes, as Ian says you will have to drop and then recreate all foreign key constraints.
Not sure which DBMS you're using but if it happens to be SQL Server: ``` SET IDENTITY_INSERT [MyTable] ON ``` allows you to update/insert the primary key column. Then when you are done updating the keys (you could use a [CURSOR](http://msdn.microsoft.com/en-us/library/ms180169.aspx) for this if the logic is complicat...
renumber primary key
[ "", "sql", "primary-key", "" ]
I have been trying to read a picture saved in Access DB as a OLE object in a PictureBox in a C# windows Application. The code that does this is presented below: ``` string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Rajesh\SampleDB_2003.mdb;"; OleDbConnection oConn = new OleDbConnec...
Your bytestream is corrupted somehow, becouse I tried the exact method of yours but filled the byte array with PNG data from a file instead. I would suggest creating two streams, one from the database, and one from the file that was the source of the image in the database. Then compare them byte by byte. If there is e...
Unfortunately I have no good answer for you, but I can tell you that when I tried, I got the same results. Sometimes skipping the first 78 bytes of the byte array worked, sometimes it didn't. This is because the OLE Object datatype stores some kind of header in the field, so that Access knows what type of OLE Object i...
Read a picture from Access DB into PictureBox
[ "", "c#", "ms-access", "picturebox", "" ]
I have recently been working with Python using Komodo Edit and other simpler editors but now I am doing a project which is to be done in C# using VS 08. I would appreciate any hints on how to get productive on that platform as quickly as possible.
As far as becoming proficient with C# I would highly recommend [Programming C#](https://rads.stackoverflow.com/amzn/click/com/0596527438) and [C# in Depth](https://rads.stackoverflow.com/amzn/click/com/1933988363). For Visual Studio, start poking around in the IDE a lot, play around, get familiar with it. Start with s...
I would personally concentrate on learning the core parts of both C# and .NET first. For me, that would mean writing console apps (rather than Windows Forms) to experiment with the language and important aspects like IO. When you're happy with the foundations, move onto whichever "peripheral" technology (WinForms, WPF,...
Fastest way to get productive in VS 08 and C#
[ "", "c#", "visual-studio", "visual-studio-2008", "development-environment", "" ]
I have a problem wih a logging setup in a apring webapp deployed under tomcat 6. The webapp uses the commons-logging api, on runtime log4j should be used. The log file is created but remains empty - no log entries occur. the setup is the following: WEB-INF/web.xml: ``` <context-param> <param-name>log4jConfigLo...
There are numerous documented instances on the web warning people about the use of commons-logging. So much so, that [SLF4J](http://www.slf4j.org/) is gaining a lot of popularity. Considering that you are not interested in using Tomcat with Log4j, you should just use Log4j directly in your application. Particularly if...
Be especially careful that you have **not** placed log4j.jar in the Tomcat commons/lib directory. If the root classloader loads the log4j libraries, you'll run into conflicts and initialization problems when your webapps also try to use log4j. If you need to use log4j for common Tomcat logging, you'll need to be caref...
Problem with Commons Logging / Log4j setup in spring webapp with tomcat 6
[ "", "java", "tomcat", "logging", "log4j", "" ]
I am writing an XML document in C#. I have something like this... ``` string output = "REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _"; ``` and I do this... ``` objXmlTextWrit...
Sorry, got confused before (deleted the wrong answer). But I can't reproduce what you seem to be seeing. Check this program... it does preserve spaces. ``` class Program { static void Main(string[] args) { XmlWriter w = XmlTextWriter.Create("./foo.xml"); w.WriteStartElement("foo"); w.W...
OK... This is only an IE display problem. Something to do with the font I guess. When I open the XML in notepad++ I see the white space is actually preserved properly.
Preserve white space in string with XmlTextWriter.WriteString
[ "", "c#", ".net", "xml", "whitespace", "" ]
Ruby on Rails has a lot of ways to generate JavaScript. Particularly when it comes to Ajax. Unfortunately, there are a few problems that I often see with the JavaScript that it generates. * Rails typically uses inline event handling. ``` <a onclick="somejavascript(); return false;" /> ``` This is generally f...
If you prefer jQuery you can use the [jQuery on Rails Project](http://ennerchi.com/projects/jrails). A drop in to replace Prototype with jQuery. Some of what Rails does with Javascript generation is good and some is bad. In the bad instances, write it yourself and keep it unobtrusive. At any given time you're uncomfor...
I used to work in Symfony (a Rails clone) and at first, we used a lot of Javascript helpers. Client requirements led us (me!) to have to write a lot of code the helpers just couldn't generate. I eventually came to the conclusion that I prefer not to use helpers **at all.** Progressive enhancement is the way to go, in ...
How much JavaScript do you let Rails generate?
[ "", "javascript", "ruby-on-rails", "ruby", "" ]
I have a Timestamp value that comes from my application. The user can be in any given local TimeZone. Since this date is used for a WebService that assumes the time given is always in GMT, I have a need to convert the user's parameter from say (EST) to (GMT). Here's the kicker: The user is oblivious to his TZ. He ente...
Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so...
``` public static Calendar convertToGmt(Calendar cal) { Date date = cal.getTime(); TimeZone tz = cal.getTimeZone(); log.debug("input calendar has date [" + date + "]"); //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT long msFromEpochGmt = date.getTime(); //gives you...
How to handle calendar TimeZones using Java?
[ "", "java", "calendar", "timezone", "" ]
What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?
**From .NET 4.5 on, there is the [`Stream.CopyToAsync` method](http://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx)** ``` input.CopyToAsync(output); ``` This will return a [`Task`](http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx) that can be continued on when completed, ...
`MemoryStream` has `.WriteTo(outstream);` and .NET 4.0 has `.CopyTo` on normal stream object. .NET 4.0: ``` instream.CopyTo(outstream); ```
How do I copy the contents of one stream to another?
[ "", "c#", "stream", "copying", "" ]
Here's the scenario: You have a Windows server that users remotely connect to via RDP. You want your program (which runs as a service) to know who is currently connected. This may or may not include an interactive console session. Please note that this is the **not** the same as just retrieving the current interactiv...
Here's my take on the issue: ``` using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace EnumerateRDUsers { class Program { [DllImport("wtsapi32.dll")] static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] string pServerName); [DllImport("wtsapi32...
Another option, if you don't want to deal with the P/Invokes yourself, would be to use the [Cassia](https://github.com/danports/cassia) library: ``` using System; using System.Security.Principal; using Cassia; namespace CassiaSample { public static class Program { public static void Main(string[] args...
How do you retrieve a list of logged-in/connected users in .NET?
[ "", "c#", ".net", "windows-services", "authentication", "" ]
I am relatively new to matchers. I am toying around with [hamcrest](http://code.google.com/p/hamcrest/) in combination with JUnit and I kinda like it. Is there a way, to state that one of multiple choices is correct? Something like ``` assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamc...
``` assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3))) ``` From [Hamcrest tutorial](http://hamcrest.org/JavaHamcrest/tutorial#logical): > `anyOf` - matches if any matchers match, short circuits (like Java ||) See also [Javadoc](http://hamcrest.org/JavaHamcrest/javadoc/2.2/org/hamcrest/core/AnyOf.html). M...
marcos is right, but you have a couple other options as well. First of all, there *is* an either/or: ``` assertThat(result, either(is(1)).or(is(2))); ``` but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do: ```...
Multiple correct results with Hamcrest (is there an or-matcher?)
[ "", "java", "junit", "hamcrest", "matcher", "" ]
I have a table that was imported as all UPPER CASE and I would like to turn it into Proper Case. What script have any of you used to complete this?
Here's a UDF that will do the trick... ``` create function ProperCase(@Text as varchar(8000)) returns varchar(8000) as begin declare @Reset bit; declare @Ret varchar(8000); declare @i int; declare @c char(1); if @Text is null return null; select @Reset = 1, @i = 1, @Ret = ''; while (@i <= len(@Tex...
This function: * "Proper Cases" all "UPPER CASE" words that are delimited by white space * leaves "lower case words" alone * works properly even for non-English alphabets * is portable in that it does not use fancy features of recent SQL server versions * can be easily changed to use NCHAR and NVARCHAR for unicode sup...
SQL Server: Make all UPPER case to Proper Case/Title Case
[ "", "sql", "sql-server", "uppercase", "title-case", "" ]
I have been tasked to optimize some sql queries at work. Everything I have found points to using Explain Plan to identify problem areas. The problem I can not find out exactly what explain plan is telling me. You get Cost, Cardinality, and bytes. What do this indicate, and how should I be using this as a guide. Are lo...
You get more than that actually depending on what you are doing. Check out this [explain plan](http://www.oracle-base.com/articles/8i/ExplainPlanUsage.php) page. I'm assuming a little bit here that you are using Oracle and know how to run the script to display the plan output. What may be more important to start with i...
I also assume you are using Oracle. And I also recommend that you check out the explain plan web page, for starters. There is a lot to optimization, but it can be learned. A few tips follow: First, when somebody tasks you to optimize, they are almost always looking for acceptable performance rather than ultimate perf...
How to use Explain Plan to optimize queries?
[ "", "sql", "oracle", "optimization", "" ]
What is the most reliable and secure way to determine what page either sent, or called (via AJAX), the current page. I don't want to use the `$_SERVER['HTTP_REFERER']`, because of the (lack of) reliability, and I need the page being called to only come from requests originating on my site. Edit: I am looking to ve...
The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons. If you want to verify if a request is coming from your site, well you can't, but you can verify the user has bee...
What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer. So if you are generating a FB callback then it would look something like this: ``` $token = uniqid(mt_rand(), TRUE); $_SESSION['token'] = $token; $url = "http://example.com/index.php?token={$token}"; ```...
Determining Referer in PHP
[ "", "php", "http-referer", "" ]
I have a swing application that includes radio buttons on a form. I have the `ButtonGroup`, however, looking at the available methods, I can't seem to get the name of the selected `JRadioButton`. Here's what I can tell so far: * From ButtonGroup, I can perform a `getSelection()` to return the `ButtonModel`. From there...
I would just loop through your `JRadioButtons` and call `isSelected()`. If you really want to go from the `ButtonGroup` you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?
I got similar problem and solved with this: ``` import java.util.Enumeration; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; public class GroupButtonUtils { public String getSelectedButtonText(ButtonGroup buttonGroup) { for (Enumeration<AbstractButton> buttons = buttonGroup.getElement...
How do I get which JRadioButton is selected from a ButtonGroup
[ "", "java", "swing", "" ]
I'm writing a query to summarize some data. I have a flag in the table that is basically boolean, so I need some sums and counts based on one value of it, and then the same thing for the other value, like so: ``` select location ,count(*) ,sum(duration) from my.table where type = 'X' and location = @location ...
``` select location ,Sum(case when type = 'X' then 1 else 0 end) as xCount ,Sum(case when type = 'Y' then 1 else 0 end) as YCount ,Sum(case when type = 'X' then duration else 0 end) as xCountDuration ,Sum(case when type = 'Y' then duration else 0 end) as YCountDuration from my.table where location = @locati...
Your example with the join doesn't make a lot of sense. You're doing a Cartesian product between A and B. Is this really what you want? The following will find count(\*) and sum(duration) for each pair that satisfies the WHERE clause. Based on your description, this sounds like what you're looking for: ``` select ...
Group by when joining the same table twice
[ "", "sql", "db2", "" ]
How do I get the [ASCII](https://en.wikipedia.org/wiki/ASCII) value of a character as an `int` in Python?
From [here](http://mail.python.org/pipermail/python-win32/2005-April/003100.html): > The function **`ord()`** gets the int value > of the char. And in case you want to > convert back after playing with the > number, function **`chr()`** does the trick. ``` >>> ord('a') 97 >>> chr(97) 'a' >>> chr(ord('a') + 3) 'd' >>>...
Note that `ord()` doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of `ord('ä')` can be 228 if you're using Latin-1, or it can raise a `TypeError` if you're using UTF-8. It can even return the Unicode codepoint instead if you pas...
How to get the ASCII value of a character
[ "", "python", "ascii", "" ]
I want to do some basic filtering on a file. Read it, do processing, write it back. I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with: ``` from __future__ import with_statement filename = "..." # or sys.argv... with open(filename) as f: new_txt = # ...s...
Actually an easier way using fileinput is to use the inplace parameter: ``` import fileinput for line in fileinput.input (filenameToProcess, inplace=1): process (line) ``` If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file. This exampl...
I would go for elegance a different way: implement your file-reading and filtering operations as generators, You'll write more lines of code, but it will be more flexible, maintainable, and performant code. See David M. Beazley's [Generator Tricks for Systems Programmers](http://www.dabeaz.com/generators/), which is a...
Open file, read it, process, and write back - shortest method in Python
[ "", "python", "coding-style", "" ]
Which algorithm does the JavaScript `Array#sort()` function use? I understand that it can take all manner of arguments and functions to perform different kinds of sorts, I'm simply interested in which algorithm the vanilla sort uses.
I've just had a look at the WebKit (Chrome, Safari …) [source](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/ArrayPrototype.cpp?rev=138530#L647). Depending on the type of array, different sort methods are used: [Numeric arrays](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSA...
If you look at this bug [224128](https://bugzilla.mozilla.org/show_bug.cgi?id=224128), it appears that MergeSort is being used by Mozilla.
Javascript Array.sort implementation?
[ "", "javascript", "algorithm", "arrays", "sorting", "" ]
I have a search form on each of my pages. If I use form helper, it defaults to `$_POST`. I'd like the search term to show up in the URI: ``` http://example.com/search/KEYWORD ``` I've been on Google for about an hour, but to no avail. I've only found articles on how `$_GET` is basically disabled, because of the nativ...
There's a better fix if you're dealing with people without JS enabled. **View:** ``` <?php echo form_open('ad/pre_search');?> <input type="text" name="keyword" /> </form> ``` **Controller** ``` <?php function pre_search() { redirect('ad/search/.'$this->input->post('keyword')); } function...
As far as I know, there is no method of accomplishing this with a simple POST. However, you can access the form via Javascript and update the destination. For example: ``` <form id="myform" onsubmit="return changeurl();" method="POST"> <input id="keyword"> </form> <script> function changeurl() { var form = docume...
Simple Search: Passing Form Variable to URI Using CodeIgniter
[ "", "php", "codeigniter", "" ]
I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this. Which of these offers the best perf...
Always use **T.TryParse(string str, out T value)**. Throwing exceptions is expensive and should be avoided if you can handle the situation *a priori*. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good cod...
Try-Catch will always be the slower. TryParse will be faster. The IF and TryParse are the same.
Parsing Performance (If, TryParse, Try-Catch)
[ "", "c#", "parsing", "text", "" ]
I know that you can run almost all Java in *Dalvik's VM* that you can in *Java's VM* but the limitations are not very clear. Has anyone run into any major stumbling blocks? Any major libraries having trouble? Any languages that compile to Java byte code (**Scala**, **Jython** etc...) not work as expected?
There is a number of things that Dalvik will not handle or will not handle quite the same way as standard Java bytecode, though most of them are quite advanced. The **most severe example is runtime bytecode generation** and custom class loading. Let's say you would like to create some bytecode and then use classloader...
If you see "[Dalvik Virtual Machine internals](http://www.youtube.com/watch?v=ptjedOZEXPM)" Google IO session, you can find Dalvik does not support [generational GC](http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29#Generational_GC_.28aka_Ephemeral_GC.29). So, it could degrade performance of frequ...
What can you not do on the Dalvik VM (Android's VM) that you can in Sun VM?
[ "", "java", "android", "jvm", "dalvik", "" ]
I need write an update statement that used multiple tables to determine which rows to update, since in Oracle, multiple tables aren't allowed. The following query will return a "ORA-00971: Missing SET keyword" error ``` UPDATE TABLE1 a, TABLE2 b SET a.COL1 = 'VALUE' WHERE a.FK = b.PK AND b.COL2 IN ('SET OF V...
Another option: ``` UPDATE TABLE1 a SET a.COL1 = 'VALUE' WHERE a.FK IN ( SELECT b.PK FROM TABLE2 b WHERE b.COL2 IN ('SET OF VALUES') ) ``` Your second example would work if (a) the view included the **declared** PK of TABLE1: ``` UPDATE ( SELECT a.COL1, a.PKCOL FROM TABLE1 a, TABLE2 b ...
I find that a nice, quick, consistent way to turn a SELECT statement into an UPDATE is to make the update based on the ROWID. ``` UPDATE TABLE1 SET COL1 = 'VALUE' WHERE ROWID in ( SELECT a.rowid FROM TABLE1 a, TABLE2 b WHERE a.FK = b.PK AND b.COL2 IN ('SET OF VALUES'...
Using a subquery instead of a table name in an Oracle Update Statement
[ "", "sql", "oracle", "" ]
I have a page that is supposed to launch the Print Preview page onload. I found this: ``` var OLECMDID = 7; /* OLECMDID values: * 6 - print * 7 - print preview * 1 - open window * 4 - Save As */ var PROMPT = 1; // 2 DONTPROMPTUSER var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340...
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk. That's why your example uses Active X, which bypasses the JavaScript security issues. So instead use the print stylesheet that you already should have and show it for m...
I think the best that's possible in cross-browser JavaScript is `window.print()`, which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog. FYI, the *print dialog* is your computer's Print popup, what you get when you do Ctrl-p. The *print preview* is Firefox's own Preview window, and...
How can Print Preview be called from Javascript?
[ "", "javascript", "printing", "" ]
In my experience Meta-templates are really fun (when your compilers are compliant), and can give good performance boosts, and luckily I'm surrounded by seasoned C++ programmers that also grok meta-templates, however occasionally a new developer arrives and can't make heads or tails of some of the meta-template tricks w...
If you can you find enough candidates who really know template meta-programing then by all means, require it. You will be showing a lot of qualified and potentially productive people the door (there are plenty of legitimate reasons not to know how to do this, namely that if you do it on a lot of platforms, you will cre...
Yes, but I would not personally place a high priority on it. It's a nifty feature, but it's a bit situational, and good C++ code can be developed without it. I've personally used it once or twice, but haven't really found it to be valuable enough in *my* work to regularly use it. (Maybe that's a function of my lack of ...
Are C++ meta-templates required knowledge for programmers?
[ "", "c++", "metaprogramming", "" ]
I have a table, call it TBL. It has two columns,call them A and B. Now in the query I require one column as A and other column should be a comma seprated list of all B's which are against A in TBL. e.g. TBL is like this 1 Alpha 2 Beta 1 Gamma 1 Delta Result of query should be 1 Alpha,Gamma,Delta 2 Beta This typ...
You can concatenate the records with a User Defined Function (UDF). The code below can be pasted 'as is' into a standard module. The SQL for you example would be: ``` SELECT tbl.A, Concatenate("SELECT B FROM tbl WHERE A = " & [A]) AS ConcA FROM tbl GROUP BY tbl.A ``` This code is by DHookom, Access MVP, and...
I believe you can create VBA functions and use them in your access queries. That might help you.
Does MS access(2003) have anything comparable to Stored procedure. I want to run a complex query in MS acceess
[ "", "sql", "ms-access", "stored-procedures", "ms-office", "" ]
Exception is: 'Country' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value ``` UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country"); Country.DataSource = dsCountry.tblDropDownValues; Country.DataTextField = "AttrValue"...
Every time I got this error it was because the keys I was matching on to bind my data didn't match. The lines you showed may not be the problem. Look into when you are possibly loading a record from another table and binding their values into the dropdown list. For example, if you have a dropdown list on your page th...
Try binding the data on postback. It sounds like when the event handler is accessing the DropDownList, it hasn't been repopulated with the values you are initially binding to the DropDownList. Also, remember to bind early enough so that it is bound before the event handler starts its processing. OnInit or OnLoad shoul...
SelectedValue is invalid - doesn't exist in list - C#/ASP.NET
[ "", "c#", "asp.net", "" ]
Has Java 1.6 SDK been released for mac? I can't seem to find it...
Yes, but only for 64-bit Intel-based Macs, i.e. Macs using Core 2 (duo or solo) or Xeon chips. The original Core chip is not supported, nor is any PPC chip. Also, Java 6 is currently Leopard-only. The update should appear in Software Update, if you have a compatible Mac and recent-enough OS version. Here are the relea...
If you don't have a 64-bit Intel-based Mac you may also be interested in [SoyLatte](http://landonf.bikemonkey.org/static/soylatte/) which is an independent X11-based port of Java 1.6 based on the FreeBSD version.
Java 1.6 SDK on Mac OS 10.5
[ "", "java", "macos", "" ]
At the moment, our application uses the Trident Win32 component, but we want to move away from that for a few reasons, chief among them being our desire to go cross-platform. We're looking at [WebKit](http://webkit.org/) and [Gecko](http://developer.mozilla.org/en/Gecko), but I'd love to get some feedback before I mak...
A little history might help in your decision. When Apple was considering which engine to use in making Safari they looked at Gecko, but decided to go with KHTML, fork it and called it WebKit. Their reasons for doing this was that Gecko had tons of legacy cruft still leftover from Netscape and was far more complicated. ...
I am biased, but if you do not mind using (LGPL-ed) Qt, what about using [QtWebKit](http://doc.trolltech.com/4.5/qtwebkit.html)? It is fairly easy to embed, cross-platform of course, has a nice web browser demonstration, and also other [related examples](http://labs.trolltech.com/blogs/category/labs/internet/webkit/).
What is the best HTML Rendering Engine to embed in an application?
[ "", "c++", "qt", "webkit", "gecko", "rendering-engine", "" ]
Is there a dialect of XML for defining the tables, indexes and relations of a relational database, and a "compiler" or stylesheet to transform that definition into SQL CREATE statements (DDL)? EG, something that might look like: ``` <Table Name="orders"> <Column Name="order_id" Type="varchar" Size="20"/> ... ...
Something like [xml2ddl](http://xml2ddl.berlios.de/)?
Sounds like XML based migrations, never seen one though. If you're into OR/M you could take a look at (N)Hibernate's [hbm2ddl](http://www.hibernate.org/hib_docs/reference/en/html/toolsetguide.html) tool. It generates the appropriate create commands for the schema on various database dialects out of an XML definition.
Is there an XML language for defining/authoring SQL database schemas?
[ "", "sql", "xml", "database", "xslt", "" ]
Using Vim, I'm trying to pipe text selected in visual mode to a UNIX command and have the output appended to the end of the current file. For example, say we have a SQL command such as: ``` SELECT * FROM mytable; ``` I want to do something like the following: ``` <ESC> V " select text :'<,'>!mysql -u...
How about copying the selected text to the end of the file, select the copy and run the command? If you do not want to repeat the same commands over and over again, you can record the sequence by using `q` or add a new command. I have tried the latter as follows: ``` :com -range C <line1>,<line2>yank | $ | put | .,$ !...
If you prefer more programmatic approach, you can have ``` :call append(line("$"), system("command", GetSelectedText())) ``` where `GetSelectedText` is the reusable function: ``` func! GetSelectedText() normal gv"xy let result = getreg("x") normal gv return result endfunc ```
How to pipe visually selected text to a UNIX command and append output to current buffer in Vim
[ "", "sql", "vim", "editor", "vi", "" ]
I'm searching for a **PHP syntax highlighting engine** that can be customized (i.e. I can provide my **own tokenizers** for new languages) and that can handle several languages *simultaneously* (i.e. on the same output page). This engine has to work well together with **CSS classes**, i.e. it should format the output b...
Since no existing tool satisfied my needs, I wrote my own. Lo and behold: ## [Hyperlight](https://github.com/klmr/hyperlight) Usage is extremely easy: just use ``` <?php hyperlight($code, 'php'); ?> ``` to highlight code. Writing new language definitions is relatively easy, too – using regular expressions and a po...
[I marked this answer as *Community Wiki* because you're specifically *not* looking for Javascript] **<http://softwaremaniacs.org/soft/highlight/>** is a PHP (*plus the following list of other languages supported*) syntax highlighting library: > *Python, Ruby, Perl, PHP, XML, HTML, CSS, Django, Javascript, VBScript, ...
PHP syntax highlighting
[ "", "php", "syntax-highlighting", "" ]
What is the best way to overwrite a specific line in a file? I basically want to search a file for the string '@parsethis' and overwrite the rest of that line with something else.
If the file isn't too big, the best way would probably be to read the file into an array of lines with [file()](http://php.net/file), search through the array of lines for your string and edit that line, then [implode()](http://php.net/implode) the array back together and [fwrite()](http://php.net/fwrite) it back to th...
If the file is really big (log files or something like this) and you are willing to sacrifice speed for memory consumption you could open two files and essentially do the trick [Jeremy Ruten](https://stackoverflow.com/questions/235604/overwite-line-in-file-with-php#235610) proposed by using files instead of system memo...
Overwrite Line in File with PHP
[ "", "php", "file-io", "fopen", "fwrite", "" ]
I have a little demonstration below of a peculiar problem. ``` using System; using System.Windows.Forms; namespace WindowsApplication1 { public class TestForm : Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Win...
Firstly, thanks for the complete program - it made it *much* easier to work out what was going on! While the textbox isn't visible, it isn't resized. When you select tabPage1, the Selected event fires *before* the controls become visible and the textbox gets laid out again. Now, that's why it's happening - but what's...
I'm pretty sure that what's happening is the `Selected` event is raised slightly before the tab page becomes visible. The text box is not resized until the tab page becomes visible, so you end up checking the value of the text box's size before it is actually resized. When you change tabs again, the text box is already...
Question about an event perculiarity in a TabControl
[ "", "c#", "winforms", "event-handling", "tabcontrol", "" ]
Does anyone know how to programmaticly find out where the java classloader actually loads the class from? I often work on large projects where the classpath gets very long and manual searching is not really an option. I recently had a [problem](https://stackoverflow.com/questions/226280/eclipse-class-version-bug "prob...
Here's an example: ``` package foo; public class Test { public static void main(String[] args) { ClassLoader loader = Test.class.getClassLoader(); System.out.println(loader.getResource("foo/Test.class")); } } ``` This printed out: ``` file:/C:/Users/Jon/Test/foo/Test.class ```
Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: `-verbose:class`
Find where java class is loaded from
[ "", "java", "classpath", "classloader", "" ]
I am using C#. By default, when I add a web form in Visual Studio 2008 with or without a master page, the AutoEventWireup attribute is set to true in the page directive. This attribute is also set to true inside the master page master directive. What value should I have AutoEventWireup set to (true/false)? What are t...
That is a way of automatically wiring up event handlers to events based on naming conventions that Microsoft has setup. The way this is implemented is with reflection, if I remember correctly. At runtime, ASP.NET will inspect your class, look for methods with signatures that match the naming convention expected, and t...
That just causes runtime to automatically hook up the conventional page lifecycle methods like Page\_Load to their equivalent eventhandler (Page.Load). If you set AutoEventWireup to false, then you need something like: ``` protected override void OnLoad(EventArgs e) { base.OnLoad(e); } ``` instead of the MS conve...
What value should AutoEventWireup be set to in the page directive in ASP.Net?
[ "", "c#", "asp.net", "vb.net", "" ]
Suppose a header file defines a function template. Now suppose two implementation files `#include` this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type. ``` // header.hh template <typename T> void f(const T& o) { //...
In order to support C++, the linker is smart enough to recognize that they are all the same function and throws out all but one. EDIT: clarification: The linker doesn't compare function contents and determine that they are the same. Templated functions are marked as such and the linker recognizes that they have the sa...
The Gnu C++ compiler's manual has [a good discussion of this](http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html). An excerpt: > C++ templates are the first language > feature to require more intelligence > from the environment than one usually > finds on a UNIX system. Somehow the > compiler and linker hav...
Multiple definitions of a function template
[ "", "c++", "templates", "linker", "" ]
After looking at another question on SO ([Using NaN in C++](https://stackoverflow.com/questions/235386/using-nan-in-c)) I became curious about `std::numeric_limits<double>::signaling_NaN()`. I could not get signaling\_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catchin...
You can use the [`_control87()`](http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx) function to enable floating-point exceptions. From the MSDN documentation on `_control87()`: > Note: > > The run-time libraries mask all floating-point exceptions by default. When floating point exceptions are enabled, you can use...
A word of warning: Using 3rd party DLLs may silently enable these exceptions. This is especially true for loading DLL's that are written in a language that enables them by default. I've had that happen in two instances: Printing from an embedded browser control to a HP printer, and registering my DLL (that sets some i...
How to use std::signaling_nan?
[ "", "c++", "visual-c++", "floating-point", "nan", "" ]
Is it possible to serialize and deserialize a class in C++? I've been using Java for 3 years now, and serialization / deserialization is fairly trivial in that language. Does C++ have similar features? Are there native libraries that handle serialization? An example would be helpful.
The [`Boost::serialization`](http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html) library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, [here](http://www.boost.org/doc/libs/1_36_0/libs/serialization/example/demo.cpp). The only nat...
I realize this is an old post but it's one of the first that comes up when searching for `c++ serialization`. I encourage anyone who has access to C++11 to take a look at [cereal](https://uscilab.github.io/cereal/), a C++11 header-only library for serialization that supports binary, JSON, and XML out of the box. cerea...
Is it possible to serialize and deserialize a class in C++?
[ "", "c++", "serialization", "" ]
Can you add new statements (like `print`, `raise`, `with`) to Python's syntax? Say, to allow.. ``` mystatement "Something" ``` Or, ``` new_if True: print "example" ``` Not so much if you *should*, but rather if it's possible (short of modifying the python interpreters code)
You may find this useful - [Python internals: adding a new statement to Python](http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/), quoted here: --- This article is an attempt to better understand how the front-end of Python works. Just reading documentation and source code ma...
One way to do things like this is to preprocess the source and modify it, translating your added statement to python. There are various problems this approach will bring, and I wouldn't recommend it for general usage, but for experimentation with language, or specific-purpose metaprogramming, it can occassionally be us...
Can you add new statements to Python's syntax?
[ "", "python", "syntax", "language-specifications", "" ]
I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focu...
Related: [Unexpected behaviour of Process.MainWindowHandle](https://stackoverflow.com/questions/48288/unexpected-behaviour-of-processmainwindowhandle) Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says. That explains why the main window of your other pr...
Have you tried SWP\_NOACTIVATE?
focus lost after making another app's window topmost
[ "", "c#", "winapi", "focus", "z-order", "topmost", "" ]
Building a client-side swing application what should be notified on a bus (application-wide message system, similar in concept to JMS but much simpler) and what should be notified using direct listeners? When using a bus, I always have an unescapable feeling of "I have no idea who uses that and where". Also, no set or...
Event buses are very, very useful tools for providing decoupling in certain architectures. Listeners are easy to implement, but they have significant limitations when your object and dependency graph gets large. Listeners tend to run into problems with cyclic dependencies (events can 'bounce' in odd ways, and you wind ...
In my experience, trying to make Swing do something it wasn't designed for, or doesn't want you to do, is extremely painful. I would go with the simplest thing that would work; keep your code clean, do it the "Swing Way" until you start seeing problems.
Bus or listeners/delegates in client-side Swing application?
[ "", "java", "swing", "events", "architecture", "" ]
When I build a unit test project before the tests are executed the test output is copied to a TestResults folder and then the tests are executed. The issue I'm having is that not all the files in the Debug/bin directory are copied to the TestResults project. How can I get a file that is copied to the Debug/bin directo...
The standard way to do this is by specifying the [deployment items](http://msdn.microsoft.com/en-us/library/ms182473.aspx "MSDN: Team System Test Deployment") in the *`.testrunconfig`* file, which can be accessed via the *Edit Test Run Configurations* item in the Visual Studio ***Test*** menu or in the *Solution Items*...
You can specify deployment attribute like an example shown below; Also you need to set "Content" & "Copy if newer" property ( there is no documentation on the later settings, but you have set those to make it work. ``` [TestMethod] [DeploymentItem("mytestdata.xml")] public void UploadTest() { } ```
How can I get "Copy to Output Directory" to work with Unit Tests?
[ "", "c#", ".net", "visual-studio-2008", "unit-testing", "mstest", "" ]
How do I print debug messages in the Google Chrome JavaScript Console? Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the **print** command in JavaScript Debugger will not work here. In the JavaScript Console, `print()` will send the parameter...
Executing following code from the browser address bar: ``` javascript: console.log(2); ``` successfully prints message to the "JavaScript Console" in Google Chrome.
Improving on Andru's idea, you can write a script which creates console functions if they don't exist: ``` if (!window.console) console = {}; console.log = console.log || function(){}; console.warn = console.warn || function(){}; console.error = console.error || function(){}; console.info = console.info || function(){...
How do I print debug messages in the Google Chrome JavaScript Console?
[ "", "javascript", "console", "debugging", "google-chrome", "" ]
I'm writing a client-server app using BSD sockets. It needs to run in the background, continuously transferring data, but cannot hog the bandwidth of the network interface from normal use. Depending on the speed of the interface, I need to throttle this connection to a certain max transfer rate. What is the best way t...
The problem with sleeping a constant amount of 1 second after each transfer is that you will have choppy network performance. Let BandwidthMaxThreshold be the desired bandwidth threshold. Let TransferRate be the current transfer rate of the connection. Then... If you detect your TransferRate > BandwidthMaxThreshold...
The best way would be to use a [token bucket](http://en.wikipedia.org/wiki/Token_bucket). Transmit only when you have enough tokens to fill a packet (1460 bytes would be a good amount), or if you are the receive side, read from the socket only when you have enough tokens; a bit of simple math will tell you how long yo...
How do you throttle the bandwidth of a socket connection in C?
[ "", "c++", "c", "sockets", "network-programming", "" ]
I was reading some 3rd party code and I found this: ``` x.Flags = x.Flags ^ Flags.Hidden; ``` What does it do? I've used '&' and '|' for bitwise 'and' and 'or' with enums, but it's the first time I see the that symbol...
^ is the bitwise XOR operator in C#. EDIT: a ^ b returns true if a is true and b is false or if a is false and b is true, but not both.
That would be the 'xor' operator. In your example code, it would toggle the Flags.Hidden either on or off, depending on the current value of x.Flags. The benefit of doing it this way is that it allows you to change the setting for Flags.Hidden without affecting any other flags that have been set.
What does '^' do in c# (Enums)?
[ "", "c#", "enums", "operators", "" ]
How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this: ``` http://site/catalogue/BrowseByStyleLevel/1 ``` The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it. For example, ...
There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter: ``` routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}/{ignoreThisBit}", new { controller = "Home", ac...
This is how I have implemented the slug URL on my application. **Note:** The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list. ``` routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new...
How can I create a friendly URL in ASP.NET MVC?
[ "", "c#", "asp.net-mvc", "asp.net-mvc-routing", "friendly-url", "slug", "" ]
Is there a way to Deserialize Expressions in C#, I would like to store Expressions in a Database and load them at run time.
I continued work on the library that was mentioned by [Serializing and Deserializing Expression Trees in C#](https://stackoverflow.com/questions/217961/serializing-and-deserializing-expression-trees-in-c/1486253#1486253) It looks like the project was abandoned (2008) but I did some work on it and now it works with .NE...
There's an project on GitHub/Nuget called [MetaLinq](https://github.com/mcintyre321/metalinq) that aims to make working with expression tress more easy. It converts between normal Expressions and 'EditableExpressions' which are mutable and fully Serializable, so can be used with Json, Xml, Binary etc. Also check this...
Serializing and Deserializing Expression Trees in C#
[ "", "c#", "serialization", "expression-trees", "" ]
The situation is as follows: I've got 2 models: 'Action' and 'User'. These models refer to the tables 'actions' and 'users', respectively. My action table contains a column `user_id`. At this moment, I need an overview of all actions, and the users to which they are assigned to. When i use `$action->fetchAll()`, I onl...
I designed and implemented the table-relationships feature in Zend Framework. My first comment is that you wouldn't use `findDependentRowset()` anyway -- you'd use `findParentRow()` if the Action has a foreign key reference to User. ``` $actionTable = new Action(); $actionRowset = $actionTable->fetchAll(); foreach ($...
You could always make a view in your database that does the join for you. ``` CREATE OR REPLACE VIEW VwAction AS SELECT [columns] FROM action LEFT JOIN user ON user.id = action.user_id ``` Then just use ``` $vwAction->fetchAll(); ``` Just remember that views in MySQL are read-only (assuming this is MySQL)
Automatically joining tables without breaking default behaviour in Zend Framework
[ "", "php", "zend-framework", "" ]
I am trying to override the DataGridViewTextBoxCell's paint method in a derived class so that I can indent the foreground text by some variable amount of pixels. I would like it if the width of the column adjusts so that its total width is the length of my cells text plus the "buffer" indent. Does anyone know of a way ...
If you are trying to auto-size the columns (depending on size of the cell contents) then you should look at `Column.AutoSizeMode` property and `Column.DefaultCellStyle` property. ``` static const int INDENTCOEFF = 5; DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); cellStyle.Padding = new Padd...
You can just hook up to the CellFormattingEvent in the datagridview and do your formatting there. Or, if you're inherting from the DataGridView, you can just override the OnCellFormatting method. The code would look something like this: ``` if (e.ColumnIndex == 1) { string val =...
Overriding DataGridViewTextBoxCell Paint Method
[ "", "c#", "winforms", "" ]
Is there a good test suite or tool set that can automate website navigation -- with Javascript support -- and collect the HTML from the pages? Of course I can scrape straight HTML with BeautifulSoup. But this does me no good for sites that require Javascript. :)
You could use [Selenium](http://selenium.dev/) or [Watir](http://watir.com/) to drive a real browser. Ther are also some JavaScript-based headless browsers: * [PhantomJS](http://www.phantomjs.org/) is a headless Webkit browser. + [pjscrape](http://nrabinowitz.github.com/pjscrape/) is a scraping framework based on P...
Using [HtmlUnit](http://htmlunit.sourceforge.net/) is also a possibility. > HtmlUnit is a "GUI-Less browser for > Java programs". It models HTML > documents and provides an API that > allows you to invoke pages, fill out > forms, click links, etc... just like > you do in your "normal" browser. > > It has fairly good J...
What's a good tool to screen-scrape with Javascript support?
[ "", "javascript", "screen-scraping", "" ]
In the documentation of hardware that allows us to control it via UDP/IP, I found the following fragment: > In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data, > BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d...
C# itself doesn't define the endianness. Whenever you convert to bytes, however, you're making a choice. The [BitConverter](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) class has an [IsLittleEndian](http://msdn.microsoft.com/en-us/library/system.bitconverter.islittleendian.aspx) field to tell you h...
You can also use ``` IPAddress.NetworkToHostOrder(...) ``` For short, int or long.
C# little endian or big endian?
[ "", "c#", "hardware", "udp", "endianness", "" ]
I am trying to debug a JavaScript script that gets read in a Firefox extension and executed. I only can see errors via the Firebug console (my code is invisible to Firebug), and it's reporting a "unterminated string literal." I checked the line and the lines around it and everything seems fine-parentheses, braces, and...
Most browsers seem to have problems with code like this: ``` var foo = "</script>"; ``` In Firefox, Opera and IE8 this results in an unterminated string literal error. Can be pretty nasty when serializing html code which includes scripts.
Look for linebreaks! Those are often the cause.
Common sources of unterminated string literal
[ "", "javascript", "debugging", "firefox-addon", "" ]
Does anyone have a good articles or tutorial on correctly using dispose and IDisposable. I am trying to explain this to some junior dev and wanted to get some extra material, examples, etc.
A good place to start is this MSDN article by Shawn Farkas <http://msdn.microsoft.com/en-us/magazine/cc163392.aspx>. The definitive article is by Joe Duffy at <http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx> with some follow-up in <http://www.bluebytesoftware.com/b...
Many older sources of advice on this imply that IDisposable is linked in some way to finalizers. Pay very close attention to the comments of Herb Sutter on this subject. Do NOT leap to the conclusion that you need to write a finalizer if you implement IDisposable, to "make sure that Dispose runs eventually in case the ...
Winforms Disposing IDisposable
[ "", "c#", "winforms", "dispose", "idisposable", "" ]
I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string? e.g. ``` CString strIn = "Test number 1"; CString strQuery = "num"; bool fRet = SomeFn(strIn, StrQuery); if( fRet == true ) { // Ok strQuery was found in strIn ... ``` I have found a small number...
[CString::Find()](http://msdn.microsoft.com/ja-jp/library/ms928981.aspx) is what you want, one of the overloads does sub-string searching. ``` CString strIn = "test number 1"; int index = strIn.Find("num"); if (index != -1) // ok, found ```
[string::find](http://www.cplusplus.com/reference/string/string/find.html)
Searching CStrings in C++
[ "", "c++", "mfc", "string", "search", "cstring", "" ]
Here is a snippet of the code : ``` HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request.RawUrl); WebRequest.DefaultWebProxy = null;//Ensure that we will not loop by going again in the proxy HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); string charSet = response.CharacterSet; E...
Firstly, the easier way of writing that code is to use a StreamReader and ReadToEnd: ``` HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(myURL); using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) { using (Stream resStream = response.GetResponseStream()) { StreamR...
CharacterSet is "ISO-8859-1" by default, if it is not specified in server's content type header (different from "charset" meta tag in HTML). I compare HttpWebResponse.CharacterSet with charset attribute of HTML. If they are different - I use the charset as specified in HTML to re-read the page again, but with correct e...
Encoding trouble with HttpWebResponse
[ "", "c#", "encoding", "" ]
I have a WPF app that makes use of a Winforms User Control that I have created using C++/CLI. When my app goes to parse the XAML for my main window, it throws an exception. The information appears to be somewhat abbreviated, but it says: ``` A first chance exception of type 'System.Windows.Markup.XamlParseException' o...
I have experienced problems like that (but not with the exact same error message). It seems as if WPF cannot instantiate your Winforms User Control. The challenge is to find out why. Here are my suggestions that you could try: 1. Check if you have enabled unmanaged debugging (in Project Properties -> Debug) 2. Find o...
I've seen this problem when trying to use boost::threads. To support thread-local storage, boost::threads makes some Win32 API call that is incompatible with CLI applications. The problem gets triggered if you try to #include something from threads in CLI code. Solution is to either avoid using boost::threads entirely...
WPF throwing an exception parsing XAML that includes a Winforms User Control
[ "", "c#", "wpf", "winforms", "xaml", "user-controls", "" ]
When I am creating a new database table, what factors should I take into account for selecting the primary key's data type?
Sorry to do that, but I found that the answers I gave to related questions (you can check [this](https://stackoverflow.com/questions/159087/composite-primary-keys-versus-unique-object-id-field#164338) and [this](https://stackoverflow.com/questions/224576/will-sql-server-2005-penalize-me-for-using-an-nvarchar50-as-a-pri...
If using a numeric key, make sure the datatype is giong to be large enough to hold the number of rows you might expect the table to grow to. If using a guid, does the extra space needed to store the guid need to be considered? Will coding against guid PKs be a pain for developers or users of the application. If using...
What should I consider when selecting a data type for my primary key?
[ "", "sql", "database-design", "" ]
I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members. For example, the legacy code that I've inheritted has alot of these: ``` struct MyStruct { TCHAR szMyChar[STRING_SIZE]; bool ...
That kind of Hungarian Notation is fairly useless, and possibly worse than useless if you have to change the type of something. ([The *proper* kind of Hungarian Notation](http://www.joelonsoftware.com/articles/Wrong.html) is a different story.) I suggest you use whatever your group does. If you're the only person work...
The most important thing is to be consistent. If you're working with a legacy code base, name your variables and functions *consistently* with the naming convention of the legacy code. If you're writing new code that is only interfacing with old code, use your naming convention in the new code, but be consistent with y...
Variable Naming Conventions in C++
[ "", "c++", "variables", "naming-conventions", "" ]
I'm getting odd results from a `MySQL SELECT` query involving a `LEFT JOIN`, and I can't understand whether my understanding of `LEFT JOIN` is wrong or whether I'm seeing a genuinely odd behavior. I have a two tables with a many-to-one relationship: For every record in `table 1` there are 0 or more records in `table 2...
You need to `GROUP BY d.dateID`. In two of your cases, `s.DateID` is `NULL` (`LEFT JOIN`) and these are combined together. I think you will also find that this is invalid (ANSI) SQL, because d.date is not part of a `GROUP BY` or the result of an aggregate operation, and should not be able to be `SELECT`ed.
I think you mean to group by d.dateId.
MySQL LEFT JOIN SELECT not selecting all the left side records?
[ "", "sql", "mysql", "join", "" ]
Given the following inheritance tree, what would be the best way of implementing it in a way that works? ``` abstract class Foo<T> : IEnumerable<T> { public abstract Bar CreateBar(); } class Bar<T> : Foo<T> { // Bar's provide a proxy interface to Foo's and limit access nicely. // The general public should...
Okay, new answer: 1. Split Bar into an interface and a concrete class. 2. Express the public abstract method in terms of IBar. 3. Make Bar a private nested class in Foo, implementing IBar. Give it an internal constructor which you can call from Foo. 4. Write a protected method in Foo which creates an instance of Bar f...
Would it be possible for you to make Baz a nested type within Bar? That's the only way you'll give it more access to Bar than it would otherwise have. Just having the same parent class only gives it access to protected members of Foo, and Foo doesn't have special access to Bar. I suspect there are other tortuous ways o...
Inheritance trees and protected constructors in C#
[ "", "c#", "inheritance", "protected", "" ]
I am doing 2nd year computer science and we have a software engineering group project. There are 5 people in the group and we would like to build a web application in php. Please suggest some ideas for me
Have a look a Paul Graham's list of "Startup Ideas We'd Like to Fund" - lots more ideas and the CMS has been done to death. <http://ycombinator.com/ideas.html> The list in short: 1. A cure for the disease of which the RIAA is a symptom. 2. Simplified browsing 3. New news 4. Outsourced IT 5. Enterprise software 2.0 6...
How about a [content management system](http://en.wikipedia.org/wiki/Content_management_system)? This allows you to show off every part of your web development skill and it shouldn't be hard to do with a 5 person team. CMSs often include file uploads, file management and on-line text editors (something like TinyMCE). ...
Suggestions for a Web application for a group project
[ "", "php", "web-applications", "" ]
Is there a good way to read RAW image files (especially Canon CR2 and Adobe DNG files) as GDI+ bitmaps that is reasonably fast? I found an example running under WPF that would read an image using any installed image codec and then display it in an image control. And I modified this example to create a GDI+ bitmap by w...
Disclaimer: I work at Atalasoft. Our [DotImage Photo Pro](http://www.atalasoft.com/products/dotimage) product can do this. If you want to try to do it yourself, look into wrapping the opensource DCRaw or look at how Paint.NET does it (I think there's a RAW plugin for it)
The DotImage Photo Pro component worked well, but I had a problem extracting the preview image from raw files using it. It is also outside my budget for this project. But, I found the code for a RAW plugin for Paint.NET [here](http://paintdotnet.forumer.com/viewtopic.php?f=16&t=3759) and it was quite simple to adapt t...
Reading RAW image files as GDI+ bitmaps
[ "", "c#", "asp.net", ".net", "gdi+", "dng", "" ]
Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month. To do it manually, one could use: ``` String[] dateFields = dateString.split("/"); int month = Integer.parseInt(dateFields[0]); int day = Integer.parseInt(da...
Looks like my problem was using "MM/DD/yyyy" when I should have used "MM/dd/yyyy". Uppercase **D** is "Day in year", while lowercase **d** is "Day in month". ``` new SimpleDateFormat("MM/dd/yyyy").parse(dateString); ``` Does the job. Also, "M/d/y" works interchangeably. A closer reading of the [SimpleDateFormat API D...
Yep, use setLenient: ``` DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); df.setLenient(true); System.out.println(df.parse("05/05/1999")); System.out.println(df.parse("5/5/1999")); ```
Date time parsing that accepts 05/05/1999 and 5/5/1999, etc
[ "", "java", "date", "time", "parsing", "" ]
I am inserting a column in a DataGridView programmatically (i.e., not bound to any data tables/databases) as follows: ``` int lastIndex = m_DGV.Columns.Count - 1; // Count = 4 in this case DataGridViewTextBoxColumn col = (DataGridViewTextBoxColumn)m_DGV.Columns[lastIndex]; m_DGV.Columns.RemoveAt(lastIndex); m_DGV.Col...
I suspect this is because the order of the columns in the DataGridView do not necessarily dictate the display order, though without explicitly being assigned by default the order of the columns dictate the DisplayIndex property values. That is why there is a DisplayIndex property, so you may add columns to the collecti...
I have a couple of ideas. 1. How about addressing your columns by a unique name, rather than the index in the collection? They might not already have a name, but you could keep track of who's who if you gave them a name that meant something. 2. You can use the `GetFirstColumn`, `GetNextColumn`, `GetPreviousColumn`, `G...
Why does Columns.Insert not update the DisplayIndex in DataGridView (C#)?
[ "", "c#", "datagridview", "" ]
I am looking for an Applet with similar functionality to the Oracle/Stellent OutsideIn ActiveX control or the Autonomy KeyView technology that act as a browser plug-in allowing the rendering/display of a large number of file formats (Word processing, spreadhseet, graphics, etc.) I currently use the Stellent solution, b...
If a commercial product is an option, [ViewOne](http://www.daeja.com/products/viewone1.asp) is a nice product. It's an Applet and you can view a large variety of document.
If you are looking for pure Java component that supports all these formats, I'm pretty confident that it doesn't exist. If what you want is to embed Browser, MS Office, Acrobat etc. you would need an ActiveX container. Here are some choices: [JDIC](https://jdic.dev.java.net/#demos) - if you are using Swing (see the D...
Looking for a "Universal" Document viewer component/library
[ "", "java", "applet", "viewer", "plugins", "" ]
What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise? ### Example ``` void Test() { OnlyHexInString("123ABC"); // Returns true OnlyHexInString("123def"); // Returns true OnlyHexInString("123g"); // Ret...
``` public bool OnlyHexInString(string test) { // For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z" return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z"); } ```
Something like this: (I don't know C# so I'm not sure how to loop through the chars of a string.) ``` loop through the chars { bool is_hex_char = (current_char >= '0' && current_char <= '9') || (current_char >= 'a' && current_char <= 'f') || (current_char >= 'A' && cu...
Check a string to see if all characters are hexadecimal values
[ "", "c#", "" ]
What would be the best way to fill an array from user input? Would a solution be showing a prompt message and then get the values from from the user?
``` string []answer = new string[10]; for(int i = 0;i<answer.length;i++) { answer[i]= Console.ReadLine(); } ```
Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference. If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces o...
How to Fill an array from user input C#?
[ "", "c#", "" ]
``` private string? typeOfContract { get { return (string?)ViewState["typeOfContract"]; } set { ViewState["typeOfContract"] = value; } } ``` Later in the code I use it like this: ``` typeOfContract = Request.QueryString["type"]; ``` I am getting the following error at the declaration of `typeOfContract` line sta...
System.String is a reference type and already "nullable". Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
You are making it complicated. `string` is already nullable. You don't need to make it **more** nullable. Take out the `?` on the property type.
C# nullable string error
[ "", "c#", "nullable", "" ]
I am trying to create a databound WPF GridView whose rows can either be read-only or editable (by double-clicking or through a context menu). I would like for the row to return to a read-only state if any of its editable controls loses focus. The functionality I am looking for is very similar to [this example](http://b...
With the ListView + GridView control il quite complex because this control "thinks in column" so you have to create a template for every column and switch the read-only template with edit template (for every cell). I suggest you to take a look a the xceed DataGrid. It's free and it implements the edit functionality in ...
there is also the "official" wpf datagrid from microsoft at codeplex : <http://www.codeplex.com/wpf>
Editable WPF GridView Row
[ "", "c#", "wpf", "gridview", "" ]
How do I get the list of open file handles by process id in C#? I'm interested in digging down and getting the file names as well. Looking for the programmatic equivalent of what process explorer does. Most likely this will require interop. Considering adding a bounty on this, the implementation is nasty complicate...
Ouch this is going to be hard to do from managed code. There is a [sample on codeproject](http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx?fid=422864&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=2277170) Most of the stuff can be done in interop, but you need a driver to get the filename cause i...
You can also run the command line app, [Handle](http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx), by Mark Rusinovich, and parse the output.
How do I get the list of open file handles by process in C#?
[ "", "c#", ".net", "" ]
I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem. So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's m...
Try this (where `this` is your form): ``` this.Bounds = Screen.PrimaryScreen.Bounds; this.TopMost = true; ``` That'll set the form to fullscreen, and it'll cover the taskbar.
I've tried so many solutions, some of them works on Windows XP and all of them did NOT work on Windows 7. After all I write a simple method to do so. ``` private void GoFullscreen(bool fullscreen) { if (fullscreen) { this.WindowState = FormWindowState.Normal; this.FormBorder...
C# - Why won't a fullscreen winform app ALWAYS cover the taskbar?
[ "", "c#", ".net", "winforms", "fullscreen", "keyboard-hook", "" ]
Is it more performant to have a bidimensional array (`type[,]`) or an array of arrays (`type[][]`) in C#? Particularly for initial allocation and item access
Of course, if all else fails... test it! Following gives (in "Release", at the console): ``` Size 1000, Repeat 1000 int[,] set: 3460 int[,] get: 4036 (chk=1304808064) int[][] set: 2441 int[][] get: 1283 (chk=1304808064) ``` So a jagged array is quicker, at least in this test. Interesting! However, it ...
I believe that [,] can allocate one contiguous chunk of memory, while [][] is N+1 chunk allocations where N is the size of the first dimension. So I would guess that [,] is faster on initial allocation. Access is probably about the same, except that [][] would involve one extra dereference. Unless you're in an excepti...
What's better in regards to performance? type[,] or type[][]?
[ "", "c#", "performance", "arrays", "" ]