Our new Indie Games subforum is now open for business in G&T. Go and check it out, you might land a code for a free game. If you're developing an indie game and want to post about it, follow these directions. If you don't, he'll break your legs! Hahaha! Seriously though.
Our rules have been updated and given their own forum. Go and look at them! They are nice, and there may be new ones that you didn't know about! Hooray for rules! Hooray for The System! Hooray for Conforming!

The beginner programming thread

JaninJanin Registered User
Turning progamers into programmers hell yeah

I wrote up this wall of text while playing EVE. I hope that this thread will become a place where people new to programming can learn what languages are available, how to operate basic parts of programming, get help deciphering inscrutable homework assignments, etc. It might also serve as a useful repository for commonly-asked questions like "what is a pointer", "how do I write a function", etc.

Basic overview

In the code samples here, lines starting with the "#" character are comments. This means that they are not part of the program itself, but are instructions or notes to the reader.

Stuff that doesn't go anywhere specific

Always turn on compiler or interpreter warnings, and set them to maximum. If possible, make them errors rather than warnings. Compiler writers are very smart, and probably know more than you do. Read the documentation to your compiler or interpreter to determine how to set warning and error levels.

Variables

Variables are a way to "label" a certain value. They can be used to reduce code duplication. If you wanted to change the base value in the old code, you would have to update it in three places. In the new code, it only has to be updated in one.
# Old code
value1 = (5 * 10) + 5
value2 = (5 * 10) + 6
value3 = (5 * 10) + 7

# New code
base = 5 * 10
value1 = base + 5
value1 = base + 6
value1 = base + 7

To document code behavior. In the old code, the numbers "5", "10", and "100" are "magic numbers". Their purpose is unknown - may be it's how many cars have been sold, how many employees took the day off sick, or how many dollars were spent on candy bars. May be there's a comment hidden somewhere about its purpose, or may be not. In the new code, their purposes are inherently documented everywhere the variables are used.
# Old code
var = 100
income_today = var * 10 * 0.3

# New code
cent_multiplier = 100
net_dollar_income = 10
tax_rate = 0.3
income_today = net_dollar_income * cent_multiplier * tax_rate

In most modern languages, variables have "types". A type determines what values a variable can hold and what operations you can perform on it. For example, you can add two numbers, but cannot add a number and a string.

Common types of variables:
Boolean - May be either True or False, nothing else. In some primitive languages, such as C, the integers 0 and 1 are used instead of true and false.
Integer - A number with no fractional part.
Floating Point - A number that may contain fractional parts. Because computers only operate on Base 2 numbers, floating point math in most languages can give very "weird" values. For an example, enter "javascript:alert (0.1 + 0.2)" into your browser's URL bar.
String - An ordered list of characters. These might be letters like A, digits like 2, punctuation like !, or "unprintable" control characters such as a "new line" marker.
List - An ordered list of variables. These are usually accessed by a "0-based" index. For example, position 0 of the list (5 10 15 20) is 5, and position 3 is 20.

Conditionals

Conditionals are what separate a programming language from a mere list of equations. A conditional always has an if-block, and sometimes an else-block. In some languages, the two can be combined to save space. One thing to note here is the use of "==" to check for equality. Because "=" is used to assign to a variable, "==" checks if two values are equal.

An example of an if statement:
name = "Alice"
if name == "Alice":
	print "Hello Alice!"
else:
	if name == "Bob":
		print "Guten Tag Bob!"
	else:
		print "I don't know who you are."

# The same as above, with a combined 'elif' statement
name = "Alice"
if name == "Alice":
	print "Hello Alice!"
elif name == "Bob":
	print "Guten Tag Bob!"
else:
	print "I don't know who you are."

Loops

Loops are used to help reduce code duplication. If you have to do something many times, it's easier to put into a loop than try to write out every step. And if you want to change how many times something happens, it'll have to be in a loop.

The most basic form of the loop is the while loop. This loop will simply run over and over until some condition is met. If you make a mistake in the body, the loop might run forever and freeze your program.
x = 10
while x < 500:
	x = x * 10
print x

The other popular form of the loop is the for loop. A for loop is used for doing something once for every item in a group.
numbers = [5, 10, 15, 20, 25, 30]
# The number is: 5
# The number is: 10
# etc
for number in numbers:
	print "The number is: ", number


# The name is: Alice
# The name is: Bob
# etc
for name in ["Alice", "Bob", "Charlie", "David", "Eve"]:
	print "The name is: ", name

Janin on
[SIGPIC][/SIGPIC]
«13456763

Posts

  • MKRMKR Registered User regular
    edited November 2007
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

  • AndorienAndorien Registered User
    edited November 2007
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

  • MiserableMirthMiserableMirth Registered User regular
    edited November 2007
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

  • AndorienAndorien Registered User
    edited November 2007
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

    You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.

    Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.

    Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
    Program
    Source File 1
    Source File 2

  • MKRMKR Registered User regular
    edited November 2007
    Andorien wrote: »
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

    You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.

    Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.

    Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
    Program
    Source File 1
    Source File 2

    Why would you be using .NET 2003? It's free.

    Go download 2005, or 2008 if you feel like being a lab rat.

  • MonoxideMonoxide Registered User, ClubPA regular
    edited November 2007
    What's wrong with vi and g++?

    People are so picky these days.

  • AndorienAndorien Registered User
    edited November 2007
    MKR wrote: »
    Andorien wrote: »
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

    You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.

    Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.

    Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
    Program
    Source File 1
    Source File 2

    Why would you be using .NET 2003? It's free.

    Go download 2005, or 2008 if you feel like being a lab rat.

    I know it's free. But see, here's the thing, I just don't like how C++ 2005 Express operates, while 2003 doesn't piss me off near as bad. C# 2005 is fine. Also, my version of 2003 is the standard edition, which means I get cool things with it like the GUI designer, which is pretty handy when dealing with Win32.

  • MKRMKR Registered User regular
    edited November 2007
    Andorien wrote: »
    MKR wrote: »
    Andorien wrote: »
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

    You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.

    Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.

    Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
    Program
    Source File 1
    Source File 2

    Why would you be using .NET 2003? It's free.

    Go download 2005, or 2008 if you feel like being a lab rat.

    I know it's free. But see, here's the thing, I just don't like how C++ 2005 Express operates, while 2003 doesn't piss me off near as bad. C# 2005 is fine. Also, my version of 2003 is the standard edition, which means I get cool things with it like the GUI designer, which is pretty handy when dealing with Win32.

    VC++.net 2005 express comes with a GUI designer as far as I know. All the other expresses do, so it seems logical.

  • jackaljackal Registered User regular
    edited November 2007
    Andorien wrote: »
    MKR wrote: »
    Andorien wrote: »
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

    You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.

    Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.

    Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
    Program
    Source File 1
    Source File 2

    Why would you be using .NET 2003? It's free.

    Go download 2005, or 2008 if you feel like being a lab rat.

    I know it's free. But see, here's the thing, I just don't like how C++ 2005 Express operates, while 2003 doesn't piss me off near as bad. C# 2005 is fine. Also, my version of 2003 is the standard edition, which means I get cool things with it like the GUI designer, which is pretty handy when dealing with Win32.

    What do you mean by "GUI designer?" Express Edition has basically the same visual form designer that other editions have.

    I use Visual Studios 2003 Enterprise Developer at work and the various Express Editions at home. There aren't many times that I run into things that I need that are missing. Add-ons and conditional break points would be nice. The express editions don't have as many project types, but usually that just means you have to go into options and change a setting or write a line or two of code to get the same effect. It is worth it to get generics and anonymous delegates and LINQ and whatever that feature is called where you create a static method that takes an instance of some type and some other arguments, and then allows you to call it as if it were an instance method of that type that you passed in.

    [edit]
    Crap, you are talking about C++ and I am talking about C#. C++ is the only Express Edition I haven't installed. Several of the CS courses I took used C++, but damn I wouldn't want to use it day to day. If you know what you are doing in C# you can usually get >90% of the performance for a fraction of the effort. I say usually because a C# program could never get anywhere near 90% of the performance of FFTW, but that is what P/Invoke is for. Here is a good example.

  • AndorienAndorien Registered User
    edited November 2007
    MKR wrote: »
    Andorien wrote: »
    MKR wrote: »
    Andorien wrote: »
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

    Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!

    Sweet. Thanks guys.

    You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.

    Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.

    Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
    Program
    Source File 1
    Source File 2

    Why would you be using .NET 2003? It's free.

    Go download 2005, or 2008 if you feel like being a lab rat.

    I know it's free. But see, here's the thing, I just don't like how C++ 2005 Express operates, while 2003 doesn't piss me off near as bad. C# 2005 is fine. Also, my version of 2003 is the standard edition, which means I get cool things with it like the GUI designer, which is pretty handy when dealing with Win32.

    VC++.net 2005 express comes with a GUI designer as far as I know. All the other expresses do, so it seems logical.

    They come with a designer for Windows Forms, but not Win32, and I'm pretty sure C++ comes with neither. Even if it did have Forms, if I were using Forms, I'd be in C# anyway.

    Added: I should note that it's actually not mostly a matter of features. Fact is, I rarely use Win32 anyway. There's just something in the feel of it that annoys me, and is only present in VC++.net 2005. VC#.net 2005 doesn't suffer from this oddly enough.

    Added again: just tried the 2008 beta, as it occured to me that I hadn't messed with it yet. Same problems, though I appreciate them loading it up with Win32 stuff on install, rather than having to install other stuff as well as modifying the template files to get first class support going. Still no designer though.

    jackal: Ah, yeah, easy mistake to make. I actually really like the C# express edition, I think it works really well. What I hate the most about the C++ version is the build output window. It doesn't make it easy to find errors in that mass of output at all. I don't understand why they did it like they did- the C# version is great, and is identical to the 2003 editor. It confuses me greatly.

    Also, I usually code in C#, but often times C++ is needed when working with some specific API that doesn't have .Net bindings. I work in C# when I can, but C++ will always always get the job done.

  • LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    Here's a good beginner question: How the hell can I get something like a C array in Python?

    Lists are cool and all, but not when I just need a mass of data of a fixed size that has to be accessed very quickly and is also mutable (unlike a tuple).

    Specifically, my roguelike calls for a ton of 2D arrays. I have a 2D array of tiles in the current map. My display class needs an array of tile-to-screen mappings to avoid doing lots of repeated multiplication to place tiles on the right pixels (actually I suppose that wouldn't be much faster, if at all, but I thought of this idea and dammit it seems like a good one). I need to iterate through these with "for" loops. If Python has an equivalent way of implementing this kind of thing that's not horribly inefficient, I haven't found it.

    Also, I've looked at Numeric some, and I don't need arrays of numbers - I need arrays of objects.

  • sonictksonictk Registered User regular
    edited November 2007
    Just curious: why is it that every C++ IDE I see recommended is either MS VS/VC++ or Dev C++, and no one seems to like the Eclipse project? Granted I'm no programmer, but I've tried using the IDE before to code a few simple test programs and it seems similar to VC++ in a lot of aspects.

  • AndorienAndorien Registered User
    edited November 2007
    sonictk wrote: »
    Just curious: why is it that every C++ IDE I see recommended is either MS VS/VC++ or Dev C++, and no one seems to like the Eclipse project? Granted I'm no programmer, but I've tried using the IDE before to code a few simple test programs and it seems similar to VC++ in a lot of aspects.

    As far as I know, it's because C++ isn't actually supported out of the box, and relies on a plugin that's not actually done yet.

    However, whenever someone breaths Java, Eclipse is always shouted pretty loudly.

  • MKRMKR Registered User regular
    edited November 2007
    sonictk wrote: »
    Just curious: why is it that every C++ IDE I see recommended is either MS VS/VC++ or Dev C++, and no one seems to like the Eclipse project? Granted I'm no programmer, but I've tried using the IDE before to code a few simple test programs and it seems similar to VC++ in a lot of aspects.

    The same reason people don't seem to like Blender or The GIMP. They're excellent programs with many strengths, but there is a minor learning curve on the interface.

    I didn't like Eclipse's interface, but that was a first impression, and I haven't had any incentive to try it since Code::Blocks works for me. :)

  • JaninJanin Registered User
    edited November 2007
    Here's a good beginner question: How the hell can I get something like a C array in Python?

    Lists are cool and all, but not when I just need a mass of data of a fixed size that has to be accessed very quickly and is also mutable (unlike a tuple).

    Specifically, my roguelike calls for a ton of 2D arrays. I have a 2D array of tiles in the current map. My display class needs an array of tile-to-screen mappings to avoid doing lots of repeated multiplication to place tiles on the right pixels (actually I suppose that wouldn't be much faster, if at all, but I thought of this idea and dammit it seems like a good one). I need to iterate through these with "for" loops. If Python has an equivalent way of implementing this kind of thing that's not horribly inefficient, I haven't found it.

    Also, I've looked at Numeric some, and I don't need arrays of numbers - I need arrays of objects.

    You could try using list comprehensions, I've found those to be faster than for loops in general. However, to get near-C performance in Python you'll want to take a look at a library like Pyrex.

    However, the speed benefit of moving to compiled modules in C is likely to be much less than what you could gain by simply using a more efficient algorithm.

    [SIGPIC][/SIGPIC]
  • ChewyWafflesChewyWaffles Registered User
    edited November 2007
    MKR wrote: »
    sonictk wrote: »
    Just curious: why is it that every C++ IDE I see recommended is either MS VS/VC++ or Dev C++, and no one seems to like the Eclipse project? Granted I'm no programmer, but I've tried using the IDE before to code a few simple test programs and it seems similar to VC++ in a lot of aspects.

    The same reason people don't seem to like Blender or The GIMP. They're excellent programs with many strengths, but there is a minor learning curve on the interface.

    I didn't like Eclipse's interface, but that was a first impression, and I haven't had any incentive to try it since Code::Blocks works for me. :)

    Interesting. Code::Blocks handles Java or does Eclipse handle C/C++? Either way, color me surprised, because I thought the former was mostly for C/C++ and the latter was Java. I'm a NetBeans guy, myself.


    Wow, that last sentence makes me sound like a fairy.

    mwf2sig.jpg
  • JaninJanin Registered User
    edited November 2007
    Interesting. Code::Blocks handles Java or does Eclipse handle C/C++? Either way, color me surprised, because I thought the former was mostly for C/C++ and the latter was Java. I'm a NetBeans guy, myself.


    Wow, that last sentence makes me sound like a fairy.

    Eclipse has support for C/C++ through CDT. I learned how to program in Eclipse, but was never very fond of it. I stopped using it when it began to take longer to start up than to compile my applications.

    [SIGPIC][/SIGPIC]
  • LindenLinden Registered User regular
    edited November 2007
    Janin wrote: »
    Eclipse has support for C/C++ through CDT. I learned how to program in Eclipse, but was never very fond of it. I stopped using it when it began to take longer to start up than to compile my applications.

    Eclipse supports a surprising amount. I haven't used it much, but it seems a real demonstration of the power of extensibility. Nothing like Emacs (a text editor that can do email?), but still impressive.

    And compiling compilers really sucks – as a notice to any Haskell users reading this for whatever reason, GHC 6.8.1 is now available. Of course, I couldn't get at a binary version, so I had a five-hour compilation on my hands. Which was truly wonderful.

    What if this weren't a rhetorical question?
  • LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    Janin wrote: »
    Here's a good beginner question: How the hell can I get something like a C array in Python?

    Lists are cool and all, but not when I just need a mass of data of a fixed size that has to be accessed very quickly and is also mutable (unlike a tuple).

    Specifically, my roguelike calls for a ton of 2D arrays. I have a 2D array of tiles in the current map. My display class needs an array of tile-to-screen mappings to avoid doing lots of repeated multiplication to place tiles on the right pixels (actually I suppose that wouldn't be much faster, if at all, but I thought of this idea and dammit it seems like a good one). I need to iterate through these with "for" loops. If Python has an equivalent way of implementing this kind of thing that's not horribly inefficient, I haven't found it.

    Also, I've looked at Numeric some, and I don't need arrays of numbers - I need arrays of objects.

    You could try using list comprehensions, I've found those to be faster than for loops in general. However, to get near-C performance in Python you'll want to take a look at a library like Pyrex.

    However, the speed benefit of moving to compiled modules in C is likely to be much less than what you could gain by simply using a more efficient algorithm.

    In what context would I use list comprehensions though? My problem is not with generating or altering lists, it's with accessing them quickly. For example, my "MapView" class first decides which ranges of tiles in the array of map data will be visible, and then iterates through all the visible tiles, blitting their sprites to locations specified in a screen mapping array. At the moment, the speed of this is perfectly acceptable on my MacBook Pro, so I'm calling it good for now, but I'm concerned that it may be an issue.

  • LewishamLewisham Registered User regular
    edited November 2007
    As you are still learning Lone, I just wouldn't concern yourself with it. The important thing is that it works.

    1. Make something that works.
    2. Make it work fast.

    Do number 1 throughout the whole project first. Worry about the other stuff later; that's why we use abstraction in object-orientated programming; you get to screw to your heart's content later on, and not break stuff (as long as you pay attention to the API).

  • Recoil42Recoil42 Registered User
    edited November 2007
    So I'm too lazy to make an "The Intermediate programming thread" but anyways, this'll suffice.

    So I'm messing around with PHP and SQL/MySQL, and well... there's something bugging me. Do you *really* put the username/password to the SQL database in every PHP file that wants to access it? Doesn't that seem... just a little insecure to anyone else?

    I mean, if there's ever an apache glitch, and a user gets the raw PHP file... all your data is compromised. No?

  • JaninJanin Registered User
    edited November 2007
    Oh, in that case you might want to use map (). The basic rules when it comes to loop speed is that for loops are slow, map is fast, and list comprehensions are fastest. This holds true even if you just throw away the calculated values. The Python wiki has some more information on loop speed: PerformanceTips: Loops, PythonSpeed, Python Patterns - An Optimization Anecdote.

    As a dynamic language, ways to increase performance in Python might not be obvious. I wouldn't worry about it at all until it starts affecting your framerate.

    [SIGPIC][/SIGPIC]
  • JaninJanin Registered User
    edited November 2007
    Recoil42 wrote: »
    So I'm too lazy to make an "The Intermediate programming thread" but anyways, this'll suffice.

    So I'm messing around with PHP and SQL/MySQL, and well... there's something bugging me. Do you *really* put the username/password to the SQL database in every PHP file that wants to access it? Doesn't that seem... just a little insecure to anyone else?

    I mean, if there's ever an apache glitch, and a user gets the raw PHP file... all your data is compromised. No?

    Put connection details in an external configuration file, then create a PHP function to load + parse the file, and return a database connection based on the data contained. If you put the configuration file outside the webroot, a proper webserver won't display it.

    [SIGPIC][/SIGPIC]
  • Recoil42Recoil42 Registered User
    edited November 2007
    Janin wrote: »
    Recoil42 wrote: »
    So I'm too lazy to make an "The Intermediate programming thread" but anyways, this'll suffice.

    So I'm messing around with PHP and SQL/MySQL, and well... there's something bugging me. Do you *really* put the username/password to the SQL database in every PHP file that wants to access it? Doesn't that seem... just a little insecure to anyone else?

    I mean, if there's ever an apache glitch, and a user gets the raw PHP file... all your data is compromised. No?

    Put connection details in an external configuration file, then create a PHP function to load + parse the file, and return a database connection based on the data contained. If you put the configuration file outside the webroot, a proper webserver won't display it.

    Ewww.. really? Is that what "everyone else" does, too?

  • LewishamLewisham Registered User regular
    edited November 2007
    That seems reasonable Recoil. Putting the database password in a file only readable by the web server somewhere that it won't display is pretty normal, it's certainly how my workplace does stuff in Perl.

  • Recoil42Recoil42 Registered User
    edited November 2007
    Reasonable, yes, but still a lot of code for something so trivial. I found another idea/method in the comments section of the PHP online docs that is a lot simpler, though not as flexible: Rather than storing the username/pass in a plain text file to be parsed, as above; instead store them in a PHP file.

    That way, rather than having to load and parse the text file, you just include the PHP file:

    http://www.php.net/manual/en/function.mysql-connect.php#73983
    <?php
        $g_link = false;
       
        function GetMyConnection()
        {
            global $g_link;
            if( $g_link )
                return $g_link;
            $g_link = mysql_connect( 'host.name', 'user', 'password') or die('Could not connect to server.' );
            mysql_select_db('database_name', $g_link) or die('Could not select database.');
            return $g_link;
        }
       
        function CleanUpDB()
        {
            global $g_link;
            if( $g_link != false )
                mysql_close($g_link);
            $g_link = false;
        }
       
    ?>
    

    Simply include your connnection.php file in your script and anywhere you use the mysql_query() function include a call to the GetMyConnection() function.
    <?php
        $res = mysql_query("SELECT ...", GetMyConnection() );
    ?>
    

  • Shazkar ShadowstormShazkar Shadowstorm Registered User regular
    edited November 2007
    So as part of one assignment I need to remove the "magic numbers" from a bit code. But they are all just different numbers to scale down a given input to make a pretty picture of a car, sometimes by 6, or 2/3 or 3... should I just make final static variables called like... SCALE_DOWN_BY_SIX, SCALE_DOWN_BY_TWO_THIRDS, SCALE_DOWN_BY_THREE, and so on, or is there a better way I should be naming these/going about with this?

    Damn this OOD&P class and its horrible teacher.

    | Steam & XBL: Shazkar | 3DS: 3110-5421-3843 | SS Wishlists |
  • GanluanGanluan Registered User regular
    edited November 2007
    Recoil42 wrote: »
    Janin wrote: »
    Recoil42 wrote: »
    So I'm too lazy to make an "The Intermediate programming thread" but anyways, this'll suffice.

    So I'm messing around with PHP and SQL/MySQL, and well... there's something bugging me. Do you *really* put the username/password to the SQL database in every PHP file that wants to access it? Doesn't that seem... just a little insecure to anyone else?

    I mean, if there's ever an apache glitch, and a user gets the raw PHP file... all your data is compromised. No?

    Put connection details in an external configuration file, then create a PHP function to load + parse the file, and return a database connection based on the data contained. If you put the configuration file outside the webroot, a proper webserver won't display it.

    Ewww.. really? Is that what "everyone else" does, too?

    I'm not familiar with PHP specifically, but for ASP .NET you almost always store your connection strings in a Web.Config file, similar to what Janin is talking about. Although in ASP, the Web.Config consists of key/value pairs in a very fast hashtable, so it's extremely easy to read from.

  • GanluanGanluan Registered User regular
    edited November 2007
    So as part of one assignment I need to remove the "magic numbers" from a bit code. But they are all just different numbers to scale down a given input to make a pretty picture of a car, sometimes by 6, or 2/3 or 3... should I just make final static variables called like... SCALE_DOWN_BY_SIX, SCALE_DOWN_BY_TWO_THIRDS, SCALE_DOWN_BY_THREE, and so on, or is there a better way I should be naming these/going about with this?

    Damn this OOD&P class and its horrible teacher.

    Something similar to what you're doing would be fine. The main idea behind removing all magic numbers and using constants instead is that your code is basically documenting itself.

    scale * 6.37894 doesn't make much sense compared to scale * SCALE_FACTOR_SIX.

  • Shazkar ShadowstormShazkar Shadowstorm Registered User regular
    edited November 2007
    Ah, that makes sense. The assignment said to make it more self documenting as well, so I guess this is a part of it.

    | Steam & XBL: Shazkar | 3DS: 3110-5421-3843 | SS Wishlists |
  • mastmanmastman Registered User regular
    edited November 2007
    I imagine you can find some PHP libraries already written to do standard stuff like read connectino properties from a file and create a connection for you.

    ByalIX8.png
  • MaximilianMaximilian Registered User
    edited November 2007
    So as part of one assignment I need to remove the "magic numbers" from a bit code. But they are all just different numbers to scale down a given input to make a pretty picture of a car, sometimes by 6, or 2/3 or 3... should I just make final static variables called like... SCALE_DOWN_BY_SIX, SCALE_DOWN_BY_TWO_THIRDS, SCALE_DOWN_BY_THREE, and so on, or is there a better way I should be naming these/going about with this?

    Damn this OOD&P class and its horrible teacher.

    You need to give your constants names that express the meaning of them and not the value. I hope I can explain this:

    In this case it mostly depends on how the value is chosen. If, say, these values can be chosen by the user (in a combo box or something), I would probably name them something like SCALE_LEVEL_1, SCALE_LEVEL_2 and so on (or better yet, create a lookup array). Like this, if the options for the user change you can just change the value of a certain SCALE_LEVEL.

    If the used value depends on a different thing you need to give it a different name. Perhaps it depends on current connection speed to a server, then you should name them something like SCALE_LEVEL_FAST_CONN, SCALE_LEVEL_SLOW_CONN and so on.

    If you do it like this, and somebody decides that for super fast connections you don't have to scale anything at all, you just need to change the value of SCALE_LEVEL_SUPER_FAST_CON to "1". If you would have called it SCALE_DOWN_BY_TWO, then for clarity's sake you would also have to change the name to DONT_SCALE (or something) and all of its occurences in the code. And this is exactly what you are trying to avoid when using constants.

    Simple rule: If you need to change the name of your constant whenever its value changes than the name is bad or you just don't need a constant at all.

    Did this help?

  • Shazkar ShadowstormShazkar Shadowstorm Registered User regular
    edited November 2007
    Hm, alright, that makes sense. I'll need to look at this code thoroughly to understand what each of these numbers are doing, because as far as I can tell these constants are just arbitrary ones to make a picture of a car based on a given width input.

    EDIT: When can the Java compiler tell what the exact method that will be called before a program executes? W/regards to polymorphism. I'm trying to find it in this chapter of my textbook, but I cannot.

    | Steam & XBL: Shazkar | 3DS: 3110-5421-3843 | SS Wishlists |
  • MaximilianMaximilian Registered User
    edited November 2007
    EDIT: When can the Java compiler tell what the exact method that will be called before a program executes? W/regards to polymorphism. I'm trying to find it in this chapter of my textbook, but I cannot.

    It can't. When you call a virtual method it's decided at runtime which implementation is executed. The compiler just doesn't know. It only stores somethig like "Call method xyz on the object at this place.", and when the program executes, different methods get executed depending on the type of "the object at this place".

  • Shazkar ShadowstormShazkar Shadowstorm Registered User regular
    edited November 2007
    That's what I thought... hence why I am confused when there is a question in my book asking to name two situations where it can do just what I asked... weird. Hm. Google times...

    | Steam & XBL: Shazkar | 3DS: 3110-5421-3843 | SS Wishlists |
  • MaximilianMaximilian Registered User
    edited November 2007
    Well, if you do
    MyType foo = new MyType();
    foo.someMethod()
    

    The compiler can probably determine that someMethod of type MyType will be called and optimize the dispatching away. But from a programming perspective this doesn't matter at all.

  • mausmalonemausmalone Registered User regular
    edited November 2007
    Recoil42 wrote: »
    Janin wrote: »
    Recoil42 wrote: »
    So I'm too lazy to make an "The Intermediate programming thread" but anyways, this'll suffice.

    So I'm messing around with PHP and SQL/MySQL, and well... there's something bugging me. Do you *really* put the username/password to the SQL database in every PHP file that wants to access it? Doesn't that seem... just a little insecure to anyone else?

    I mean, if there's ever an apache glitch, and a user gets the raw PHP file... all your data is compromised. No?

    Put connection details in an external configuration file, then create a PHP function to load + parse the file, and return a database connection based on the data contained. If you put the configuration file outside the webroot, a proper webserver won't display it.

    Ewww.. really? Is that what "everyone else" does, too?

    I don't even put it outside the the webroot (because my hosting company won't allow it). I actually have it set variables. The variables will never display unless I actually tell them to display.
    <?PHP
    $MYSQLDBName = "db";
    $MYSQLUser = "my_username";
    $MYSQLPassword = "my_password";
    ?>
    

    This is actually pretty damned secure because even if somebody knows where your config file is the web server will never serve that up as text that they can read. The only way they'd be able to read your database username and password would be if they had file access to your server ... and then you'd have bigger problems to worry about.

    The bigger danger is from SQL injection, but as long as you realize that you can take steps to prevent it.

    266.jpg
  • JaninJanin Registered User
    edited November 2007
    mausmalone wrote: »
    Recoil42 wrote: »
    Janin wrote: »
    Recoil42 wrote: »
    So I'm too lazy to make an "The Intermediate programming thread" but anyways, this'll suffice.

    So I'm messing around with PHP and SQL/MySQL, and well... there's something bugging me. Do you *really* put the username/password to the SQL database in every PHP file that wants to access it? Doesn't that seem... just a little insecure to anyone else?

    I mean, if there's ever an apache glitch, and a user gets the raw PHP file... all your data is compromised. No?

    Put connection details in an external configuration file, then create a PHP function to load + parse the file, and return a database connection based on the data contained. If you put the configuration file outside the webroot, a proper webserver won't display it.

    Ewww.. really? Is that what "everyone else" does, too?

    I don't even put it outside the the webroot (because my hosting company won't allow it). I actually have it set variables. The variables will never display unless I actually tell them to display.
    <?PHP
    $MYSQLDBName = "db";
    $MYSQLUser = "my_username";
    $MYSQLPassword = "my_password";
    ?>
    

    This is actually pretty damned secure because even if somebody knows where your config file is the web server will never serve that up as text that they can read. The only way they'd be able to read your database username and password would be if they had file access to your server ... and then you'd have bigger problems to worry about.

    The bigger danger is from SQL injection, but as long as you realize that you can take steps to prevent it.

    He was specifically asking how to avoid compromising his password if his server was misconfigured to send PHP scipts as plain text, which your solution does not address. Get a better hosting provider.

    [SIGPIC][/SIGPIC]
  • MKRMKR Registered User regular
    edited November 2007
    Keep the config file above the web root.

  • HalibutHalibut Registered User regular
    edited November 2007
    No love for Java in this thread? I suppose a dynamic language is probably easier to learn for beginners.

    There's a language modeled after Ruby called Groovy. It's pretty cool because it has a very Ruby-like syntax (most of Ruby's core language features like dynamic typing, closures, etc...), but it runs on Java's JVM. It can also be compiled to Java .class files and then imported in any Java class (and vice versa). This allows a lot of quick prototyping opportunities where you can create an implementation of some component in Groovy and replace it later with a Java implementation if you need to.

«13456763
This discussion has been closed.