...

Hi! I’m Starx

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

Extacting words between $ symbol

Question by rajesh

I want to extract the words between the symbol $.

String = " this is first attribute $color$. this is the second attribute $size$"

I want to get a string list as List =[color , size]

I have used

Pattern pattern = Pattern.compile("(\$) .* (\$)");
Matcher matcher = pattern.matcher(sentence);

but I get the out put as

"$color$.this is the second attribute $size$"

please help me to solve this problem

Answer by halex

The problem is that the regex you are using is greedy and consumes everything beginning at the first $ until the last $ in your string. You have to add a ? after the * to make the regex nongreedy:

Pattern pattern = Pattern.compile("\$(.*?)\$");
Matcher matcher = pattern.matcher(sentence);
List<String> result = new ArrayList<String>();
for(int i=1; i <= matcher.groupCount(); i++)
    result.add(matcher.group(i);

Answer by Starx

Try this regex. It should give what is expected.

Pattern pattern = Pattern.compile("$(.*?)$");
Read more

loading content in div from other html file one by one

Question by Shubham Jain

I want to divide my page in two parts. say div 1 and div 2. I want to load first div when clicked on the page link. and when contents in div 1 is fully loaded then I want to start load the content in div 2.

Any possible solution that works fine in all major browsers.

I also want the content in these divs from other html in the same directory. Below is the code what I tried to do the thing.

$(document).ready(function(){ 
    $('#div1').load('home/index.html', function() {
        $("#div2").load('home/index2.html');
    });
});

I want that when the content from ‘home/index.html’ is fully loaded in div1 then content from ‘home/index2.html’ start loading in div2.

Below code is displaying contents in both div but I want to start loading in second div when my first div is completely loaded.

$(document).ready(function(){ 
    $('#div1').load('home/index.html');
    $("#div2").load('home/index2.html');
});

Answer by Starx

The callback function of .load() is to indicate load was performed not load is complete

Reference: http://api.jquery.com/load/

If a “complete” callback is provided, it is executed after
post-processing and HTML insertion has been performed. The callback is
fired once for each element in the jQuery collection, and this is set
to each DOM element in turn.

Read more

Using numeric indices to pass data from controller to view

Question by raheel shan

I have a simple question. Let me explain
We use this to pass data from controller to view

function index(){

    $data['title'] = 'This is title';
    $data['message'] = 'This is message';
    $this->load->view('test',$data);
}

Here we are using Associative Array to pass data
And now this function again and use indexed array instead of Associative Array

function index(){

    $data[] = 'This is title';
    $data[] = 'This is message';
    $this->load->view('test',$data);
}   

And now in View this does not work.

echo $data[0];
echo '<br>';
echo $data[1];

i only want to know if why this does not work. And in the user guide i never read that associative array is necessary.

Answer by Starx

The view data are converted into variables when parsed. A similar result of what extract() function of PHP gives. For example:

$data['title'] = 'This is the title';

will be accessible directly as $title not $data['title']. In fact, if you look at the sources, you will find it does uses extract() and similar conversion happens on your case to, but since variable $0 and $1 are invalid so they are not available.

Stick to string indexing. If that is not an option, then you might want to prefix something before the texts like:

$data['d0'] = 'This is the title';

Read the manual here its quoted. However, you can pass an array instead of a string and giving the exact result of what you want.

$data['data'] = array('This is the title', 'This is the description');

Now, this you will be access using $data[0] and $data[1].

Read more
October 29, 2012

Animate/Ease an element to position when other elements disappear

Question by Jonathan

Please take a look at this fiddle: http://jsfiddle.net/dhcyA/

Try clicking on a block. What I want is that when the other elements disapear, the selected block will animate/ease to his giving position instead of just jumping like it does now. Then the same animation repeats itself when clicking again on the box, but then back to place.

Maybe to keep in mind:
I’m using a reponsive design, which means those blocks can be vertical and horizontal after scaling the window.

Any redevisions on the fiddle or suggustions would be great!

Answer by Starx

Here is my solution & features it offers:

  • Remembers the last position and gradually animate to/from this position
  • Block positions are calculated and animated on load and every resize
  • Repositioning happens on $(window).resize() thus maintaining the fluid nature of the block, despite the use of position absolute
  • Support variable heights
  • Minor change on existing markup & CSS

On your existing markup, I added a wrapper division.

<div id="wrapper">
    <div class="block">
        <h2>I'm block 1</h2>
    </div>
    ....
</div>

To maintain the fluidness of the block, I created a function to position the block on the wrapper. Here is the function for position of the blocks:

var reposition = function() {
    wrapper = $("#wrapper");
    pLeft = 0; //The starting point of all repositioning
    pTop = 0;

    maxRowHeight = 0;

    $(".block").each(function(){
        $(this).stop(0,0).animate({
          'top' : pTop + 'px',
          'left' : pLeft + 'px'
        });

        pLeft += $(this).width(); //Add the left position for next block

        if($(this).height() > maxRowHeight) maxRowHeight = $(this).height(); //Find out the longest block on the row

        //If the next block will exceed the width of the wrapper
        if(pLeft + $(this).next().width() >= wrapper.innerWidth()) {
           pLeft = 0; //reset the left
           pTop += maxRowHeight;
           maxRowHeight = 0; 
        }
    });    
};

Finally, the script to toggle the block

$(".block").click(function() {

    $(this).siblings().slideToggle('slow'); //Toggle other blocks

    if(!$(this).data('active')){ //if the block is not active
        $(this).data('left', $(this).position().left); //sets its left
        $(this).data('top', $(this).position().top);   // and top position
        $(this).animate({ //animate at the top and bottom
            top:0,
            left:0
        },'slow');

        $(this).data('active',true);

    }else{

        $(this).animate({ //animate to its last known position
            top:$(this).data('top'),
            left:$(this).data('left')
        },'slow');

        $(this).data('active',false);
    }
});

Demos

  • Demo[Full] (Resize this to see the fluidness maintained)
  • Demo[Full] (version supporting variable heights)
Read more
October 28, 2012

Why couldn't I call eval() in this way?

Question by warl0ck

Why is the following code fails to compile:

<?php
  $str = "echo "ok"";
  $func = "eval";
  $func ($str);
?>

And php tells me eval was undefined.

Answer by Boann

In PHP, eval is a “language construct”, not a function. (Notice It turns keyword-color in syntax highlighting editors.) Language constructs cannot be called using the variable function syntax $func() or used with other function-specific things like is_callable().

From http://www.php.net/manual/en/functions.variable-functions.php:

Variable functions won’t work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Answer by Starx

eval() cannot be called using a variable function. If you don’t understand what a variable function is? look at the following part of your code

  $func = "eval";
  $func ($str); //Here $func becomes eval upon execution making it a variable function

If you look at the manual reference, its clearly noted

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Read more

Suggestions with pagination

Question by dorin dorin

I’ve a problem with pagination. The php code of pagination query is:

$ <? if (isset($_GET["page"])) { 

    $Page = preg_replace("/[^0-9]/","", $_GET["page"]);
} else {
    $Page = 0;
}
$limit       = 10;
$StartFrom  = $limit * $Page;
$TotalFiles = mysql_num_rows(mysql_query("SELECT * FROM linkuri WHERE `categorie` = 'Afaceri' AND status = 1"));
$TotalPages = floor($TotalFiles / $limit); ?>

And code to display it:

$i = 0; while ($TotalPages >= $i) { echo '<a class="active imgf" style="opacity: 1;margin-bottom:3px; margin-top:3px;" href="afaceri.php?page='.$i.'">'.($i+1).'</a>';$i++;}

The problem is I am trying to make the display as: PAGES: "BACK" 1 2 3 4 5 "NEXT"

Answer by Starx

First I would like to suggest an improvement on your query. To count the total rows use:

SELECT count(*) as `totalpost` FROM linkuri WHERE `categorie` = 'Afaceri' AND status = 1

Then, you are create that pagination by doing something like this:

$totalPost = 50; //Dummy total post
$limit = 10;

$pages = $totalPost / $limit; //Giving 5

//Now we know there are five pages
for($i=1; $i<=$pages; $i++) {
  echo $i; // Better echo something like <a href="link">$i</a>
}

P.S: This is a very basic example

After you get the hang of how to create the pagination effect, check this tutorial

How to paginate with PHP?

Read more

Is there a Javascript library to go from geopoint and time to timezone?

Question by Luke Hoersten

I’m looking for a Javascript library that can take a geopoint and date and return the timezone. The date is used as input in order to determine the daylight savings time status for that date and location.

I’ve seen there are services which make this information available:

The information is mostly static, though, so I’d like to not have to depend on external services and am therefore looking for a library. Here’s an example of how I’d like it to work:

tz = geodate.timezone(someFutureDate, lat, lng) => TimeZoneObject
tz.abbr() => "CST"

Answer by Starx

Finding the time zone based on the latitude and longitude has been previously asked on this community. Check

  1. Determine timezone from latitude/longitude without using web services like Geonames.org
  2. Get PHP Timezone Name from Latitude and Longitude? (Similar to 1)

Quoting an answer from Michael

  • Download the database of cities from geonames.org
  • convert it to a compact lat/lon -> timezone list
  • Use an R-Tree implementation to efficiently lookup the nearest city (or rather, its timezone) to a given coordinate

Now, answering the JavaScript part, JS alone cannot perform such queries as it runs on Client’s Machine. SO either you have to create an API to query the results or send AJAX request to a server page returning you the results.

Sending AJAX request would be a lot better and easier.

Read more

How to put a function inside an object and directly output the result

Question by Dan Myasnikov

Look, I ve got the following code to be executed and the result expected:

a = { a: function(){ return 'red'} }

so whenever I call

a.a #=> I would like to receive 'red' rather than 'function(){ return 'red'}

Any help appreciated

Answer by Starx

Simply do this

a = { 
   a: 'red' 
};

But if having the result return function that important, we have to make sure the function get called and returned.

a = {
    a: function() {
        return 'red-by-function';
    }() //This will ensure the function is called rather that returning the whole function
};

Demo of both cases

Read more

Scroll a 100% height div over top of main content area while scrolling?

Question by Dustin McGrew

What I’m trying to do is a little hard to explain. I want to have a “panel” that would be 100% of the window height and is overlaid on top of the main content of the website. What I want to happen is to have the main website content locked to the top of the browser window and have this “panel” over top of it. This part is easy just using z-index. The problem I’m having is getting the main content of the site to stay fixed at the top of the browser window and when the user scrolls down only the “panel” slides up to reveal the main part of the website below it. Once the panel has cleared the top of the browser window I want the main part of the site to scroll as usual. I would like this to be driven by jQuery.

Here’s the HTML I have:

This is an overlay that needs to slide over top of the main content when the user scrolls down.

This is the main content of the website.

And some CSS:

html, body {height:100%;}

.panel {height:100%; background-color: rgba(186,85,85,0.38); position: relative; z-index:1;}

.main {position: absolute; top:0px; min-height: 1500px;}

EDIT: Think of this effect like a curtain rising on a stage. The stage stays in place while the curtain rises.

Answer by Starx

Viewing this problem from overly simple point of view, using position: fixed can fix the main content website while others scroll.

Read more
October 27, 2012

How to solve a session expiration issue

Question by user1295167

I am doing a site which has a problem with session expire issue. The form contain almost 50 input fields , I have done it in ajax. I have given the user checkings in page reload the problem is that session and cookies are setting is done when page reloads,

How can I check whether user logined or not without lossing data? Is there any ajax functions
to retain session?

Answer by Starx

One way of solving this would be to increase the session timeout.

ini_set('session.gc_maxlifetime', '3600'); //Assign the time in seconds
Read more
...

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