Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Consider an algorithm that needs to determine if a `string` contains any characters outside the whitelisted characters. The whitelist looks like this: > '-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ > ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÖÜáíóúñÑÀÁÂÃÈÊËÌÍÎÏÐÒÓÔÕØÙÚÛÝßãðõøýþÿ > > Note: spaces and apostrophes are needed to be included in this whitelist. Typically this will be a static method, but it will be converted to an extension method. ``` private bool ContainsAllWhitelistedCharacters(string input) { string regExPattern="";// the whitelist return Regex.IsMatch(input, regExPattern); } ``` **Considerations:** Thanks for the performance comments to all the answerers. Performance is not an issue. Quality, readability and maintainability is! Less code = less chance for defects, IMO. **Question:** What should this whitelist regex pattern be?
You could pattern match using the following: ``` ^([\-\.a-zA-Z ÇüéâäàåçêëèïîíìÄÅÉæÆôöòûùÖÜáíóúñÑÀÁÂÃÈÊËÌÍÎÏÐÒÓÔÕØÙÚÛÝßãðõøýþÿ]+)$ ``` Make it an extension method with: ``` public static bool IsValidCustom(this string value) { string regExPattern="^([\-\.a-zA-Z ÇüéâäàåçêëèïîíìÄÅÉæÆôöòûùÖÜáíóúñÑÀÁÂÃÈÊËÌÍÎÏÐÒÓÔÕØÙÚÛÝßãðõøýþÿ]+)$"; return Regex.IsMatch(input, regExPattern); } ``` I can't think of an easy way to do a maintainable range with extended characters since the order of the characters is not obvious.
Why does it have to be a regex? ``` private bool ContainsAllWhitelistedCharacters(string input) { string whitelist = "abcdefg..."; foreach (char c in input) { if (whitelist.IndexOf(c) == -1) return false; } return true; } ``` No need to jump straight into regexes if you aren't sure how to implement the one you need and you haven't profiled that section of code and found out you need the extra performance.
.NET Regex for whitelisted characters
[ "", "c#", ".net", "regex", "" ]
Before I delete/replace a stored procedure, I would usually do a string search of the name of the stored procedure in the working project to make sure no unsuspecting code is using it. Is there a better and more reliable way of doing this?
For SQL Server 2005 and above, works with longer code. ``` SELECT OBJECT_NAME(object_id) FROM sys.sql_modules WHERE definition LIKE '%' + 'mySP' + '%' ```
or rename the sp instead of deleting it. if there's an unidentified dependency you can quickly get your sp back. another thing you can do is script out your views, functions, and sps, and search the scripts. again, won't catch dynamic sql, but might catch a few extra references.
Deleting a stored procedure in SQL server
[ "", "c#", "sql-server", "stored-procedures", "visual-studio-2008", "" ]
A dumbveloper at my work (years ago) moved the `body` column from our `comments` table to a secondary `comment_extensions` table as some sort of sketchy guesswork optimization. It seems ill-advised to do a join every time we want to display a comment, so I'm going to try moving that column back into our `comments` table and run some benchmarks. My problem is that this update crawls. I let it run for an hour before shutting it off, fearing that it would take all night. ``` UPDATE comments SET body = comment_extensions.body FROM comment_extensions WHERE comments.id = comment_extensions.comment_id; ``` It's a PostgreSQL 8.1 database, and `comment_extensions.comment_id` is indexed. Any suggestions for making this run faster?
How about this? <http://www.postgresql.org/docs/8.1/interactive/sql-createtableas.html> ``` CREATE TABLE joined_comments AS SELECT c.id, c.author, c.blablabla, ce.body FROM comments c LEFT JOIN comment_extensions ce ON c.id = ce.comment_id; ``` That would create a new joined\_comments table. That could be almost enough (you'd need to still recreate indexes and so on) but I remember Postgres 8.1 has a bug about the way serial columns get created (sorry can't find a link). So my suggestion would be that after you have this new joined table, then you COPY TO a BINARY file from that joined\_comments table, create a new comments table stating that id is a SERIAL right from the start, then COPY FROM that BINARY file to the new comments table. Then, recreate indexes.
Well, for an academic question, why is this ill-advised? What percentage of a lookup involves needing know the comment info? My suggestion: update in small batches (10,000 rows at a time?). It may still take all night. Depending on the nature of your system, you may also have to implement cut-over logic that prevents the system from updating or pulling from your extensions table during this migration. Large databases hurt like that ;)
PostgreSQL: What's an efficient way to update 3m records?
[ "", "sql", "postgresql", "" ]
I've written some JQuery code to iterate over some checkboxes on an ASP.Net web page, and am seeing 2 very strange problems with the if statement embedded in the $.each function. The code is selecting my checkboxes just fine, and as the code iterates through the $.each function I can clearly see that the objValue.checked is true or false, appropriately, depending on if I checked the checkbox or not. The problems that I am seeing are: 1) that it always falls into my if statement (even when the value of objValue.checked is false), and 2) the value of my availableInstalls variable is never decremented, even though I can see in debug mode that it hits the "availableInstalls = availableInstalls - 1" line of code. Anyone know what may be causing this behavior? ``` $(document).ready(function() { $(".installsoftwarecb").click(function() { var availableInstalls = 10; var checkBoxes = $(".installsoftwarecb input[type='checkbox']"); $.each( checkBoxes, function(intIndex, objValue) { if (objValue.checked) { availableInstalls = availableInstalls - 1; } }); }); }); ```
How about writing something like this: ``` $(document).ready(function() { $(".installsoftwarecb").click(function() { //count number of checked items directly. var availableInstalls = 10 - $('input:checkbox:checked', this).length; alert(availableInstalls); } } ```
**[Working Demo](http://jsbin.com/ewuna)** code from demo ``` $(document).ready(function() { $("#button").click(function() { var availableInstalls = 10; $("input:checkbox").each(function() { if (this.checked) { availableInstalls = availableInstalls - 1; } }); alert(availableInstalls); }); }); ``` or you cold just use a "checked" selector ``` $("input:checkbox:checked").length; // number of checked checkboxes ```
JQuery if statement
[ "", "c#", "asp.net", "jquery", "iteration", "" ]
Is there any way in c# .NET 2.0! to combine multiple Predicates? Let's say I have the following code. ``` List<string> names = new List<string>(); names.Add("Jacob"); names.Add("Emma"); names.Add("Michael"); names.Add("Isabella"); names.Add("Ethan"); names.Add("Emily"); List<string> filteredNames = names.FindAll(StartsWithE); static bool StartsWithE(string s) { if (s.StartsWith("E")) { return true; } else { return false; } } ``` This gives me: ``` Emma Ethan Emily ``` So this is pretty cool stuff, but I know want to be able to filter using multiple predicates. So I want to be able to say something like this: ``` List<string> filteredNames = names.FindAll(StartsWithE OR StartsWithI); ``` In order to get: ``` Emma Isabella Ethan Emily ``` How can I achieve this? Currently I am just filtering the complete list twice and combining the results afterwards. But unfortunately this is quite inefficent and even more importantly I lose the original sort order, which is not acceptable in my situation. I also need to be able to iterate over any number of filters/predicates as there can be quite a lot. Again it needs to be a .NET 2.0 solution unfortunately I can't use a newer version of the framework Thanks a lot.
How about: ``` public static Predicate<T> Or<T>(params Predicate<T>[] predicates) { return delegate (T item) { foreach (Predicate<T> predicate in predicates) { if (predicate(item)) { return true; } } return false; }; } ``` And for completeness: ``` public static Predicate<T> And<T>(params Predicate<T>[] predicates) { return delegate (T item) { foreach (Predicate<T> predicate in predicates) { if (!predicate(item)) { return false; } } return true; }; } ``` Then call it with: ``` List<string> filteredNames = names.FindAll(Helpers.Or(StartsWithE, StartsWithI)); ``` Another alternative would be to use multicast delegates and then split them using `GetInvocationList()`, then do the same thing. Then you could do: ``` List<string> filteredNames = names.FindAll(Helpers.Or(StartsWithE+StartsWithI)); ``` I'm not a huge fan of the latter approach though - it feels like a bit of an abuse of multicasting.
I guess you could write something like this: ``` Func<string, bool> predicate1 = s => s.StartsWith("E"); Func<string, bool> predicate2 = s => s.StartsWith("I"); Func<string, bool> combinedOr = s => (predicate1(s) || predicate2(s)); Func<string, bool> combinedAnd = s => (predicate1(s) && predicate2(s)); ``` ... and so on.
Combine Multiple Predicates
[ "", "c#", ".net-2.0", "predicate", "" ]
I am writing a program that starts another java process which runs certain code. Is there any way I can "talk" to that process to call methods of the running class(es)?
You're going to have to use some form of remoting. That could be: * RMI; * Web Services (JAX-WS, Spring Web Services, etc); * Sockets; * Embedded Web container; * etc.
They will be able to communicate via pipes or sockets. You either create your own communication protocol over it, or use something like [RMI](http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp).
Access Other Java Processes
[ "", "java", "process", "" ]
Can anyone help me understand #pragma? ``` ifndef TARGET_OS_LINUX #pragma once endif ``` What,when, where, why, an example? The above is in some code that I am refactoring....
`#pragma` is just the prefix for a compiler-specific feature. In this case, `#pragma once` means that this header file will only ever be included once in a specific destination file. It removes the need for [include guards](http://en.wikipedia.org/wiki/Include_guard).
* What -- it is header guard. This file will be included only once. * When -- at a compile process * why -- to avoid double including. "Header guards are little pieces of code that protect the contents of a header file from being included more than once."
What is #pragma once used for?
[ "", "c++", "" ]
Is there a way to get the Content-Type of the response or conversely set the Content-Type of an outgoing request in Silverlight using WebClient? **Edit** I need to make http requests and be able to show progress for them. I want to package the machinery for making the requests into a generic module and use it everywhere in my code. This I have already done. The difficulty seems to be when submitting different types of data to the server in POST I have no way to tell the server what the data is (json,xml,form encode,binary) I believe I can deal with this by passing ?content-type=x with the request, and setting the server to prefer that over the Content-Type header. I also have no way to know what kind of content the server responds with, I think I can solve this by passing the expected type of the data when I make a request. If anyone has a better solution, please speak up :) **/Edit** Here's my predicament. The HttpWebRequest/Response objects implement an internal interface that allows for monitoring the progress of the request. If you want to do large requests it's very important that the user get to see a progress bar showing the status of the download/upload. So using HttpWebRequest/Response is out. Leaving only WebClient, but I'm finding some odd things about it. It cannot be subclassed. It's not actually sealed, but the constructor is marked [SecuritySafeCritical], which as far as I can tell, means I can't call it from a derived class. At least I failed, and found others on Google who had failed, but I would be very happy to be proved wrong on this point. Internally it uses BrowserHttpWebResponse, which does not override the abstract Headers property, and WebClient.ResponseHeaders just forwards to m\_Response.Headers, which just throws NotImplementedException. Not sure Content-Type would even be in ResponseHeaders, but I would have liked to check. It seems that we have the unhappy choice of having progress info or Content-Type info but not both in Silverlight. According to the docs, there also seems no way to set Content-Type on the outgoing request either with WebClient. Content-Type is listed as a restricted header. I haven't actually tested this though. Although it's interesting to note that on an error, you actually get passed the response object and have access to StatusCode, Content-Type, etc.
An easier solution might be to have the client/server code break the upload/download into chunks and send them one at a time. Then you can update your progress bar after each chunk. Of course, the smaller your chunk size the slower it will go. Also: you could tell the server what content type it is via query string argument?
Have you tried using the WebClient and the DownloadProgressChanged event on the WebClient?
C# Silverlight WebClient get Content-Type of Response?
[ "", "c#", "silverlight", "webclient", "" ]
Is it possible to send an ajax request in onsubmit() of a form? I have been trying it and the results are flaky, mainly because probably if the browser happens to take longer sending my request than it takes sending the original form, my request is discarded as soon as the location of the loaded page change, so sometimes it never even hits the server. Basically, what I want to do is add an audit log collector that collects login events, I want to hook that to existing apps with minimal invasion.
This is easily achievable. Just hold off the form submission until the AJAX request completes. Make your form `onsubmit` attribute call the AJAX function and return false (which cancels the form submission). When your AJAX call completes, submit the form programmatically. For instance: ``` <form name="myform" onsubmit="javascript: startAjax(); return false;"> ... <script type="text/javascript"> function startAjax() {} // Calls ajaxComplete() when finished function ajaxComplete() { document.myform.submit(); } </script> ```
There is another way to solve this issue, that is you can make the ajax call as synchronous. Example: ``` xmlhttp.open("GET", imageUrlClickStream, false); ``` By this we can make sure that the form submission will wait until the ajax call get the response.
Sending an Ajax request before form submit
[ "", "javascript", "html", "" ]
I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing something in these frameworks or does this not work? Does anybody have suggestions for python test framworks usable for automated system tests?
I was wanting something similar for functional testing that I'm doing using nose. I eventually came up with this: ``` def raw_print(str, *args): out_str = str % args sys.stdout.write(out_str) class DeferredAsserter(object): def __init__(self): self.broken = False def assert_equal(self, expected, actual): outstr = '%s == %s...' % (expected, actual) raw_print(outstr) try: assert expected == actual except AssertionError: raw_print('FAILED\n\n') self.broken = True except Exception, e: raw_print('ERROR\n') traceback.print_exc() self.broken = True else: raw_print('PASSED\n\n') def invoke(self): assert not self.broken ``` In other words, it's printing out strings indicating if a test passed or failed. At the end of the test, you call the invoke method which actually does the *real* assertion. It's definitely not preferable, but I haven't seen a Python testing framework that can handle this kind of testing. Nor have I gotten around to figuring out how to write a nose plugin to do this kind of thing. :-/
You asked for suggestions so I'll suggest [robot framework](http://code.google.com/p/robotframework/).
Python test framework with support of non-fatal failures
[ "", "python", "testing", "assert", "nose", "" ]
My employer has asked me to create some web pages with various charts - one of the requirements is to have a click through ability for further detials. I am looking for sugestions on chart libraries that I could use. c#, .net 2.0 UPDATE: I used zedgraph with a imagemap [drilldown Sample](http://zedgraph.org/wiki/index.php?title=Use_an_ImageMap)
Check out [**ZedGraph**](http://sourceforge.net/projects/zedgraph/). Seems to be a bit stale in terms of active development, but it may give you what you want.
The free [**ASP.NET Charting controls**](http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx) support clickable regions. You can set a URL for individual data items. As long as you don't mind wiring all this up, you'll be fine. If you want the drill-down to happen automatically, you'll want something more powerful.
Drill down charts for asp.net
[ "", "c#", "asp.net", "zedgraph", "" ]
Is it possible with Python to set the timezone just like this in PHP: ``` date_default_timezone_set("Europe/London"); $Year = date('y'); $Month = date('m'); $Day = date('d'); $Hour = date('H'); $Minute = date('i'); ``` I can't really install any other modules etc as I'm using shared web hosting. Any ideas?
``` >>> import os, time >>> time.strftime('%X %x %Z') '12:45:20 08/19/09 CDT' >>> os.environ['TZ'] = 'Europe/London' >>> time.tzset() >>> time.strftime('%X %x %Z') '18:45:39 08/19/09 BST' ``` To get the specific values you've listed: ``` >>> year = time.strftime('%Y') >>> month = time.strftime('%m') >>> day = time.strftime('%d') >>> hour = time.strftime('%H') >>> minute = time.strftime('%M') ``` See [here](http://docs.python.org/library/time.html#time.strftime) for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.
Be aware that running ``` import os os.system("tzutil /s \"Central Standard Time\""); ``` will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as: ``` >>> os.environ['TZ'] = 'Europe/London' >>> time.tzset() ``` which will only set in the current environment time (in Unix only)
Setting timezone in Python
[ "", "python", "timezone", "" ]
The code below is my current solution. **A great example of what I am trying to mimic would be the FrameworkElement.ActualWidth property.** You know how the ActualWidth property is calculated and reassigned, whenever the Width property changes, or whenever the control is redrawn, or whenever else? ------ From the developer's perspective, it just looks like data-binding hard-at-work. But ActualWidth is a read-only dependency-property. Does Microsoft really have to go through this gigantic trash-hole of code to make that work? Or is there a simpler way that utilizes the existing functionality of the data-binding system? ``` public class foo : FrameworkElement { [ValueConversion(typeof(string), typeof(int))] public class fooConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { ... } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { ... } } private static readonly fooConverter fooConv = new fooConverter(); private static readonly DependencyPropertyKey ReadOnlyIntPropertyKey = DependencyProperty.RegisterReadOnly( "ReadOnlyInt", typeof(int), typeof(foo), null); public int ReadOnlyInt { get { return (int)GetValue(ReadOnlyIntPropertyKey.DependencyProperty); } } public static readonly DependencyProperty ReadWriteStrProperty = DependencyProperty.Register( "ReadWriteStr", typeof(string), typeof(foo), new PropertyMetadata(ReadWriteStr_Changed)); public string ReadWriteStr { get { return (string)GetValue(ReadWriteStrProperty); } set { SetValue(ReadWriteStrProperty, value); } } private static void ReadWriteStr_Changed( DependencyObject d, DependencyPropertyChangedEventArgs e) { try { if (d is foo) { foo f = d as foo; f.SetValue( ReadOnlyIntPropertyKey, fooConv.Convert(f.ReadWriteStr, typeof(int), null, CultureInfo.CurrentCulture)); } } catch { } } } ```
Unfortunately, you'll need most of what you have. The IValueConverter isn't required in this case, so you could simplify it down to just: ``` public class foo : FrameworkElement { private static readonly DependencyPropertyKey ReadOnlyIntPropertyKey = DependencyProperty.RegisterReadOnly( "ReadOnlyInt", typeof(int), typeof(foo), null); public int ReadOnlyInt { get { return (int)GetValue(ReadOnlyIntPropertyKey.DependencyProperty); } } public static readonly DependencyProperty ReadWriteStrProperty = DependencyProperty.Register( "ReadWriteStr", typeof(string), typeof(foo), new PropertyMetadata(ReadWriteStr_Changed)); public string ReadWriteStr { get { return (string)GetValue(ReadWriteStrProperty); } set { SetValue(ReadWriteStrProperty, value); } } private static void ReadWriteStr_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { foo f = d as foo; if (f != null) { int iVal; if (int.TryParse(f.ReadWriteStr, out iVal)) f.SetValue( ReadOnlyIntPropertyKey, iVal); } } } ```
It's not as bad as you suggest, IMHO... You could get rid of the converter : `IValueConverter` is for bindings, you don't need it for conversions in code-behind. Apart from that, I don't see how you could make it more concise...
Is there a *clean* way to make a read-only dependency-property reflect the value of another property?
[ "", "c#", ".net", "wpf", "data-binding", "dependency-properties", "" ]
I have a large complex PHP project made up of many PHP files. Is there some function I can call in my code that will return a list of all included files?
`get_included_files` or `get_required_files` (alias of `get_included_files`) <http://us.php.net/manual/en/function.get-included-files.php> <http://us.php.net/manual/en/function.get-required-files.php> (Alias of `get_included_files`) ``` <?php // This file is abc.php include 'test1.php'; include_once 'test2.php'; require 'test3.php'; require_once 'test4.php'; $included_files = get_included_files(); foreach ($included_files as $filename) { echo "$filename\n"; } ?> ----- The above example will output: abc.php test1.php test2.php test3.php test4.php ```
``` register_shutdown_function( function() { your_logger(get_included_files()); } ); ``` get\_included\_files will be called at the end of script execution, so u`ll get full list of included files
PHP: List all includes
[ "", "php", "" ]
I'm trying to get this Python MYSQL update statement correct(With Variables): ``` cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID) ``` Any ideas where I'm going wrong?
It [should be](http://mysql-python.sourceforge.net/MySQLdb.html): ``` cursor.execute (""" UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server=%s """, (Year, Month, Day, Hour, Minute, ServerID)) ``` You can **also** do it with basic string manipulation, ``` cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID)) ``` but **[this way is discouraged because it leaves you open for SQL Injection](http://bobby-tables.com/)**. As it's so easy (and similar) to do it the *right way*tm. Do it correctly. The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).
You've got the syntax all wrong: ``` cursor.execute (""" UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server=%s """, (Year, Month, Day, Hour, Minute, ServerID)) ``` For more, [read the documentation](http://mysql-python.sourceforge.net/MySQLdb.html).
Python MYSQL update statement
[ "", "python", "mysql", "mysql-python", "prepared-statement", "" ]
Suppose I have a **Monkey** class which sometimes needs to acquire an instance of **Banana**. The way this banana is provided is not of interest to the monkey, but it does initiate the banana acquisition. Now I have at least three possible ways to wire my monkey to a banana provider. **What is the best way to do it?** **1. Event** Raise a `Monkey.BananaNeeded` event. The event handler sets the `BananaNeededEventArgs.Banana` property. **2. Interface** Invoke `IBananaProvider.GetBanana`. The `IBananaProvider` instance is injected in the monkey as a constructor argument or through a property. **3. Delegate** Invoke a delegate of type [`System.Func<Banana>`](http://msdn.microsoft.com/en-us/library/bb534960.aspx). The delegate is injected in the monkey as a constructor argument or through a property. This one is tempting because it doesn't require the declaration of any extra interfaces or classes, but apparently it is not a popular choice.
I don't like the event and delegate options unless there is a mechanism to ensure multiple handlers won't be attached. Option 2 is therefore the winner, IMO.
The event model works best if there is several possible banana providers, i.e. the monkey asks all providers in turn for a banana, and the first one that can provide one gets to deliver it. The other two models work fine for a single banana prover per monkey. The delegate is easier to create a provider for, and the interface is more structured.
Event, delegate or interface?
[ "", "c#", "" ]
I need to step through a .gif image and determine the RGB value of each pixel, x and y coordinates. Can someone give me an overview of how I can accomplish this? (methodology, which namespaces to use, etc.)
This is a complete example with both methods, using LockBits() and GetPixel(). Besides the trust issues with LockBits() things can easily get hairy. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace BitmapReader { class Program { static void Main(string[] args) { //Try a small pic to be able to compare output, //a big one to compare performance System.Drawing.Bitmap b = new System.Drawing.Bitmap(@"C:\Users\vinko\Pictures\Dibujo2.jpg"); doSomethingWithBitmapSlow(b); doSomethingWithBitmapFast(b); } public static void doSomethingWithBitmapSlow(System.Drawing.Bitmap bmp) { for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color clr = bmp.GetPixel(x, y); int red = clr.R; int green = clr.G; int blue = clr.B; Console.WriteLine("Slow: " + red + " " + green + " " + blue); } } } public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); byte red = 0; byte green = 0; byte blue = 0; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { //See the link above for an explanation //of this calculation int position = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat)/8); blue = rgbValues[position]; green = rgbValues[position + 1]; red = rgbValues[position + 2]; Console.WriteLine("Fast: " + red + " " + green + " " + blue); } } bmp.UnlockBits(bmpData); } } } ```
You can load the image using `new Bitmap(filename)` and then use [`Bitmap.GetPixel`](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx) repeatedly. This is very slow but simple. (See Vinko's answer for an example.) If performance is important, you might want to use [`Bitmap.LockBits`](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.lockbits.aspx) and unsafe code. Obviously this reduces the number of places you'd be able to use the solution (in terms of trust levels) and is generally more complex - but it can be a *lot* faster.
How can I iterate through each pixel in a .gif image?
[ "", "c#", "system.drawing", "" ]
I searched for this for a while but came up empty ... hopefully someone here can help. Is there a query I can run on a database (SQL Server 2005) that will return the number of rows in each table?
You could try something like [this](http://web.archive.org/web/20080701045806/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-get-a-list-of-sql-server-tables-and-their-row-counts.html): ``` SELECT [TableName] = so.name, [RowCount] = MAX(si.rows) FROM sysobjects so, sysindexes si WHERE so.xtype = 'U' AND si.id = OBJECT_ID(so.name) GROUP BY so.name ORDER BY 2 DESC ```
Galwegian got it almost right :-) For SQL Server 2005 and up, I always recommed using the "sys.\*" system views instead of the (soon to be deprecated) sysobjects and sysindexes tables. ``` SELECT t.NAME AS 'Table Name', SUM(p.[Rows]) as 'Row Count' FROM sys.tables t INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id WHERE t.NAME NOT LIKE 'dt%' AND i.OBJECT_ID > 255 AND i.index_id = 1 GROUP BY t.NAME ORDER BY SUM(p.[Rows]) DESC ``` Marc
SQL 2005 - Query to Find Tables with Most Rows
[ "", "sql", "sql-server", "t-sql", "" ]
I have a list like this: ``` List<Controls> list = new List<Controls> ``` How to handle adding new position to this list? When I do: ``` myObject.myList.Add(new Control()); ``` I would like to do something like this in my object: ``` myList.AddingEvent += HandleAddingEvent ``` And then in my `HandleAddingEvent` delegate handling adding position to this list. How should I handle adding new position event? How can I make this event available?
You could inherit from List and add your own handler, something like ``` using System; using System.Collections.Generic; namespace test { class Program { class MyList<T> : List<T> { public event EventHandler OnAdd; public new void Add(T item) // "new" to avoid compiler-warnings, because we're hiding a method from base-class { if (null != OnAdd) { OnAdd(this, null); } base.Add(item); } } static void Main(string[] args) { MyList<int> l = new MyList<int>(); l.OnAdd += new EventHandler(l_OnAdd); l.Add(1); } static void l_OnAdd(object sender, EventArgs e) { Console.WriteLine("Element added..."); } } } ``` ### Warning 1. Be aware that you have to re-implement all methods which add objects to your list. `AddRange()` will not fire this event, in this implementation. 2. We ***did not overload*** the method. We hid the original one. If you `Add()` an object while this class is boxed in `List<T>`, the ***event will not be fired***! ``` MyList<int> l = new MyList<int>(); l.OnAdd += new EventHandler(l_OnAdd); l.Add(1); // Will work List<int> baseList = l; baseList.Add(2); // Will NOT work!!! ```
I believe What you're looking for is already part of the API in the [ObservableCollection(T)](http://msdn.microsoft.com/en-us/library/ms668604.aspx) class. Example: ``` ObservableCollection<int> myList = new ObservableCollection<int>(); myList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler( delegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) { MessageBox.Show("Added value"); } } ); myList.Add(1); ```
How to handle add to list event?
[ "", "c#", "events", "list", "event-handling", "" ]
I need to validate measurements entered into a form generated by PHP. I intend to compare them to upper and lower control limits and decide if they fail or pass. As a first step, I imagine a PHP function which accepts strings representing engineering measurements and converts them to pure numbers before the comparison. At the moment I'm only expecting measurements of small voltages and currents, so strings like '1.234uA', '2.34 nA', '39.9mV'. or '-1.003e-12' will be converted to 1.234e-6, 2.34e-9, 3.99e-2 and -1.003e-12, respectively. But the method should be generalisable to any measured quantity.
``` function convert($value) { $units = array('p' => 'e-12', 'n' => 'e-9', 'u' => 'e-6', 'm' => 'e-3'); $unitstring = implode("", array_keys($units)); $matches = array(); $pattern = "/^(-?(?:\\d*\.\\d+)|(?:\\d+))\s*([$unitstring])([a-z])$/i"; $result = preg_match($pattern, $value, $matches); if ($result) $retval = $matches[1].$units[$matches[2]].$matches[3]; else $retval = $value; return $retval; } ``` So to explain what the above does: * $units is an array to map unit-prefix to the exponent. * $unitstring conglomerates the units into a single string (in the example it would be 'pnum') * The regular expression will match an optional -, followed by either 0 or more digits, a period and 1 or more digits OR 1 or more digits, followed by one of the unit prefixes (only one) and then a single alphabetical character. There can be any amount of whitespace between the number and the units. * Because of the parethesis and the use of preg\_match, the number section, the unit prefix, and the unit are all separately captured in the array $matches as elements 1, 2, and 3. (0 will contain the entire string) * $result will be 1 if it matched the regex, 0 otherwise. * $retval is constructed by just connecting the number, the exponent (based on the unit prefix from the array) and the units provided, or it will just be the passed in string (such as if you're given the -1.003e-12, it will be returned) Of course you can tweak some things, but in general this is a good start. Hope it helps.
In your function first you need to initialize values for units like -6 for u, -3 for m...etc divide the string in Number and Unit(i.e micro(u),mili(m),etc). and then say the entered no is NUM; and unit is UNIT..(char like u,m etc); ``` while(NUM>10) { NUM=NUM/10; x++; //x is keeping track of the DOT. } UNIT=UNIT+x; //i.e UNIT is increased(for M,K,etc) or decreased(for u,m,etc) echo NUM.e.UNIT; ``` May be it will do!
Validate measurements with PHP
[ "", "php", "validation", "units-of-measurement", "" ]
I have following scenario: I have a XML-Document, e.g. like this ``` <someRootElement> <tag1> <tag2 someKey=someValue someKey2=someValue2 /> <tag3/> <tag4 newKey=newValue newKey2=newValue2 /> </tag1> </someRootElement> ``` Now I want the parent **tag1** to be called **reallyCoolTag** without losing the childnodes. I tried the following, but it unfortunately doesn't work as I wish it would (but I do know why, b/c it is missing something, I guess): ``` // the new element: Element neu = doc.createElement( newValue ); // append it to the root: root.appendChild( neu ); // get all the child nodes: NamedNodeMap nnm = nodes.item(i).getAttributes(); for( int dg = 0; dg < nnm.getLength(); dg++ ){ neu.setAttribute( nnm.item( dg ).getNodeName(), nnm.item( dg ).getNodeValue() ); } //--------------------------------------------------------- // HERE I GUESS I AM MISSING THE PART WHERE THE CHILD NODES // ARE BEING APPENDED TO THE NEW NODE????? //--------------------------------------------------------- // nodes.item(i) := the old value (nodes := is a NodeList root.replaceChild( neu, nodes.item(i)); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource( doc ); StreamResult result = new StreamResult( xml ); transformer.transform( source, result ); nodes.item( i ).getParentNode().removeChild( nodes.item(i) ); ``` Now this does work to a certain extend, as I mentioned, I guess I am missing the part where the child nodes are being appened, but what I actually wanted to know is, whether there is a really short way to rename the parent node without having to copy everything and replace the whole thing? Thnx in advance!!!
Using [Document.renameNode](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Document.html#renameNode(org.w3c.dom.Node,%20java.lang.String,%20java.lang.String)): ``` NodeList nodes = document.getElementsByTagName("tag1"); for (Node eachNode: nodes) { document.renameNode(eachNode, null, "reallyCoolTag"); } ```
You could use an XSL Transformation (XSLT) for this: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes" /> <xsl:template match="*"> <!-- match anything --> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> <xsl:template match="tag1"> <!-- switch the element name --> <xsl:element name="reallyCoolTag"> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:element> </xsl:template> </xsl:stylesheet> ``` This can be used with the [javax.xml.transform](http://java.sun.com/javase/6/docs/api/javax/xml/transform/package-summary.html) package (Java 1.4 and above): ``` TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(new StreamSource( new File("RenameTag.xslt"))); transformer .transform(new DOMSource(document), new StreamResult(System.out)); ``` See [DOMResult](http://java.sun.com/javase/6/docs/api/javax/xml/transform/dom/DOMResult.html) if you want a [Document](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Document.html) as the output.
Changing node name of xml-node with Java
[ "", "java", "xml", "xmlnode", "" ]
If I'm inserting content into a textarea that TinyMCE has co-opted, what's the best way to set the position of the cursor/caret? I'm using `tinyMCE.execCommand("mceInsertRawHTML", false, content);` to insert the content, and I'd like set the cursor position to the end of the content. Both `document.selection` and `myField.selectionStart` won't work for this, and I feel as though this is going to be supported by TinyMCE (through something I can't find on their forum) or it's going to be a really ugly hack. **Later:** It gets better; I just figured out that, when you load TinyMCE in WordPress, it loads the entire editor in an embedded iframe. **Later (2):** I can use `document.getElementById('content_ifr').contentDocument.getSelection();` to get the selection as a string, but not a Selection Object that I can use `getRangeAt(0)` on. Making progress little by little.
After spending over 15 hours on this issue (dedication, I know), I found a partial solution that works in FF and Safari, but not in IE. For the moment, this is good enough for me although I might continue working on it in the future. The solution: When inserting HTML at the current caret position, the best function to use is: `tinyMCE.activeEditor.selection.setContent(htmlcontent);` In Firefox and Safari, this function will insert the content at the current caret position within the iframe that WordPress uses as a TinyMCE editor. The issue with IE 7 and 8 is that the function seems to add the content to the top of the page, not the iframe (i.e. it completely misses the text editor). To address this issue, I added a conditional statement [based on this code](http://www.quirksmode.org/js/detect.html) that will use this function instead for IE: `tinyMCE.activeEditor.execCommand("mceInsertRawHTML", false, htmlcontent);` The issue for this second function, however, is that the caret position is set to the beginning of the post area after it has been called (with no hope of recalling it based on the browser range, etc.). Somewhere near the end I discovered that this function works to restore the caret position at the end of the inserted content with the first function: `tinyMCE.activeEditor.focus();` In addition, it restores the caret position to the end of the inserted content without having to calculate the length of the inserted text. The downside is that it only works with the first insertion function which seems to cause problems in IE 7 and IE 8 (which might be more of a WordPress fault than TinyMCE). A wordy answer, I know. Feel free to ask questions for clarification.
First what you should do is add a span at the end of the content you want to create. ``` var ed = tinyMCE.activeEditor; //add an empty span with a unique id var endId = tinymce.DOM.uniqueId(); ed.dom.add(ed.getBody(), 'span', {'id': endId}, ''); //select that span var newNode = ed.dom.select('span#' + endId); ed.selection.select(newNode[0]); ``` This is a strategy used by the TinyMCE developers themselves in writing Selection.js. Reading the underlying source can be massively helpful for this kind of problem.
What's the best way to set cursor/caret position?
[ "", "javascript", "wordpress", "iframe", "tinymce", "getselection", "" ]
Was just wondering how I would go about creating a planar shadow from a 4x3 matrix, all online demos I've seen use 4x4 matrices instead.
I guess that this is done by projecting a 3D object onto a plane, which essentially needs a fourth coordinate to represent infinity. If you only use 3 coordinates, you can only represent |R^3. However, for projections like shadows you will need full 3-space, thus including infinity - so you need the fourth coordinate. I guess you can solve this with trigonometry and not matrices at all. What is it you are trying to accomplish?
As noted in the other answer, you really need 4x4 to encode a projection. If it's any help at all you can do directly overhead shadows by scaling your height axis to 0 and translating the squashed geometry to your ground plane. A bit rubbish, but might be something you could use. I used this once a few years ago on a project that actually wanted shadows like that.
Creating planar shadows with 4x3 matrices?
[ "", "c++", "math", "directx", "matrix", "" ]
I have the following pair of functions: ``` void RegisterSink( ISink & Sink ) void UnregisterSink( ISink & Sink ) ``` Where ISink is an abstract base class. Internally, I would like to store pointers to the sinks in an std::set. When a sink is unregistered, i simply search for the pointer in my set, and remove it. My question is, is there any way, that taking the adress of the parameter Sink would yield different results, although the same object was passed as a parameter. I know, that pointers can change when casting in certain multiple inheritance szenarios, but what about this situation? Thanks in advance!
In case of multiple inheritance the meaning of "same object" sometimes is not obvious. For example, if ISink is present twice in the list of base classes and wasn't inherited with "virtual", such situation is possible: ``` class A {}; class B:public A {}; class C:public A {}; class D:public B,public C {}; ... void f(A *a); ... { D d; f(static_cast<B*>(&d)); f(static_cast<C*>(&d)); } ``` In this case f will get two different addresses. Whether is's same object or not probably depends on context. If you want to treat them as the same object, dynamic\_casting to void\* may help - it castes to most derived class (something virtual in A is needed, of course)
As you've said, pointer addresses may change when casting between virtual classes with multiple inheritance. However, in your case the static type is always the same: `ISink` so comparing two points of this static type is guaranteed to be safe, and yield reproducible results.
Determine object identity from a reference to a superclass
[ "", "c++", "" ]
I have several hundred lines of code like this: ``` if (c.SomeValue == null || c.SomeProperty.Status != 'Y') { btnRecordCall.Enabled = false; } if (c.SomeValue == null || (c.SomeProperty.Status != 'Y' && c.SomeOtherPropertyAction != 'Y')) { btnAddAction.Enabled = false; } if (c.SomeValue == null || c.SomeProperty.Processing != 'Y') { btnProcesss.Enabled = false; } ``` How can I refactor this correctly? I see that the check 'c.SomeValue == null' is being called every time, but it is included with other criteria. How can I possibly eliminate this duplicate code?
If you don't want to do much refactoring, you can easily pull the null check out. ``` if (c.SomeValue == null) { btnRecordCall.Enabled = false; btnAddAction.Enabled = false; btnProcesss.Enabled = false; } else { if(c.SomeProperty.Status != 'Y') { btnRecordCall.Enabled = false; } if((c.SomeProperty.Status != 'Y') && (c.SomeOtherPropertyAction != 'Y')) { btnAddAction.Enabled = false; } if(c.SomeProperty.Processing != 'Y') { btnProcesss.Enabled = false; } } ``` If you're looking to refactor instead of shuffle, the wall of boolean testing could be moved in to methods/extension methods of whatever class your object c is an instance of - that way you could say ``` btnRecordCall.Enabled = c.IsRecordCallAllowed(); ```
I would use the [specification pattern](http://en.wikipedia.org/wiki/Specification_pattern), and build composite specifications that map to a proper Enabled value. The overall question you want to answer is whether some object c satisfies a given condition, which then allows you to decide if you want something enabled. So then you have this interface: ``` interface ICriteria<T> { bool IsSatisfiedBy(T c); } ``` Then your code will look like this: ``` ICriteria<SomeClass> cr = GetCriteria(); btnAddAction.Enabled = cr.IsSatisfiedBy(c); ``` The next step is to compose a suitable ICriteria object. You can have another ICriteria implementation, (in additon to Or and And), called PredicateCriteria which looks like this: ``` class PredicateCriteria<T> : ICriteria<T> { public PredicateCriteria(Func<T, bool> p) { this.predicate = p; } readonly Func<T, bool> predicate; public bool IsSatisfiedBy(T item) { return this.predicate(item); } } ``` One instance of this would be: ``` var c = new PredicateCriteria<SomeClass>(c => c.SomeValue != null); ``` The rest would be composition of this with other criteria.
Refactor help c#
[ "", "c#", "design-patterns", "refactoring", "" ]
``` ulong foo = 0; ulong bar = 0UL;//this seems redundant and unnecessary. but I see it a lot. ``` I also see this in referencing the first element of arrays a good amount ``` blah = arr[0UL];//this seems silly since I don't expect the compiler to magically //turn '0' into a signed value ``` Can someone provide some insight to why I need 'UL' throughout to specify specifically that this is an unsigned long?
``` void f(unsigned int x) { // } void f(int x) { // } ... f(3); // f(int x) f(3u); // f(unsigned int x) ``` It is just another tool in C++; if you don't need it don't use it!
In the examples you provide it isn't needed. But suffixes are often used in expressions to prevent loss of precision. For example: ``` unsigned long x = 5UL * ... ``` You may get a different answer if you left off the UL suffix, say if your system had 16-bit ints and 32-bit longs. Here is another example inspired by Richard Corden's comments: ``` unsigned long x = 1UL << 17; ``` Again, you'd get a different answer if you had 16 or 32-bit integers if you left the suffix off. The same type of problem will apply with 32 vs 64-bit ints and mixing long and long long in expressions.
Why or why not should I use 'UL' to specify unsigned long?
[ "", "c++", "" ]
I am using SQL Server 2008 Enterprise. I am learning OUTPUT parameter of SQL Server stored procedure. For example, stored procedure sp\_add\_jobschedule has an OUTPUT parameter called schedule\_id. <http://msdn.microsoft.com/en-us/library/ms366342.aspx> My confusion is, looks like OUTPUT parameter could be provided an input value and also returns a value, looks like it has behaviors of both INPUT and OUTPUT parameter? Is it allowed not to provide any INPUT values for OUTPUT parameter (to make it look like pure output parameter behavior)?
The confusion is justified to a degree - and other RDBMS like Oracle do have stored procedure parameters which can be of type `IN` (input only), `OUT` (output only), or `INOUT` (both ways - "pass by reference" type of parameter). SQL Server is a bit sloppy here since it labels the parameter as `OUTPUT`, but really, this means `INPUT`/`OUTPUT` - it basically just means that the stored proc has a chance of returning a value from its call in that parameter. So yes - even though it's called `OUTPUT` parameter, it's really more of an `INPUT`/`OUTPUT` parameter, and those `IN`, `INOUT`, `OUT` like in Oracle do not exist in SQL Server (in T-SQL).
I can give you short example on how to create stored procedure with output parameter. ``` CREATE PROCEDURE test_proc @intInput int, @intOutput int OUTPUT AS set @intOutput = @intInput + 1 go ``` And to call this procedure and then use output parameter do as following: ``` declare @intResult int exec test_proc 3 ,@intResult OUT select @intResult ``` You see, that you should declare ouput variable first. And after executing stored procedure, the output value will be in your variable. You can set any value to your output variable, but after executing stored procedure it will contain exactly what stored procedure return (no matter what value was in the output variable). For example: ``` declare @intResult int exec test_proc 3 ,@intResult OUT select @intResult ``` It will return 4. And: ``` declare @intResult int set @intResult = 8 exec test_proc 3 ,@intResult OUT select @intResult ``` Also return 4.
SQL Server output parameter issue
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "" ]
I am writing some class and it wont compile without "using System.Linq". But i don't understand why its needed. What i am writing has nothing to do with Linq. How can i find out where a namespace is used? And the very badly written piece of code (I am trying to figure out what i want it to do): ``` using System; using System.Collections; using System.Collections.Generic; //using System.Linq; using System.Text; namespace DateFilename { public class FailedFieldsList { private static List<FailedFields> ErrorList = new List<FailedFields>(); public void AddErrorList(FailedFields errs) { ErrorList.Add(errs); } public void addSingleFailedField(string vField, string vMessage) { //FailedFields } public List<FailedFields> GetErrorList() { return ErrorList; } public class FailedFields { public List<FailedField> ListOfFailedFieldsInOneRecord = new List<FailedField>(); public class FailedField { public string fieldName; public string message; public FailedField(string vField, string vMessage) { this.fieldName = vField; this.message = vMessage; } public override string ToString() { return fieldName + ", " + message; } } public void addFailedField(FailedField f) { ListOfFailedFieldsInOneRecord.Add(f); } public int getFailedFieldsCount() { return ListOfFailedFieldsInOneRecord.Count(); } } } } ``` Error message produced when i dont include the linq namespace: `Error 4 Non-invocable member 'System.Collections.Generic.List<DateFilename.FailedFieldsList.FailedFields.FailedField>.Count' cannot be used like a method. D:\Slabo\My Documents\Visual Studio 2008\Projects\DateFilename\DateFilename\FailedFieldsList.cs 47 54 DateFilename` Thanks
The problem is in the last method: ``` public int getFailedFieldsCount() { return ListOfFailedFieldsInOneRecord.Count(); } ``` The method **Count()** is not a member of a List(T). The property **Count**, however, is. If you replace Count() by Count, this will compile without the need for using System.Linq. By including System.Linq, you enable the extension method Count(), which, confusingly enough, does exactly the same thing. See [List(T) Members](http://msdn.microsoft.com/en-us/library/d9hw1as6.aspx) on msdn for a breakdown of what's part of a List(T).
You could be using some Extension Methods included in the `System.Linq` namespace (like Distinct, Select, Where, or some other collection methods). The build output window should give you a pretty good indication where the necessary using statement should be. EDIT: ``` 'System.Collections.Generic.List<DateFilename.FailedFieldsList.FailedFields.FailedField>.Count cannot be used like a method. ``` The only place that contains the word count in your code sample is: `ListOfFailedFieldsInOneRecord.Count()` in `getFailedFieldsCount()` Count is an Extension Method introduced in the [`System.Linq`](http://msdn.microsoft.com/en-us/library/system.linq.aspx) namespace, namely via the [Enumerable](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx) static class. [Here](http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx) are all of the Extension Methods this class affords you.
how to find out if a certain namespace is used, and if so, where?
[ "", "c#", ".net", "debugging", "" ]
Im using sql server 2005. i want data with comma. for example ['5000'],['5001'],.. but the last record should not include comma. Pls help me. Query: select '['''+convert(varchar,parcelid)+'''],' from sampletable
Try the COALESCE function ``` SELECT @groupedText = COALESCE(@groupedText, '') + [Text] + ',' FROM Requirement WHERE CampaignId = @campaignId ORDER BY [Text] ``` Then you could try one of the string functions to kill the end comma [T-SQL string functions](http://doc.ddart.net/mssql/sql70/fa-fz_23.htm)
You can use regular expressions to remove the last comma or do it using your programming language (ASP etc. like a chop function or something). <http://weblogs.sqlteam.com/jeffs/archive/2007/04/27/SQL-2005-Regular-Expression-Replace.aspx>
SQL Query: data with comma
[ "", "sql", "" ]
This might get closed, but I'll try anyway. I was showing a VB6 programmer some of my C# code the other day and he noticed the var keyword and was like "Oh a variant type, that's not really strong typing when you do that." and I had to go on the typical "var != VARIANT" speech to explain to him that it is not a variant it just compiler inferred. I was thinking about other words they (C# team) could have used so this kind of thing didn't happen. I personally like *infer*, something like: ``` infer person = new Person("Bob"); ``` I know this is not really that big of deal, but just curious to see what other people would use to do the same thing. I have made this a community wiki because it doesn't really have an answer.
C++0x uses the "auto" keyword for type inference: <http://en.wikipedia.org/wiki/C%2B%2B0x#Type_inference> That's not a bad trade-off for those guys since "auto" was (AFAIK) already a keyword. I can imagine it in C#: ``` auto i = 3; ``` I do like "infer" though (but then I don't have any problem with "var" either).
``` thisappearsweaklytypedbutisactuallystronglytyped i = 3; ``` It's the only way to avoid confusion! Don't worry, autocomplete means it won't really take that much longer to type...
Better word for inferring variables other than var
[ "", "c#", "language-design", "" ]
I have a windows Application that stores certain files in a directory. I would like to know if there is a way in .net that I can restrict users not to have access to that directly (by just going to that directory in windows, and grab files) so only my application can add/verify/delete a file in that directory.
Could you use the Isolated Storage in .Net? While, it isn't necessarily restricted away from your users it may be a lot harder to find.... (stores under the local settings\application data\isolated storage for the logged in user) Via code you work with it by using / importing the System.Io.IsolatedStorage and then you can create directories, files, etc... normal. You also don't have to keep track of the actual directory on the HD it's in as .Net manages this. Maybe a nice plus.
This is only possible if your application runs with different credentials than the user running the application. By default all applications run with the credentials of the user who launched the process. This means the application has the same directory and file restrictions as the user. Without a different account, the application can only decrease it's ability to access the file system, not increase it. Dealing with the file system is evil in general. Even if you could get the user to not play in that directory you still can't trust the results will be in the exact same state as you left them. It's possible for other users, physical disk corruption or any number of other things to corrupt your files. The only way to sanely program the file system is to expect failure from the start and count yourself lucky when it actually works.
Restrict a directory that can be used only through a .net Application
[ "", "c#", "windows", "security", "permissions", "windows-xp", "" ]
It seems that I am unable to change most request headers from JavaScript when making an AJAX call using XMLHttpRequest. Note that when `request.setRequestHeader` has to be called after `request.open()` in Gecko browsers (see <http://ajaxpatterns.org/Talk:XMLHttpRequest_Call>). When I set the *Referer*, it doesn't get set (I looked at the request headers sent using Firebug and Tamper Data). When I set *User-Agent*, it messed up the AJAX call completely. Setting *Accept* and *Content-Type* does work, however. Are we prevented from setting *Referer* and *User-Agent* in Firefox 3? ``` var request = new XMLHttpRequest(); var path="http://www.yahoo.com"; request.onreadystatechange=state_change; request.open("GET", path, true); request.setRequestHeader("Referer", "http://www.google.com"); //request.setRequestHeader("User-Agent", "Mozilla/5.0"); request.setRequestHeader("Accept","text/plain"); request.setRequestHeader("Content-Type","text/plain"); request.send(null); function state_change() { if (request.readyState==4) {// 4 = "loaded" if (request.status==200) {// 200 = OK // ...our code here... alert('ok'); } else { alert("Problem retrieving XML data"); } } } ```
[W3C Spec on setrequestheader](http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#dfn-setrequestheader). The brief points: > If the request header had > already been set, then the new value > MUST be concatenated to the existing > value using a U+002C COMMA followed by > a U+0020 SPACE for separation. > > UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it. However - After searching through the framework XHR in jQuery they don't allow you to change the User-Agent or Referer headers. The closest thing: ``` // Set header so the called script knows that it's an XMLHttpRequest xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); ``` I'm leaning towards the opinion that what you want to do is being denied by a security policy in FF - if you want to pass some custom `Referer` type header you could always do: ``` xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com'); ```
@gnarf answer is right . wanted to add more information . Mozilla Bug Reference : <https://bugzilla.mozilla.org/show_bug.cgi?id=627942> Terminate these steps if header is a case-insensitive match for one of the following headers: ``` Accept-Charset Accept-Encoding Access-Control-Request-Headers Access-Control-Request-Method Connection Content-Length Cookie Cookie2 Date DNT Expect Host Keep-Alive Origin Referer TE Trailer Transfer-Encoding Upgrade User-Agent Via ``` Source : <https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader>
Set a request header in JavaScript
[ "", "javascript", "ajax", "" ]
I've been charged with creating a little GUI launcher app to go on a CD which will offer the user some software and some videos. It's not being aimed at particularly tech-savvy people, so it needs to be quite simple. I guess the real sticking point here is that it will be form based. I would very much like the launcher to just run from an exe without having to install any .net stuff or have java installed. I know ClickOnce is fairly simple and I will fall back on it if necessary, but I thought it might be worth asking if there are any easy ways to do this. I mainly program using visual c# these days, but have experience with java and c and I am a relatively quick learner, so feel free to suggest other languages.
Depending on the minimum target OS, you could possibly choose VB6, if it doesn't affend you too much, because the VB6 runtime has been included in windows since Windows 2000. However, you need to stick to the included controls to keep things simple.
The most straightforward way to create a dependency-free executable for Windows is to use ordinary Win32 functions from C (or C++). Alternatively, you could use MFC with C++ because you can link MFC right into your executable to avoid a dependency on MFC DLLs. There are probably other C/C++ frameworks that can be linked into an executable. However, you probably want to avoid Java and C# or any other .Net language, if you want minimal dependencies.
Best way to create a standalone program for windows without having to install pre-requisites?
[ "", "java", ".net", "winforms", "" ]
I want to determine the available disk space on windows. I don't care that my code is not portable. I use this : ``` String[] command = {"dir",drive}; Process process = Runtime.getRuntime().exec(command); InputStream result = process.getInputStream(); ``` aiming to parse the result from a "dir C:" type of call, but the String I get from the command line call is as if I called dir with a `/W` option (not giving any information about file sizes or disk usage / free space). (Although when I launch `dir C:` directly from the command line, I get the expected result, so there is no `dir` particular setup on my system.) Trying to pass a token `/-W` or on any other option seems not to work : I just get the name of the folders/files contained in the drive, but no other information whatsoever. Someone knows a fix / workaround ? **NOTE:** I can't go along the `fsutil` route, because `fsutil` does not work on network drives.
It sounds like your `exec()` is finding a program called "dir" somewhere in your path because with your `String[] command` as it is I would otherwise expect you to get an `IOException (The system cannot find the file specified)`. The standard dir command is built into the cmd.exe Command Prompt and is not a standalone program you can execute in its own right. To run the dir command built into cmd.exe you need to use the /c switch on cmd.exe which executes the specified command and then exits. So if you want to execute: ``` cmd /c dir ``` your arguments to pass to exec would be: ``` String[] command = { "cmd", "/c", "dir", drive }; ```
If you don't care about portability, use the [GetDiskFreeSpaceEx](http://support.microsoft.com/kb/202455) method from Win32 API. Wrap it using JNI, and viola! Your Java code should look like: ``` public native long getFreeSpace(String driveName); ``` and the rest can be done through the example [here](http://patriot.net/%7Etvalesky/jninative.html). I think that while JNI has its performance problems, it is less likely to cause the amount of [pain you'll endure](https://bugs.java.com/bugdatabase/view_bug?bug_id=6474073) by using the Process class....
Java : how to determine disk space on Windows system prior to 1.6
[ "", "java", "windows", "diskspace", "" ]
How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red. I am using webforms and I do have the jquery library available to me.
Here is quick and dirty thing (but it works!) ``` <form id="form1" runat="server"> <asp:TextBox ID="txtOne" runat="server" /> <asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtOne" Text="SomeText 1" /> <asp:TextBox ID="txtTwo" runat="server" /> <asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="txtTwo" Text="SomeText 2" /> <asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();" Text="Click" CausesValidation="true" /> </form> <script type="text/javascript"> function BtnClick() { //var v1 = "#<%= rfv.ClientID %>"; //var v2 = "#<%= rfv2.ClientID %>"; var val = Page_ClientValidate(); if (!val) { var i = 0; for (; i < Page_Validators.length; i++) { if (!Page_Validators[i].isvalid) { $("#" + Page_Validators[i].controltovalidate) .css("background-color", "red"); } } } return val; } </script> ```
You could use the following script: ``` <script> $(function(){ if (typeof ValidatorUpdateDisplay != 'undefined') { var originalValidatorUpdateDisplay = ValidatorUpdateDisplay; ValidatorUpdateDisplay = function (val) { if (!val.isvalid) { $("#" + val.controltovalidate).css("border", "2px solid red"); } originalValidatorUpdateDisplay(val); } } }); </script> ``` This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary. Hope this helps,
Change textbox's css class when ASP.NET Validation fails
[ "", "asp.net", "javascript", "jquery", "validation", "webforms", "" ]
I'd like to truncate a dynamically loaded string using straight JavaScript. It's a url, so there are no spaces, and I obviously don't care about word boundaries, just characters. Here's what I got: ``` var pathname = document.referrer; //wont work if accessing file:// paths document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>" ```
Use the [substring](http://www.w3schools.com/jsref/jsref_substring.asp) method: ``` var length = 3; var myString = "ABCDEFG"; var myTruncatedString = myString.substring(0,length); // The value of myTruncatedString is "ABC" ``` So in your case: ``` var length = 3; // set to the number of characters you want to keep var pathname = document.referrer; var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length)); document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + trimmedPathname + "</a>" ```
Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges: ``` function truncateString(str, num) { if (str.length > num) { return str.slice(0, num) + "..."; } else { return str; } } ```
Truncate a string straight JavaScript
[ "", "javascript", "truncate", "" ]
``` Public Sub cleanTables(ByVal prOKDel As Short) Dim sqlParams(1) As SqlParameter Dim sqlProcName As String sqlProcName = "db.dbo.sp_mySP" sqlParams(1) = New SqlParameter("@OKDel", prOKDel) Try dbConn.SetCommandTimeOut(0) dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams) Catch ex As Exception Finally End Try End Sub ``` Is there ``` CommandType.StoredProcedure...CommandType.Function sqlParams(1) = New SqlParameter("@OKDel", prOKDel)... ``` and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams) Thanks
Sorry, there is no way to run a function directly. Either call it using a sql Text command ``` Public Sub RunFunction(ByVal input As Short) Using myConnection As New Data.SqlClient.SqlConnection Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection) myCommand.CommandType = CommandType.Text myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input)) myCommand.CommandTimeout = 0 Try myCommand.ExecuteNonQuery() Catch ex As Exception End Try End Using End Using End Sub ``` Or Wrap a procedure round it... ``` Create Procedure RunMyFunction(@MyParam as int) Select * FROM dbo.MyFunction(@MyParam) Go ```
Yes you can call a function directly as demonstrated below. ``` Dim dtaName As New SqlClient.SqlDataAdapter dtaName.SelectCommand = New SqlClient.SqlCommand With dtaName.SelectCommand .CommandTimeout = 60 .Connection = prvcmpINC.cntINC .CommandType = CommandType.StoredProcedure .CommandText = "dbo.app_GetName" .Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn) .Parameters.Add("@intResult", SqlDbType.Int) .Parameters("@intResult").Direction = ParameterDirection.ReturnValue End With dtaName.SelectCommand.ExecuteScalar() intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value ```
How can I call a sqlserver function from VB.net(or C#) ? Is there some syntax like stored procedure?
[ "", "c#", "sql-server", "vb.net", "function", "" ]
I'm trying to convince my organization to start running unit tests on our C++ code. This is a two-part question: 1. Any tips on convincing my employer that unit testing saves money in the long run? (They have a hard time justifying the immediate expenses.) 2. I'm not familiar with any C++ testing frameworks that integrate well with MFC. Does anyone have experience with this, or use any general test harnesses that could be extended?
I can answer the second question - the Boost Test framework can be used with MFC and someone has posted an excellent article about it on Code Project: <http://www.codeproject.com/KB/architecture/Designing_Robust_Objects.aspx>
Boost test is really complete, but a little cumbersome. If you just want to make simple tests, spending as little time as possible, have a look at [google test](http://code.google.com/p/googletest/).
C++ unit testing with Microsoft MFC
[ "", "c++", "unit-testing", "mfc", "" ]
My httphandler does not work in IIS7 (virutal directory), but using cassini it works. It used to work on my windows xp IIS also. What could be the cause of this? I am getting a 404 not found error when trying to access the httphandler's page.
IIS7 depends on the registration for HttpHandlers to be in a different location than usual. There is a section in system.web/webserver/handlers where you should be able to register your HttpHandler, as opposed to the standard system.web/httpHandlers Hope that helps
Check that the Network Service (or whatever the identiy underwhich its application pool runs) has read access to the .ashx file.
My HttpHandler doesn't work with a virtual directory in IIS7, but using cassini it does?
[ "", "c#", "asp.net", "iis-7", "" ]
I have 3 columns of data in SQL Server 2005 : LASTNAME FIRSTNAME CITY I want to randomly re-order these 3 columns (and munge the data) so that the data is no longer meaningful. Is there an easy way to do this? I don't want to change any data, I just want to re-order the index randomly.
When you say "re-order" these columns, do you mean that you want some of the last names to end up in the first name column? Or do you mean that you want some of the last names to get associated with a *different* first name and city? I suspect you mean the latter, in which case you might find a programmatic solution easier (as opposed to a straight SQL solution). Sticking with SQL, you can do something like: ``` UPDATE the_table SET lastname = (SELECT lastname FROM the_table ORDER BY RAND()) ``` Depending on what DBMS you're using, this may work for only one line, may make all the last names the same, or may require some variation of syntax to work at all, but the basic approach is about right. Certainly some trials on a *copy* of the table are warranted before trying it on the real thing. Of course, to get the first names and cities to also be randomly reordered, you could apply a similar query to either of those columns. (Applying it to all three doesn't make much sense, but wouldn't hurt either.) Since you don't want to change your original data, you could do this in a temporary table populated with all rows. Finally, if you just need a single random value from each column, you could do it in place without making a copy of the data, with three separate queries: one to pick a random first name, one a random last name, and the last a random phone number.
I suggest using newid with checksum for doing randomization ``` SELECT LASTNAME, FIRSTNAME, CITY FROM table ORDER BY CHECKSUM(NEWID()) ```
How to randomize order of data in 3 columns
[ "", "sql", "sql-server", "" ]
Is it possible to deploy a .NET 2.0 application as a portable executable? So that my program can be ran in a Flash Disk without the .NET Framework 2.0 installed in the target machine. Or maybe is it possible to distribute my program with the required .NET DLLs, so that no framework installation is necessary? I know that there are some alternative tools to turn my .NET exe into a single native executable like RemoteSoft Salamander, Xenocode Postbuild, and Thinstall, but unfortunately I can't afford one. I also tried to embed the dependencies with Mono's mkbundle, but it messed my program up =\ (no XP visual style, broke some controls and its functionality) Any kind of help would be appreciated :) Thanks. fyi: my IDE is Microsoft Visual C# 2008 Express Edition with .NET Framework 2.0 as the target framework.
Well, other than things like Salamander and Thinstall (now VMWare ThinApp) you would have to have .NET installed if you really want to run .NET. It *may* be possible to run [Mono](http://mono-project.com) without actually installing it (not statically linking your program, but including Mono on the flash drive). I suspect it would be tricky though, as you'd have to tell the runtime about things like the GAC location. I can't see anything in the Mono FAQ about this, but you might want to ping a Mono mailing list - it sounds like a potentially interesting and useful thing to be able to do.
No; you need either the framework installed, or the tools like you have mentioned. You *could* potentially look at mono's new static linker, but that is about it...
Deploying C# (.NET 2.0) application as a portable application?
[ "", "c#", ".net", ".net-2.0", "portability", "" ]
Just had my mind going today. I spent some time in IE debug mode, browsing the web as usual, and oh boy do I see many errors :) Most of these errors are because some value are of a different type than expected (at least as far as I interpret the error messages). What are the reasons JavaScript and similar scripting languages aren't strongly typed? Is it just to make the languages "easier" to understand and more accessable, or is the lack of a "compile-time" the real problem?
It should definitely have strong typing *available*. Actionscript 3 is strongly typed, but still has prototype inheritance and a wildcard type if you need dynamic objects. There are no downsides to having that feature available, and I have to say, for a project of moderate to large size, strong typing prevents A TON of problems. To get the most out of it you need IDE support so it can report errors and provide autocomplete options, but Javascript would be in a whole new world if it had real classes and strong typing.
It gains flexibility from not being typed. I personally enjoy the weakly typed languages. So the answer is there'd be benefits and drawbacks. For people who want a strongly-typed language in the browser, GWT and Script# are available.
Would javascript and similar scripting languages benefit from being strongly typed?
[ "", "javascript", "strong-typing", "scripting-languages", "" ]
I have a long list (1000+) of hex colors broken up in general color categories (Red, Orange, Blue, etc). When I show the list of colors in each category I need to show them in order of shade. i.e. light red first and dark red last. What would the algorithm be to do this? (googling has failed me)
Convert the colors from RGB to a [HSV or HSL](http://en.wikipedia.org/wiki/HSL_color_space) scale and then sort them by Value or Lightness. Lightness might work better as it would capture the "faded" colors better, such as pink->red->dark red.
I know this question is old, but I didn't found a pretty solution to this problem, so I investigate a little bit and want to share what I did for hypothetical future googlers. First, convert to HSL is a great idea. But sort only by hue or light didn't solve completely the issue when your color are not "classified". Given an array which look like: ``` $colors = [ [ 'color' => '#FDD4CD'], [ 'color' => '#AE3B3B'], [ 'color' => '#DB62A0'], ... ] ``` ## First we convert all Hex colors to HSL ``` foreach ($colors as &$color) { $color['hsl'] = hexToHsl($color['color']); } /** * Convert a hexadecimal color in RGB * @param string $hex * @return array */ function hexToHsl($hex){ list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x"); return rgbToHsl($r, $g, $b); } /** * Convert a RGB color in its HSL value * @param int $r red * @param int $g green * @param int $b blue * @return array */ function rgbToHsl($r, $g, $b) { $r /= 255; $g /= 255; $b /= 255; $max = max($r, $g, $b); $min = min($r, $g, $b); $h = 0; $l = ($max + $min) / 2; $d = $max - $min; if ($d == 0) { $h = $s = 0; // achromatic } else { $s = $d / (1 - abs(2 * $l - 1)); switch ($max) { case $r: $h = 60 * fmod((($g - $b) / $d), 6); if ($b > $g) { $h += 360; } break; case $g: $h = 60 * (($b - $r) / $d + 2); break; case $b: $h = 60 * (($r - $g) / $d + 4); break; } } return array('h' => round($h, 2), 's' => round($s, 2), 'l' => round($l, 2)); } ``` ## Then sort colors We compare: * Their hue if they are in the same 'interval' ([This help to understand why I choose 30°](http://www.december.com/html/spec/colorhslhex.html)). So we compare the hue only if both are in [0-30], [30-60], [60-90],... * If not in the same interval, sort by their Lightness, then by saturation if both share the same Lightness. So: ``` usort($colors, function ($a, $b) { //Compare the hue when they are in the same "range" if(!huesAreinSameInterval($a['hsl']['h'],$b['hsl']['h'])){ if ($a['hsl']['h'] < $b['hsl']['h']) return -1; if ($a['hsl']['h'] > $b['hsl']['h']) return 1; } if ($a['hsl']['l'] < $b['hsl']['l']) return 1; if ($a['hsl']['l'] > $b['hsl']['l']) return -1; if ($a['hsl']['s'] < $b['hsl']['s']) return -1; if ($a['hsl']['s'] > $b['hsl']['s']) return 1; return 0; }); /** * Check if two hues are in the same given interval * @param float $hue1 * @param float $hue2 * @param int $interval * @return bool */ function huesAreinSameInterval($hue1, $hue2, $interval = 30){ return (round(($hue1 / $interval), 0, PHP_ROUND_HALF_DOWN) === round(($hue2 / $interval), 0, PHP_ROUND_HALF_DOWN)); } ``` > rgbToHsl found on [www.brandonheyer.com](http://www.brandonheyer.com/2013/03/27/convert-hsl-to-rgb-and-rgb-to-hsl-via-php/) > > hexToRgb found on [stackoverflow](https://stackoverflow.com/a/15202130/291541)
Sorting by Color
[ "", "php", "sorting", "colors", "" ]
I have a database with hundreds of tables. I am building a script to delete all of the rows in this database. Of course, being a relational database, I have to delete rows from the children before I can touch the parents. Is there something I can use for this or do I have to do this the hard way? **EDIT** ***Accepted Answer was modified to include Disable Trigger as well*** ``` EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL ON ? ' EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' EXEC sp_MSForEachTable 'DELETE FROM ?' EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' EXEC sp_MSForEachTable 'ENABLE TRIGGER ALL ON ? ' ```
You can disable all the constraints, then delete all the data, and enable the constraints again. You can put the code in a stored procedure for reutilization. Something quick and dirty: ``` CREATE PROCEDURE sp_EmplyAllTable AS EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’ EXEC sp_MSForEachTable ‘DELETE FROM ?’ EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’ GO ```
I'm guessing you want the structure without any of the data? Can you script the tables / sp's / user-defined functions / triggers / permissions etc. and then drop the database before recreating it with the script? This link explains how to generate a script for all the objects in a database using SQL server Management studio... <http://msdn.microsoft.com/en-us/library/ms178078.aspx>
Cleaning up a database
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "" ]
As a short term solution I'm trying to jam a windows form 'usercontrol' into a WPF application. I see in the WPF application view that I can add a 'custom windows form control' to the project and it makes an empty custom control, but I can't figure out how to add it. Ideally I'd like to know how to take the .dll from my compiled windows forms user control and stick it into the WPF app, or import the user control into the WPF application. Thanks, Sam
You can't really add it as a control to the toolbox like you could for a Windows Forms Application. What you should do instead is "host" the user control inside of the WPF application. [See how to do it on MSDN](http://msdn.microsoft.com/en-us/library/ms742875.aspx). Here's an example of how to use a masked text box (which you can easily modify to use your custom control): ``` <Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" Title="HostingWfInWpf"> <Grid> <WindowsFormsHost> <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/> </WindowsFormsHost> </Grid> </Window> ```
Add a reference to System.Windows.Forms and WindowsFormsIntegration to your Project ``` xmlns:WinForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" xmlns:WindowsFormsIntegration="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" ``` And place Windows forms host in the window. ``` <WindowsFormsHost Name="wfhDate" HorizontalAlignment="Center" VerticalAlignment="Stretch"> <WinForms:FlowLayoutPanel/> </WindowsFormsHost> ``` Now in C# code ``` using Forms = System.Windows.Forms; ......................... Forms.FlowLayoutPanel flpPanel = this.wfhDate.Child as Forms.FlowLayoutPanel; // Initialize your Forms contol here. flpPanel.Controls.Add( yourControl ); ```
How to put a custom windows forms control in a WPF application?
[ "", "c#", "wpf", "user-controls", "" ]
I have the following use case: There's a class called Template and with that class I can create instances of the ActualObject class (ActualObject copies its inital data from the Template). The Template class has a list of Product:s. Now here comes the tricky part, the user should be able to delete Products from the database but these deletions may not affect the content of a Template. In other words, even if a Product is deleted, the Template should still have access to it. This could be solved by adding a flag "deleted" to the Product. If a Product is deleted, then it may not be searched explicitly from the database, but it can be fetched implicitly (for example via the reference in the Template class). The idea behind this is that when an ActualObject is created from a template, the user is notified in the user interface that "The Template X had a Product Z with the parameters A, B and C, but this product has been deleted and cannot be added as such in ActualObject Z". My problem is how I should mark these deleted objects as deleted. Before someone suggests that just update the delete flag instead of doing an actual delete query, my problem is not that simple. The delete flag and its behaviour should exist in all POJOs, not just in Product. This means I'll be getting cascade problems. For example, if I delete a Template, then the Products should also be deleted and each Product has a reference to a Price-object which also should be deleted and each Price may have a reference to a VAT-object and so forth. All these cascaded objects should be marked as deleted. My question is how can I accomplish this in a sensible manner. Going through every object (which are being deleted) checking each field for references which should be deleted, going through their references etc is quite laborious and bugs are easy to slip in. I'm using Hibernate, I was wondering if Hibernate would have any such inbuilt features. Another idea that I came to think of was to use hibernate interceptors to modify an actual SQL delete query to an update query (I'm not even 100% sure this is possible). My only concern is that does Hibernate rely on cascades in foreign keys, in other words, the cascaded deletes are done by the database and not by hibernate.
> My problem is how I should mark these > deleted objects as deleted. I think you have choosen a very complex way to solve the task. It would be more easy to introduce `ProductTemplate`. Place into this object all required properties you need. And also you need here a reference to a `Product` instance. Than instead of marking `Product` you can just delete it (and delete all other entities, such as prices). And, of course, you should clean reference in `ProductTemplate`. When you are creating an instance of `ActualObject` you will be able to notify the user with appropriate message.
``` public interface Deletable { public void delete(); } ``` Have all your deletable objects implement this interface. In their implementations, update the `deleted` flag and have them call their children's `delete()` method also - which implies that the children must be `Deletable` too. Of course, upon implementation you'll have to manually figure which children are `Deletable`. But this should be straightforward, at least.
Hiding deleted objects
[ "", "java", "hibernate", "jpa", "" ]
I am using Convert.ChangeType() to convert from Object (which I get from DataBase) to a generic type T. The code looks like this: ``` T element = (T)Convert.ChangeType(obj, typeof(T)); return element; ``` and this works great most of the time, however I have discovered that if I try to cast something as simple as return of the following sql query ``` select 3.2 ``` the above code (T being double) wont return 3.2, but 3.2000000000000002. I can't realise why this is happening, or how to fix it. Please help!
What you're seeing is an artifact of the way floating-point numbers are represented in memory. There's quite a bit of information available on exactly why this is, but [this paper](http://www.physics.ohio-state.edu/~dws/grouplinks/floating_point_math.pdf) is a good one. This phenomenon is why you can end up with seemingly anomalous behavior. A `double` or `single` should never be displayed to the user unformatted, and you should avoid equality comparisons like the plague. If you need numbers that are accurate to a greater level of precision (ie, representing currency values), then use `decimal`.
This probably is because of [floating point arithmetic](http://en.wikipedia.org/wiki/Floating_point). You probably should use decimal instead of double.
C# Wrong conversion using Convert.ChangeType()
[ "", "c#", "generics", "casting", "" ]
Using aspnet 3.5. I have some javascript functions in my aspx file. Why do the javascript comments get passed to the browser? It makes the download file unnecessarily large.
Which is why production environments will typically minify/pack Javascript files. This removes unnecessary white-space and comments. But if the comments are in the HTML file itself (or the HTML document outputted by an ASP.NET page) then the server has to either send the comments to the client or have an extra step to strip them out. The problem is that this process could be relatively expensive since you basically have to parse the HTML output to figure out where the Javascript is and then where the comments are. It's not as simple as a regular expression search and replace (not if you want it to be reliable at any rate).
Javascript is evaluated on the client, so it downloads all the source (including the comments).
Why are javascript comments downloaded to the browser?
[ "", "asp.net", "javascript", "" ]
I've constructed a regular expression which I compile to a Pattern to find Fortran Real\*8 numbers. The tricky bit is that the file I'm reading from is a single line with a few million columns.. When I do this: ``` Scanner recordScanner = new Scanner(recordString); String foundReal = recordScanner.findInLine(real8Regex); ``` I get what I'm looking for, but when I use the next(Pattern) method, I get an InputMismatchException.. Strange, considering both findInLine and next return Strings. ``` Scanner recordScanner = new Scanner(recordString); String foundReal = recordScanner.next(real8Regex); ``` Am I missing something crucial in the use of the next() method?
Is it a "not all tokens match the pattern and thus `next(Pattern)` gets stuck at the first non-matching token" issue? `next(Pattern)` could be used like this: ``` String toSearch = "ab123d4e::g67f912g34h"; Scanner aScanner = new Scanner(toSearch); aScanner.useDelimiter("[a-z]+"); while (aScanner.hasNext("[0-9]+")) { System.out.println(aScanner.next("[0-9]+")); } ``` but will only output 123 and 4 as the non-matching third token causes the `while` loop to terminate. In that scenario, however, I should just use `hasNext()` and `next()` instead. I'm struggling to think of a real reason to ever use `next(Pattern)` because it will get stuck at the first token which does not match the pattern. `next(Pattern)` does *not* mean "return the first token after the current position which matches Pattern"; it means "return the next token in the sequence if it matches Pattern; otherwise do nothing" You (presumably) need to read in all of the tokens so would be better to use `hasNext()` and `next()` and then use a `Matcher` against the required `Pattern` for each token Finally, you may find [question 842496](https://stackoverflow.com/questions/842496/reading-text-with-java-scanner-nextpattern-pattern) useful
It seems to me that the documentation isn't brilliantly written, but it's doing what it's meant to. `next(pattern)` is documented to return the token *if* it is found at the scanner's current location. `findInLine(pattern)` is documented to return `null` if the pattern isn't matched within the current line. To check first, use `hasNext(pattern)` before calling `next(pattern)`.
Trouble With/Confused By Java.util.Scanner's next(Pattern) Method
[ "", "java", "regex", "" ]
I'm trying to parse XML feed with SimpleXML, here is a chunk of the XML tree: ``` <item> <game:name>Tetris</game:name> <game:desc>Way Cool Game</game:desc> <size>5mb</size> </item> ``` Well actually, I can succesfully access 'size' with something like that: `$item->size`, but how do I get value? Of course I can't call like that: `$item->game:name`, and I don't know how what goes after ':' is called. Is it a parameter, attribute or what? Thanks for advance!
You need to define the namespace for game. XML requires all namespaces to be defined. There have been several previous answers about using custom namespaces: i.e. * [How do I parse XML containing custom namespaces using SimpleXML?](https://stackoverflow.com/questions/1133897/how-do-i-parse-xml-containing-custom-namespaces-using-simplexml)
Use the [children()](http://us.php.net/manual/en/function.simplexml-element-children.php) function to get the children of the namespace. ``` $useThis = $xmlDoc->children("http://game.namespace/"); ``` given that <http://game.namespace> is the URL to your game namespace in the root node. Here's an explanation/sample: * [SimpleXML and namespaces (Oct 2005; by Kevin Yank for Sitepoint)](http://www.sitepoint.com/simplexml-and-namespaces/)
How to access element like <game:title> with simplexml?
[ "", "php", "xml", "simplexml", "" ]
I posted on this topic [earlier](https://stackoverflow.com/questions/1018005/method-for-making-a-variable-size-struct) but now I have a more specific question/problem. Here is my code: ``` #include <cstdlib> #include <iostream> typedef struct{ unsigned int h; unsigned int b[]; unsigned int t; } pkt; int main(){ unsigned int* arr = (unsigned int*) malloc(sizeof(int) * 10); arr[0] = 0xafbb0000; arr[1] = 0xafbb0001; arr[2] = 0xafbb0011; arr[3] = 0xafbb0111; arr[4] = 0xafbb1111; arr[5] = 0xafbc0000; arr[6] = 0xafbc0001; arr[7] = 0xafbc0011; arr[8] = 0xafbc0111; arr[9] = 0xafbc1111; pkt* p = (pkt*) malloc(sizeof(int)*13); p->h = 0x0905006a; int counter; ``` Here's what I get for(counter=0; counter < 10; counter++) p->b[counter] = arr[counter]; ``` p->t = 0x55555555; std::cout << "header is \n" << p->h << std::endl; std::cout << "body is" << std::endl; for(counter=0; counter < 10;++counter) std::cout << std::hex << *((p->b)+counter) << std::endl; std::cout << "trailer is \n" << p->t << std::endl; ``` } Here's what I get ``` header is 151322730 body is 55555555 afbb0001 afbb0011 afbb0111 afbb1111 afbc0000 afbc0001 afbc0011 afbc0111 afbc1111 trailer is 55555555 ``` \*(p->b) is replaced with the trailer! And if I remove the line where I assigned the trailer, that is p->t=0x55555555;, then the trailer and p->b are the same (afbb0000). So my question is, how can I keep the structure define at the top the way it is and have this packet function properly. EDIT: I should be more clear. I writing this for a networking application, so I have to make a packet where the output is in this exact order, I am testing this by writing to a file and doing a hex dump. So my question really is: How do I make a packet with a header, variable sized body, and a trailer always have this order? The only two solutions I can think of are having many different structures, or having a vector. That is, I could structs where ``` typedef struct{ unsigned int h; unsigned int b[12]; unsigned int t; } pkt1; typedef struct{ unsigned int h; unsigned int b[102]; unsigned int t; } pkt2; etc ``` or I could do ``` std::vector<unsigned int> pkt (12); pkt[0] = header; pkt[1] = data; ... pkt[2]= data; pkt[11] = trailer; ``` I don't really like either of these solutions though. Is there a better way?? Also, this is somewhat of a separate question, I will have to do the same thing for receiving data. It is wise to do something like cast a block of data to a vector? I am going to be receiving the data as a void\* and I will know the max length.
A C++ solution: ``` #include <iostream> using namespace std; class Packet { public: Packet (int body_size) : m_body_size (body_size) { m_data = new int [m_body_size + 2]; } ~Packet () { delete [] m_data; m_data = 0; } int &Header () { return m_data [0]; } int &Trailer () { return m_data [m_body_size + 1]; } int Size () { return m_body_size; } int *Data () { return m_data; } int &operator [] (int index) { return m_data [index + 1]; } // helper to write class data to an output stream friend ostream &operator << (ostream &out, Packet &packet) { out << "Header = " << packet.Header () << endl; out << "Data [" << packet.Size () << "]:" << endl; for (int i = 0 ; i < packet.Size () ; ++i) { out << " [" << i << "] = 0x" << hex << packet [i] << endl; } out << "Trailer = " << packet.Trailer () << endl; return out; } private: int m_body_size, *m_data; }; // simple test function for Packet class int main () { Packet packet (10); packet.Header () = 0x0905006a; packet [0] = 0xafbb0000; packet [1] = 0xafbb0001; packet [2] = 0xafbb0011; packet [3] = 0xafbb0111; packet [4] = 0xafbb1111; packet [5] = 0xafbc0000; packet [6] = 0xafbc0001; packet [7] = 0xafbc0011; packet [8] = 0xafbc0111; packet [9] = 0xafbc1111; packet.Trailer () = 0x55555555; cout << packet; } ``` I've not put error checking in or const accessors, you can bounds check the array access. Receiving data is straightforward: ``` Packet Read (stream in) { get size of packet (exluding header/trailer) packet = new Packet (size) in.read (packet.Data, size + 2) return packet } ```
Try updating the struct and then adding the following: ``` typedef struct{ unsigned int h; unsigned int* b; unsigned int t; } pkt; ... ... pkt p; p->b = arr ``` Here is a visual example of what it is doing... ``` |----------------------| | header | |----------------------| | B int* | ------- p->b = arr |----------------------| | | trailer | | |----------------------| v |----------------------| arr | | | B items [0 ... N] | | | |----------------------| ``` If you want to get tricky you can do something like this ... ``` |----------------------| | header | |----------------------| | B int* | ------- (= to memory address after trailer) |----------------------| | | trailer | | |----------------------| | | | <------- | B items [0 ... N] | | | |----------------------| ``` Here is a working version of the later: ``` #include "stdlib.h" #include "stdio.h" #include "malloc.h" typedef struct{ unsigned int h; unsigned int* b; unsigned int t; } pkt; int main(){ pkt* p = (pkt*) malloc( sizeof(pkt) + sizeof(int)*10); p->h = 0x0905006a; p->b = &(p->t)+1; p->t = 0x55555555; p->b[0] = 0xafbb0000; p->b[1] = 0xafbb0001; p->b[2] = 0xafbb0011; p->b[3] = 0xafbb0111; p->b[4] = 0xafbb1111; p->b[5] = 0xafbc0000; p->b[6] = 0xafbc0001; p->b[7] = 0xafbc0011; p->b[8] = 0xafbc0111; p->b[9] = 0xafbc1111; int counter; printf( "header is \n" ); printf( "%0x\n", p->h); printf( "body is\n" ); for(counter=0; counter < 10;++counter) printf( "%0x\n", (p->b)[counter]); printf( "trailer is\n" ); printf( "%0x\n", p->t ); } ```
Variable sized structs with trailers
[ "", "c++", "data-structures", "" ]
I have a logging function that takes the calling object as a parameter. I then call getClass().getSimpleName() on it so that I can easily get the class name to add to my log entry for easy reference. The problem is that when I call my log function from a static method, I can't pass in "this". My log function looks something like this: ``` public static void log(Object o, String msg){ do_log(o.getClass().getSimpleName()+" "+msg); } public void do_something(){ log(this, "Some message"); } ``` But let's say I want to log from a static function: ``` public static void do_something_static(){ log(this, "Some message from static"); } ``` Obviously do\_something\_static() won't work because it is static and "this" is not in a static context. How can I get around this? And can I do it without using reflection (since I understand there is a lot of overhead involved and it might affect performance since I log a LOT of data) I know I can probably hard-code the current class into the call somehow, but I'm sure that when I move the function to another class, I will forget to update the hard-coded reference and it will no longer be correct. Thanks!
You could add "Class" as first parameter and overload the log method: ``` public class SomeClass { // Usage test: public static void main( String [] args ) { log( SomeClass.class, "Hola" ); log( new java.util.Date(), "Hola" ); } // Object version would call Class method... public static void log( Object o , String msg ) { log( o.getClass(), msg ); } public static void log( Class c , String message ) { System.out.println( c.getSimpleName() + " " + message ); } } ``` Output: ``` $ java SomeClass SomeClass Hola Date Hola ``` But it feels just bad to have the calling class passed as the first argument. Here's where object oriented model comes into play as opposite of "procedural" style. You could get the calling class using the stacktrace, but as you metioned, there would be an overhead if you call it thousands of times. **But** if you create is as class variable, then there would be only one instance for class if you happen to have 1,000 classes using this utility, you would have at most 1,000 calls. Something like this would be better ( subtle variation of this [other](https://stackoverflow.com/questions/1075935/using-current-class-in-java-static-method-declaration/1076166#1076166) answer) : ``` public class LogUtility { private final String loggingFrom; public static LogUtility getLogger() { StackTraceElement [] s = new RuntimeException().getStackTrace(); return new LogUtility( s[1].getClassName() ); } private LogUtility( String loggingClassName ) { this.loggingFrom = "("+loggingClassName+") "; } public void log( String message ) { System.out.println( loggingFrom + message ); } } ``` Usage test: ``` class UsageClass { private static final LogUtility logger = LogUtility.getLogger(); public static void main( String [] args ) { UsageClass usageClass = new UsageClass(); usageClass.methodOne(); usageClass.methodTwo(); usageClass.methodThree(); } private void methodOne() { logger.log("One"); } private void methodTwo() { logger.log("Two"); } private void methodThree() { logger.log("Three"); } } ``` OUtput ``` $ java UsageClass (UsageClass) One (UsageClass) Two (UsageClass) Three ``` Notice the declaration: ``` .... class UsageClass { // This is invoked only once. When the class is first loaded. private static final LogUtility logger = LogUtility.getLogger(); .... ``` That way, it doesn't matter if you use the "logger" from objectA, objectB, objectC or from a class method ( like main ) they all would have one instance of the logger.
querying the stacktrace maybe worty for your problem. You have 3 possible approachs. ## Exception#getStackTrace() Just create an exception instance and get the first frame: ``` static String className() { return new RuntimeException().getStackTrace()[0].getClassName(); } ``` ## Thread Using Thread is even easier: ``` static String className2() { return Thread.currentThread().getStackTrace()[1].getClassName(); } ``` these two approachs have the disadvantage that you cannot reuse them. So you may want to define an Helper class for that: ``` class Helper { public static String getClassName() { return Thread.currentThread().getStackTrace()[2].getClassName(); } } ``` now you can obtain your class name programmatically, without hardcoding the class name: ``` public static void log(Object o, String msg){ do_log(Helper.getCClassName() + " " + msg); } ```
Java: How to get a class object of the current class from a static context?
[ "", "java", "reflection", "logging", "" ]
My application use "FileSystemWatcher()" to raise an event when a TXT file is created by an "X" application and then read its content. the "X" application create a file (my application detect it successfully) but it take some time to fill the data on it, so the this txt file cannot be read at the creation time, so im looking for something to wait until the txt file come available to reading. not a static delay but something related to that file. any help ? thx
You can open and read a locked file like this ``` using (var stream = new FileStream(@"c:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var file = new StreamReader(stream)) { while (!file.EndOfStream) { var line = file.ReadLine(); Console.WriteLine(line); } } } ``` However, make sure your file writer flushes otherwise you may not see any changes.
Create the file like this: myfile.tmp Then when it's finished, rename it to myfile.txt and have your filewatcher watch for the .txt extension
wait for a TXT file to be readable c#
[ "", "c#", "" ]
Right, so I have an enumerable and wish to get distinct values from it. Using `System.Linq`, there's, of course, an extension method called `Distinct`. In the simple case, it can be used with no parameters, like: ``` var distinctValues = myStringList.Distinct(); ``` Well and good, but if I have an enumerable of objects for which I need to specify equality, the only available overload is: ``` var distinctValues = myCustomerList.Distinct(someEqualityComparer); ``` The equality comparer argument must be an instance of `IEqualityComparer<T>`. I can do this, of course, but it's somewhat verbose and, well, cludgy. What I would have expected is an overload that would take a lambda, say a `Func<T, T, bool>`: ``` var distinctValues = myCustomerList.Distinct((c1, c2) => c1.CustomerId == c2.CustomerId); ``` Anyone know if some such extension exists, or some equivalent workaround? Or am I missing something? Alternatively, is there a way of specifying an `IEqualityComparer` inline (embarrass me)? **Update** I found a reply by Anders Hejlsberg to a [post](https://social.msdn.microsoft.com/Forums/en-US/6834054e-e1c1-49db-970c-370a9012c675/distinct-method-suggestion?forum=linqprojectgeneral) in an MSDN forum on this subject. He says: > The problem you're going to run into is that when two objects compare > equal they must have the same GetHashCode return value (or else the > hash table used internally by Distinct will not function correctly). > We use IEqualityComparer because it packages compatible > implementations of Equals and GetHashCode into a single interface. I suppose that makes sense.
``` IEnumerable<Customer> filteredList = originalList .GroupBy(customer => customer.CustomerId) .Select(group => group.First()); ```
It looks to me like you want [`DistinctBy`](https://github.com/morelinq/MoreLINQ#distinctby) from [MoreLINQ](https://github.com/morelinq/MoreLINQ). You can then write: ``` var distinctValues = myCustomerList.DistinctBy(c => c.CustomerId); ``` Here's a cut-down version of `DistinctBy` (no nullity checking and no option to specify your own key comparer): ``` public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> knownKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (knownKeys.Add(keySelector(element))) { yield return element; } } } ```
Distinct() with lambda?
[ "", "c#", "c#-3.0", "lambda", "extension-methods", "" ]
Is this legal? ``` $string1= "INSERT INTO....;"; $string1 .= "INSERT INTO....;"; $string1 .= "INSERT INTO....;"; mysql_query($string1) or die(mysql_error()); ```
For what it's worth, and depending on if you're inserting the same data into the same tables, [it's much better to insert multiple values with the one insert](http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html) e.g. ``` INSERT INTO a VALUES (1,23),(2,34),(4,33); INSERT INTO a VALUES (8,26),(6,29); ```
No, [`mysql_query()`](http://php.net/mysql_query) only allows one query at a time. You can insert multiple rows like this: ``` INSERT INTO table (col1, col2) VALUES (1, 2), (3, 4), (5, 6) ```
Multiple mysql INSERT statements in one query php
[ "", "php", "mysql", "" ]
I wrote this code. ``` import socket host = 'localhost' port = 3794 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) while 1: print 'Type message you want to send...' msg = raw_input() if msg == '': s.close() break s.sendall(msg) ``` and next execute this code. ``` Traceback (most recent call last): File "socket.py", line 11, in ? s.bind((host, port)) File "<string>", line 1, in bind socket.error: (99, 'Cannot assign requested address') ``` What's wrong? Do you know solutions?
This means that you already have a socket bound to 3794 port. It may be another application or it means that port didn't got released yet after the previous run of your own script (it happens, if script terminated improperly). Simply try to use another port number - I believe everything will work fine.
I had this same problem and it was caused by trying to listen on the wrong host. When I changed it to an IP that was actually associated with the machine the code was running on (localhost), the problem went away.
Python socket error occured
[ "", "python", "sockets", "" ]
What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since > Some care must be taken if both > signals and threads are used in the > same program. The fundamental thing to > remember in using signals and threads > simultaneously is: always perform > signal() operations in the main thread > of execution. Any thread can perform > an alarm(), getsignal(), pause(), > setitimer() or getitimer(); **only the > main thread can set a new signal > handler, and the main thread will be > the only one to receive signals** > (this is enforced by the Python signal > module, even if the underlying thread > implementation supports sending > signals to individual threads). This > means that signals can’t be used as a > means of inter-thread > communication.Use locks instead. Update: each thread in my case blocks -- it is downloading a web page using urllib2 module and sometimes operation takes too many time on an extremely slow sites. That's why I want to terminate such slow threads
Since abruptly killing a thread that's in a blocking call is not feasible, a better approach, when possible, is to avoid using threads in favor of other multi-tasking mechanisms that don't suffer from such issues. For the OP's specific case (the threads' job is to download web pages, and some threads block forever due to misbehaving sites), the ideal solution is [twisted](http://twistedmatrix.com/trac/) -- as it generally is for networking tasks. In other cases, [multiprocessing](http://docs.python.org/library/multiprocessing.html) might be better. More generally, when threads give unsolvable issues, I recommend switching to other multitasking mechanisms rather than trying heroic measures in the attempt to make threads perform tasks for which, at least in CPython, they're unsuitable.
As Alex Martelli suggested, you could use the multiprocessing module. It is very similar to the Threading module so that should get you off to a start easily. Your code could be like this for example: ``` import multiprocessing def get_page(*args, **kwargs): # your web page downloading code goes here def start_get_page(timeout, *args, **kwargs): p = multiprocessing.Process(target=get_page, args=args, kwargs=kwargs) p.start() p.join(timeout) if p.is_alive(): # stop the downloading 'thread' p.terminate() # and then do any post-error processing here if __name__ == "__main__": start_get_page(timeout, *args, **kwargs) ``` Of course you need to somehow get the return values of your page downloading code. For that you could use multiprocessing.Pipe or multiprocessing.Queue (or other ways available with multiprocessing). There's more information, as well as samples you could check [here](http://docs.python.org/library/multiprocessing.html). Lastly, the multiprocessing module is included in python 2.6. It is also available for python 2.5 and 2.4 at pypi (you can use `easy_install multiprocessing`) or just visit pypi and download and install the packages manually. Note: I realize this has been posted awhile ago. I was having a similar problem to this and stumbled here and saw Alex Martelli's suggestion. Had it implemented for my problem and decided to share it. (I'd like to thank Alex for pointing me in the right direction.)
Terminate long running python threads
[ "", "python", "multithreading", "" ]
I have a simple Web Form with code like this: ``` //... //tons of text //... <a name="message" /> //... //tons of text //... <asp:Button ID="ButtonSend" runat="server" text="Send" onclick="ButtonSend_Click" /> ``` After POST I want to navigate user to my anchor "message". I have following code for this: ``` protected void ButtonSend_Click(object sender, EventArgs e) { this.ClientScript.RegisterStartupScript(this.GetType(), "navigate", "window.location.hash='#message';", true); } ``` This simple JavaScript is not working in Firefox 3.5.2 - url is changing in browser but page is not navigated to anchor. In IE 8 it works perfectly. Why this JavaScript code is not working in Firefox? Am I missing something?
I've solved my problem. JavaScript code was called before my anchor even existed. That's why Firefox wasn't scroll page down. My code looks now like tihs: ``` this.ClientScript.RegisterStartupScript(this.GetType(), "navigate", "window.onload = function() {window.location.hash='#message';}", true); ``` After page load I'm calling my simple JavaScript function. The key to found solution was Cleiton answer. Firebug reports that getElementById was returning null reference. Then I looked at generated HTML like andrewWinn suggested - JavaScript was called before anchor existed. Made little googling and found solution. Thanks for your answers!
Mendoza, you can use native **scrollIntoView** function. To do what you want, just write: ``` this.ClientScript.RegisterStartupScript(this.GetType(), "navigate", "document.getElementById('id_of_the_element').scrollIntoView();", true); ```
ASP.NET navigate to anchor in code behind
[ "", "asp.net", "javascript", "anchor", "" ]
I'm just trying reflection : ``` using System; using System.Collections.Generic; using System.Reflection; public class CTest { public string test; } public class MyClass { public static void Main() { CTest cTest = new CTest(); Type t=cTest.GetType(); PropertyInfo p = t.GetProperty("test"); cTest.test = "hello"; //instruction below makes crash string test = (string)p.GetValue(cTest,null); Console.WriteLine(cTest.GetType().FullName); Console.ReadLine(); } } ```
"`test`" is not a property, it's a field. You should use `Type.GetField` method to get a `FieldInfo`: ``` CTest CTest = new CTest(); Type t = CTest.GetType(); FieldInfo p = t.GetField("test"); CTest.test = "hello"; string test = (string)p.GetValue(CTest); Console.WriteLine(CTest.GetType().FullName); Console.ReadLine(); ```
Others have observed that the member is a field. IMO, though, the best fix is to **make** it a property. Unless you're doing some very specific things, touching fields (from outside the class) is usually a bad idea: ``` public class CTest { public string test { get; set; } } ```
Why my C# reflection code crashes?
[ "", "c#", "" ]
I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it? Here's the code being used if you want to know: ``` len(str(float(x)/3)) ```
Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses). For example: ``` >>> .1 0.10000000000000001 ``` In this case, you're seeing .1 converted to a string using `repr`: ``` >>> repr(.1) '0.10000000000000001' ``` I believe python chops off the last few digits when you use str() in order to work around this problem, but it's a partial workaround that doesn't substitute for understanding what's going on. ``` >>> str(.1) '0.1' ``` I'm not sure exactly what problems "rounding" is causing you. Perhaps you would do better with string formatting as a way to more precisely control your output? e.g. ``` >>> '%.5f' % .1 '0.10000' >>> '%.5f' % .12345678 '0.12346' ``` [Documentation here](http://docs.python.org/library/string.html#formatstrings).
``` len(repr(float(x)/3)) ``` However I must say that this isn't as reliable as you think. Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition: ``` >>> print len(repr(0.1)) 19 >>> print repr(0.1) 0.10000000000000001 ``` The explanation on why this happens is in [this chapter](http://docs.python.org/tutorial/floatingpoint.html) of the python tutorial. A solution would be to use a type that specifically tracks decimal numbers, like python's [`decimal.Decimal`](http://docs.python.org/library/decimal.html): ``` >>> print len(str(decimal.Decimal('0.1'))) 3 ```
Converting a float to a string without rounding it
[ "", "python", "string", "floating-point", "rounding", "" ]
``` using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(new B("MyName").Name); } } abstract class A { public A(string name) { this.GetType().GetField("Name").SetValue(this, name); } } class B : A { public B(string name) : base(name) { } public string Name { set; get; } } } ``` Is it possible to do something like that?
I can't stress how very, very, very bad this is. You are creating an inverse coupling that is convoluted, confusing and contrived, severely lacking in clarity, failing best practices and object oriented principals, which is going to create a maintenance and management nightmare for people implementing derivatives of your abstract class. Do the right thing!! ``` abstract class A { protected A(string name) { Name = name; } public abstract string Name { get; protected set; } } class B: A { public B(string name) : base(name) { } private string m_name; public override string Name { get { return "B Name: " + m_name; } protected set { m_name = value; } } } ```
It is possible, but i wouldn´t recommend to do that. The problem is that your base class knows to much about the class that are derived from it. When you derive a class from your abstract base class that does not define the property *Name* you get an Exception on runtime. If you expect that each class, that is derived from your base class, has a property *Name*, then it would be easier to define the Property *Name* in your abstract base class and set the property with you constructor.
Setting value to a field in the derived class
[ "", "c#", "inheritance", "" ]
I have a project with multiple forms and when, for example, Form A opens Form B which opens Form C, then Form C is closed, Form B and Form A have gone to the back of the window order, so that whatever other programs are open are shown in front of these other forms in the project. Why is this happening and how would I go about making sure the last opened form is shown when another form is closed?
Ensure that you are setting the `Owner` property of forms that are opened by other controls or Forms, either by setting the property explicitly or by passing the owner in as a parameter to `Show()` or `ShowDialog()`.
You could track the "last" form in each of your forms, and on close, activate it. ie: if Form B opens Form C, Form C could keep a reference to Form B (or any form to activate on close), and force it to the foreground when you close your form. That being said, I personally think that it's often better to just let the operating system perform its normal window manipulation/handling, unless there is a specific reason to override it. Applications that force their windows into the forefront often annoy me - instead of being beneficial, it can be disruptive to your users.
.net Window Order
[ "", "c#", ".net", "winforms", "" ]
We experience several minutes lags in our server. Probably they are triggered by "stop the world" garbage collections. But we use concurrent mark and sweep GC (-XX:+UseConcMarkSweepG) so, I think, these pauses are triggered by memory fragmentation of old generation. How can memory fragmentation of old generation be analyzed? Are there any tools for it? Lags happen every hour. Most time they are about 20 sec, but sometimes - several minutes.
Look at your Java documentation for the "java -X..." options for turning on GC logging. That will tell you whether you are collecting old or new generation, and how long the collections are taking. A pause of "several minutes" sounds extraordinary. Are you sure that you aren't just running with a heap size that is too small, or on a machine with not enough physical memory? * If your heap too close to full, the GC will be triggered again and again, resulting in your server spending most of its CPU time in the GC. This will show up in the GC logs. * If you use a large heap on a machine with not enough physical memory, a full GC is liable to cause your machine to "thrash", spending most of its time madly moving virtual memory pages to and from disc. You can observe this using system monitoring tools; e.g. by watching the console output from "vmstat 5" on a typical UNIX/Linux system. **FOLLOWUP** Contrary to the OP's belief, turning on GC logging is *unlikely* to make a noticeable difference to performance. The [Understanding Concurrent Mark Sweep Garbage Collector Logs](http://www.sun.com/bigadmin/content/submitted/cms_gc_logs.jsp) page on the Oracle site should be helpful in interpreting GC logs. Finally, the OP's conclusion that this is a "fragmentation" problem is unlikely, and (IMO) unsupported by the snippets of evidence that he has provided. It is most likely something else.
For low-level monitoring you will want to use this `-XX:PrintFLSStatistics=1` (or make it 2 for more at more blocking cost) . It's undocumented and occasionally gives you some stats. Unfortunately it's not very useful in most applications for different reasons, but it's at least ballpark-useful. You should be able to see for example ``` Max Chunk Size: 215599441 ``` and compare it to this ``` Total Free Space: 219955840 ``` and then judge the fragmentation based on the average block sizes and number of blocks.
How to analyze memory fragmentation in java?
[ "", "java", "memory-management", "" ]
Greetings, everyone! Examining my own code, I came up to this interesting line: ``` const CString &refStr = ( CheckCondition() ) ? _T("foo") : _T("bar"); ``` Now I am completely at a loss, and cannot understand why it is legal. As far as I understand, const reference must be initialized, either with r-value or l-value. Uninitialized references cannot exist. But ()? operator executes a CheckCondition() function before it assigns value to the reference. I can see now, that while CheckCondition() is executed, refStr exists, but still not initialized. What will happen if CheckCondition() will throw an exception, or pass control with a goto statement? Will it leave the reference uninitialized or am I missing something?
Simpler example: `const int x = foo();` This constant too has to be initialized, and for that `foo()` needs to be called. That happens in the order necessary: x comes into existance only when foo returns. To answer your additional questions: If `foo()` would `throw`, the exception will be caught by a `catch()` somewhere. The `try{}` block for that `catch()` surrounded `const int x = foo();` obviously. Hence `const int x` is out of scope already, and it is irrelevant that it never got a value. And if there's no `catch` for the exception, your program (including `const int x`) is gone. C++ doesn't have random `goto`'s. They can jump within `foo()` but that doesn't matter; `foo()` still has to return.
You are missing something - it is completely legal code, and in fact such code is one of the commonest and best uses of the conditional operator. It's always a mistake to think that the compiler must internally do things in the same order that the code is layed out on the page - it is perfectly at liberty to evaluate the conditional operator (which is justv another expression) and then use the result to perform the initialisation. As for a goto, there is no way of using one in an initialisation. And if an exception is thrown, the reference is deemed never to have been created in the first place.
Reference initialization in C++
[ "", "c++", "reference", "ternary-operator", "" ]
I'm planning on making a web app that will allow users to post entire web pages on my website. I'm thinking of using [HTML Purifier](http://htmlpurifier.org/) but I'm not sure because HTML Purifier edits the HTLM and it's important that the HTML is maintained just how it was posted. So I was thinking making some regex to get rid of all script tags and all the javascript attributes like onload, onclick, etc. I saw a Google video a while ago that had a solution for this. Their solution was to use another website to post javascript in so the original website cannot be accessed by it. But I don't wanna purchase a new domain just for this.
If you can find any other way of letting users post content, that does not involve HTML, do that. There are plenty of user-side light markup systems you can use to generate HTML. > So I was thinking making some regex to get rid of all script tags and all the javascript attributes like onload, onclick, etc. Forget it. You cannot process HTML with regex in any useful way. Let alone when security is involved and attackers might be deliberately throwing malformed markup at you. If you can convince your users to input XHTML, that's much easier to parse. You still can't do it with regex, but you can throw it into a simple XML parser, and walk over the resulting node tree to check that every element and attribute is known-safe, and delete any that aren't, then re-serialise. > HTML Purifier edits the HTLM and it's important that the HTML is maintained just how it was posted. Why? If it's so they can edit it in their original form, then the answer is simply to purify it on the way out to be displayed in the browser, *not* on the way in at submit-time. If you *must* let users input their own free-form HTML — and in general I'd advise against it — then HTML Purifier, with a whitelist approach (ban all elements/attributes that aren't known-safe) is about as good as it gets. It's very very complicated and you may have to keep it up to date when hacks are found, but it's streets ahead of anything you're going to hack up yourself with regexes. > But I don't wanna purchase a new domain just for this. You can use a subdomain, as long as any authentication tokens (in particular, cookies) can't cross between subdomains. (Which for cookies they can't by default as the domain parameter is set to only the current hostname.) Do you trust your users with scripting capability? If not don't let them have it, or you'll get attack scripts and iframes to Russian exploit/malware sites all over the place...
be careful with homebrew regexes for this kind of thing A regex like ``` s/(<.*?)onClick=['"].*?['"](.*?>)/$1 $3/ ``` looks like it might get rid of onclick events, but you can circumvent it with ``` <a onClick<a onClick="malicious()">="malicious()"> ``` running the regex on that will get you something like ``` <a onClick ="malicious()"> ``` You can fix it by repeatedly running the regex on that string until it doesn't match, but that's just one example of how easy it is to get around simple regex sanitizers.
What precautions should I take to prevent XSS on user submitted HTML?
[ "", "javascript", "xss", "" ]
Say I have an array like this: ``` $array = array('', '', 'other', '', 'other'); ``` How can I count the number with a given value (in the example blank)? And do it efficiently? (for about a dozen arrays with hundreds of elements each) This example times out (over 30 sec): ``` function without($array) { $counter = 0; for($i = 0, $e = count($array); $i < $e; $i++) { if(empty($array[$i])) { $counter += 1; } } return $counter; } ``` In this case the number of blank elements is 3.
How about using [array\_count \_values](http://www.php.net/manual/en/function.array-count-values.php) to get an array with everything counted for you?
Just an idea, you could use `array_keys( $myArray, "" )` using the optional second parameter which specifies a search-value. Then count the result. ``` $myArray = array( "","","other","","other" ); $length = count( array_keys( $myArray, "" )); ```
Count number of values in array with a given value
[ "", "php", "arrays", "count", "" ]
**How can you send an email by jQuery and PHP if the user flags a question?** **My JS code in HEAD** ``` jQuery('a.flag_question').live('click', function(){ jQuery.post('/codes/handlers/flag_question.php', { question_id: jQuery(this).attr('rel') }); alert ("Question was reported."); }); ``` **Its handler flag\_question.php which does not send me an email** ``` $question_id = $_POST['question_id']; // data from jQuery.post $subject = "Flagged question"; $to = '"Michael Boltman <michael.boltman777@gmail.com>'; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $message = "<a href='index.php?question_id=" . $question_id . "'>" . "The question " . $question_id . "</a> is flagged by an user. Please, review it."; if ( mail( $to, $subject, $message ) ) { echo ("Thank you for your report!"); } ``` I did use my real email address, while the one in the code is pseudo one. **The link is generated by PHP** ``` echo ("<a href='#'" . " class='flag_question'" . " rel='" . $question_id . "'>flag</a>" ); ```
You may not have a mail server! This happens usually when you're using a LocalHost on your computer.
**You can checkout the documentation for php's mail function [here](https://www.php.net/manual/en/function.mail.php).** **Item of note:** There are many people posting workarounds in the documentation comments because this function often seems to not work if your server/system isn't configured correctly. This users comment might be useful ([link](https://www.php.net/manual/en/function.mail.php#92639)) > **Edward 01-Aug-2009 09:08** > > Currently my hosting service is on Godaddy. When attempting to use the mail function without the fifth parameter containing "-f", my message headers would not work. > > Whenever your message headers do not work, simply try using the fifth parameter: ``` <?php mail($to, $subject, $message, $headers, "-femail.address@example.com"); ?> ```
Sending email by jQuery / PHP
[ "", "php", "jquery", "email", "" ]
I want to build a tool (with HTML5, JS and CSS3), which helps customers to arrange elements on a website mockup (e.g. text blocks and pictures). I want to save the position of these elements in order to reconstruct the whole mockup website later. Maybe a grid system would be the best? [alt text http://img.skitch.com/20090817-t4p54kbxw3rj58mkmqxspj4qch.png](http://img.skitch.com/20090817-t4p54kbxw3rj58mkmqxspj4qch.png) I would be happy to get some ideas on approaches for this challenge. Are there any similar projects, I should take a look at? Regards, Stefan
The [jQuery](http://www.jquery.com) framework would help you in synchronizing the JS and DHTML events. As far as other projects that use this, I'm not aware of any, but a grid model seems like a good way to go. Just make sure it's more precise than the 125px you currently have :) EDIT: The website that was mentioned in the DHTML book I mentioned in my comment was <http://www.panic.com> . You can take a look at their JavaScript code for some inspiration, as they implement a drag and drop system for downloading their products.
YUI has lots of widgets for this sorta thing with lots of examples. [Drag & Drop: Examples](https://web.archive.org/web/20110521232325/http://developer.yahoo.com/yui/examples/dragdrop/index.html) Especially this example [Drag & Drop: Using Interaction Groups](https://web.archive.org/web/20160728103129/https://developer.yahoo.com/yui/examples/dragdrop/dd-groups.html) All you would have to do register a listener on the drop event to send an ajax request to the server and save the xy co-ordinates. ALSO, if you want to do resizing as well [Resize Utility: Examples](https://web.archive.org/web/20110522014136/http://developer.yahoo.com/yui/examples/resize/index.html) They have a few really neat examples, including this image cropper [ImageCropper Control: Real Time Crop Feedback](https://web.archive.org/web/20160728103433/https://developer.yahoo.com/yui/examples/imagecropper/feedback_crop.html)
Arranging elements on the screen and saving their positions
[ "", "javascript", "html", "css", "gridview", "prototypejs", "" ]
In the boost tutorials online for program options : <http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/tutorial.html#id2891824> It says that the complete code examples can be found at "BOOST\_ROOT/libs/program\_options/example" directory. I could not figure out where is this. Can anyone help me finding the examples?
On Debian systems, you find it in `/usr/share/doc/libboost-doc/examples/libs/program_options`. Otherwise, I suggest to download the archive from boost.org and have a look there.
The examples are online at <https://www.boost.org/doc/libs/1_83_0/libs/program_options/example/> For a different version of boost, change the number in the link.
Boost Program Options Examples
[ "", "c++", "boost", "boost-program-options", "" ]
I am using this property file to setup log4j in Spring: ``` log4j.appender.EMAIL=org.apache.log4j.net.SMTPAppender log4j.appender.EMAIL.filter=org.apache.log4j.varia.LevelRangeFilter log4j.appender.EMAIL.filter.levelMin=FATAL ``` but getting: ``` log4j:WARN Failed to set property [filter] to value "org.apache.log4j.varia.LevelRangeFilter". ``` Any ideas?
From the docs for [PropertyConfigurator](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PropertyConfigurator.html): > The PropertyConfigurator does not > handle the advanced configuration > features supported by the > DOMConfigurator such as support for > Filters, custom ErrorHandlers, nested > appenders such as the AsyncAppender, > etc. I suggest you use an XML file to set it up instead.
You don't need a filter for this. log4j.appender.EMAIL.Threshold=FATAL
Can't set LevelRangeFilter for log4j
[ "", "java", "spring", "log4j", "" ]
How can I implement background processing queues in my ASP.NET MVC web app? While most data changes, updates etc. need to be visible immediately, there are other updates that don't need real time processing which I would like to hand off to a lower-priority background process which will take care of it at its own pace. As an example, take StackOverflow's badge award system. Usually you may take a specific action that would award you a badge, but the actual 'award' happens later (typically between 10 minutes and a couple hours later). I assume this is done via a separate background process as it is not critical for SO's workings to award badges immediately when earned. So, I'm trying to create some kind of queue system in which I could stuff tasks (say anything implementing ITask interface which will have a Process() method) which will eventually get executed by a separate process. How would I go about implementing such a system? Ideas/Hint/Sample Code? Thank you!
Windows Services and MSMQ to communicate with them (if you even need to). -- Edit To slightly expand. You'll create several services, depending on what you want to do, and have them all run an endless thread of various sleeping levels, to do what you want. They will then update the database appropriately, and you will not have had to do anything on the client side. You may wish to interact with them from an admin point of view, hence you may have an MSMQ that they listen to admin commands on. Depending on your implementation, you may need to restart them for some reason, or possibly just 'force' a running of whatever they wish to do. So you'll use an MSMQ Private Queue to do it (System.Messaging namespace). One of the main things to note about MSMQ, is that message need to be < 4meg. So if you intend to send large object graphs, serialise to a file first and just send the filename. MSMQ is quite beautiful. You can send based on a 'Correlation ID' if you need to, but, for some amusing reason, the correlation ID must be in the form of: ``` {guid}\1 ``` Anything else does not work (at least in version 2.0 of the framework, the code may have changed). -- Edit Example, as requested: ``` using System.Messaging; ... MessageQueue queue = new MessageQueue(".\\Private$\\yourqueue"); queue.Formatter = new BinaryMessageFormatter(); Message m = new Message(); m.Body = "your serialisable object or just plain string"; queue.Send(m); // on the other side MessageQueue queue = new MessageQueue(".\\Private$\\yourqueue"); queue.Formatter = new BinaryMessageFormatter(); Message m = queue.Receive(); string s = m.Body as string; // s contains that string now ```
Jeff has a great post showing how he achieved this originally for Stack Overflow at <https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/> While it might not be as reliable as a service if that's an option to you, it's served me well in the past for non essential tasks, and I've had it working in a virtual hosting environment.
Queue-Based Background Processing in ASP.NET MVC Web Application
[ "", "c#", "asp.net-mvc", "" ]
I'm running the following query, expecting it to return an INTEGER, but it returns "Resource id #3" What am I doing wrong? ``` $queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms"); echo $queryPlans; ``` There are actually 15 rows in this table, and I would like to return the number 15. Any suggestions?
You need: ``` $queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms"); $row = mysql_fetch_array($queryPlans); echo $row[0]; ``` [`mysql_query()`](https://www.php.net/manual/en/function.mysql-query.php) isn't returning the result. It's returning a resource you can loop across and interrogate for rows (as above).
mysql\_query will return a php resource(see: <http://www.php.net/manual/en/language.types.resource.php>). The returned resource should then be passed to mysql\_fetch\_assoc or similar. Since you are only getting the count, you can use the following: ``` $queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms"); $count = mysql_result($queryPlans,0,0); echo $count; ```
MySQL PHP count(*) returning something weird
[ "", "php", "mysql", "" ]
I know... you must be calling me nuts by now, for using text files as databases. If thats ok to you, certainly using java 1.3 will be enough to call me insane. Let me explain (yes there's an excuse for that): I work for a company that for a thousand reasons can't (or won't) upgrade to java 5 or 6 and so on... It doesn't allow us to create/modify databases on it's DB2 systems as well. I know... It looks like they don't wanna let us do our jobs... Well, enough said. The point is that we are using text files to feed our 300 reports. 300 and growing... And our servers are on the verge of breaking down... I tried using SQLite, but could not find any connector/wrapper that would work with java 1.3... And now I'm out of ideas... If anyone has been through that road (and survived to tell), and could give me any piece of advise...actually, any idea, from anyone.... **Edit:** I forgot to mention that I can't install any database server. That's why I considered SQLite, 'cos it is a "serveless" database.
Java 1.3, ye gods, do you use punch cards as well? :) On a serious note, [HSQLDB](http://hsqldb.org/web/hsqlFeatures.html) claims to support every JDK, even the prehistoric 1.1 one. Maybe that will be of use to you.
There are a number of open-source embedded databases for Java that may fit your requirements: <http://java-source.net/open-source/database-engines> The big question is which (if any) of them still support Java 1.3. I suggest having a rummage around in their docs to see what you can find.
What is a good alternative to text files as Database for java 1.3?
[ "", "java", "database", "" ]
How does Silverlight stack up against Flash 10? 1. which is lighter? (CPU consumption, loading times, performance) 2. which has richer capabilities (APIs, libraries) 3. faster for developing? 4. what about media handling (audio/video streaming) ? 5. do I need special server/client software to use them?
1. which is lighter ? ( CPU consumption , loading times , speed of executing things etc .. ) * They are comparable. [Bubblemark](http://bubblemark.com/) has a comparison that tries to benchmark them but I would take it with a grain of salt. Fact is, you can get decent performance with either. If you start staring too hard at micro-benchmarks you're gonna lose the point of using such high-level frameworks. 2. which has richer capabilities ( API-s , libraries etc.. ) * This will depend on what it is you are trying to do. Silverlight has the .Net libs (not sure of the exact subset) which is probably nice. But ActionScript and Flash have been around for ages and have a huge community complete with almost any library you want. I think you would be hard pressed to find something one can do that the other cannot. I like ActionScript alright but I think I'd prefer C# as a development language. 3. faster for developing ? * Hate to keep saying "it depends" but that is the truth. If you know .Net and C# already you may be familiar with the Microsoft toolkit. Flash 10 can be programmed using Flash CS4 or Flex Builder (which is an IDE) so it depends if you are coming from an engineering or graphical design perspective on which you would use. I think MS would win the development tools battle but Adobe would win the integration with graphics tools battle. I don't mind Flex Builder and it hasn't let me down, but when I was developing using VS (C++) I was really pleased with the experience. 4. what about media handling ( audio/video streaming ) ? * youtube is Flash. Same with almost any other mainstream Audio/Video streaming site on the web (with few exceptions). That said, some of the new Silverlight demos show incredible video capability and control. 5. do i need special server/client software to use them ? * To deliver content through the browser, both require a plug-in. Flash is by far more ubiquitous at the moment. If you are going for sheer number of current installs then Flash is the best choice. Adobe also has Air which allows you to publish Flash content as a cross-platform desktop application. This does require the user has the Air runtime installed on their computer, but it would allow you to then create apps that run on Windows, OS X and Linux. One thing I touched on which is really important is community size. The Flash community is much older and much larger. This is important because it is easier to find people who have done things similar to what you are trying to do. The number of tutorials, example code, blogs, forums, open-source 3rd party libraries, etc. makes it easy to learn ActionScript. For me the decision comes down to a few questions for yourself: 1. Do you already know C#/.Net and Microsoft development tool-chains? 2. How important is the size of the current installed user base to your decision? 3. Are you interested in developing cross-platform desktop style applications as well as browser plug-in content? 4. Would you rather be a pioneer in a young platform or take the benefits of experience available in an older platform?
3.By most accounts I've heard, C#/XAML is a more developer-friendly environment than actionscript. It had better be - it was built years later. 4.Silverlight has [adaptive bitrate video](http://msdn.microsoft.com/en-us/library/dd159743.aspx). I believe for Flash you need the Autobahn Flash extension to get that. That's just one feature though, other people undoubtedly know of others where one wins over the other.
Silverlight 3 (C#) vs. Flash 10 (AS3)
[ "", "c#", "silverlight", "flash", "actionscript-3", "" ]
In C#, I have a string that I'm obtaining from WebClient.DownloadString. I've tried setting client.Encoding to new UTF8Encoding(false), but that's made no difference - I still end up with a byte order mark for UTF-8 at the beginning of the result string. I need to remove this (to parse the resulting XML with LINQ), and want to do so in memory. So I have a string that starts with \x00EF\x00BB\x00BF, and I want to remove that if it exists. Right now I'm using ``` if (xml.StartsWith(ByteOrderMarkUtf8)) { xml = xml.Remove(0, ByteOrderMarkUtf8.Length); } ``` but that just feels wrong. I've tried all sorts of code with streams, GetBytes, and encodings, and nothing works. Can anyone provide the "right" algorithm to strip a BOM from a string?
If the variable *xml* is of type string, you did something wrong already - in a character string, the BOM should not be represented as three separate characters, but as a single code point. Instead of using DownloadString, use DownloadData, and parse byte arrays instead. The XML parser should recognize the BOM itself, and skip it (except for auto-detecting the document encoding as UTF-8).
I recently had issues with the .NET 4 upgrade, but until then the simple answer is `String.Trim()` removes the BOM up until .NET 3.5. However, in .NET 4 you need to change it slightly: ``` String.Trim(new char[]{'\uFEFF'}); ``` That will also get rid of the byte order mark, though you may also want to remove the [ZERO WIDTH SPACE](https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8192&number=128) (U+200B): ``` String.Trim(new char[]{'\uFEFF','\u200B'}); ``` This you could also use to remove other unwanted characters. Some further information is from *[String.Trim Method](https://learn.microsoft.com/en-us/dotnet/api/system.string.trim)*: > The .NET Framework 3.5 SP1 and earlier versions maintain an internal list of white-space characters that this method trims. Starting with the .NET Framework 4, the method trims all Unicode white-space characters (that is, characters that produce a true return value when they are passed to the Char.IsWhiteSpace method). Because of this change, the Trim method in the .NET Framework 3.5 SP1 and earlier versions removes two characters, ZERO WIDTH SPACE (U+200B) and ZERO WIDTH NO-BREAK SPACE (U+FEFF), that the Trim method in the .NET Framework 4 and later versions does not remove. In addition, the Trim method in the .NET Framework 3.5 SP1 and earlier versions does not trim three Unicode white-space characters: MONGOLIAN VOWEL SEPARATOR (U+180E), NARROW NO-BREAK SPACE (U+202F), and MEDIUM MATHEMATICAL SPACE (U+205F).
Strip the byte order mark from string in C#
[ "", "c#", "string", "encoding", "" ]
I am having some trouble to achieve this little [round robin](http://en.wikipedia.org/wiki/Round-robin_tournament) project. What i try to do is to generate a preview calendar of games then I want to output; day 1: Team 1 vs Team 2; Team 3 vs Team 4; Team 5vs Team 6; day 2 Team 1 vs Team 4; Team 6 vs Team 3; Team 2 vs Team 5; till the end of the championship; Here is the code i've got so far but i'm having trouble to let the first team fixed while the rest of the array rotates...: ``` static void Main(string[] args) { string[] ListTeam = new string[] {"Equipe1", "Equipe2", "Equipe3", "Equipe4", "Equipe5", "Equipe6"}; IList<Match> ListMatch = new List<Match>(); it NumberOfDays = (ListTeam.Count()-1); int y = 2; for (int i = 1; i <= NumberOfDays; i++) { Console.WriteLine("\nDay {0} : \n",i); Console.WriteLine(ListTeam[0].ToString() + " VS " + ListTeam[i].ToString()); for (y =ListTeam.Count(); y>0 ; y--) { Console.WriteLine(ListTeam[y].ToString() + " VS " + ListTeam[y+1].ToString()); y++; } } } ``` EDIT: I found a [code sample in java but](http://www.developpez.net/forums/d267356-2/c-cpp/cpp/generation-calendrier-football/#post1700042) i cant translate it...
This should be easy enough to do using modular arithmetic: **UPDATE 2:** (As promised correct algorithm) ``` public void ListMatches(List<string> ListTeam) { if (ListTeam.Count % 2 != 0) { ListTeam.Add("Bye"); } int numDays = (numTeams - 1); int halfSize = numTeams / 2; List<string> teams = new List<string>(); teams.AddRange(ListTeam.Skip(halfSize).Take(halfSize)); teams.AddRange(ListTeam.Skip(1).Take(halfSize -1).ToArray().Reverse()); int teamsSize = teams.Count; for (int day = 0; day < numDays; day++) { Console.WriteLine("Day {0}", (day + 1)); int teamIdx = day % teamsSize; Console.WriteLine("{0} vs {1}", teams[teamIdx], ListTeam[0]); for (int idx = 1; idx < halfSize; idx++) { int firstTeam = (day + idx) % teamsSize; int secondTeam = (day + teamsSize - idx) % teamsSize; Console.WriteLine("{0} vs {1}", teams[firstTeam], teams[secondTeam]); } } } ``` which would print each day's team matches. Let me quickly try to explain how the algorithm works: I noticed that since we are rotating all the teams except the first one, if we put all the teams in an array except the first one, then we should just read off the first team from that array using index offset based on the day and doing modular arithmetic to wrap around correctly. In practice we would be treating that array as infinitely repeating in both directions and we would be sliding our view incrementally to right (or to the left). There is one snag, however, and that is the fact that we have to order the teams in a very particular way for this to work correctly. Otherwise, we do not get the correct rotation. Because of this we need to read of the matching second team in a very peculiar way as well. The correct way to prepare your list is as follows: * Never put the first team (Team#1) in the list. * Take the last half of the team list and put them in the front of the list. * Take the first half of the list, reverse it and put them in the list (but not Team#1). Now, the correct way to read off the list is as follow: * For each day, increment the first index you are looking at by `1`. * For the first team that you see at that location, match that team with Team#1. * For the next team in the list (`(day + idx) % numDays`), we would normally match it with the team that is offset by half the number of teams minus 1 (minus 1 because we dealt with the first match ourselves). However, since the second half of our list was prepared by reverting, we need to match that offset in the reverted second half of the list. A simpler way to do is to observe that in this is equivalent to matching the same index but from the end of the list. Given the current `day` offset that is `(day + (numDays - idx)) % numDays`. **UPDATE 3:** I was not happy that my solution involved such convoluted selection, matching, reversing of array elements. After I got thinking about what my solution involved I realized that I was too hung up about keep the order of the teams as given. However, that is not a requirement and one can get a different but equally valid schedule by not caring about the initial ordering. All that matters is the selection algorithm I describe in the second part of my explanation. Thus you can simplify the following lines: ``` teams.AddRange(ListTeam.Skip(halfSize).Take(halfSize)); teams.AddRange(ListTeam.Skip(1).Take(halfSize -1).ToArray().Reverse()); ``` to: ``` teams.AddRange(ListTeam); // Copy all the elements. teams.RemoveAt(0); // To exclude the first team. ```
It sounds like you want to schedule a [round-robin tournament](http://en.wikipedia.org/wiki/Round-robin_tournament). The wp article contains the algorithm. I don't see where you are even trying to rotate the array. The permutation will look something like: 1 -> 2 -> 3 -> 4 ... -> n/2 - 1 -> n - 1 -> n - 2 -> n - 3 -> ... -> n/2 -> 1 (and 0 stays fixed). You can do that in 2 loops (top row and bottom row).
Round Robin Tournament algorithm in C#
[ "", "c#", "algorithm", "round-robin", "" ]
the Requirement in simple words goes like this. * Its a charting Application ( kinda Dashboard) with multiple views (Charts , PDF and Excel) * DataSources could be primarily from Oracle but there are other data sources like Excel,flat Files....etc. * Charting library would be Component art (I would like to try the new asp.net charting but as its already being used in other apps they would like to continue) As I told you, We have a already have an application which is like basic 3 layered with some DTOs and mostly DataTables;where I feel any data model is tightly coupled with Views, they would like to continue with the same :) I would like to propose a new architecture for this and I need your honest comments. I think 1. It should be designed using traditional MVC pattern, as there is one model and different Views(chart,excel,pdf) 2. A Solid Service layer(Enterprise Lib) with 1) Security(Provider model) 2)Data source Abstraction (flat files , oracle , excel) 3) Caching ( each report would have its own refresh time and the data/view can be cached accordingly 4)Error logging 5)Health monitoring 3) using WCF services to expose the views or DTOs 4) Complete AJAX and partial rendering 5) develop a solid wcfservice which would take the datamodel name and view(chart,excel,pdf then returns the view accordingly. Please guide me, I want to build a loosely coupled and configurable architecture which can be reused.
Honest answer: It sounds like you are either **over-engineering** this, or you are **irresponsibly re-inventing** the wheel. > I want to build a loosely coupled and > configurable architecture which can be > reused. That's a lovely goal, but is it a requirement of this project? I'm guessing it's not a fundamental requirement, at most a *nice-to-have.* It seems that the business needs a dashboard with some exportable charts and reports, and you're proposing to build a platform. That's classic over-engineering. If you really need a reusable platform, it will take considerable effort and skills to build an intuitive, robust, secure, testable, configurable, maintainable reporting platform with sophisticated and trainable authoring tools. And even if you build a perfect platform, *you'll have a custom system that nobody else knows*. If you use an established BI/reporting platform, you can hire people who already know the technology or point people at reams of already existent training materials. In other words, it's going to be difficult and more expensive to build, which is bad, but also difficult and more expensive for the organization to use for years to come, which is worse. I routinely choose build over buy, but reporting is a known problem that has been solved well enough by commercial platforms. So, sure, that architecture sounds reasonable. And without knowing more about the requirements, it's impossible to judge: maybe you really do need to build this from scratch, but from your description "charting Application ( kinda Dashboard)", building a reporting platform sounds unnecessary, though perhaps quite fun.
I recommend the following book: [Microsoft® .NET: Architecting Applications for the Enterprise](http://www.amazon.co.uk/Microsoft-NET-Architecting-Applications-PRO-Developer/dp/073562609X/ref=sr_1_1?ie=UTF8&s=books&qid=1251234106&sr=8-1) by Dino Esposito; Andrea Saltarello. They are discussing architecture in a pragmatic way (Yes there are code examples). Many of the things you have mentioned will be described in the book. You will probably not get all the answers but it will inspire you. (They have made a book about Ajax/ASP.NET arch too but I have not read that one) You want to use a lot of new cool technology, that’s cool. But most important is why do you want to use it, what business value will it add? Ask yourself what do you want to with your product in the future? To be able to figure out today and tomorrows requirement will be the best thing to help you build “loosely coupled and configurable architecture” it will help you more then any of the techs you have choosen.
Best Architecture for Reporting Application in ASP.net ( with dynamic Sources)
[ "", "c#", "asp.net-mvc", "wcf", "reporting", "" ]
I use java.text.NumberFormat simply to convert numbers into more readable Strings, with commas separating thousands, etc. Basically I define it as: ``` public static NumberFormat nf = NumberFormat.getInstance(Locale.US); ``` ...and then I just call nf.format(some\_number) in any thread where I want to make a readable version of a number. But looking at the JavaDoc, it says: "Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally." If I am only using the format(number) method of the NumberFormat object, could there ever be a synchronization issue? I tried using NumberFormat.getInstance(Locale.US).format(number) instead, but there is overhead associated with doing that every time that I feel is probably not really needed. Does this really need external synchronization? Or is there a simpler, efficient way of accomplishing the same thing without NumberFormat? Thanks!
Even if format is the only method you ever call, it's still not thread-safe. In fact, we've had bugs at work due to this. We usually either create NumberFormat objects on the fly, or use a ThreadLocal as Gerco suggested. If you wanted to get fancy, you could subclass NumberFormat and in the format method, either synchronize before calling format on a delegate NumberFormat or use a ThreadLocal to retrieve a delegate. However, I believe the most straightforward way, especially if you're going to format/parse several numbers in a row, is to use a ThreadLocal manually.
Use a ThreadLocal<NumberFormat>. That way each thread will have it's own private NumberFormat instance and there will be no need to synchronise and only minimal overhead.
Java: Synchronization issue with NumberFormat?
[ "", "java", "" ]
[This question is close to what I want to do](https://stackoverflow.com/questions/791390/more-elegant-exception-handling-than-multiple-catch-blocks), but not quite there. Is there a way to simplify the following code? ``` private bool ValidDirectory(string directory) { if (!Directory.Exists(directory)) { if (MessageBox.Show(directory + " does not exist. Do you wish to create it?", this.Text) == DialogResult.OK) { try { Directory.CreateDirectory(directory); return true; } catch (IOException ex) { lblBpsError.Text = ex.Message; } catch (UnauthorizedAccessException ex) { lblBpsError.Text = ex.Message; } catch (PathTooLongException ex) { lblBpsError.Text = ex.Message; } catch (DirectoryNotFoundException ex) { lblBpsError.Text = ex.Message; } catch (NotSupportedException ex) { lblBpsError.Text = ex.Message; } } } return false; } ``` It seems a waste, and if I later want to change how I report an error back to the user, or perhaps I want to log these errors, or whatever, then I've got to change 5 different catch blocks. Am I missing something, or is this blatantly against code-reuse? Am I just trying to be (too) lazy?
You can use : ``` catch (SystemException ex) { if( (ex is IOException) || (ex is UnauthorizedAccessException ) // These are redundant // || (ex is PathTooLongException ) // || (ex is DirectoryNotFoundException ) || (ex is NotSupportedException ) ) lblBpsError.Text = ex.Message; else throw; } ```
If the exceptions share a common super-class then you can just catch the superclass.
Can you catch more than one type of exception with each block?
[ "", "c#", "try-catch", "" ]
I'm making a sampler program where each key from 1 to 9 will make a different sound. Everything works fine, but when I press two (or more) sounds at the same time, the second one "kills" the first one. I'm playing the sounds from .WAV files, using `SoundPlayer`. How can I solve this?
You'll need to use DirectX (DirectSound) or some similar API that is designed to allow the playing of multiple sounds at the same time.
There is one simple way to play multiple sounds at once in C# or VB.Net. You will have to call the `mciSendString()` API Function to play each .wav file. You won't even have to do multi-threading, unless you are loop-playing. [Here](http://pastebin.com/TtrCdeER) is a complete working example of a `MusicPlayer` class created using `mciSendString()`. ``` // Sound api functions [DllImport("winmm.dll")] static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback); ``` In the above function, the key is first parameter command. As long as you call two functions with a separate command name, they will play separately/simultaneously. This is what I did in one of my C# programs: ``` private void PlayWorker() { StringBuilder sb = new StringBuilder(); mciSendString("open \"" + FileName + "\" alias " + this.TrackName, sb, 0, IntPtr.Zero); mciSendString("play " + this.TrackName, sb, 0, IntPtr.Zero); IsBeingPlayed = true; } ``` EDIT: Added link to a working example.
Play multiple sounds using SoundPlayer
[ "", "c#", ".net", "audio", "wav", "" ]
I'm trying to make my program faster, so I'm profiling it. Right now the top reason is: ``` 566 1.780 0.003 1.780 0.003 (built-in method decode) ``` What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don't believe they are unicode-encoded.
Most likely, this is the [decode method of string objects](http://docs.python.org/library/stdtypes.html#str.decode).
Presumably this is str.decode ... search your source for "decode". If it's not in your code, look at Python library routines that show up in the profile results. It's highly unlikely to be to be anything to do with cPickle. Care to show us a few more "reasons", preferably with the column headings, to give us a wider view of your problem? Can you explain the connection between "using cPickle" and "some test cases would run faster"? You left the X and Y out of "Is there anything that will do task X faster than resource Y?" ... **Update** so you were asking about cPickle. What are you using for the (optional) protocol arg of cPickle.dump() and/or cPickle.dumps() ?
What does "built-in method decode" mean in Python when profiling?
[ "", "python", "string", "optimization", "performance", "pickle", "" ]
I vaguely remember there is a .NET type name with the suffix "2". I can't remember exactly which one it is though. Can anyone point it out to me? Thanks
There are a couple: [ITypeLib2](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.comtypes.itypelib2.aspx), [ITypeInfo2](http://msdn.microsoft.com/en-us/library/ms221565.aspx), [RC2](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rc2.aspx), [IDesignerLoaderHost2](http://msdn.microsoft.com/en-us/library/system.componentmodel.design.serialization.idesignerloaderhost2.aspx), and [X509Certificate2](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx).
There are a lot of them...For example some of the code extensibility uses this. We're going to need some more information for the specific type you want because there are far more than one of these types of objects. [CodeModel](http://msdn.microsoft.com/en-us/library/envdte.codemodel(VS.80).aspx) to [CodeModel2](http://msdn.microsoft.com/en-us/library/envdte80.codemodel2(VS.80).aspx)
.NET type with a "2" suffix?
[ "", "c#", ".net", "types", "" ]
Ok I don't want this to be a hacking advice question, so please don't down-vote for that. I work in a web shop and I've found some of our old PHP pages are vulnerable to SQL injection in the username and want to know how bad. We use a PHP string to embed the user input from the POST on the login form. ``` $uname = $_POST['username']; $pass = md5($_POST['pass']); $sql = "SELECT * FROM users WHERE username='$uname' AND password='$pass' AND userlevel='user'"; ... ``` then I run the query. Now, I'm no SQL expert, I just use what I can piece together on phpMyAdmin. But I was able to log in without a username by instead using: ``` ' OR 1 ' ``` I know to escape the user input, I use `mysql_real_escape_string`. My question is, how vulnerable is this code, and could someone log into this page and not need the password? I would think maybe they wouldn't need the username, but could only brute force the password. But I'm no SQL guru and am wondering if some tricks could be used against us. We use MySQL. And please I don't need any lectures on input validation, I know how bad this is. We should be doing lots of things, like timeouts and lockouts on our page so it can't be brute-forced.
"Could someone log into this page and not need the password": Yes, trivially. Try the username `yourfavoriteadmin' OR 1; --`. [May as well link this, since certainly somebody will...](http://xkcd.com/327/)
It’s very vulnerable. If you know about all the nifty stuff like `mysql_real_escape_string` why do you waste your time and ask this question? You should be all over that code, fixing it. You know, like, **NOW**.
How vulnerable is my code to SQL injection?
[ "", "php", "mysql", "security", "" ]
I would like to understand the difference between the `Boolean` and `boolean` types in Java, specifically as they relate to GWT. I know that methods are not supported but I want more info if it is available.
I'm not sure if the GWT factor makes a difference but in general: **boolean** is a java primitive type whereas **Boolean** is an object/reference type that wraps a boolean Converting between primitives and objects like this is known as boxing/unboxing. Here is more info: <http://javaeye.wordpress.com/2008/06/17/boxing-and-unboxing-conversion/> Why box you ask? <http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html> <http://www.javapractices.com/topic/TopicAction.do?Id=197>
It's fairly Simple and the same for GWT and Java: * boolean can be yes or no * Boolean can be yes, no or NULL. So unless you need the NULL (like for example your loading the field from the database, and you want NULL to be different to false) then stick to boolean.
What's the difference between boolean and Boolean in Java?
[ "", "java", "gwt", "boolean", "" ]
I have the convenient object factory template that creates objects by their type id names. The implementation is pretty obvious: `ObjectFactory` contains the map from `std::string` to object creator function. Then all objects to be created shall be registered in this factory. I use the following macro to do that: ``` #define REGISTER_CLASS(className, interfaceName) \ class className; \ static RegisterClass<className, interfaceName> regInFactory##className; \ class className : public interfaceName ``` where `RegisterClass` is ``` template<class T, class I> struct RegisterClass { RegisterClass() { ObjectFactory<I>::GetInstance().Register<T>(); } }; ``` Usage ``` class IFoo { public: virtual Do() = 0; virtual ~IFoo() {} } REGISTER_CLASS(Foo, IFoo) { virtual Do() { /* do something */ } } REGISTER_CLASS(Bar, IFoo) { virtual Do() { /* do something else */ } } ``` Classes are defined and registered in factory simultaneously. The problem is that `regInFactory...` static objects are defined in .h files, so they will be added to every translation unit. The same object creator will be registered several times, and, more important, there will be a lot of redundant objects with static storage duration. Is there any way to do such elegant registration (not to copy/paste class and interface names), but do not spread redundant static objects around the globe? If a good solution needs some VC++ specific extensions (not conforming to C++ standard), I will be OK with that.
So you want to put variables definitions in header file? There is a portable way: static variables of template classes. So we get: ``` template <typename T, typename I> struct AutoRegister: public I { // a constructor which use ourRegisterer so that it is instantiated; // problem catched by bocco AutoRegister() { &ourRegisterer; } private: static RegisterClass<T, I> ourRegisterer; }; template <typename T, typename I> RegisterClass<T, I> AutoRegister<T, I>::ourRegisterer; class Foo: AutoRegister<Foo, IFoo> { public: virtual void Do(); }; ``` Note that I've kept the inheritance of IFoo non virtual. If there is any risk of inheriting from that class multiple times, it should be virtual.
Cygon's answer is probably what you need, but you also might get away with lazy registration, depending what exacly is registration for. Move registration into special base class and attach that besides interface in the macro. Inside constructor use a local static flag, so that each class registers only once on first instanse creation. Probably won't compile, but you should get what I meant: ``` template<className, interfaceName> class RegistratorBase { public: RegistratorBase() { static bool registered = false; if(!registered) ObjectFactory<interfaceName>::GetInstance().Register<className>(); } }; #define REGISTER_CLASS(className, interfaceName) \ class className : public interfaceName, private RegistratorBase<className, interfaceName> ```
Register an object creator in object factory
[ "", "c++", "design-patterns", "visual-c++", "implementation", "" ]
I've a ListView with about 10 GridViewColumn's and about 100 Lines/Row. I'd like to display a "Total" or summary row at the bottom of the ListView. Does anyone have a idea how to do that, with keeping the ColumnWidth etc. like the others and making it a separate item, so the "main" ListView can have a scrollbar? I've uploaded here a mock-up (sorry for my bad graphic talent :-)): [image](http://img245.imageshack.us/img245/7977/listviewexample.png)
This is an example on how to have a listview with totals area at the end. The column width are binded between each column and its total ``` <Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="Window1" x:Name="ctl" Height="300" Width="300"> <Window.Resources> <GridViewColumnCollection x:Key="gvcc"> <GridViewColumn Width="{Binding Path=ActualWidth, ElementName=col1}" Header="Date" /> <GridViewColumn Width="{Binding Path=ActualWidth, ElementName=col2}" Header="Day Of Week" DisplayMemberBinding="{Binding DayOfWeek}" /> <GridViewColumn Width="{Binding Path=ActualWidth, ElementName=col3}" Header="Year" DisplayMemberBinding="{Binding Year}" /> </GridViewColumnCollection> </Window.Resources> <Grid> <DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" LastChildFill="True"> <GridViewRowPresenter Name="listview_total" DockPanel.Dock="Bottom" Margin="0,5,0,5" Columns="{StaticResource gvcc}"> <GridViewRowPresenter.Content> <sys:DateTime>2005/2/1</sys:DateTime> </GridViewRowPresenter.Content> </GridViewRowPresenter> <ListView x:Name="listview_rows" SelectionMode="Single" DockPanel.Dock="Top" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> <ListView.View> <GridView> <GridViewColumn x:Name="col1" Header="Date" /> <GridViewColumn x:Name="col2" Header="Day Of Week" DisplayMemberBinding="{Binding DayOfWeek}" /> <GridViewColumn x:Name="col3" Header="Year" DisplayMemberBinding="{Binding Year}" /> </GridView> </ListView.View> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> </ListView> </DockPanel> </Grid> </Window> ``` [![enter image description here](https://i.stack.imgur.com/p5zTT.png)](https://i.stack.imgur.com/p5zTT.png)
Building off [federubin's excellent answer](https://stackoverflow.com/a/1573817/203816), you can bind the `GridViewRowPresenter`'s `Columns` property directly to the `Columns` property of the `GridView`. ``` <GridViewRowPresenter Columns="{Binding ElementName=ListViewGridViewName, Path=Columns}" ...> ``` The columns' widths will be updated automatically in the presenter when they are changed in the main grid and you no longer have to duplicate your column definitions. ``` <Window x:Class="WpfTestbed.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <Grid> <DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" LastChildFill="True"> <GridViewRowPresenter Columns="{Binding ElementName=ListViewGridView, Path=Columns}" DockPanel.Dock="Bottom" Margin="4,5,0,5"> <GridViewRowPresenter.Content> <sys:DateTime>2005/2/1</sys:DateTime> </GridViewRowPresenter.Content> </GridViewRowPresenter> <ListView SelectionMode="Single" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> <ListView.View> <GridView x:Name="ListViewGridView"> <GridViewColumn Header="Date" /> <GridViewColumn Header="Day Of Week" DisplayMemberBinding="{Binding DayOfWeek}" /> <GridViewColumn Header="Year" DisplayMemberBinding="{Binding Year}" /> </GridView> </ListView.View> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> <sys:DateTime>1/2/3</sys:DateTime> <sys:DateTime>4/5/6</sys:DateTime> <sys:DateTime>7/8/9</sys:DateTime> <sys:DateTime>10/11/12</sys:DateTime> </ListView> </DockPanel> </Grid> </Window> ```
C#/WPF: Idea how to display the last row of a ListView separately?
[ "", "c#", "wpf", "listview", "" ]
I am using SQL Express 2005 and do a backup of all DB's every night. I noticed one DB getting larger and larger. I looked at the DB and cannot see why its getting so big! I was wondering if its something to do with the log file? Looking for tips on how to find out why its getting so big when its not got that much data in it - Also how to optimise / reduce the size?
Several things to check: * is your database in "Simple" recovery mode? If so, it'll produce a lot less transaction log entries, and the backup will be smaller. Recommended for development - but not for production * if it's in "FULL" recovery mode - do you do regular transaction log backups? That should limit the growth of the transaction log and thus reduce the overall backup size * have you run a `DBCC SHRINKDATABASE(yourdatabasename)` on it lately? That may help * do you have any log / logging tables in your database that are just filling up over time? Can you remove some of those entries? You can find the database's recovery model by going to the Object Explorer, right click on your database, select "Properties", and then select the "Options" tab on the dialog: [![alt text](https://i.stack.imgur.com/rOAXu.jpg)](https://i.stack.imgur.com/rOAXu.jpg) Marc
If it is the backup that keeps growing and growing, I had the same problem. It is not a 'problem' of course, this is happening by design - you are just making a backup 'set' that will simply expand until all available space is taken. To avoid this, you've got to change the overwrite options. In the SQL management studio, right-click your DB, TASKS - BACKUP, then in the window for the backup you'll see it defaults to the 'General' page. Change this to 'Options' and you'll get a different set of choices. The default option at the top is 'Append to the existing media set'. This is what makes your backup increase in size indefinitely. Change this to 'Overwrite all existing backup sets' and the backup will always be only as big as one entire backup, the latest one. (If you have a SQL script doing this, turn 'NOINIT' to 'INIT') CAUTION: This means the backup will only be the latest changes - if you made a mistake three days ago but you only have last night's backup, you're stuffed. Only use this method if you have a backup regime that copies your .bak file daily to another location, so you can go back to any one of those files from previous days.
Reducing Size Of SQL Backup?
[ "", "sql", "sql-server", "" ]
I'm using Xstream to serialize a EJB entity class to be transferred by a web service, but it also writes the database specific information in this case the following code. Is it possible to omit this information? ``` <oracle.toplink.essentials.internal.helper.DatabaseField> <scale>0</scale> <length>255</length> <precision>0</precision> <isUnique>false</isUnique> <isNullable>true</isNullable> <isUpdatable>true</isUpdatable> <isInsertable>true</isInsertable> <columnDefinition></columnDefinition> <name>ZIPCODEID</name> <table> <name>ZIPCODE</name> <tableQualifier></tableQualifier> <qualifiedName>ZIPCODE</qualifiedName> <uniqueConstraints/> </table> <sqlType>4</sqlType> <index>0</index> </oracle.toplink.essentials.internal.helper.DatabaseField> ```
From [FAQ](http://x-stream.github.io/faq.html): How do I specify that a field should not be serialized? Make it transient, specify it with XStream.omitField() or annotate it with @XStreamOmitField
EclipseLink (open sourced from TopLink) JAXB has extensions specifically for mapping JPA entities to XML: For more information see: * <http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA>
Serialization of Entity classes using Xstream
[ "", "java", "jpa", "xstream", "" ]
I have recently been developing a sim game in java, as many of my questions show, and it's come a long way! Graphically, it is somewhat lacking, and at current I'm using shapes for items, people, rooms etc. I was looking at other similar projects, and noticed that one was using OpenGL. I have been reading CokeAndCode "space invaders 103 - refactoring and OpenGL", and I still don't know if it is something I need in my game or not. Here is a video that I used for a previous question, but it still shows basically what I have so far (<http://www.screenjelly.com/watch/Bd7d7pObyFo>), although I have done a lot of refactoring and re coding over the last few weeks, but graphically, nothing has changed. As I understand it, I'm currently using java2D to do this. I really don't know how I should continue graphically with this game. This is my first project I have done outside of learning for my own enjoyment, and so I'm still rather new to this. Thanks in advance!
This could turn into a long subjective conversation quickly but I want to state the fact that you don't **need** openGL. Your application doesn't need to be the best looking one out there. Nethack still attracts people and between you and me : the graphics sucks. Do you want to learn about 2D and 3D graphics and textures and so on ? Then try stuff... best way to learn. Then you can add this to your resume. There are a lot of tutorial to do your first steps in OpenGL or some other graphic library. You can even try Qt Jambi. But once you start, you're in for a ride ;)
One good side of using opengl (even for 2D graphics) is that you will get (if properly done) hardware graphics acceleration for your scenes. Also, you can use orthogonal projection and keep one of the axis (Z) as zero to do your 2D graphics. It will be easy if you want to add a 3D effect (like lightning or something) if you use OpenGL. However it all depends on how much you want to improve the graphics, since adding OpenGL might make things a little more complicated than plain Java2D.
Do I need to use OpenGL in my 2D Java sim game?
[ "", "java", "opengl", "java-2d", "" ]
I see this quiet often in C# documentation. But what does it do? ``` public class Car { public Name { get; set; } } ```
It is shorthand for: ``` private string _name; public string Name { get { return _name; } set { _name = value; } } ``` The compiler generates the member variable. This is called an [automatic property](http://msdn.microsoft.com/en-us/library/bb384054.aspx).
In simple terms they are referred as property accessors. Their implementation can be explained as below 1.get{ return name} The code block in the get accessor is executed when the property is **Read**. 2.set{name = value} The code block in the set accessor is executed when the property is **Assigned** a new value. Eg.(Assuming you are using C#) ``` class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } } ``` 1. Now when you refer to this property as below > Person p = new Person();// Instantiating the class or creating object > 'p' of class 'Person' > > ``` > System.Console.Write(p.Name); //The get accessor is invoked here > ``` The get accessor is invoked to **Read** the value of property i.e the compiler tries to read the value of string 'name'. 2.When you **Assign** a value(using an argument) to the 'Name' property as below ``` Person p = new Person(); p.Name = "Stack" // the set accessor is invoked here Console.Writeline(p.Name) //invokes the get accessor Console.ReadKey(); //Holds the output until a key is pressed ``` The set accessor **Assigns** the value 'Stack" to the 'Name property i.e 'Stack' is stored in the string 'name'. Ouput: > Stack
What does this mean ? public Name {get; set;}
[ "", "c#", "properties", "" ]
The code below generates an error using Guice 2.0. With Guice 1.0 everything is fine. The JDK is Java 6 update 15. ``` public class App { public static void main(String[] args) { Guice.createInjector(new AbstractModule() { @Override protected void configure() { // just testing } }); } } ``` The error is: ``` Exception in thread "main" java.lang.NoClassDefFoundError: [Lorg/aopalliance/intercept/MethodInterceptor; at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2427) at java.lang.Class.getDeclaredMethods(Class.java:1791) at com.google.inject.internal.ProviderMethodsModule.getProviderMethods(ProviderMethodsModule.java:78) at com.google.inject.internal.ProviderMethodsModule.configure(ProviderMethodsModule.java:70) at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223) at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:232) at com.google.inject.spi.Elements.getElements(Elements.java:101) at com.google.inject.InjectorShell$Builder.build(InjectorShell.java:135) at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:102) at com.google.inject.Guice.createInjector(Guice.java:92) at com.google.inject.Guice.createInjector(Guice.java:69) at com.google.inject.Guice.createInjector(Guice.java:59) at App.main(App.java:6) Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) ... 14 more ``` What can be the problem?
You have missed to include a [dependency jar](http://sourceforge.net/projects/aopalliance/) with the class `org.aopalliance.intercept.MethodInterceptor` in the classpath.
as [Boris Pavlović](https://stackoverflow.com/questions/1266587/error-with-guice-2-0#1266786) mentions in his answer, you're missing a jar. Specifically the aopalliance.jar file, which comes in the guice [zip file](http://google-guice.googlecode.com/files/guice-2.0.zip) Alternatively, you might try using [guice-2.0-no\_aop.jar](http://google-guice.googlecode.com/files/guice-2.0-no_aop.jar), but I'm not sure if that will work. Adding this file to the classpath depends on which tool you use to run your java code. * If you are running java from the command line: > ``` > windows: java -cp aopalliance.jar;guice-2.0.jar;other_jars.jar YourMainClass > *nix: java -cp aopalliance.jar:guice-2.0.jar:other_jars.jar YourMainClass > ``` * If you are running java from Eclipse, typically you'll have some type of lib/ directory. Put your jar there, then right-click on the jar -> Build Path -> Add to Build Path
ClassNotFoundException with Guice 2.0
[ "", "java", "guice", "classnotfoundexception", "" ]
I want to add some Ajax sorting options to a list. Since my site runs without JavaScript thus far I'd like to keep it running for people with it turned off, old/mobile browsers or noscript. How can I run a block of JavaScript when clicking a link if JavaScript is enabled and have that link direct the browser to a new page if it's not. I'd like to keep away from hacky noscript tags.
Your links need valid href values pointing to the alternative non-JavaScript pages, and in your click event, you need to return false, to avoid JavaScript enabled browsers to follow the links: ``` <a id="aboutLink" href="about-us.html">About Us</a> ``` --- ``` $('#aboutLink').click(function () { // ajax content retrieval here... return false; // stop the link action... }); ```
I would use [`preventDefault`](http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29): ``` $('a').click(function(e) { e.preventDefault(); //stop the browser from following $('#someDiv').load('content.php'); }); <a href="no-script.html">Load content</a> ``` If there's no Javascript, the HREF will be followed.
What's the best way to allow the browser to fall back to a link if JavaScript is turned off or disabled?
[ "", "javascript", "jquery", "compatibility", "" ]
Looking for API that helps me with processing of taxonomies. It should be possible to work with taxonomy in object model (loading from xml file), list categories, traverse tree of categories (if it's tree taxonomy), getting name and value for category, etc. Read only mode is sufficient. Google hasn't helped a lot :( Usage can be as follows: `Taxonomy taxonomy = Taxonomy.loadFromStream(XMLInputStream);` List categories = taxonomy.listAllCategories(); Category rootCategory = taxonomy.getRootCategory(); What's important about it is that I don't want to handle XML directly. It's useless. If there will be some YAML adapter, taxonomy can be in YAML format and my code stays unaffected...
I don't think that you will ever find an XML based library for taxonomy: it is too **specific**. However you can implement **taxonomy model** yourself on top of a library like [XStream](http://xstream.codehaus.org/) of [JAXB](http://jaxb.java.net/) in order to serialize to XML without writing verbose XML manipulation code.
If you cannot find something specifically for taxonomies, try doing the same for *ontologies*. Then you can create an ontology with only taxonomic relations. The OWL API (<http://owlapi.sourceforge.net/>) seems to solve the problem. You can create and OWL ontology and easily convert it to XML and back using their OWL/XML parser and writer. And here is an example of creating a hierarchy with this library: <https://github.com/owlcs/owlapi/blob/master/contract/src/test/java/uk/ac/manchester/owl/owlapi/tutorial/examples/SimpleHierarchyExample.java> Hope that helps.
Java API for processing of taxonomies
[ "", "java", "taxonomy", "utility", "" ]
Given the following: **byte[] sData;** and a function declared as **private byte[] construct\_command()** if I were to then assign the result of **construct\_command()** to **sData** would sData just point to the contents of what's returned from the function or would some space be alloctaed for sData in memory and the contents of the result of the function be copied into it?
Assuming sData is a local variable, it will live in the stack and it will **refer** to the array returned by the method. The method does not return the contents of the array itself, but a reference to the array. In .net, arrays are first class objects and all array-type variables are in fact references.
The assignment will simply assign the sData to reference the instance returned by construct\_command. No copying of data will occur. In general, the CLR breaks the world down into 2 types * Value Types: This is anything that derives from System.ValueType. Assignment between values of these types happens by value and essentially results in a copy of the values between locations * Reference Types: Anything else. Assignment between values of these types simply causes the location to reference a different object in memory. No copying of values occurs Arrays are reference types in the CLR and hence do not cause a copying of the underlying value.
What kind of memory semantics govern array assignment in c#?
[ "", "c#", ".net", "" ]
I have a script giving me error `403 Forbidden error`, it's just a copy of another script but the difference in this is that both use another mysql class to access database. My whole project is complete and this is last file so I don't want to do the whole work again for a single file. Server logs shows that **client denied by server configuration:** What should I look for? I have tried the following: * Permissions are 644 * New file with just simple echo gives 403 too * Changed name of folder However, `index.php` works perfectly.
This issue occurs if you have had denied for all in your `.htaccess` file. Changing that resolves the issue.
Check the permissions and also ***ownership*** of the file. Generally, 403 means that the web server doesn't have the rights to read the file and therefore can't continue the request. The permissions may be set correctly, however the file might be owned by another account on the server - an account that isn't part of the same group as the account which is running the server. For instance, I believe\* Apache is ran by default under the `httpd` user account, which is part of the `httpd` group. However, the FTP user you're logging in as (for instance `ftpuser`) might not be part of the `httpd` group. So, in copying the file you've created it under a different user account and Apache won't get execute access with `644`. \* it's been a while since I've used apache, but it's similar under nginx.
403 Forbidden response – what should I look for?
[ "", "php", "permissions", "webserver", "" ]
I'd like to set this up as a post where all known JavaScript client development platforms could be listed by company/organization/ecosystem. \* anything that is HTML/JavaScript-based. **Microsoft** [Windows Gadgets](http://msdn.microsoft.com/en-us/library/dd370867%28VS.85%29.aspx)\* [HTA - HTML Applications](http://msdn.microsoft.com/en-us/library/ms536471%28VS.85%29.aspx)\* **Adobe** [Adobe AIR](http://www.adobe.com/products/air/tools/sdk/)\* Can be done with only HTML/JS but can also can use Flex/Flash [Adobe Director](http://www.adobe.com/products/director/) [Adobe PDF](http://www.adobe.com/devnet/acrobat/javascript.html) **Yahoo** [Konfabulator](http://widgets.yahoo.com/tools/) **Google** [Google Desktop Gadgets](http://desktop.google.com/plugins/) - SDK link on the left **Mozilla/Firefox** [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/748) [XUL Runner](https://developer.mozilla.org/en/XULRunner) **Appcelerator** Titanium What did I miss? Should I also list JScript.NET, managed JScript, [Rhino](http://www.mozilla.org/rhino/)? note: I've set this up as a community wiki.
There's also Titanium. <http://www.appcelerator.com/> You can use JavaScript, Python, or Ruby for desktop apps. I believe that mobile apps are JavaScript (no Python or Ruby).
Windows Mobile 6.5 (MS Smart Phone OS) will support HTML/JavaScript Widgets similar to Vista/Windows 7 Widgets: [Windows Mobile Developer](http://developer.windowsmobile.com/) Looks pretty interesting.
Client-side Development Platforms based on JavaScript
[ "", "javascript", "runtime", "rich-internet-application", "" ]
I have difficulty understanding the difference between passing by value and passing by reference. Can someone provide a C# example illustrating the difference?
In general, read [my article about parameter passing](http://pobox.com/~skeet/csharp/parameters.html). The basic idea is: *If the argument is passed by reference, then changes to the parameter value within the method will affect the argument as well.* The subtle part is that if the parameter is a reference type, then doing: ``` someParameter.SomeProperty = "New Value"; ``` *isn't* changing the value of the parameter. The parameter is just a reference, and the above doesn't change what the parameter refers to, just the data within the object. Here's an example of *genuinely* changing the parameter's value: ``` someParameter = new ParameterType(); ``` Now for examples: **Simple example: passing an int by ref or by value** ``` class Test { static void Main() { int i = 10; PassByRef(ref i); // Now i is 20 PassByValue(i); // i is *still* 20 } static void PassByRef(ref int x) { x = 20; } static void PassByValue(int x) { x = 50; } } ``` **More complicated example: using reference types** ``` class Test { static void Main() { StringBuilder builder = new StringBuilder(); PassByRef(ref builder); // builder now refers to the StringBuilder // constructed in PassByRef PassByValueChangeContents(builder); // builder still refers to the same StringBuilder // but then contents has changed PassByValueChangeParameter(builder); // builder still refers to the same StringBuilder, // not the new one created in PassByValueChangeParameter } static void PassByRef(ref StringBuilder x) { x = new StringBuilder("Created in PassByRef"); } static void PassByValueChangeContents(StringBuilder x) { x.Append(" ... and changed in PassByValueChangeContents"); } static void PassByValueChangeParameter(StringBuilder x) { // This new object won't be "seen" by the caller x = new StringBuilder("Created in PassByValueChangeParameter"); } } ```
Passing by value means a copy of an argument is passed. Changes to that copy do not change the original. Passing by reference means a reference to the original is passed and changes to the reference affect the original. This is not specific to C#, it exists in many languages.
What is different between Passing by value and Passing by reference using C#
[ "", "c#", "" ]
I am using Ivy as part of my continuous integration build system, but I need to override the default location that Ivy's local cache area is.
Although the answer above from skaffman is correct, I found it to be a lot more work than I had expected! When I added the ivysettings.xml file to the project, I then needed to redefine almost everything, as the default values had been working fine until then. so, I found out how to add the new cache directory to the in-line command-line within my NAnt script... ``` < exec program="java" commandline="... ... -jar ${ivy.jar} -cache ${project.cache} ... ... /> ``` (Where `${ivy.jar}` is the location of my .jar file and `${project.cache}` is the new location set earlier in the script where I want the cache area to use.) This means that I don't need the ivysettings.xml file, and I can revert everything back to using the default resolvers, etc.
Something like this in `ivysettings.xml`: ``` <ivysettings> <caches defaultCacheDir="/path/to/my/cache/dir"/> </ivysettings> ``` See documentation at <http://ant.apache.org/ivy/history/latest-milestone/settings/caches.html>
How to override the location of Ivy's Cache?
[ "", "java", "ivy", "" ]
I am binding a Dictionary to a ComboBox which keeps the Enum values. To retrieve the selected value I used: `comboBox1.SelectedItem` which returns a dimensional value of `[0,Permanent]`. I just want to retrieve `Permanent` and then convert it back to Enum. Something like: `Employee.JobType = Enum.Parse(JobType, comboBox1.SelectedItem)` How can I achieve this?
Either: ``` Employee.JobType = (JobType)Enum.Parse(typeof(JobType), comboBox1.SelectedValue); ``` Or: ``` Employee.JobType = (JobType)Enum.Parse(typeof(JobType), comboBox1.SelectedText); ```
If items source for combo box is a dictionary, SelectedItem is of type: KeyValuePair<[type of key], JobType> You can access your enum value by casting SelectedItem and accessing Value property. ``` var selectedItem = (KeyValuePair<[type of key], JobType>) comboBox1.SelectedItem; var jobType = selectedItem.Value; ```
C# How to get the Enum value from ComboBox in WinForms?
[ "", "c#", "winforms", "enums", "combobox", "" ]
I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property. ``` $(".AspNet-GridView-Normal > td > input").click(function() { //Need to access the C# property here //Take action here based on the value of the C# property }); ```
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side. Markup: ``` <asp:HiddenField ID="hfValueINeedToKnow" runat="server"/> ``` Code Behind: ``` hfValueINeedToKnow.Value = <some value>; ``` jQuery: ``` $("#<%= hfValueINeedToKnow.ClientID %>").val(); ``` You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
You mentioned in a comment that the value is an int. And I see it's also a `public` property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free: ``` <script> $(".AspNet-GridView-Normal > td > input").click(function() { var AvailableInstalls = <%= AvailableInstalls %>; }); </script> ```
Reading C# property into JQuery code
[ "", "c#", "asp.net", "jquery", "properties", "" ]