Friday, April 15, 2011

Read from file in eclipse

Hi,

I'm trying to read from a text file to input data to my java program. However, eclipse continuosly gives me a Source not found error no matter where I put the file.

I've made an additional sources folder in the project directory, the file in question is in both it and the bin file for the project and it still can't find it.

I even put a copy of it on my desktop and tried pointing eclipse there when it asked me to browse for the source lookup path.

No matter what I do it can't find the file.

here's my code in case it's pertinent:

System.out.println(System.getProperty("user.dir"));
 File file = new File("file.txt");


 Scanner scanner = new Scanner(file);

in addition, it says the user directory is the project directory and there is a copy there too.

I have no clue what to do.

Thanks, Alex

after attempting the suggestion below and refreshing again, I was greeted by a host of errors.

FileNotFoundException(Throwable).<init>(String) line: 195
FileNotFoundException(Exception).<init>(String) line: not available FileNotFoundException(IOException).<init>(String) line: not available
FileNotFoundException.<init>(String) line: not available
URLClassPath$JarLoader.getJarFile(URL) line: not available
URLClassPath$JarLoader.access$600(URLClassPath$JarLoader, URL) line: not available
URLClassPath$JarLoader$1.run() line: not available
AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] URLClassPath$JarLoader.ensureOpen() line: not available URLClassPath$JarLoader.<init>(URL, URLStreamHandler, HashMap) line: not available
URLClassPath$3.run() line: not available
AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] URLClassPath.getLoader(URL) line: not available URLClassPath.getLoader(int) line: not available URLClassPath.access$000(URLClassPath, int) line: not available
URLClassPath$2.next() line: not available
URLClassPath$2.hasMoreElements() line: not available
ClassLoader$2.hasMoreElements() line: not available CompoundEnumeration<E>.next() line: not available
CompoundEnumeration<E>.hasMoreElements() line: not available
ServiceLoader$LazyIterator.hasNext() line: not available
ServiceLoader$1.hasNext() line: not available
LocaleServiceProviderPool$1.run() line: not available
AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] LocaleServiceProviderPool.<init>(Class<LocaleServiceProvider>) line: not available
LocaleServiceProviderPool.getPool(Class<LocaleServiceProvider>) line: not available NumberFormat.getInstance(Locale, int) line: not available
NumberFormat.getNumberInstance(Locale) line: not available
Scanner.useLocale(Locale) line: not available
Scanner.<init>(Readable, Pattern) line: not available
Scanner.<init>(ReadableByteChannel) line: not available Scanner.<init>(File) line: not available
code used:

System.out.println(System.getProperty("user.dir"));
 File file = new File(System.getProperty("user.dir") + "/file.txt");


 Scanner scanner = new Scanner(file);
From stackoverflow
  • Have you tried using an absolute path:

    File file = new File(System.getProperty("user.dir") + "/file.txt");

  • Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

    When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

    Also, if you're in Linux, remember that its file systems are usually case sensitive.

    Buzkie : I think the problem was I had refreshed the src and files file, but not the project file, so it never found it. thanks for the help
    Pablo Santa Cruz : Did it solve your problem?
    Buzkie : yes it works now
  • There's nothing wrong with your code, the following works fine for me when I have the file.txt in the user.dir directory.

    import java.io.File;
    import java.util.Scanner;
    
    public class testme {
        public static void main(String[] args) {
            System.out.println(System.getProperty("user.dir"));
            File file = new File("file.txt");
            try {
                Scanner scanner = new Scanner(file);
            } catch (Exception e) {
            System.out.println(e);
            }
        }
    }
    

    Don't trust Eclipse with where it says the file is. Go out to the actual filesystem with Windows Explorer or equivalent and check.

    Based on your edit, I think we need to see your import statements as well.

  • You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

    If you whish to read the file in a given directory, you have to says so :

    File file = System.getProperty("user.dir")+"/"+"file.txt";
    

    You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

    Note that there is also a property for the separator (hard-coded to "/" in my exemple)

    regards Guillaume

how can I access the formula in an excel sheet with c#?

I am parsing thorugh a 2000+ record excel file, and need ot be able to grab the formula itself from the cells and not just the value. For example, one cell 'Contributions' may be a single number like 1500 or it can be a few numbers 1500+500-200 but I dont want the total, I want the actual formula so I can get the different numbers.

I was just parsing with an oledbconnection and that only seems to get me the total. How would I go about getting the formula? Is it possible (I can get it in either XLS or XLSX)?

Thank you.

From stackoverflow
  • A quick google found the following: http://codingsense.wordpress.com/2009/03/01/get-all-formula-from-excel-cell/

    Stuck In Baghdad : grrrrr... blocked from work, I'll have to check this from home
  • The xslx is an xml file so it should be easy enough to read. Alternatively you can use third-part components like the one from Infragistics that allows you to read xsl-files programmatically and also to access the formulas.

  • Using OLE Automation, you can access the formula in a cell as follows:

    formula = worksheet.Cells(1, 1).Formula
    

    EDIT:

    To use OLE Automation in your C# project, see the following Microsoft KB article:

    Stuck In Baghdad : can you explain more about this? What kind of object is 'worksheet'? How do I get one :P

Winforms multithreading scenario question

Hello,

this morning I saw some strange code from one of my coworkers. In an winforms application the whole Mainform was given into a thread as reference. He did this to invoke methods from the Form. Nothing to interact with the UI, just plain calculation methods. I am already sure this is not a best-practice but I wonder something. If I call methods from the Mainform from inside a thread are these methods still processed as multithreading? Or do they run inside the Mainform? Will the UI thread be affected when I call methods from the Mainfrom from a thread?

From stackoverflow
  • Functions from the form called from a different thread will run on the thread that is calling them and have no effect on the GUI thread. As a side effect, this means that if you call a function that interacts with the GUI you will get an exception.

    If you want them to be called on the GUI thread, the easiest thing to do is call Control.Invoke(...) which causes the delegate you pass in to be executed on the GUI thread, allowing GUI interaction.

Can NHibernate persist to flat files instead of database?

Here is a curiousity question. I have an application that must support both flat files and the database as a place to persist data. I was thinking maybe using a .csv or tab-delimited set of files as input ...

Is it possible to use NHibernate to write to do both persistance tasks?

From stackoverflow
  • No not to the best of my knowledge. I have the same requirement and have ended up just using flat XML files and hand rolling all the CRUD.

    Just today I did happen to notice this File System Database on codeplex but haven't looked into it properly yet.

  • Try using the Jet engine (see this)

    Dialect and other nhibernate settings should be the ones for Microsoft Access.

Hibernate rollbacks

If I do the following

session.getTransaction().rollback();

is it then ok/possible to start calling save/update/delete etc. on the same session object? Couldnt find the answer to this in the Hibernate Session/Transaction API, or in the Hibernate reference documentation.

Or do you recommend me to close that Session object, open a new Session and begin a new Transaction?

From stackoverflow
  • I'm not sure if this is possible/adviceable from a database point of view, but writing atomic code is so much better for readibility. You may even reuse the structure of a template method to forget about the wirings around your transaction.

  • I say close the session and open a new one. Hibernate is not known for being forgiving about abuse of its sessions. It may hurt performance a bit, but it will probably prevent a bug down the road.

    Yuval =8-)

Programatically loop through a DatagridView and check checkboxes

Hi ,

I have DataGridView bound by a datatable i have checkboxes to the same.

I want to navigate or loop through the the datagridview and check mark these checkboxes ,Below is the syntax i use .

foreach(DataGridViewRow dr in dgvColumns.Rows)
{
    DataGridViewCheckBoxCell checkCell =
        (DataGridViewCheckBoxCell)dr.Cells["CheckBoxes"];
    checkCell.Value=1;
    //Also tried checkCell.Selected=true;
    //Nothing seems to have worked.!
}
From stackoverflow
  • If it is bound to a DataTable, can you not work on the model (the table) instead? The DataGridView is a view...

    Try looping over the rows in the table, setting the values. For example (below) - note that I don't update the DataGridView - just the DataTable:

    using System;
    using System.Data;
    using System.Windows.Forms;
    
    static class Program
    {
        [STAThread]
        static void Main()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Selected", typeof(bool));
            table.Rows.Add("Fred", false);
            table.Rows.Add("Jo", false);
            table.Rows.Add("Andy", true);
    
            Button btn = new Button();
            btn.Text = "Select all";
            btn.Dock = DockStyle.Bottom;
            btn.Click += delegate
            {
                foreach (DataRow row in table.Rows)
                {
                    row["Selected"] = true;
                }
            };
    
            DataGridView grid = new DataGridView();
            grid.Dock = DockStyle.Fill;
            grid.DataSource = table;
    
            Form form = new Form();
            form.Controls.Add(grid);
            form.Controls.Add(btn);
            Application.Run(form);
        }
    }
    
    Marc Gravell : If it is data-bound, then changing the *bound* value should fix this too, I believe.
  • Something along the lines of:

    foreach(DataGridViewRow dgvr in dgvColumns.Rows)
    {
        // Get the underlying datarow
        DataRow dr = ((DataRowView)dgvr.DataBoundItem).Row;
    
        // Update the appropriate column in the data row.
        // Assuming this is your column name in your 
        // underlying data table
        dr["CheckBoxes"] = 1;
    }
    
    Justin Bannister : Sorry, the cast was wrong. I have amended the code above.
    Justin Bannister : Is the combo box data bound?
    Justin Bannister : Assuming you have populated the combo with data by adding items. Simply get a reference to the DataGridComboBoxCell and set the value of the item. But the item must be in the list.
  • The following worked for me, it checked the checkboxes perfectly :)

    foreach (DataGridViewRow row in dgvDataGridView.Rows)

         {
                 ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
    
          }
    

How to make WPF Expander Stretch?

The Expander control in WPF does not stretch to fill all the available space. Is there any solutions in XAML for this?

From stackoverflow
  • HorizontalAlignment="Stretch"
    
    Ngm : This is not working
  • All you need to do is this:

    <Expander>
      <Expander.Header>
        <TextBlock
          Text=”I am header text…”
          Background=”Blue”
          Width=”{Binding
            RelativeSource={RelativeSource
              Mode=FindAncestor,
              AncestorType={x:Type Expander}},
            Path=ActualWidth}”
          />
      </Expander.Header>
      <TextBlock Background=”Red”>
        I am some content…
      </TextBlock>
    </Expander>
    

    http://joshsmithonwpf.wordpress.com/2007/02/24/stretching-content-in-an-expander- header/

    Ngm : How do I do this in code? I realized that I have to account for some space for a button
    Jonathan Parker : Sorry I don't know how to do it in code.
    Josh G : TextBlock bx = new TextBlock(); bx.Text = "I am header text..."; Binding wdBind = new Binding("ActualWidth"); wdBind.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Expander), 1); bx.SetBinding(TextBlock.TextProperty, wdBind);
    Josh G : bx.Background = Colors.Blue; Expander ex = new Expander(); ex.Header = bx;
    Josh G : TextBlock contBx = new TextBlock(); contBx.Background = Colors.Red; contBx.Text = "I am some content..."; ex.Content = contBx;
    Josh G : ... This code is exactly equivalent to the XAML above.
    Jonathan Parker : Josh, you can always put this code in your own answer. That way it's more visible and can be voted on and marked as the answer.
  • Non stretchable Expanders is usually the problem of non stretchable parent controls.. Perhaps one of the parent controls has defined a HorizontalAlignment or VerticalAlignment property ?

    If you can post some sample code, we can give you a better answer..

    HTH

  • I Agree with HTH - check what sort of a container you're putting the Expander in... the StackPanel will always fold it's children down to the smallest size they can go to.

    I'm using Expanders a lot in my project, and if you drop them into a Grid / DockPanel, then the expander will fill all available space (assuming it's Vertical & Horizontal orientations are set to Stretch).

    Jonathan's suggestion of Binding the Expander's width to the container's width can get a bit tricky... I tried this technique a few weeks back and found that it can producte undesirable results in some cases, because it can inhibit the functioning of the layout system.

    PS: As a general tip (and I'm sure I'm gonna get flamed for writing this), if you're unsure of what sort of layout-container to your controls in, then start off with a Grid. Using the Column & Row definitions allows you to very easily control whether child controls use minimum space ("Auto"), maximum space ("*") or an exact amount of space ("[number]").

    Josh G : Grid is definitely the most versatile and easy to use container. I've heard that it performs much worse than most containers also.
    Bryan Anderson : @Mark, you mean you agree with Arcturus. HTH means Hope That Helps and is a common closing around here.
  • The Silverlight Toolkit includes an Accordion control which acts like an expander that always stretches to the available space. I haven't tested it yet, but it might be functional for WPF too, like the Silverlight Chart controls.

Why doesn't FileSystemWatcher detect changes from Visual Studio?

I have made a tiny application that responds to changes to files in a folder. But when I edit the file in Visual Studio 2008, it never detects anything. If I edit the file in Notepad instead, everything works as expected.

Surely Visual Studio saves the file at some point, but the watcher does not even trigger when I close the studio. Do you have any idea what I'm missing here?

This sample code (C#) should illustrate the problem:

FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("C:\Test", "*.cs");
WaitForChangedResult changed = fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All);
Console.Out.WriteLine(changed.Name);

I found a blog post by Ayende that describes the same problem, but unfortunately no solution.

From stackoverflow
  • This was really mind boggling... when you try my example program below and change the file in VS, you will notice two lines in your output window:

    Deleted

    Renamed

    So Visual Studio does never change an existing file, it saves the constents to a new file with a temporary name, then deletes the original file and renames the new file to the old name.

    Actually, this is a good practice, because if you do it the usual way (just writing the changed file, which would cause the Changed event to be fired), the event handler may be called before the writing process is complete. If the event handler processes the file contents, this may cause problems because it would process an incomplete file.

    In other words: It's not a bug, it's a feature ;-)

     static class Program
     {
      [STAThread]
      static void Main()
      {
       FileSystemWatcher FSW = new FileSystemWatcher("c:\\", "*.cs");
    
       FswHandler Handler = new FswHandler();
    
       FSW.Changed += Handler.OnEvent;
       FSW.Created += Handler.OnEvent;
       FSW.Deleted += Handler.OnEvent;
       FSW.Renamed += Handler.OnEvent;
    
       FSW.EnableRaisingEvents = true;
    
       System.Threading.Thread.Sleep(555000);
       // change the file manually to see which events are fired
    
       FSW.EnableRaisingEvents = false;
      }
     }
     public class FswHandler
     {
      public void OnEvent(Object source, FileSystemEventArgs Args)
      {
       Console.Out.WriteLine(Args.ChangeType.ToString());
      }
     }
    }
    
    Haugholt : That was not what I expected at all, but now it makes perfect sense. I suspect there is less chance of corrupting files in case of a crash, by doing it this way. Thank you!
  • Just to document this possibility ...

    From msdn:

    If multiple FileSystemWatcher objects are watching the same UNC path in Windows XP prior to Service Pack 1, or Windows 2000 SP2 or earlier, then only one of the objects will raise an event. On machines running Windows XP SP1 and newer, Windows 2000 SP3 or newer or Windows Server 2003, all FileSystemWatcher objects will raise the appropriate events.

    So my idea was that Visual Studio holds its own FileSystemWatcher on a file for whatever reason ... however you have no UNC paths and no mentioned OS.

    Treb : Good tip, thanks! The more I learn about the FileSystemWatcher, the less I like it...

reusing the backgroundworker more than once

i am using the background worker to do an expensive operation:

backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.RunWorkerAsync(inputs);

At the end i have this:

 void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   Messagebox.Show("Done with expensive operation 1"};
}

I now have another expensive operation. Can i reuse this same background worker. I now want new callbacks as i dont want switch statements on the ProgressChanged and DoWork Callbacks to determine if i am doing operation 1 or 2.

Is it just simpler to use 2 seperate background worker classes

From stackoverflow
  • Yes, you can re-use a BackgroundWorker - but you can only use it once at any time - not concurrently. If the operations are different, however, I'd use a separate worker. Otherwise you'll have to unhook the events, hook the correct events, etc. Messy.

Fastest way to create a list of unique strings from within a loop?

I have a set of strings (~80 000) I can only access sequentially by the hits.Doc(int).Get("fieldName") method.

List<string> idStrings = new List<string>();
int count = hits.Length();
for (int i = 0; i < count; i++)
{
    string idString = hits.Doc(i).Get("id");
    if (!idStrings.Contains(idString))
        idStrings.Add(idString);
}

The strings will later on have to be int.TryParse()'d. I think there should be a faster way to do this. Any suggestions?

From stackoverflow
  • The statement that slows your code down is idStrings.Contains(idString).

    You can try using a faster data structure than List (a tree or a hash table, maybe?).

    Specifically, you need a data structure with sublinear search time. Hash tables have constant search time, while trees usually have logarithmic search time.

  • First of all, use a Hashset<string> instead of a list, the Contains method will go faster:

    int count = hits.Length();
    Hashset<string> idStrings = new Hashset<string>();
    

    EDIT: You don't have to call "Contains" if you use a Hashset as it can't contain duplicate items. Just use Add, it will automatically remove duplicate values.

    itsmatt : Agreed - List.Contains() is a O(n) function. HashSet.Contains is O(1).
    borisCallens : Great, this whas what I was thinking I should remember, but didn't. Hope that makes sence to anyone :P
    borisCallens : Please note there is no overload to set the capacity by an int.
    ybo : @Boris, right, the hashset manages its capacity internally, I'll correct my answer.
  • Use a Dictionary instead of a List. The Dictionary.ContainsKey method is much faster than the List.Contains method.

    Dictionary<string, int> idStrings = new Dictionary<string, int>();
    int count = hits.Length();
    for (int i = 0; i < count; i++) {
       string idString = hits.Doc(i).Get("id");
       if (!idStrings.ContainsKey(idString)) {
          idStrings.Add(idString, 1);
       }
    }
    

    If you use framework 3.5 you can use a HashSet instead of a Dictionary:

    HashSet<string> idStrings = new HashSet<string>();
    int count = hits.Length();
    for (int i = 0; i < count; i++) {
       string idString = hits.Doc(i).Get("id");
       idStrings.Add(idString);
    }
    

Why does accessing my Storyboard x:Name work in Silverlight but not in WPF?

The following WPF code gets the error: The name 'zipButtonOut' does not exist in the current context.

However, the identical code works in Silverlight as I demonstrate here: http://tanguay.info/web/index.php?pg=codeExamples&id=65

What do I have to do to the WPF code to be able to access the Storyboard within Window.Resources? I tried it in a WPF UserControl as well but got the same error.

XAML:

<Window x:Class="TestDataGrid566.Test1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test1" Height="300" Width="300">
    <Window.Resources>
        <Storyboard x:Name="zipButtonOut" x:Key="zipButtonOut">
            <DoubleAnimation Storyboard.TargetName="buttonContinue"
Storyboard.TargetProperty="Width"
From="0" To="300" Duration="0:0:.2"></DoubleAnimation>
            <DoubleAnimation Storyboard.TargetName="buttonContinue"
Storyboard.TargetProperty="Height"
From="2" To="50" Duration="0:0:.4"></DoubleAnimation>
        </Storyboard>
    </Window.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel HorizontalAlignment="Center" Margin="20">
            <Button x:Name="buttonBegin" Content="Click here to begin" Background="Green" Click="buttonBegin_Click"/>
            <Button x:Name="buttonContinue" Margin="0 70 0 0" Width="160" Height="2" FontSize="18" Background="Yellow"
Content="Click here to continue" Visibility="Collapsed"></Button>
        </StackPanel>
    </Grid>
</Window>

code-behind:

using System.Windows;

namespace TestDataGrid566
{
    public partial class Test1 : Window
    {
        public Test1()
        {
            InitializeComponent();
        }

        private void buttonBegin_Click(object sender, RoutedEventArgs e)
        {
            buttonBegin.Visibility = Visibility.Collapsed;
            buttonContinue.Visibility = Visibility.Visible;
            //zipButtonOut.Begin(); //GETS ERROR: The name 'zipButtonOut' does not exist in the current context.
        }
    }
}
From stackoverflow
  • I don't know why it works in Silverlight, but in WPF controls you add to the resources collection are not available by their x:Name in the code behind. They're accessible through the Resources collection by their x:Key, so you can remove the x:Name attribute and add the following line of code just before the line in your code behind that is commented out, and it'll work (uncomment the line in question, of course):

    Storyboard zipButtonOut = (Storyboard)Resources["zipButtonOut"];
    

    Note that this requires the following using statement:

    using System.Windows.Media.Animation;
    
  • Looks like the VS Silverlight tools generate a "zipButtonOut" accessor for x:Name resources also. In the future, just take a look at the generated file (probably "test1.g.cs") in the obj folder to see what code is generated for x:Names.

Is there a way to use a repository as a "template" to start a new repository?

I have a Subversion repository that contains the externals and some files to start creating a new site, such as a basic login setup based on libraries.

What I'm wondering is if there is a way to "copy" this repository into another that will keep the externals so I don't have to set them up again? I'm not worried about keeping the history. This would be similar to performing an export and then setting the externals, but would be a one step process. Is there a way?

From stackoverflow
  • The commands you need are:

    svnadmin dump and svnadmin load

    Darryl Hein : Would you only dump the head version, such that it would include everything as it stands at that moment?
    nickf : no, make your template repository and then dump it and save the dump file. each time you create a new repo, load in the dump.
    Darryl Hein : I actually just tried it with the last revision and it worked perfectly!
    Stefan : make sure you use --ignore-uuid for the 'svnadmin load' command! Otherwise you'll end up with multiple repositories that have the same uuid, which will get you into troubles later.
  • Please, make sure your new repository has a new UUID. If you just copy your repository some subversion commands will see the repository as the same.

    (See svnadmin help setuuid if you need to change your uuid).

    Keeping the same UUID will break some forms of caching, intra-repository merges and probably even more in future Subversion versions. (The UUID is the primary key to identify what is from a different or the same repository)

Best way of sorting a list of strings based on difference from a target string?

I need to sort a List based on the difference between the strings in the list and a target string.

What's the best way of implementing this kind of sorting algorithm?

I don't care too much about performance but the collection could potentially become big (let's say half a million tops).

Any Help Appreciated!

From stackoverflow
  • I would recommend calculating the Levenshtein distance and then simply ordering by the integer result. (Magic code)

    public void Example()
    {
        string target = "target";
    
        List<string> myStings = new List<string>();
    
        myStings.Add("this");
        myStings.Add("that");
    
        myStrings = myStings.OrderBy(each => Levenshtein(each, target)).ToList();
    }
    
    public int Levenshtein(string stringA, string stringB)
    {
        // Magic goes here
        return 0;
    }
    

    Without OrderBy for the old skool 2.0 guys?

    List<string> myStrings;
    myStrings.Sort(LevenshteinCompare);
    ...
    
    public class LevenshteinCompare: IComparer<string>
    {
        public int Compare(string x, string y)
        {
            // Magic goes here
        }
    }
    
    JohnIdol : This looks what I am looking for. Beg your pardon for my ignorance - is the Levensthein a simple character based difference count (number of different characters)?
    Dead account : Levenshtein is commonly use for spell checkers, so L("doog","dog") and L("dag", "dog") both = 1. The first being "add o" the second being "swop a for o"
    JohnIdol : Just as a matter of interest - if I was implementing in .NET 2.0 how would you substitute the OrderBy + Lambda expression?
    JohnIdol : nice stuff - thanks for helping
    JohnIdol : I've got a problem with this - it compiles and build fine but I can't debug into the Levenshtein method (the breakpoint doesn't get hit) and it looks like it is not ordering! Any idea?
    Dead account : Try using it manually, rather than using the OrderBy method. Literally call it int i = (new LevenshteinCompare()).Compare("This", "That");
    JohnIdol : I wasn't calling ToList after the OrderBy! It's all good now (edited you code)
  • Just to make the Magic Code a little less magic take a look at:

    http://www.merriampark.com/ld.htm

    http://www.merriampark.com/ldcsharp.htm

  • What's the best way of implementing this kind of sorting algorithm?

    Being tongue-in-cheek, I'd suggest using the library implementation of quicksort, with the distance to the target string as the sorting key.

    That's of course not a helpful answer. Why not? Because what you really want to know is "What's a good difference metric for strings?"

    The answer to the real qusetion is, sadly, "it depends"; it depends on which properties of the distance you care about.

    That being said, read up on the Levenstein Distance and what it really says about the strings.

    You can modify the basic algorithm to skew the metric in favor of identical characters occurring in long runs by fiddling with the weighting of different steps in the dynamic programming matrix.

    You can also use the Soundex algorithm, which says something about which strings sound similar (but that works best for short strings; I don't know what kind of input you use).

    If the strings are of equal length, you can also use the hamming distance (count the number of indexes where the strings differ). That can probably be generalized to something by counting (unilaterally) non-existing indexes as always different, which gives you something Levenstein-like (kinda' sorta' maybe).

    The short version: it depends. I've given some input, but I can't say which is going to be a good decision for you without some more information from you.

    JohnIdol : Thanks for your answer and the overview - the only thing I care about in this case is the number of different characters - so it looks like a subcase of the Levenstein Distance (for equally long strings) would do for me!

DataGrid Paging

Hi, I am using VB.Net 2005, with IE7. I have a datagrid where I have set paging "AllowPaging" = True However, when I click the link to the next page, the records are still the same.

My code is:

ds = SQLHelper.ExecuteDataset(strConn, 
      CommandType.StoredProcedure, "GetInventory")
dv = ds.Tables(0).DefaultView
dgInvestoryList.DataSource = dv
dgInvestoryList.DataBind()

What am I missing?

From stackoverflow
  • If you are using the Wizard with the SqlDataSource, then paying will be there all ready.

    But if you go and place your code in the code behind you will have to do something like this - sorry i dont have the code for VB.NET - Must place code in the PageIndexChanging event. Use this This link to change my C# code to VB.NET, i use it ALOT

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                DataSet ds = new DataSet();
                GridView1.DataSource = ds;
                GridView1.PageIndex = e.NewPageIndex;
                this.GridView1.DataBind();
            }
            catch (Exception)
            {
                Response.Redirect("Login.aspx");
            }
    
        }
    
    Etienne : They are very similar, but cant tell u exaclty what the diff. is. But trust me, use a datagrid! Its alot easier and you can do alot more with it. Cheers and good luck

Javascript - get pixel data from image under canvas element?

You can sample pixel color data on a canvas image with getImageData(). If I layer a transparent canvas element over a background image or flash movie, can I sample a color from that via the canvas tag?

From stackoverflow
  • I think not. You would get the colour of the canvas at that point. I did find the method document.defaultview.getComputedStyle(element,pseudoElt), but on a 1 pixel div with no background-color, it returned 'transparent'.

    So, unfortunately, this may be impossible at present. What is your higher-level aim? We may be able to come up with an alternative route.

    "I had an idea earlier to copy image data into a javascript object. You could make a canvas element that covers the entire page and captures an image of the rendered screen. Once you have that data, you could do real-world cross browser testing, perhaps."

    If you don't mind that it's a static image, there is a great website that does this for you: Browser Shots. It generates screenshots of your website running in a huge range of different browsers.

    Geuis : I had an idea earlier to copy image data into a javascript object. You could make a canvas element that covers the entire page and captures an image of the rendered screen. Once you have that data, you could do real-world cross browser testing, perhaps.
    Phil H : I've added a note to the answer about the browsershots website, which should do what you're thinking in a nice, simple fashion.
  • Phil's right, you can't do it. Canvas, by design, only returns its own intrinsic pixel data, not any on-screen rendered content originating from other elements.

    You could make a canvas element that covers the entire page and captures an image of the rendered screen.

    If possible, that would be a cross-site-scripting security hole. You could iframe a target site (leveraging the users cookies/authentication/intranet to access it), then suck out the content from it pixel by pixel.

Boost considered harmful?

Lots of the answers to C++ questions here contain the response:

"You should be using boost::(insert your favourite smart pointer here) or even better boost::(insert your favourite mega complex boost type here)"

I'm not at all convinced that this is doing any favours to the questioners who, by and large, are obvious C++ novices. My reasons are as follows:

  • Using smart pointers without understanding what is going on under the hood is going to lead to a generation of C++ programmers who lack some of the basic skills of a programmer. Pretty much this seems to have happened in the Java field already.

  • Deciding which type of smart pointer to use depends very much on the problem domain being addressed. This is almost always missing from the questions posted here, so simply saying "use a shared pointer" is likely to be at the least unhelpful and possibly totally wrong.

  • Boost is not yet part of the C++ standard and may not be available on the specific platform the questioner is using. Installing it is a bit painful (I just did it using Jam) and is way overkill if all you want are a few smart pointers.

  • If you are writing FOSS code, you don't want the code to be heavily dependent on external libraries that, once again, your users may not have. I've been put off using FOSS code on a number of occasions simply because of the Byzantine complexity of the dependencies between libraries.

To conclude, I'm not saying don't recommend Boost, but that we should be more careful when doing so.

From stackoverflow
  • I disagree. No-one would suggest that you should dive in to smart pointers without a thorough understanding of what's going on behind the scenes, but used sensibly they can remove a whole host of common errors. Moreover, Boost is high-quality production code from which a C++ novice can learn a great deal, in terms of design as much as implementation. It's not all hugely complicated, either, and you can pick and choose the bits you need.

  • Few points:

    • Using anything without understanding is considered harmful. But it is only the ignorant technology user (and his manager) who gets burned in the end.
    • You don't have to install boost to get the smart pointers - they are header only. And installation itself is rather straightforward, in the simplest approach just typing one or two commands.
    • Many of the Boost libraries and solutions are present in TR1 or will be present in C++0x
    • You will always depend on external libraries... Try to choose the one that have a bright future in terms of maintenance and support.
    • Unless you want to roll-out your custom solution - which would have some advantages and disadvantages.
  • I can see your point, but understanding something does not mean that you have to rewrite everything from scratch.

    They are not "standard" but they are as standard as a library can get.

    It is true that deploying them can be painful (but not all of the sublibraries require compilation); on the other hand they do not have further dependencies on their own, so I wouldn't be too worried about that part neither.

  • I think boost is a great library. I love it. My favourite library is boost::bind and boost::function, which make function pointers much more flexible and easy-to-use. It fits in very well with different frameworks and keeps the code tidy.

    I also use different Boost classes. For example, I use boost::graph to create graph classes and I use boost::filesystem for working with files inside directories.

    However, boost is very complex. You need to be an experienced programmer to know its worth. Moreover, you need to have atleast some experience in C++ to understand how Boost works and implications of using Boost here or there.

    Therefore, I would highly recommend looking at Boost for experienced programmers, especially if they are trying to re-invent the wheel (again). It can really be what it says on the tin: a boost towards your goal.

    However, if you feel that the person asking a question is a beginner and tries to understand (for example) memory allocation, telling him to try boost smart pointers is a very bad idea. It's not helpful at all. The advantages of smart pointer classes, etc. can be comprehended only when the person experienced how standard memory allocation techniques work.

    To finish off, Boost is not like learning to drive a car with automatic gearbox. It's like learning to drive on a F1 racing car.

    David Thornley : Some parts of Boost are like a racing car. Others, like the smart pointers, can be dropped in easily with fewer problems than leaving them out would cause.
  • I disagree. Of course you will always know more about the internal workings of everything when coding it from scratch than when using 3rd party libraries. But time and money are limited, and using good 3rd party libraries such as boost is a very good way to save your resources.

    Johannes Schaub - litb : it's not going to cost you much money from sitting 2 hours and learning stuff behind smart pointers i think. it's not like you would need to learn it every time again. in fact, i think learning it once will save you more money than debugging bugs introduced by not having learned the facts.
    Adrian Grigore : I am not saying that it is not a good idea to learn how smart pointers work. But the thread is about boost being harmful, and I am honestly not interested in studying how boost::threads or boost::filesystem is implemented on each OS behind the scenes.
  • Quite frankly, for beginners I think boost isn't that well-suited. I think a beginner is better off understanding how the basics work before moving up the food chain using higher level tool/libs like boost or even STL. At the beginner stage it is not about productivity, it is about understanding. I think knowing how pointers work, being able for instance to manually create a linked list or sort one are part of the fundamentals that each programmer should learn.

    David Thornley : Beginners at what? Beginners at C++ are, I believe, best off using high-level constructs from the start, and then getting deeper in. There is little point in teaching them a way of doing something and then saying "Don't do that!"
    Johannes Schaub - litb : one does not say "don't use pointers" but one does say "avoid them". i think there is a good point in doing so. first one has to understand what problem we have (pointers being not managed for us and tracked of) and then one should see a solution (smart pointers).like i've tried to show in my answer
    Anders K. : I have met many programmers who don't know how to use pointers, the reason for this is that they never needed them. By starting with high-level constructs there is a great risk that you never bother learning how the internals work. IMHO
    Dustin Getz : but it is about productivity--engineering isn't about charity work
    Anders K. : My point was just that by using boost (as a beginner) you may miss some of the fundamental internals of the language. A skill that may come in handy when you have to deal with old legacy C++ programs
  • I would agree with the point about smart pointers. I am a C++ beginner, and when asking a simple question about pointer syntax, one answer suggested smart pointers were the way to go. I know I'm not ready for boost (I'm not really ready for the STL either), so in most cases I steer myself away from that type of suggestion.

    MadKeithV : You are selling yourself short thinking you're not ready for the STL or Boost. Try reading "Effective STL" by Scott Meyers, or the Guru Of the Week (http://www.gotw.ca/gotw/) columns - you'll find you can grasp more than you think!
    Skilldrick : Awesome link, cheers!
    jpalecek : But in your case, the answer was really irrelevant, not because it mentioned boost, but because it didn't answer the question ("don't use pointers" is not an answer to "how do I declare pointers?")
    jpalecek : OTOH, if you asked "how do I manage memory of objects stored in a container", suggesting boost would be a valid answer, and it's up to you to decide whether you take it or leave it, and it's not about what zabzonk considers harmful.
    David Thornley : You're not ready for raw pointers and arrays, if you're a C++ beginner. You are ready for STL containers and Boost smart pointers. Why do so many people insist on teaching the hard way, then telling the student to forget all that, do this instead?
    Max Lybbert : "I know I'm not ready for boost (I'm not really ready for the STL either)": Boost and the STL exist to make your job easier. If you steer yourself away from them you are condemning yourself to suffer from the problems that they solve, without knowing what those problems really are.
    jalf : There's no such thing as "not ready for STL". But you should make it clear in your answer whether you want to know "how does this work under the hood", or "what is the correct high-level way to solve this problem". The answer to the latter is often "use Boost", but the former demands an explanation
  • The consensus among almost all the answers is that boost is very valuable for experienced developers and for complex, real world, C++ software. I completely agree.

    I also think that boost can be very valuable for beginners. Isn't it easier to use lexical_cast than to use ostringstream? Or to use BOOST_FOREACH instead of iterator syntax? The big problem is lack of good documentation of boost, especially for beginners. What is needed is a book that will tell you how to start with boost, which libraries are simple libraries that simplify tasks, and which libraries are more complex. Using these libraries together with good documentation will IMO make learning C++ easier.

    • It's impossible to understand everything thoroughly all the time. So take the word of many professional C++ developers for it that many parts of boost are indeed very useful things to use in your day-to-day development.
    • The inclusion of quite a lot of boost in C++0X is testament that even the team that manages the evolution of the language thinks that boost is a Good Thing (tm)
    • C++ is a weird, tough language. It's relatively easy to learn compared to how incredibly hard it is to master. There's some really arcane stuff you can do with it. Boost::mpl builds on some of those arcane things. I love boost, but I cringe every time I see someone in my organisation use boost::mpl. The reason: even quite seasoned C++ developers have trouble wrapping their head around how it works, and the code that uses it often reflects that (it ends up looking like someone banged code out until it worked). This is not a good thing, so I partially agree that some parts of boost should not be used without caution (boost::spirit is another example).
    • The C++ standard is also a weird thing. Most common compilers don't implement all of the existing standard (e.g. template exports). It's only a guideline of what to expect.
    • If your developer doesn't have the savvy to decide which smart pointer to use in a particular situation, perhaps they shouldn't be messing around in that part of the code without senior guidance.
    • There are always external libraries, starting with the run-time. A lot of boost is header-only so it does not introduce new external dependencies.
  • Do you know how the compiler works ? Do you know how the OS works ? Do you know how the processor works ? Do you know how electronics works ? Do you know how electricity works ?

    At some point you are using a black box, the question is, "is my ignorance problematic for what I am currently doing?".

    If you have the taste for knowledge that's a great thing - and I clearly consider that a plus when interviewing engineers - but don't forget the finality of your work : build systems that solve problems.

    Tim Lesher : The rule of thumb I've always used is the one I learned a long time ago from a CS professor: "To effectively work at a level of abstraction N, you must have a working knowledge of level N-1, and an understanding of the principles of N-2."
    Johannes Schaub - litb : "Do you know how the compiler works ? Do you know how the OS works ? Do you know how the processor works ? Do you know how electronics works ? Do you know how electricity works ?" one doesn't need to know that. but one cares about how a scoped_ptr deletes your object and how a shared_ptr doesn't :)
    greyfade : In answer to these questions: Yes, unfortunately yes, yes, yes, and yes. I really wish I didn't.
    prestomation : @Tim, That was almost mindblowing. I wish I had CS professors like that.
    Jason Short : Actually when I went to university it was required before learning coding that you actually did understand electricty and how the gates all work in the computer. And yes, we did actually write OS code in those days as well... Man, I am old.
    Max Lybbert : @J Short: we studied that too, but not before writing "Hello World." I think Computer Architecture was a second year class, and Operating Systems were third year.
    Paul Nathan : @Edouard: yes, yes, yes, somewhat, somewhat.
    Edouard A. : Most people I interview don't know much about all of this... A shame, but that's actually not that critical.
    KitsuneYMG : @Edouard yes, well enough, yes, yes, yes. CompE FTW
  • I fully agree with you. It is the reason that i first explain them how it should be done (i.e when recommending boost::variant, i explain they should in general use a discriminated union. And i try not to say it's just a "magic boost thing" but show how they in principle implemented it. When i recommend boost::shared_ptr, i explain they would need to use a pointer - but it's better to use a smart pointer that has shared ownership semantics.). I try not to say just "use boost::xxx" when i see the questioner is a beginner. It is a language that's not just as simple to use as some scripting language. One has to understand the stuff one uses, because the language does not protect the programmer from doing bad things.

    Of course it's not possible for novices to understand everything from the start on. But they should understand what their boost library solves and how it does it basically.

    You can't compare this with learning processors or assembly language first. Similar it's not important to know how the bit-pattern of a null-pointer looks like. Knowledge of those are irrelevant in learning programming with C++. But pointers, array or any other basic things in C++ is not. One doesn't get around learning them before using [boost|std]::shared_ptr or [boost|std]::array successfully. These are things that has to be understood first in order to use the boost utilities successfully in my opinion. It's not about details like how to manually implement the pimpl-idiom using raw pointers - that's not the point I'm making. But the point is that one should first know basic things about pointers or the other parts a boost library helps with (for pointers, what they are and what they are good for, for example). Just look at the shared_ptr manual and try to get it without knowing about pointers. It's impossible.

    And it's important to always point them to the appropriate boost manual. Boost manuals are high quality.

    David Thornley : Why is it necessary for me, a C++ developer, to understand how shared_ptr wraps a pointer? Why is it better for a beginner to struggle with raw pointers first?
    Johannes Schaub - litb : because the beginner has to understand what pointers are. a shared_ptr is initialized with a raw pointer. and the c++ language deals with pointers too. it's a basic construct that is inherently a part of the c++ language.
    Johannes Schaub - litb : i'm not saying beginners should use pointers in their production ready programs - of course not. but they should be familiar with them when using smart pointers imho.
    David Thornley : Familiarity with pointers is necessary, but why not teach them to write them as shared_ptr<> rather than * at first? Why not teach them things they can use at first, and then show more fundamentals?
    Johannes Schaub - litb : nothing wrong with that, i think. but it should go hand in hand imho (learning them the same time). because when they dive into arrays (though boost::array also can be taught first/at the same time), "literals", shared_ptr's ctor, main's second argument they have to understand pointers anyway.
    Johannes Schaub - litb : understanding pointers is no more difficult that understanding shared_ptr imho. so there is no problem with learning that after having looked into shared_ptr. but in my opinion, one should learn first the problems, then the solution. and not first the solution and then the problems.
    Johannes Schaub - litb : but maybe i'm just a bad teacher without working concepts :) i'm about writing a german c++ tutorial with a handful other germans. i'll look at how they do it and try becoming a better c++ teacher :)
    Johannes Schaub - litb : btw i'm not talking about trying to use raw pointers as member in classes or something like that. i mean just the basic uses (like, that they are objects on their own and store addresses as their values). i fully agree that their applications should be taught way later [...]
    Johannes Schaub - litb : [...] when it's time diving into the fun details. but their basic meaning and problems that would show up when manually messing with it should be taught first or while teaching smart points. ... ok now i'll stop spamming this comment sections :p
  • C++ is not a novice-friendly language. With apologies to Scott Meyers, a beginner isn't learning just one language with C++, but four:

    1. The C parts
    2. Object Oriented parts: classes, inheritance, polymorphism, etc.
    3. The STL: containers, iterators, algorithms
    4. Templates and metaprogramming

    I would argue that if the beginner is already climbing this mountain, they should be pointed towards the more "modern" aspects of C++ from the start. To do otherwise means that the beginner will learn C-ish C++ with regular pointers, resource leaks, etc. Find themselves in a world of pain, and then discover Boost and other libraries as a way to stem the hurt.

    It's a complicated picture no matter what, so why not point them in a direction that has a positive pay-off for the invested mental efort?

    As for dependencies, a great deal of Boost is header-only. And Boost's liberal license should permit its inclusion in just about any project.

    Edan Maor : I've been programming for a (long) while in C++, and only recently (via StackOverflow) have begun to explore the standard library. This is partly because I worked on a project that couldn't use the STL, but also partly ignorance. After reading some chapters of "The C++ Standard Library: Tutorial and Reference", I actually sat with my mouth open, amazed that the language I considered so horrible, could do some things in so few lines of code (I thought only dynamic languages could do that!).
  • Boost is a great library. I really hope that it grows in breadth and acceptance. Use it, extend it, and promote it.

    One of the great things about the .NET community is that it has a great base class library. One of the fundemental problems with C++, I believe, is the minimalistic C++ standard library. Anywhere you go to develop code, FOSS or corporate, there is some selection of libraries that are used since there isn't a broad standard library. So you end up being a INSERT_YOUR_COMPANY_HERE C++ programmer and not necessarily too transferrable. Yes, you design/architecture skills transfer, but there is the learning curve with picking up familiarity with whatever set of libraries the next place is using. Where as a .NET developer will basically be using the same class library and can hit the ground running. Also, the libraries that are built (and reused) have a broader base to build on.

    Just as an aside, you can use http://codepad.org for a code paste bin and it supports boost!

  • I'm not at all convinced that this is doing any favours to the questioners who, by and large, are obvious C++ novices. ...:

    • Using smart pointers without understanding what is going on under the hood is going to lead to a generation of C++ programmers who lack some of the basic skills of a programmer.

    Do we tell novice programmers that they must learn assembly language before they get to read up on modern programming languages? They clearly don't know what's going on under the hood otherwise.

    Should "Hello World" include an implementation of the I/O subsystem?

    Personally I learned how to construct objects before I learned how to write classes. I think I learned how to use STL vectors before I learned C-style arrays. I think it's the right approach: "here's how to refer to several nearly identical variables using a std::vector, later I'll show you what's swept under the rug via C-style arrays and new[] and delete[]."

  • I have worked for companies who have viewed boost as library to avoid due in part to its past reputation as a poorly managed project. I know things have changed with the project, but commercial projects who want to use boost must be aware of the source of the code contained in the library, or at least be assured that they're not going to be liable for IP or patent infringements.

    Sadly, the library has this reputation and it will take a while for it to break before it sees wide use in the commercial sector. I also feel this is a reason not to recommend it blindly.

    jalf : Boost is used quite a lot commercially. Have you checked this? http://www.boost.org/users/uses.html
  • I agree with you, high level libraries hide things from you. It might be a good idea in the short run, but in the long run, the novice will have severe gaps in their understanding of the language.

    It's easy for us non-novices to say "just use this library" because we've been down that long hard road of learning things the hard way, and naturally we want to save someone else the trouble of doing the same.

    Novices SHOULD have to struggle with rolling their own low-level solutions to problems. And then, when they've got a better understanding of how their own solution worked, they can use the third-party solution, confident that they have some idea of what's going on under the hood. They'll use that library better!

    I think this is a broader subject than just being about Boost. I completely regret picking up VB as my first language. If I had just started with ugly, hard to learn c, I'd be years ahead of where I am now.

    David Thornley : Again, why? You're advocating teaching them the hard stuff when they're beginning, then telling them "but don't do that, here's the easy stuff" when they're ready to write production code. Asking them to learn the low-end stuff first is nearly an infinite regress ("this is a lepton").
    Kevin Laity : What's infinite about it? I'm not asking them to go down to particle physics. I'm only asking them to go as far down as the core language. "This is a pointer. Here's how to use new. Always remember to delete your pointers. Now that you've learned that, here's a library to make your life easier."
  • I think you are mixing a lot of different concerns, not all of them related to Boost specifically:

    First, should programmers (or C++ novices specifically) be encouraged to use libraries, idioms, paradigms, languages or language features they don't understand?

    • No, of course not. Every programmer should understand the tools they use, especially in a language like C++. However, I don't see a lot of questions here on SO where people are encouraged to not understand the code they're using. When people say they want to do X in C++, I think it's find to say "Boost has an implementation of X which works, which is more than a homebrewed solution would do, so use that".

    Of course if the question is "how does X work", the question can't be answered with "use Boost's implementation". But I really don't see the problem in recommending Boost for the former kind of questions.

    I also don't see how it's even possible to use Boost without understanding what's going on under the hood. C++, with or without Boost, is not Java. Using Boost in no way protects you from the complexities of the language. You still have to worry about copy constructors, pointer arithmetics, templates and everything else that can blow up in your face.

    This is nothing like what happened in Java. They designed a language that removed all the subtleties. Boost doesn't do that. Quite the contrary, it has pioneered new idioms and techniques in generic programming. Using Boost is not always simple.

    About the availability of Boost, I think that's a non-issue. It is available on the platforms used in the vast majority of questions, and if they're not able to use Boost, the suggestion is still not harmful, just useless.

    Further, most Boost libraries are header-only and don't require you to install the whole thing. If you only want smart pointers, simply include those headers and nothing else.

    About FOSS, you have a point in some cases But I'd say this is a problem for less universal libraries that users do not have. But Boost is extremely common, and if people don't have it, they should get it, as it is applicable to pretty much any problem domain. And of course, the license is compatible with any FOSS project you care to mention. I'd rather work on a OSS project that used Boost to do the heavy lifting than one which reinvented its own (buggy and proprietary) wheels, with steep learning curves that could have been avoided.

    So yeah, in some cases, recommending Boost is unhelpful. But I don't see how it can be harmful.

    In any case, I don't see how it can be even half as harmful as teaching novices to roll their own. In C++, that's a recipe for disaster. It's the sole reason why C++ still has a reputation for being error-prone and produce buggy software. Because for far too long, people wrote everything from scratch themselves, distrusting the standard library, distrusting 3rd party code, distrusting everything that wasn't legal in C.

  • We should encourage the use of standard canned libraries (and Boost is almost as standard as they get) whenever possible.

    Some people seem to think that beginners should be taught the C side of C++ first, and then introduced to the higher-level stuff later. However, people tend to work as they're trained, so we're going to see a lot of production code written with badly managed raw pointers (well-managed raw pointers are awfully difficult sometimes), arrays (and the inevitable confusion between delete and delete []), and stuff like that. I've worked with code like that. I don't want to do it again any more than I have to.

    Start beginners off with the way you want them writing code. This means teaching them about the STL containers and algorithms and some of the Boost libraries at first, so the first thing they think about when needing a group of things is a vector<>. Then teach them the lower-level constructs, so they'll know about them (or where to look them up) when they encounter them, or on the very rare occasions when they need to micro-optimize.

    There's basically two types of programmers: the coders, who should be taught languages the way they should be writing them, and the enthusiast, who will learn the low-level stuff, including principles of operating systems, C, assembly code, and so on. Both are well served by learning the language they're going to use up front, while only the enthusiasts will be well served by learning from some arbitrary level of fundamentals.

  • A good programmer will want to learn the inner workings at some point, but maybe not today. I might be missing something but isn't telling people to use shared pointers (and telling them to be aware of cycles) a good thing?

    Making the user read a 100-page manual of different pointer types will only make them despise their current language. Also as Max Lybbert excellently pointed out: "Should Hello World include an implementation of the I/O subsystem?". Where does it end?

    No one writes as bad code as one that despises their current language ("it's crap anyway"-mindset).

  • Scoped and dynamic resource ownership are general basic neeeds and boost's implementation of'em is very good an highly recommended. I use them a lot and they work fine.