The "IT DOESN'T WORK!" thread

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

Re: The "IT DOESN'T WORK!" thread

Postby Lorenz » Sun Jul 31, 2011 1:22 am UTC

I'm not sure I understand exactly what you want. To loop through a dictionary you could use

for key in dictionary.keys():

You can then compare to the max previous value.

But I'm not sure that's what you were asking.
User avatar
Lorenz
 
Posts: 25
Joined: Fri Apr 29, 2011 5:57 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Sun Jul 31, 2011 6:18 am UTC

So, if I'm understanding you right, you have a dictionary of:
Code: Select all
the_dict["name"] = (cost, value)
and want to find the one with the highest value?

Well, first, for looping purposes, in this case, you want the_dict.items(), which returns the entries as a sequence of key-value tuples:
Code: Select all
print the_dict.items() # will print [("name", (cost, value)), ...]
(Note the nested tuples, because each entry is a tuple of key/value, and in this case value is itself a tuple)

So, to get the maximum, you can do:
Code: Select all
def getValue(val):
  return val[1][1] # val is (name, (cost, value)) so val[1][1] is value
the_max = max(the_dict.items(), key=getValue)
the_max will then be the (name, (cost, value)) tuple with the highest value... so the_max[0] will be the name that maps to the highest value in the_dict.

You also mentioned you wanted to get the one with the highest value that's less than a given cost... you can do that too:
Code: Select all
def getValue(val):
  return val[1][1] # val is (name, (cost, value)) so val[1][1] is value
the_max = max((i for i in the_dict.items() if i[1][0] <= max_cost), key=getValue)


Also, the function you use for the "key" doesn't have to be a simple extraction of a single value... you can put other code in there too, for more complicated sorting. For instance, to find the element with the highest value-per-cost ratio:
Code: Select all
def getValuePerCost(val):
  return val[1][1] / val[1][0]
the_max = max(the_dict.items(), key=getValuePerCost)
While no one overhear you quickly tell me not cow cow.
but how about watch phone?
User avatar
phlip
Restorer of Worlds
 
Posts: 6740
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia

Re: The "IT DOESN'T WORK!" thread

Postby Steax » Mon Aug 01, 2011 5:50 pm UTC

Dammit, wordpress, PHP, WHAT DO YOU WANT FROM ME?

Code: Select all

$catlist 
= new WP_Query( 'category_name='.$cat->slug.'&post_type=tutorial&orderby=date&order=asc' );
        echo '<ul>';
        while($catlist->have_posts()){
        $catlist->the_post();
        $posttitle = the_title();
        echo('<li><strong>');
        echo($posttitle); 
        echo
('</strong></li>');
    }
echo '</ul>';
 


Comes up with this:

Code: Select all
<ul>
Some Post Name<li><stong></strong></li>
Some Other Post Name<li><stong></strong></li>
</ul>


I tried all sorts of permutations to get the text to otherwise get in there.

First of all, screw you, whoever decided upon wordpress' function name conventions. WHAT THE HOLY HAMBURGER FORK IS A THE_POST() FUNCTION?

Okay, that aside. From experience, I know this kind of thing is more often than not a HTML thing. It refuses to allow X tag to be a child of Y, and so prematurely closes a tag. But now it's just refusing to open the tags where I want them to.

Maybe this is what I get for coding at 1 in the morning.

EDIT:

Okay, so my mistake was that the_title();, by default, echos the, uh, title. How was I supposed to know that? the_permalink();, which I'm using in the same line, does not do this. Listen, whoever made these functions. I hate you.

EDIT 2: Oh, so the other function was "get_permalink();". Ha. How clever. Ha ha. So I guess the equivalent would be get_title();... WAIT NO IT'S get_the_title();. BUUUUUUUUUUUUURRRRRRNNNNNNNN

EDIT 3: Oh, get_the_title requests a post ID. It won't autodetect the ALLPOWERFUL WORDPRESS LOOP. Great. Screw it.
In Minecraft, I use the username Rirez.
User avatar
Steax
SecondTalon's Goon Squad
 
Posts: 2712
Joined: Sat Jan 12, 2008 12:18 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Tue Aug 02, 2011 12:35 am UTC

On the good side, once your code is done you can show it to functional purists and send them into seizures.

Wait, that's not a good side.
While no one overhear you quickly tell me not cow cow.
but how about watch phone?
User avatar
phlip
Restorer of Worlds
 
Posts: 6740
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia

Re: The "IT DOESN'T WORK!" thread

Postby phar897 » Wed Aug 03, 2011 1:08 pm UTC

Hello All!

I'm a VB.Net newbie just trying to bring myself up to speed. I have an issue handling a scenario:

I want to convert .msg file to .tiff and then retrieve the path of the files in VB.Net. Any suggestion how I can go about this is very welcome and will be appreciated.

Thanks
phar897
 
Posts: 1
Joined: Wed Aug 03, 2011 12:53 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby RoadieRich » Thu Aug 11, 2011 5:33 pm UTC

What's a .msg file? The only slightly relevant google hit is a proprietary 3d modelling system.
roband wrote:Mav is a cow.

UniJam 2012: Inter-university Games Jam hosted by Nottingham Trent University DevSoc.
nlug: Nottingham Linux User Group
DevSoc: The Nottingham Trent University Software Development Society
User avatar
RoadieRich
The Black Hand
 
Posts: 1030
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Somewhere only we know

Re: The "IT DOESN'T WORK!" thread

Postby Anonymously Famous » Thu Aug 11, 2011 6:19 pm UTC

I suppose you could be talking about a Microsoft Outlook file, in which case I'm lost as to why you'd want to convert it to a .tiff.

However, you should be able to do it. You can access other Office programs within VB.net, so you should be able to access Outlook. I'm not sure how I'd go about it... But good luck in figuring it out!
Anonymously Famous
 
Posts: 240
Joined: Thu Nov 18, 2010 4:01 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby RoadieRich » Thu Aug 18, 2011 11:48 pm UTC

... I had some non-working IRC code I could have posted here, but I deleted it in a fit of rage. Is there any way to make py3k use bytestrings by default, or are we forced to subclass socket.socket (which went wrong the first time I tried it) or have 'b"""s everywhere? Why hasn't the distributed socket.socket been updated to take a str?
roband wrote:Mav is a cow.

UniJam 2012: Inter-university Games Jam hosted by Nottingham Trent University DevSoc.
nlug: Nottingham Linux User Group
DevSoc: The Nottingham Trent University Software Development Society
User avatar
RoadieRich
The Black Hand
 
Posts: 1030
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Somewhere only we know

Re: The "IT DOESN'T WORK!" thread

Postby TheChewanater » Fri Aug 19, 2011 3:24 am UTC

RoadieRich wrote:... I had some non-working IRC code I could have posted here, but I deleted it in a fit of rage. Is there any way to make py3k use bytestrings by default, or are we forced to subclass socket.socket (which went wrong the first time I tried it) or have 'b"""s everywhere? Why hasn't the distributed socket.socket been updated to take a str?

Because the Py3k str class only does unicode, which (I assume) cannot be used with sockets. What's wrong with having b''s everywhere?

Although, it's too bad this code doesn't change the default type of quote-enclosed characters. That would be an awesome hack.
Code: Select all
str = bytes
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.
User avatar
TheChewanater
 
Posts: 1261
Joined: Sat Aug 08, 2009 5:24 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby RoadieRich » Fri Aug 19, 2011 4:39 am UTC

TheChewanater wrote:
RoadieRich wrote:... I had some non-working IRC code I could have posted here, but I deleted it in a fit of rage. Is there any way to make py3k use bytestrings by default, or are we forced to subclass socket.socket (which went wrong the first time I tried it) or have 'b"""s everywhere? Why hasn't the distributed socket.socket been updated to take a str?

Because the Py3k str class only does unicode, which (I assume) cannot be used with sockets. What's wrong with having b''s everywhere?

Although, it's too bad this code doesn't change the default type of quote-enclosed characters. That would be an awesome hack.
Code: Select all
str = bytes

It's not having b''s everywhere I have a problem with: it's forgetting to put them in, trying to test, then having to go back. Then discovering that you need to add byte() calls as well, and then str() calls anywhere you're trying to call split() on output (or probably any other string method - bytestrings don't support the buffer protocol, apparently, which means split() fails).
roband wrote:Mav is a cow.

UniJam 2012: Inter-university Games Jam hosted by Nottingham Trent University DevSoc.
nlug: Nottingham Linux User Group
DevSoc: The Nottingham Trent University Software Development Society
User avatar
RoadieRich
The Black Hand
 
Posts: 1030
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Somewhere only we know

Re: The "IT DOESN'T WORK!" thread

Postby Ptolom » Mon Aug 22, 2011 2:15 pm UTC

If I manually move the stack pointer and then call a function, like this:
Code: Select all
tasks[task].sp=tasks[task-1].sp - padding;
  asm volatile(
    "lds r26, %0\n\t"
    "ld r28, x+\n\t"
    "out __SP_L__, r28\n\t"
    "ld r28, x\n\t"
    "out __SP_H__, r28\n\t"
    : : "x" (&(tasks[task].sp)));
  init_function();

Will the function work as normal with its stack where I put it, at least until in comes to return (which will never happen in this case)? I am trying to write a simple multitasking system and the combination of asm and C is baffling me.
It Should Be Real wrote:Fuck the wizard.
We're doing this manually.

http://www.hexifact.co.uk - Hacking blog: in which I take some things apart, and put other things together.
User avatar
Ptolom
 
Posts: 1428
Joined: Mon Mar 24, 2008 1:55 pm UTC
Location: The entropy pool (Leicester)

Re: The "IT DOESN'T WORK!" thread

Postby jareds » Fri Aug 26, 2011 7:24 am UTC

Ptolom wrote:If I manually move the stack pointer and then call a function, like this:
Code: Select all
tasks[task].sp=tasks[task-1].sp - padding;
  asm volatile(
    "lds r26, %0\n\t"
    "ld r28, x+\n\t"
    "out __SP_L__, r28\n\t"
    "ld r28, x\n\t"
    "out __SP_H__, r28\n\t"
    : : "x" (&(tasks[task].sp)));
  init_function();

Will the function work as normal with its stack where I put it, at least until in comes to return (which will never happen in this case)? I am trying to write a simple multitasking system and the combination of asm and C is baffling me.

There's a fairly decent chance it will work in your example, but then again it might not. As a rule of thumb, don't modify the stack pointer yourself in a C function unless you really, really, really know what you're doing. Instead, do it in pure assembly. You could, for example, write an assembly function call_with_stack(void (*)(void), void*) and do:
Code: Select all
tasks[task].sp=tasks[task-1].sp - padding;
call_with_stack(init_function, tasks[task].sp)
in C.
jareds
 
Posts: 317
Joined: Wed Jan 03, 2007 3:56 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby NecklaceOfShadow » Sat Aug 27, 2011 11:17 pm UTC

Umm... hi

*waves*

I don't frequent the Coding forum nearly as much as I should. I hope that you won't mind my asking for help right now.

I'm trying to write an asynchronous IRC bot in Python. I think that I've written the majority of the core methods and it should be able to connect to a network and remain on it. This is the progress I've made so far on the bot.

The weird thing is that whenever I run it, I get this exception:

Code: Select all
error: uncaptured python exception, closing channel <__main__.ServConnection connected at 0x5824f0> (<class 'AttributeError'>:'str' object has no attribute 'more' [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asyncore.py|write|89] [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asyncore.py|handle_write_event|455] [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asynchat.py|handle_write|194] [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asynchat.py|initiate_send|245])


Since the asyncore and asynchat modules are in the standard library, I'm hesitant to say that there's a bug in either of them. However, I've no idea what the flaw(s) in my program might be.
boobies?

Shadow's Crescent, my blag, is where I wax poetic about inclusiveness and the kyriarchy. Please make some thoughtful and insightful comments therein.
User avatar
NecklaceOfShadow
 
Posts: 716
Joined: Sun May 03, 2009 7:40 pm UTC
Location: In a swarm of lovelies

Re: The "IT DOESN'T WORK!" thread

Postby thoughtfully » Sun Aug 28, 2011 1:22 am UTC

It looks like you are passing a string when you should be passing a byte array. I don't have Python 3 installed, so I can't check it explicitly.
It looks like you have one of those modules that screws up the traceback, so you can't see where the problem in your code is. I hate those.
http://diveintopython3.org/strings.html#byte-arrays

asyncore and asynchat aren't that complicated. You might check them to see if the port to Python 3 wasn't just right. I think I recall reading that some of the standard library modules weren't completely converted, and I think the most frequent problem was with Unicode support.
http://innuendopoly.org/arch/2to3-bytes

I love the complex version number :)

I did see one glitch:
Code: Select all
self.data = self.data.join(self.recv(ac_in_buffer_size))
ac_in_buffer_size isn't defined in the scope of that method.
Image
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
-- Antoine de Saint-Exupery
User avatar
thoughtfully
 
Posts: 1917
Joined: Thu Nov 01, 2007 12:25 am UTC
Location: Minneapolis, MN

Re: The "IT DOESN'T WORK!" thread

Postby NecklaceOfShadow » Sun Aug 28, 2011 5:43 am UTC

I... I kind of hate bytes and strings.

I tried to amend my code to this: http://pastebin.com/wPCBHHTe This should have, in theory, solved the bytearray problem.

Now, however, I get this error:

Code: Select all
error: uncaptured python exception, closing channel <__main__.ServConnection connected at 0x5819f0> (<class 'TypeError'>:can't concat bytearray to str [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asyncore.py|write|89] [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asyncore.py|handle_write_event|455] [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asynchat.py|handle_write|194] [/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/asynchat.py|initiate_send|257] [bot.py|send|41])


As far as I've seen, I'm not concatenating strings and bytearrays. It... It, yeah.
boobies?

Shadow's Crescent, my blag, is where I wax poetic about inclusiveness and the kyriarchy. Please make some thoughtful and insightful comments therein.
User avatar
NecklaceOfShadow
 
Posts: 716
Joined: Sun May 03, 2009 7:40 pm UTC
Location: In a swarm of lovelies

Re: The "IT DOESN'T WORK!" thread

Postby RoadieRich » Mon Aug 29, 2011 1:24 am UTC

NecklaceOfShadow wrote:I... I kind of hate bytes and strings.

I've been trying an IRC bot in Py3k... so I know how you feel.

The first thing that jumps out at me is I don't think
Code: Select all
self.data.join(self.recv(ac_in_buffer_size).decode('utf-8'))

does what you think it does. It's only worked so far because it's only ever received a full line.

Try updating to 3.2. It's possible there was a bug fixed, because I can't see anything that could cause that.

The stacktrace is saying the problem is in your send() method, so you could try checking python isn't being silly with either half of that expression.
roband wrote:Mav is a cow.

UniJam 2012: Inter-university Games Jam hosted by Nottingham Trent University DevSoc.
nlug: Nottingham Linux User Group
DevSoc: The Nottingham Trent University Software Development Society
User avatar
RoadieRich
The Black Hand
 
Posts: 1030
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Somewhere only we know

Re: The "IT DOESN'T WORK!" thread

Postby Tomlidich » Mon Sep 19, 2011 10:57 pm UTC

was pretty frustrated with python for not doing accurate math the way it should. then a lightbulb went off.

import math.

needless to say, im happy now.
User avatar
Tomlidich
 
Posts: 462
Joined: Mon Sep 19, 2011 8:15 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Eftersom » Tue Sep 20, 2011 8:15 pm UTC

Hello

I just started learning Java and I'm having some troubles. I need to turn a char array into a String array, is there any way to do this? When I google I only find ways to turn a char array into a String, but that's not what I want.

this is what I've done so far:
Spoiler:
This method is supposed to turn a string into a string array. It's a part of a calculator program.
Code: Select all
 
    public static String[] divide(String input){
        String[] divided = new String[4];
         
        char[] stickspar = new char[255];
        int j=0;
        String tal = "0123456789";
        String operator = "+-*/()";
// checking if input contains 'tal' or 'operator'
        for(int i=0; i<input.length();i++){
            for(int e=0; e<11; e++)
               {
                if (input.charAt(i) == tal.charAt(e))
                   {
                    stickspar[j] = input.charAt(i);
                    j++;
             
                }
                else                                                           
                {
                    for(int u=0;u<=j;u++)
                    {
                        divided[u] = new String(stickspar);
                     

                    }
                }

            }
        }


        return divided;
    }
}

when I run this method it returns: '[Ljava.lang.String;@1b67f74'
I know there are other problems with this code than converting char array to string array, but hopefully I will be able to fix those once the converting works.


So what I want to do is turning a char array (e.g.: char[] a = {"1", "2"}) into a string array ( e.g.: String[] b ={"12"}) then I want to add more arrays to that string. Anyone who knows how to do this?
Eftersom
 
Posts: 1
Joined: Sat Jun 11, 2011 8:31 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Fri Sep 23, 2011 2:22 am UTC

Eftersom wrote:when I run this method it returns: '[Ljava.lang.String;@1b67f74'

That looks like the sort of thing you'd get if you tried to directly print a string array... like, if you passed the string array directly to System.out.print...
If you want to print out the string array, you'll need to loop through them, print them one at a time.
While no one overhear you quickly tell me not cow cow.
but how about watch phone?
User avatar
phlip
Restorer of Worlds
 
Posts: 6740
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia

Re: The "IT DOESN'T WORK!" thread

Postby Travuersa » Sat Sep 24, 2011 7:47 pm UTC

in C++

bool AngryAboutGoto = false;
Lol:

Basically I am just trying to make a text biased adventure that displays string "s0," gets a reply of either 1 or 2, and then displays the next string.
Like this:

s0 //actually a set of words, NOT JUST s0
1
s1 //actually a set of words, NOT JUST s1
2
s12 //actually a set of words, NOT JUST s12
1
s121 //actually a set of words, NOT JUST s121

How would I do this?

Full code is here:
Code: Select all
#include <iostream>
#include <string>
using namespace std;

//Define situations
string s0 = "s0";
string s1 = "s1";
string s2 = "s2";
string s11 = "s11";
string s12 = "s12";
string s21 = "s21";
string s22 = "s22";

//Define error codes
string sErrorInputNot1or2 = "Input error. Enter either 1 or 2.\n"; //Error if input is not 1 or 2

//Define variables
string stringinput;
bool dead = false;
int sequence;
int input;

int main ()
{
   Restart:
   dead = false;
   sequence = 0;
   input = 0;
   while (dead == false) //Loop initializes main code.
   {
   cout << s0 << "\n"; //cout is "s" plus "sequence"
   InputTest:
   cin >> input;
   if ((input == 1) || (input == 2)) //Error handling
      sequence = sequence * 10 + input;
   else
      {
      cout << sErrorInputNot1or2;
      goto InputTest;
      }
   if ((sequence == 222) || (sequence == 211) || (sequence == 111)) //Death handling
      {
      dead = true;
      cout << "Game over!\nEnter 1 to play again.\n";
      cin >> input;
      if (input == 1)
         goto Restart;
      }
   }
   return 0;
}


if (AngryAboutGoto = True)
goto Lol;
Travuersa
 
Posts: 1
Joined: Sat Sep 24, 2011 7:35 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Great Justice » Sun Sep 25, 2011 2:53 am UTC

Travuersa wrote:in C++

bool AngryAboutGoto = false;
Lol:

Basically I am just trying to make a text biased adventure that displays string "s0," gets a reply of either 1 or 2, and then displays the next string.
Like this:

s0 //actually a set of words, NOT JUST s0
1
s1 //actually a set of words, NOT JUST s1
2
s12 //actually a set of words, NOT JUST s12
1
s121 //actually a set of words, NOT JUST s121

How would I do this?
Spoiler:
Full code is here:
Code: Select all
#include <iostream>
#include <string>
using namespace std;

//Define situations
string s0 = "s0";
string s1 = "s1";
string s2 = "s2";
string s11 = "s11";
string s12 = "s12";
string s21 = "s21";
string s22 = "s22";

//Define error codes
string sErrorInputNot1or2 = "Input error. Enter either 1 or 2.\n"; //Error if input is not 1 or 2

//Define variables
string stringinput;
bool dead = false;
int sequence;
int input;

int main ()
{
   Restart:
   dead = false;
   sequence = 0;
   input = 0;
   while (dead == false) //Loop initializes main code.
   {
   cout << s0 << "\n"; //cout is "s" plus "sequence"
   InputTest:
   cin >> input;
   if ((input == 1) || (input == 2)) //Error handling
      sequence = sequence * 10 + input;
   else
      {
      cout << sErrorInputNot1or2;
      goto InputTest;
      }
   if ((sequence == 222) || (sequence == 211) || (sequence == 111)) //Death handling
      {
      dead = true;
      cout << "Game over!\nEnter 1 to play again.\n";
      cin >> input;
      if (input == 1)
         goto Restart;
      }
   }
   return 0;
}


if (AngryAboutGoto = True)
goto Lol;

You could use a stl map of <string, string> keeping the input as string, then break your main into separate functions, checking for invalid input, etc (which btw would also do away with the goto [I'm not angry, just... disappointed]).
Great Justice
 
Posts: 34
Joined: Sun Aug 15, 2010 5:28 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby thoughtfully » Sun Sep 25, 2011 3:22 am UTC

Don't be too hard on him; we were all noobies once. If all the code he's ever seen is from a sufficiently old BASIC, that'd be the reasonable thing to do.

Check out some tutorials, such as this one. Read lots of source code, too. One of the many excellent features of open source! Well, at least when the code isn't too badly written :)

There's a lot of threads in the Coding forum to help noobies, mainly How do I learn about [n], but also browse backwards in the history or experiment with the search feature.

Oh yeah. One more thing: GOTO considered harmful; avoid it and its kin, unless you know what you are doing.
Image
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
-- Antoine de Saint-Exupery
User avatar
thoughtfully
 
Posts: 1917
Joined: Thu Nov 01, 2007 12:25 am UTC
Location: Minneapolis, MN

Re: The "IT DOESN'T WORK!" thread

Postby Jplus » Sun Sep 25, 2011 9:50 am UTC

I think this topic might also prove relevant. Read it at least up to and including the first post by Yakk, I think a state machine might be the best solution in this case.
Hey, like coding? Perhaps you should check out the red spider project.
Feel free to call me Julian. J+ is just an abbreviation.
User avatar
Jplus
 
Posts: 1091
Joined: Wed Apr 21, 2010 12:29 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Yakk » Sun Sep 25, 2011 2:46 pm UTC

Code: Select all
#include <shared_ptr> // or is it <memory>?  I forget
#include <map>
#include <string>

class State;
typedef std::shared_ptr<State> pState;

struct StateTransition {
  std::string description;
  pState destination;
  // A simple constructor to make initializing this easier:
  StateTransition( std::string description_, pState destination_ ):
    description(description_), destination(destination_)
  {}
};

class State {
public:
  virtual StateTransition Execute() = 0;
  virtual ~State() {}
  State() {};
};

class SimpleState;
typedef std::shared_ptr<SimpleState> pSimpleState;

class SimpleState: public State {
private:
  std::map< std::string, StateTransition > exitMap;
  std::string description;
protected:
  virtual std::string OnBadInput( std::string command )
  {
    return "I don't understand.  Please try again.\n";
  }
public:
  virtual StateTransition Execute(); // implement below
  void AddExit( std::string command, StateTransition transition )
  {
    exitMap[command] = transition;
  }
  void SetDescription( std::string description_ )
  {
    description =  description_;
  }
  SimpleState() {}
};

class TrivialStateEngine {
public:
  void RunEngine( pState start_state );
};

// in .cpp:
StateTransition SimpleState::Execute()
{
  std::cout << description;
  // repeat until we return:
  while(true) {
    std::string user_command;
    std::getline(std::cin, user_command);
    if (exitMap.find(user_command) == exitMap.end()) {
      std::cout << OnBadInput( user_command );
      continue; // try again
    };
    return exitMap[ user_command ];
  };
}

void TrivialStateEngine::RunEngine( pState start_state )
{
  pState current_state = start_state;
  while (current_state)
  {
    StateTransition transition = current_state->Execute();
    std::cout << transition.description;
    current_state = transition.destination;
  };
}

int main()
{
  pSimpleState s1(new SimpleState);
  s1->SetDescription("Room s1");
  pSimpleState s2(new SimpleState);
  s2->SetDescription("Room s2");
  pSimpleState s11(new SimpleState);
  s11->SetDescription("Room s11");
  pSimpleState s12(new SimpleState);
  s12->SetDescription("Room s12");
  pSimpleState s21(new SimpleState);
  s21->SetDescription("Room s21");
  pSimpleState s22(new SimpleState);
  s22->SetDescription("Room s22");
  s1->AddExit( "1", StateTransition( "Going to room s11", s11 );
  s1->AddExit( "2", StateTransition( "Going to room s12", s12 );
  s2->AddExit( "1", StateTransition( "Going to room s21", s21 );
  s2->AddExit( "2", StateTransition( "Going to room s22", s22 );
  s11->AddExit( "e", StateTransition( "Exiting game", pState() );
  s12->AddExit( "e", StateTransition( "Exiting game", pState() );
  s21->AddExit( "e", StateTransition( "Exiting game", pState() );
  s22->AddExit( "e", StateTransition( "Exiting game", pState() );

  TrivialStateEngine engine;
  engine.RunEngine( s1 );
  return 0;
}


Notes on the above:
1: I didn't bother using const& parameters. Most should be.
2: I dislike the direct cin/cout read/writes. I'd be tempted to abstract that, but it would make this example overly complex.
3: TrivialStateEngine could just be a function.
4: All of those new and add exit commands are stupid -- we really should be mechanically reading states and transitions from a file.
5: In most games, a non-state-engine state is useful: like inventory. The above doesn't have any way to handle that, it would have to be extended.
6: I used the NULL pState() to indicate that the game is over.
7: The next thing I'd augment simplestate with is the idea that exits have descriptions both when you take them, and when you see them in the room. Some exits would be marked as hidden. Then I could have SimpleState dump all of the exits visible in the room.
8: The above code is completely untested. I didn't even compile it.

Edit:
Spoiler:
Added a missing : to a public above in the code.

Added trivial constructors to State and SimpleState.

Added some ;, probably unneeded mostly.

Fixed some formatting.
Last edited by Yakk on Mon Sep 26, 2011 4:01 pm UTC, edited 1 time in total.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
 
Posts: 10039
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: The "IT DOESN'T WORK!" thread

Postby Tomlidich » Mon Sep 26, 2011 3:53 pm UTC

the ford 4.6 has a .0008" tolerance for cylinder dimesnsions. mine are off by .008"

ford! y u no make engines easy to work on?!?!?!

no way i can get mine that precise in my backyard, thats cnc work.
User avatar
Tomlidich
 
Posts: 462
Joined: Mon Sep 19, 2011 8:15 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby e^iπ+1=0 » Mon Sep 26, 2011 11:11 pm UTC

Er... this is the coding forum. Accordingly, this is the thread for code that doesn't work.
poxic wrote:You, sir, have heroic hair.

(Avatar by Sungura)
User avatar
e^iπ+1=0
Gooder
 
Posts: 1923
Joined: Sun Feb 15, 2009 9:41 am UTC
Location: 54.0367˚N, 2.7961˚W; Lancaster

Re: The "IT DOESN'T WORK!" thread

Postby Tomlidich » Tue Sep 27, 2011 10:49 pm UTC

e^iπ+1=0 wrote:Er... this is the coding forum. Accordingly, this is the thread for code that doesn't work.

aha woops.
thought THis was just the "my *insert anything here* doesn't work! waaa" thread.
User avatar
Tomlidich
 
Posts: 462
Joined: Mon Sep 19, 2011 8:15 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Steax » Mon Oct 03, 2011 3:44 am UTC

Well this is confusing.

1. Tries to set svnserve to run as another user, on startup, through launchd.
2. Never works.
3. Suddenly it starts working on every startup, under my user.
4. I remove the launchd entry.
5. It still starts up every time.

I can't find any LaunchAgents/Daemons that might cause-

AAAAAAH OKAY.

/runs off

(I realized I had the sudo command saved as an Automator script, and it was set to Run on Startup.)

Still, it doesn't explain why it launches under my user, and refuses to run as the other one. Argh.
In Minecraft, I use the username Rirez.
User avatar
Steax
SecondTalon's Goon Squad
 
Posts: 2712
Joined: Sat Jan 12, 2008 12:18 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby userxp » Mon Oct 03, 2011 5:02 pm UTC

I'm a noob in C++, but isn't
Code: Select all
int main(){
    for (int a = 1, bool finished = false; not finished; a++){
        if (a == 4) finished = true;
    }
}

supposed to work?

g++ wrote:In function `int main()':
2: error: expected unqualified-id before "bool"
2: error: expected `,' or `;' before "bool"
2: error: `finished' undeclared (first use this function)
2: error: (Each undeclared identifier is reported only once for each function it appears in.)

THERE IS A COMMA! :evil:
userxp
 
Posts: 436
Joined: Thu Jul 09, 2009 12:40 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Yakk » Mon Oct 03, 2011 5:38 pm UTC

userxp wrote:I'm a noob in C++, but isn't
Code: Select all
int main(){
    for (int a = 1, bool finished = false; not finished; a++){
        if (a == 4) finished = true;
    }
}

supposed to work?

g++ wrote:In function `int main()':
2: error: expected unqualified-id before "bool"
2: error: expected `,' or `;' before "bool"
2: error: `finished' undeclared (first use this function)
2: error: (Each undeclared identifier is reported only once for each function it appears in.)

THERE IS A COMMA! :evil:

I'm guessing it is parsing that as:
Code: Select all
int a = (1, bool finished = false)

, is also an operator, annoyingly enough. And that can cause weird parsing quirks. Possibly this is one of them.

As an aside, start using ++a instead of a++. The post-increment operator is a strange beast, and you should use it only when you need to use it (even if, with integers, in this case, they do the same thing).
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
 
Posts: 10039
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: The "IT DOESN'T WORK!" thread

Postby EvanED » Mon Oct 03, 2011 5:56 pm UTC

Yakk wrote:I'm guessing it is parsing that as:
Code: Select all
int a = (1, bool finished = false)

, is also an operator, annoyingly enough. And that can cause weird parsing quirks. Possibly this is one of them.

I don't think you can declare two variables of different types in a for loop header. You can say for(int a=1, finished=false; ...) if you don't mind some unfortunate type punning.

As an aside, start using ++a instead of a++. The post-increment operator is a strange beast, and you should use it only when you need to use it (even if, with integers, in this case, they do the same thing).

I wouldn't say it's a "strange beast", not any more strange than the pre-increment. But there's a small potential for the pre-increment to be more efficient when you get into iterators, so for C++ folks I agree it's preferable to get into the habit of using ++a all the time even when it doesn't matter. (My personal style more-or-less forbids mixing ++ operators into larger expressions; if yours doesn't then make the appropriate "except for the cases where a++ is really what you need in the larger context" exception.)
EvanED
 
Posts: 3767
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI

Re: The "IT DOESN'T WORK!" thread

Postby Yakk » Mon Oct 03, 2011 6:26 pm UTC

Yes, the performance hit from overloaded post-increment is one reason to use pre-increment. The other reason is the ridiculous ease of invoking undefined behavior without realizing it if you use post-increment in non-trivial situations. Relatively few C/C++ programmers understand sequence points fully, and without understanding sequence points fully, non-trivial use of post-increment is not recommended.

Post increment is a strange beast.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
 
Posts: 10039
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: The "IT DOESN'T WORK!" thread

Postby userxp » Mon Oct 03, 2011 7:05 pm UTC

Oh well, don't worry, I already restructured the code and changed that bit.
userxp
 
Posts: 436
Joined: Thu Jul 09, 2009 12:40 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby EvanED » Mon Oct 03, 2011 7:26 pm UTC

Yakk wrote:Yes, the performance hit from overloaded post-increment is one reason to use pre-increment. The other reason is the ridiculous ease of invoking undefined behavior without realizing it if you use post-increment in non-trivial situations. Relatively few C/C++ programmers understand sequence points fully, and without understanding sequence points fully, non-trivial use of post-increment is not recommended.

Post increment is a strange beast.

Hmm, not to threadjack, but I'm having a problem thinking of when a statement has defined behavior with pre-increment but not if you replace it with post-increment. Care to elaborate a little?
EvanED
 
Posts: 3767
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI

Re: The "IT DOESN'T WORK!" thread

Postby Jplus » Mon Oct 03, 2011 7:44 pm UTC

userxp wrote:I'm a noob in C++, but isn't
Code: Select all
int main(){
    for (int a = 1, bool finished = false; not finished; a++){
        if (a == 4) finished = true;
    }
}

supposed to work?

Your problem has been solved already, but:

Why didn't you just do this?
Code: Select all
int main ( ) {
    for (int a = 1; a <= 4; a++) {
        // ...
    }
}
... or this?
Code: Select all
int main ( ) {
    for (int a = 1; true; a++) {
        // ...
        if (a == 4) break;
        // ...
    }
}


EvanED wrote:Hmm, not to threadjack, but I'm having a problem thinking of when a statement has defined behavior with pre-increment but not if you replace it with post-increment. Care to elaborate a little?

I second this question.
Hey, like coding? Perhaps you should check out the red spider project.
Feel free to call me Julian. J+ is just an abbreviation.
User avatar
Jplus
 
Posts: 1091
Joined: Wed Apr 21, 2010 12:29 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Yakk » Mon Oct 03, 2011 8:08 pm UTC

The simplest example is:
Code: Select all
i = i++

There is no sequence point above, so when the increment occurs is anytime after the RHS's value is evaluated. In particular, it could occur either before or after the RHS is assigned to the LHS. So the above could either NOOP, or increment i.

Code: Select all
i = ++i
this has fully defined behavior.

The strange beast part of post-increment is that the built-in version has a 'danging increment' that occurs at some undetermined future point, but before the next sequence point.

Then, note that operator overloaded post-increment is almost completely unrelated to the strange beast of standard post-increment to the mix.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
 
Posts: 10039
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: The "IT DOESN'T WORK!" thread

Postby EvanED » Mon Oct 03, 2011 8:25 pm UTC

Yakk wrote:The simplest example is:
Code: Select all
i = i++

There is no sequence point above, so when the increment occurs is anytime after the RHS's value is evaluated. In particular, it could occur either before or after the RHS is assigned to the LHS. So the above could either NOOP, or increment i.

And just to be pedantic: or do anything else. That is fully-undefined-behavior, and not just "the order of evaluation of arguments to a function is undefined"-style-undefined.

Code: Select all
i = ++i
this has fully defined behavior.

Are you sure about this? My understanding (and reading of section 5, para 4 of the C++ standard) is that this expression has two modifications of i and the behavior is thus undefined. The standard does not appear to define "modification" precisely, however, it explicitly calls out (in a non-normative example) i = ++i + 1; as being undefined.

(This is assuming that i is a standard scalar value and not an object with a ++ operator.)
EvanED
 
Posts: 3767
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI

Re: The "IT DOESN'T WORK!" thread

Postby jaap » Mon Oct 03, 2011 8:28 pm UTC

Yakk wrote:
Code: Select all
i = ++i
this has fully defined behavior.

No it isn't. This also does not have a sequence point, and strictly speaking has undefined behaviour. In practice no compiler will produce code that defers the increment of i till after the assignment (with the value of i+1), but it is allowed.
User avatar
jaap
 
Posts: 1720
Joined: Fri Jul 06, 2007 7:06 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Yakk » Mon Oct 03, 2011 8:44 pm UTC

Yep, you are right. The result is undefined!
"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored."

Mea culpa!
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
 
Posts: 10039
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: The "IT DOESN'T WORK!" thread

Postby xGeovanni » Sun Oct 09, 2011 6:47 am UTC

Hi, I'm just starting to learn how to program, can anyone help me find the problem with this? (It's Python)

Code: Select all
import random

print(
"""
                                 -The Number guesser-
                        Think of a number between 1 and 100
                             and I will try to guess it
                           mode 1 is 1-10, mode 2 is 1-100
                               reply "yes" or "no"
"""
)

tries=0

mode=input("Mode 1 or 2? ")

if mode==1:
    response=""
    while response!="yes":
        guess=random.randint(1,10)

        print("\nMy guess is", guess)
        response=input("\nAm I correct?")

        if response=="no":
            tries+=1

elif mode==2:
    response=""
    while response!="yes":
        guess=random.randint(1,100)

        print("\nMy guess is", guess)
        response=input("\nAm I correct?")

        if response=="no":
            tries+=1

   

print("\nIt took me", tries, "tries")

input("\n\nPress enter to exit")


the problem is, whenever I enter the mode, it skips right to the part where it declares the number of tries, help please.
xGeovanni
 
Posts: 32
Joined: Thu Oct 06, 2011 7:03 pm UTC

PreviousNext

Return to Coding

Who is online

Users browsing this forum: Breakfast, GuetraGma, MobTeeseboose and 6 guests