...

Hi! I’m Starx

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

How to access information from a superclass and subclass?

Question by SkyVar

What I am trying to do is access information (variables, methods, etc) from a superclass and it’s subclasses.

If, what I know about inheritance is right, by accessing the superclass we have access to it’s subclasses by default. So I am thinking that I only need to be able to access the parent (super) class.

But how do I do that?

I am not going to post all the code up here, and that will turn this post into 3 pages.

The superclass is just a general code to create a contact and the class that needs to access the superclass is a class that creates an arraylist and records each contact in the arraylist.

I am not trying to get the code written for me, but all the help to understand how this will work, will be greatly appreciated.

To keep this short, I won’t post the subclasses unless needed.

Contacts (Superclass):

public class Contacts
{
    protected String fname;
    protected String lname;
    protected String email;
    protected String phone;

    public Contacts(String fname, String lname, String email, String phone)
    {
        this.fname=fname;
        this.lname=lname;
        this.email=email;
        this.phone=phone;

    }

    public String getfname()
    {
        return fname;
    }

    public void setfname(String first)
    {
        this.fname=first;       
    }

    public String getlname()
    {
        return lname;
    }

    public void setlname(String last)
    {
        this.lname=last;
    }

    public String getemail()
    {
        return email;
    }

    public void setemail(String e)
    {
        this.email=e;
    }

    public String getphone()
    {
        return phone;
    }

    public void setphone(String num)
    {
        this.phone=num;
    }

    public String getFullName()
    {
        String full=fname+" "+lname;
        return full;
    }

I haven’t done much on this code because I have been trying to figure it out without really knowing where to start. I do not think the arguments should be null, I just included those to satisfy the evil compiler.

Addressbook:

import java.util.ArrayList;
public class AddressBook
{
    Contacts enteredContact = new Contacts(null, null, null, null);
}

Here is one of the subclasses to get an idea of what is included.

Friends (subclass):

public class Friend extends Contacts
{
    private String dob;

    /**
     * Constructs a new Friend object. (Insert any further description that is needed)
     * @param fname
     * @param lname
     * @param email
     * @param phone
     */
    public Friend(String fname, String lname, String email, String phone)
    {
        super(fname, lname, email, phone);
    }

    /**
     * @return the dob
     */
    public String getDob()
    {
        return dob;
    }

    /**
     * @param dob the dob to set
     */
    public void setDob(String dob)
    {
        this.dob = dob;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString()
    {
        return fname+", "+lname+", "+email+", "+phone+", "+dob;
    }

}

Answer by Starx

Use super function/keyword to access parent class. You can call a parent method like this

super.methodName();

To access parent constructor, you can do it in the following way using super() method.

super(null, null, null, null);
Read more

How can we speed up the query*

Question by mustafa

I have written this code to query the mysql tables customerselections, companies and companycampaigns. The tables have indexes on necessary fields.

The query time (without caching) is around 0,30. I think query time is high considering concurrent connections. Is it possible to rewrite in a different way to speed up the query time?

SELECT  
customerselections.customer_id, 
customerselections.selectedcompany_id,
customerselections.selection_id,
companycampaigns.campaign_id,
companycampaigns.company_id,
companycampaigns.campaign_title,
companycampaigns.campaign_detail,
companycampaigns.published,

companies.company_logo,
companies.company_gsm,
companies.company_landline,
companies.company_address

FROM  customerselections
LEFT JOIN companies ON customerselections.selectedcompany_id=companies.company_id 
LEFT  JOIN companycampaigns ON  companycampaigns.company_id=companies.company_id AND companycampaigns.published='1'
WHERE customerselections.customer_id='$customerid'  LIMIT $offset,$limit 

Answer by Starx

Select based on field like customerselections.customer_id is slower comparing to selecting all rows as server does not have to do any filtering. So this will give a minor boost.

SELECT  
customerselections.*,
companycampaigns.*,
companies.*
FROM  customerselections
LEFT JOIN companies ON customerselections.selectedcompany_id=companies.company_id 
LEFT  JOIN companycampaigns ON  companycampaigns.company_id=companies.company_id AND companycampaigns.published='1'
WHERE customerselections.customer_id='$customerid'  LIMIT $offset,$limit 
Read more

ZF2 Unit test album module returns routing issue

Question by Beniston

I am trying out the phpunit in the Zf2 album module. I encountered an error which states about routing.

Below is the debug information. It says ‘Route with name “album” not found’, but when I checked module.config.php in the album module folder, I see that is correctly set and in the browser the redirection to that route is working fine.

AlbumControllerAlbumControllerTest::testDeleteActionCanBeAccessed
ZendMvcRouterExceptionRuntimeException: Route with name "album" not found
D:wwwzend2vendorzendframeworkzendframeworklibraryZendMvcRouterSimpleRouteStack.php:292
D:wwwzend2vendorzendframeworkzendframeworklibraryZendMvcControllerPluginUrl.php:88
D:wwwzend2vendorzendframeworkzendframeworklibraryZendMvcControllerPluginRedirect.php:54
D:wwwzend2moduleAlbumsrcAlbumControllerAlbumController.php:80
D:wwwzend2vendorzendframeworkzendframeworklibraryZendMvcControllerAbstractActionController.php:87
D:wwwzend2vendorzendframeworkzendframeworklibraryZendEventManagerEventManager.php:468
D:wwwzend2vendorzendframeworkzendframeworklibraryZendEventManagerEventManager.php:208
D:wwwzend2vendorzendframeworkzendframeworklibraryZendMvcControllerAbstractController.php:108
D:wwwzend2testsmoduleAlbumsrcAlbumControllerAlbumControllerTest.php:35
C:wampbinphpphp5.4.3phpunit:46

I understand that the issue in AlbumController.php line 80 is

return $this->redirect()->toRoute('album');

But not sure why it is not working. Any one has encountered and overcome such issues?

Answer by dave b.

I hope it will save approx. 30 minutes of searching in the zend framework 2 code:

class AlbumControllerTest extends PHPUnit_Framework_TestCase
{

//...

    protected function setUp()
    {
        $bootstrap        = ZendMvcApplication::init(include 'config/application.config.php');
        $this->controller = new AlbumController();
        $this->request    = new Request();
        $this->routeMatch = new RouteMatch(array('controller' => 'index'));
        $this->event      = $bootstrap->getMvcEvent();

        $router = new ZendMvcRouterSimpleRouteStack();
        $options = array(
                    'route'    => '/album[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'AlbumControllerAlbum',
                        'action'     => 'index',
                    ),
            );
        $route = ZendMvcRouterHttpSegment::factory($options);

        $router->addRoute('album', $route);

        $this->event->setRouter($router);
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
        $this->controller->setEventManager($bootstrap->getEventManager());
        $this->controller->setServiceLocator($bootstrap->getServiceManager());
    }

}

Answer by Starx

Actually the easy way is to get the config data from the service manager:

$config = $serviceManager->get('Config');

Full code for the function setUp():

protected function setUp() {
    $serviceManager = Bootstrap::getServiceManager();
    $this -> controller = new AlbumController();
    $this -> request = new Request();
    $this -> routeMatch = new RouteMatch(
        array(
            'controller' => 'index',
        )
    );
    $this -> event = new MvcEvent();
    $config = $serviceManager->get('Config');
    $routerConfig = isset($config['router']) ? $config['router']  : array();
    $router = HttpRouter::factory($routerConfig);
    $this -> event -> setRouter($router);
    $this -> event -> setRouteMatch($this -> routeMatch);
    $this -> controller -> setEvent($this -> event);
    $this -> controller -> setServiceLocator($serviceManager);
}
Read more
March 27, 2013

strftime gets wrong date

Question by crnm

I’m using strftime to display future date.

But while using

strftime('%a., %d. %B %Y',time()+60*60*24*4)

I’m getting Mo., 01. April 2013 instead of Su., 31. March 2013 while using this today.

(Unix timestamp is 1364423120)

strftime('%a., %d. %B %Y',time()+60*60*24*3)

displays the correct Sa., 30. March 2013

What is wrong here with the last day of March?

Answer by Terje D.

The timestamp represents 23:25:20 local time. As daylight savings time comes into effect on March 31th, adding 96 h will give 00:25:20 as local time, thus a date one day later than expected. Using gmstrftime instead of strftime avoids this problem.

<?php

$timestamp = 1364423120;

echo strftime('%a., %d. %B %Y (%c %Z)', $timestamp)."n";
echo strftime('%a., %d. %B %Y (%c %Z)', $timestamp +60*60*24*4)."n";
echo gmstrftime('%a., %d. %B %Y (%c %Z)', $timestamp)."n";
echo gmstrftime('%a., %d. %B %Y (%c %Z)', $timestamp +60*60*24*4)."n";

gives

Wed., 27. March 2013 (Wed Mar 27 23:25:20 2013 CET)
Mon., 01. April 2013 (Mon Apr  1 00:25:20 2013 CEST)
Wed., 27. March 2013 (Wed Mar 27 22:25:20 2013 GMT)
Sun., 31. March 2013 (Sun Mar 31 22:25:20 2013 GMT)

Answer by Starx

According to the manual

strftime — Format a local time/date according to locale settings

Its better if you specify a locale while you are using it, to avoid such problem.

setlocale(LC_TIME, "de_DE");
strftime('%a., %d. %B %Y',time()+60*60*24*4)
Read more

Ajax Animation JQuery 1.9.2

Question by Chris Nevill

How would i upgrade the solution provided in this question
jQuery "Please Wait, Loading…" animation?

to work with JQuery 1.9.2?

I can’t seem to get it to work.
I’ve tried the following
http://jsfiddle.net/VpDUG/2485/

$(document).ajaxStart(function(){   $("body").addClass("loading"); });
$(document).ajaxStart(function(){   $("body").removeClass("loading"); });

but that hasn’t worked?

Answer by jfriend00

I think you meant to do this (using ajaxStop() for the second one):

$(document).ajaxStart(function(){   $("body").addClass("loading"); });
$(document).ajaxStop(function(){   $("body").removeClass("loading"); });

See it working here on a modified version of your jsFiddle: http://jsfiddle.net/jfriend00/gk3RL/


Also, a little more efficient to use document.body instead of "body":

$(document).ajaxStart(function(){   $(document.body).addClass("loading"); });
$(document).ajaxStop(function(){   $(document.body).removeClass("loading"); });

Answer by Starx

The second event should be ajaxComplete

$(document).ajaxComplete(function(){   $("body").removeClass("loading"); });
Read more
March 22, 2013

Writing jQuery code

Question by Roman

What i am doing wrong. I want to write in one field and after that opened by the following.I want thet if i enter the text in one field and after that other field are opening but other field dus not open’s. Please help me

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>

    $(document).ready(function() {
        $(function(){
            if($('#name' == '')){
                $('#version').attr( 'disabled', 'disabled' );
            }
            else {
                $('#version').removeAttr( 'disabled', 'disabled');  
            }
        }); 

        $(function(){
            if($('#name' !== '')){
                $('#version').attr( 'disabled', 'disabled' );
            }
            else {
                $('#version').removeAttr( 'disabled', 'disabled');  
            }
        });
    });
</script>
</head>
<body>
    <div>
        <form>
        Name: <input type="text" name="name" id="name">
        Version: <input type="text" name="version" id="version">
        Build: <input type="text" name="build" id="build">
        <input type="submit" value="Submit" id="submit"></br>
        <input type="text">
        </form>
    </div>
</body>
</html>

Answer by Starx

This is invalid:

if($('#name' == '')){
    $('#version').attr( 'disabled', 'disabled' );
}

You can use this instead:

if($('#name' ).length){
    $('#version').attr( 'disabled', 'disabled' );
}
Read more

Being attacked – What's that?

Question by Ariel

Seems like my website is being attacked.
I looked at the Apache logs and I saw thousands of lines like these;
Some random folders which don’t even exist. Looks like some brute force for websites…
Any ideas on what it is?

84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /files/console HTTP/1.1" 404 211
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /account/Admin/config.php HTTP/1.1" 404 222
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /Images/ini HTTP/1.1" 404 208
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /etc/wp-includes HTTP/1.1" 404 213
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /changelog/test.php" 200 58
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /Images/readme.txt HTTP/1.1" 404 215
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /changelog/logs//..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252fwindows/win.ini HTTP/1.1" 404 269
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /jscripts/tiny_mce HTTP/1.1" 404 215
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /files/addons HTTP/1.1" 404 210
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "POST /account/logs/logs_process.php?adm=1&JsygZ81Q=1 HTTP/1.1" 302 23349
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /etc/iishelp HTTP/1.1" 404 209
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /Images/_include HTTP/1.1" 404 213
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /account/Admin/config.inc.php HTTP/1.1" 404 226
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /changelog/test.php%2f HTTP/1.1" 404 217
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /Images/README HTTP/1.1" 404 211
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /changelog/logs//%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/etc/passwd HTTP/1.1" 404 280
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "OPTIONS / HTTP/1.1" 200 3405
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /Images/pass HTTP/1.1" 404 209
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /jscripts/tinymce HTTP/1.1" 404 214
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /files/invoker HTTP/1.1" 404 211
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /etc/iisadmin HTTP/1.1" 404 210
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /changelog/test.php%5c HTTP/1.1" 404 217
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /Images/config.php HTTP/1.1" 404 215
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /changelog/logs//%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/windows/win.ini HTTP/1.1" 404 285
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /account/Admin/localconfig.php HTTP/1.1" 404 227
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /etc/tsweb HTTP/1.1" 404 207
84.220.206.177 - - [22/Mar/2013:19:45:28 +0100] "GET /files/cp HTTP/1.1" 404 206

Answer by Starx

Those are requests made on your domains to access resources. May and may not be related to threats.

But looking at it briefly, seems like vulnerability scanning to find loop holes in your application.

Read more
March 19, 2013

php difference between 1 and '1'

Question by Blaze Tama

I have struggle with this problem for hours. I have this method my model (codeigniter) :

public function get_umat($kelas1 = 0, $kelas2 = 0) {
    $this->db->select('*');
    $this->db->from('msumat');
    $this->db->join('mskelas', 'msumat.kelas_id = mskelas.kelas_id');

    if($kelas1 != 0)
    {
        echo $kelas1;
        var_dump($kelas1);
        $this->db->where('mskelas.kelas_id', $kelas1);
    }
    else if($kelas2 !=0)
    {
        echo '2';
        $this->db->where('mskelas.kelas_id', $kelas2);
    }
    else if($kelas1 != 0 && $kelas2 !=0)
    {
        echo '3';
        $this->db->where('mskelas.kelas_id BETWEEN $kelas1 AND $kelas2');
    }

    return $this->db->get();
}

EDIT :
The one that not working is in this line of code (taken from above) :

$this->db->where('mskelas.kelas_id', $kelas1);

Its not working when i called this method in my controller, like this :

$this->backend_m->get_umat($_POST['ddl_kelas1'], $_POST['ddl_kelas1']);

I get ‘1’(String) when i vardump the ($_POST['ddl_kelas1']

Then i try to change the parameter in the controller, but its still not working :

 $this->backend_m->get_umat(1, $_POST['ddl_kelas1']);

Desperately, i tried to change the parameter directly in the model, and its working :

public function get_umat($kelas1 = 1, $kelas2 = 0)

Whats going on here?i think it has something to do with the difference of 1 (int) and ‘1’ (String). Thanks 😀

Answer by Starx

Cast your variables as integer.

$this->backend_m->get_umat((int)$_POST['ddl_kelas1'], (int)$_POST['ddl_kelas1']);
Read more
March 18, 2013

fadein after 2s, then fadeout after 10s animation

Question by Marino

I have a problem which I don’t know how to solve.

I want to to get this cloud to become visible after 2s and then become invisible again after 10s. It is important that the px remains as I have it because the cloud should:

  • travel
  • become visible in the beginning of the content area
  • become invisible at the end of the content area
  • travel to the end of the page invisible.

CSS:

.cloud1 {
  margin:18px 0px 0px 0px;
  animation:mymove 31s infinite;
  animation-delay:0s;
  position:absolute;
  z-index:1;

  /*Safari and Chrome*/
  -webkit-animation:mymove 31s infinite;
  -webkit-animation-delay:0s;
  -webkit-opacity:0 5s;
}

@keyframes mymove
{
  from {left:1050px;}
  to {left:0px;}
}

@-webkit-keyframes mymove /*Safari and Chrome*/
{
  from {left:1050px;}
  to {left:0px;}
}

Answer by Starx

It can be done with a little trick. With the animation set for 10 seconds. You can do something like this.

@keyframes mymove
{

    0%   {left:0px; opacity: 0;}
    20%  {left:1050px; opacity: 1; } /* This 20% will mean 2 second on a 10 seconds scale */
    100% {opacity: 0; left: 1050px; }

}

Demo

Read more

Inline div causing uneven layout

Question by Tiffany

I’m working with Twitter and have pulled a list of all my followers and their screen names down using the API. I’m trying to display them in a nice ‘grid’ on my web page. However, it currently looks like this:

Bad layout

The issue happens when the person’s screen name is so long that it goes on to two lines. I don’t know why it sometimes puts a single person on a line like that…

Here’s my CSS code:

div.inline { 
float:left; 
padding-left: 40px;
padding-bottom: 20px;
text-align: center;
font-family: sans-serif;
width: 90px;
}

And the HTML code:

<div class = "inline">
    <?php echo $userName; ?><br>
    <?php echo "<img src = ".$userImage." class = ".$class.">"; ?><br>
    <select name = "choice">
        <option value = "blank"></option>
        <option value = "cool">Cool</option>
        <option value = "uncool">Uncool</option>
    </select>
</div>

Can anyone help? Perhaps there is a way to put in a blank line after the first line of their name or something if it’s less than two lines long?

Answer by fanfavorite

The reason someone is on a single line is because each div is different heights. Either wrap the username in an element (div for example) and set a height to that or set a height to the entire inline div. I think it would be nice to have the images aligned though, so the first option is best.

<div class="inline">
    <div class="username"><?=$userName;?></div>
    <?='<img src="'.$userImage.'" class="'.$class.'" alt="'.$userName.'" />';?><br />
    <select name="choice">
        <option value="blank"></option>
        <option value="cool">Cool</option>
        <option value="uncool">Uncool</option>
    </select>
</div>

For 2 lines use the following:

.username { 
   height: 30px;
   line-height: 15px;
}

Increase height by line-height value for each line you want.

Answer by Starx

Specify a fixed height for the name and image. Your problem will be solved.

Update your markup as this:

<div class = "inline">
    <div class="name"><?php echo $userName; ?></div>
    <div class="image"><?php echo "<img src = ".$userImage." class = ".$class.">"; ?></div>
    <select name = "choice">
        <option value = "blank"></option>
        <option value = "cool">Cool</option>
        <option value = "uncool">Uncool</option>
    </select>
</div>

And CSS to something similar.

.name { height: 30px; }
.image { height: 200px; }
Read more
...

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