...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 5, 2013

Completing a class definition

Question by user2086204

Suppose that you are given the following PetDriver class, which includes a main method:

public class PetDriver{
  public static void main(String[] args){
    int weight = 40;
    Pet doggie = new Pet("Rover", weight);
    System.out.println("my pet's name is " + doggie.getName());
    System.out.println("my pet's weight is " + doggie.getWeight());
  }
}

Executing main produces the following output:

my pet’s name is Rover
my pet’s weight is 40

My code is as follows but It is returning null.

public class pet {

    public String name;
    public int weight = 40;

    public Pet (String y, int x){
        y = name;
        x = weight;
    }

    public String getName(){
        return name;
    }

    public int getWeight(){
        return weight;
    }
}

Thanks!

Answer by Starx

Your constructor does not assign the value to the properties. Change them to the following.

public Pet (String y, int x){
  name = y;
  weight = x;
}
Read more

PHP – get a KEY of a nested array

Question by Obmerk Kronen

I have an array called $plugins that looks something like this :

Array
(
    [path/to/file.php] => Array
        (
            [Name] => somevalue_a
            [TextDomain] => somevalue_b
            [value_c] => somevalue_c
            [value_d] => somevalue_d
            ...
            ...
            ..

        )
    [path/to/file2.php] => Array
        (
            [Name] => somevalue_a
            [TextDomain] => somevalue_b
            [value_c] => somevalue_c
            [value_d] => somevalue_d
            ...
            ...
            ..
        )
)

Now, I am having trouble to get the KEY name (which is path)of each array element ..

function get_plugin_data(){

    foreach ($plugins as $plugin => $data) {
    $plugin_data = $plugins[$plugin];

    // Start simple DEBUG
    echo '</br>===============================</br>' ;
    echo '</br><b>Plugin Name : </b>'. $data[Name]; .'</br>' ;
    echo '</br><b>Plugin Path : </b>'. key($plugins)   .'</br>' ; // <-- Problem here
    echo '</br>TextDomain set  : '. $data[TextDomain] .'</br>' ;
    echo '</br>===============================</br>' ;
    // End DEBUG
    }
}

When using key($plugins) it gives me always the same value (first one).
When using key($data) it is giving me the FIRST LETTER only.. (??)

How can I get the this key of each nested array ?

Answer by kennypu

just return $plugin, not key($plugin). $plugin should already be the key.

to elaborate, when you use the syntax:

foreach ($plugins as $plugin => $data)

it is setting $plugin to the key, and $data to it’s value.

Answer by Starx

Your foreach loop indicates that the path are available as $plugin. Use that

   foreach ($plugins as $plugin => $data) {
                      // ^ This represents the key of the array item
    $plugin_data = $plugins[$plugin];

    // Start simple DEBUG
    echo '</br>===============================</br>' ;
    echo '</br><b>Plugin Name : </b>'. $data[Name]; .'</br>' ;
    echo '</br><b>Plugin Path : </b>'. $plugin .'</br>' ; // <-- Problem here
    echo '</br>TextDomain set  : '. $data[TextDomain] .'</br>' ;
    echo '</br>===============================</br>' ;
    // End DEBUG
   }
Read more
March 4, 2013

Database results as objects or arrays?

Question by Jonathan

This question is similar to Mysql results in PHP – arrays or objects? However, my question expands on what has been discussed there.

I’m trying to decide which format is better for working with database results: objects or arrays. I’m not concerned about performance (from what I understand it makes little difference). My focus is also more on displaying the results—not creating, updating or deleting them.

To date I’ve always used objects, via functions like mysqli_fetch_object or PDO’s fetchObject. This normally works nice, until I start doing joins. Joins lead to strange objects that are a blend of fields from two or more tables. My code quickly starts getting confusing.

I should note, I’m assigning specific class names, and not sticking with the default stdClass. I do this so that I can access any helper methods I’ve created in my classes. For example:

foreach ($members as $member)
{
    echo $member->full_name();
    echo $member->age();
}

For the sake of clarity, I’m considering moving to arrays for all my database results. From what I’ve read others do this as well. However, this leaves me with no easy way to access my helper methods.

Using the above example, I guess I could just output both the first and last name instead of using the full_name() method, not a big deal. As for the age() method, I guess I could create a generic utility class and put it in there.

My questions:

  1. If you use (model) objects, how do you deal with joins?
  2. If you use arrays, how do you deal with helper methods?

Answer by Starx

I think its better to represent all of your datas and its type in form of Model. For both joined and singular objects. Doing so will always omit your problem.

class Member_Details {
    public $id;    
    public $first_name;
    public $last_name;

    public function FullName() {
         return $this -> first_name." ".$this -> last_name;
    }
}

class Member_Address {
    public $id;
    public $address;
    public $city;
}

class MemberJoins {
     public $objects = array();
}

After creating such classes you can configures a JOIN in the following way.

$obj_details = new Member_Details();
$obj_address = new Member_Address();
//Add data to the objects and then

//Then create the join object
$obj_address_details = new MemberJoins();
$obj_address_details -> objects = array($obj_details, $obj_address);

These both have a common property id from which its data can be linked.

Read more
March 3, 2013

Dynamically Replacing Content with Javascript and Links

Question by Kristopher Perovic

http://jsfiddle.net/bUjx7/42/

<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'>
</script>

<script type='text/javascript'>
$(document).ready(function () {
    $('.fieldreplace a').click(function () {
        $('#fieldmatch, .fieldgame').hide();
        var region = $(this).data('region');
        $('#' + region).show();
    });
});
</script>

I’m trying to make it so clicking one link will replace content in all the cells, and not, as it is, in just one cell.

Help?

Answer by Starx

You can replace the contends of all tds like?

$('#tableId td').html('content to update on all cells');
Read more

Secure JavaScript Site Specific API

Question by Ryan Naddy

I have been thinking about how to do this for a while, and I am not sure what the best approach is for this.

What I want to do, is allow users to sign up their website, they then are given a javascript snippet with a key, code, and a link to a file stored on my server.

Example

<script>
    var prefix_key  = 1234567890;
    var prefix_code = "hfj48fj4587tgfj5trutjh47dl4gx04jd9f";
</script>
<script src="http://mysite.com/js/somefile.js"></script>

Now, what can happen is say I have that on my site, and you come and copy it to your site. How can I secure it so it doesn’t work on your site but still works on mine?

Note: I will be using PHP as a back end if back end is needed.

Answer by Starx

Get the key and code from an ajax request based on a fixed API code which is user specific.

For example:

Give you every user a fixed API code to query the page which returns key and code

http://mysite.com/some_page_to_get_the_key_and_code.php?apikey=243h325h2353
Read more

How to prevent "a" styling from applying to a link?

Question by Dustin L.

I am trying to create a banner for my site without using an image. However, that banner is also a link.

Is there a way for me to override the use of the “a” (link) CSS styling from my div?

Assume the CSS looks like this:

a:link, a:visited {
    color: #176093;
}

#logo {
    color: red;
    font-size: 48px;
}

In other words, I’d like the CSS definitions for #logo to override the definitions for links.

Answer by Kolink

Converting comments to answer:

Using this, you can specify styles within a given container:

#logo a {
    color: red;
    /* ... */
}

Answer by Starx

If you only want to apply your styles to the anchor within the div #logo, you have to use a selector like this:

#logo a { 
    color: red;
    font-size: 48px;
}
Read more

keep current src attr so I can retrieve image

Question by mt0s

Code is like this :

$(' html body div.wrapper div.middle div.post_home:first-child a ').hover(
function() {
        $(' html body div.wrapper div.middle div.post_home:first-child a > img ').attr("src", "http:/site/test1.png");
},
 function() {
        $('html body div.wrapper div.middle div.post_home:first-child a > img ').attr("src", "currentSrc");
});

I just need to keep the src value of the image before the change so on mouseleave I can retrieve the image and display it.

Answer by Starx

Backup your src attrivute at the start of your event before changing it. And use it when you want to go to back.

var currentSrc;
$('.post_home:first-child a ').hover(function() {

    currentSrc = $('.post_home:first-child a > img').attr("src");
    $('.post_home:first-child a > img ').attr("src", "http:/site/test1.png");

}, function() {

        $('.post_home:first-child a > img').attr("src", currentSrc);

});

Note: I edited your selectors because what you have is more than necessary.

Read more

How to strip a string in PHP from everything besides numbers

Question by devirkahan

Currently when I echo a string I have saved it looks like this:

• 94% positive ·

What I want to have instead is simply:

94

I thought that the following would do the trick:

preg_replace(“/[^0-9]/”,””, $string)

But for some reason (I am assuming the bullet point) doing so instead gives me this:

94018332

Any help to get just the “94”?

Answer by Kolink

You are correct, the bullet point is being handled as an HTML entity and therefore contains numbers.

However, since your format is specific enough, you can use a better regex:

preg_match("/d+(?=%)/",$string,$match);
$percentage = $match[0];

This regex specifically searches for numbers followed immediately by a percent sign (and only the first such match).

Answer by Starx

You can use the filter functions to filter the number out.

$yourString =  "• 94% positive";
$int = filter_var($yourString, FILTER_SANITIZE_NUMBER_INT);
echo $int; //WIll echo 94

Demo

Read more

How can I combine 2 or more jquery keydown functions into one function?

Question by Pachonk

My goal:

To clean up multiple keydown functions leading to the same button press by making it one function.

My issue:

I have made many functions like this:

$("#username").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});
$("#password").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

That trigger button clicks on buttons. It is too messy and uses many lines. I want to combine the lines into one function. I have many boxes for my registration form as well.

What have I tried?

1.
I have tried the following code bellow and other replications which do not work:

$("#username","#password").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

2.
Another idea I had was to use a class, I just don’t know if this is considered the “proper” way to do it, so I need opinions:

$(".logintextbox").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

Then I would also add that class in my html so all of the login text boxes and all of the register text boxes have unique classes “grouping” them.

My question/tl;dr:

How can I combine 2 or more jquery keydown functions into one function using multiple id’s or one class?

Answer by Starx

I suggest delegating from your form instead of individual elements.

$("#your_form_id").on('keydown', 'input', function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

This will capture the key being pressed on all inputs within your form.

Read more
...

Please fill the form - I will response as fast as I can!