Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Let's say we have these two classes: ``` public class Base { public static int GetInt() { return 1; } } public class Derived : Base { } ``` Let's also say that a piece of code calls Derived.GetInt(). How can I tell from within GetInt() that it was Derived.GetInt() and not Base.GetInt() that was called? What reflection technique do I use?
There's no way to tell the difference, with Reflection or otherwise. The calls are precisely equivalent, and when compiling, already at MSIL level there is no difference.
I don't think you do, since there *is* no Derived.GetInt. GetInt is a static member, and although you're referencing it through Derived, it only belongs to Base.
C# reflection and inheritance of static members
[ "", "c#", "reflection", "inheritance", "" ]
I'm using PHP5, CodeIgniter and Apache. The localhost php pages were loading fine and then suddenly they started crashing Apache. The web pages seem to get to different stages of loading when apache crashes. The only interesting line in the Apache error log file says : [notice] Parent: child process exited with status 3221225477 -- Restarting. There is a lot of discussion of this issue on the web but it seems there is no one solution, different people have described different solutions that worked for their system. Suggestions Appreciated.
I found a solution that worked for me. I copied the following two files from my PHP directory to the Win32 directory and the errors stopped : php5apache.dll, libmysql.dll. So even though these files should have been found in the PHP directory under certain circumstances they needed to be in the system dir
This problem often happens in Windows because of smaller Apache’s default stack size. And it usually happens when working with php code that allocates a lot of stacks. To solve this issue, add the following at the end of apache config file, httpd.conf ``` <IfModule mpm_winnt_module> ThreadStackSize 8888888 </IfModule> ``` AND restart apache. i take this solution from this [site](http://www.codexpedia.com/apache-server/parent-child-process-exited-with-status-3221225725-restarting-on-xamp-apache/).
Apache error [notice] Parent: child process exited with status 3221225477 -- Restarting
[ "", "php", "apache", "" ]
**Background:** Suppose I have the following obviously-incorrect PHP: ``` try{ $vtest = ''; print(array_pop($vtest)); }catch(Exception $exx){} ``` For it to work with array\_pop, $vtest should obviously be an array, not a string. Nevertheless, when I run this code the Warning is exhibited. I don't want that, I just want the code to fail silently. **Question:** Is there something special about PHP try-catch compared to other languages that cause this not to work? **Disclaimer:** Just for reference, it is true there are other ways to handle this situation in PHP, but these are undesirable. The goal here is to avoid: **The "at-sign" trick:** ``` $vtest = ''; print(@array_pop($vtest)); // <-- would like to avoid this ``` **Type Casting:** ``` $vtest = ''; $vtest = (array)$vtest; print(array_pop($vtest)); ```
Warnings and notices are not technically exceptions in PHP. To catch an exception it has to be explicitly thrown, and many of the built-in libraries of functions do not throw exceptions (mostly because they were written before PHP supported exceptions). It would have been nice if somehow exceptions were built on top of the existing notice/warning/error framework but perhaps that is asking too much.
A warning will always be produced by the code you provided but you can use [set\_error\_handler](http://ca.php.net/manual/en/function.set-error-handler.php) to dictate how the warning is handled; i.e. you can cause it to throw an exception. Furthermore, you can use [restore\_error\_handler](http://www.php.net/manual/en/function.restore-error-handler.php) to return to default error handling when your done. ``` function errorHandler($errno, $errstr, $errfile, $errline) { throw new Exception($errstr, $errno); } set_error_handler('errorHandler'); ```
PHP try-catch blocks: are they able to catch invalid arg types?
[ "", "php", "arrays", "exception", "try-catch", "" ]
I just converted a VB.net solution into C# solution. But lots of variables have been coverted like: ``` string var1 = (string)1; string var2 = (string)intVar; //intVar is a int value ``` I just want to convert all `(string)XXXX` to `XXXX.ToString()` by using some Regular expressions or some other replace methods. Can someome help me out?
Suggest you to use this one Find: \(string\){(.\*)}{:Po} Replace: \1.ToString()\2 Good luck!
find: **\(string\){:a\*}** replace: **\1.ToString()** Back up your solution first!
In C# VS2008 how to replace (string)aaa to aaa.ToString()
[ "", "c#", "vb.net", "" ]
I have a simple question about std::string and google's protocol buffers library. I have defined a message like so: ``` message Source { required string Name = 1; required uint32 Id = 2; optional string ImplementationDLL = 3; optional bytes Icon = 4; } ``` I want to use the Icon field to send an image, it most probably will be a png image. After feeding this to the protobuf compiler i got something like this to access/manipulate the Icon field. ``` inline bool has_icon() const; inline void clear_icon(); static const int kIconFieldNumber = 4; inline const ::std::string& icon() const; inline void set_icon(const ::std::string& value); inline void set_icon(const char* value); inline void set_icon(const void* value, size_t size); inline ::std::string* mutable_icon(); ``` the std::string\* mutable\_icon() function is giving me a headache. It is returning a std::string but i believe strings can not hold binary data ! or can they ? i can use set\_icon(const void\*, size\_t) function to put binary data, but then how do i get it on the other side ? i think std::string might be able to hold binary data, but how ????
the answer to this question: [How do you construct a std::string with an embedded null?](https://stackoverflow.com/questions/164168/how-do-you-construct-a-stdstring-with-an-embedded-null)
``` const std::string s = icon(); const void *data=s.c_str(); ```
Using Protocol Buffers to send icons/small images
[ "", "c++", "stl", "protocol-buffers", "" ]
I intend to call a function whenever `m_logger<<"hello"<<"world"` is called. m\_logger is of type ofstream. So i decide to overload << with following signature ``` friend ofstream& operator<<(ofstream &stream,char *str); ``` However the vc compiler gives following error: > error C2666: 'operator <<' : 6 overloads have similar conversions Is there anyother way to achieve this, my objective is to divert all the write operation to ofstream object to different function? Creating an object of my own calss works for me, however how can i make it work like normal ofstream object which typecasts all system defined types into strings or char\*. i know one approach would be to overload the operator for each and every type but is there a cleaner approach
The problem is that `ofstream` is already overloaded this way. If you make `mlogger` of a new type holding an `ofstream`, then you can do this: ``` class mlogger_t { public: ofstream stream; ... } mlogger_t& operator<<(mlogger_t& stream, const string& str) { stream.stream << str; ... } //EDIT: here is how to make this work for other types too using templates: template<typename T> mlogger_t& operator<<(mlogger_t& stream, T val) { stream.stream << val; } ... mlogger_t mlogger; mlogger << "foo"; ``` Also, you should definitely use a `const string&` (as I did in this example) rather than a C-style string. If you *really* need it to be C-style, at least use `const char *`.
"overload" isn't "override". You can overload a function or operator for arguments of different types; you cannot override an existing function or operator with your own implementation (aside from overriding virtual functions, which is obviously very different). The only exceptions are `operator new` and `operator delete`, where it's possible to override built-in ones.
How do I overload the << operator?
[ "", "c++", "visual-c++", "operators", "operator-overloading", "operator-keyword", "" ]
At the office, when I leave for the night I very rarely log off or reboot. I simply lock my workstation and go home, leaving all my development tools exactly how I left them. If Windows-Update rolls through and reboots my machine in the middle of the night I'm only slightly peeved because when I log back in the next morning, any MS Office application, or Visual Studio instance I had running will have already automatically restarted, opening whatever file(s)/projects/solutions I may have been working on. **My question is:** How can I make my Windows Forms applications (C#) do this? Is there some way for my application to "register" that it wants to be restarted if the system automatically reboots?
I *think* the [RegisterApplicationRestart](http://msdn.microsoft.com/en-us/library/aa373347(VS.85).aspx) Win32 API function might be what you're after, it's part of the Restart Manager API.
If you have Windows Vista or Windows 7, you can use the Managed Restart and Recovery API. The links on that page also point to some useful blog entries <http://channel9.msdn.com/posts/DanielMoth/Windows-Vista-Restart-amp-Recovery-APIs-from-managed-code/>
How to restart my application if Windows Update forces a reboot?
[ "", "c#", "windows", "winforms", "windows-update", "" ]
I want to build a bot that basically does the following: 1. Listens to the room and interacts with users and encourages them to PM the bot. 2. Once a user has PMed the bot engage with the client using various AI techniques. Should I just use the IRC library or Sockets in python or do I need more of a bot framework. What would you do? Thanks! Here is the code I'm currently using, however, I haven't gotten it to work. ``` #!/usr/bin/python import socket network = 'holmes.freenet.net' port = 6667 irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) irc.connect ( ( network, port ) ) irc.send ( 'NICK PyIRC\r\n' ) irc.send ( 'USER PyIRC PyIRC PyIRC :Python IRC\r\n' ) irc.send ( 'JOIN #pyirc\r\n' ) irc.send ( 'PRIVMSG #pyirc :Can you hear me?\r\n' ) irc.send ( 'PART #pyirc\r\n' ) irc.send ( 'QUIT\r\n' ) irc.close() ```
Use [Twisted](http://twistedmatrix.com) or [Asynchat](http://docs.python.org/library/asynchat.html) if you want to have a sane design. It is possible to just do it with sockets but why bother doing it from scratch?
If you want to have AI techniques involved, then I suggest you look at the [AIML](http://pyaiml.sourceforge.net/) package for Python. It is the same technology that ALICE bots are done in.
IRC Python Bot: Best Way
[ "", "python", "irc", "bots", "" ]
I continue my understanding of MVVC with the [code of MSDN](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx) and I have a question. In the .xaml they have a list of commands displayed to the screen. ``` <Border Grid.Column="0" Style="{StaticResource MainBorderStyle}" Width="170" > <HeaderedContentControl Content="{Binding Path=Commands}" ContentTemplate="{StaticResource CommandsTemplate}" Header="Control Panel" Style="{StaticResource MainHCCStyle}" /> </Border> ``` From here, I understand that the DataContext is set (not shown here) and it will display the collection of Commands. What I do not understand is the CommandsTemplate that you can see below: ``` <DataTemplate x:Key="CommandsTemplate"> <ItemsControl IsTabStop="False" ItemsSource="{Binding}" Margin="6,2"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Margin="2,6">pou <Hyperlink Command="{Binding Path=Command}"> <TextBlock Text="{Binding Path=DisplayName}" /> </Hyperlink> </TextBlock> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </DataTemplate> ``` How does the binding is created? How this code tell to check the property Command and DisplayName from the object inside the collection? Is it from the ItemsSource? If yes, I do not understand why it's only at {Binding}. Anyone can explain me please how the DataTemplate binding work from a ContentTemplate?
As you said, the DataContext is set to the ViewModel class so the control that you mentioned in XAML will be able to access the public properties of that ViewModel. For example: ``` private ObservableCollection<Commander> commands = new ObservableCollection<Commander>(); public ObservableCollection<Commander> Commands { get { return commands; } set { commands = value; } } ``` The structure of Commander class. ``` public class Commander { public ICommand Command { get; set; } public string DisplayName { get; set; } } ``` That VM has the property called Commands which might be ObservableCollection. This property can be accessible from XAML. You can imagine that HeaderedContentControl is a container. The content of that HeaderedContentControl is a DataTemplate "CommandsTemplate" that has a ItemsControl and it bind to the Commands property of VM. Content="{Binding Path=Commands}" And then, you can to bind ItemControl with Commands again but that ItemControl is inside the content that bind to Commands. So you don't need to specify the path again. You can just use ``` ItemsSource="{Binding}" instead of ItemsSource="{Binding Commands}". ``` Two textblocks are inside ItemControl so they are at the same level as Commander class of Commands ObservableCollection. That's why you can access Text="{Binding Path=DisplayName}" directly. Hope it helps.
Example: **XAML** ``` <Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" Loaded="Window_Loaded"> <Window.Resources> <DataTemplate x:Key="CommandsTemplate"> <ItemsControl IsTabStop="False" ItemsSource="{Binding}" Margin="6,2"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Margin="2,6">pou <Hyperlink Command="{Binding Path=Command}"> <TextBlock Text="{Binding Path=DisplayName}" /> </Hyperlink> </TextBlock> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </DataTemplate> </Window.Resources> <Grid> <Border Width="170"> <HeaderedContentControl Content="{Binding Path=Commands}" ContentTemplate="{StaticResource CommandsTemplate}" Header="Control Panel"/> </Border> </Grid> </Window> ``` **C#** ``` /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); Commands.Add(new Commander() { DisplayName = "DN1" }); Commands.Add(new Commander() { DisplayName = "DN2" }); Commands.Add(new Commander() { DisplayName = "DN3" }); this.DataContext = this; } private void Window_Loaded(object sender, RoutedEventArgs e) { } private ObservableCollection<Commander> commands = new ObservableCollection<Commander>(); public ObservableCollection<Commander> Commands { get { return commands; } set { commands = value; } } } public class Commander { public ICommand Command { get; set; } public string DisplayName { get; set; } } ```
WPF DataTemplate and Binding
[ "", "c#", "wpf", "data-binding", ".net-3.5", "templates", "" ]
Lately I've been thinking a lot about building a website/blog/community oriented site. However I can't decide if it's a good idea to build it using Wordpress as a base. I've been reading around the Internet, and I've seen that many users have trouble with Wordpress using lot of CPU and other resource related problems. So, what do you think? Is it wise to actually build an application based on Wordpress? Or it would probably lead to undesired results? Any opinions would help.
WordPress is quite flexible once you get the hang of its WordPress Loop, Page Templates and how to create a customised homepage. Using some plugins, such as the Page Redirect To and Custom Taxonomy, you can have a pseudo-CMS. There are also widgets and plugins that let WordPress mimics CMS-like behaviour, such as listing all sub-pages within a pages, customize how categories are shown and etc. If you can handle the WordPress loop and use Page Templates, WordPress is okay to build on-top of. However, its database schema is quite confusing. Depending on your goals, you may want to use CodeIgniter or something else.
If you to get really farther than a blogging software, maybe you can have a look at more generic CMSes. I kinda like [Drupal](http://drupal.org/) (which has *a lot* of plugins that can help you do almost whatever you want on your site) ; as a reference point, it is used by many quite big sites, so, if correctly configured, can hold a bit of load. Just a remark : you might need at least a couple of day to learn how to use it well, because it is quite rich, has lots of features, and you will probably want to have a look at many modules, to get the ones you need/like. *(But that would be true for any CMS, I guess)*
Developing an Application using Wordpress as a base?
[ "", "php", "wordpress", "web-applications", "" ]
I am trying to create a directory in Java. I think I have provided correctly all necessary things so that I make the directory, but it is not created. You can see from my code below and the corresponding output that every element from which I compose the path of the new directory should be correct and valid. It seems, however, that `tDir.mkdir();` is not doing anything, and therefore the `success` variable is always `false`. I cannot understand why. Thank you in advance. ``` System.out.println("experimentDir: " + experimentDir); System.out.println("item.getName(): " + item.getName()); System.out.println("dirName: " + dirName); String tDirStr = experimentDir + "/" + item.getName() + "All/" + dirName + "DataAll"; System.out.println("tDirStr: " + tDirStr); File tDir = new File(tDirStr); if (tDir.exists()) { System.out.println("EXISTS!!!"); } else { boolean success = tDir.mkdir(); if(success) { System.out.println("Dir created"); } else { System.out.println("No dir created!"); } ``` Output: ``` experimentDir: /home/Documents/datasets/test-experiments item.getName(): PosNegReviews dirName: test tDirStr: /home/Documents/datasets/test-experiments/PosNegReviewsAll/testDataAll No dir created! ```
If you want to create multiple (nested) directories you should use [mkdirs()](http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs()) (note the **s**).
you may be needing to create any parent directory that dont exist. try File.mkdirs().
Problem with creating a directory in Java
[ "", "java", "directory", "" ]
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
Have a look at ACL [WordUtils](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html). ``` WordUtils.capitalize("your string") == "Your String" ```
Here is the code ``` String source = "hello good old world"; StringBuffer res = new StringBuffer(); String[] strArr = source.split(" "); for (String str : strArr) { char[] stringArray = str.trim().toCharArray(); stringArray[0] = Character.toUpperCase(stringArray[0]); str = new String(stringArray); res.append(str).append(" "); } System.out.print("Result: " + res.toString().trim()); ```
How to upper case every first letter of word in a string?
[ "", "java", "string", "" ]
I want to start this as a hobby in developing a desktop game. I have found several engines, but I am not sure whether it does the initial job I am looking at. Initially I want to do the following: 1. Create a figure (avatar), and let the user dress the avatar 2. Load the avatar in the game In later stages, I want to develop this as a multi-player game. What should I do?
I also recommend Ogre. Ogre can do this, it provides everything needed in regards of mesh and animation support, but not as a drop-in solution. You have to write lots of code for this to be done. For our project we implemented something like you do. The main character and any other character can be dressed with different weapons and armor and the visuals of the character avatar change accordingly. As a start hint for how to go about this: In your modeling tool (Blender, Maya, 3ds max, etc.) you model your avatar and all its clothes you need and rig them to the same skeleton. Then export everything individually to Ogre's mesh format. At runtime you can then attach the clothing meshes the user chooses to the skeleton instance so that they together form the avatar. This is not hard to do via Ogre-API, but for even easier access to this you can use [MeshMagick](http://www.ogre3d.org/wiki/index.php/MeshMagick) Ogre extension's meshmerge tool. It has been developed for exactly this purpose. If you want to change other characteristics like facial features, this is possible too, as Ogre supports vertex pose animations out of the box, so you can prepare pathes for certain characteristics of the face and let the user change the face by sliders or somthing like this. (e.g like in Oblivion) One thing to be aware regarding Ogre: It is a 3d graphics engine, not a game engine. So you can draw stuff to the screen with it and animate and light and in any way change the visuals, but it doesn't do input or physics or sound. For this you have to use other libs and integrate them. Several pre-bundled game engines based on Ogre are available though.
If you are good with C++ you should use Ogre, it's the best open-source engine, continuously been updated by it's creators, with a lot of tutorials and a very helpful community. <http://www.ogre3d.org/> It's more of a GFX engine, but it has all the prerequisites you desire. Good luck!
Choosing a 3D game engine
[ "", "c++", "" ]
I'm using Visual Studio 2005 and have a DataTable with two columns and some rows that I want to output to the console. I hoped there would be something like: ``` DataTable results = MyMethod.GetResults(); Console.WriteLine (results.ToString()); ``` What's the best way (i.e. least amount of coding from me) to convert a simple DataTable to a string?
You could use something like [this](http://msdn.microsoft.com/en-us/library/a8ycds2f(VS.80).aspx): ``` Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String) Dim sw As System.IO.StringWriter Dim output As String Console.WriteLine(label) ' Loop through each row in the table. ' For Each row As DataRow In table.Rows sw = New System.IO.StringWriter ' Loop through each column. ' For Each col As DataColumn In table.Columns ' Output the value of each column's data. sw.Write(row(col).ToString() & ", ") Next output = sw.ToString ' Trim off the trailing ", ", so the output looks correct. ' If output.Length > 2 Then output = output.Substring(0, output.Length - 2) End If ' Display the row in the console window. ' Console.WriteLine(output) Next Console.WriteLine() End Sub ```
Prerequisite ``` using System.Linq; ``` then ... ``` string res = string.Join(Environment.NewLine, results.Rows.OfType<DataRow>().Select(x => string.Join(" ; ", x.ItemArray))); ```
How to convert a DataTable to a string in C#?
[ "", "c#", "datatable", "" ]
I am working on a simple Firefox Extension and I want to get the selected text. I tried this: ``` var WordCount = { /* ... */ changeSelected: function() { var selectedText = this.getSelection(); var words = this.countWords(selectedText); this.changeStatus(words, " selected"); //alert(selectedText); }, getSelection: function(e) { var focused_window = document.commandDispatcher.focusedWindow; var sel_text = focused_window.getSelection(); return sel_text.toString(); } } window.addEventListener("select", function(e) { WordCount.changeSelected(); }, false); ``` The Problem is, that I dont get the selection with **document.commandDispatcher.focusedWindow.getSelection()** and I don't know why :(
Your problem is that `document.commandDispatcher.focusedWindow` is going to be pointing to a chrome window, where I suspect you actually want a content window. Try replacing that with `content.getSelection()`
This works in firefox javascripting, so should be OK ``` window.getSelection().toString(); ``` My guess is that document.commandDispatcher.focusedWindow fails
Firefox Extension: Get selected text
[ "", "javascript", "firefox", "selection", "" ]
I have generic list which must be a preserved order so I can retrieve the index of an object in the list. The problem is IndexOf is way too slow. If I comment the IndexOf out, the code runs fast as can be. Is there a better way, such as a *preserved* ordered hash list for c#? Thanks, Nate * Edit - The order in which the items are added/inserted is the order it needs to be. No sorting on them is necessary. Also this list has the potential to be updated often, add, remove, insert. Basically I need to translate the object to an index due to them being represented in a grid control so I can perform operations on the grid control based on index.
If it's not sorted, but the order **needs to be preserved**, then you could have a separate `Dictionary<YourClass, int>` which would contain the index for each element. If you want a sorted list, then check previous posts - you can use `SortedList<Tkey, TValue>` in .Net 3.5, or sort it and use BinarySearch in older .Net versions. [Edit] You can find similar examples on the web, e.g.: [OrderedList](http://www.koders.com/csharp/fid988E7B990B12FE3B54C12466B8F593183E8E8296.aspx?s=mdef:insert). This one internally uses an ArrayList and a HashTable, but you can easily make it generic. [Edit2] Ooops.. the example I gave you doesn't implement IndexOf the way I described at the beginning... But you get the point - one list should be ordered, the other one used for quick lookup.
Sort it using [`List<T>.Sort`](http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx), then use the [`List<T>.BinarySearch`](http://msdn.microsoft.com/en-us/library/w4e7fxsh.aspx) method: *"Searches the entire sorted `List(T)` for an element [...] This method is an O(log n) operation, where n is the number of elements in the range."*
IndexOf too slow on list. Faster solution?
[ "", "c#", "list", "performance", "indexof", "" ]
> **Possible Duplicate:** > [How do you find all subclasses of a given class in Java?](https://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java) Hi, I would like to get a list of classes that implement an interface in Java at runtime so I can do a lookup service without having to hard code it. Is there a simple way of doing this? I fear not.
The short answer is no. The long answer is that subclasses can come into existence in many ways, which basically makes it impossible to categorically find them all. You can't do it at runtime but you can't find classes until they're loaded and how do you know they're loaded? You could scan every JAR and class file but that's not definitive. Plus there are things like URL class loaders. Inner classes (static and non-static) are another case to consider. Named inner classes are easier to find. Anonymous inner classes are potentially much more difficult to find. You also have to consider that if a class has subclasses then new subclasses can be created at a later point.
you should use Java [ServiceLoader](http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html) that is a builtin class. It is capable of iterating at runtime over all know service (interface) implementations. If for some reason you don't want it, you can use ClassLoader.getSystemResources() to iterate over all resources; e.g. if you have 6 times the file /META-INF/com.interface you'll get 6 iterations.
Is it possible to get all the subclasses of a class?
[ "", "java", "reflection", "runtime", "" ]
I have a small job that takes a text file of email/zip codes and inserts them into a sql server 2005 table. It reads each line of the source file, checks to make sure that it parses into a valid email address/zip code, creates a sql insert command, adds it to a string builder and eventually executes it. I want to do a single execute instead of individual sql calls as there will possibly be several thousand inserts. This works, but I'd like to know if this is a bad approach. What's the best practice here? ``` Dim SqlString As String = "insert into [CollectedEmail] values('{0}','{1}');" Do Until sourceFile.Peek = -1 line = sourceFile.ReadLine If line.Length > 0 Then Dim emailAddress As String = Trim(line.Substring(0, EmailLength)) Dim zipcode As String = Trim(line.Substring(EmailLength + 2, ZipCodeLength)) If CVal.validEmail(emailAddress) AndAlso CVal.validZip(zipcode) Then SQL.AppendLine(String.Format(SqlString, emailAddress, zipcode)) ElseIf CVal.validEmail(emailAddress) Then SQL.AppendLine(String.Format(SqlString, emailAddress, "")) Else badAddresses.WriteLine(emailAddress) End If End If Loop InsertToDatabase(SQL.ToString) ``` Thank you
For bulk inserts, check out .NET 2.0 onwards, [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx) class (in the System.Data.SqlClient namespace) Marc Gravell posted an example of its use here on SO: [Copy from one database table to another C#](https://stackoverflow.com/questions/565732/copy-from-one-database-table-to-another-c) **Updated in response to comment**: you can read the cleansed data into a `DataTable`, and use that with `SqlBulkCopy`, similiar to this [example](http://davidhayden.com/blog/dave/archive/2006/03/08/2877.aspx).
If you have sql server 2008 then you can use Table-Valued Parameters, see here for some more info [Table-Valued Parameters in SQL Server 2008](http://msdn.microsoft.com/en-us/library/bb675163.aspx) and sample code. Otherwise do bulk insert
Creating batched sql statements
[ "", ".net", "sql", "sql-server-2005", "batch-file", "" ]
I have the worlds most simple javascript function: ``` fnSubmit() { window.print(); document.formname.submit(); } ``` Which is called by: ``` <button type="button" id="submit" onclick="fnSubmit()">Submit</button> ``` All is well and good, the print dialog shows up, however after printing or canceling the print I get the following error: "document.formname.submit is not a function" My form is defined as follows: (obviously I am not using formname in the actual code but you get the idea) ``` <form name="formname" id="formname" method="post" action="<?=$_SERVER['SCRIPT_NAME']?>"> ``` Obviously I am not trying to do anything special here and I have used similar approaches in the past, what in the world am I missing here?
In short: change the **id** of your submit button to something different than "submit". Also, don't set the **name** to this value either. Now, some deeper insight. The general case is that `document.formname.submit` is a method that, when called, will submit the form. However, in your example, `document.formname.submit` is not a method anymore, but the DOM node representing the button. This happens because elements of a form are available as attributes of its DOM node, via their `name` and `id` attributes. This wording is a bit confusing, so here comes an example: ``` <form name="example" id="example" action="/"> <input type="text" name="exampleField" /> <button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button> </form> ``` On this example, `document.forms.example.exampleField` is a DOM node representing the field with name "exampleField". You can use JS to access its properties such as its value: `document.forms.example.exampleField.value`. However, on this example there is an element of the form called "submit", and this is the submit button, which can be accessed with `document.forms.example.submit`. This overwrites the previous value, which was the function that allows you to submit the form. **EDIT:** If renaming the field isn't good for you, there is another solution. Shortly before writing this, I left the question on the site and got a response in the form of a neat JavaScript hack: ``` function hack() { var form = document.createElement("form"); var myForm = document.example; form.submit.apply(myForm); } ``` See [How to reliably submit an HTML form with JavaScript?](https://stackoverflow.com/questions/1999891/how-to-reliably-submit-an-html-form-with-javascript) for complete details
Given that your form has both an `id` and a `name` defined, you could use either one of these: With the `form` tag's `id`: ``` document.getElementById('formname').submit(); ``` With the `form` tag's `name` attribute: ``` document.forms['formname'].submit(); ```
Form not submitting with JS
[ "", "javascript", "onclick", "submit", "" ]
One error I stumble upon every few month is this one: ``` double x = 19.08; double y = 2.01; double result = 21.09; if (x + y == result) { MessageBox.Show("x equals y"); } else { MessageBox.Show("that shouldn't happen!"); // <-- this code fires } ``` You would suppose the code to display "x equals y" but that's not the case. The short explanation is that the decimal places are, represented as a binary digit, do not fit into double. Example: 2.625 would look like: 10.101 because ``` 1-------0-------1---------0----------1 1 * 2 + 0 * 1 + 1 * 0.5 + 0 * 0.25 + 1 * 0,125 = 2.65 ``` And some values (like the result of 19.08 plus 2.01) cannot be be represented with the bits of a double. One solution is to use a constant: ``` double x = 19.08; double y = 2.01; double result = 21.09; double EPSILON = 10E-10; if ( x + y - result < EPSILON ) { MessageBox.Show("x equals y"); // <-- this code fires } else { MessageBox.Show("that shouldn't happen!"); } ``` If I use decimal instead of double in the first example, the result is "x equals y". But I'm asking myself If this is because of "decimal" type is not vulnerable of this behaviour or it just works in this case because the values "fit" into 128 bit. Maybe someone has a better solution than using a constant? Btw. this is not a dotNet/C# problem, it happens in most programming languages I think.
Decimal will be accurate so long as you stay within values which are naturally decimals in an appropriate range. So if you just add and subtract, for example, without doing anything which would skew the range of digits required too much (adding a very very big number to a very very small number) you will end up with easily comparable results. Multiplication is likely to be okay too, but I suspect it's easier to get inaccuracies with it. As soon as you start dividing, that's where the problems can come - particularly if you start dividing by numbers which include prime factors other than 2 or 5. Bottom line: it's safe in certain situations, but you really need to have a good handle on exactly what operations you'll be performing. Note that it's not the 128-bitness of decimal which is helping you here - it's the representation of numbers as floating *decimal* point values rather than floating *binary* point values. See my articles on .NET [binary floating point](http://pobox.com/~skeet/csharp/floatingpoint.html) and [decimal floating point](http://pobox.com/~skeet/csharp/decimal.html) for more information.
System.Decimal is just a floating point number with a different base so, in theory, it is still vulnerable to the sort of error you point out. I think you just happened on a case where rounding doesn't happen. More information [here](http://www.yoda.arachsys.com/csharp/decimal.html).
Is dotNet decimal type vulnerable for the binary comparison error?
[ "", "c#", ".net", "comparison", "decimal", "" ]
How do I convert `int[]` into `List<Integer>` in Java? Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.
There is no shortcut for converting from `int[]` to `List<Integer>` as `Arrays.asList` does not deal with boxing and will just create a `List<int[]>` which is not what you want. You have to make a utility method. ``` int[] ints = {1, 2, 3}; List<Integer> intList = new ArrayList<Integer>(ints.length); for (int i : ints) { intList.add(i); } ```
# Streams 1. In Java 8+ you can make a stream of your `int` array. Call either [`Arrays.stream`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#stream(int%5B%5D)) or [`IntStream.of`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/IntStream.html#of(int...)). 2. Call [`IntStream#boxed`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/IntStream.html#boxed()) to use boxing conversion from `int` primitive to [`Integer`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/Integer.html) objects. 3. Collect into a list using `Stream.collect( Collectors.toList() )`. Or more simply in Java 16+, call [`Stream#toList()`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/Stream.html#toList()). Example: ``` int[] ints = {1,2,3}; List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList()); ``` In Java 16 and later: ``` List<Integer> list = Arrays.stream(ints).boxed().toList(); ```
How to convert int[] into List<Integer> in Java?
[ "", "java", "arrays", "collections", "boxing", "autoboxing", "" ]
basically what I want is simple, when people onclick, the field become editable. After they change the value, press Esc at keyboard/ or click outside , to save the record. I'm not sure why it's not working. Documentation seems not complete... Anyone got idea on how this work? The documentation page: <http://www.appelsiini.net/projects/jeditable> Here I post my existing code here for guys to review. **testing.html** ``` <head> <title></title> <script src="jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="jquery.jeditable.mini.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> $(function() { $(".click").editable("jeditabletest.php", { indicator : "<img src='indicator.gif'>", tooltip : "Click to edit...", style : "inherit" }); }); </script> <style type="text/css"> #sidebar { width: 0px; } #content { width: 770px; } .editable input[type=submit] { color: #F00; font-weight: bold; } .editable input[type=button] { color: #0F0; font-weight: bold; } </style> </head> <body> <b class="click" style="display: inline">Click me if you dare!</b></> or maybe you should </body> </html> jeditabletest.php <?php echo "hehehe" ?> ``` does anyone know what's wrong? I tried so many times, it just not working at all. All related library files are already put in.
To enable submitting the form when user clicks outside do the following: ``` $(".editable").editable("http://www.example.com/save.php", { onblur : "submit" }); ``` Submitting when pressing ESC is generally a bad idea since ESC is universally reserved for canceling. If you really really want to do this you need to edit Jeditable code. Search and edit the following in jquery.jeditable.js: ``` /* discard changes if pressing esc */ input.keydown(function(e) { if (e.keyCode == 27) { e.preventDefault(); reset.apply(form, [settings, self]); } }); ```
yeap: i recommend <http://valums.com/edit-in-place/> It uses `div`'s `contentEditable` property. You may want to look into that before you start using it. jrh
jquery- jeditable not working
[ "", "javascript", "jquery", "inline", "editing", "jeditable", "" ]
After trying to make a while(bool) loop and it failing because I couldn't see the contents of the vectors because there was nothing in them, I made a while(true) loop with the intention of breaking out if the user inputs a 0. Here are the important portions of the code. Edit: Working code, but what does|= mean? ``` #include "std_lib_facilities.h" class Name_pairs { public: vector<string>names; vector<double>ages; bool test(); string read_names(); double read_ages(); void print(); }; string Name_pairs::read_names() { string name; cout << "Enter name: "; cin >> name; names.push_back(name); return name; } double Name_pairs::read_ages() { double age; cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; return age; } void Name_pairs::print() { for(int i = 0; i < (names.size()-1) && i < (ages.size()-1); ++i) cout << names[i] << " , " << ages[i] << endl; } bool Name_pairs::test() { if(ages.empty() || names.empty()) return true; if(ages.back() = 0 || names.back() == "0"){ return false;} return true; } int main() { Name_pairs np; cout << "Enter names and ages. Use 0 to cancel.\n"; bool finished = false; while(!finished){ finished |= "0" == np.read_names(); finished |= 0 == np.read_ages();} np.print(); keep_window_open(); } ```
If you change the problem and view it upside down it becomes quite simple. Change your setter methods to actually return the value that was just entered. I also made age a local variable of the method to prevent side effects from creeping : ``` Double Name_pairs::read_ages() { Double age; cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; return age; } ``` Then in the loop you can test directly for the returned value : ``` bool finished = false; while(!finished) { finished = finished || "0" == np.read_names(); finished = finished || 0 == np.read_ages(); } ``` Since you are setting your exit condition in the main (type 0 to exit) it is preferable to test the exit condition there for consistency. Is how I see it anyway... code is shorter and easier to understand --- Edit I changed the code to reflects comments aem. This way the correct logical operator is used. As for the cascading evaluation it is quite true that if the first answer was 0 then the second question will not even be asked (finished evaluated to true thus the rest of the or statement will not be evaluated) and as such you must be careful of this (if for example you expect both Vectors to always have the same length). However I found that usability wise since the user already stated that he wanted to exit I saw no use in asking him the other question.
Well you could simply make each function return a bool, then in the loop check if the function returned false. If so break. You could also throw an error from within the functions, catch it externally and handle it appropriately but I think this is a little extreme. I get the impression you are just looking for an 'exit code' type thing. If this is the case I would suggest simply returning a bool and checking whether you should break out of the loop. **Edit:** So your updated code seems a little complicated, but this is what I was getting at as far as returning a bool goes: ``` void Name_pairs::read_names() { cout << "Enter name: "; cin >> name; names.push_back(name); } bool Name_pairs::read_ages() { cout << "Enter corresponding age: "; cin >> age; if ( age == 0 ) return false; ages.push_back(age); cout << endl; return true; } // Now we can test if its time to break. while ( true ) { np.read_names(); if ( !np.read_ages() ) break; } ```
Possible to break a loop when outside of it?
[ "", "c++", "" ]
I've seen people use `size_t` whenever they mean an unsigned integer. For example: ``` class Company { size_t num_employees_; // ... }; ``` Is that good practice? One thing is you have to include `<cstddef>`. Should it be `unsigned int` instead? Or even just `int`? Just using `int` sounds attractive to me since it avoids stupid bugs like these (because people do often use `int`): ``` for(int i = num_employees_ - 1; i >= 0; --i) { // do something with employee_[i] } ```
`size_t` may have different size to `int`. For things like number of employees, etc., this difference usually is inconsequential; how often does one have more than 2^32 employees? However, if you a field to represent a file size, you will want to use `size_t` instead of `int`, if your filesystem supports 64-bit files. Do realise that object sizes (as obtained by `sizeof`) are of type `size_t`, not `int` or `unsigned int`; also, correspondingly, there is a `ptrdiff_t` for the difference between two pointers (e.g., `&a[5] - &a[0] == ptrdiff_t(5)`).
Using size\_t in many situations helps with portability. size\_t isn't always "unsigned int", but it is always the size that can represent the largest possible object on the given platform. For instance, some platforms have a 16-bit integer size, but use 32-bit pointers. In that case if you use unsigned int for the size of something you'll be restricting it to 65,536 bytes (or other elements) even though the platform can handle something much larger. In your example I would probably use a typedef for a 32-bit or 64-bit unsigned integer rather than using int or unsigned int or size\_t.
Is it good practice to use size_t in C++?
[ "", "c++", "types", "" ]
This piece of code compiles and runs as expected on GCC 3.x and 4.x: ``` #include <stdio.h> typedef union buggedUnion { public: // 4 var init constructor inline buggedUnion(int _i) { i = _i; } friend inline const buggedUnion operator - (int A, const buggedUnion &B) { return buggedUnion(A - B.i); } friend inline const buggedUnion operator - (const buggedUnion &A, const buggedUnion &B) { return buggedUnion(A.i - B.i); } int i; } buggedUnion; int main() { buggedUnion first(10); buggedUnion second(5); buggedUnion result = 10 - (first - second); printf("%d\n", result.i); // 0 return 0; } ``` MSVC, however, will not compile that code, complaining: ``` main.cpp(60) : error C3767: '-': candidate function(s) not accessible could be the friend function at 'main.cpp(41)' : '-' [may be found via argument-dependent lookup] or the friend function at 'main.cpp(45)' : '-' [may be found via argument-dependent lookup] main.cpp(60) : error C2676: binary '-' : 'buggedUnion' does not define this operator or a conversion to a type acceptable to the predefined operator ``` Which of the compilers is correct? How can this be resolved? I'm trying to achieve clean code (no *outside* friend methods) while maintaining portability, flexibility and self-documenting code. **Some notes:** * This is a **test-case** to show the problem, the original data-type is much more sophisticated and carefully designed, albeit not working in MSVC (main compiler is GCC, though MSVC compatibility is also desired). * Adding 'public:' at the start of the union declaration does not resolve it. * Adding 'public:' before each operator does not resolve it * Converting the test case to a struct/class *does* fix it, but this is not desired (Please no flames, I got reasons. Most of them are limitations of the C++ language) * Operator method is to be left at *global scope* (not a member function) Optimal solution would not rely on moving the declaration outside of the union definition for aestetic reasons (over 24 different combinations of operators and operands), but will be done if there is no other solution.
It is difficult to say which one is right, since unnamed `struct`s are not allowed by the standard (although they are a common extension), and as such the program is ill-formed. **Edit**: It does seem to be a bug in msvc, since the following code, which is perfectly valid, fails to compile. ``` union buggedUnion { friend buggedUnion operator - (int A, const buggedUnion &B) { return B; } friend buggedUnion operator - (const buggedUnion &A, const buggedUnion &B) { return A; } int i; }; int main() { buggedUnion first = { 1 }; buggedUnion second = { 1 }; buggedUnion result = 3 - (first - second); } ``` You can work around this by defining the functions outside the class. ``` union buggedUnion { int i; }; buggedUnion operator - (int A, const buggedUnion &B) { return B; } buggedUnion operator - (const buggedUnion &A, const buggedUnion &B) { return A; } ``` You can even retain the friend status by declaring the functions inside the class (but still defining them outside), but I doubt you'd ever need that in a union. Note that I removed the unnecessary `typedef` and `inline`s.
You need to declare those friend function in the enclosing scope, as once you declare them within the class, they're no longer visible in the external scope. So either move the function body out of the class as avakar said, or keep them in the class and add the following line to reintroduce the name into the enclosing scope: ``` extern const buggedUnion operator-(const buggedUnion& A, const buggedUnion&B); int main() { ...etc ``` Hope this helps. Not sure whether it's a bug but it appears (?) to me to be correct behavior, now implemented correctly, which many compilers used to interpret differently. See: --ffriend-injection in <http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html>.
MSVC: union vs. class/struct with inline friend operators
[ "", "c++", "visual-c++", "struct", "unions", "" ]
``` <div class="item"> <p><img src="images/photos_sample1.jpg" border="0" rel="images/google_map.jpg"></p> <p>Dining Area</p> </div> <div class="item"> <p><img src="images/photos_sample2.jpg" border="0" rel="images/sample_photo.jpg"></p> <p>Pool Area</p> </div> ``` I have the above HTML code and I want to get the `rel` attribute's value when I click the image. I wrote this jQuery script, but it doesn't seem to work: ``` $('div.item').click(function() { var getvalue = $('this > p > img').attr('rel'); alert(getvalue); }); ```
Replace this: ``` var getvalue = $('this > p > img').attr('rel'); ``` With this: ``` var getvalue = $(this).find('p > img').attr('rel'); ``` As it is right now you are doing a global search for elements with the literal tag name `this` An equivalent code would also be: ``` var getvalue = $('p > img', this).attr('rel'); ``` Although by the looks of it the items are image/caption combinations and you wouldn't really expect other images, in which case it is better to just do: ``` var getvalue = $(this).find('img').attr('rel'); ``` Or maybe give it a descriptive class and replace `img` with `img.someclassname` - this would make it so that if you edit your HTML later on your Javascript doesn't break because of your specific selector. Furthermore, you could just bind the click event to the images themselves: ``` $('div.item img').click(function() { var getvalue = $(this).attr('rel'); }); ```
``` $('div.item').click(function() { var getvalue = $(this).find('> p > img').attr('rel'); alert(getvalue); }); ```
How to get the attr with jQuery?
[ "", "javascript", "jquery", "attributes", "" ]
in my [previous](https://stackoverflow.com/questions/1109446/c-generate-gaussian-distribution) post I was asking how to generate numbers following a normal distribution. Since I have also other distributions to generate and I saw 3 libraries might provide them ([GSL](http://www.gnu.org/software/gsl/manual/html_node/Random-Number-Distributions.html), TechnicalReport1(doc link?), [Boost](http://www.boost.org/doc/libs/1_39_0/libs/libraries.htm#Math)), I was wondering which one you would choose. As a side note: the reference platform for my application is a GNU/Linux system and performance is a matter.
Here are some notes on getting started with [random number generation using C++ TR1](http://www.johndcook.com/cpp_TR1_random.html).
Take Boost it is quite popular and well designed for C++. GSL is very good library that gives tools far behind distributions, but it is covered by GPL (not LGPL) meaning that if you want to develop non-GPL applications and distribute them, you can't.
C++: TR1 vs GSL vs Boost for statistical distributions?
[ "", "c++", "random", "" ]
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > Traceback (most recent call last): > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
Because you did `from os import *`, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error.
Don't do `import * from wherever` without a good reason (and there aren't many). Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do `import os` then call `os.open(....)`. Whichever open you want to call, read the documentation about what arguments it requires.
An integer is required? open()
[ "", "python", "file-io", "integer", "argv", "" ]
I'm looking for a way to append elements with javascript using javascript. Basically I have two lists of items. One has a list of items with an "ADD" button (using "link\_to\_remote") and the other has a list of items with a "REMOVE" button (using "link\_to\_remote"). When I click the "ADD" it immediately places the item into the other list. However, I need to be able to have the newly inserted item perform the reverse action for "REMOVE". I see no way (besides, perhaps creating a partial to render a non-object) to dynamically generate dynamic items of this nature.
Have you checked out [jQuery](http://jquery.com/)? It is a popular JavaScript library. It can do exactly what you described with ease. I've used it for years and it's never let me down. [This page of the documentation](http://docs.jquery.com/Manipulation/appendTo#selector) shows the `append()` method. You can do stuff like... ``` $("span").appendTo("#foo"); ``` The `$("span")` part is finding an element (or elements) of the DOM, then the `appendTo("#foo")` part is appending it to another element of the DOM. You can also append arbitrary snippets of HTML. If needed, such a snippet could be retrieved via an AJAX request. jQuery has really simple and reliable AJAX support. With jQuery, the basic concept is that you bind JavaScript methods to DOM elements in a separate `.js` file, rather than using HTML "`on_this`" or "`on_that`" attibutes. So if you used jQuery for this situation, you wouldn't think in terms of generating JS code through templates. The `add()` and `remove()` functions would be in your `.js` file ready to go and you would bind and unbind them to DOM elements as needed. For example, when you added an `li` to the list, you'd unbind your `add()` function from the `li` and bind the `remove()` function to it.
This can be fairly easy. There are a bunch of things doing this for you (check out jquery). I handcoded something a while ago (sorry for the poorly written code). It adds and remove tracks from a playlist **controller:** ``` def add_track unless session[:admin_playlist_tracks].include?(params[:recording_id]) session[:admin_playlist_tracks] << params[:recording_id] end render :partial => "all_tracks" end def remove_track session[:admin_playlist_tracks].delete_if {|x| x.to_s == params[:recording_id].to_s } render :partial => "all_tracks" end ``` **container:** ``` <div id="artist_recordings" class="autocomplete_search"></div> ``` **Adding stuff:** ``` <%= link_to_remote "Add", :url => {:controller => :playlists, :action => :add_track, :recording_id => recording.id}, :update =>"all_tracks", :complete => visual_effect(:highlight, 'all_tracks') %> ``` Displaying / removing stuff: ``` <%session[:admin_playlist_tracks].each do |recording_id|%> <div style="margin-bottom:4px;"> [<%=link_to_remote "Remove", :url => {:controller => :playlists, :action => :remove_track, :recording_id => recording_id}, :update =>"all_tracks"%>] <%recording = Recording.find_by_id(recording_id)%> <%=recording.song.title%> <br /> by <%=recording.artist.full_name%> (<%=recording.release_year%>) </div> <%end%> ``` This worked with me because I could use session variable. But be careful! In some cases where a user will have various windows with the same form, this will surely break since there will be concurrent access on the session variable. There are some parts missing because I'm doing some autocomplete on this as well, but I hope this will help you get the big idea.
How do I generate dynamic items dynamically?
[ "", "javascript", "ruby-on-rails", "dynamic", "rails-generate", "" ]
How can I add key value pairs to an array? This won't work: ``` public function getCategorieenAsArray(){ $catList = array(); $query = "SELECT DISTINCT datasource_id, title FROM table"; if ($rs=C_DB::fetchRecordset($query)) { while ($row=C_DB::fetchRow($rs)) { if(!empty($row["title"])){ array_push($catList, $row["datasource_id"] ."=>". $row["title"] ); } } } return($catList); } ``` Because it gives me: ``` Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 ) ``` And I expect: ``` Array ( [1] =>Categorie 1 [5] => Categorie 2 ) ```
Use the [square bracket syntax](http://docs.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying): ``` if (!empty($row["title"])) { $catList[$row["datasource_id"]] = $row["title"]; } ``` `$row["datasource_id"]` is the key for where the value of `$row["title"]` is stored in.
``` $data =array(); $data['user_code'] = 'JOY' ; $data['user_name'] = 'JOY' ; $data['user_email'] = 'joy@cargomar.org'; ```
How can I create an array with key value pairs?
[ "", "php", "arrays", "" ]
And if so, under what circumstances? Javadoc and JPA spec says nothing.
You are right. JPA specification says nothing about it. But **Java Persistence with Hibernate book, 2nd edition**, says: > If the query result is empty, a null is returned Hibernate JPA implementation (Entity Manager) return null when you call query.getResultList() with no result. **UPDATE** As pointed out by some users, it seems that a newest version of Hibernate returns an empty list instead. An empty list is returned in Eclipselink as well when no results are found.
If the specs said it could't happen, would you belive them? Given that your code could conceivably run against may different JPA implementations, would you trust every implementer to get it right? No matter what, I would code defensively and check for null. Now the big question: should we treat "null" and an empty List as synonymous? This is where the specs should help us, and don't. My guess is that a null return (if indeed it could happen) would be equivalent to "I didn't understand the query" and empty list would be "yes, understood the query, but there were no records". You perhaps have a code path (likely an exception) that deals with unparsable queries, I would tend to direct a null return down that path.
Can javax.persistence.Query.getResultList() return null?
[ "", "java", "hibernate", "jpa", "" ]
I need a function to determine if a directory is a mount point for a drive. I found this code already which works well for linux: ``` def getmount(path): path = os.path.abspath(path) while path != os.path.sep: if os.path.ismount(path): return path path = os.path.abspath(os.path.join(path, os.pardir)) return path ``` But I'm not sure how I would get this to work on windows. Can I just assume the mount point is the drive letter (e.g. C:)? I believe it is possible to have a network mount on windows so I'd like to be able to detect that mount as well.
Windows didn't use to call them "mount points" [**edit**: it now does, see below!], and the two typical/traditional syntaxes you can find for them are either a drive letter, e.g. `Z:`, or else `\\hostname` (with two leading backslashes: escape carefully or use `r'...'` notation in Python fpr such literal strings). **edit**: since NTFS 5.0 mount points are supported, but according to [this post](http://brainrack.wordpress.com/2008/05/28/broken-and-ill-documented-api-for-windows-mount-points/) the API for them is in quite a state -- "broken and ill-documented", the post's title says. Maybe executing the microsoft-supplied [mountvol.exe](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/mountvol.mspx?mfr=true) is the least painful way -- `mountvol drive:path /L` should emit the mounted volume name for the specified path, or just `mountvol` such list all such mounts (I have to say "should" because I can't check right now). You can execute it with `subprocess.Popen` and check its output.
Do you want to find the mount point or just determine if it is a mountpoint? Regardless, as commented above, it is possible in WinXP to map a logical drive to a folder. See here for details: <http://www.modzone.dk/forums/showthread.php?threadid=278> I would try win32api.GetVolumeInformation ``` >>> import win32api >>> win32api.GetVolumeInformation("C:\\") ('LABEL', 1280075370, 255, 459007, 'NTFS') >>> win32api.GetVolumeInformation("D:\\") ('CD LABEL', 2137801086, 110, 524293, 'CDFS') >>> win32api.GetVolumeInformation("C:\\TEST\\") # same as D: ('CD LABEL', 2137801086, 110, 524293, 'CDFS') >>> win32api.GetVolumeInformation("\\\\servername\\share\\") ('LABEL', -994499922, 255, 11, 'NTFS') >>> win32api.GetVolumeInformation("C:\\WINDOWS\\") # not a mount point Traceback (most recent call last): File "<stdin>", line 1, in <module> pywintypes.error: (144, 'GetVolumeInformation', 'The directory is not a subdirectory of the root directory.') ```
Python: Get Mount Point on Windows or Linux
[ "", "python", "windows", "linux", "operating-system", "mount", "" ]
Lets say i have the following c# classes: ``` abstract class a { protected abstract void SomeMethod(); } abstract class b : a { protected abstract override void SomeMethod(); } class c : b { protected override void SomeMethod() { } } ``` Is there actually any point in overriding the method in b when it could just as easily be writen as: ``` abstract class b : a { } ``` What would be the "prefered" way of writting b? And if there is no point overriding an abstract method or property why is it allowed?
One reason you might want to allow it: it shows intent. It explains that yes, you know this method is abstract in the base class. I know that, and I *still* want it to be abstract here. That way, if the base class removes the method, your abstract class will fail to compile, rather than only the concrete class (which may not even be in your code). That said, it's not a particularly important reason... I'd normally leave it out.
Additional to the already said: `override` could also be used to **declare attributes** that are not defined in the base class. If still not having an implementation, it will be an abstract override. ``` abstract class b : a { [SomeAttribute] protected abstract override void SomeMethod(); } ```
.net abstract override quirk
[ "", "c#", ".net", "" ]
How can I get this to compile? The error is when I start using boost::ref(). I thought boost::ref is used to pass reference to C++ algorithm classes? ``` list<Object> lst; lst.push_back(Object(1,2.0f)); lst.push_back(Object(3,4.3f)); struct between_1_and_10 { int d; void operator() (Object& value) { value.a += 5; value.b -= 3.3f; cout << d << endl; d += value.a; } }; between_1_and_10 val; val.d = 4; for_each(lst.begin(), lst.end(), boost::ref(val)); // Problem is here printf("rg"); ``` **EDIT** Here's the compiler error as people suggested: ``` 1>c:\program files (x86)\microsoft visual studio 9.0\vc\include\algorithm(29) : error C2064: term does not evaluate to a function taking 1 arguments 1> c:\users\swangrun\desktop\minescout work\feat-000-gettargetimages\minescouttest\maintest.cpp(102) : see reference to function template instantiation '_Fn1 std::for_each<std::list<_Ty>::_Iterator<_Secure_validation>,boost::reference_wrapper<T>>(_InIt,_InIt,_Fn1)' being compiled 1> with 1> [ 1> _Fn1=boost::reference_wrapper<main::between_1_and_10>, 1> _Ty=Object, 1> _Secure_validation=true, 1> T=main::between_1_and_10, 1> _InIt=std::list<Object>::_Iterator<true> 1> ] ```
This what you really want: ``` for_each(lst.begin(), lst.end(), boost::bind<void>(boost::ref(val),_1 ) ); ``` EDIT: Some explanation upon the OP's request. Recall that for\_each() takes a function, but you were merely passing it a reference to your struct (yes, the struct has it's operator() overloaded but you were not passing that). bind() basically "exposes" the function inside your struct. EDIT2: Explanation of the "\_1" can be found in the comments below.
[`boost::reference_wrapper`](http://www.boost.org/doc/libs/1_39_0/doc/html/boost/reference_wrapper.html) (which is what `boost::ref` returns) does not overload `operator()`. You can use it with `boost::bind`, which has special treating for it (not using `ref` would make `bind` copy the provided function object). But `for_each` returns the function object it invokes the stuff on. So just do this ``` between_1_and_10 val; val.d = 4; val = for_each(lst.begin(), lst.end(), val); printf("rg"); ``` It will call the stuff on the copied `val`, and return the function object as it's after the last invocation. --- Just to tell you where you might use `boost::ref`, because you seem to misuse it. Imagine a template that takes its parameter by value, and calls another function: ``` void g(int &i) { i++; } template<typename T> void run_g(T t) { g(t); } ``` If you now want to call it with a variable, it will copy it. Often, that's a reasonable decision, for example if you want to pass data to a thread as start parameters, you could copy it out of your local function into the thread object. But sometimes, you could want not to copy it, but to actually pass a reference. This is where `boost::reference_wrapper` helps. The following actually does what we expect, and outputs `1`: ``` int main() { int n = 0; run_g(boost::ref(n)); std::cout << n << std::endl; } ``` For binding arguments, a copy is a good default. It also easily makes arrays and functions decay to pointers (accepting by reference would make `T` be possibly an array/function-type, and would cause some nasty problems).
Using Boost::ref correctly..?
[ "", "c++", "boost", "" ]
I am looking for a .net class to deal with logging various information to a file. The logger should have timestamps, categories for the logged data (to be able to differentiate between notificiation and errors), severity levels for errors, to be able to split the log file after it exceeds a certain size.
[Enterprise Library](http://entlib.codeplex.com/) Logging Application Block.
I suggest you use the open source [log4net](http://logging.apache.org/log4net/index.html)
File logger in C#
[ "", "c#", ".net", "file", "logging", "" ]
I believe the answer is **no**. And am looking for a **counter example** to show that order of output is not guaranteed, absent an order by clause. consider: ``` create table #order (orderId int primary key clustered , customerId int not null -- references customer(customerId) , orderDateTIme datetime not null) insert into #order values (1, 100, '2009-01-01') insert into #order values (2, 101, '2009-01-02') insert into #order values (3, 102, '2009-01-03') insert into #order values (4, 103, '2009-01-04') insert into #order values (5, 100, '2009-01-05') insert into #order values (6, 101, '2009-01-06') insert into #order values (7, 101, '2009-01-07') insert into #order values (8, 103, '2009-01-08') insert into #order values (9, 105, '2009-01-09') insert into #order values (10, 100, '2009-01-10') insert into #order values (11, 101, '2009-01-11') insert into #order values (12, 102, '2009-01-12') insert into #order values (13, 103, '2009-01-13') insert into #order values (14, 100, '2009-01-14') insert into #order values (15, 100, '2009-01-15') insert into #order values (16, 101, '2009-01-16') insert into #order values (17, 102, '2009-01-17') insert into #order values (18, 101, '2009-01-18') insert into #order values (19, 100, '2009-01-19') insert into #order values (20, 101, '2009-01-20') select * from #order -- Results in PK order due to clustered primary key select orderId, CustomerId, orderDateTime , row_number() over (partition by customerId order by orderDateTime) RN from #order ``` On MS SQL Server 2005, the output ordering has two properties: 1. The rows for each `customerId` are contiguous in the output. 2. `Row_number()` is sequential within each customerId. My understanding is that these two properties are not guaranteed absent an explicit order by clause. I am looking for an example where the above properties do not hold that is not forced by an order by clause, but is just a result of how MS SQL Server happens to work. Feel free to develop own table definition, indexes, etc in your example if needed. Or if I am wrong, a link to a reference that would show that these orderings are guaranteed, even without an explicit order by clause.
If you want an ordered result set, **add an ORDER BY clause to your SELECT**. Period. Anything else is circumstantial and may or may not work depending on the current SQL build you're testing, the day's mood of the optimizer and the phase of Mars transit in Pisces. A trivial example that contradicts your assumption: ``` select orderId, CustomerId, orderDateTime , row_number() over (partition by customerId order by orderDateTime) RN , row_number() over (partition by orderDateTime order by customerId) AntiRN from #order ```
Im struggling to find the relevance here; if you want explicit ordering the recommended way would be to use an ORDER BY clause in the query. I would *never* rely on the default ordering of a table when producing a query that I relied on the order of the results. Any modern RDBMS is going to be able to optimize an order by based on indexes and the like, so it's not something that has to be worried about. In regards to row\_number, while it is a side effect that if no ORDER BY clause exists, the output is ordered by the ROW\_NUMBER value, you **cannot** depend on this behavior, as it is not guaranteed. Again, the *only* way to guarantee order of the output is with an ORDER BY clause.
Can I depend on order of output when using row_number()
[ "", "sql", "sql-server", "t-sql", "" ]
I want to build a survey which has about 20 questions. All questions are in the same page. The structure of whole survey is like the tree structure. Initially, only one question is shown in the page. if user chooses option 1,2 of question 1, the survey ends. if user chooses option 3,4,5 of question 1, then question 2 appears. if user chooses option 1,2,6 of question 2, then question 3 appears, otherwise go to question 12. if user chooses 1,2 of question 3, go to question 5, otherwise go to question 4. .... It's quite troublesome to switch questions (using display:none and display:block) by javascript when there are lots of questions. What is the simplest way in this situation? Following code is written according to JacobM's anwer. Another problem appears. I need to hide and show another question if user chooses another options. option 1 of 2a -> show q12 option 4 of 2a -> show q3 and hide q12 option 1 of q3 -> show q4 option 1 of 2a -> show q12, hide q3 and q4 <--- this situation is quite complex What should I do? ``` var responses = { 1 : {1:'end', 2:'end', 3:2, 4:2, 5:2, 6:2}, '2a': {1:12,2:12,3:3,4:3,5:3,6:12} }; function handleResponse(question, key) { option = question.selectedIndex+1; var next = responses[key][option]; if (next=='end') return; showQuestion(next); } function showQuestion(question){ $('tr[id^=trQ'+question+']').show(); } ```
First of all, definitely use a javascript framework. I like jQuery, but there are many good ones. Secondly, figure out a way to store the set of appropriate actions as some type of abstraction, ratther than trying to code each rule. For example, you said > if user chooses option 1,2 of question > 1, the survey ends. if user chooses > option 3,4,5 of question 1, then > question 2 appears. You could encode this into a heirarchy of objects as ``` var responses = { 1: {1:'end', 2:'end', 3:2, 4:2, 5:2}, 2:{ //and the mappings here for the various responses for question 2} ...etc. } ``` Then you need a function to turn the current question and response into an action. ``` function handleResponse( question, option ) { var next = responses[question][option]; if (next='end') return;//or however you want to handle being done. showQuestion(next); } ``` Then you just need a showQuestion function that willl take '2' and show question 2 (trivial with jQuery). If there are particular responses that are quite complex, you could allow the value in the map to be a function. Thus you could have ``` 2:{1:function(){show(3);hide(6);hide(14)}, 2:5, etc.} ``` and then add to your handle response method (after if (next='end)...) ``` if (jQuery.isFunction(next)) next; ```
Most surveys I've seen do this server-side, not client-side, using an interface similar to a [wizard](http://en.wikipedia.org/wiki/Wizard_%28software%29).
Options show step by step based on users' choices
[ "", "javascript", "jquery", "" ]
I need to read the output from ffmpeg in order to even try the solution to [my question from yesterday](https://stackoverflow.com/questions/1106955/php-and-ffmpeg-performing-intelligent-video-conversion). This is a separate issue from my problem there, so I made a new question. How the heck do I get the output from an `ffmpeg -i` command in PHP? This is what I've been trying: ``` <?PHP error_reporting(E_ALL); $src = "/var/videos/video1.wmv"; $command = "/usr/bin/ffmpeg -i " . $src; echo "<B>",$command,"</B><br/>"; $command = escapeshellcmd($command); echo "backtick:<br/><pre>"; `$command`; echo "</pre><br/>system:<br/><pre>"; echo system($command); echo "</pre><br/>shell_exec:<br/><pre>"; echo shell_exec($command); echo "</pre><br/>passthru:<br/><pre>"; passthru($command); echo "</pre><br/>exec:<br/><pre>"; $output = array(); exec($command,$output,$status); foreach($output AS $o) { echo $o , "<br/>"; } echo "</pre><br/>popen:<br/><pre>"; $handle = popen($command,'r'); echo fread($handle,1048576); pclose($handle); echo "</pre><br/>"; ?> ``` This is my output: ``` <B>/usr/bin/ffmpeg -i /var/videos/video1.wmv</B><br/> backtick:<br/> <pre></pre><br/> system:<br/> <pre></pre><br/> shell_exec:<br/> <pre></pre><br/> passthru:<br/> <pre></pre><br/> exec:<br/> <pre></pre><br/> popen:<br/> <pre></pre><br/> ``` I don't get it. `safe_mode` is off. There's nothing in `disable_functions`. The directory is *owned* by `www-data` (the apache user on my Ubuntu system). I get a valid status back from `exec()` and `system()` and running the same command from the command line give me tons of output. I feel like I must be missing something obvious but I have no idea what it is.
The problem is you catch only *stdout* and not *stderr* (see [*Standard Streams*](http://en.wikipedia.org/wiki/Standard_streams)). Change this line: ``` $command = "/usr/bin/ffmpeg -i " . $src; ``` into ``` $command = "/usr/bin/ffmpeg -i " . $src . " 2>&1"; ``` and give it another try :)
Use ffprobe instead, it's much quicker and supports JSON output. ``` $output = shell_exec('ffprobe -v quiet -print_format json -show_format -show_streams "path/to/yourfile.ext"'); $parsed = json_decode($output, true); ``` And you have all your video info in a php array! This is much faster than ffmpeg -i for some reason.
Capture FFMPEG output
[ "", "php", "ffmpeg", "exec", "" ]
I am looking for the **init**.py file for django. I tried whereis and find, but I get a lot of dirs.
you can just print it out. ``` >>> import django >>> print django.__file__ /var/lib/python-support/python2.5/django/__init__.pyc >>> ``` or: ``` import inspect import django print inspect.getabsfile(django) ```
This (or something like this) also works when you are searching for files in other packages: ``` $ dpkg -L python-django | grep __init__.py ```
where does django install in ubuntu
[ "", "python", "django", "ubuntu", "" ]
[This example](http://bytes.com/groups/net-xml/177700-how-do-i-serialize-object-string-instead-stream) uses a `StringWriter` to hold the serialized data, then calling `ToString()` gives the actual `string` value: ``` Person john = new Person(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person)); StringWriter stringWriter = new StringWriter(); xmlSerializer.Serialize(stringWriter, john); string serializedXML = stringWriter.ToString(); ``` Is there any easier/Cleaner way to do this? All of the `Serialize()` overloads seem to use a `Stream` or Writer. **UPDATE:** Asked a similar question about [serializing an IEnumerable via an Extension Method](https://stackoverflow.com/questions/1138667/extension-method-for-serializing-an-ienumerablet-object-to-a-string-array) .
Fun with extension methods... ``` var ret = john.ToXmlString() ``` --- ``` public static class XmlTools { public static string ToXmlString<T>(this T input) { using (var writer = new StringWriter()) { input.ToXml(writer); return writer.ToString(); } } public static void ToXml<T>(this T objectToSerialize, Stream stream) { new XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize); } public static void ToXml<T>(this T objectToSerialize, StringWriter writer) { new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize); } } ```
More or less your same solution, just using an extension method: ``` static class XmlExtensions { // serialize an object to an XML string public static string ToXml(this object obj) { // remove the default namespaces XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); // serialize to string XmlSerializer xs = new XmlSerializer(obj.GetType()); StringWriter sw = new StringWriter(); xs.Serialize(sw, obj, ns); return sw.GetStringBuilder().ToString(); } } [XmlType("Element")] public class Element { [XmlAttribute("name")] public string name; } class Program { static void Main(string[] args) { Element el = new Element(); el.name = "test"; Console.WriteLine(el.ToXml()); } } ```
Can I Serialize XML straight to a string instead of a Stream with C#?
[ "", "c#", "xml-serialization", "" ]
I need to learn RegEx but don't have time to figure this out right now. -- So I'm attempting exploit the community's capabilities. I have a string containing a list of acceptable 1-character comment variables. ``` String comments = "#;"; ``` And I want: ``` String[] parsedComments = {"#", ";"}; ``` What RegEx string will solve my problems? ``` String[] parsedComments = comments.split(/* "???" */); ```
First, why do you need to break them into an array? A String has almost the exact same methods available to getting chars at indexes and virtually the same performance. But, to answer your question: ``` string.split(""); ``` This will give you an extra empty string at the first pos of the resulting array.
Why do you want to use a regex? Try [String.toCharArray()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#toCharArray()) for example.
How do I use regex to split a string into characters?
[ "", "java", "regex", "" ]
I have the following scenario. The client code only has access to FooHandler, not directly to Foo instances. ``` public delegate void FooLoaded(object sender, EventArgs e); class Foo { public event FooLoaded loaded; /* ... some code ... */ public void Load() { load_asynchronously(); } public void callMeWhenLoadingIsDone() { loaded(this,EventArgs.Empty); } } class FooHandler { public event FooLoaded OneFooLoaded; /* ... some code ... */ public void LoadAllFoos() { foreach (Foo f in FooList) { f.loaded += new FooLoaded(foo_loaded); f.Load(); } } void foo_loaded(object sender, EventArgs e) { OneFooLoaded(this, e); } } ``` Then the clients would use the OneFooLoaded event of the FooHandler class to get notifications of loading of foos. Is this 'event chaining' the right thing to do? Are there any alternatives? I don't like this (it feels wrong, I cannot precisely express why), but if I want the handler to be the point of access I don't seem to have many alternatives.
If it feels wrong because events are more sophisticated and outward-facing than necessary for your internal communications (which I believe is at least partially true considering events can call multiple clients whereas you know you only need to notify one, right?), then I propose the following alternative. Instead of using events to communicate the completion of Foo to FooHandler, since Foo is internal anyway, you could add a callback parameter to the constructor or Load method of Foo, which Foo can call when it is done loading. This parameter can be just a function if you only have one callback, or it can be an interface if you have many. Here's how I think your code would look with the simplified internal interface: ``` public delegate void FooLoaded(FooHandler sender, EventArgs e); class Foo { Action<Foo> callback; /* ... some code ... */ public void Load(Action<Foo> callback) { this.callback = callback; load_asynchronously(); } public void callMeWhenLoadingIsDone() { callback(this); } } class FooHandler { public event FooLoaded OneFooLoaded; /* ... some code ... */ public void LoadAllFoos() { foreach (Foo f in FooList) { f.Load(foo_loaded); } } void foo_loaded(Foo foo) { // Create EventArgs based on values from foo if necessary OneFooLoaded(this, null); } } ``` Notice that this also allows you to be more strongly typed with the FooLoaded delegate. If, on the other hand, it feels wrong because the event shouldn't have to go through FooHandler to get to the client, then 1) I would dispute that because if the client doesn't want to deal with the individual Foo objects, it shouldn't be sinking events from them at that level either, and 2) If you really wanted to do that, you could implement some public callback interface on Foo even though Foo is private, or use a mechanism like Pavel suggested. I think, however, that clients like the simplicity of implementing fewer event handlers and distinguishing the source within the one handler rather than having to connect (and potentially disconnect) events from dozens of smaller objects.
A different way to do it is to create a single point (a single class) in the domain where all events go through. Any classes using the domain would hook up to that class, which has a list of static events and any internal class event in the domain would be listened to by this class, thereby avoiding event chaining in the domain at least. References: * [Udi Dahan with code examples on domain events](http://www.udidahan.com/2008/08/25/domain-events-take-2/) * [Martin Fowler more general on domain events](http://www.martinfowler.com/eaaDev/DomainEvent.html)
what's the best way to implement chained events in C#
[ "", "c#", ".net", "events", "" ]
I really need an easy to use build tool which supports multiple languages with strong Java support. I have tried Scons but found the Java support lacking. Is there anything else out there? I'm not excited about learning yet another build tool. Also, I really don't want a build tool which is difficult to use without an IDE since I use emacs and will be writing the build scripts by hand. Edit: When I said general purpose I meant a build tool that works with many languages. I'd like to save myself the time spent learning a new build system for every languages I use.
<http://ant.apache.org/> Here is how to do C++ projects with Ant: <http://www.codemesh.com/products/junction/doc/ant_cpp.html> Or <http://ant-contrib.sourceforge.net/cpptasks/index.html>
[Ant](http://ant.apache.org/), [Maven](http://maven.apache.org/), and [Gradle](http://gradle.org/) all are designed for building Java applications. EDIT: Let me expound.... Ant is a really good option. As the first very good open source java build system, it has grown to be a popular and widespread option. Most anything you will do in a typical java system has been done through Ant. You can find sample after sample and great tutorials on learning this. Now, just because it can handle everything doesn't mean it's quick and painless. There's a lot of 'boilerplate' build.xml that you almost certainly will be writing. Also, there is no dependency management. Enter Maven -- Dependency management is handled very well here. Merely specify the name of the jar(s) that your project depends on and it will ensure that you have the appropriate version. Also, the help and tutorials available are very good and you can be up and building in [5 minutes](http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html). Gradle -- this is a newer build system, built to take out most of the pain points and boilerplate code. This is a great option if you are interested in using/learning Groovy!
General purpose build tool with good Java support?
[ "", "java", "build", "" ]
I'm writing a program where the user inputs names and then ages. The program then sorts the list alphabetically and outputs the pairs. However, I'm not sure how to keep the ages matched up with the names after sorting them alphabetically. All I've got so far is... Edit: Changed the code to this - ``` #include "std_lib_facilities.h" struct People{ string name; int age; }; int main() { vector<People>nameage; cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n"; People name; People age; while(name != "0"){ cin >> name; nameage.push_back(name); cin >> age; nameage.push_back(age);} vector<People>::iterator i = (nameage.end()-1); nameage.erase(i); } ``` I get compiler errors for the != operator and the cin operators. Not sure what to do.
Rather than two vectors (one for names, and one for ages), have a vector of a new type that contains both: ``` struct Person { string name; double age; }; vector<Person> people; ``` --- **edit for comments:** Keep in mind what you're now pushing onto the vector. You must push something of type Person. You can do this in a couple of ways: Push back a default constructed person and then set the name and age fields: ``` people.push_back(Person()); people.back().name = name; people.back().age = age; ``` Give Person a constructor that takes a name and an age, and push a Person with some values: ``` struct Person { Person(const string& name_, double age_) : name(name_), age(age_) {} string name; double age; }; people.push_back(Person(name, age)); ``` Create a Person, give it some values, and push that into the vector: ``` Person person; person.name = name; person.age = age; people.push_back(person); ``` Or more simply: ``` Person person = { name, age }; people.push_back(person); ``` (thanks avakar)
In addition to the solution posted by jeje and luke, you can also insert the pairs into a `map` (or `multimap`, in case duplicate names are allowed). ``` assert(names.size() == ages.size()); map<string, double> people; for (size_t i = 0; i < names.size(); ++i) people[names[i]] = ages[i]; // The sequence [people.begin(), people.end()) is now sorted ``` Note that using `vector<person>` will be faster if you fill it up only once in advance. `map` will be faster if you decide to add/remove people dynamically.
Trying to keep age/name pairs matched after sorting
[ "", "c++", "" ]
I have long HTTP request ( generating large Excel file - about 60K records or so) which takes like 5 minutes to complete. The wheel with icefaces shows connection is dead and although the file is ready on the server, ICEFaces page is dead and I have to refresh it and can't get the file! How to about extending timeout I tried the following in web.xml but it didn't help: Code - Web.xml: ``` ..... <context-param> <param-name>blockingConnectionTimeout</param-name> <param-value>600000</param-value> </context-param> <context-param> <param-name>synchronousUpdate</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>connectionTimeout</param-name> <param-value>600000</param-value> </context-param> <context-param> <param-name>heartbeatRetries</param-name> <param-value>20</param-value> </context-param> <context-param> <param-name>heartbeatInterval</param-name> <param-value>400000</param-value> </context-param> <context-param> <param-name>heartbeatTimeout</param-name> <param-value>2000000</param-value> </context-param> ..... ``` Any ideas? Thanks, Tam
Seems to be a client timeout! Try async creation with ajax response.
Try setting the buffer size to an increased value to prevent unneccessary handshaking between client/server. ``` <context-param> <param-name>facelets.BUFFER_SIZE</param-name> <param-value>500000</param-value> </context-param> ``` *web.xml* You'll find a lot of positive feedback from people who increased their JSF performance drastically with this little switch. Maybe it will help in your situation, too?
Server Connection dies out with ICEFaces with long request
[ "", "java", "jsf", "icefaces", "" ]
I've got a java application on a windows machine which pins the CPU from time to time. Would like to run a utility to get an idea of how many threads etc that application is creating. Is there such a utility?
I've always been partial to [YourKit](http://www.yourkit.com/). There are lots of others though, both open source and commercial. If you do a google search for "[java profilers](http://www.google.com/search?q=java+profilers)" you should be able to find one to your liking.
[jconsole](http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html) is included with the jdk and includes thread/memory/cpu monitoring
Utility to view threads in a Java process
[ "", "java", "multithreading", "process", "" ]
I would like to have some functionality by which if I write ``` <textarea maxlength="50"></textarea> <textarea maxlength="150"></textarea> <textarea maxlength="250"></textarea> ``` it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery. Note: This can be done if I do something like this: ``` <textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50"> function imposeMaxLength(Event, Object, MaxLen) { return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40)) } ``` Copied from *[What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?](https://stackoverflow.com/questions/451491/what-is-the-best-way-to-emulate-an-html-input-maxlength-attribute-on-an-html-te)* But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.
``` window.onload = function() { var txts = document.getElementsByTagName('TEXTAREA'); for(var i = 0, l = txts.length; i < l; i++) { if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { var func = function() { var len = parseInt(this.getAttribute("maxlength"), 10); if(this.value.length > len) { alert('Maximum length exceeded: ' + len); this.value = this.value.substr(0, len); return false; } } txts[i].onkeyup = func; txts[i].onblur = func; } }; } ```
I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust. Inspired by, but an improvement over Dana Woodman's answer: Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE): ``` // Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting: $('textarea[maxlength]').live('keyup blur', function() { // Store the maxlength and value of the field. var maxlength = $(this).attr('maxlength'); var val = $(this).val(); // Trim the field if it has content over the maxlength. if (val.length > maxlength) { $(this).val(val.slice(0, maxlength)); } }); ``` EDIT: Updated version for [jQuery 1.7+](http://api.jquery.com/live/#entry-longdesc), using `on` instead of `live` ``` // Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting: $('textarea[maxlength]').on('keyup blur', function() { // Store the maxlength and value of the field. var maxlength = $(this).attr('maxlength'); var val = $(this).val(); // Trim the field if it has content over the maxlength. if (val.length > maxlength) { $(this).val(val.slice(0, maxlength)); } }); ```
How to impose maxlength on textArea in HTML using JavaScript
[ "", "javascript", "html", "textarea", "" ]
I'm running JBoss 4.2.3, Java 1.5, and Ubuntu. Before you tell me to post on the JBossWS forum, I already have and there is not a lot of activity over there. I am trying to call a Microsoft Exchange web service end point from a JSF web application. I have written other web service end points and have successfully built clients into my web application. I also use the same code for this client in a stand alone Java application to call the exchange web service and everything works great, but for some reason I am getting this exception in my web app: ``` org.jboss.ws.WSException: Cannot uniquely indentify operation: {http://schemas.microsoft.com/exchang e/services/2006/messages}Subscribe ``` The exception is thrown when the com.microsoft.schemas.exchange.services.\_2006.messages.ExchangeServicePortType subscribe method is called. Relevent part of the exception output: ``` 13:17:15,718 ERROR [STDERR] org.jboss.ws.WSException: Cannot uniquely indentify operation: {http://s chemas.microsoft.com/exchange/services/2006/messages}Subscribe 13:17:15,719 ERROR [STDERR] at org.jboss.ws.metadata.umdm.EndpointMetaData.getOperation(EndpointMet aData.java:417) 13:17:15,719 ERROR [STDERR] at org.jboss.ws.core.CommonClient.getOperationMetaData(CommonClient.jav a:195) 13:17:15,719 ERROR [STDERR] at org.jboss.ws.core.CommonClient.getOperationMetaData(CommonClient.jav a:184) 13:17:15,719 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientImpl.invoke(ClientImpl.java:309 ) 13:17:15,719 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientProxy.invoke(ClientProxy.java:1 72) 13:17:15,719 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientProxy.invoke(ClientProxy.java:1 52) 13:17:15,719 ERROR [STDERR] at $Proxy101.subscribe(Unknown Source) ``` There is also is a bunch of output when the javax.xml.ws.Service object is created: ``` 13:17:13,438 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'The "xml:" Namespace'. 13:17:13,438 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'The "xml:" Namespace'. 13:17:13,438 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'This Version:'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'April 19, 2006'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Description'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'The namespace whose name is'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'http://www.w3.org/XML/1998/namespace'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'is bound by definition to'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the prefix '. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'according to '. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Namespaces in XML,'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'W3C Recommendation 14 Jan 1999'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw '(and by '. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Namespaces in XML 1.1'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw ').'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Note that unlike all other XML namespaces, both t he name '. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'and'. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the prefix are specified; '. 13:17:13,439 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'i.e., if you want XML 1.0 processors to recognize this namespace, you must use'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the reserved prefix '. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw '.'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:lang'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'and '. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:space'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'As of the last update of this document, the '. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'XML 1.0 (Third Edition) Specification'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw '(and also the '. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'XML 1.1 Specification'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw ')'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'defines two attribute names in this namespace:'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:lang'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Designed for identifying'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the human language used in the scope of the eleme nt to which it's'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'attached.'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:space'. 13:17:13,440 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Designed to express whether or not the document's creator wishes white'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'space to be considered as significant in the scop e of the element to which'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'it's attached.'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:base'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'The '. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'XML Base specification'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'describes a facility, similar to that of HTML BAS E, for defining base URIs for'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'parts of XML documents.'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'It defines a single attribute,'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:base'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw ', and describes in'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'detail the procedure for its use in processing re lative URI refeferences.'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:id'. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'The '. 13:17:13,441 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:id specification'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'defines'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'a single attribute, '. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:id'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw ', known to be of type '. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'ID'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'independently of any DTD or schema.'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Namespace change policy'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'The '. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'XML Core Working'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Group'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'reserves the right to'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'bring additional names from this namespace into a ctive use by'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'providing definitions for them in new specificati ons or'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'subsequent editions of existing specifications. The Working'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Group may also make modifications to the definiti ons of the'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'names already in use, although such changes will not normally'. 13:17:13,442 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'change the well-formedness or validity of existin g documents'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'or significantly change their meaning.'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'All changes to the use of this namespace will be achieved by'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the publication of documents governed by the W3C Process.'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Related Resources'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Section'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw '2.10'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'of the XML 1.0 specification describes the syntax and semantics of'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the '. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:space'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'attribute.'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'Section'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw '2.12'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'of the XML 1.0 specification describes the syntax and semantics of'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'the '. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:lang'. 13:17:13,443 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'attribute.'. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'An '. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'XML Schema'. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'fragment'. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'is available which constrains the syntax of '. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:lang'. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw ', '. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:space'. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw ','. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'xml:base'. 13:17:13,444 ERROR [JBossXSErrorHandler] [domain:http://www.w3.org/TR/xml-schema-1]::[key=s4s-elt-ch aracter]::Message=s4s-elt-character: Non-whitespace characters are not allowed in schema elements ot her than 'xs:appinfo' and 'xs:documentation'. Saw 'and '. 13:17:13,444 ```
Its actually easier to solve than this. I'm using jboss 4.2.3 with java 1.6. All you need to do is delete the jar files jboss-jaxws.jar and jboss-jaxws-ext.jar from jboss/server/<>/lib, <> is probably default. This functionality is contained in the jdk now, and the older version in jboss should be tossed. I just discovered another pair of jar files in the jboss-4.2.3.GA/lib/endorsed/ directory. Make sure you toss them too. Update 2/25/2011 I am now using JBoss 5.1. The jar files to remove in this version are jbossws-native-jaxws-ext.jar and jbossws-native-jaxws.jar.
This would seem to be a fairly common problem with Microsoft web services, in that the operations defined in the WSDL often share Message types. This, I believe, is not permitted by the WSDL specification, in that each operation's message payload must have a uniquely identifiable type. JBoss-WS would seem to be relying on this compliance (not unreasonably), but that's not much comfort to you. As is often the case with Java WS client questions, I suggest not using JBoss-WS and using [Spring-WS](http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html) instead. It ignores the WSDL and just send SOAP-wrapped XML documents. I've used Spring-WS to integrate with Microsoft web services that have exactly this "non-unique operation" problem, but I've never managed to get a traditional WSDL-binding client to work in cases like these.
Call Microsoft EWS from JSF app running on JBoss
[ "", "java", "web-services", "jboss", "" ]
I'm working on a RESTful web service in Java. I need a good way to send error messages to the client if something's wrong. According to the [Javadoc](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html#setStatus(int,%20java.lang.String)), `HttpServletResponse.setStatus(int status, String message)` is deprecated *"due to ambiguous meaning of the message parameter."* Is there a preferred way to set the status message or "[reason phrase](https://www.rfc-editor.org/rfc/rfc2616#section-6.1.1)" of the response? The `sendError(int, String)` method doesn't do it. **Edit**: To clarify, I want to modify the HTTP status line, i.e. `"HTTP/1.1 404 Not Found"`, not the body content. Specifically, I'd like to send responses like `"HTTP/1.1 400 Missing customerNumber parameter"`. Or I want to modify the HTTP status line to say something like [`227 IM Used`](https://datatracker.ietf.org/doc/html/rfc3229) - in other words: an *HTTP Status Description* different from what the web-server would know to send.
I don't think any RESTful client would expect to look at the reason phrase to figure out what went wrong; most RESTful services I've seen/used will send the standard status info and an expanded message in the body of the response. `sendError(int, String)` is ideal for that situation.
If you're using Tomcat, see the setting org.apache.coyote.USE\_CUSTOM\_STATUS\_MSG\_IN\_HEADER: <http://tomcat.apache.org/tomcat-5.5-doc/config/systemprops.html> * If this is true custom HTTP status messages will be used within HTTP headers. Users must ensure that any such message is ISO-8859-1 encoded, particularly if user provided input is included in the message, to prevent a possible XSS vulnerability. If not specified the default value of false will be used. See this page for some detail on the original vulnerability: <http://www.securityfocus.com/archive/1/archive/1/495021/100/0/threaded>
How to properly send an HTTP message to the client
[ "", "java", "http", "jakarta-ee", "servlets", "status", "" ]
This is a pretty simple question but I'm somewhat stumped. I am capturing sections of text that match "xxxxxxxxxx". It works fine. ``` string pattern = "(?<quotePair>\"[^/\"]*\")"; ``` Now I want to make a new pattern to capture “xxxxxxxxxx”... I used: ``` string pattern2 = "(?<lrquotePair>“[^/\"“]*”)"; ``` For some reason the second pattern won't catch anything. What am I missing?
Your patterns are more complicated than how you describe them - for example, the first one won't match `"foo/bar"`, and the second one won't match `“foo/bar”` or `“foo"bar”`. Perhaps your input falls into one of those categories? If there is an encoding problem, it's not with the regex - .NET regexes support Unicode just fine. But it might be that you didn't read the text in the correct encoding in the first place - try printing it out and check that the fancy `“”` quotes are still there. In particular, if you use `StreamReader` class with a single-argument constructor (or `File.OpenText` helper), it defaults to UTF-8 encoding for input, which might not be what you actually have there.
[Encoding might be getting in your way.](http://www.regular-expressions.info/unicode.html) Try with `\u0093` and `\u0094` instead.
Capturing “xxxxxxxxxx”
[ "", "c#", ".net", "regex", "" ]
Java's checked exceptions sometimes force you to catch a checked exception that you believe will never be thrown. Best practice dictates that you wrap that in an unchecked exception and rethrow it, just in case. What exception class do you wrap with in that case? What exception would you wrap with in the "// Should never happen" case?
I don't yet have one, but I'd do it the following way: * have it extend **Error** rather then Exception/RuntimeException, since then it's less likely to be caught by an error handler which is not prepared for it; * wrap it in some static utility calls: Example: ``` public static void doAssert(boolean result, String reason) { if ( !result ) throw new OMGWereDoomedError("Assertion failed: " + reason + " ."); } ``` I prefer these wrapper since I can then change the implementation if needed. Also, I don't advocate using assertions since I don't always control the runtime flags, but I do want execution to halt abruptly if the system is compromised. Consider this: * showing the user a *Sorry, we're unable to process your payment* page; * confirming the result to the user, even though the system is in an uncertain state. Which would you choose?
For example, my caveat is the to-UTF-8-bytes character conversion ``` String.getBytes("UTF-8"); ``` And the need to always wrap it in try-catch as it is a generic method. As UTF-8 could be regarded as standard, I would expect to have a direct `String.getUTF8()` like call on string, similarly the GetStringUTF8Bytes JNI method. Of course it could be replaced by a static Charset.UTF8 constant for example and use the getBytes() with that. Second annoyance for me is the need to wrap the `close()` into a try-catch. Maybe I'm not that experienced but can't see how it helps when you have already a problem with the stream and you can't even silently close it down for good. You'd practically just log and ignore the exception. Apparently, you can use a suppressor method call to do just that. There are also the trivial value-string conversions when you are 100% sure the string is a valid value as you checked it with regex or schema validation.
What's Your ShouldNeverHappenException?
[ "", "java", "exception", "" ]
My application is a commercial GIS C++ application, and I'm looking for a robust/easy to use connector for Postgresq. (Side note: I also plan to use PostGIS) Does anyone have any recommendations based on your experience? A plus would be if you have tried out various ones. I have looked at: 1. [Postgres's C client](http://www.postgresql.org/docs/8.3/static/client-interfaces.html) 2. [pqxx](http://pqxx.org/development/libpqxx/) 3. [QSql](http://doc.trolltech.com/4.5/qtsql.html) **EDIT** Also, does anyone know what's a good admin GUI tool? I see a community list [here](http://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools). But there are so many! I'm developing on Windows, and dont mind paying for commercial tools. Someone in another Stackoverflow post suggested [Maestro](http://www.sqlmaestro.com/products/postgresql/maestro/).
[libpq++](http://www.postgresql.org/docs/7.2/static/libpqplusplus.html) is one provide very good connector for PostgreSQL [SQLAPI++](http://www.sqlapi.com/) is a C++ library for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL and ODBC, SQLite). [Abstract Database Connector](http://ostatic.com/a-dbc) is a C/C++ library for making connections to several databases (MySQL, mSQL, PostgreSQL, Interbase, Informix, BDE, ODBC). It runs on Linux, UNIX, BeOS, and Windows, and a dynamic driver loader for ELF OSes is under development [Navicat](http://www.navicat.com/download/) is Nice GUI tool for PostgrSQL
Take a look at SOCI. Is an open source lib under Boost Software License (one of the most non-restrictive licenses at all). This lib is designed especially for C++ with the idea of generic programming and type safety in mind. [SOCI Site](http://soci.sourceforge.net/)
Good C/C++ connector library for PostgreSQL
[ "", "c++", "postgresql", "" ]
Is there a way to directly read a binary file into RAM? What I mean is, is there a way to tell the compiler, here's the file, here's the block of RAM, please put the file contents in the RAM, off you go, quickly as you can please. Currently I'm stepping through the file with ifstream loading it into RAM (an array) 64bit block by 64 bit block. But I'm thinking that this must slow it down as it's like (here comes an analogy) using a thimble to bail the water out of a cup (the file) into a jug (the RAM) rather than just picking up the cup and tipping the entire contents into the jug in one go. As a relative newcomer to this I may have completely the wrong idea about this - any guidence would be a great help. I'm just after the quickest way to get a big file into RAM. Thanks
What prevents you from reading the file in one pass? Is it too big to fit in memory? You can also use mapped file, UNIX : mmap, Windows : CreateFileMapping
I think what you need is [memory mapped file](http://en.wikipedia.org/wiki/Memory-mapped_file), however the API depends on which OS you are on, in UNIX I believe it's mmap().
Read data directly from file to RAM in C++
[ "", "c++", "file", "ram", "ram-scraping", "" ]
Consider the following case: ``` public class A { public A() { b = new B(); } B b; private class B { } } ``` From a warning in Eclipse I quote that: the java complier emulates the constructor A.B() by a synthetic accessor method. I suppose the compiler now goes ahead and creates an extra "under water" constructor for B. I feel this is rather strange: why would class B not be visible as a.k.o. field in A? And: does it mean that class B is no longer private at run time? And: why behaves the protected keyword for class B different? ``` public class A { public A() { b = new B(); } B b; protected class B { } } ```
Inner classes are essentially a hack introduced in Java 1.1. The JVM doesn't actually have any concept of an inner class, and so the compiler has to bodge it. The compiler generates class B "outside" of class A, but in the same package, and then adds synthetic accessors/constructors to it to allow A to get access to it. When you give B a protected constructor, A can access that constructor since it's in the same package, without needing a synthetic constructor to be added.
I know this question is now almost three years old, but I find that a part of the question is still not answered: > And: does it mean that class B is no longer private at run time? Carlos Heubergers comment on skaffmans answer suggests, class `B` is still `private` for other classes in the package. He is probably right for the Java programming language, i.e. it is not possible to refer to class `B` from an other class. At least not without using reflection (with which also private class members may be accessed from the outside), but this is another issue. But as the JVM does not have any concept of an inner class (as skaffman states), I asked myself how an "accessible by only one class" visibility is realized at the bytecode level. The answer: It isn't realized at all, for the JVM the inner class looks like a normal package private class. This is, if you write bytecode for yourself (or modify one generated by the compiler) you can access class `B` without problems. You can access all synthetic accessor methods from all classes in the same package, too. So if you assign a value to a private field of class `A` in a method of class `B`, a synthetic accessor method with default (i.e. package private) visibility is generated in class `A` (named something like `access$000`) that sets the value for you. This method is supposed to only be called from class `B` (and indeed it can only be called from there using the Java language). But from the JVMs point of view, this is just a method as any other and can be called by any class. So, to answer the question: * From the Java languages point of view, class `B` is and stays private. * From the JVMs point of view, class `B` (or better: class `A$B`) is not private.
Java inner class visibility puzzle
[ "", "java", "inner-classes", "" ]
I have 3 arrays of data that are used to populate some fields on screen. When a user posts the form (unrelated to the data contained in the arrays) I want to display the array data on screen again, but without retrieving it from the database when the page reloads. What's the best way to temporarily store these values? I was thinking of storing them in the session, is that bad practice? Is there a better way, perhaps passing them as hidden form values?
Another option could be to [serialize](http://ch2.php.net/serialize) the array and save it into a temporary file. About the question session vs. hidden form fields: The disadvantage of the form fields is that hackers could see it in the HTML source code and misuse it. So you would have to do some extra checks to see if the form fields are in any way valid or not. The problem with session and serialize is, that the information would be laying around on the server if the user is moving away from the website before he finished the whole process. And the last thing: You are not writing how large those arrays are. If each of those 3 arrays have several thousand entries then serialize could be a better option than the session and form fields. Probably sessions is what you need. But the other things should be taken into account too.
Generate a set of hidden inputs in the form. Then you can just read them from the post.
What's the best way of displaying fields on screen after a user posts a form, without going back to the db?
[ "", "php", "session", "post", "hidden-field", "" ]
I have this horrible habit of typing the below and not catching it until well into testing: ``` int i = 1; int j = 2; i =+ j; //i equals 2, not 3 as intended; assign only, + is unary and works on the j ``` The correct version, of course, would be ``` int i = 1; int j = 2; i += j; //i equals 3, as intended with additive & assignment compound operator ``` I have made this mistake a zillion times. It would not surprise me of there is some code out there with a bug in it that escaped a test case. There has just got to be a way to prevent this systematically. Any ideas?
Regularly use tools like [PMD](http://pmd.sourceforge.net/) and/or [Checkstyle](http://checkstyle.sourceforge.net/). Ideally as part of your build process/continuous integration. You might have to define a custom rule for this, because I don't know if any of those tools recognizes this as a problem by default. This will not only catch this problem, but also hint at a lot of other potential problems as well.
Depending on what IDE you use, if it does syntax highlighting, I would modify the highlighting so that it looks for the pattern `=+` and makes it some awful-to-look-at color.
Automatically catching the use of =+ rather than += in Java
[ "", "java", "operators", "compound-operator", "" ]
When programming an OO program using a SQL database back-end, do objects' attributes correspond with the rows in the tables? Or more than that? I don't quite understand how objects' attributes relate to data in tables. Thanks for your help.
It really depends which orm you are using, however, in general the idea is: ``` class = > table instance => row attribute => column ```
ennuikiller mentioned some things, but an object may also be store over multiple rows and tables because there may be no correlation because of how data is modelled and normalised. It's not straightforward... some reading [Object-relational impedance mismatch](http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch) (Wikipedia)
OO program and SQL database
[ "", "sql", "oop", "" ]
I am trying to set up an automated build system on Windows using Cygwin. Among other things, it needs to be able to build several Visual C++ solutions. I have a script which sets up the environment variables needed for devenv, and if I type 'devenv' in bash it brings up the Visual Studio IDE. No problems so far. I am also able to build a solution from cygwin's bash prompt by typing ``` $ devenv mysolution.sln /build Debug ``` The problem is that it is not showing me the build output. In fact, it does not even tell me whether or not the build succeeded. The command simply finishes, and I get back the prompt. Then I can go into the output directory, and check whether or not the executable was created, but for a build system I want to be able to grep for errors. What am I doing wrong? I can see the debug output when I run devenv in the windows shell, but not in cygwin. Where is it being sent, and how do I get it back?
Will cygwin find and run .com files? There are 2 `devenv` executables, one is `devenv.com` which is a console mode application that handles stdin, stdout and stderr proxying for the other executable, `devenv.exe`, which is a GUI mode application. If `devenv.exe` is what cygwin is loading then there will be no stdin/stdout stuff. If `devenv.com` is being loaded, it should launch `devenv.exe` while proxying the stdout stuff to the console. Maybe if you explicitly specify that `devenv.com` should be run?
Have you considered using [MSBuild](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx)? You can use msbuild to build VS solutions without any modifications and it spits output out the stdout. The command would look something like: ``` msbuild mysolution.sln /t:Build /p:"Configuration=Debug" /p:"Platform=Win32" ``` MSBuild is the tool that MS designed to do automated builds, so it may fit your problem a little better than running the devenv.exe.
How to build a Visual Studio 9.0 solution from Cygwin and get build output?
[ "", "c++", "visual-studio-2008", "build-automation", "cygwin", "" ]
I have just been helped on a problem I have [here](https://stackoverflow.com/questions/1112340/how-to-run-function-of-parent-window-when-child-window-closes). ``` var win = window.open(url, name); win.onunload = StartLoad; win.close(); ``` To solve this problem completely, I wanted to know if **onunload** will be triggered once or every time a event occurs? In other words, will my function startLoad run every time the child window "win" gets redirected, closed etc? Or will it do this event once and that's it? Apologies, if this is a silly question. Thanks all
No - this method can fire multiple times as you navigate off a page in IE6 and IE7. This code snippet illustrates this (save as OnUnloadTest.htm): ``` <body> <form id="form" action="OnUnloadTest.htm" method="post"> Click <a href="javascript:form.submit()">here</a> </form> <script type="text/javascript"> window.onbeforeunload = beforeunload function beforeunload() { alert('OnUnload'); } </script> </body> ``` Basically, the event fires once for the actual anchor click, and once as the page actually posts back. I've only seen this issue when you have javascript in the href of the anchor, although if you use ASP.NET linkbuttons then be warned as this puts javascript in the href. For most other sorts of navigation (e.g. user clicks a normal anchor, or closes the browser, or navigates away with a bookmark, etc) the event does only fire once.
It *should* only fire once, the first time the window unloads. Anything else would be a security hole.
How many times is onunload triggered?
[ "", "javascript", "events", "" ]
This is a really strange problem, that appears to be somewhat intermittent (although it has started consistently occurring now - possibly due to a Windows Update?). My code has previously worked fine in IE7, and continues to work in Firefox, Chrome, and seemingly any other browser but IE8. I'm setting some session data and then passing the user to a payment gateway (Protx / Sage, if that makes any difference), which on return needs to reference my session data. But my session data disappears. I'm not doing anything fancy with the payment gateway display - no iframes, just a link that takes the user to the payment page, in the same browser window. Having done some reading, I've tried adding the following to force compatibility mode in my page (as apparently this can cause IE8 to lose session data): ``` <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> ``` This had no effect (but then, as far as I can tell, the payment page is not forcing compatibility mode). There seem to be quite a few people saying that iframes cause this behaviour, but again, no iframes are used. Considering how persistent session data is in IE8 - unlike IE7, and other browsers, when a new instance of the browser is initiated, any session in another instance of the browser are accessible - I'm struggling to see where and how my session data is being lost.
I've done this kind of thing with Sage Pay before. Here is what I did, it might help: 1. Register the transaction 2. Save the current session Id to database (eg. inside the temporarily stored transaction) 3. Send the user off to sage pay to do the payment 4. Sage pay notifies you and you can load up the temp transaction 5. Pass the session id as a query string parameter for your redirect url 6. On the redirect (completion page) check if there is a session id var in the request and if there is, then call session\_id($theIdYouGotFromQueryString) before calling session\_start() p.s yes i know it doesn't directly answer your question. But maybe doing it this way will help?
I had the same problem and what I tracked it down to was that if you use a page to generate the session and then once it is generated you do a header(Location:...); call IE will think it needs to generate a new session in protected mode and will drop all cookies from the previous session.
IE8 loses my session data when using payment gateway
[ "", "php", "internet-explorer", "session", "internet-explorer-8", "" ]
I'm writing a method which approximates the Kolmogorov complexity of a String by following the LZ78 algorithm, except instead of adding to a table I just keep a counter i.e i'm only interested in the size of the compression. The problem is that for large inputs it is taking hours. Is it the way I have implemented it? ``` /** * Uses the LZ78 compression algorithm to approximate the Kolmogorov * complexity of a String * * @param s * @return the approximate Kolmogorov complexity */ public double kComplexity(String s) { ArrayList<String> dictionary = new ArrayList<String>(); StringBuilder w = new StringBuilder(); double comp = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (dictionary.contains(w.toString() + c)) { w.append(c); } else { comp++; dictionary.add(w.toString() + c); w = new StringBuilder(); } } if (w.length() != 0) { comp++; } return comp; } ``` UPDATE: Using ``` HashSet<String> dictionary = new HashSet<String>(); ``` instead of ``` ArrayList<String> dictionary = new ArrayList<String>(); ``` makes it much faster
I think I can do better (sorry a bit long): ``` import java.io.File; import java.io.FileInputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class LZ78 { /** * Uses the LZ78 compression algorithm to approximate the Kolmogorov * complexity of a String * * @param s * @return the approximate Kolmogorov complexity */ public static double kComplexity(String s) { Set<String> dictionary = new HashSet<String>(); StringBuilder w = new StringBuilder(); double comp = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (dictionary.contains(w.toString() + c)) { w.append(c); } else { comp++; dictionary.add(w.toString() + c); w = new StringBuilder(); } } if (w.length() != 0) { comp++; } return comp; } private static boolean equal(Object o1, Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } public static final class FList<T> { public final FList<T> head; public final T tail; private final int hashCodeValue; public FList(FList<T> head, T tail) { this.head = head; this.tail = tail; int v = head != null ? head.hashCodeValue : 0; hashCodeValue = v * 31 + (tail != null ? tail.hashCode() : 0); } @Override public boolean equals(Object obj) { if (obj instanceof FList<?>) { FList<?> that = (FList<?>) obj; return equal(this.head, that.head) && equal(this.tail, that.tail); } return false; } @Override public int hashCode() { return hashCodeValue; } @Override public String toString() { return head + ", " + tail; } } public static final class FListChar { public final FListChar head; public final char tail; private final int hashCodeValue; public FListChar(FListChar head, char tail) { this.head = head; this.tail = tail; int v = head != null ? head.hashCodeValue : 0; hashCodeValue = v * 31 + tail; } @Override public boolean equals(Object obj) { if (obj instanceof FListChar) { FListChar that = (FListChar) obj; return equal(this.head, that.head) && this.tail == that.tail; } return false; } @Override public int hashCode() { return hashCodeValue; } @Override public String toString() { return head + ", " + tail; } } public static double kComplexity2(String s) { Map<FList<Character>, FList<Character>> dictionary = new HashMap<FList<Character>, FList<Character>>(); FList<Character> w = null; double comp = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); FList<Character> w1 = new FList<Character>(w, c); FList<Character> ex = dictionary.get(w1); if (ex != null) { w = ex; } else { comp++; dictionary.put(w1, w1); w = null; } } if (w != null) { comp++; } return comp; } public static double kComplexity3(String s) { Map<FListChar, FListChar> dictionary = new HashMap<FListChar, FListChar>(1024); FListChar w = null; double comp = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); FListChar w1 = new FListChar(w, c); FListChar ex = dictionary.get(w1); if (ex != null) { w = ex; } else { comp++; dictionary.put(w1, w1); w = null; } } if (w != null) { comp++; } return comp; } public static void main(String[] args) throws Exception { File f = new File("methods.txt"); byte[] data = new byte[(int) f.length()]; FileInputStream fin = new FileInputStream(f); int len = fin.read(data); fin.close(); final String test = new String(data, 0, len); final int n = 100; ExecutorService exec = Executors.newFixedThreadPool(1); exec.submit(new Runnable() { @Override public void run() { long t = System.nanoTime(); double value = 0; for (int i = 0; i < n; i++) { value += kComplexity(test); } System.out.printf("kComplexity: %.3f; Time: %d ms%n", value / n, (System.nanoTime() - t) / 1000000); } }); exec.submit(new Runnable() { @Override public void run() { long t = System.nanoTime(); double value = 0; for (int i = 0; i < n; i++) { value += kComplexity2(test); } System.out.printf("kComplexity2: %.3f; Time: %d ms%n", value / n, (System.nanoTime() - t) / 1000000); } }); exec.submit(new Runnable() { @Override public void run() { long t = System.nanoTime(); double value = 0; for (int i = 0; i < n; i++) { value += kComplexity3(test); } System.out.printf("kComplexity3: %.3f; Time: %d ms%n", value / n, (System.nanoTime() - t) / 1000000); } }); exec.shutdown(); } } ``` Results: ``` kComplexity: 41546,000; Time: 17028 ms kComplexity2: 41546,000; Time: 6555 ms kComplexity3: 41546,000; Time: 5971 ms ``` **Edit** Peer pressure: How does it work? Franky, have no idea, it just seemed to be a good way to speed up things. I have to figure it out too, so here we go. It was an observation that the original code made lot of string appends, however, replacing it with a `LinkedList<String>` wouldn't help as there is a constant pressure for looking up collections in the hash-table - every time, the hashCode() and equals() are used it needs to traverse the entire list. But how can I make sure the code doesn't perform this unnecessary? The answer: Immutability - if your class is immutable, then at least the hashCode is constant, therefore, can be pre-computed. The equality check can be shortcutted too - but in worst case scenario it will still traverse the entire collection. That's nice, but then how do you 'modify' an immutable class. No you don't, you create a new one every time a different content is needed. However, when you look close at the contents of the dictionary, you'll recognize it contains redundant information: `[]a`, `[abc]d`, `[abc]e`, `[abcd]f`. So why not just store the head as a pointer to a previously seen pattern and have a tail for the current character? Exactly. Using immutability and back-references you can spare space and time, and even the garbage collector will love you too. One speciality of my solution is that in F# and Haskell, the list uses a head:[tail] signature - the head is the element type and the tail is a pointer to the next collection. In this question, the opposite was required as the lists grow at the tail side. From here on its just some further optimization - for example, use a concrete `char` as the tail type to avoid constant char autoboxing of the generic version. One drawback of my solution is that it utilizes recursion when calculating the aspects of the list. For relatively small list it's fine, but longer list could require you to increase the Thread stack size on which your computation runs. In theory, with Java 7's tail call optimization, my code can be rewritten in such a way that it allows the JIT to perform the optimization (or is it already so? Hard to tell).
In my opinion an `ArrayList` isn't the best datastructure for keeping a dictionary with only contains and adds. EDIT Try using an [HashSet](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html), which stores its elements in a hash table, is the best-performing implementation of the [Set interface](http://java.sun.com/javase/6/docs/api/java/util/Set.html); however it makes no guarantees concerning the order of iteration
Slow implementation of famous compression algorithm (LZ78)
[ "", "java", "algorithm", "optimization", "compression", "" ]
I was just reading abit about JMS and Apache ActiveMQ. And was wondering what real world use have people here used JMS or similar message queue technologies for ?
JMS (ActiveMQ is a JMS broker implementation) can be used as a mechanism to allow asynchronous request processing. You may wish to do this because the request take a long time to complete or because several parties may be interested in the actual request. Another reason for using it is to allow multiple clients (potentially written in different languages) to access information via JMS. ActiveMQ is a good example here because you can use the STOMP protocol to allow access from a C#/Java/Ruby client. A real world example is that of a web application that is used to place an order for a particular customer. As part of placing that order (and storing it in a database) you may wish to carry a number of additional tasks: * Store the order in some sort of third party back-end system (such as SAP) * Send an email to the customer to inform them their order has been placed To do this your application code would publish a message onto a JMS queue which includes an order id. One part of your application listening to the queue may respond to the event by taking the orderId, looking the order up in the database and then place that order with another third party system. Another part of your application may be responsible for taking the orderId and sending a confirmation email to the customer.
Use them all the time to process long-running operations asynchronously. A web user won't want to wait for more than 5 seconds for a request to process. If you have one that runs longer than that, one design is to submit the request to a queue and immediately send back a URL that the user can check to see when the job is finished. Publish/subscribe is another good technique for decoupling senders from many receivers. It's a flexible architecture, because subscribers can come and go as needed.
Real world use of JMS/message queues?
[ "", "java", "jms", "message-queue", "" ]
I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like: ``` MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' ``` I've got the CSS files in /mysite/media/css/ and the template code contains: ``` <link rel="stylesheet" type="text/css" href="/media/css/site_base.css" />` ``` then, in the url.py file I have: ``` # DEVELOPMENT ONLY (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/media'}), ``` but the development server serves the plain html (without styles). What am I doing wrong? -- OK - I got it working based on what you folks have said. The answer is: settings.py: ``` MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media MEDIA_URL = '/mymedia/' #because admin already using /media ``` site\_base.html: ``` <link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" /> ``` urls.py ``` from mysite import settings if settings.DEBUG: urlpatterns += patterns('', (r'^mymedia/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) ``` And voila! It works.
in the "development only" block in your urls.py you need to change ``` (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/media'}), ``` to... ``` (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ```
`ADMIN_MEDIA_PREFIX` is set to `\media\` by default, and is probably 'stealing' the path. Change that setting, or use a different one for non-admin media - eg `site_media` or `assets`.
Django template can't see CSS files
[ "", "python", "css", "django", "django-templates", "" ]
I want to create a bunch of errors. each specific to its own class and module. Then i would like to attach the id to an exception so when my msg change the id is still the same. How do i create this list of errors without maintaining a large global enum ?
Divide the unsigned 32-bit hexadecimal number range up as a hierarchy: ``` 0xMMCCCEEE ``` where: * MM is module ID * CCC is class ID * EEE is error ID Then you can have 0 to 0xFF (256) modules, and 0 to 0xFFF (4096) each of classes and errors, and you only have to ensure that each error is unique to its class, and each class is unique to its module, so you don't have to keep all error messages in a single giant table. Example: ``` 0x0401D00A ``` That's module 04, class 01D, error 00A.
Generate a GUID for each error.
How do i create a global unique error id? C#
[ "", "c#", "" ]
We all know about [Boost](http://www.boost.org/). What other free C++ libraries are worth using? Why? Are they easily usable with common compilers?
See: [What modern C++ libraries should be in my toolbox?](https://stackoverflow.com/questions/777764/what-modern-c-libraries-should-be-in-my-toolbox)
[Qt](http://qt.nokia.com/) is a multiplatform framework that provides you not only with a great GUI toolkit, but also with [a lot of different libraries](http://qt.nokia.com/products/library/modular-class-library) and functionality that makes your life a lot easier, including a reimplementation of many standard C++ features, easing their use even further. It's heavily used in the KDE desktop environment in Linux. It's an awesome framework. C++ almost feels like Java with it.
High-quality libraries for C++
[ "", "c++", "multiplatform", "" ]
How could I run a game made with XNA on the iPhone/iTouch? Which steps/tools (existing ones or imaginary...) should be used? **Note:** The goal is to avoid modifying existing C# code > UPDATE : > If I understand correctly, I must be able to: > > 1. Run my XNA code on Mono ([monoxna](http://code.google.com/p/monoxna/) or [SilverSprite](http://silversprite.codeplex.com), promising?) > 2. Run Mono on iPhone ([MonoTouch](http://mono-project.com/MonoTouch))
I don't believe there is a good answer to your question. XNA doesn't target the iPhone, so the chances of being able to effectively port an XNA game without modifying the C# source code isn't likely to happen. Instead, I'd recommend that you take a look at the various frameworks that exist to help you craft cross-platform games. [Unity](http://unity3d.com/unity/) often comes up in these discussions, but it isn't free. If cross-platform isn't your goal, but free iPhone development is, then I'd recommend looking at [Cocos](http://code.google.com/p/cocos2d-iphone/). Edit: The [MonoTouch](http://www.mono-project.com/MonoTouch) project may be able to assist you in the future, but doesn't help you out right now. Still, it's something to keep an eye on. Edit: The landscape has changed a lot in the ~5 years since this question was posted. If you have an XNA project that you want to get running on iOS, then [Xamarin.iOS](http://xamarin.com/ios) (formerly MonoTouch) plus MonoGame is a near-perfect fit. MonoGame is missing a huge chunk of the XNA content pipeline, which means you'll either have to abandon it or have a VS2010 instance somewhere compiling your assets.
Not only is it possible but here is a video of someone doing XnaTouch on MonoTouch: [First game to IPhone build with XnaTouch (XNA for IPhone)](http://www.youtube.com/watch?v=8iDtHy36E5k) Here is the mono article about doing it <http://www.mono-project.com/MonoTouch>
How toI run a game made with XNA on the iPhone/iTouch?
[ "", "c#", ".net", "iphone", "clr", "xna", "" ]
I am having trouble using the output cache param in an aspnet 2.0 page directive. I am using a session variable to hold the value of the selected image. It seems that the dynamic control in a datalist, is not working when the output cache is set to true in the page directive. Is there a way to cache the images seperately to avoid using a page directive? datalist code " RepeatColumns="6" CellPadding="8" CellSpacing="8" GridLines="Both" SelectedItemStyle-BackColor="#33ff66" OnSelectedIndexChanged="dtlImages\_SelectedIndexChanged" OnItemCommand="dtlImages\_ItemCommand"> ' Runat="server"> ' ID="lblDescription" Font-Bold="True" Font-Size="12px" Font-Names="Arial"> code that retrieves the image from the database protected void Page\_Load(object sender, System.EventArgs e) { string strImageID = Request.QueryString["id"]; ``` string wf4uConnect = System.Configuration.ConfigurationManager.ConnectionStrings["wf4uConnectionString"].ConnectionString; System.Data.SqlClient.SqlConnection wf4uConn = new System.Data.SqlClient.SqlConnection(wf4uConnect); System.Data.SqlClient.SqlCommand myCommand = new SqlCommand("Select ImageFile, ImageType from wf4u_ImageThumb Where ImageId =" + strImageID, wf4uConn); wf4uConn.Open(); SqlDataReader byteReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); while ((byteReader.Read())) { Response.BinaryWrite((byte [])byteReader.GetValue(0)); Response.ContentType = (string)byteReader.GetValue(1); } wf4uConn.Close(); } ``` I have implemented an http context object to cache the images as they're loaded into the webpage. public ImageList (string clientName) { HttpContext context = HttpContext.Current; ``` if((context.Cache["ImageIdList" + clientName] == null)) { string wf4uConnect = System.Configuration.ConfigurationManager.ConnectionStrings["wf4uConnectionString"].ConnectionString; System.Data.SqlClient.SqlConnection wf4uConn = new System.Data.SqlClient.SqlConnection(wf4uConnect); string queryStr = "SELECT ImageId FROM wf4u_imageThumb WHERE ClientName = @ClientName"; SqlCommand ImageIdComm = new System.Data.SqlClient.SqlCommand(queryStr, wf4uConn); ImageIdComm.Parameters.Add("@ClientName", SqlDbType.VarChar).Value = clientName; wf4uConn.Open(); SqlDataReader ImageIdReader = ImageIdComm.ExecuteReader(); if (ImageIdReader.Read()) { _ImageId = ImageIdReader.GetInt32(0); _ClientName = ImageIdReader.GetString(1); context.Cache.Insert("ImageIdList" + clientName, this, null, DateTime.Now.AddSeconds(600), TimeSpan.Zero); } wf4uConn.Close(); } else { ImageList list = (ImageList)context.Cache["ImageIdList" + clientName]; _ImageId = list.ImageId; _ClientName = list.ClientName; } } ``` any suggestions would be welcomed.
You can implement an async handler like this: ``` using System; using System.Web; using System.Data.SqlClient; public class FileHandler : IHttpAsyncHandler { #region Variables private HttpContext _currentContext = null; protected SqlCommand _command = null; protected delegate void DoNothingDelegate(); #endregion public void ProcessRequest(HttpContext context) { } public void DoNothing() { } public bool IsReusable { get { return false; } } #region IHttpAsyncHandler Members public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { _currentContext = context; int imageId; if (int.TryParse(context.Request.QueryString["imageId"], out imageId)) { // begin get file - make you own // return FileController.BeginGetFile(out _command, cb, extraData, imageId); } else { DoNothingDelegate doNothingDelegate = new DoNothingDelegate(DoNothing); return doNothingDelegate.BeginInvoke(cb, extraData); } } public void EndProcessRequest(IAsyncResult result) { File file = null; if (null != _command) { try { // end get file - make your own // file = FileController.EndGetFile(_command, result); } catch { } } if (null != file) { // in my case File entity may be stored as a binary data //or as an URL // here is URL processing - redirect only if (null == file.Data) { _currentContext.Response.Redirect(file.Path); } else { _currentContext.Response.ContentType = file.ContentType; _currentContext.Response.BinaryWrite(file.Data); _currentContext.Response.AddHeader("content-disposition", "filename=\"" + file.Name + (file.Name.Contains(file.Extension) ? string.Empty : file.Extension) + "\"" ); _currentContext.Response.AddHeader("content-length", (file.Data == null ? "0" : file.Data.Length.ToString())); } _currentContext.Response.Cache.SetCacheability(HttpCacheability.Private); _currentContext.Response.Cache.SetExpires(DateTime.Now); _currentContext.Response.Cache.SetSlidingExpiration(false); _currentContext.Response.Cache.SetValidUntilExpires(false); _currentContext.Response.Flush(); } else { throw new HttpException(404, HttpContext.GetGlobalResourceObject("Image", "NotFound") as string); } } #endregion } ``` And set necessary values to the cache headers. **EDIT:** Guess, in this case it would be better to use headers instead of using Cache object.
You can use `Cache` object see: [ASP.NET Caching: Techniques and Best Practices](http://msdn.microsoft.com/en-us/library/aa478965.aspx)
How to cache images from a SQl Server 2005 database call?
[ "", "c#", "asp.net", "sql-server-2005", "caching", "" ]
On my .NEt projects I'm used to the tool called ReSharper but my current project is c/c++ and I so miss my loved ReSharper any one know of a tool with at least kinda the same capabilities for c/c++ (Especially refactoring and dead code analysis)
Some refactoring support and intellisense is ensured by Visual Assist. Pretty good actually. However, don't expect to have the same support for refactoring as in case of ReSharper with C# or VB.NET. From this point of view, C++ is a nightmare and I don't know a tool that can do it correctly in all situations.
Visual Assist from WholeTomato actually Software predates Resharper and is very good
ReSharper for c/c++
[ "", ".net", "c++", "visual-c++", "" ]
I'm using django with apache and mod\_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms). While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s. Anyone have any advice? How can I modify Django to use a persistent connection or speed up the connection from Python to DB?
Django **1.6** has added [persistent connections support (link to doc for latest stable Django )](https://docs.djangoproject.com/en/stable/ref/databases/#persistent-connections): > Persistent connections avoid the overhead of re-establishing a > connection to the database in each request. They’re controlled by the > CONN\_MAX\_AGE parameter which defines the maximum lifetime of a > connection. It can be set independently for each database.
Try [PgBouncer](http://wiki.postgresql.org/wiki/PgBouncer) - a lightweight connection pooler for PostgreSQL. Features: * Several levels of brutality when rotating connections: + Session pooling + Transaction pooling + Statement pooling * Low memory requirements (2k per connection by default).
Django persistent database connection
[ "", "python", "database", "django", "mod-wsgi", "persistent", "" ]
How can I disable a `DropDownList` in ASP.NET? ### Code: ``` <asp:TemplateField HeaderText="Effective Total Hours"> <ItemTemplate> <%# Eval("TotalHoursEffect")%> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlEditTotalHoursEffect" AppendDataBoundItems="true" DataSourceID="dsTHMsql" DataValueField="Minutes" Enabled="false" ReadOnly="true" DataTextField="Display" SelectedValue='<%# Eval("TotalHoursEffect") %>' runat="server"> <asp:ListItem Selected="True" Value="">(Choose Minutes)</asp:ListItem> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> ``` This is not working for me. What am I doing wrong?
There is no readonly property for a true dropdownlist for asp.net webforms. ``` <asp:DropDownList ID="DropDownList1" runat="server" Enabled="False"> </asp:DropDownList> ``` If that isn't what you're doing, you will need to be a lot more specific. You didn't ask a question, you didn't explain WHAT isn't working, or say if you're using webforms or winforms, or if it's in the code behind or the aspx page. ETA: remove the readonly property from the dropdownlist, it isn't valid. AFTER you test that part and see if it fixed it, if it still isn't doing what you want, please tell us what it isn't doing. Is it not disabling? Is it not databinding? What's going on with it? Oh, and make sure you use Bind, not Eval, for edit templates if the value is being passed back in any way such as to a query update. Sometimes the platform is doing it behind the scenes, so generally speaking, just use Bind. One more edit: this works for me in the most basic sense in that it binds and the dropdown is not selectable. ``` <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="sqldsProducts" AutoGenerateEditButton="True"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" SortExpression="ProductID" /> <asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID"> <EditItemTemplate> <asp:DropDownList Enabled="false" ID="ddlCategory" runat="server" DataSourceID="sqldsCategories" DataTextField="CategoryName" DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>' AppendDataBoundItems="True"> <asp:ListItem Selected="True" Value="" Text="-- choose one --" /> </asp:DropDownList> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblCategory" runat="server" Text='<%# Bind("ProductID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" /> </Columns> </asp:GridView> ```
You can disable a dropdownlist but you'll need to do it from the code behind. Try this in your .cs (assuming your asp:DropDownList as an id of ddlCategory), ``` ddlCategory.Attributes.Add("disabled", "disabled"); ```
How can I disable a dropdownlist in ASP.NET?
[ "", "c#", "asp.net", "webforms", "" ]
We use this small utility method. But we don't like it. Since it's not very crucial (it works anyway ... ) , we have forgotten it. But that's ugly, because we have to go through the whole array, only to convert it from `Byte[]` to `byte[]`. I'm looking : * for a way to cast the `Byte[]` in `byte[]` without going through it * or for a utility method for cast a List into string ``` public static String byteListToString(List<Byte> l, Charset charset) { if (l == null) { return ""; } byte[] array = new byte[l.size()]; int i = 0; for (Byte current : l) { array[i] = current; i++; } return new String(array, charset); } ```
Your method is pretty much the only way to do it. You may find an external library that does all or part of it, but it will essentially do the same thing. However, there is one thing in your code that is a potential problem: When calling `new String(array)`, you are using the platform default encoding to convert the bytes to characters. The platform encoding differs between operating system and locale settings - using it is almost always a bug waiting to happen. It depends on where you're getting those bytes from, but their encoding should be specified somewhere, passed as argument to the method and used for the conversion (by using the String constructor with a second parameter).
``` import org.apache.commons.lang.ArrayUtils; ... Byte[] bytes = new Byte[l.size()]; l.toArray(bytes); byte[] b = ArrayUtils.toPrimitive(bytes); ```
List<Byte> to String, can you help refactor this ( small ) method?
[ "", "java", "arrays", "" ]
I have a string 'item3' and a listbox with 'item1,item2,item3,item4', how do I select item3 in the list box when I have the item name in a string? Thanks
``` int index = listBox1.FindString("item3"); // Determine if a valid index is returned. Select the item if it is valid. if (index != -1) listBox1.SetSelected(index,true); ```
``` listBox.FindStringExact("item3"); ``` Returns the index of the first item found, or ListBox.NoMatches if no match is found. you can then call ``` listBox.SetSelected(index, true); ``` to select this item
c# How do I select a list box item when I have the value name in a string?
[ "", "c#", "listbox", "" ]
I have a string: ``` HLN (Formerly Headline News) ``` I want to remove everything inside the parens and the parens themselves, leaving only: ``` HLN ``` I've tried to do this with a regex, but my difficulty is with this pattern: ``` "(.+?)" ``` When I use it, it always gives me a `PatternSyntaxException`. How can I fix my regex?
Because parentheses are special characters in regexps you need to escape them to match them explicitly. For example: ``` "\\(.+?\\)" ```
``` String foo = "(x)()foo(x)()"; String cleanFoo = foo.replaceAll("\\([^\\(]*\\)", ""); // cleanFoo value will be "foo" ``` The above removes empty and non-empty parenthesis from either side of the string. plain regex: ``` \([^\(]*\) ``` You can test here: <http://www.regexplanet.com/simple/index.html> My code is based on previous answers
How can I replace a string in parentheses using a regex?
[ "", "java", "regex", "" ]
I am writing a daemon program using python 2.5. In the main process an exit handler is registered with `atexit` module, it **seems** that the handler gets called when each child process ends, which is not I expected. I noticed this behavior isn't mentioned in python `atexit` doc, anybody knows the issue? If this is how it should behave, how can I unregister the exit handler in children processes? There is a atexit.unregister in version 3.0, but I am using 2.5.
There isn't an API to do it in Python 2.5, but you can just: ``` import atexit atexit._exithandlers = [] ``` in your child processes - if you know you only have one exit handler installed, and that no other handlers are installed. However, be aware that some parts of the stdlib (e.g. `logging`) register `atexit` handlers. To avoid trampling on them, you could try: ``` my_handler_entries = [e for e in atexit._exithandlers if e[0] == my_handler_func] for e in my_handler_entries: atexit._exithandlers.remove(e) ``` where `my_handler_func` is the `atexit` handler you registered, and this should remove your entry without removing the others.
When you `fork` to make a child process, that child is an exact copy of the parent -- including of course registered exit functions as well as all other code and data structures. I believe that's the issue you're observing -- of course it's not mentioned in each and every module, because it necessarily applies to every single one.
Is registered atexit handler inherited by spawned child processes?
[ "", "python", "multiprocessing", "atexit", "" ]
I want to show a open dialog for the user, where the user can select only the files from the removable disks in the system. I am using the below code. But i need to get the Guid of removable disk to open the dialog. Tell me how... ``` System.Windows.Forms.OpenFileDialog dls = new System.Windows.Forms.OpenFileDialog(); dls.CustomPlaces.Clear(); foreach (DriveInfo Drive in ListDrives) { if (Drive.DriveType == DriveType.Removable) { dls.CustomPlaces.Add(-----Guid of Drive------); } dls.ShowDialog(); } ```
I don't have an answer how to get the Guids for the removable drives, however setting the `CustomPlaces` collection will not restrict your users from selecting anything but the folders in the collection, they will simply show up as shortcuts on the left of the open file dialog, and then only if you have the `AutoUpgradeEnabled` proptery set to `true` and your users are running Windows Vista or higher. See: <http://msdn.microsoft.com/en-us/library/bb397814.aspx> Although, to finish off where you started, use the `DriveInfo.Name` to create a new entry in your custom places: ``` System.Windows.Forms.OpenFileDialog dls = new System.Windows.Forms.OpenFileDialog(); dls.CustomPlaces.Clear(); foreach (DriveInfo Drive in ListDrives) { if (Drive.DriveType == DriveType.Removable) { dls.CustomPlaces.Add(Drive.Name); } dls.ShowDialog(); } ```
Karthik, a better approach will be to get the path of selected file and check if it is from removable drive. ``` OpenFileDialog ofd = new OpenFileDialog(); ofd.CustomPlaces.Clear(); foreach (var item in System.IO.DriveInfo.GetDrives()) { if (item.DriveType == DriveType.Removable) ofd.CustomPlaces.Add(item.RootDirectory.ToString()); } if (ofd.ShowDialog() == DialogResult.OK) { FileInfo f = new FileInfo(ofd.FileName); string s = f.Directory.Root.ToString(); DriveInfo df = new DriveInfo(s); if (df.DriveType == DriveType.Removable) { //DO STUFF WITH FILE } } ```
Opendialog for showing Removable disks in c#
[ "", "c#", "" ]
I am studying snapshot isolation level of SQL Server 2008 from the below link. My confusion is, <http://msdn.microsoft.com/en-us/library/ms173763.aspx> 1. It is mentioned "Data modifications made by other transactions after the start of the current transaction are not visible to statements executing in the current transaction." -- seems data committed by other transactions are not visible to the current snapshot isolation level transaction; 2. It is mentioned "A transaction running under SNAPSHOT isolation level can view changes made by that transaction." -- seems data committed by other transactions are visible to the current snapshot isolation level transaction. Seems 1 and 2 are conflicting? Any comments? thanks in advance, George
Number 2 means "I can see my own changes; I can't see other changes" So if I start a transaction and I make changes, I can see them. Other transactions for other sessions/connections started after my TXN can not see my changes
You also need to know the difference between SNAPSHOT and READ COMMITTED SNAPSHOT - for the latter, you need to modify your quote from BOL as follows: "Data modifications made by other transactions after the start of the current STATEMENT (not transaction!) are not visible to statements executing in the current transaction." An example of a case when it makes a big difference: [When Snapshot Isolation Helps and When It Hurts](http://www.devx.com/dbzone/Article/32957/0/page/3)
SQL Server snapshot isolation level issue
[ "", "sql", "sql-server", "sql-server-2008", "transactions", "isolation-level", "" ]
I am trying to come up with a "smart" and "secure" way of generating about 63million unique codes to be used in a competition. The codes will be about 10 characters long. Has anyone done anything similar or aware of any "hurdles" that might arise from this issues? How do we minimize the probability of someone being able to guess the codes? This project will be done in PHP, but that won't really matter, it's more of the logic that's an issue here. Any feedback would be really appreciated. **UPDATE** Just to clarify it will be 10 **characters** of case insensitive Alpha Numeric Values. A-Z0-9
**Syntax**: You probably will have people copying these codes, so that means these codes should be easy to copy. 10^10 is too small, as Gamecat points out. kgiannakakis has a better idea, but that causes another problem: "1" looks a lot like "I". "0", "C", "O" and "Q" are also quite similar. This is not a big problem. Define a safe alfabet: "0123456789ABDEFGHJKLMNPRSTUVXYZ" (leaves out COIQ) *From the comments: depending on the fonts you pick, 5/S and U/V may also be visually ambiguous; replace as required*. This is a 32 symbol (5 bit) code. A 10 character code is a 50 bits number. Those should be fairly trivial to generate, sort, copy, compare etc. Chances of being guessed are about 0.63E-7 Since the codes are too long to remember, users will need a resting point when copying them. So split the string in two or three parts and make sure the input field matches this breakdown. E.g. AKG3L-45TEE => two groups of 5, and even if you can't remember 5 chars it's a lot easier to find the point back where you stopped reading. --- **How to generate them**: This is fairly simple. You don't need a particularly sophistciated algorithm to generate candidates. You can generate 10 random numbers per code needed, take 5 bits from each number (*typically the middle bits are best, e.g. (rand()/64) modulo 32*). Use this value [0-31] as index into your alphabet. Create a database table with this string as a primary key, and insert until the table has 63 million entries. You probably want to add "generated on" and "redeemed on" dates to this table.
If I understand you correctly, you want to create 63 milion codes of 10 digits that have a low "guess factor". There are 10,000,000,000 valid combinations. Of these 63,000,000 are price numbers. 63 / 10,000 = 0.0063. So each guess has a 0,63% chance of success. Does not sound high, but with brute force, the numbers are quite easy to obtain. Are you sure the 63 on 10,000 ratio is good enough?
How to generate 63 million prize codes
[ "", "php", "" ]
One of the fields in my database is of 'DATE' Type (field-name = 'post\_date'). after fetching an array ``` $record = mysql_fetch_array($queryResult); ``` if I do ``` echo $record['post_date']; ``` I do not get any output (blank). What should I do to properly handle the date type?
If you get a blank output from doing that (and your query is non-broken), the problem is that the column value is NULL, not that there's anything wrong with the PHP interaction.
This should work. Are you sure the fieldname is right, and that there's data in there? As an aside: Dates are handled differently in MySQL and PHP: * PHP stores dates as unix time, i.e. number of seconds since 00:00:00 on Jan 1st, 1970. * MySQL stores them as Strings, like humans read them. You can use the MySQL `from_unixtime()` and `unix_timestamp()` functions to convert back and forth as required.
Why is my MySQL date displaying as blank in PHP?
[ "", "php", "mysql", "date", "" ]
It is a commonly held belief that the the C++ standard library is not generally intended to be extended using inheritance. Certainly, I (and others) have criticised people who suggest deriving from classes such as `std::vector`. However, this question: [Can what() return NULL for exceptions?](https://stackoverflow.com/q/1038482) made me realise that there is at least one part of the Standard Library that is intended to be so extended - `std::exception`. So, my question has two parts: 1. Are there any other standard library classes which are intended to be derived from? 2. If one does derive from a standard library class such as `std::exception`, is one bound by the interface described in the ISO Standard? For example, would a program which used an exception class who's `what()` member function did not return a NTBS (say it returned a null pointer) be standard conforming?
Good nice question. I really wish that the Standard was a little more explicit about what the intended usage is. Maybe there should be a C++ Rationale document that sits alongside the language standard. In any case, here is the approach that I use: (a) I'm not aware of the existence of any such list. Instead, I use the following list to determine whether a Standard Library type is likely to be designed to be inherited from: * If it doesn't have any `virtual` methods, then you shouldn't be using it as a base. This rules out `std::vector` and the like. * If it does have `virtual` methods, then it is a candidate for usage as a base class. * If there are lots of `friend` statements floating around, then steer clear since there is probably an encapsulation problem. * If it is a template, then look closer before you inherit from it since you can probably customize it with specializations instead. * The presence of policy-based mechanism (e.g., `std::char_traits`) is a pretty good clue that you shouldn't be using it as a base. Unfortunately I don't know of a nice comprehensive or *black and white* list. I usually go by gut feel. (b) I would apply [LSP](http://en.wikipedia.org/wiki/Liskov_substitution_principle) here. If someone calls `what()` on your exception, then it's observable behavior should match that of `std::exception`. I don't think that it is really a standards conformance issue as much as a correctness issue. The Standard doesn't require that subclasses are substitutable for base classes. It is really just a *"best practice"*.
a) the stream library is made to be inherited :)
Can you extend the standard library by inheritance?
[ "", "c++", "inheritance", "stl", "" ]
I have a view which was working fine when I was joining my main table: ``` LEFT OUTER JOIN OFFICE ON CLIENT.CASE_OFFICE = OFFICE.TABLE_CODE. ``` However I needed to add the following join: ``` LEFT OUTER JOIN OFFICE_MIS ON CLIENT.REFERRAL_OFFICE = OFFICE_MIS.TABLE_CODE ``` Although I added `DISTINCT`, I still get a "duplicate" row. I say "duplicate" because the second row has a different value. However, if I change the `LEFT OUTER` to an `INNER JOIN`, I lose all the rows for the clients who have these "duplicate" rows. What am I doing wrong? How can I remove these "duplicate" rows from my view? --- ### Note: This question is not applicable in this instance: > [How can I remove duplicate rows?](https://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows)
DISTINCT won't help you if the rows have any columns that are different. Obviously, one of the tables you are joining to has multiple rows for a single row in another table. To get one row back, you have to eliminate the other multiple rows in the table you are joining to. The easiest way to do this is to enhance your where clause or JOIN restriction to only join to the single record you would like. Usually this requires determining a rule which will always select the 'correct' entry from the other table. Let us assume you have a simple problem such as this: ``` Person: Jane Pets: Cat, Dog ``` If you create a simple join here, you would receive two records for Jane: ``` Jane|Cat Jane|Dog ``` This is completely correct if the point of your view is to list all of the combinations of people and pets. However, if your view was instead supposed to list people with pets, or list people and display one of their pets, you hit the problem you have now. For this, you need a rule. ``` SELECT Person.Name, Pets.Name FROM Person LEFT JOIN Pets pets1 ON pets1.PersonID = Person.ID WHERE 0 = (SELECT COUNT(pets2.ID) FROM Pets pets2 WHERE pets2.PersonID = pets1.PersonID AND pets2.ID < pets1.ID); ``` What this does is apply a rule to restrict the Pets record in the join to to the Pet with the lowest ID (first in the Pets table). The WHERE clause essentially says "where there are no pets belonging to the same person with a lower ID value). This would yield a one record result: ``` Jane|Cat ``` The rule you'll need to apply to your view will depend on the data in the columns you have, and which of the 'multiple' records should be displayed in the column. However, that will wind up hiding some data, which may not be what you want. For example, the above rule hides the fact that Jane has a Dog. It makes it appear as if Jane only has a Cat, when this is not correct. You may need to rethink the contents of your view, and what you are trying to accomplish with your view, if you are starting to filter out valid data.
So you added a left outer join that is matching two rows? OFFICE\_MIS.TABLE\_CODE is not unique in that table I presume? you need to restrict that join to only grab one row. It depends on which row you are looking for, but you can do something like this... ``` LEFT OUTER JOIN OFFICE_MIS ON OFFICE_MIS.ID = /* whatever the primary key is? */ (select top 1 om2.ID from OFFICE_MIS om2 where CLIENT.REFERRAL_OFFICE = om2.TABLE_CODE order by om2.ID /* change the order to fit your needs */) ```
How do I remove "duplicate" rows from a view?
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that [Python's `heapq` implementation](http://docs.python.org/library/heapq.html) doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting `heapify()` to result in an ordered list that facilitated list comprehension in an ordered fashion. Using a priority cue example, as in the Python documentation: ``` from heapq import heapify, heappush, heappop from random import shuffle class Item(object): def __init__(self, name): self.name = name lst = [] # iterate over a pseudo-random list of unique numbers for i in sample(range(100), 15): it = Item("Some name for %i" % i) heappush(lst, (i, it)) print([i[0] for i in lst]) ``` Results in ``` >>> [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] ``` This, we note, is not the *original* ordering of the list, but apparently some heap-centric ordering as [described here](http://docs.python.org/library/heapq.html#theory). I was lazily expecting this to be fully ordered. As a test, running the list through heapify() results in no change (as the list is already heap-ishly ordered): ``` heapify(lst) print([i[0] for i in lst]) >>> [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] ``` Whereas iterating through the list with the `heappop()` function results in ordering as expected: ``` lst2 = [] while lst: lst2.append(heappop(lst)) print([i[0] for i in lst2]) >>> [2, 7, 10, 22, 27, 32, 33, 40, 45, 51, 67, 69, 89, 94, 97] ``` So, it would seem that `heapq` does not order a list (at least in the human sense of the word), but rather the `heappush()` and `heappop()` functions are able to grok the heap-ishly ordered list. **The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results.** Is this true, and is this *always* true? (BTW: Python 3.0.1 on a WinXP system)
A heap is not a sorted list (it's a representation of a partially sorted binary tree). So yes, you're right, if you expect a heapified list to behave like a sorted list, you'll be disappointed. The only sorting assumption you can make about a heap is that `heap[0]` is always its smallest element. (It's difficult to add much to what you've already written - your question is an excellent writeup of How Things Are. 8-)
> The result: Any slicing and list > comprehension operations on a > heapified list will yield non-ordered > results. > > Is this true, and is this always true? If you just want to get a one-time sorted list, use: ``` myList.sort() ``` Priority queues/heaps can be used to implement a sort, or they can be used to keep a queue in priority form. Insertions into a heap are O(lg n), gets are O(1), and removals are O(lg n), which is a lot better than just resorting the entire list over and over again.
Does Python's heapify() not play well with list comprehension and slicing?
[ "", "python", "heap", "list-comprehension", "" ]
The following is a well known implementation of singleton pattern in C++. However, I'm not entirely sure whether its thread-safe. Based upon answers to similar question asked here previously, it seems it is thread safe. Is that so? ``` //Curiously Recurring Template Pattern //Separates a class from its Singleton-ness (almost). #include <iostream> using namespace std; template<class T> class Singleton { Singleton(const Singleton&); Singleton& operator=(const Singleton&); protected: Singleton() {} virtual ~Singleton() {} public: static T& instance() { static T theInstance; return theInstance; } }; // A sample class to be made into a Singleton class MyClass : public Singleton<MyClass> { int x; protected: friend class Singleton<MyClass>; MyClass() { x = 0; } public: void setValue(int n) { x = n; } int getValue() const { return x; } }; ```
No, this is not thread safe because the static local is not guarded in any way. By default a static local is not thread safe. This means you could run into the following issues * Constructor for the singleton runs more than once * The assignment to the static is not guaranteed to be atomic hence you could see a partial assignment in multi-threaded scenarios * Probably a few more that I'm missing. Here is a detailed blog entry by Raymond Chen on why C++ statics are not thread safe by default. * <http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx>
IT IS **NOT** THREAD SAFE. To become thread safe you should add a check before the lock (semaphore lock) and an other check after the lock. And then you are sure that even in simultaneous call from different threads you provide one instance.
Thread safe singleton implementation in C++
[ "", "c++", "multithreading", "design-patterns", "" ]
In PHP `switch` statements, does placing more common cases near the top improve performance? For example, say the following function is called 1,000 times: ``` <?php function foo_user ($op) { switch ($op) { case 'after_update': //Some Stuff case 'login': //Some other Stuff } } ``` If in 990 of the 1,000 of the times the function is called the $op argument is 'login', would performance improve by having `case: 'login'` above `case 'after_update':` in the `switch` statement? For example, would the code after `case 'after_update':` be ignored if `$op = login` was passed? I've run some informal tests on this idea, but the difference has been negligible -- perhaps because the code after `case: 'login'` and `case 'after_update':` are both trivial. I'd prefer to avoid setting up a more extensive test with non-trivial operations if someone knows the answer outright. This is specifically a Drupal question, but I imagine it could be addressed by anyone who is familiar with optimizing PHP.
This is likely going to be called a micro optimisation. I don't believe there would be a large difference. However, order does mean a lot to the logic of the switch case if you allow the cases to fall through, example ``` switch ($var) { case 0: case 1: do_it(); break; case 2: do_it_else(); break; } ``` The order is important, the case will fall through and execute any code until it hits a break. I wouldn't be concerned about the speed of the switch case, unless you had say 100 possible cases. But if then, it'd be likely you should refactor your code.
You will need a whole lot more than 1000 cases to notice a difference, but yes, there is a difference. I wrote up a test: ``` function test_switch($value) { $startTime = time() + microtime(); for ($i = 0; $i < 10000000; $i++) { switch($value) { case "abcdefg": $j = $j + 1; break; case "hijklmno": $j = $j + 1; break; } } $endTime = time() + microtime(); echo "Total time for argument $value: " . ($endTime - $startTime) . "<br>\n"; } test_switch("abcdefg"); test_switch("hijklmno"); ``` That is 10 million executions of the switch statement. The output is: ``` Total time for argument abcdefg: 3.99799704552 Total time for argument hijklmno: 5.38317489624 ``` So there is a difference, but it won't be noticeable until you reach on the order of 10 million executions, depending on your processor of course.
Does the order of cases matter in PHP switch statements?
[ "", "php", "optimization", "drupal", "micro-optimization", "" ]
Is it possible to have multiple classes that inherit/extends same class in Google AppEngine with Java (GAE/J) for my entities (JDO). For example I have: > * Content (Abstract class) > * Course and then my Course will have : > * list of Video that is extends Content > * list of Books At the same time > * Video has list of Tags > * Book has list of Tags > * Course has list of Tags Is it possible to do it GAE? I'm doing similar to this but having so much problems. Is there any examples of this kind of stuff?
**Update based on new question title** I still don't understand what your difficulty is, but I will give it a shot Your question is > Is it possible to have multiple > classes that inherit/extends same > class in Google AppEngine with Java > (GAE/J) for my entities The answer is yes, why not? I don't see anything in your question that can't be done. What problem are you having? > I'm doing similar to this but having > so much problems. Is there any > examples of this kind of stuff? > How are you doing it exactly, because I can't see anything wrong with the description you posted. and just to help you out, here is one way it can be done, ``` interface Tagable { public doSomeThingWithTagList(); } class abstract Content implements Tagable { List<Tag> tagList; } class Video extend Content implements Tagable { } class Book Tagable{ List<Tag> tagList; } class Course Tagable { List<Video> videoList; List<Books> bookList; List<Tag> tagList } ```
I'll take a shot in the dark here based on what you mentioned: * Put the tag list in Content along with management methods * Video, Books, and Course can all extend Content (not sure if this makes sense in the design) * Course can contain List of Video and Books. * All will have list of tags Like I mentioned, this may not make logical sense in your design, but without more information, I can't tell.
Complex Class Hierarchy in Google AppEngine (Java)
[ "", "java", "google-app-engine", "google-cloud-datastore", "" ]
I have written a basic Application for windows mobile 5. It is using visual studio 2008 and c# .net I am currently trying to find a way of storing my customer names but im not sure what format is best for storing data directly on the device ( i dont need it to integrate with any servers or anything) I'm hoping someone here knows which direction i should be looking. I'm looking into the dataset object at the moment but doesnt seem to be saving anything? Here is a snippet of code i've been playing with. ``` private void menuItem1_Click(object sender, EventArgs e) { DataSet mySet = new DataSet1(); DataRow oOrderRow = mySet.Tables["tblPeople"].NewRow(); oOrderRow["name"] =nameTextBox.Text; mySet.Tables["tblPeople"].Rows.Add(oOrderRow); } ```
Try [SQL Server Compact edition](http://www.microsoft.com/sqlserver/2008/en/us/compact.aspx). It's very similar to the "real" SQL Server from client perspective. It supports easy data access with LINQ.
You can create an sqlce database if ur using vs 2008 using sqlce 3.5 would be the easiest. or if you dont have a lot of data store all your information in an xml file.
How do i create a database and access it for my windows mobile 5 app?
[ "", "c#", ".net", "windows-mobile", "" ]
I have some ``` std::list<char> list_type ``` Now I have to supply contents of the list as (char \*data, int length). Is there convenient way to present list contents as pointer and length? Does `<vector>` has such interface? Thank you in advance.
You can do it with a vector, because its data is stored contiguously: ``` std::vector<char> vec; char* data = &vec[0]; int length = static_cast<int>(vec.size()); ``` For list, you have to copy the data to an array. Luckily, that too is fairly easy: ``` std::list<char> list: int length = static_cast<int>(list.size()); char* data = new char[length]; // create the output array std::copy(list.begin(), list.end(), data); // copy the contents of the list to the output array ``` Of course, you're then left with a dynamically allocated array you have to free again.
You can do this with vector, not with list. A vector is guaranteed to be a contigous chunk of memory so you can say: ``` char *data = &list_type[0]; std::vector<char>::size_type length = list_type.size(); ```
std::list<char> list_type to (char * data, int lenght)
[ "", "c++", "stl", "" ]
I have MySQL running such that I can open a client command line and log on and make databases, tables, etc. I wanted to do some AJAX. Doing AJAX with ASP, SQL Server, etc is not advisable since both places where I am hosting my websites do not use the Microsoft products. So I am forced to do my development with PHP and MySQL. I just about have everything set up. I have set up IIS so that I can go to my localhost and I can test out web pages. I have PHP installed so that I can pull up the PHP setting pages. The problem occurs when I try to bring up the MySQL database in PHP. I use this very simple PHP command: ``` <?php $con = mysql_connect('localhost', 'testuser', 'testpassword'); ?> ``` When I try to connect to the mysql database through PHP, I get this error: [Click here](http://gelsana.com/IIS%207_0%20Detailed%20Error%20-%20500_0%20-%20Internal%20Server%20Error.htm) I figure the problem must be in the settings that are in the php.ini. But it seems that my php.ini is set up for MySQL although it is not mentioned in the output when I query the phpinfo page with this code Here is the result from this: [Click here](http://gelsana.com/phpinfo.htm)
It looks that your php is missing mysql module in php.ini make sure that you have correct extensions path eg.: ``` extension_dir = "C:\php\ext" ``` and make sure you have commented out: ``` extension=php_mysql.dll extension=php_mysqli.dll ```
Which version of PHP are you running and are you sure you have MySQL installed and running on localhost with a username of "testuser" and a password of "testpassword" (and have you reloaded the privilege tables after creating those users)? Have you got IIS configured to log errors into a file - does that provide any more information?
Connecting to MySQL with PHP
[ "", "php", "mysql", "iis", "" ]
I don't understand the => part. ``` foreach ($_POST[‘tasks’] as $task_id => $v) { ``` What does it do in a foreach loop?
A foreach loops goes through each item in the array, much like a for loop. In this instance, the $task\_id is the key and the $v is the value. For instance: ``` $arr = array('foo1' => 'bar1', 'foo2' => 'bar2'); foreach ($arr as $key => $value) { echo $key; // Outputs "foo1" the first time around and "foo2" the second. echo $value; // Outputs "bar1" the first time around and" bar2" the second. } ``` If no keys are specified, like in the following example, it uses the default index keys like so: ``` $arr = array('apple', 'banana', 'grape'); foreach ($arr as $i => $fruit) { echo $i; // Echos 0 the first time around, 1 the second, and 2 the third. echo $fruit; } // Which is equivalent to: for ($i = 0; $i < count($arr); $i++) { echo $i; echo $arr[$i]; } ```
In PHP, all arrays are associative arrays. For each key and value pair in the array, the key is assigned to $task\_id and the value is assigned to $v. If you don't specify another key, the key is a 0-based integer index, however it can be anything you want to, as long as the key is only used once (trying to reuse it will mean overwriting the old value with a new value).
What does this code do? (2)
[ "", "php", "foreach", "" ]
I have some C# code that generates google maps. This codes looks at all the Points I need to plot on the map and then works out the Bounds of a rectangle to include those points. It then passes this bounds to the Google Maps API to set the zoom level appropriately to show all of the points on the map. This code is working fine however I have a new requirement. One of the points may have a precision associated with it. If this is the case then I draw a circle around the point with the radius set to the precision value. Again this works fine however my bounds checking is now not doing what I want it to do. I want to have the bounding box include the complete circle. This requires an algorithm to take a point x and calculate the point y that would be z metres north of x and also z metres south of x. Does anyone have this algorithm, preferably in C#. I did find a generic algorithm [here](http://edwilliams.org/avform.htm#Intro) but I appear to have not implemented this correctly as the answers I am getting are 1000s of km adrift. This is the Generic example ``` Lat/lon given radial and distance A point {lat,lon} is a distance d out on the tc radial from point 1 if: lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc)) IF (cos(lat)=0) lon=lon1 // endpoint a pole ELSE lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi ENDIF ``` And this is my C# translation. ``` // Extend a Point North/South by the specified distance public static Point ExtendPoint(Point _pt, int _distance, int _bearing ) { Decimal lat = 0.0; Decimal lng = 0.0; lat = Math.Asin(Math.Sin(_pt.Lat) * Math.Cos(_distance) + Math.Cos(_pt.Lat) * Math.Sin(_distance) * Math.Cos(_bearing)); if (Math.Cos(lat) == 0) { lng = _pt.Lng; // endpoint a pole } else { lng = ( (_pt.Lng - Math.Asin(Math.Sin(_bearing) * Math.Sin(_distance) / Math.Cos(lat)) + Math.PI) % (2 * Math.PI)) - Math.PI; } ret = new Point(lat,lng); return ret; } ``` I am calling this function with a bearing of 0 to calculate the new northerly position and a value of 180 to calculate the new southerly position. Can anyone either see what I have done wrong or perhaps provide a known working algorithm?
If you have a given latitude and longitude you can calculate the correct latitude and longitude of an x-km change in latitude like so: ``` new-lat = ((old-km-north + x-km-change)/40,075) * 360) ^ is the ratio of the ^ times the ratio of the circle earth the change by 360 to get the total ratio covers. covered in degrees. ``` The same can apply to longitude. If you have the total distance plus the change you can calculate the total degrees in a similar fashion. ``` new-long = ((old-km-east + x-km-change)/40,075) * 360) ^ is the ratio of the ^ times the ratio of the circle earth the change by 360 to get the total ratio covers. covered in degrees. ``` Again, these calculations should work, but I'm running off pure intuition here, but the logic does seem to hold true. Edit: As pointed out by Skizz 40,075 needs to be adjusted to the circumference of the earth at any given latitude using 2.pi.r.cos(lat) or 40074.cos(lat)
I have a very similar piece of code. It got me very close results when compared to another implementation. I think the problem with yours is that you are using "distance" as linear distance in meters instead of angular distance in radians. ``` /// <summary> /// Calculates the end-point from a given source at a given range (meters) and bearing (degrees). /// This methods uses simple geometry equations to calculate the end-point. /// </summary> /// <param name="source">Point of origin</param> /// <param name="range">Range in meters</param> /// <param name="bearing">Bearing in degrees</param> /// <returns>End-point from the source given the desired range and bearing.</returns> public static LatLonAlt CalculateDerivedPosition(LatLonAlt source, double range, double bearing) { double latA = source.Latitude * UnitConstants.DegreesToRadians; double lonA = source.Longitude * UnitConstants.DegreesToRadians; double angularDistance = range / GeospatialConstants.EarthRadius; double trueCourse = bearing * UnitConstants.DegreesToRadians; double lat = Math.Asin( Math.Sin(latA) * Math.Cos(angularDistance) + Math.Cos(latA) * Math.Sin(angularDistance) * Math.Cos(trueCourse)); double dlon = Math.Atan2( Math.Sin(trueCourse) * Math.Sin(angularDistance) * Math.Cos(latA), Math.Cos(angularDistance) - Math.Sin(latA) * Math.Sin(lat)); double lon = ((lonA + dlon + Math.PI) % UnitConstants.TwoPi) - Math.PI; return new LatLonAlt( lat * UnitConstants.RadiansToDegrees, lon * UnitConstants.RadiansToDegrees, source.Altitude); } ``` Where ``` public const double EarthRadius = 6378137.0; // WGS-84 ellipsoid parameters ``` and LatLonAlt is in degrees/meters (conversion takes place internally). Adjust as needed. I assume you can figure out what the value for `UnitConstants.DegreesToRadians` is :)
How do I find the lat/long that is x km north of a given lat/long?
[ "", "c#", "geometry", "gis", "" ]
I'm in the middle in studying some code and I encountered this word "Append" and I don't understand what it does. ### Code: ``` public static void appendData(string data) { if (isRecording) sb.Append(data + Environment.NewLine); } ``` What does append mean?
The answer from ChrisF is correct as far as StringBuilder.Append is concerned. In general, the word "Append" means "to add to the end of". See <http://en.wiktionary.org/wiki/append>.
I would guess that `sb` is of type `StringBuilder`. `Append()` adds the supplied string to the end of the string being built in the `StringBuilder` variable.
What is the meaning of the word "Append"
[ "", "c#", "" ]
I'm using Firefox and I've been reading some forums claiming this doesn't work in firefox but it has been working for me for the last few days but has stopped working and I can not figure out why. I make a AXAX POST Request using an IFrame. When I get the response I use this: ``` function startLoad(){ $.get("update.php", function(data){ if(data==''){ startLoad(); } else{ document.getElementById("tweetform").submit(); } }); } ``` However, from firebug, I get this: ``` document.getElementById("tweetform").submit is not a function [Break on this error] document.getElementById("tweetform").submit(); ``` I know submit exists, but what is going on?
My *guess* would be that you have an element in the form that is called "submit" (possibly a `<button>` or `<input type="submit">`, and that ".submit" is retrieving a reference to that element, rather than the member function "submit()". If this is the case, try renaming that element to something else (e.g., "submit\_button").
**Jason Musgrove** explained the issue well. You can use a native **submit** method of HTMLFormElement to work around a problem: ``` HTMLFormElement.prototype.submit.call($('#tweetform')[0]); ```
document.getElementById("tweetform").submit is not a function?
[ "", "javascript", "" ]
What is the difference between a synchronized method and synchronized block in Java ? I have been searching the answer on the Net, people seem to be so unsure about this one :-( My take would be there is no difference between the two, except that the synch block might be more localized in scope and hence the lock will be of lesser time ?? And in case of Lock on a static method, on what is the Lock taken ? What is the meaning of a Lock on Class ?
A synchronized method uses the method receiver as a lock (i.e. `this` for non static methods, and the enclosing class for static methods). `Synchronized` blocks uses the expression as a lock. So the following two methods are equivalent from locking prospective: ``` synchronized void mymethod() { ... } void mymethod() { synchronized (this) { ... } } ``` For static methods, the class will be locked: ``` class MyClass { synchronized static mystatic() { ... } static mystaticeq() { syncrhonized (MyClass.class) { ... } } } ``` For synchronized blocks, you can use any non-`null` object as a lock: ``` synchronized (mymap) { mymap.put(..., ...); } ``` **Lock scope** For synchronized methods, the lock will be held throughout the method scope, while in the `synchronized` block, the lock is held only during that block scope (otherwise known as critical section). In practice, the JVM is permitted to optimize by removing some operations out of the `synchronized` block execution if it can prove that it can be done safely.
A synchronized method is shorthand. This: ``` class Something { public synchronized void doSomething() { ... } public static synchronized void doSomethingStatic() { ... } } ``` is, for all intents and purposes, equivalent to this: ``` class Something { public void doSomething() { synchronized(this) { ... } } public static void doSomethingStatic() { synchronized(Something.class) { ... } } } ``` (Where `Something.class` is the class object for the class `Something`.) So indeed, with a synchronized block, you can be more specific about your lock, and more fine-grained about when you want to use it, but other than that there's no difference.
What is the difference between a synchronized method and synchronized block in Java?
[ "", "java", "multithreading", "synchronization", "synchronized", "synchronized-block", "" ]
How do I add two numbers without using ++ or + or any other arithmetic operator? It was a question asked a long time ago in some campus interview. Anyway, today someone asked a question regarding some bit-manipulations, and in answers a beautiful quide *[Stanford bit twiddling](http://graphics.stanford.edu/~seander/bithacks.html)* was referred. I spend some time studying it and thought that there actually might be an answer to the question. I don't know, I could not find one. Does an answer exist?
This is something I have written a while ago for fun. It uses a [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) representation and implements addition using repeated shifts with a carry bit, implementing other operators mostly in terms of addition. ``` #include <stdlib.h> /* atoi() */ #include <stdio.h> /* (f)printf */ #include <assert.h> /* assert() */ int add(int x, int y) { int carry = 0; int result = 0; int i; for(i = 0; i < 32; ++i) { int a = (x >> i) & 1; int b = (y >> i) & 1; result |= ((a ^ b) ^ carry) << i; carry = (a & b) | (b & carry) | (carry & a); } return result; } int negate(int x) { return add(~x, 1); } int subtract(int x, int y) { return add(x, negate(y)); } int is_even(int n) { return !(n & 1); } int divide_by_two(int n) { return n >> 1; } int multiply_by_two(int n) { return n << 1; } int multiply(int x, int y) { int result = 0; if(x < 0 && y < 0) { return multiply(negate(x), negate(y)); } if(x >= 0 && y < 0) { return multiply(y, x); } while(y > 0) { if(is_even(y)) { x = multiply_by_two(x); y = divide_by_two(y); } else { result = add(result, x); y = add(y, -1); } } return result; } int main(int argc, char **argv) { int from = -100, to = 100; int i, j; for(i = from; i <= to; ++i) { assert(0 - i == negate(i)); assert(((i % 2) == 0) == is_even(i)); assert(i * 2 == multiply_by_two(i)); if(is_even(i)) { assert(i / 2 == divide_by_two(i)); } } for(i = from; i <= to; ++i) { for(j = from; j <= to; ++j) { assert(i + j == add(i, j)); assert(i - j == subtract(i, j)); assert(i * j == multiply(i, j)); } } return 0; } ```
Or, rather than Jason's bitwise approach, you can calculate many bits in parallel - this should run much faster with large numbers. In each step figure out the carry part and the part that is sum. You attempt to add the carry to the sum, which could cause carry again - hence the loop. ``` >>> def add(a, b): while a != 0: # v carry portion| v sum portion a, b = ((a & b) << 1), (a ^ b) print b, a return b ``` when you add 1 and 3, both numbers have the 1 bit set, so the sum of that 1+1 carries. The next step you add 2 to 2 and that carries into the correct sum four. That causes an exit ``` >>> add(1,3) 2 2 4 0 4 ``` Or a more complex example ``` >>> add(45, 291) 66 270 4 332 8 328 16 320 336 ``` **Edit:** For it to work easily on signed numbers you need to introduce an upper limit on a and b ``` >>> def add(a, b): while a != 0: # v carry portion| v sum portion a, b = ((a & b) << 1), (a ^ b) a &= 0xFFFFFFFF b &= 0xFFFFFFFF print b, a return b ``` Try it on ``` add(-1, 1) ``` to see a single bit carry up through the entire range and overflow over 32 iterations ``` 4294967294 2 4294967292 4 4294967288 8 ... 4294901760 65536 ... 2147483648 2147483648 0 0 0L ```
How to add two numbers without using ++ or + or another arithmetic operator
[ "", "c++", "c", "algorithm", "bit-manipulation", "" ]
Can anyone help.. I have a generic list like so ``` IList<itemTp> itemTps; ``` itemTp basically is a class (has a number of properties) and one property on this is "code" I need to be able to sort it an specific order which i have set in another List. This list is a simple list that lists the order (starting from first to last) like say code1 code3 code2 code5 (notice it goes from 1 to 3 to 2 to 5 - these are the names, they can be called anything .. the important thing is the order, it doesn't have anything to do with the numbers) Basically i need ensure the items in itemTp sort according what is present in the other list... So imagine my Ilist is like this code1,code2,code3,code5 - so once the sort is done in my ``` IList<itemTp> ``` will contain 4 classes that are in order and have the property like code1,code3,code2,code5 (order change) Any ideas how to do this?
You'll need to create an IComparer that will compare items based on the state of your other list. The advantage of using an IComparer is that you'll be able to build caching logic into your class to avoid repeated IndexOf() lookups if you need that optimization. Also, you'll be able to maintain multiple "other" lists that can be used when appropriate. ``` class ItemTpComparer : IComparer<itemTp> { private IList<codeTp> otherList; public ItemTpComparer(IList<codeTp> otherList) { this.otherList = otherList; } public int Compare(itemTp a, itemTp b) { return otherList.IndexOf(a.Code) - otherList.IndexOf(b.Code); } } ``` And to perform the sort: ``` myList.Sort(new ItemTpComparer(otherList)); ```
Using C# 3 and LINQ to Objects, I would just create a new list instead of trying to sort the existing one: ``` void Example() { IList<string> codes; IList<ItemTp> itemTps; itemTps = codes.Select(code => itemTps.Single(itp => itp.Code == code)).ToList(); } ```
Sorting an List<> with my custom order which is stored in another List (C#)?
[ "", "c#", ".net", "visual-studio", "sorting", "" ]
I want to write a lambda expression within an inline if statement. But inline if statement must have strong type results. ``` MyType obj = someObj.IsOk ? null : () => { MyType o = new MyType(intVal); o.PropertyName = false; return o; }; ``` Of course this doesn't work, because lambda expression isn't strongly typed. I thought of using `Func<intVal, MyType>` delegate, to make it strong type. But how do I use this `Func<>` inside inline if? Is it at all possible of would I have to define my own function outside and use it in inline if statement?
Even with the more complicated code, you can use an object initializer expression: ``` MyType obj = someObj.IsOk ? null : new MyType(intVal) { ProName = false }; ``` If you *really* want to use a lambda though, you could write: ``` MyType obj = someObj.IsOk ? null : ((Func<MyType>) (() => { MyType o = new MyType(intVal); o.ProName = false; return o; }))(); ``` However, this is frankly a *nightmare* of brackets and casts. You can make it simpler with a helper method: ``` public T Execute(Func<T> func) { return func(); } ... MyType obj = someObj.IsOk ? null : Execute(() => { MyType o = new MyType(intVal); o.ProName = false; return o; }); ```
It has nothing to do with the lambda's typing here. You are trying to return either `null` or (a function taking no arguments and returning a MyType) but you are telling the compiler that the result of that statement is not a function, but just a MyType. I think what you want to do is ``` MyType obj = someObj.IsOk ? null : new MyType(intVal); ```
How to write strongly typed lambda expressions?
[ "", "c#", "lambda", "inline-if", "" ]
I'm developing a simple web app, and it makes a lot of sense to store some denormalized data. Imagine a blogging platform that keeps track of Comments, and the BlogEntry model has a "CommentCount" field that I'd like to keep up to date. One way of doing this would be to use Django signals. Another way of doing this would be to put hooks directly in my code that creates and destrys Comment objects to synchronously call some methods on BlogEntry to increment/decrement the comment count. I suppose there are other pythonic ways of accomplishing this with decorators or some other voodoo. What is the standard Design Pattern for denormalizing in Django? In practice, do you also have to write consistency checkers and data fixers in case of errors?
You have managers in Django. Use a customized manager to do creates and maintain the FK relationships. The manager can update the counts as the sets of children are updated. If you don't want to make customized managers, just extend the `save` method. Everything you want to do for denormalizing counts and sums can be done in `save`. You don't need signals. Just extend `save`.
I found [django-denorm](http://github.com/initcrash/django-denorm) to be useful. It uses database-level triggers instead of signals, but as far as I know, there is also branch based on different approach.
Best way to denormalize data in Django?
[ "", "python", "mysql", "django", "" ]
Suppose I have attached a variety of event listeners to various form elements. Later, I want to remove the entire form. Is it necessary (or suggested) to unregister any event handlers that exist on the form and its elements? If so, what is the easiest way to remove all listeners on a collection of elements? What are the repercussions of not doing so? I'm using Prototype, if it matters. Here's what I'm actually doing. I have a simple form, like this: ``` <form id="form"> <input type="text" id="foo"/> <input type="text" id="bar"/> </form> ``` I observe various events on the inputs, e.g.: ``` $('foo').observe('keypress', onFooKeypress); $('bar').observe('keypress', onBarKeypress); ``` etc. The form is submitted via AJAX and the response is a new copy of the form. I replace the old form with a copy of the new one doing something like `$('form').replace(newForm)`. Am I accumulating a bunch of event cruft?
Yeah, a bit. Not enough to be a huge problem, but older versions of IE will leak under those circumstances. As of Prototype 1.6.1 (currently in its final release candidate), the library handles this cleanup on page unload. When you use Prototype to add an event observer, it keeps a reference to that element in an array; on page unload, it loops through that array and removes all your observers. However, if the user is going to stay on this page for a while, memory usage will accumulate over the life of the page. You have several options: 1. Listen for events on an *ancestor* of the form, one that never gets replaced. Then, in your handler, check where the event came from. (i.e., "event delegation") 2. Explicitly un-register all your calls before calling `Element#replace`. In your example, you'd do: ``` $('foo', 'bar').each(Element.stopObserving); ``` This is equivalent to calling `stopObserving` with no arguments, which has the effect of removing *all* handlers on a given element. I would recommend option 1. (We've talked about doing automatic listener removal in a future version of Prototype as part of `Element#update` and `Element#replace`, but it's a performance trade-off.)
Events which are not unregistered may not free their memory automatically. This is especially a problem in older versions of IE. Prototype used to have an automatic garbage collection system for this, but the method has been removed in version 1.6. It is documented [here](http://www.prototypejs.org/api/event/unloadCache). Whether the removal of the method means that the garbage collection no longer takes place, or the method just isn't publicly available anymore, I don't know. Also note that it was only ever called on page unload, meaning that if your users stay on the same page for a long time while doing a lot of AJAX and DOM updates, memory may leak to an unacceptable extent even during that one page visit.
Do Javascript event listeners need to be removed prior to removing the element they're attached to?
[ "", "javascript", "events", "event-handling", "prototypejs", "dom-events", "" ]
Probably really easy for a pro, but could someone re-write this from it's PHP shorthand form to non-shorthand? ``` ($facebook) ? $fb_active_session = $facebook->fbc_is_session_active() : $fb_active_session = false; ``` Thanks!
``` if($facebook) { $fb_active_session = $facebook->fbc_is_session_active(); } else { $fb_active_session = false; } ```
It would have been better and more clearly written (still using the ternary op) as: ``` $fb_active_session = ($facebook) ? $facebook->fbc_is_session_active() : false; ```
PHP shorthand rewrite
[ "", "php", "" ]
Consider this code: ``` public <T> List<T> meth(List<?> type) { System.out.println(type); // 1 return new ArrayList<String>(); // 2 } ``` It does not compile at line 2, saying that List is required. Now, if it's changed to: ``` public <T> List<?> meth(List<T> type) { System.out.println(type); // 1 return new ArrayList<String>(); // 2 } ``` It does compile. Why? I thought the difference between declaring a generic type with T and using the wildcard was that, when using the wildcard, one cannot add new elements to a collection. Why would `<?>` allow a subtype of List to be returned? I'm missing something here, what's the explicit rule and how it's being applied?
The difference is in the return type declaration. `List<String>` is not a subtype of `List<T>`, but it is a subtype of `List<?>`. `List<?>` makes no assumptions regarding its type variable, so the following statements are valid: ``` List<?> l0 = new ArrayList<String>(); List<?> l1 = new ArrayList<Object>(); List<? extends Number> ltemp = null; List<?> l2 = ltemp; ``` `List<T>` assumes that the type argument will be resolved in the context of client (e.g. type use), when you declared it as `List<String>` or `List<Object>`. Within the method body, you cannot make any assumptions about it either.
In the first case, `T` is not necessarily a superclass of `String`. If you choose a `T` like `Integer` and call the method, it'll fail; so it won't compile. However, the second will compile as surely, any `ArrayList<String>` is a valid `List` of *something*.
Java Generic Method Question
[ "", "java", "generics", "" ]
First off the html row looks like this: ``` <tr class="evenColor"> blahblah TheTextIneed blahblah and ends with </tr> ``` I would show the real html but I am sorry to say don't know how to block it. *feels shame* Using BeautifulSoup (Python) or any other recommended Screen Scraping/Parsing method I would like to output about 1200 .htm files in the same directory into a CSV format. This will eventually go into an SQL database. Each directory represents a year and I plan to do at least 5 years. I have been goofing around with `glob` as the best way to do this from some advice. This is what I have so far and am stuck. ``` import glob from BeautifulSoup import BeautifulSoup for filename in glob.glob('/home/phi/data/NHL/pl0708/pl02*.htm'): #these files go from pl020001.htm to pl021230.htm sequentially soup = BeautifulSoup(open(filename["r"])) for row in soup.findAll("tr", attrs={ "class" : "evenColor" }) ``` I realize this is ugly but it's my first time attempting anything like this. This one problem has taken me months to get to this point after realizing that I don't have to manually go through thousands of files copy and pasting into excel. I have also realized that I can kick my computer repeatedly out of frustration and it still works (not recommended). I am getting close and I need to know what to do next to make those CSV files. Please help or my monitor finally gets hammer punched.
You need to import the [csv module](http://docs.python.org/library/csv.html) by adding `import csv` to the top of your file. Then you'll need something to create a csv file outside your loop of the rows, like so: ``` writer = csv.writer(open("%s.csv" % filename, "wb")) ``` Then you need to actually pull the data out of the html row in your loop, similar to ``` values = (td.fetchText() for td in row) writer.writerow(values) ```
You don't really explain why you are stuck - what's not working exactly? The following line may well be your problem: ``` soup = BeautifulSoup(open(filename["r"])) ``` It looks to me like this should be: ``` soup = BeautifulSoup(open(filename, "r")) ``` The following line: ``` for row in soup.findAll("tr", attrs={ "class" : "evenColor" }) ``` looks like it will only pick out even rows (assuming your even rows have the class 'evenColor' and odd rows have 'oddColor'). Assuming you want all rows with a class of either evenColor or oddColor, you can use a regular expression to match the class value: ``` for row in soup.findAll("tr", attrs={ "class" : re.compile(r"evenColor|oddColor") }) ```
Parsing HTML rows into CSV
[ "", "python", "html", "csv", "screen-scraping", "beautifulsoup", "" ]