Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
nielsm
Jun 1, 2009



ufarn posted:

I want to do something similar to dropping and creating an empty database in MySQL in postgreSQL, but I can't drop a template datbase like template1. Nevertheless, I want to clear the table for purposes in a Django project.

What's the best way to go about this? Basically, I want some kind of "clear" command.

SQL questions megathread

Also your question is very unclear.

Do you want to remove and re-create a template database?
Do you want to remove and re-create a regular database?
Do you want to remove and re-create a regular database such that it is not based on any template at all?
Do you just want to remove all data stored in a database but keep all tables and other objects?

DELETE FROM tablename; empties a table, while checking for foreign key constraints and running any triggers.
DROP TABLE tablename; deletes a table and all data in it, but it will fail if any other tables have foreign key constraints to that table. (There are probably more ways it can fail.)
Creating and removing databases is done with an administration tool not based on SQL.

Adbot
ADBOT LOVES YOU

ufarn
May 30, 2009

nielsm posted:

SQL questions megathread

Also your question is very unclear.

Do you want to remove and re-create a template database?
Do you want to remove and re-create a regular database?
Do you want to remove and re-create a regular database such that it is not based on any template at all?
Do you just want to remove all data stored in a database but keep all tables and other objects?

DELETE FROM tablename; empties a table, while checking for foreign key constraints and running any triggers.
DROP TABLE tablename; deletes a table and all data in it, but it will fail if any other tables have foreign key constraints to that table. (There are probably more ways it can fail.)
Creating and removing databases is done with an administration tool not based on SQL.
I want to clear everything inside template1 in postgreSQL, the same end result as is achieved by doing drop database mydb; create database mydb; in MySQL, which I am more familiar with. I want the same template1 I had, before I populated it with data from a Django project.

I'll look more into it, and thanks for the link I somehow didn't manage to find.

csammis
Aug 26, 2003

Mental Institution

ufarn posted:

I want to clear everything inside template1 in postgreSQL, the same end result as is achieved by doing drop database mydb; create database mydb; in MySQL, which I am more familiar with. I want the same template1 I had, before I populated it with data from a Django project.

I'll look more into it, and thanks for the link I somehow didn't manage to find.

If you just want to clear it and maintain the table structure, TRUNCATE.

Syenite
Jun 21, 2011
Grimey Drawer
So, if anyone here is familiar with autohotkey, I've got a weird issue that I have no clue where it's coming from.

This is the script which prepares a file which contains stuff the main script needs to run:

code:
FileDelete menus.ahk

Loop, Read, menus.txt
{
	Loop, parse, A_LoopReadLine,|
	{
		if A_Index = 1
			name := A_LoopField
		if A_Index = 3
			code := A_LoopField
		if A_Index = 4
			flags := A_LoopField
	}
	FileAppend,
	(
%name%:
gomenu(%code%)
flagexec(%flags%)
return


	),menus.ahk
	name := ""
	code := ""
	flags := ""
}

Run mouse.ahk
And this is the relevant bit of the main script:

code:
Loop, Read, menus.txt
{
	Loop, parse, A_LoopReadLine,|
	{
		if A_Index = 1
			name := A_Loopfield
		if A_Index = 2
			parent := A_Loopfield
	}
	if (parent <> "")
		menu, %parent%, add, %name%
	else if (parent = "")
		parent := context
	if (name = lastparent)
		menu, %parent%, add, %name%, :%name%
	lastparent := parent
	name := ""
	parent := ""
}

#Include menus.ahk
And a short example of what menus.txt could be:

code:
Furniture|Buildings
Buildings
Designations
Stockpiles
The issue is that when the main script is running through, adding menus and whatnot, it throws a "Menu Name too Long" error. At no point in the script are any of the variables in the script even approaching the menu character limit of something like 260 or so, so I have no clue why in the world it would throw this error. :psyduck:


E: Nevermind, got it figured out. It's working now, I just don't know why it was throwing that specific error.

Syenite fucked around with this message at 00:26 on Feb 20, 2012

Tots
Sep 3, 2007

:frogout:
Who wants to help me complete a basic java assignment that's due tomorrow morning? I don't want you to do it for me, but kind of just walk me through the whats and whys in a collab online editor. If you're successful in helping me finish it I'll get you an upgrade/whatever of your choice.

Jewel
May 2, 2009

Tots posted:

Who wants to help me complete a basic java assignment that's due tomorrow morning? I don't want you to do it for me, but kind of just walk me through the whats and whys in a collab online editor. If you're successful in helping me finish it I'll get you an upgrade/whatever of your choice.

I might help take a look at it? At the very least, chat a bit about it!

Look Around You
Jan 19, 2009

Tots posted:

Who wants to help me complete a basic java assignment that's due tomorrow morning? I don't want you to do it for me, but kind of just walk me through the whats and whys in a collab online editor. If you're successful in helping me finish it I'll get you an upgrade/whatever of your choice.

:lol:

e:
Less dickish: what problems are you having with it?

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

:lol:

e:
Less dickish: what problems are you having with it?

I just don't have a solid grasp on OOP. Reading about it isn't doing much good, so I figure it's tutor time.

E: Feel free to make fun of me/deface my retard program here: http://collabedit.com/k4w9y

Assignment detail here:
https://www.dropbox.com/s/djars6tl1vyghyu/HW6_Methods.pdf


Yes I know I'm retarded and should quit programming etc etc

Tots fucked around with this message at 06:33 on Feb 21, 2012

Look Around You
Jan 19, 2009

Tots posted:

I just don't have a solid grasp on OOP. Reading about it isn't doing much good, so I figure it's tutor time.

E: Feel free to make fun of me/deface my retard program here: http://collabedit.com/k4w9y

Assignment detail here:
https://www.dropbox.com/s/djars6tl1vyghyu/HW6_Methods.pdf


Yes I know I'm retarded and should quit programming etc etc

Sorry, I was being kind of harsh, it's just that usually when people say "I need help on an assignment" they actually do want it pretty much done for them, even if they say they don't (usually in the form of a ton of hand holding)

e: I looked through it and said this in the chat but I dunno if you got it:
code:
(line 46)        EmployeePayment EmployeePayment = new EmployeePayment();
This isn't right; you can't (or at least shouldn't) use the exact name of the class as the name of a variable. Try EmployeePayment employeePayment or something similar (java is case sensitive).

Also this isn't on you but more on the professor: using floating point numbers (float, double) for money is BAD BAD BAD, but it's way beyond the scope of the course to explain why most likely.

Look Around You fucked around with this message at 07:02 on Feb 21, 2012

baquerd
Jul 2, 2007

by FactsAreUseless

Look Around You posted:

Also this isn't on you but more on the professor: using floating point numbers (float, double) for money is BAD BAD BAD, but it's way beyond the scope of the course to explain why most likely.

I know this gets said a lot, but this only really matters for transactional applications. The vast majority of reporting and tracking applications, for example, have no need for perfect precision.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Alright, this Scheme question has me completely stumped. I'm supposed to take a complex list like this:
code:
((name: <name here>) (args: <arguments here>) (body: <body here>))
and transform it into a function defined outside the function (so, I have a list mylist formatted like that, I pass it as the parameter to my function, and then it's a function I can call.) I think from examples in class, we're supposed to use let, but I can't figure out how to take what happens and define it outside the function.

Here's what I have:
code:
(define makefun
  (lambda (prototype)
    (define (car (cdr (car prototype))) 
      (list 'lambda (cdr (car (cdr prototype))) (cdr (car (cddr prototype)))))))
I get an error on (define (car [(cdr (car prototype))]) of "define: not an identifier for procedure argument in: (cdr (car prototype))" when the function is being defined, not when it's being called.

For reference, here's the example that uses let, it builds a lambda and displays it:

code:
(define mAA
  (lambda (a b)
    (let ((fbody (list (list 'lambda '(x y) (list '+ 'x 'y)) a b)))
      (display fbody))))
It seems to me that it wants to run the define immediately, instead of when called, or it's having a problem seeing that a symbol should resolve from those composed functions.

Any pointers to push me in the right direction?

I'm using DrScheme (PLT 372, Textual, MzScheme R5RS) if that matters.

Look Around You
Jan 19, 2009

Ok since collabedit is impossible to use, here's a summary of OO concepts that you're having problems with:

Static methods/variables are "class" variables. There is only one of them per class.

Non static methods (i forgot the technical term) and instance variables are used on instances of a class.

code:
public class Person {
  private static int numPeople = 0;
  private String name;
  private boolean isMale;

  // class methods

  public static int getPopulation() {
    return numPeople;
  }

  public static void addPerson() {
    numPeople++;
  }  

  // instance methods

  public String toString() {
    return name + " : " + Boolean.toString(isMale);
  }

  public String getName() {
    return name;
  }
  public void setName(String newName) {
    this.name = newName;
  }

  public boolean isMale() {
    return this.isMale;
  }
  public void setMale(boolean isMale) {
    this.isMale = isMale; 
        // ^^ careful; your objects property, this.isMale 
        // is different than the parameter isMale!
  }
}


So in this example, there is only ONE numPeople no matter how many instances of hte class are made. In contrast, every instance of the class has a separate name variable (field/property).

code:
public class DoStuffWithPeople {
  public static void main(String[] args) {
    Person dude1 = new Person(); // make dude1 an INSTANCE of Person
    Person.addPerson();  // use STATIC METHOD addPerson
    dude1.setName("bob");
    dude1.setMale(true);

    System.out.println(Person.getPopulation()); // prints 1
    System.out.println(dude1.toString()); // prints bob : true

    Person dude2 = new Person(); // make dude2 a SEPARATE INSTANCE of Person
    Person.addPerson();
    dude2.setName("bill");
    dude2.setMale(true);

    System.out.println(Person.getPopulation()); // prints 2
    System.out.println(dude2.toString()); // prints bill : true
    
    dude1.setName("mary");
    dude1.setMale(false);
    
    System.out.println(dude1.toString()); // prints mary : false
    System.out.println(dude2.toString()); // prints bill : true
    System.out.println(Person.getPopulation()); // prints 2
  }
}
e: tables

Tots
Sep 3, 2007

:frogout:
Just wanted to give a big thanks to LookAroundYou and orenj for helping me wrap my head around some pretty important concepts.

I'll rain down the good karma on new beginners in a few months.

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice

baquerd posted:

I know this gets said a lot, but this only really matters for transactional applications. The vast majority of reporting and tracking applications, for example, have no need for perfect precision.

I agree, even if the report is doing something silly and incrementing $0.29 for every sale row of your iPhone widget, you'd have to be reporting like $10 trillion dollars for precision to start being an issue (but what if hyperinflation kicks in? :v:). That being said, the concept of floating point loss of precision should be reenforced early on. It is important to know because it can lead to odd bugs that aren't very obvious unless you understand what is happening.
code:
#include <string>
#include <iostream>

int main() 
{
	float a = 3.5E-15;
	float b = 1.0E14;
	float c = (a + b);

	if( (c - b) == a ) { 
		std::cout << "The numbers match." << std::endl;
	} else {
		std::cout << "The number don't match." << std::endl;
	}

	system("pause");
	return 0;
}
It doesn't require rote memorization of the IEEE-754 standard to understand why the following prints, "The numbers don't match." I can't see any reason not to teach this to first-year programmers.

oRenj9 fucked around with this message at 08:08 on Feb 21, 2012

Look Around You
Jan 19, 2009

carry on then posted:

(scheme stuff)

Do you have to create a new top-level definition from this or do you need to return a callable function?

e:
By that I mean, do you have to be able to do this?
code:
(makefun '((name: myfunc) (args: (arg1 arg2)) (body: (+ arg1 arg2))))
[...]
(myfunc 2 3)
e2:
or can it do this:
code:
; maybe these parens don't match idk
(define myfunc (makefunc '((name: blah) (args: blahblah) (body: (+ blahblah 1)))) 
[...]
(myfunc 3) ; prints 4 
e3:
The problem you're having with your define is this:

code:
;; What you have
(define makefun
  (lambda (prototype)
    (define (car (cdr (car prototype))) ;; <- here is the problem
      (list 'lambda (cdr (car (cdr prototype))) (cdr (car (cddr prototype)))))))
The issue is that you're not giving a name to what you're defining; the syntax for define is (define <var> <expr>). There's an alternate syntax used as shorthand for defining procedures: (define (<var> <args>) <body>) which is equivalent to (define <var> (lambda (<args>) <body>)), which is what scheme thinks you're doing there probably.

Look Around You fucked around with this message at 09:18 on Feb 21, 2012

Cornflake
Jun 22, 2005
Psycho Alpha Disco Beta Bio Aqua Do Loop
I'm a recreational/newbie programmer and I was wondering how to implement testing. Its not so much the actual tests I'm concerned about as much as how they are implemented into the overall program.

Do you have to compile a special version of your program which reports the results of the tests? Do you just incorporate the tests in your main program and the compiler will fail if a test fails? Do you maintain a separate copy of your application which you compile just for testing?

I guess I'm just confused as to how this would work conceptually.

BizarroAzrael
Apr 6, 2006

"That must weigh heavily on your soul. Let me purge it for you."
I'm using Python to read an XML file, the XML representing a file structure. So each directory is an entity with subdirectories as child entities. To recurse through the actual file structure I start at the root of the target file structure and check the child entities to find the directories to proceed to. This means if I entity.childnodes() on a directory entity I collect the name of the root directory, the sub directories I want to move to and all subdirectories of them. Is there a way to get only the immediate children of an entity?

baquerd
Jul 2, 2007

by FactsAreUseless

Cornflake posted:

I'm a recreational/newbie programmer and I was wondering how to implement testing. Its not so much the actual tests I'm concerned about as much as how they are implemented into the overall program.

Do you have to compile a special version of your program which reports the results of the tests? Do you just incorporate the tests in your main program and the compiler will fail if a test fails? Do you maintain a separate copy of your application which you compile just for testing?

Modern unit testing frameworks generally have you create entirely separate code that is designed to use the framework to test other code you have written. The general thrust behind testing is to ensure correctness, meaning that if a test fails the code is behaving incorrectly and needs to be fixed.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Look Around You posted:

<snip>

Thanks for mentioning the shorter syntax. I got it working as
code:
(define makefun
  (lambda (prototype)
    (let ((func (append (cons 'define (list (append (list (car (cdr (car prototype)))) (cdr (car (cdr prototype)))))) (cdr (car (cddr prototype))))))
      (eval func))))

(define butts '((fname: butts) (fargs: a b) (fbody: (* a b))))
(makefun butts)
(butts 3 4) ; => 12
So yeah, thanks for the help!

Edit: and yeah, I go crazy with the cons, list, and append stuff, I'll clean that up now that I have it working.

Cornflake
Jun 22, 2005
Psycho Alpha Disco Beta Bio Aqua Do Loop

baquerd posted:

Modern unit testing frameworks generally have you create entirely separate code that is designed to use the framework to test other code you have written. The general thrust behind testing is to ensure correctness, meaning that if a test fails the code is behaving incorrectly and needs to be fixed.

I see. Does this mean you have to make a copy of all your functions/classes in your test code (or I guess in the case of TDD, copy the code from your testing application to your main program)? Wouldn't this be a problem for much larger applications where it would be hard to isolate the dependencies of various bits of code?

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Presumably your language of choice has some means to include code from other files, so you just use that.

code:
# test_updog.rb
require 'hilarity' # you wrote this

def test_updog
  assert Hilarious.Joke == "What is updog?"
end
That throws an exception if your hilarious joke isn't that exact question.

What language are you using? I'm sure we can all pile on with contradictory suggestions that are more specific to you.

edit:

Cornflake posted:

Wouldn't this be a problem for much larger applications where it would be hard to isolate the dependencies of various bits of code?

It can actually be rather hard to isolate dependencies in large, or even small, projects. It makes does tend to make testing easier, though.

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?
If you have proper code separation then your application logic will separate from your UI logic - by which I mean in a separate class / namespace / project depending on the size and complexity of the codebase. This makes testing the application logic relatively straightforward as you can call the methods in the same way your UI would.

Lanithro
Aug 31, 2006
Been playing around with writing a dice roller, and I started by using the modulus operator -- I'm beginning to realize why it might suck.

Below are some example rolls. I've taken care of modulus bias by making sure that the random value cannot be higher than the highest multiple of the dice you're rolling.

But the real problem is: Why bother generating huge pseudo-random numbers when you're using modulus which only really cares about the last few digits?

Could someone point me in the direction of alternate methods to determine a d20 roll from a random number?

By using modulus, I'm ending up with a lot of duplicate rolls even though the random number is totally different.

pre:
Dice		Random Value			 Roll Result (randval % diceval + 1)
------------------------------------------------------------------------------------
diceval: 20     randval: 3297342412118512937     roll: 18
diceval: 20     randval: 9759874835077874119     roll: 20
diceval: 20     randval: 12049328428928256614    roll: 15
diceval: 20     randval: 1604217091879388076     roll: 17
diceval: 20     randval: 13051262830981756516    roll: 17
diceval: 20     randval: 675644988715073016      roll: 17
diceval: 20     randval: 13355903627639918928    roll: 9
diceval: 20     randval: 6119727242163020892     roll: 13
diceval: 20     randval: 11039749756647233713    roll: 14
diceval: 20     randval: 18339397570138391653    roll: 14

Lanithro fucked around with this message at 01:04 on Feb 22, 2012

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
One common way to generate random numbers is a Linear Congruential Generator.
code:
int seed = 0xDEADBEEF;
int rand() {
	seed = (1664525 * seed + 1013904223);
	return seed;
}
The calculation we perform here is implicitly modulo 2^32 due to overflow behavior. The function calculated is chaotic- that is, terms form a deterministic but complex pattern. If the seed we start with is taken from the system clock or some other source of unpredictability, we will see a different set of "random" numbers every time we use this algorithm.

One important observation about this system is that, even with an ideally chosen initial seed (and the constants in the feedback expression), the longest non-repeating sequence of "random" numbers we can generate is 2^32, because that's how many distinct values the seed can represent. By taking the result of rand() modulo 20, we only look at a few low-order bits of the seed for any given die roll, but the overall pattern formed by our die rolls can have a repeating sequence much longer than we are likely to notice in the course of a game.

As for why you see a lot of repeating numbers, that doesn't necessarily say anything is wrong. If each roll is independent, the probability of rolling a 20 ten times consecutively on a real die is the same as any other given sequence.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I feel like a loving retard for asking this question, but being a self-taught hobbyist means I've got wide gaps in my knowledge that only get filled when I need to know something.

I don't understand bitwise operations.

For example, take this code (from AutoIT, but that doesn't really matter):

code:
Local $iIDFrom = BitAND($wParam, 0xFFFF) ; LoWord - this gives the control which sent the message
Local $iCode = BitShift($wParam, 16) ; HiWord - this gives the message that was sent
I get that this extracts two values out of another value...but I don't really understand how it's doing that. So, what's going on here?

ufarn
May 30, 2009
I am currently building a static blog hosted on Amazon S3, and this requires using a subdomain to point to the S3 bucket - in other words that I host the site on https://www.mydomain.com. Now, it's not like I can just turn away my non-www visitors, so which is the best way to redirect them?

I don't know a whole lot about the SEO stuff that goes on behind the scenes, and I obviously don't want to cripple the traffic of my blog, so which is the smoothest way to go about it?

Cornflake
Jun 22, 2005
Psycho Alpha Disco Beta Bio Aqua Do Loop

pokeyman posted:

Presumably your language of choice has some means to include code from other files, so you just use that.

code:
# test_updog.rb
require 'hilarity' # you wrote this

def test_updog
  assert Hilarious.Joke == "What is updog?"
end
That throws an exception if your hilarious joke isn't that exact question.

What language are you using? I'm sure we can all pile on with contradictory suggestions that are more specific to you.

edit:


It can actually be rather hard to isolate dependencies in large, or even small, projects. It makes does tend to make testing easier, though.

Okay this is all starting to make sense. I use C++ primarily. I'm actually working my way through Programming: Principles and Practice Using C++ by Bjarne Stroustrup. I was trying to read up on testing and I stumbled across TDD and it seemed like a cool way to tackle programming but I just wanted to understand the implementation better. The tests make perfect sense, I just couldn't seem to find many examples of how to integrate it into a project.

ToxicFrog
Apr 26, 2008


Internet Janitor posted:

As for why you see a lot of repeating numbers, that doesn't necessarily say anything is wrong. If each roll is independent, the probability of rolling a 20 ten times consecutively on a real die is the same as any other given sequence.

On the other hand, some PRNGs have issues in this respect - for example, the legacy implementation of rand() (which is still the default on windows) has low-order bits (which is to say: the ones you will actually be looking at using mod) that are much less random than the high-order bits.

So while it can be random chance, there are some PRNGs that will do this consistently because they don't work very well.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Thermopyle posted:

I feel like a loving retard for asking this question, but being a self-taught hobbyist means I've got wide gaps in my knowledge that only get filled when I need to know something.

I don't understand bitwise operations.

For example, take this code (from AutoIT, but that doesn't really matter):

code:
Local $iIDFrom = BitAND($wParam, 0xFFFF) ; LoWord - this gives the control which sent the message
Local $iCode = BitShift($wParam, 16) ; HiWord - this gives the message that was sent
I get that this extracts two values out of another value...but I don't really understand how it's doing that. So, what's going on here?

Do you know what an AND operation is? What the first line of code is doing is its taking the first 2^16 (0xffff) bits and setting them to true only if the equivalent bits in $wParam are also true.

For example, to make it easier, say you want to BitAND $wParam by 0xF (16) instead. If $wParam is the number 100, convert it into binary (0b01100100) first. Then you match it up with 16 and do an & operation on each bit.
code:
  01100100 (the number 100)
& 00001111 (the number 16)
----------
  00000100 
Which is equivalent to 0100, or the first four (least significant) bits of 100.

Now if you want to get the bits after the first four bits of 100, well you don't want to just assume that there are only 4 more bits after the first 4 (the number could be greater than 2^8, so you can't just BitAND $wParam with 11110000. What you need to do is to move those bits out of the way, what BitShift does is it pushes the bits out by dropping the least significant digit.

So if you do BitShift(100, 1): 100 = 0b01100100 becomes 0b00110010. If you call BitShift(100,4) that pushes the 4 least significant digits off. So 0b01100100 becomes 00000110. So the BitShift($wParam,16) pushes the 16 least significant digits (or the value that $iIDFromm holds) out of $wParam.


ufarn posted:

I am currently building a static blog hosted on Amazon S3, and this requires using a subdomain to point to the S3 bucket - in other words that I host the site on https://www.mydomain.com. Now, it's not like I can just turn away my non-www visitors, so which is the best way to redirect them?

I don't know a whole lot about the SEO stuff that goes on behind the scenes, and I obviously don't want to cripple the traffic of my blog, so which is the smoothest way to go about it?

If you're running Apache/nginx, you setup an htaccess file to redirect the user whenever there is no www prefix. Honestly though probably better to just drop the www and go with mydomain.com

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
ToxicFrog: Of course. My point is simply that "eyeballing" isn't a good way to judge the quality of random numbers.

nielsm
Jun 1, 2009



Thermopyle posted:

I feel like a loving retard for asking this question, but being a self-taught hobbyist means I've got wide gaps in my knowledge that only get filled when I need to know something.

I don't understand bitwise operations.

For example, take this code (from AutoIT, but that doesn't really matter):

code:
Local $iIDFrom = BitAND($wParam, 0xFFFF) ; LoWord - this gives the control which sent the message
Local $iCode = BitShift($wParam, 16) ; HiWord - this gives the message that was sent
I get that this extracts two values out of another value...but I don't really understand how it's doing that. So, what's going on here?

First, what binary is: A different way of writing numbers. In the usual decimal system, every time you move one position to the left the figure at that position is worth 10 times that of figures to the right of it. In binary, every position to the left is worth 2 times that of figures to the right of it. And instead of 10 symbols (0 1 2 3 4 5 6 7 8 9) you only have two symbols (0 1).
For example, the binary number 10010110 rewritten in decimal becomes 1*128 + 1*16 + 1*4 + 1*2 = 150. Remember that the computer doesn't work in decimal, it works in binary, when you read and write numbers in decimal on the computer it's just a convenience given to you.
Also, when working in binary you usually work with bitfields of a fixed width. I'll work with 8 bits here because that's shorter in explanations.

The three basic bitwise operators:
code:
AND  0  1    OR  0  1    XOR  0  1
 0   0  0    0   0  1     0   0  1
 1   0  1    1   1  1     1   1  0
If you consider 0 as "false" and 1 as "true", then AND means "both are true", OR means "at least one is true" and XOR (exclusive or) means "exactly one is true".

Doing bitwise calculations simply means taking the binary representation of two numbers and doing the operation on each pair of bits.
code:
     10010110  (150 decimal, 0x96 hexadecimal)
AND  00001111  ( 15 decimal, 0x0F hexadecimal)
=    00000110  (  6 decimal, 0x06 hexadecimal)
This is an example of what the first operation you have does. It uses AND to isolate the value in just some of the bits. In this case, the four lowest bits are set in the second number, so it takes those and zeroes the rest. In your case, the 16 lowest bits of a 32 bit number are set, meaning it isolates the 16 lowest bits.

Bit shifting is exactly what it sounds like: Shifting the bits around in the field. In C, the operators for bit shifting are << and >> for shifting left and right. With 8 bit (unsigned) numbers:
10010110 << 4 = 01100000
10010110 >> 4 = 00001001

In the first, four zeroes are shifted in from right, and they push the four topmost bits out of the field. In the second case, four zeroes are shifted in from left and push the four rightmost bits out.
If you shift a 32 bit number right by 16 bits, you are moving the topmost 16 bits into the low 16 bit, and the top 16 bits are zeroed out. Effectively, you have isolated the top 16 bits, that is what happens in your code.


(EFB etc, hopefully two explanations are better than one :))

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

Cornflake posted:

Okay this is all starting to make sense. I use C++ primarily. I'm actually working my way through Programming: Principles and Practice Using C++ by Bjarne Stroustrup. I was trying to read up on testing and I stumbled across TDD and it seemed like a cool way to tackle programming but I just wanted to understand the implementation better. The tests make perfect sense, I just couldn't seem to find many examples of how to integrate it into a project.

I'm not up on C++ but here's a sample unit test in C++.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



ToxicFrog posted:

On the other hand, some PRNGs have issues in this respect - for example, the legacy implementation of rand() (which is still the default on windows) has low-order bits (which is to say: the ones you will actually be looking at using mod) that are much less random than the high-order bits.

So while it can be random chance, there are some PRNGs that will do this consistently because they don't work very well.

http://www.random.org/analysis/ you can never be sure :)

He could at least generate ~10k numbers and see what the distribution looks like, rather than 5 or 10.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Strong Sauce and nielsm:

My confusion arose from it seeming "unnatural" to use AND and the like on individual digits of binary numbers. That's probably because I only theoretically understand binary numbers and avoid them like the plague (same with hex). I guess I need to find some exercises or something to help me internalize alternative representations like those.

Your explanations both made a lot of sense and helped ground me a bit more in binary, so thanks!

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?

Thermopyle posted:

I feel like a loving retard for asking this question, but being a self-taught hobbyist means I've got wide gaps in my knowledge that only get filled when I need to know something.

I don't understand bitwise operations.

For example, take this code (from AutoIT, but that doesn't really matter):

code:
Local $iIDFrom = BitAND($wParam, 0xFFFF) ; LoWord - this gives the control which sent the message
Local $iCode = BitShift($wParam, 16) ; HiWord - this gives the message that was sent
I get that this extracts two values out of another value...but I don't really understand how it's doing that. So, what's going on here?

Without knowing the size of $wParam (this may be implied but I know nothing about AutoIT) it's hard to say exactly but In terms of understanding the technique, the key is that these are bitwise operations (as are their counterparts of OR and XOR):

code:
    1010
AND 1111
  = 1010

    1010
 OR 1111
  = 1111

    1010
XOR 1111
  = 0101
A bitshift does what it sounds like - it moves the binary sequence one way or another within the bit field, but implementations differ in that some languages support rotary shifts and others simply overflow.

10110001 shifted to the left two places with a non-rotary shift:
11000100

10110001 shifted to the left two places with a rotary shift:
11000110


What's the point of all of this? Well one reason is that in some situations (e.g. embedded systems interfacing directly with hardware at a low level, where bandwidth/storage is limited) you need to pass information as efficiently as possible, so you encode multiple values into one byte/word/dword.

Let's say you have a byte containing 10110101. The lowest (right-hand) 4 bits represent 1 value and the upper (left-hand) 4 bits represent another. Let's say this byte is represented by a variable called "param".

code:
(pseudocode)
value1 = param AND 0x0F //0x0F is the 8 bit hex representation of 00001111.
                        //This removes the upper 4 bits from the value:
                        //    10110101
                        //AND 00001111
                        //  = 00000101
                        //That means value1 holds the value of the lowest 4 bits of param.

//Language with non-rotary shift
value2 = RIGHT-SHIFT-4(param) //This does 10110101 -> 00001011.
                              //Value2 now holds the value of the highest 4 bits of param.

//Language with rotary shift
value2 = RIGHT-SHIFT-4(param) //This does 10110101 -> 01011011.
value2 = value2 AND 0x0F      //As per the value1 example
                              //Value 2 now holds the value of the highest 4 bits of param.
edit:
Damnit, beaten by a country mile!

rolleyes fucked around with this message at 20:48 on Feb 21, 2012

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Thermopyle posted:

Strong Sauce and nielsm:

My confusion arose from it seeming "unnatural" to use AND and the like on individual digits of binary numbers. That's probably because I only theoretically understand binary numbers and avoid them like the plague (same with hex). I guess I need to find some exercises or something to help me internalize alternative representations like those.

Your explanations both made a lot of sense and helped ground me a bit more in binary, so thanks!

I was lucky in that my 6th grade teacher use to be CompSci and taught me about how our number system was in base 10 and it blew my little 6th grade mind.

I think this is a good article about understanding binary: http://www.garlikov.com/Soc_Meth.html
and
http://www.exploringbinary.com/how-i-taught-my-mother-binary-numbers/

Lanithro
Aug 31, 2006

Munkeymon posted:

http://www.random.org/analysis/ you can never be sure :)

He could at least generate ~10k numbers and see what the distribution looks like, rather than 5 or 10.

Generating the numbers is not the problem I have. I'm using the Super KISS PRNG by George Marsaglia, and seeding it by reading bits off /dev/urandom. I can generate 100 million numbers without any duplicates, so I don't think I need to worry about the actual random numbers.

Perhaps it's paranoia. Maybe it's just seems off to me that two wildly different numbers end up returning the same roll when you use modulus because they end in "6" when, really, the probability of that happening is actually totally acceptable.

Lanithro fucked around with this message at 01:00 on Feb 22, 2012

JawnV6
Jul 4, 2004

So hot ...

Strong Sauce posted:

is its taking the first 2^16 (0xffff) bits
It's taking the first 16 bits. Not 2^16 or 65,536.

Strong Sauce posted:

0xF (16)
& 00001111 (the number 16)
0xf = 0b1111 = 15

Not 16.

ultrafilter
Aug 23, 2007

It's okay if you have any questions.


Lanithro posted:

Perhaps it's paranoia. Maybe it's just seems off to me that two wildly different numbers end up returning the same roll when you use modulus because they end in "6" when, really, the probability of that happening is actually totally acceptable.

Very likely the latter. True randomness is a very difficult concept for us humans to get our heads around.

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Lanithro posted:

Generating the numbers is not the problem I have. I'm using the Super KISS PRNG by George Marsaglia, and seeing it by reading bits off /dev/urandom. I can generate 100 million numbers without any duplicates, so I don't think I need to worry about the actual random numbers.

Perhaps it's paranoia. Maybe it's just seems off to me that two wildly different numbers end up returning the same roll when you use modulus because they end in "6" when, really, the probability of that happening is actually totally acceptable.

Yeah, it is probably paranoia, and I'm trying to say that you should do 10k 'dice rolls' and see if the distribution of that is skewed because 5-10 isn't enough of a sample to determine whether something is actually wrong. One test method could do that for you and give you more (or even less) confidence in your results.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply