Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 ... 504 505 [506] 507 508 ... 796

Author Topic: if self.isCoder(): post() #Programming Thread  (Read 908650 times)

TheDarkStar

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7575 on: July 16, 2015, 09:54:56 pm »

So I've started looking at SDL. Has anyone else used it? Does anyone have recommendations for using it?
Logged
Don't die; it's bad for your health!

it happened it happened it happen im so hyped to actually get attacked now

Orange Wizard

  • Bay Watcher
  • mou ii yo
    • View Profile
    • S M U G
Re: if self.isCoder(): post() #Programming Thread
« Reply #7576 on: July 16, 2015, 10:02:51 pm »

Get a wrapper designed for your preferred programming language rather than using SDL itself. Low-level libraries are usually pretty nightmarish to use directly.
Logged
Please don't shitpost, it lowers the quality of discourse
Hard science is like a sword, and soft science is like fear. You can use both to equally powerful results, but even if your opponent disbelieve your stabs, they will still die.

Spehss _

  • Bay Watcher
  • full of stars
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7577 on: July 16, 2015, 11:43:49 pm »

You are probably best off interviewing someone with more professional credtentials than me I guess.

computer science degree, dabbling in open source and amateur coding projects / homebrew games, some published game programming work and currently studying a second degree, Bachelor of Games Development

Hate to break it to you Reelya, but you've got pretty good professional cred. And good actual cred, having read most of your posts to this thread.

I agree, Reelya knows their shit at programming.

-article on programming-
Did you mention Dwarf Fortress and how much of an in depth simulation it is? I feel like that's a huuuuge example of what someone can achieve through programming.
Logged
Steam ID: Spehss Cat
Turns out you can seriously not notice how deep into this shit you went until you get out.

Sappho

  • Bay Watcher
  • AKA Aira; Legendary Female Gamer
    • View Profile
    • Aira Plays Games
Re: if self.isCoder(): post() #Programming Thread
« Reply #7578 on: July 25, 2015, 01:47:06 pm »

I'm using Code Academy to learn coding! It is working! I'm doing Javascript! Hooray!

I'm stuck on one part though. I completed the task assigned, which was to use for... loops and arrays to search text for a particular series of letters (my name). But the actual task only looks at the first letter, then prints all the letters after it up to the length of your name. I wanted to make it work better, to only return if it finds my exact name. So I wrote this code, but it only returns an empty array. What have I done wrong here? Why isn't my name being pushed to the hits array? (By the way, I know this is far from the most efficient way to search text, but I'm just playing with what they gave me and trying to make it do other stuff.)

Code: [Select]
var text = "as erfndfga aNegafaerfaersmrfah aifuvadr Name asdmasef \
efmegaasd jwefaf Namesacfsjf";
var myName = "Name";
var test = [];
var hits = [];

for (var i = 0; i < text.length; i++){
    if (text[i] === myName[0]) {
        for (var j = i; j < i + myName.length; j++) {
            test.push(text[j]);
            }
        }
        if (test === myName) {
                hits.push(test);
                test = [];
            } else {
                test = [];
        }
}

if (hits === 0) {
    console.log("Your name wasn't found!");
} else {
    console.log(hits);
}

alway

  • Bay Watcher
  • 🏳️‍⚧️
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7579 on: July 25, 2015, 02:38:29 pm »

So the other big part of coding (and really the most important part) is figuring out why something doesn't work when you think it should be. Some of the main parts of that are determining A: Whether the program is executing the parts of code you expect it to be in the order you expect it to be, and B: Whether the data stored as it does so is what you expect it to be.

To figure this out, the easiest way is to start with a method for displaying information on screen; likely whatever you're using to see it's currently returning an empty array. As your program is executing, dump out logging information that tells you the state of things as it executes, either displaying it at that time or later, depending on how your method for displaying the information works. Along the lines of this:

Code: [Select]
var text = "as erfndfga aNegafaerfaersmrfah aifuvadr Name asdmasef \
efmegaasd jwefaf Namesacfsjf";
var myName = "Name";
var test = [];
var hits = [];
var log = [];

for (var i = 0; i < text.length; i++){
    if (text[i] === myName[0]) {
        for (var j = i; j < i + myName.length; j++) {
            test.push(text[j]);
            log.push("A");
            log.push(text[j]);
            log.push(" ");
            }
        }
        if (test === myName) {
                hits.push(test);
                test = [];
                log.push("B");
                log.push(test);
                log.push(" ");
            } else {
                test = [];
                log.push("C ");
        }
}
Then, by displaying the info in log, you should get a good idea of how your program is doing things.
In this case, you would expect to see something like this, with some Cs in between the valid bits.
...  AN Ae Ag Aa C    ...    AN Aa Am Ae BName ...
However, what is actually seen is a C on the second of those two. From the displayed information, we can surmise that at this point, we have pushed "N" "a" "m" "e" into test. On the comparison, it is then comparing the contents of test with "Name", and finding they are not equal. There is yet another hint to be found in the log. Executing the code in an environment such as this: http://jsconsole.com/ shows something interesting about the data we pushed into the log file. Instead of "C C C C C C C C C C AN Ae Ag Aa C ..." the contents are ["C ", "C ", "C ", "C ", "C ", "C ", "C ", "C ", "C ", "AN ", ....].

I don't know javascript enough to have known that would be the case earlier, but it appears that you aren't really creating a string with the contents you're adding to test. Rather, test is an array, into which is being pushed characters from the string myName. Instead of test having a value of "Name", test has a value of ["N", "a", "m", "e"]. An array of the elements which were pushed into it, rather than a string like "Name". Thus a comparison shows them to be not equal. An array and a string are different things (in this language anyway) and so are not interchangeable like that. You must either compare it element by element, or you must use a string for test (using test=test.concat(text[j]); instead of test.push(text[j]); ) and compare it that way.

Overall, this sort of containers issue is one of the trickier points of learning to code from high level languages like javascript. The behavior of these things is sort of a confusing mix of high level 'it just works' mentality (string comparisons) and low level 'how it actually works' (array comparisons, array-string comparisons). The low-level reality is that computers don't compare strings or arrays as a whole; they do an element-by-element comparison like you are doing to find the first matching character. High level languages like javascript often wrap up that operation into a string-specific operation like your === sign. This mixture of high and low level concepts is rightfully confusing for those unfamiliar with them.
« Last Edit: July 25, 2015, 02:48:03 pm by alway »
Logged

Sappho

  • Bay Watcher
  • AKA Aira; Legendary Female Gamer
    • View Profile
    • Aira Plays Games
Re: if self.isCoder(): post() #Programming Thread
« Reply #7580 on: July 25, 2015, 03:05:20 pm »

...well now I'm 100x more confused than I was. :(

I'm using the Code Academy site to learn this, which has a window for writing the code, a button to submit/run the code, and a little console window. I'm an absolute beginner here, and I only know the few commands they have taught me which are, at this point, how to create and modify variables, how to write and run functions, and how to write if...then and for... statements.

This project combines all that to show some of the ways these things can be used practically. Ironically, this program is not practical, but it does give an idea of how these little tools can be used. (I think you can look at it by going to https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/7 )

The basic program that it teaches you to write, step by step, results in it printing a list of letters in an array that start with the first letter of your "name". This is the sample code given, which you then recreate step by step so you can learn how it works:

Code: [Select]
text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {
// If we find it, add characters up to
// the length of my name to the array
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

It gives the result: [ 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c' ]

Which is not at all practical, but it is still a neat thing that I can actually do given my current level of understanding. Unfortunately, it is only checking the first letter, so it will return anything starting with the first letter of your name.

What I was trying to do was change it so it only returns the characters if they all match the name you put in by checking to see if the characters returned match the name before pushing them to the "hits" array. But what it returned was an empty array.

Now, what I think is happening based on what you wrote and what I've been trying to figure out, is that the "test" array will never match the "myName" variable because one is a string and the other is an array. But in this case, instead of returning an empty array, shouldn't it return "Your name wasn't found!" because hits should be 0?

Can you explain what "test = test.concat(text[j])" means and how it works? I don't know "concat" and I'm still struggling with for loops and arrays. (Incidentally, every time I've tried to learn programming before, I've done really, really well until I got to arrays, then the world exploded and I couldn't figure out how to feed myself anymore because no one has ever been able to explain to me how arrays really work in a way that I understand. So now that I'm at arrays again, I'm trying to take the tiniest baby steps and learn one tiny command/concept at a time so I don't get overwhelmed and lost... but it's difficult and confusing and it's taking me ages to get through each step in this course, trying to wrap my head around how the computer is seeing this data...)

I'm assuming that "log.push" is the same as "console.log"?

Just as a random complaint, Javascript is MESSY as hell and it's ugly and I hate it. I started with the Python course first, which is SO much cleaner and easier to understand... But it seems to be necessary to learn Javascript in order to do what I plan to do, so onward I slog... Sorry, just needed to vent that a bit. :)

I beg of everyone, please write all answers as though you are explaining to a five-year-old, because otherwise I will be overwhelmed with all the jargon, panic, and run away crying. I've never been able to learn coding before because people have always explained things using a thousand words I didn't understand. Code Academy is working because they break everything down into the tiniest pieces so I can learn just one bit at a time, but I am still an absolute beginner who only understands the few concrete things that I have learned.

Thank you so much for the patience and help!!! :D

Skyrunner

  • Bay Watcher
  • ?!?!
    • View Profile
    • Portfolio
Re: if self.isCoder(): post() #Programming Thread
« Reply #7581 on: July 25, 2015, 09:46:41 pm »

I'm not sure what the main question is, but I'll try answering the sub-questions.

Quote
Now, what I think is happening based on what you wrote and what I've been trying to figure out, is that the "test" array will never match the "myName" variable because one is a string and the other is an array. But in this case, instead of returning an empty array, shouldn't it return "Your name wasn't found!" because hits should be 0?

Let's try it out in the Javascript console!

['T','E','S','T'] == ['T','E','S','T']
> false

It looks like two arrays won't match even if they have the 'same' content.

I don't see any "test"s in the code you posted though. Did you make sure to post the right version of your code?


Quote
Can you explain what "test = test.concat(text[j])" means and how it works?

Here's a documentation link. Googling for whatever usually turns up help. It says:

Quote from: MDN
The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

So... if you have

var A = ["T", "E"]
var B = ["S", "T"]
var C = A.concat(B)

C would be ["T", "E", "S", "T"]
A, B would be unaltered.

There are more examples on the linked page!

(as an aside, doing A + B gives you a string with the content "T,E,S,TT,E,S,T")

Quote
I'm assuming that "log.push" is the same as "console.log"?

I have never seen log.push before, so I'm assuming it's a CodeAcademy-only construct.
Logged

bay12 lower boards IRC:irc.darkmyst.org @ #bay12lb
"Oh, they never lie. They dissemble, evade, prevaricate, confoud, confuse, distract, obscure, subtly misrepresent and willfully misunderstand with what often appears to be a positively gleeful relish ... but they never lie" -- Look To Windward

Reelya

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7582 on: July 25, 2015, 09:50:31 pm »

getting characters with [] also doesn't work in all implementations of javascript. Try printing out your "text" variable one letter at a time and check that it is actually getting the letters.

string.charAt(i) is a function that works when string [ i ] doesn't

You can avoid a lot of pain, by using print commands at every step where you are having problems. Never assume a variable has what you think it has, always check. and print out the individual characters that are being compared etc. This is the only way that you can narrow down problems, since different implementations of the same language may not work the same on all platforms. For example, running your JavaScript here natively, it couldn't even extract the individual characters of the text with your original code. So it was extracting nothing, comparing it to nothing, and putting nothing in the output. Once i realized there was a problem getting the original characters, then I just google "javascript get characters from string" and got a few replacement options from stackoverflow.
« Last Edit: July 25, 2015, 09:58:22 pm by Reelya »
Logged

Moghjubar

  • Bay Watcher
  • Science gets you to space.
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7583 on: July 25, 2015, 09:55:42 pm »

I'm using Code Academy to learn coding! It is working! I'm doing Javascript! Hooray!


May want to check out http://www.freecodecamp.com/  as well, has a decent overall tutorial (and linkbacks to Code Academy / other places as well).  Have been plowing thru it last week or so: starts with CSS/Jquery, moves into Javascript and eventually advanced stuff. 

... I feel so much rage at Javascript trying to do things that I would have been able to do instantly in C.   *SIGH*.  Ah well, I guess part of learning another language.
All of my rage though: Regular Expressions.
Logged
Steam ID
Making things in Unity
Current Project: Demon Legend
Made This too (publisher abandoned ) Farworld Pioneers
Mastodon

Reelya

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7584 on: July 25, 2015, 10:01:02 pm »

I've used regex pretty extensively in JavaScript, so if you have any issues run them by me.

RegExp are neat though. With them, Sappho's entire program basically becomes:

hits = text.match(RegExp("\\b"+myName+"\\b","g"));

Then check whether hits === null or not.
« Last Edit: July 25, 2015, 10:16:55 pm by Reelya »
Logged

Skyrunner

  • Bay Watcher
  • ?!?!
    • View Profile
    • Portfolio
Re: if self.isCoder(): post() #Programming Thread
« Reply #7585 on: July 25, 2015, 10:02:46 pm »

edit: whoops, misread
Logged

bay12 lower boards IRC:irc.darkmyst.org @ #bay12lb
"Oh, they never lie. They dissemble, evade, prevaricate, confoud, confuse, distract, obscure, subtly misrepresent and willfully misunderstand with what often appears to be a positively gleeful relish ... but they never lie" -- Look To Windward

alway

  • Bay Watcher
  • 🏳️‍⚧️
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7586 on: July 25, 2015, 11:00:08 pm »

@ sappho:
So basically, when you're doing your comparison there, if (text === "E") returns true when it finds an E, as it is comparing an element within the array text to the character E. An array is essentially just a big box with slots in which you can put things. Those things won't interact with one another, merge, etc; they're just data in separate slots of memory. So it looks into slot i within text, pulls out the contents (which happen to be "E"), and then compare that with "E". These match.

However, say we compare the big box of characters called text to the string "Eric". Javascript looks at it and says "sorry chief, that's a box of letters, and is not equal to "Eric"". Within the slots of the box of letters are the individual letters "E", "r", "i", "c", but javascript doesn't look inside the box, it just sees the box, says that isn't "Eric" and goes on its way.

Then, consider the comparison Skyrunner mentioned: when Javascript compared 2 boxes, each with the same letters in their slots. Javascript looks at the two boxes, and says "these boxes are not the same box, they are different boxes; thus they are not equal."

(Somewhat confusing side-note on why it does this, ahoy!)
Code: [Select]
Why is this important? For one, because a box can have any
type of data inside. Some types may be entirely impossible or
at least impractical to evaluation for equivalence. For example,
take 2 'boxes' and put boxes in their slots. Box A contains Box B;
and Box B contains Box A. It will use the following code:

var BoxA = [];
var BoxB = [];
BoxA.push(BoxB);
BoxB.push(BoxA);

This will result in A containing B and B containing A. You can
even push a box into one of its own slots!

(details you don't really need yet at your stage of learning code
with Javascript) The underlying reason for this is that rather than
being a physical space with slots, Box A and Box B (or any other array)
are essentially IOU cards telling you where to find the slots for
Box A and Box B. The end result of this montage of confusion is
that arrays may not even necessarily have a bottom level!

Box A could even be something [i]really[/i] weird, like [BoxA, "E"].
If compared by finding out what was inside the boxes, you could end
up with an infinite loop.

And so, instead of looking into the potentially
terrifying recursive box, Javascript simply looks at the outside of Box A,
and says "That's not Box B"
If you see the notation [some, stuff, separated, by, commas] it means it is an array, with slots separated by commas.

When you see the notation "Eric", it implies "Eric" is a string, which is a special data type for character manipulation, and has special properties and functions as such. Unlike the box of the array, we know for a fact that the string will always contain characters. No numeric value which haven't been turned into their character representation, no arrays, no boxes-which-may-or-may-not-contain-themselves. This additional structure means we can compare them by looking at what characters they contain, since we don't run the risk of finding uncomparable things. Similarly, they have predefined functions to make the day-to-day string operations easier, with a decently well-defined vocabulary that crosses languages.

The concat function is one such special function for dealing with strings. It's short for 'concatenate,' which has the specific meaning of 'link the end of the first thing to the beginning of the second.' Without changing the two things, it then returns the linked version. This is a fairly standard string operation, and adds one string to another.
Code: [Select]
var StringPartOne = "FirstPart";
var StringPartTwo = "SecondPart";
var Result = StringPartOne.concat(StringPartTwo);
That operation takes StringPartTwo, and puts it on the end of FirstPart. The string Result is now "FirstPartSecondPart".

This is different from an array's push function. If instead we do this:
Code: [Select]
var Result = [];
Result.push("FirstPart");
Result.push("SecondPart");
Result is now equal to ["FirstPart","SecondPart"]. Essentially what we've done is started by creating a box, Result. The push operation tells the box Result "Create a new slot within yourself, then put this thing in it." So it created a new slot, and put "FirstPart" into that slot. It then created a second new slot, and put "SecondPart" into that one. So now, Result has 2 slots, one holding the first string, the second holding the other string.

As for console.log, that's actually a display function. That's a function that it simply uses to display something to the console log. As for my log.push stuff, that was just sticking data into an array to be examined later; I just wasn't sure which method/s you were using to display that data, and so didn't want to give a specific function to use.
Logged

Reelya

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7587 on: July 25, 2015, 11:35:23 pm »

Here you have why I prefer static typed languages to dynamic types languages. Dynamic typing just saves a tiny bit of typing, but is a whole fucking pain in the ass to debug what's actually going on. Dynamic typed languages let you put in absolutely rubbish code and run it, giving absolutely rubbish results without any error messages, and then you're left looking up an encyclopedia of weblinks to work out what the dynamic typing is actually doing.

On the other hand, a static typed language like C++ or C# would have given you detailed error messages about the whole mess before you even run your program. None of this JavaScript bullshit about accidentally making an array when you wanted a string etc. In C++ or C# you know exactly what types every variable are, and they're not accidentally a different type on tuesday because someone typed in unexpected inputs.
« Last Edit: July 25, 2015, 11:40:26 pm by Reelya »
Logged

Skyrunner

  • Bay Watcher
  • ?!?!
    • View Profile
    • Portfolio
Re: if self.isCoder(): post() #Programming Thread
« Reply #7588 on: July 25, 2015, 11:45:49 pm »

I am pretty sure the issue with javascript isn't the dynamic typing but the weak typing. It has a ton of implicit casting, too. like array to string or int to string.
Logged

bay12 lower boards IRC:irc.darkmyst.org @ #bay12lb
"Oh, they never lie. They dissemble, evade, prevaricate, confoud, confuse, distract, obscure, subtly misrepresent and willfully misunderstand with what often appears to be a positively gleeful relish ... but they never lie" -- Look To Windward

Bauglir

  • Bay Watcher
  • Let us make Good
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7589 on: July 26, 2015, 12:09:36 am »

Anybody here familiar with BeautifulSoup? I'm trying to extract text from a webpage, and am getting some really bizarre results.

Code: [Select]
page_src = BeautifulSoup(self.browser.page_source, 'lxml')
page_text = page_src.get_text()

Where self.browser.page_source is a reference to another bit of code. I've tested the output of the first line, and as far as I can tell it works fine. However, get_text() also grabs a lot of chunks of javascript that I don't want to be in there, so I tried inserting what seems to be the standard way of handling it in between those two lines:

Code: [Select]
for script in page_src(["script", "style"]):
    script.extract()

When I do this, get_text() returns a scrap of text out of the page title, as well as some javascript. What boggles the mind is that, if I print page_src after the loop, not only is there much more text remaining in the data structure that is successfully gotten when I don't try to remove scripts with that loop but mysteriously ignored if I do, the javascript that get_text() gets isn't even there anymore. Replacing extract() with decompose() removes the errant javascript from get_text's output, but doesn't restore the actual content.

I can't fit the contents of page_src into a single post, but if they'll help let me know. It's a narrow difference, so without the get_text() output they should fit into a second one. The main thing of note is that all the actual text that's displayed in Spoiler #1 is still in the source, so it didn't get erroneously deleted.

Here's the test page (random dude from local university website) Here are those outputs:


Spoiler: get_text() with loop (click to show/hide)
« Last Edit: July 26, 2015, 12:39:24 am by Bauglir »
Logged
In the days when Sussman was a novice, Minsky once came to him as he sat hacking at the PDP-6.
“What are you doing?”, asked Minsky. “I am training a randomly wired neural net to play Tic-Tac-Toe” Sussman replied. “Why is the net wired randomly?”, asked Minsky. “I do not want it to have any preconceptions of how to play”, Sussman said.
Minsky then shut his eyes. “Why do you close your eyes?”, Sussman asked his teacher.
“So that the room will be empty.”
At that moment, Sussman was enlightened.
Pages: 1 ... 504 505 [506] 507 508 ... 796