...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
September 13, 2012

How to refer to "this" in abstract Java class?

Question by user1111929

Is it possible in Java to use this inside a method of an abstract class, but as an instance of the subclass at hand, not just of the abstract class?

abstract class MyAbstractClass <MyImplementingClass extends MyAbstractClass> {

    public abstract MyImplementingClass self();
}

which I overwrite in every subclass I with

class MyImplementingClass extends MyAbstractClass<MyImplementingClass> {

    @Override public MyImplementingClass self() {
        return this;
    }
}

but I wonder if there are more elegant methods to do this. In particular, one that doesn’t require every subclass to overwrite a routine like self().

Answer by amit

The issue here I believe is that your self() method returns MyImplementingClass and not MyAbstractClass.

You should return a MyAbstractClass, the dynamic type of the returned object will be the relevant one.

I also do not follow why wouldn’t you just use this? It returns the object itself, with the correct dynamic type, regardless of where it is called. You can cast it if you need to

Answer by Starx

I believe, you can return newInstance() of a class to behave like that

@Override public MyImplementingClass self() {
    return MyImplementingClass.newInstance();
}
Read more
September 12, 2012

jquery nth selector in IE7

Question by Phil

I have a list of elements and need to make some amends to the first element in the list using jquery. I have tried a few methods to target the first item but none of them seem to work in IE7. These are the following methods I’ve tried…

 $(this).eq(1)
 $(this).first()
 $(this:nth-child(1))

All of these methods worked in all browsers except IE7, does anyone know of a fix to use for IE7 or a different method that will work in IE7?

Thanks in advance for any help?

Answer by Pradeeshnarayan

Try like this

$(this:first-child)

Will get more info from here

EDIT

Sorry for the confusion.
What I was trying to say is to use first-child instead of first()

You can use like this $('ul li:first-child').css('background-color', 'red');

Answer by Starx

.first() is a valid function and will work.

For example:

$("li").first(); // will match the first li in the tree
Read more

Access String variable from one if statement in another

Question by user185812

I am new to java coming from C#.

If I have a string that gets set in an “if-statement” is there a way to carry that string’s value to other if statements?

E.g. I set the String hi to carry the text “hello” in an if statement, but now have a completely separate if statement, and would like to use the value set to the String hi in the previous if statement.

My issue is that the veriable can’t be set until certain things in the if statement happen.

if(add.equals(temp)) {
    System.out.println ("What is the first number?");
    numberone = listen.nextDouble ();
    System.out.println ("What is the second number?");
    numbertwo = listen.nextDouble ();
    numberthree = numberone + numbertwo;
    previousproblem = numberthree;
    System.out.println ("The answer is " + numberthree);
}

So later on, in another if statement I, need to reference previousproblem, but it can’t be set until this if statement, as numberthree isn’t set until this statement.

Answer by dasblinkenlight

Java is identical to C# in this respect, all you need to do is declaring the variable outside both if statements, and set its initial value:

String s = null;
if (someCondition) {
    s = "hello";
}
if (anotherCondition) {
    System.out.println("s is "+s);
}

Answer by Starx

Define the string, before you start you if and else sequence.

String str1,str2;
if(true) {
   // ... true part
   str1 = "hello";
} else { 
   // ... false part
}

Now in another If

if(true) {
    str2 = str1; //assign the value of str1 to str2 demonstrating the use str1 in another if
}
Read more
September 11, 2012

array looping issue

Question by Nisanth

I have the following array

Array(
Array
(
    [Segment] => Array
        (
            [id] => 738
    )
),
Array
(
    [Segment] => Array
        (
            [0] => array([id] => 740),
            [1] => array([id] => 750)
    )
)
)

how can i loop the array. The second value need inner loop.

i need the output as

first loop as id->738

second loop as id->740, id->750

Regards,
Nisanth

Answer by Starx

You can do it like this:

foreach($array as $a) {
    foreach($a as $segment => $array) {
        if(isset($array['id'])) {
           echo $array['id']; //if there is an `id` index echo it
        } else {
           foreach($array as $k => $v) { //or else.. start looping again
               echo $v['id'];
           }
        }
    }
}
Read more
September 9, 2012

mysql_real_escape_string() for entire $_REQUEST array, or need to loop through it?

Question by ajo

Is there an easier way of safely extracting submitted variables other than the following?

if(isset($_REQUEST['kkld'])) $kkld=mysql_real_escape_string($_REQUEST['kkld']);
if(isset($_REQUEST['info'])) $info=mysql_real_escape_string($_REQUEST['info']);
if(isset($_REQUEST['freq'])) $freq=mysql_real_escape_string($_REQUEST['freq']);

(And: would you use isset() in this context?)

Answer by deceze

To escape all variables in one go:

$escapedGet = array_map('mysql_real_escape_string', $_GET);

To extract all variables into the current namespace (i.e. $foo = $_GET['foo']):

extract($escapedGet);

Please do not do this last step though. There’s no need to, just leave the values in an array. Extracting variables can lead to name clashes and overwriting of existing variables, which is not only a hassle and a source of bugs but also a security risk. Also, as @BoltClock says, stick to $_GET or $_POST. Also2, as @zerkms points out, there’s no point in mysql_real_escaping variables that are not supposed to be used in a database query, it may even lead to further problems.

Answer by Starx

You can also use a recursive function like this to accomplish that

function sanitate($array) {
   foreach($array as $key=>$value) {
      if(is_array($value)) { sanitate($value); }
      else { $array[$key] = mysql_real_escape_string($value); }
   }
   return $array;
}
sanitate($_POST);
Read more
September 7, 2012

PHP changing old mysql_query to PDO

Question by neeko

I have some old mysql_query queries in my code which i want to convert in to PDO but am struggling to get to work.

my original code was:

mysql_query("UPDATE people SET price='$price', contact='$contact', fname='$fname', lname='$lname' WHERE id='$id' AND username='$username' ")
or die(mysql_error()); 

now i am trying:

$sql = "UPDATE people SET price='$price', contact='$contact', fname='$fname', lname='$lname' WHERE id='$id' AND username='$username'";
$q   = $conn->query($sql) or die("failed!");

but can’t seem to get it to work, any ideas?

UPDATED CODE:

$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);


 // check if the form has been submitted. If it has, process the form and save it to the   database
 if (isset($_POST['submit']))
 { 
 // confirm that the 'id' value is a valid integer before getting the form data
 if (is_numeric($_POST['id']))
  {
 // get form data, making sure it is valid
 $id = $_POST['id'];
 $fname = mysql_real_escape_string(htmlspecialchars($_POST['fname']));
 $lname = mysql_real_escape_string(htmlspecialchars($_POST['lname']));
 $contact = mysql_real_escape_string(htmlspecialchars($_POST['contact']));
 $price = mysql_real_escape_string(htmlspecialchars($_POST['price']));


 // check that firstname/lastname fields are both filled in
 if ($fname == '' || $lname == '' || $contact == '' || $price == '' )
 {
 // generate error message
 $error = 'ERROR: Please fill in all required fields!';

 //error, display form
 renderForm($id, $fname, $lname, $contact, $price, $error);
 }
 else
 {
 // save the data to the database
 $username = $_SESSION['username'];

 $query = "UPDATE people 
         SET price=?, 
             contact=?, 
             fname=?, 
             lname=? 
          WHERE id=? AND 
                username=?";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $price);
$stmt->bindParam(2, $contact);
$stmt->bindParam(3, $fname);
$stmt->bindParam(4, $lname);
$stmt->bindParam(5, $id);
$stmt->bindParam(6, $username);    
$stmt->execute();


 // once saved, redirect back to the view page
header("Location: view.php"); 
}

Answer by John Woo

For more information visit this link: PHP PDO

based on your example,

<?php

    $query = "UPDATE people 
             SET price=?, 
                 contact=?, 
                 fname=?, 
                 lname=? 
              WHERE id=? AND 
                    username=?";
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(1, $price);
    $stmt->bindParam(2, $contact);
    $stmt->bindParam(3, $fname);
    $stmt->bindParam(4, $lname);
    $stmt->bindParam(5, $id);
    $stmt->bindParam(6, $username);    
    $stmt->execute();

?>

PDO Prepared statements and stored procedures

enter image description here

Answer by Starx

Few things you have to be clear while using PDO extension is that there are multiple ways to get things done.

The way you are currently using being one of them including few more. However it is always a good idea to bind parameters separately, because this prevents many problems like SQL Injection and many more.

Other important things to look at are statement, prepare and execute.

$conn = new PDO("...."); //Creating the handler

//Create the statement
$stmt = $conn -> prepare("UPDATE people SET price = :price, contact = :contact, fname = :fname, lname = :lname WHERE id= :id AND username = :username");

// Bind the params
$stml -> bindParam(":contact", $contact, PDO::PARAM_STR); //This way you can also define the DATATYPE of the parameter

//Execute
$stmt -> execute(array(
   ":price" => $price, //another way of binding the params
   ":fname" => $fname, 
   ":lname" => $lname,
   ":id" => $id, 
   ":username" => $username));
Read more
September 5, 2012

How to set a default layout in Magento 1.5 using local.xml?

Question by Reed Richards

So I’ve done some layouts that I want to use and I was thinking that setting this in your local.xml file would fix this for every page. Like this

<default>
<reference name="root">
    <action method="setTemplate">
      <template>page/mytheme.phtml</template>
    </action>
</reference>
</default>

This however doesn’t do anything. Instead if I go

...<customer_account_forgotpassword>
  <reference name="root">
    <action method="setTemplate"><template>page/mytheme.phtml</template></action>
  </reference>
</customer_account_forgotpassword>  

<customer_account_confirmation>
  <reference name="root">
    <action method="setTemplate"><template>page/mytheme.phtml</template></action>
  </reference>
</customer_account_confirmation>...

and so on for every specific place it gets changed on those specific pages. Am I thinking wrong or this the only way to do it?

Answer by Alan Storm

The problem you’re (probably) running into is that something comes along later and sets the template for the root block again, overriding your change.

More recent versions of Magento (1.4somethingish) introduced a way to prevent this from happening. If you look in page.xml, you’ll see a handle like this

<page_one_column translate="label">
    <label>All One-Column Layout Pages</label>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
        <!-- Mark root page block that template is applied -->
        <action method="setIsHandle"><applied>1</applied></action>
    </reference>
</page_one_column>

If the page_one_column handle gets applied to your request, or you manually apply it with

<update handle="page_one_column" />

Magento will change the template and call the setIsHandle method on the block.

<action method="setIsHandle"><applied>1</applied></action>

There’s code in Magento that will look for the IsHandle property, and if it’s true, further calls to setTemplate will be ignored. (that’s over-simplifying things a bit, but is more or less true)

Try something like

<default>
    <reference name="root">
        <action method="setTemplate">
          <template>page/mytheme.phtml</template>
        </action>
        <action method="setIsHandle">
            <applied>1</applied>
        </action>       
    </reference>
</default>  

And see if that helps.

Keep in mind this is one of those grey areas where it’s not clear if third party developers are supposed to tread. Also, changing the template for all pages may have un-desirable effect on parts of the site that expect to be in a certain template.

Answer by Starx

Actually, you are the on the right track. You just didn’t specify the request on your local.xml. You should also include the request you are overriding.

Here is a example code of local.xml

<layout>
    <default>
    ....
    </default>

    <!-- Update Configuration for this request specially -->
    <customer_account_confirmation> 
      <reference name="root">
        <action method="setTemplate"><template>page/mytheme.phtml</template></action>
      </reference>
    </customer_account_confirmation>

</layout>

This much configuration is enough to do, what you need.

Read more
September 4, 2012

Echo an array from another PHP file

Question by Curtis

I’m currently stuck on what I thought would be an easy solution… I’m working with PHPFileNavigator, and the only thing I’m stuck on is how I can echo the Title that is returned to an array on a separate file. Every time a file is created/edited for an uploaded file, it generates the following file below when a title is added to the file.

Update

Generally all I’m wanting to do is return the one Array value from my destination file which in this case would be from the ‘titulo’ key, and then print it back to my source file.

Destination File

 <?php
 defined('OK') or die();
 return array(
    'titulo' => 'Annual 2011 Report',
    'usuario' => 'admin'
 );
 ?>

Source File

<?php
  $filepath="where_my_destination_file_sits";
  define('OK', True); $c = include_once($filepath); print_r($c);
?>

Current Result

Array ( [titulo] => Annual 2011 Report [usuario] => admin )

Proposed Result

Annual 2011 Report

All I’m wanting to find out is how can I echo this array into a variable on another PHP page? Thanks in advance.

Answer by Starx

If you know the file name and file path, you can easily capture the returned construct of the php file, to a file.

Here is an example:

$filepath = 'path/to/phpfile.php';
$array = include($filepath); //This will capture the array
var_dump($array);

Another example of include and return working together: [Source: php.net]

return.php

<?php

$var = 'PHP';

return $var;

?>

noreturn.php

<?php

$var = 'PHP';

?>

testreturns.php

<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

Update

To only print a item from the array, you can use the indices. In your case:

<?php

$filepath="where_my_destination_file_sits";

define('OK', True); $c = include_once($filepath); print_r($c);
echo $c['titulo']; // print only the title

?>
Read more

How to search and highlight the string using jQuery?

Question by Rajasekhar K

How to search the word and highlighting using jquery, can you please help,
here is my code

$("div:icontains('look')").css("background-color", "yellow");

I need to search and highlight the only ‘look’ in the div.

<div>
     On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document. 
</div>

Thanks, Rajasekhar.

Answer by Starx

Your selector is wrong, it should be :contains rather than :icontains, with that correction, you code works and here is a demo of that.

Or, you can try using the highlight plugin its quite easy.

A simple example:

$("div:contains('look')").highlight('look').show();
Read more

how to assign the value for global variable in javascript?

Question by User

I use the following script function for get the row id from the grid. It was working properly. I get the ID within the click function. But if I try to get the outside of the function it will display Empty. I need the click function value for selr outside? How to do this?

var selr='';           
$(document).ready(function(){
               $("#datagrid").click(function(e) {
                 row = jQuery(e.target).closest('tr');
                 getId= row.attr("id");//for getting row number
                 selr = $("#datagrid").getCell(getId,'companyid');//getting Row ID
                 alert('alert in'+selr);
                 });
                  alert('alert out'+selr);
});

Answer by Praveen Kumar

The thing is, the value of selr gets declared only when you initiate the click function. So check after clicking the jqGrid.

The script inside the $(document).ready(); will not work, and will show as empty because, after the document is ready, the selr wouldn’t have set.

Instead of having a simple variable, assign selr as a global variable. Just replace selr with window.selr.

window.selr='';           
$(document).ready(function(){
    $("#datagrid").click(function(e) {
     row = jQuery(e.target).closest('tr');
     getId= row.attr("id");//for getting row number
     window.selr = $("#datagrid").getCell(getId,'companyid');//getting Row ID
     alert('alert in'+window.selr);
     });
     alert('alert out'+window.selr);
});

Answer by Starx

You are already assigning the variable as global.

The problem is the variable is initiated inside a function which is triggered on click of $("#datagrid") and the alert('alert out'+selr); executes upon DOM Ready Event, most probably before the click event triggers.

Read more
...

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