• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Aeris130

Member
You need to call return when an item has been inserted to avoid multiple insertions, since every item past the first match will also be higher than the one you're inserting. Either that, or set some boolean to true to exit the while loop:

Code:
while (cList.hasMoreElements() && !insertionDone)

Try doing some logging to see where it goes wrong:

Code:
{
  cList.insertAt(c, count);
  insertionDone = true;
  System.out.println("Inserting " + c + " at position " + count);
  System.out.println("Current list: " + cList);
}

There also needs to be a special case before or after the loop for when the list is empty, since hasMoreElements will return false on the first run.
 

pompidu

Member
You need to call return when an item has been inserted to avoid multiple insertions, since every item past the first match will also be higher than the one you're inserting. Either that, or set some boolean to true to exit the while loop:

Code:
while (cList.hasMoreElements() && !insertionDone)

Try doing some logging to see where it goes wrong:

Code:
{
  cList.insertAt(c, count);
  insertionDone = true;
  System.out.println("Inserting " + c + " at position " + count);
  System.out.println("Current list: " + cList);
}

There also needs to be a special case before or after the loop for when the list is empty, since hasMoreElements will return false on the first run.
K let me try that. I just made the returns before your edit and it worked fine for all but 2 contacts, which didnt appear at all. Il try this
 

Aeris130

Member
The missing contacts are probably due to the fact that any item that is larger than any item currently in the list is never inserted. You can just insert the item at the end of the list if the loop ever finishes without inserting anything (insertionDone == false). The only time that happens is if the list is empty (end of the list is also the beginning), or the item being inserted is the largest (and thus belongs at the end).
 

pompidu

Member
In fact, forget the special case. You can just insert the item at the end of the list if the loop ever finishes without inserting anything (insertionDone == false). The only time that happens is if the list is empty (end of the list is also the beginning), or the item being inserted is the largest (and thus belongs at the end).

It works!! I own you something man for all your work!
Code:
public boolean insert(Contact c)
	{
		int count = 0;
		boolean insertionDone = false;
		cList.resetCurrentElement();
		while (cList.hasMoreElements() && !insertionDone)
		{
			if (cList.nextElement().compareTo(c) > 0)
			{
				cList.insertAt(c, count);
				  insertionDone = true;
				  System.out.println("Inserting " + c + " at position " + count);
				  System.out.println("Current list: " + cList);
				  return insertionDone;
			}
			else
				count++;
		}
		
		if (insertionDone == false)
		{
			cList.insertAtEnd(c);
		}
		return insertionDone;
	}
 

Aeris130

Member
You still need to decide on using insertionDone or return true (no insertionDone needed, just return true after insert and at the end.). Right now the method return false if the list was empty, since insertionDone never gets set to true inside the loop.
 

pompidu

Member
You still need to decide on using insertionDone or return true (no insertionDone needed, just return true after insert and at the end.). Right now the method return false if the list was empty, since insertionDone never gets set to true inside the loop.

The list is never empty, first one is added before the loop, inside the constructor like so
Code:
 if (i == 0)
	        	cList.insertAtBeginning(contactName);
	        else
	        	insert(contactName);

So is this more like your asking?
Code:
public boolean insert(Contact c)
	{
		int count = 0;
		boolean insertionDone = false;
		cList.resetCurrentElement();
		while (cList.hasMoreElements() && !insertionDone)
		{
			if (cList.nextElement().compareTo(c) > 0)
			{
				cList.insertAt(c, count);
				  insertionDone = true;
				  System.out.println("Inserting " + c + " at position " + count);
				  System.out.println("Current list: " + cList);
				  return true;
			}
			else
				count++;
		}
		
		if (insertionDone == false)
		{
			cList.insertAtEnd(c);
			return true;
		}
		return false;
	}
 

Aeris130

Member
The very last "return false" probably isn't needed. If insertAtEnd returns a value (depending on if if it works or not), you can just do

Code:
return cList.insertAtEnd(c);

'insertionDone = true;' after insert can be removed as well, since the method is guaranteed to return after the two print statements, so the value is never used after that.

And since insertionDone is never used inside the loop now, you can remove it from the while() statement as well.

And now that insertionDone isn't used at all, you can remove the if-case at the end (keep the insertAtEnd). Your return-statement inside the loop guarantees that the code will only reach the end of the method if the list is empty or the element should be last, so there's no scenario where the item shouldn't be inserted.
 

pompidu

Member
The very last "return false" probably isn't needed. If insertAtEnd returns a value (depending on if if it works or not), you can just do

Code:
return cList.insertAtEnd(c);

'insertionDone = true;' after insert can be removed as well, since the method is guaranteed to return after the two print statements, so the value is never used after that.

And since insertionDone is never used inside the loop now, you can remove it from the while() statement as well.

And now that insertionDone isn't used at all, you can remove the if-case at the end (keep the insertAtEnd). Your return-statement inside the loop guarantees that the code will only reach the end of the method if the list is empty or the element should be last, so there's no scenario where the item shouldn't be inserted.

Since is boolean , have to return either true or false. Works perfectly now. Really apprecitate your help!

Code:
public boolean insert(Contact c)
	{
		int count = 0;
		cList.resetCurrentElement();
		while (cList.hasMoreElements())
		{
			if (cList.nextElement().compareTo(c) > 0)
			{
				cList.insertAt(c, count);
				  System.out.println("Inserting " + c + " at position " + count);
				  System.out.println("Current list: " + cList);
				  return true;
			}
			else
				count++;
		}
		
			cList.insertAtEnd(c);
			return true;
	}
 

Fantastical

Death Prophet
I have a question about web development. I've taken three semesters worth of C++ related programming classes, and I feel I have a pretty strong grasp on the fundamentals of the language.

This summer, I want to focus on web design and development. More specifically, I aim to create a website for myself (a portfolio-type website), as well as a similar website for my sister's job. I know the basics of HTML, but I definitely need a refresh and I need to learn CSS. For this, I'm planning on buying this book: HTML and CSS: Design and Build Websites. Furthermore, I would like to learn PHP and MySQL.

I don't know, I feel a little lost. Is this a good place to start? What are some good resources for me to understand how all this works?
 
So why are Visual Studio installs so messy? It's virtually impossible to do a clean uninstall. Also I think installing Visual Studio 2012 Ultimate has managed to wipe sql express off of my computer.
 
I have a question about web development. I've taken three semesters worth of C++ related programming classes, and I feel I have a pretty strong grasp on the fundamentals of the language.

This summer, I want to focus on web design and development. More specifically, I aim to create a website for myself (a portfolio-type website), as well as a similar website for my sister's job. I know the basics of HTML, but I definitely need a refresh and I need to learn CSS. For this, I'm planning on buying this book: HTML and CSS: Design and Build Websites. Furthermore, I would like to learn PHP and MySQL.

I don't know, I feel a little lost. Is this a good place to start? What are some good resources for me to understand how all this works?

You are me. I am you. I am quite curious about this.

I already bought my domain name, so I'll end up feeling immensely guilty for not working on it this summer. There's a good first step. Hah.

So why are Visual Studio installs so messy? It's virtually impossible to do a clean uninstall. Also I think installing Visual Studio 2012 Ultimate has managed to wipe sql express off of my computer.

I've honestly given up on trying to figure out why Microsoft does what they do with software. Don't think it'll ever make sense.
 
Not sure I entirely understood what you said, but here's what I got from it.

  1. Receive a word pair
  2. In a paragraph replace the first word with the second one

Why do you need to go through the paragraph a pair at a time? str_replace takes arrays as pairs, so you could probably use that.

Code:
//Eg word pairs: "foo bar", "abc xyz"


// Sub arrays for the words to replace and the replacements
$myAry = array(array(), array());

//Splits the string, put the first word in the first array and the second to the second array.
//(stuff)

//Two arrays that contain the words to be replaced and their replacements.
// $myAry[0] has array('foo', 'abc');
// $myAry[1] has array('bar', 'xyz');

//Then
str_replace($myAry[0], $myAry[1], $paragraph);

Thanks, that helped with part of the problem but it's still not working all the way. One problem is for example the first pair does a substitution that changes the code in such a way that that same substitution can be made a second time. The second substitution wasn't possible in the original string. Only in the altered one. Using the code as is, it doesn't make the second change.

EDIT: Nevermind! I fixed it. It was actually a far stupider mistake than I intended. My code was fine. The arguments I was feeding in had a typo that made the wrong result come out. I am an idiot. :p
 

Splatt

Member
Oh man, don't worry about that, there's so many better reasons to envy me.

Is there any particular problem you're having with prolog?

Just that I have to learn a lot about it in a short amount of time.

Making a list consisting of list as members is breaking my brain.
 

cyborg009

Banned
Doing a project and it's driving me insane does anyone know a alternative of way of using a .txt file in a GUI. I was putting them in an arraylist then in a combo box but that apparently can't work.
 

squidyj

Member
No joke, I freaked out about this yesterday before we presented. I went back and changed two splash screens that had the misspelling and fixed it in the comments that described the project in the code. I rely on spellcheck way too much sometimes >_>

As disappointed as I was, it really was a great project. Probably the most fun I have ever had with programming. I was really worried that our game was going to be incredibly basic compared to all the other projects but it ended up being pretty much on par with everything else. It was a lot of fun to see what everyone else came up with during their presentations too.

My major is in Computer Science and my school does offer a game design track but I opted for a more general track called Computer Science Foundations. I'm interested in game design, but I'd have to go back and take two physics courses to get into the classes, and I have already filled my natural science requirements for my degree so going back to take those would just be extra money spent on top.

I get to take additional calculus courses to qualify for computer graphics concentration.
 

cyborg009

Banned
What does this mean?

What's them?

Oh that's just a regular text file.

In the text file I type a movie name,rating,price, and showtime I did this for four movies. I wanted to use a combo box to list the movie name and uneditable fields for the rest.
 

usea

Member
Oh that's just a regular text file.

In the text file I type a movie name,rating,price, and showtime I did this for four movies. I wanted to use a combo box to list the movie name and uneditable fields for the rest.
I don't know where you're having trouble, but here is how I would approach the problem. (I have done winform programming, but I don't claim to be good at it)

Make a data type (class) for your movies. Call it Movie. It should be pretty basic; just have four public string fields for the name, rating, price and showtime.

Make a class whose job is to take a single line of text from the file and transform it into a Movie object. Call it something like MovieMapper. It will have a single method like: public Movie Map(string line). In other words, it will take a line of text, make a new Movie object, and set the movie's properties to the correct values from the string (probably using string.Split(',') I imagine? You're probably already doing this.

Make a class whose job is reading the text file and returning a list of Movie objects. Maybe call it MovieLoader, and give it a single method like:
Code:
public ICollection<Movie> LoadMovies(string filename)
It would work like this:
1) Read all the text from the file: File.ReadAllLines(filename)
2) For each line of text, use the MovieMapper to transform that line of text into a Movie.
3) Put all the movies into a list and return them.

Now, you have a class (MovieLoader) who takes a filename and gives you back all the movies. This maybe wasn't your problem before, but putting each separate problem into its own space gives you room to reason about things. Now you can grab all the movies with a single line of code:
Code:
var movies = movieLoader.LoadMovies(@"C:\whatever\movies.txt");
Or better yet, you can also add them all to the combobox in that line too:
Code:
comboBox1.Items.AddRange(movieLoader.LoadMovies(@"C:\whatever\movies.txt");

Next you want only the name of the movie to show in the combobox right? It looks like by default the text ComboBox shows for an item is whatever is returned by that item's ToString() method: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.items.aspx
Alternatively, you can tell the combobox which property to use by setting the combobox's DisplayMember property.

So, add a ToString() method to Movie which just returns the movie's name. Like:
Code:
public override string ToString()
{
  return this.Name;
}

Now if you add a Movie to a combobox, the box will only show the movie's name.

Now to popular other text fields with other information about the movie, you want to take action whenever the user changes the combobox's selection. Register a handler for the combobox's SelectedValueChanged event. You can either do this manually with a line of code, or just go to the combobox's property window, filter by events, find SelectedValueChanged and double click on it to generate a method.

In your combobox's selected value changed event handler method, simply grab the current selection, cast it to a Movie, and fill your text boxes with the selected movie's properties. Something like this:
Code:
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
  var selectedMovie = (Movie)comboBox1.SelectedItem;
  textBox1.Text = selectedMovie.Price;
  textBox2.Text = selectedMovie.Rating;
  textBox3.Text = selectedMovie.Showtime;
}
 

cyborg009

Banned
Thanks usea I'm going try this in the morning (1:15 now). This program has made me lose sleep since I'm the only person in the group who has to do all this by myself. And the professor keeps on telling us to use a text file.
 

Kalnos

Banned
^Don't know about the credentials of the degree but my co-op jobs were extremely beneficial and I think anyone in college should pursue at least 1 internship/co-op before they graduate. Huge boost to your resume, great experience, you will probably get paid, and you might even get a job out of the deal.
 

sans_pants

avec_pénis
I have a question about web development. I've taken three semesters worth of C++ related programming classes, and I feel I have a pretty strong grasp on the fundamentals of the language.

This summer, I want to focus on web design and development. More specifically, I aim to create a website for myself (a portfolio-type website), as well as a similar website for my sister's job. I know the basics of HTML, but I definitely need a refresh and I need to learn CSS. For this, I'm planning on buying this book: HTML and CSS: Design and Build Websites. Furthermore, I would like to learn PHP and MySQL.

I don't know, I feel a little lost. Is this a good place to start? What are some good resources for me to understand how all this works?

there is a web development track on codeacademy that covers html and css
 
I have a question about web development. I've taken three semesters worth of C++ related programming classes, and I feel I have a pretty strong grasp on the fundamentals of the language.

This summer, I want to focus on web design and development. More specifically, I aim to create a website for myself (a portfolio-type website), as well as a similar website for my sister's job. I know the basics of HTML, but I definitely need a refresh and I need to learn CSS. For this, I'm planning on buying this book: HTML and CSS: Design and Build Websites. Furthermore, I would like to learn PHP and MySQL.

I don't know, I feel a little lost. Is this a good place to start? What are some good resources for me to understand how all this works?

You are me. I am you. I am quite curious about this.

I already bought my domain name, so I'll end up feeling immensely guilty for not working on it this summer. There's a good first step. Hah.

Go learn PHP and Ruby/Ruby on Rails. Html and css are actually pretty easy (as long as you don't have to support older versions of IE) but your going to need something to do the heavy lifting. I just pushed my project to heroku yesterday (after converting my database to postgresql (which was a pain)). Sql really isn't hard at all and carries over from the different types of sql pretty heavily.
 

Ziltoid

Unconfirmed Member
Does anyone know if you can assert internal signals in a VHDL module? Without connecting it to a IO port of course.

Something like: assert mymodule.internal_signal = '1'

I'm making a testbench for a project right now, and something like this would make things a lot easier.
 

Jokab

Member

image.php
 

usea

Member
Fortunately new languages like Rust are stepping up, with massive safety increases, native code, optional garbage collection, concurrency with no shared memory (totally separate heaps), etc.
although rust's array bounds checking is done at runtime, and results in a task failure

I'm always kind of surprised how many people use C++ for systems that could be done many times faster and safer in C#, Java, etc. People will use what they're familiar with, and somehow C and C++ have become the defacto languages, with all their horrible flaws.

I saw an article the other day about a "cool trick" where you can comment in/out code by adding or removing a single character. Like
Code:
/*
foo();
int x = foo();
whatever.embiggen();
//*/
You can add a single slash / to the first line and it will be commented out. Remove it, and it's back in.

I'm like, who the fuck codes like this? Don't people use an editor with a hotkey for commenting out/in blocks of code at a time? Vim, emacs, eclipse, visual studio, sublime, code blocks, fucking notepad++, they all have it. Who are these people?

answer: they're C and C++ programmers.
 

Mordeccai

Member
Hey GAF, I have a introductory python final today and am a bit stuck.

I have a file formatted in FASTA format, which looks like so

>taxon1
TTAGCTAC
AAGGCTAA
GGGTATAC
>taxon2
AAACGTAC
CCTAGACA
CCTAGGAC
AACTTTCGA

There can be any number of sequences in the file (the one I'm working with has 3, but he will test our code with files containing various numbers of sequences), and the letters below the sequence code for an amino acid sequence which can be of any length. What I want to do is store all of these sequences in a single line based format for each sequence, with the sequence# followed by a space followed by the sequence, so that I can begin the rest of the project which involves adding flags and extracting certain sequences. So the example above would become.

Sequence1 TTAGCTACAAGGCTAAGGGTATAC
Sequence2 AAACGTACCCTAGACACCTAGGACAACTTTCGA

Here is what I've written so far for my script
Code:
#!/usr/bin/python

import sys

if len(sys.argv) < 2:
    print "Usage: final1.py test.fasta"
    sys.exit(1)

testfile = sys.argv[1]

handle = open(testfile, "r")

seq = handle.read()
seq = seq.split(">")
seq.remove('')

I'm left with an output that looks like so (the letters are different from above b/c I didn't copy the exact ones)

['taxon1\nACCGTGGATC\nCCTATTGATT\nGATATTATC\n', 'taxon2\nTTCATACTA\nGGATTCATA\nGGACA\n' , 'taxon3\nTTAGGTATTT\nTTTGACCAG\nGTATACA\n' ]

Now my problem is joining these letters and removing the new line characters. I have tried
seq = seq.replace("\n", "") to no avail.
I also tried to strip the new lines with a for loop but couldn't get that to work either.

Is there any command you guys would suggest me to look up? I'm going through the Python Standard Library now and trying different things out.
 

squidyj

Member
So... this isn't really a problem I'm having but....

<redacted>


I don't think it should be correct but I can't seem to demonstrate it's failure. I should try to write a proof but I don't feel up to starting that today. is there anything obvious I'm missing?
 
Hey GAF, I have a introductory python final today and am a bit stuck.

You could consider using a dict to store the sequences, and then iterating through them to apply the changes you need to apply.

E.g.

Code:
sequences = {}
f = open("file"):
count = 1
for line in f:
    sequences[count] = line.trim()
    count = count + 1
f.close()

# now you can do your modifications
for key in sequences:
    sequences[key] = sequences[key].replace("AA", "AAT")
# or whatever you need to do
 

Ixian

Member
Now my problem is joining these letters and removing the new line characters. I have tried
seq = seq.replace("\n", "") to no avail.
I also tried to strip the new lines with a for loop but couldn't get that to work either.

Is there any command you guys would suggest me to look up? I'm going through the Python Standard Library now and trying different things out.
Code:
for index, each in enumerate(seq):
    seq[index] = each.replace("\n", "")
 

Mordeccai

Member
You could consider using a dict to store the sequences, and then iterating through them to apply the changes you need to apply.

E.g.

Code:
sequences = {}
f = open("file"):
count = 1
for line in f:
    sequences[count] = line.trim()
    count = count + 1
f.close()

# now you can do your modifications
for key in sequences:
    sequences[key] = sequences[key].replace("AA", "AAT")
# or whatever you need to do

Dictionaries! Clever, we spent about 30 minutes on them total this semester so I'm not too polished on how to use them. Thanks for the suggestion!

Code:
for index, each in enumerate(seq):
    seq[index] = each.replace("\n", "")

Wow, this did exactly what I was wanting in so few lines. Would you mind explaining this to a complete noob like myself? enumerate() will recognize an increasing set of values within a list?
 
Go learn PHP and Ruby/Ruby on Rails. Html and css are actually pretty easy (as long as you don't have to support older versions of IE) but your going to need something to do the heavy lifting. I just pushed my project to heroku yesterday (after converting my database to postgresql (which was a pain)). Sql really isn't hard at all and carries over from the different types of sql pretty heavily.

Was going to start working with Ruby on Rails when the semester finishes up. Thanks for the tip.
 

tuffy

Member
DWow, this did exactly what I was wanting in so few lines. Would you mind explaining this to a complete noob like myself? enumerate() will recognize an increasing set of values within a list?
In this instance, enumerate just makes an index for each item in the list and uses that index to update the list. You can see that index like so:
Code:
>>> list(enumerate(["a","b","c"]))
[(0, 'a'), (1, 'b'), (2, 'c')]
But it might be easier to use a list comprehension and process all your strings at once, like:
Code:
>>> seq = [each.replace("\n","") for each in seq]
which replaces your old "seq" list with a new one where all the strings have been processed.
 
Dictionaries! Clever, we spent about 30 minutes on them total this semester so I'm not too polished on how to use them. Thanks for the suggestion!



Wow, this did exactly what I was wanting in so few lines. Would you mind explaining this to a complete noob like myself? enumerate() will recognize an increasing set of values within a list?

enumerate() returns a list of tuples of the index of the value in a list, and the value itself. So for example:

if seq is the list: ["a", "b", "c"]
Code:
enumerate(seq)

Will return the list [(0, "a"), (1, "b"), (2, "c")]
the line:

Code:
for index, each in enumerate(seq):

Uses multiple assignment, so that for each value in the list (e.g: (1, "b")), the first value will be bound to index, the second to each. So for each iteration of this loop, index is the actual index of the item in the list, and each is the item itself.

Then the line:
Code:
    seq[index] = each.replace("\n", "")
Will set the value in seq at index (remember, this will be 0 then 1 then 2) to be equal to the value that is in there already (each), with newline characters replaced with nothing, having the effect of removing the newline characters.

You could achieve the same effect with a list comprehension as well:

Code:
seq = [each.replace("\n", "") for each in seq]

Edit: Beaten so hard :\
 

Mordeccai

Member
Its awesome that you guys had the same idea within minutes of each other :p A million thanks for the explanation you two spelled it out very well.

My last problem now is trying to insert a space between some of the characters in the strings located in my list. (So eventually I will be printing taxon1 ACCGTGGATCA followed by on a new line taxon2 CATTCGAC and so on)So far I have

['taxon1ACCGTGGATCAACT', 'taxon2____', 'taxon3____'] ad nauseum. I'm trying to write code to insert a space between taxon1 and the sequence while keeping in mind taxon can actually be called anything. This is what I came up with yet saw no visible change

Code:
if int in seq:
    i = seq.index(int)
    seq.append(i, " ")
print seq

Keeping in mind that FASTA format must at least number the sequence regardless of its label, I figured searching for an integer, storing the location of the integer in a variable, and adding a space after that value would work. But I'm not seeing any spaces being added. Also I think this will just recognize the first integer it finds and not the last, which would be a problem. I'm now thinking that the sequences must start with A, G, C, or T, so I could convert all the elements into all caps and identify the index where the sequence starts, and then add the space in the spot before that index. Going back to the drawing board will update with my new effort.

I feel so bad asking for all this help but I'm going through all of our class notes and not finding anything about appending stuff in the middle of a list element!
 

Tomat

Wanna hear a good joke? Waste your time helping me! LOL!
Haaaang on, not sure I read the problem correctly.

*Well since you saw it, here you go:

If the sequence starts with a capital A, G, C, or T maybe you would put in a check for a number with a capital A, G, C, or T following the number and then put the space after the number. I don't know Python so I don't know how to slap whitespaces into a string.

May or may not work depending on on what is allowed for the Taxon though. If the Taxon can have a number in the middle and random capital letters this wouldn't work.

If you know how to find the end of the Taxon part of the string maybe you could split the string there, and then join Taxon + whitespace string + AGCT string?
 

Mordeccai

Member
Haaaang on, not sure I read the problem correctly.

Caught you pre edit and yeah you had it right the first go

So I just tried this little block
Code:
for n in seq:
    if "A" "G" "C" "T":
        n.append("A", " ")
        n.append("G", " ")
        n.append("C", " ")
        n.append("T", " ")

and realized that 1) I think append actually needs an index or integer to work not a string and 2) even if that worked I'd be throwing spaces through the entire sequence and that is totally not what I want lol

Tomat we are thinking alike at least which is good. I'm trying to create an if statement that will see a capital AGC T following a number which should do the trick.
 

RobertM

Member
I hate using WebClient in C#. The program just hangs when doing DownloadString and there are no timeouts, whats up with that? Async doesn't return so that's useless.
 

Mordeccai

Member
So I wound up going back and avoiding the problem with throwing in whitespace all together by writing this up.

Code:
import sys

if len(sys.argv) < 2:
	print "Usage: final1.py test.fasta"
	print "This script will read in a FASTA formatted file and convert it into a single line based"
	print "format for each sequence in the file."
	sys.exit(1)

testfile = sys.argv[1]

handle = open(testfile, "r")

seq = handle.read()
seq = seq.split(">") 
seq.remove('')

for line in seq:
	seq = ''.join(line)
	seq = seq.replace("\n", " ", 1)
	seq = seq.replace("\n", "")
	print "%s" % seq
handle.close()

This gives me the space between the taxon and the sequence that I needed. But at least I learned something! Thanks to everyone who chimed in.
 

usea

Member
I hate using WebClient in C#. The program just hangs when doing DownloadString and there are no timeouts, whats up with that? Async doesn't return so that's useless.
DownloadString is synchronous, while DownloadStringAsync is not. So DownloadString will wait until it's done before your code moves on. Is this for a Windows Form app? If you're doing some long-running operation in the GUI thread, yeah it'll freeze. You should put it in another thread, or use the Async version. The async one isn't broken, it does return. You have to subscribe to the DownloadStringCompleted event and check the Result property.

Also, WebClient is considered deprecated in favor of HttpClient, but that's only for .NET 4.5. I still use WebClient.

Code:
using(var client = new WebClient())
{
    client.DownloadStringCompleted += (s,e) => textBox1.Text = e.Result;
    client.DownloadStringAsync(new Uri(@"http://something.com/whatever.txt"));
}

As for a timeout, you can cancel the async version above after a period of time. But you have to do it yourself (with a timer or whatever)

Also if you're using .NET 4.5 / C# 5, the above is a lot easier using the await keyword.
 
We're making a postfix calculator in C++ using linked lists. However, mine has a weird error that I can't figure out. Could somebody look at this and help me determine where the problem lies?

4 7 9 2 - * 3 / + p should give 20 but I'm getting 4

My linked list "stack"
Code:
2
9    ---> 9 - 2 = 7
7
4
-----
7
7   ---> 7 * 7 = 49
4
-----
SHOULD BE --- ACTUALLY
3             49
49            3
4             4
 

Magni

Member
Anyone with some Groovy/Grails experience here? I have a class project with some pretty strict guidelines to follow, specifically that I need to make a "Course" table in my database with a non-standard primary key. Instead of the default 'id: Integer' that is created automatically, I need a column called 'code' of type String.

Code:
class Course {

  String title

  static constraints = {
    title blank: false
  }
	
  static mapping = {
    version false
    id column: 'code', type: 'string', generator: 'assigned'
  }
}

This works fine, but then I can't save any objects I create:

Code:
def foo = new Course(title: "bar")
foo.save()
[B]org.springframework.orm.hibernate3.HibernateSystemException: ids for this class must be manually assigned before calling save()[/B]

def foo = new Course(title: "bar", code: "baz")
foo.save()
[B]org.springframework.orm.hibernate3.HibernateSystemException: ids for this class must be manually assigned before calling save()[/B]

def foo = new Course(title: "bar", id: "baz")
foo.save()
[B]org.springframework.orm.hibernate3.HibernateSystemException: ids for this class must be manually assigned before calling save()[/B]

I always get the same error, what am I doing wrong?
 

usea

Member
We're making a postfix calculator in C++ using linked lists. However, mine has a weird error that I can't figure out. Could somebody look at this and help me determine where the problem lies?

4 7 9 2 - * 3 / + p should give 20 but I'm getting 4

My linked list "stack"
The result of your operation is somehow going on the stack after the next number? Can't help without your code.
 
The result of your operation is somehow going on the stack after the next number? Can't help without your code.

Hmm, I was trying to avoid having crazy amounts of code up. This is my best attempt to shorten it into what's happening:

Linked list function that adds nodes to the tail (**info is actually that last node's next pointer)
Code:
void listValues( char *integer, struct values **info )
{
     struct values* current = (struct values*)malloc(sizeof(struct values));

     current->num = atoi(integer);
     current->next = *info;
     *info = current;
}

In another function, a switch case performs the operation (addition in this case), stores it in the next to last node and cuts ties with the last node.
Code:
case '+':
     first = first + second;
     replacement->num = first;
     replacement->next = '\0';
     break;
Again, using the example above I get 4 instead of 20.
 
Top Bottom