ryantroop 177 Practically a Master Poster

I cant suggest O'Reilly's python course enough. It is broken down into 4 courses, and you have a mentor who is very professional and knowledgable the whole way. It is self paced, and the projects are relevant and usable after you are done with the class (and, as a perk, they teach some great concepts in programming).

The only difference between what has been posted and this one is that there is a cost to it, but if you finish the program you get a certificate of completion from University of Illinois, and each class counts as continuuing education, if that is necessary for your career/current job.

http://www.oreillyschool.com/

Personally, I learned a lot from them in a very short time.

ryantroop 177 Practically a Master Poster

:( You just take all the fun out of trying things on your own...

Thank you, though. It will certainly help figure out what's going on.

ryantroop 177 Practically a Master Poster

Works well. Thanks!

ryantroop 177 Practically a Master Poster

I did come across these.. I didnt know if they were widely accepted or worth the attempt.. I will give them a shot. Thanks! :)

ryantroop 177 Practically a Master Poster

I have taken up the Python Challenge and I am stuck on challenge 6, which requires PIL - and sadly I am using 3.2 and there is no PIL support.

Yes, alternatively I could simply download 2.7. However, I know there are some differences between 2.x and 3.x and I am more comfortable with 3.x and would like to go that route first if I have the choice.

Thanks!

Ryan

ryantroop 177 Practically a Master Poster

Which module would I look into to capture things like disc read/write speed, as well as possibly capture what the disk is reading/writing at the time.

I would like to make a diagnostic module to check if my disc speed is taking a hit, as I rebuilt a PC and after build/OS install it is running rather sluggish. I figured it would be a fun project to practice writing "usable" and sharable code.

Thanks!

ryantroop 177 Practically a Master Poster

There is this example on Daniweb:
http://www.daniweb.com/software-development/python/threads/22312/get-posted-form-data-in-python

Hope I don't get in trouble for sharing a stackoverflow link:

http://stackoverflow.com/a/11353284/1481486

There are some other fine examples of how to use python on the web there, as well.

All depends on how you plan on using the data, and how you want to retrieve it.

ryantroop 177 Practically a Master Poster

I love eclipse with the PHP extension. If you are looking for a testing platform, you will not find many good ones (and quite frankly, you are more than likely using the language wrong).

Best platform to test - get a cheap/free web host, turn on error reporting, use eclipse or netbeans, upload and test. Wash, rinse, repeat.

ryantroop 177 Practically a Master Poster

I think what youre asking is for this:

This is assuming your text document is split by "." as you have above, so...
Joe Cren(.)Ryan Troop(.)Eddie Vedder(.)Led Zepplin(.) //or something similar

if you do:

$array = explode("(.)", fread($fp, filesize($filename)));
//this array is populated ['Joe Cren', 'Ryan Troop', 'Eddie Vedder', 'Led Zepplin']

To use those, I can do:

foreach($array as $key=>$value)
{
//do something with a name, one at a time
echo "Name ".$key.": ".$value."<br>";
}

The above will output:
Name 0: Joe Cren
Name 1: Ryan Troop
Name 2: Eddie Vedder
Name 3: Led Zepplin

Alternatively, you can access the items directly using:
echo $array[0]; //will output: Joe Cren

and we can make a for loop as you have done:

for($i=0; $i<count($array);$i++)
{

echo "Name ".($i+1).": ".$array[$i]."<br>";

}

The above will output:
Name 1: Joe Cren
Name 2: Ryan Troop
Name 3: Eddie Vedder
Name 4: Led Zepplin

Hope that clarifies for you.

Ryan

EDIT: I posted at the same time as the above. The above method is much more elegant and easier to read.

ryantroop 177 Practically a Master Poster

^clever catch

ryantroop 177 Practically a Master Poster

I didnt add any redirects. You need to change the comments out.

//login stuff needs to be actual php commands..

redirect?
header("Location: mypagetogo.php");
exit();

error message?
echo "You failed to log in!!";

I left that part up to you.

You will also need to change the names in the SQL query, as well, to match your table.

ryantroop 177 Practically a Master Poster

so by your calling me a "dumb monkey" you went from having someone willing to help, to another person who will just ignore you.

You are what makes the internet rot. I for one will be happy to see you fail.

happygeek commented: well said +11
ryantroop 177 Practically a Master Poster

Also, if you are going to use a salt, it needs to be unique for each password - it defeats the purpose of a salt if they are all the same, as a rainbow table can be made by injecting the salt.

You can even be so bold as to store the salt in the database along with the username, because it would take a rediculously long time to crack a single password with the salt, and then have to do it all over for the next one.

If you want to go even further, you can use salt and pepper, and pepper can be a global variable that is stored in a protected area that no one will never see unless they gain access to your FTP/root, in which case you have bigger problems than your database being cracked.

ryantroop 177 Practically a Master Poster

blue, since you are messing around with all your different encryptions types you may have mixed yourself up.

Whatever you encrypt the password with during creation, you must use to check against the password in login.

So, if your "signup" page uses MD5, then your login script must also use MD5.

You may also have encryption turned on in your database, in which case you would be encrypting and encrypted string - but PHP would have no idea that it has been re-encrypted. So make sure that your table column is not, for any reason, encrypted during an insert. If it is, you need to decrypt it during a select (assuming you have the right key).

If you created your own tables, you would know if encryption is turned on for the insert/update.

In general, the creation process would be something like this at creation (I am not sanitizing anything for the sake of simplicty):

<?php

if($_POST) {
$usr = $_POST['usrnm'];
$pass = hash('md5', $_POST['pswrd']);

$query = "INSERT INTO login (username, password) VALUES ('$usr', '$pass');";

$result = mysql_query($query);

if(mysql_affected_rows($result) == 1){
echo "Insert Complete!";
session_start();
$_SESSION['username'] = $usr;
//redirect or whatever...
}else {
echo "Insert failed!";
//redirect or whatever...
}
}

?>

Then our retrieval at login:

<?php

if($_POST){
$usr = $_POST['usrnm'];
$pass = hash('md5', $_POST['pswrd']);

$query = "SELECT username u, password p FROM login WHERE username='$usr' AND password='$pass';";

$result = mysql_query($query);

if(mysql_num_rows($result)==1) {
//login stuff
}else{
//login failure
}
}

?>

Hope that helps,

Ryan

ryantroop 177 Practically a Master Poster

Im not sure why you want to redirect away from your site 80% of the time, as that would pretty much ensure 80% of the people would not want to visit your site because it's useless.

However, if you wish to pursue this you have 2 options.

1 - pure PHP (with a database of links), and, just as you said, do random(100) and if it's > 80, then echo "href='mylink'" as drawn from database A, and if < 80, then href='fakelink' as drawn from database B.

2 - Use javascript and at runtime, change it in the same fashion as above.

While I am trying to keep a personal tone out of this, I need to say that pushing 80% of your traffic away is stupid and counter productive... but I'm sure you have your reasons (of which, I have no desire to learn).

EDIT: I did not go to the site you linked. Im assuming if you want people to "believe" they are going to one link, but are redirected to another, you need to use javascript and onclick()

ryantroop 177 Practically a Master Poster

Just saying, if the purpose of those are to, say, increase the value of posts and help get a general style of response, wouldnt it be helpful if there is a way to see (even if simply general i.e., "off topic", "unclear answer", "abusive", ....) it would help new people to understand why the community at large does not like the post, and help prevent posts that are not contributory.

I was hoping by leading you to the "You can't" conclusion I would bring back my initial request, can we get a checkbox or comment box (maybe it should be mandatory to down vote?), so we can see why we are down voted instead of useless responses?

ryantroop 177 Practically a Master Poster

I think youre missing the point...

Maybe Ill ask, instead...

How can I find why someone down voted me?

ryantroop 177 Practically a Master Poster

Up/Down arrows dont exist for your own post :(

ryantroop 177 Practically a Master Poster

Can we possibly get a checkbox, or an optional write in so we can know why our posts are voted down?

Some of them seem so random, it would just be nice to know why they are voted down. I like coming here to try and help, and it's not helping if I don't know how I'm not helping...

So.. thanks! :)

ryantroop 177 Practically a Master Poster

Thanks muchly!

ryantroop 177 Practically a Master Poster

I did find smartystreets... I have not used it, but I did sign up. Under 250 queries/mo. free. Seems like a good deal for a start-up, and the API looks simple using REST or JSON

You have any experience with them, or anything similar?

ryantroop 177 Practically a Master Poster

So this was a fun exercise for me...

I think this should get you at least started...

import sys
import re
import os

try:
    #open our document and read it as a string
    doc = open(os.path.abspath(sys.argv[1]), 'r').read()
    #declare and compile our pattern as raw string
    regex = r'<!--content-->'
    reg = re.compile(regex)
    #split the content between our pattern points
    match = re.split(regex, doc)
    try:
        #if we get a matching sequence, print everything within the sequence
        #be wary of a TON of newline carriage returns
        print("Matches: ", match[1:])
    except Exception as e:
        #if there is an error, display it.
        print ("No match found: ", e)
except:
    #if we can't open it, display the path to our document and see if it's
    #even there.
    try:
        path = os.path.abspath(sys.argv[1])
    except:
        #if no document...
        path = 'No file given'
    #print the result
    print("There was an error opening your file.... File given: " + path)

the document i tested this on was a simple text document with the following inside:

asfasfasfafafsfs

<!--content-->

aisbfaibfa;ifbaifafnsabfasifnajfnafanfas )) AFAFA)A)__ )A )__)_0
9as09fansfoaf a00-0--

<html> bajsfnasfA </html>

afnifnafmaf

<!--content-->

a
sf
asf
af
asf
a
sfafafsaf

There is probably a cleaner way to do this, but this was my solution... if you plan on inserting, I think you want re.sub instead of re.search. re.match will fail every time, as it looks to the beginning of the string.

Hope that helps!

Ryan

ryantroop 177 Practically a Master Poster

sorry, let me be more clear...

$sql= "SELECT * FROM employee WHERE uname='$user' and pswrd='$encryptpass'";

$rs = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($rs) === 1) //if === does not work, try ==
 {
  $row = mysql_fetch_array ($rs);
  echo "name: " . $row['fname'] . " " . $row['lname'];
 }
else
 {
 ....
ryantroop 177 Practically a Master Poster

using select you are not affecting any rows.

You should use mysql_num_rows() on line 22 instead, and you want it == 1 (because each username should only have 1 assciated password, and if you are getting more than 1 you're in trouble.

Also, sanitize your variables (learn about mysql_real_escape_string())

ryantroop 177 Practically a Master Poster

Anyone know any good online.. I guess.. challenges or tutorials that will teach the fundamentals of the automated QA process using Python?

Is it simply TDD? Or is there more to it? If it is TDD, can anyone suggest where to practice this more, other than "come up with a problem and write a test for it."

Thanks!

Ryan

ryantroop 177 Practically a Master Poster

Are there any open source/free to use, commonly updated... either dumps or APIs that will let someone have zip codes and addresses validated?

Think monster.com or careerbuilder.com's location search, or something similar.

Thanks

Ryan

ryantroop 177 Practically a Master Poster

I would think that the google suggestion for search is based off a custom dictionary, and if an item is not in the dictionary it offers the closest match as a suggestion. What the closest match is will depend on your algorithm. Also, google has been mining search queries, and has methods for collecting all their search queries, for such a long time, their data sets must be massive. One way to do things is to do a daily/weekly or whatever automated query of columns that will check columns for their values and make dictionaries based on what is availabe in your database. So if people use NY or N.Y. or New York in the actual database, your script will automatically add those to a dictionary, and offer those as suggestions.

Of course, as your data becomes large enough, you may actually be able to make a whole new table based on either alphabet (starts with a, then all items with a!), and if it gets really really large (like google), I assume they have multiple tables designed around multiple paths and queries tables based on spelling.. (starts with n, then ne, then new... etc... a space will break a word, and a new word is searched.. each group of letters will have a table dedicated to them).

This may be overkill, or entirely wrong... but it's how I would solve it.

Im guessing that google actually uses the meta data from their spiders to fill their data tables, and …

ryantroop 177 Practically a Master Poster

Out of curiosity, is this the way that virus scanners work? Or is it a bit more complicated than that?

ryantroop 177 Practically a Master Poster

Interesting! I never thought of using regex for this... would make total sense, I guess... I shall refactor and see how I do.. thanks for the tip! :)

ryantroop 177 Practically a Master Poster

Let me rephrase - while line: is meant to check if there is something there for the cursor to use.

So the idea is simple - you are given a file that has some form of repetition (or a string, or whatever), but you do not know what that repetition is. The goal is to find that repition, or any repeated patterns, for whatever reason - trying to cipher an encryption by finding repeatable patterns for small words, looking for textual clues in an essay... whatever the reason, the exercise is simply to find patterns as they emerge, useful or not. It is up to the user to determine the usefulness of the information.

Ironically enough, I was just reading about how zip compression does this, but Im not sure how...

ryantroop 177 Practically a Master Poster

hmmm.. ok.. clarification on lowercase-word-generator

First, if the reference is to strip(string.punctuation+....) I intentionally made the ignore list so it can be edited and we can allow certain characters. What if we want to find a pattern of "#word#" for whatever reason, or something similar? But I doubt that's what we were going for, so on to the next part....

you use:

while line:

From my understanding, this will run until the end of the line (being, it would go through word by word until the end of the 'list').

In my case, are you suggesting I use a similar technique, and then split the word forwards and backwards with each pass? (much like you do for If so, wont that duplicate results? How would I compensate for that?

I looked through a few other snippets (the cracking caesar one was quite interesting), and I understand the concept behind the recursive matching, but the purpose of this project is to find random matches, that are not in any way pre-defined.

So.. with that in mind, is this a bit of a goofy exercise, or is this something that will be useful outside of a "can I do it?" context? I will still pursue it just for kicks, but getting a more experienced opinion would be nice.

Thanks!

Ryan

ryantroop 177 Practically a Master Poster

So, in an exercise in futility, I decided to write a script that will take either a file or a string and find patterns in the words, and display the results for a nice friendly human use.

Right now, it simply searches forwards and backwards(ish), but Im wondering if there is a cleaner way to iterate the middle part of the words without manually slicing them.

Any help is much appreciated:

import sys

try:
    document = open(sys.argv[1], 'r')
except:
    selection = input('Would you like to: \n1)Input a file name relative to path.\n2)Input a string\nSelection: ')

if selection == str(1):
    doc = input('File: ')
    try:
        document = open(doc, 'r')
    except Exception as e:
        print (e + "File Not Found...")
elif selection == str(2):
    document = input("String: ")
else:
    print("There are only 2 choices here...")
    sys.exit()

#define characters to ignore
extra_chars = "!@#$%^&*()-_=+?><,.;:'\"[]{}|\/"

patterns = dict()

try:
    words = document.read().split()
except:
    words = document.split()

for word in words:
    for char in extra_chars:
        word = word.replace(char, "")

    for i in range(len(word)+1):
        if i == 0:
            pass
        else:
            p = word[0:i]
            if p not in patterns:
                patterns[p] = 1
            else:
                patterns[p] += 1

    for i in range(len(word)+1):
        if i==0:
            pass
        else:
            p = word[-i:]
            if p not in patterns:
                patterns[p] = 1
            else:
                patterns[p] += 1


for k, v in sorted(patterns.items()):
    print(k +": "+str(v))

sys.exit()
ryantroop 177 Practically a Master Poster

heh, sorry I wasnt more clear.

by doing:

names = ['first_name', 'last_name']

You are making names be a list with 2 strings, "first_name" and "last_name".

In your particular case, you can either populate the list by manually:

staff_first = raw_input("First Name: ")
staff_last = raw_input("Last Name: ")

names = [staff_first, staff_last]

or, you can simply use the object staff_first and staff_last, which I will show you at the end.

Now, on to your problem - you forgot to close the whole query with a closing parentheses.

cursor.execute("""INSERT INTO staff (FIRST_NAME, LAST_NAME) VALUES (r{0}, r{1})""".format(*names))

Notice the 2 extra parentheses added after r{1} and (*names)

If you don't want to use the unpacking method, you can simply call the items by name -

 cursor.execute("""INSERT INTO staff (FIRST_NAME, LAST_NAME) VALUES (r{0}, r{1})""".format(staff_first, staff_last))

Hope that helps.

Ryan

ryantroop 177 Practically a Master Poster

my mistake, I forgot $ this time...

echo "$Username_exists"; exit();

Your answer should be a 1 or a 0

ryantroop 177 Practically a Master Poster

on line 18 you took out the single quotes, yes?

ryantroop 177 Practically a Master Poster

line 19, write:

echo "Username_exists"; exit();

What number is there?

ryantroop 177 Practically a Master Poster

youre sure that the user and the hashed password exist in the database?

ryantroop 177 Practically a Master Poster

destroying a session:

$_SESSION['PHPSESSID'] = '';
session_destroy();

as for your problem, on line 16 add:

or die(mysql_error()); and see if your sql is failing.

EDIT: changed cookie name. Spelling error :(

ryantroop 177 Practically a Master Poster

get rid of the ' ' around $checkUsername

There should only be 1 result if the user/pass combo exists. No one will have the same username, right? So change line 20 to:

if($Username_exists == 1) {
 header("Location: indexma.php");
 exit();//all header redirects need to kill the script or it will continue to run even after a redirect
}
else {
 //echo will not ever be seen, and it should in fact raise an error if something is output before a header change
 header("Location: register.php");
 exit();//same dealy here
}

EDIT: The above is very possible, as well. But I would encourage my changes as well.

ryantroop 177 Practically a Master Poster

If you're going to be salting the password, salt it using a stored global in .htaccess
http://www.besthostratings.com/articles/php-variables-htaccess.html

Or from an include that is stored above http access.

This makes a private salt that can only be accesed with root FTP access.

On top of that, your added "pepper" should be unique for each user, and stored in the database with the login info.

md5 is "useless", sha1 is better, sha256 is there, you might as well use it. (heck, there is even better....)

The real way to totally hash out a password is to do it multiple times, using the new hash created + salt + pepper each time... so, lets say I make my private "salt" as a gloabl var $_SALT

function enc($usr, $pw) {   //take in username and password
 $pass = hash("sha256", $pw.$_SALT);    //make initial hash, using our "secret" salt
 $pepper = hash("sha1", $usr);  //make a "pepper" based on the username (or email)
 for(i=0;i=10;i++){
  $pass = hash("sha256", $pass.$_SALT.$pepper); //10 times, we will hash the string with our current pass value, salt, and pepper.
 }

 return $pass.' '.$pepper;  //our function will return a 64 character hashed password, a blank space, and a 40 character hashed public "pepper"
}

From there, we can explode our two values:

$password_object = enc($username, $password);
list($pw_to_store, $pepper_to_store) = explode(" ", $password_object);

You will now have $pw_to_store containing our 64 character hashed password, $pepper_to_store containing our 40 character hashed "pepper", and our salt remains a "secret" only to us.

It …

broj1 commented: Nice post, I hope it will fire more discussion +4
ryantroop 177 Practically a Master Poster

Another vote for PEAR. Simple and straight forward.

ryantroop 177 Practically a Master Poster

because of this very awkward (to me) behavior, I much prefer .format()

you could easily have done:

cursor.execute("""INSERT INTO staff (FIRST_NAME, LAST_NAME) VALUES (r{}, r{})""".format(first_name, second_name)

You can even format by place holder, if you have a list, tuple, or parsed dictionary:

names = ['firstname', 'lastname']

cursor.execute("""INSERT INTO staff (FIRST_NAME, LAST_NAME) VALUES (r{0}, r{1}""".format(*names)

the r should keep quotation marks in place when doing sql inserts. (it makes it a "raw" string)

ryantroop 177 Practically a Master Poster

I would recommend you turn off all your error suppressions (@) and see if you raise any errors...

Line 1 is missing a closing ;

While I can't say it's improper, I have never seen a while loop in PHP using

while($mycontingency):
...
endwhile;

I would encourage you to use

while($mycontingency) {
...
}

EDIT: I just looked on the PHP Manual and while($foo): is totally acceptable, just not very PHP-ish as few statements follow this design. You can happily ignore the above.

line 21 you are basically saying suppress all errors but if there is an error print the error but supress the error. Not sure you are using error suppression correctly...

As to your problem...

I have had problems where queries do not run properly if they are not closed with a semi-colon.

So, try changing it to
mysql_query("DELETE FROM training_tickets WHERE transaction='$transaction' LIMIT 1;") or die ("Could not delete: ".mysql_error());

Lastly, for the sake of "true" RBDM, you should never delete any items from your database. Instead, you should add another column called "deleted" and make it a datetime, and when you run your selects you should check that datetime <= 0, and when you want to delete the item you should set datetime to "now()"

ryantroop 177 Practically a Master Poster

never trust your users. End of story. At the very minimum,

$keyword = mysql_real_escape_string($keyword);

should be used.

With the limited code you have given, it's difficult to say.

Without knowing how $siteurl is populated, or how $url3 is populated, it's difficult to see where you are failing.

ryantroop 177 Practically a Master Poster

There is not reason you cant hold the info in a database and pass a simple check to enter the page you want.

You can simply pass the username as a GET variable in the header change.

header("Location: http://www.foo.com/?user=myvar&pw=password");
exit();

Then your login page, you can check the GET for the login parameters against the database.

I would encourage you to encrypt the username and password if you use this method, or even making some sort of tokenID attached to the protected pages and query the DB for the token ID.

Hard coding your passwords in your PHP pages is poor practice.. but if it's for something simple and doesnt require security then it will do as a temporary fix.

ryantroop 177 Practically a Master Poster

looks like a spelling/case error with your DB columns. As above, make sure that 'ID' is the actual name of the column, and not something like 'userID' or something similar.

You don't need to stripslashes if you're using real_escape_string().

Don't give idiots who try to hack your page more room to get a right answer. Treat slashes as an invalid character.

If you really want to add an extra layer of security, you should look into preg_match().

ryantroop 177 Practically a Master Poster

Erm.. all isntances of mysql_numrows should be mysql_num_rows() <-notice the extra underscore

Line 50, 85, 113, 126, 164.... that should get you started... I saw a few more below it, as well.. 184, 197... there's more.

ryantroop 177 Practically a Master Poster

:(
I got schooled... Oh well, at least I learned something.

However, wouldnt my method work?

Declaring the variable outside the class, it would store adds or subtracts every time an object was created or deleted?

ryantroop 177 Practically a Master Poster

The only problem with using /temp is it potentially opens it up to public/shared access. So if you can use a non-root folder (the folder above your HTML folder) it would be preferred.

If security is not a major issue, then don't worry about it.

ryantroop 177 Practically a Master Poster

So first, Robot is not a defined variable anywhere, so Robot.population means nothing.

Second, the way you are using population wont work. Every time you make a new robot, the population will reset to 0, and only that robot will have a population of 0.

You will need to rethink how your class is going to work, and if you want to keep track of how many instances exist of the robot class, you will either need a global variable (or at least a variable outside of the class itself), or the instantiation of the class will add to a variable in the module.