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
supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

Agrikk posted:

...
I'm just going to go ahead and answer your original question so I don't have to read through that. :)

The thing with PHP is that there is no such thing as "an array of fixed size", but let's say you are artificially setting a fixed size to an array - say of size 10. This means your key are 0, 1, 2, ..., 9. You can represent the set of keys with the following array:
$keys = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
Of course, you can generate this array using array_keys or range.

Next you have your list of you want to insert into your array, let's call it $items. As long as you can make the assumption that the size of $items is always equal to or smaller than the array you are inserting into, you can do something like this:
php:
<?
shuffle($keys);
foreach($items as $item)
{
    $array[current($keys)] = $item;
    next($keys);
}
?>
You don't need to worry about collisions since you will only use each index once.

Adbot
ADBOT LOVES YOU

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
I also just noticed this in your code:
code:
do
{
    ...
} while (0);
Really?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

royallthefourth posted:

I'm pretty sure parse_url will do this without any need for regexes. It doesn't actually need to be a URL, it'll take anything formatted key1=value1&key2=value2

I tried but this is regexing the source of a requested URL which contains HTML and Javascript.

Why oh why is it returning it as an integer?

wolf_man
Oct 5, 2005

Nunez?

Agrikk posted:

To pull out the :nerd: hat here, I am writing a script that generates a star system around existing data based on the rules set forth in the MegaTraveller RPG.

I have a database of approximately 50,000 star systems and each system has 1-4 suns, 0-7 gas giants, 0-3 asteroid belts and assorted worlds.

The game's star system generation chapter has a pretty detailed method for generating orbital bodies in a star system and I am automating it using php/mysql.

My current thought is to have an array that represents the orbits of the system and all of the sub orbits (for moons around worlds, binary & trinary systems, etc).

The rules have a complicated method to place suns in a system randomly but with many modifiers, then to place gas giants, then belts, then worlds each with its own set of rules and modifiers. Since an orbit can only contain one object, rerolls are necessary.

Here's the core of what I have so far, but it's broken. It doesn't check if the array is occupied properly, so if the array item is occupied, it gets overwritten buy the incoming record:

code:
Some PHP code..


If I understood what your trying to do correctly, something like this:
php:
<?php
    unset($SystemArray);
    //random number of stars?
    $starcount rand(1,4);
    
    //system is 10 elements each element is a 2 dimentional array
    $SystemArray array_fill(0,10,array_fill(0,1,array_fill(0,1,''))); 

    //get SystemArray keys, could also use range(0,10);
    $keys array_keys($SystemArray);
    //shuffle the keys (randomize)
    shuffle($keys);
    //time to loop through the keys
    foreach($keys as $key){
        //if we've run out of items, break the loop
        if($starcount<=0){
            break;
        //else if this array element is empty, fill it with an item; subtract 1 from the count
        } else if(empty($SystemArray[$key][0][0])){
            $SystemArray[$key][0][0] = 'Star'.(--$starcount);
        }
    }
    
    //Show the array with the random elements
    print_r($SystemArray);
?>

Thats a pretty specific solution, I started by first developing a more general function (but was formatted for single dimensional arrays)

php:
<?PHP
    function randomlyInsert(&$array,$items){
        //Grab the keys from the array
        $keys array_keys($array);
        //randomize the keys
        shuffle($keys);
        //get size of items array
        $x sizeof($items);
        //time to loop through the keys
        foreach($keys as $key){
            //if we've run out of items, break the loop
            if($x<=0) break;
            //else if this array element is empty, fill it with an item; subtract 1 from the count
            else if(empty($array[$key])) $array[$key] = $items[--$x];
        }
    }
    
    randomlyInsert($my_array,$my_items);
?>    

wolf_man fucked around with this message at 04:01 on Jul 22, 2009

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Safety Shaun posted:

I tried but this is regexing the source of a requested URL which contains HTML and Javascript.

Why oh why is it returning it as an integer?

Because the matched part is really returned elsewhere... like so:

php:
<?
$matches=array();
$number_of_matches=preg_match_all($regex,$source,$matches);
var_export($matches);
?>
edit: Changed to preg_match_all. preg_match stops at the first match.

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.

supster posted:

I also just noticed this in your code:
code:
do
{
    ...
} while (0);
Really?

Yeah. The point was to keep rolling and keep trying to find a slot in the array that wasn't filled yet. Once it found an empty slot, it would break out of the loop.

This code snippit was going to be a function that would be called many times for placing stars, gas giants, belts and worlds, and I figured that many rerolls might be necessary in more crowded systems, which is okay with me.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

FeloniousDrunk posted:

Because the matched part is really returned elsewhere... like so:
I've just realised, stupidly, that google is returning to me a latitude_e6, which is an integer version of the floating point number I actually want. Has anybody experienced this before?

Munkeymon
Aug 14, 2003

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



Safety Shaun posted:

I've just realised, stupidly, that google is returning to me a latitude_e6, which is an integer version of the floating point number I actually want. Has anybody experienced this before?

It makes sense because they can hand out data without floating point conversion errors.

royallthefourth posted:

I'm pretty sure parse_url will do this without any need for regexes. It doesn't actually need to be a URL, it'll take anything formatted key1=value1&key2=value2

He'd still have to figure out which part of his data file is a URL. If he was just getting a URL without a bunch of extra crap that sounds like it's subject to change by third parties, I'd comepletely agree.

Cheesemaster200
Feb 11, 2004

Guard of the Citadel
How would I take a timestamp and get the timestamp for five days previous to it?

Essentially I have a timestamp for a meeting date and I want to cut off registration five days before it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Cheesemaster200 posted:

How would I take a timestamp and get the timestamp for five days previous to it?

Essentially I have a timestamp for a meeting date and I want to cut off registration five days before it.

php:
<?
$fivedaysago = strtotime($timestamp)-432000;
?>
(why 432000?)

Sneaking Mission
Nov 11, 2008

Cheesemaster200 posted:

How would I take a timestamp and get the timestamp for five days previous to it?

Essentially I have a timestamp for a meeting date and I want to cut off registration five days before it.

strtotime — Parse about any English textual datetime description into a Unix timestamp

php:
<?
$fivedaysago = strtotime("-5 days", $timestamp);
# or
$fivedaysago = strtotime("5 days ago", $timestamp);
?>

Sneaking Mission fucked around with this message at 18:27 on Jul 23, 2009

Mr Viper
Jun 21, 2005

Derezzed...

Clone5 posted:

strtotime — Parse about any English textual datetime description into a Unix timestamp

php:
<?
$fivedaysago = strtotime("-5 days", $timestamp);
# or
$fivedaysago = strtotime("5 days ago", $timestamp);
?>

:bang: This is one of the most useful functions I've ever seen. How have I not known this before?

I love this thread.

cLin
Apr 21, 2003
lat3nt.net
I'm not sure if this belongs here but does anyone have any recommended reading on APIs? It seems like it's common knowledge yet I have no idea on how to use them (for example, something like logging in thru digg using their API).

I'm pretty familiar with PHP but everytime I read something on how to use X API, it goes over my head.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

cLin posted:

I'm not sure if this belongs here but does anyone have any recommended reading on APIs? It seems like it's common knowledge yet I have no idea on how to use them (for example, something like logging in thru digg using their API).

I'm pretty familiar with PHP but everytime I read something on how to use X API, it goes over my head.

API translates to "the way to interface with our poo poo."

Most websites (Digg) have a web services API. You make requests to their site using certain URLs and certain query string or POST parameters, and you get data back, usually in JSON, sometimes in XML, or whatever they want.

There are a handful of web service API types. The most modern and trendy is "REST", which is another way of saying "use the HTTP verbs (GET, POST, PUT, DELETE, etc) to access resources." For example, sending "DELETE /post/1234" would delete that object. Often, REST-ful web services return data in JSON.

There are other, older ways to do web services. SOAP is one of the more convoluted and evil ways. It's a pain in the rear end wrapped in XML, and should be avoided if you don't want to lose your mind.

Sometimes the API is only exposed through code. They'll give you a set of files that usually contain a class or fifteen, and then the documentation on using the classes to do their thing. You'll usually find these monstrosities are in Java, and even though they use SOAP or something similar, they'll force you to use their code instead of giving you the API documentation because they are fucktarded. This unfortunate method has also been seen in .Net land, and is often used by "Enterprise" systems, because they take themselves too seriously and don't know how to version a web service / their toolset prevents them from implementing a versionable web service.

Does this help in the least?

McGlockenshire fucked around with this message at 04:12 on Jul 26, 2009

cLin
Apr 21, 2003
lat3nt.net
gently caress yes it helps. Thanks. With letting any user access their data, aren't they prone to attacks/malicious doings?

Standish
May 21, 2001

cLin posted:

gently caress yes it helps. Thanks. With letting any user access their data, aren't they prone to attacks/malicious doings?
No, typically you only get access to the same operations that are accessible via a HTTP/web browser interface and using the same authentication/access control, just with a more programmer-friendly interface on it.

insidius
Jul 21, 2009

What a guy!
I am fairly new to this and I aint that great so please excuse my rampant stupidity.

I have a PHP page that calls data from mysql and I want to color entries red that are over a certain age. IE greater then two weeks it should be red, if not then it should be white. I think I have it REALLY wrong. Ive only been doing it for a few days and I am wondering how I would structure it.

I have the following so far:

code:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

                        // color

                        // echo $row['lodged_date'] + 1209600;

                        if(($row['lodged_date'] + 1209600) > time()) {
                                $colour = "#FF0000";
                        } else {
                        $colour = "#FFFFFF";
                        }
I would really appreciate any tips that could be offered.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

insidius posted:

I have the following so far:
Assuming that you want older rows red and newer white, your code had the comparison wrong. Other than that, it should work perfectly well. Any other changes would be stylistic:
code:
$time_span = 60 * 60 * 24 * 14;
$now = time();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $colour = "#FFFFFF";
    if(($row['lodged_date'] + $time_span) < $now)
        $colour = "#FF0000";
    // ...
- The color will always be white unless changed. No need for the else.
- No need to re-evaluate time() every row, even though that's a pretty simple operation.
- The number 1209600 has no immediate meaning. Splitting it out into the seconds -> minutes -> hours -> days math makes it pretty obvious to figure out what the span is (14 days)
- Color either does or does not have a U. Comment consistency with variables would be nice, but I'm really just being a nitpicker.

insidius
Jul 21, 2009

What a guy!

McGlockenshire posted:

- Color either does or does not have a U. Comment consistency with variables would be nice, but I'm really just being a nitpicker.

Thank you very much. As I said I am rather new to this and it had me wracking my brains trying to figure out what I had done wrong.

I spend most of my time currently looking for missing brackets and commas eh.

duck monster
Dec 15, 2004

Clone5 posted:

strtotime — Parse about any English textual datetime description into a Unix timestamp

php:
<?
$fivedaysago = strtotime("-5 days", $timestamp);
# or
$fivedaysago = strtotime("5 days ago", $timestamp);
?>

Quick heads up. Never ever ever use strtotime to just blindly parse user input. Things will go horrifyingly wrong and probably at the level of your database and thats bad.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Most interestingly and/or horrifyingly, it's possible to get zero, null, and -1 error states depending on how bad the input is.

beeps-a-palooza
Jan 2, 2009

by T. Finn
I'm frustrated man.

Alright, so I'm the owner of a site called Happyfood, and have decided to update it from it's archaic pure html structure. I decided to use PixelPost (http://pixelpost.org).

They have a shitload of templates, and I've been really busy completely customizing AliPixel (http://www.pixelpost.org/extend/templates/alipixel/).

Here's my site for reference: http://wherefoodishappy.com/index.php

There are two things that I need help with. First off, I have written several comments, and they down show on the drop down menu. They DO show on the site (like where it says "Comments: 2). AliPixel's comments and javascript is based of http://treeswing.net/, as well as http://theworldin35mm.org/ if that helps at all.

The second problem I have is that I'm trying to center that header on the top, while keeping all of the buttons under it like that. If needed I can send you the .html file, or if really necessary, the entire customized theme as a .zip.

Please help me out!

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Is it possible to have an object constructor return a string, instead of an object? For example, I want to do...

php:
<?
$password = new PasswordGenerator;

//instead of

$object = new PasswordGenerator;
$password = $object->GeneratePassword();

//or

$password = PasswordGenerator::GeneratePassword
?>
I mean, I guess I could do the third; I'm just curious if the first is possible.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Golbez posted:

Is it possible to have an object constructor return a string, instead of an object? For example, I want to do...

php:
<?
$password = new PasswordGenerator;

//instead of

$object = new PasswordGenerator;
$password = $object->GeneratePassword();

//or

$password = PasswordGenerator::GeneratePassword
?>
I mean, I guess I could do the third; I'm just curious if the first is possible.

Why would you want an object constructor to return a string? Why wouldn't you just use a function?

Munkeymon
Aug 14, 2003

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



If you're going to use it like a regular function, why make it an object in the first place?

e: f b

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Munkeymon posted:

If you're going to use it like a regular function, why make it an object in the first place?

e: f b

A combination of curiosity, and an "oh, wait, I could use a function" halfway through asking it, and deciding to ask anyway.

(As for why use an object: It has several dependent functions and it just seemed easier to make it a class)

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
A couple of best practices questions:

1) I have some functions (like "get a list of countries from the database") that are used on multiple parts of the site. Rather than split them out into a file and include that file, I've put them into a class which, combined with an autoload in my standard header include, means I don't have to worry about including anything. I just do InternalFunctions::getCountries() and it's done, since it's in InternalFunctions.php. Is this a good thing, or should these things not be in a class?

1a) I've also started including some HTML blocks in that thing, rather than use include files. i.e. InternalFunctions::displayTableStart to echo (without any PHP variable processing or anything) the particular start code for a table start that uses our classes and javascript. Should that simply be replaced with an include, and keep the table code all alone in an include file?

2) I've read that objects shouldn't try to do too much, that they should only really do one thing each. ("one reason to change", I've seen it put) But where is the line? I have a user data object that handles reading and writing to the database (via a mysqli object), sanitizing of the object data, generation of internal ID, etc. I can't really imagine how I'd split some of these things out.

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD
If you want you can use __toString to do this:

php:
<?
class Password
{
  public function __toString()
  {
    return "54321";
  }
}

$pwd = new Password;

echo $pwd
?>

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Bhaal posted:

If you want you can use __toString to do this:

php:
<?
class Password
{
  public function __toString()
  {
    return "54321";
  }
}

$pwd = new Password;

echo $pwd
?>

toString is only called when echoing or casting as (string) or explicitly, right? So if I really wanted to do it direct, I'd have to do, like... would this work?

php:
<?
$Password = (string) new PasswordGenerator;
?>

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD
That would work but I'd highly question the need of creating an object if all you really want is a string (unless you're leaving out the other stuff done with a PasswordGenerator for clarity).

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Bhaal posted:

That would work but I'd highly question the need of creating an object if all you really want is a string (unless you're leaving out the other stuff done with a PasswordGenerator for clarity).

I know it sounds weird, I figured I'd just feel out the limits of the language. :)

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
So this is what happens after my projects are feature complete but before they get tested, I go hog wild on experimenting with code and new features. My current expedition into the code mines: Singletons. Specifically, a mysqli singleton. Is this a good idea, and is it worth it?

Right now, I have subclasses for all of the different databases we connect to, all of which are children of a central child class of mysqli. So I can just pass "new DatabaseConnection" to functions and it works. Using a singleton sadly adds another line (since you can't pass "DatabaseConnection::getInstance()" to a function expecting an object of DatabaseConnection) but it might be useful if it actually helps.

I've been googling around and find many mixed opinions on singletons, but generally that they can be useful for database connections. However, we don't have *heavy* database work; maybe on the scale of dozens of queries a minute, rather than hundreds a second. So far as I can tell, we haven't had any performance issues so far, but then again, the production site is still using mostly code based on mysql, not mysqli, so I don't know if my conversion work will cause problems.

Edit: Factory pattern. That's what I need. Not a singleton. Factory is working quite fine.

Golbez fucked around with this message at 16:38 on Aug 4, 2009

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Right now I've got a try-catch in every function I have. Should I keep doing this or just have my functions throw exceptions and catch them all in the script that's calling them?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Hm. No replies in almost 3 days. I've gotten rid of most of the try catch statements in my functions and now have them throwing exceptions if it doesn't meet a requirement. Not sure if that's how I should be handling errors though.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

drcru posted:

Hm. No replies in almost 3 days. I've gotten rid of most of the try catch statements in my functions and now have them throwing exceptions if it doesn't meet a requirement. Not sure if that's how I should be handling errors though.

Is it an exception you want to show the user? Or do you want them to see a generic "there is a problem with this page" type of thing?

I use set_exception_handler and don't have a single try/catch in my whole app. The exception handler function logs the exception so I can take a look at it later (as well as information used to help recreate it). Using the get_class function I look at the type of exception to determine what I display to the user. If it's a PublicException, I dislay the error message to the user. If it's anything else (PDOException, etc) I just display a generic error message or error page, depending on if it was a GET or POST that caused the exception.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

fletcher posted:

Is it an exception you want to show the user? Or do you want them to see a generic "there is a problem with this page" type of thing?

I use set_exception_handler and don't have a single try/catch in my whole app. The exception handler function logs the exception so I can take a look at it later (as well as information used to help recreate it). Using the get_class function I look at the type of exception to determine what I display to the user. If it's a PublicException, I dislay the error message to the user. If it's anything else (PDOException, etc) I just display a generic error message or error page, depending on if it was a GET or POST that caused the exception.

Thanks, I was looking into set_exception_handler but didn't know how to use it properly :smith:.

Can you use an object in there?

Like set_exception_handler($e->handler)

It doesn't look like you can and I'd like to try and keep the logging, etc in a separate file.

ninja edit

Acer Pilot fucked around with this message at 23:04 on Aug 4, 2009

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

drcru posted:

Thanks, I was looking into set_exception_handler but didn't know how to use it properly :smith:.

Can you use an object in there?

Like set_exception_handler($e->handler)

It doesn't look like you can and I'd like to try and keep the logging, etc in a separate file.

ninja edit

I'm not quite sure why you would want to do something like that. I have a config.php that is included in my controller, where all requests are routed through, so I don't need to have any includes in any other php file in my app. In this config.php, aside from having a few PHP config variables set and some defines() for my app to use, I declare my __autoload() function and specify and declare my exception handler.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Ah, thanks. I've never really looked into autoload. Got some reading to do!

Nurbs
Aug 31, 2001

Three fries short of a happy meal...Whacko!
I'm having a friendly arguement with a co-worker but neither of us can find compelling evidence.

He says PHP was capable of prepared statements as early as PHP 4, while I say it was PHP 5. We're both shooting at MySQL here because PHP 4 automatically compiled with it, but he found something that looks like there was a DB2 library IBM put out.

Can anyone settle this for us?

Adbot
ADBOT LOVES YOU

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
http://us3.php.net/manual/en/function.db2-prepare.php

PHP 5 came out on 2004-07-13, ibm-db2's first beta release was 2005-05-06. However, ibm-db2 works with PHP 4 (and 3, for that matter). Whether or not this counts is fairly irrelevant though, as ODBC is not an extension and has supported prepared statements since PHP 4. Ibase, ifx, dbplus, and ovrimos also all had prepared statements in PHP 4.

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