Wednesday, April 17, 2013

Yii Framework - Twiiter Bootstrap TbMenu in Navbar options

To get the image to work just embed an image in the brand name like so:


'brand'=>'<img src="path_to_img.jpg"/>"

Add extra parameters to TbMenu

'itemOptions' not 'htmlOptions' when an item has htmlOptions. So to add an id use:

array('label'=>'First Link', 'url'=>"#", 'itemOptions'=>array('id' => 'xyz'))
 

Define $this->activeMenu in your main Controller and 

set value to $this->activeMenu from anywhere.

 
<?php 
if($this->activeMenu == null) {
    $this->activeMenu = "null";
}
$this->widget('bootstrap.widgets.TbNavbar',array(
    'items'=>array(
        array(
            'class'=>'bootstrap.widgets.TbMenu',
            'items'=>array(
                array(
                    'label'=>'Home', 
                    'url'=>array('/site/index'), 
                    'visible'=>Yii::app()->user->isGuest
                ),
                array(
                    'label'=>'About', 
                    'url'=>array('/site/page', 'view'=>'about'), 
                    'visible'=>Yii::app()->user->isGuest
                ),
                array(
                    'label' => 'Contact group', 
                    'url' => array('/group/index'),
                    'itemOptions' => array(
                        "class" => "group_nav"
                    ),
                    "active" => $this->activeMenu == "group_nav"
                ),
                array(
                    'label' => 'Contact list', 
                    'url' => array('/contact/index'),
                    'itemOptions' => array(
                        "class" => "contact_nav"
                    ),
                    "active" => $this->activeMenu == "contact_nav"
                ),
                array(
                    'label'=>'Logout ('.Yii::app()->user->name.')', 
                    'url'=>array('/site/logout'), 
                    'visible'=> !Yii::app()->user->isGuest
                )
            )
        )
    )
)); 
?> 

Write Java code to crash the java virtual machine


You can use the Unsafe class which is unsafe to use as you might guess.
public static void main(String... args) throws Exception {
    getUnsafe().getByte(0);
}

private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
    Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
    theUnsafe.setAccessible(true);
    return (Unsafe) theUnsafe.get(null);
}
prints
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff1c2f23368, pid=2630, tid=140676351506176
#
# JRE version: 7.0-b147
# Java VM: Java HotSpot(TM) 64-Bit Server VM (21.0-b17 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.so+0x82c368]  Unsafe_GetNativeByte+0xa8
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /nfs/peter/IdeaProjects/scratch/hs_err_pid2630.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.sun.com/bugreport/crash.jsp
#

Java Program to find Armstrong numbers - Example Code


import java.util.Scanner;

/**
 * Simple Java Program to check or find if a number is Armstrong number or not.
 * An Armstrong number of three digit is a number whose sum of cubes of its digit is equal
 * to its number. For example 153 is an Armstrong number of 3 digit because 1^3+5^3+3^3 or   1+125+27=153
 * @author Javin
 */

public class ArmstrongTest{

   
    public static void main(String args[]) {
   
        //input number to check if its Armstrong number
        System.out.println("Please enter a 3 digit number to find if its an Armstrong number:");
        int number = new Scanner(System.in).nextInt();
     
        //printing result
        if(isArmStrong(number)){
            System.out.println("Number : " + number + " is an Armstrong number");
        }else{
            System.out.println("Number : " + number + " is not an Armstrong number");
        }

   
    }

    /*
     * @return true if number is Armstrong number or return false
     */

    private static boolean isArmStrong(int number) {
        int result = 0;
        int orig = number;
        while(number != 0){
            int remainder = number%10;
            result = result + remainder*remainder*remainder;
            number = number/10;
        }
        //number is Armstrong return true
        if(orig == result){
            return true;
        }
     
        return false;
    }
 
}

Output:
Please enter a 3 digit number to find if its an Armstrong number:
153
Number : 153 is an Armstrong number
Please enter a 3 digit number to find if its an Armstrong number:
153
Number : 153 is an Armstrong number
Please enter a 3 digit number to find if its an Armstrong number:
371
Number : 371 is an Armstrong number

Tuesday, April 16, 2013

How do I call a method before every controller action yii using beforeAction

http://www.yiiframework.com/doc/api/1.1/CController#beforeAction-detail

protected function beforeAction(CAction $action)
{
    return true;
}

If you create this in your main Controller under components then you can call by:
return parent::beforeAction($action);

"protected/controllers/MyController.php"
<?php
protected function beforeAction(CAction $action)
{
    if(parent::beforeAction($action)) {
        return true;
    }
    return false;
}
?>

"protected/components/Controller.php"
<?php
protected function beforeAction(CAction $action)
{  
    require_once "protected/Utility/General.php"
    /* Do some common work here if you need in common controller */
    return true;
}
?>

Monday, April 15, 2013

Listing post titles in alphabetical or chronological order

Listing post titles in alphabetical or chronological order 

http://www.bloggersentral.com/2009/12/list-post-titles-in-alphabetical-order.html 

In this tutorial I will show you how to list the titles of your blog’s 1000 2000 most recent  posts. If you are looking for an alternative to Blogger’s Archive gadget, then this might be it. This list can also be used as a Table Of Contents. This list is made possible with the use of Yahoo! Pipe. See the demo in Blogger Sentral Widget Showcase .
post title alphabetical order
The list comes with several options:
  1. List them inside a widget or in a post static page.
  2. Arrange the titles in alphabetical or chronological order. If you use your blog as an online serial novel, then chronological order is just what you need.
  3. Append (or not) a comment count at the end of each title.
  4. Choose numbered or bulleted list style.
Let’s get started,

1) The code


01 <!-- Alphabetical/chronological Post Title Listing with comment count Start -->
02 <script type= "text/javascript" >
03 function getYpipeTL(feed) {
04   document.write( '<ul style="font-weight:bold">' );
05   var i;
06   for (i = 0; i < feed.count ; i++)
07   {
08 var href = "'" + feed.value.items[i].link + "'" ;
09 var pTitle = feed.value.items[i].title;
10 var pComment = " \(" + feed.value.items[i].commentcount + " comments\)" ;
11 var pList = "<li>" + "<a href=" + href + '" target="_blank">' + pTitle;
12   document.write(pList);
13   document.write(pComment); //to remove comment count delete this line
14   document.write( '</a></li>' );
15   }
16   document.write( '</ul>' );
17   }
18   </script>
19   <script src="http: //pipes.yahoo.com/pipes/pipe.run?
20   YourBlogUrl=http: //www.bloggersentral.com
21   &Order=alphabet
22   &_id=401e43055731c1a29f1e1d3eb5e8e13f
23   &_callback=getYpipeTL
24   &_render=json"
25 type= "text/javascript" ></script>
26 <span style= "font-size: 80%; float:right;" >Get this <a href= "http://www.bloggersentral.com/2009/12/list-post-titles-in-alphabetical-order.html" target= "_blank" >widget</a></span>
27 <!-- Alphabetical Post Title Listing End -->

2) Put the list in a page

Use this option if you want to put the list on a separate page. (You can then access it via a tab.)
  1. Create a new page by going to Posting > Edit Pages and clicking the New Page button.
  2. Click Edit HTML tab to switch to HTML mode.
  3. Copy and paste the code into the editor.
  4. Click Post Options at the bottom of the editor. Under the Edit HTML Settings heading, select Ignore newlines .
    post options
  5. Publish and view your post . The list should appear inside the page.
  6. Then add a link to the page from your homepage. This can be done by adding navigation tabs . If you have the page gadget installed, this is added automatically by Blogger.
  7. If you want to remove the extras (sidebars, footer etc.) from the page, read Apply different layout/styling to static pages .

    3) Put the list in a gadget

    Use this option if you want to put the list on a sidebar, making it visible at all times.
    1. Go to Design > Page Elements.
    2. Click Add A Gadget link.
    3. Select HTML/Javascript gadget.
    4. Enter the title of your widget e.g. All Posts List.
    5. Copy and paste the code inside the content box. Replace http://www.bloggersentral.com (the value of YourBlogUrl ) in code line 20 with your own blog URL. Do not include the trailing slash (as in .com/). Refer to step 4 for options/customizations.
      Reminder: In the process of editing your code, never switch to Rich Text mode. Doing so will add line breaks ( <br/> ) in your code, rendering the code useless.
    6. Save and view your blog.

    4) Customizing the list

    Below are a few available customizations/options:
    • Listing order -the default order is alphabetical. To change to chronological order, just change the word alphabet in code line 21 to chrono .
    • Comment count - comment count is displayed by default. To remove comment count, delete code line 13.
    • List style -the default is bulleted list. To change to numbered list, replace ul (in line 4 and 16) with ol .
    • Style the list with the inline style attribute in line 4.
    • If your list becomes too long, you might want to put it in a scroll box

    5) Editing the pipe (optional)

    If you want further customize the widget output, you need to edit the (Yahoo) pipe itself. Follow the steps below:
    1. Go to the Yahoo! pipe .
    2. Log in to your Yahoo! account.
    3. Create a clone by clicking the Clone button.
    4. Click edit source to edit it in anyway you like.
    5. When you’re done editing and saving, test run it by clicking Run Pipe button to confirm the output of the pipe.
    6. To use your edited pipe, copy the pipe id and paste it to replace the existing id in line 22. (To get the id, look in your browser’s address bar. The id is the end part the URL when you are viewing or editing the pipe.)

    jquery format date

    Getting Started

    <script type="text/javascript" src="date.js"></script>

    Syntax Overview

    Date.today()                    // Returns today's date, with time set to 00:00 (start of day).
    Date.today().next().friday()    // Returns the date of the next Friday.
    Date.today().last().monday()    // Returns the date of the previous Monday.
    new Date().next().march()       // Returns the date of the next March.
    new Date().last().week()        // Returns the date one week ago. 
    Date.today().is().friday()      // Returns true|false if the day-of-week matches.
    Date.today().is().fri()         // Abbreviated day names. 
    Date.today().is().november()    // Month names.
    Date.today().is().nov()         // Abbreviated month names.
    Date.today().is().weekday()     // Is today a weekday?
    Date.today().addDays(1)         // Add one day (+1).
    Date.today().addMonths(-3)      // Subtract three months (-3).
    Date.today().add(1).day()       // Add one (+1) day. Supports all date parts (year, month, day, hour, minute, second, millisecond, and weeks)
    Date.today().add(-3).months()   // Subtract three (-3) months.
    (1).day().fromNow()             // One (1) day from now. 
    (3).months().ago()              // Three (3) months ago.
    var n = 6;
    n.months().fromNow()            // Six (6) months from now.
    Date.monday()                   // Returns Monday of the current week.
    Date.mon()                      // Abbreviated version of Date.monday()
    Date.march()                    // Returns March 1st of this year.
    Date.mar()                      // Abbreviated version of Date.march()
    Date.today().first().thursday() // Returns the first Thursday of the current month.
    Date.today().second().thursday()// Returns the second Thursday of the current month.
    Date.march().third().thursday() // Returns the third Thursday in March of the current year.
    Date.october().fourth().sunday()// Returns the fourth Sunday in October.
    Date.today().fifth().sunday()   // Returns the fifth Sunday in the current month, or throws a RangeError exception if there are not 5 Sundays in the current month.
    Date.october().final().sunday() // Returns the final Sunday in October.
    Date.january().first().monday() // Returns the first Monday of the current year.
    Date.december().final().friday()// Returns the last Friday of the current year.
    Date.today().at("6:15pm");      // Returns todays date at 6:15pm.
    var time = {hour:18, minute:15};
    Date.today().at(time);          // Set time with a config object.
    var birthDayParty = {month: 1, day: 20, hour: 20, minute: 30};
    Date.today().set(birthDayParty);// Set date and time with a config object.

    Parsing

    Date.parse('t')                 // Returns today's date.
    Date.parse('today')             // Returns today's date.
    Date.parse('tomorrow')          // Returns tomorrow's date.
    Date.parse('yesterday')         // Returns yesterday's date.
    Date.parse('next friday')       // Returns the date of the next Friday.
    Date.parse('last monday')       // Returns the date of the previous Monday.
    Date.parse('July 8th, 2004')    // Thu Jul 08 2004
    Date.parse('15-Jan-2004')       // Thu Jan 15 2004
    Date.parse('7/1/2004')          // Thu Jul 01 2004
    Date.parse('7.1.2004')          // Thu Jul 01 2004
    Date.parse('07.15.04')          // Thu Jul 15 2004
    Date.parse('July 23rd 2004')    // Fri Jul 23 2004
    Date.parse('Sat July 3, 2004')  // Sat Jul 03 2004
    Date.parse('10:30 PM EST')      // Wed Oct 31 2007 20:30:00
    Date.parse('10PM')              // Wed Oct 31 2007 22:00:00
    Date.parse('t + 5d')            // Adds 5 days to today.
    Date.parse('today - 1 month')   // Subtracts 1 month from today.
    Date.parse('+')                 // Add 1 day to today = tomorrow.
    Date.parse('- 3months')         // Subtract 3 months.
    Date.parse('+1year')            // Add a year to today.
    Date.parse('-12 months')        // Subtract 12 months (1 year) from today.
    Date.parse('July 4th')          // July 4th of this year.
    Date.parse('15')                // 15th day of current month/year.
    Date.parse('July 8th, 2004, 10:30 PM')      // Thu Jul 08 2004 22:30:00
    Date.parse('2004-07-15T06:45:00')           // Thu Jul 15 2004 06:45:00
    Date.parse('Thu, 1 July 2004 22:30:00 GMT') // Thu Jul 01 2004 16:30:00
    Date.parse('1997-07-16T19:20:15')           // ISO 8601 Formats
    Date.parse('1997-07-16T19:20:30+01:00')     // ISO 8601 with Timezone offset
    Date.parse('1985-04-12T23:20:50Z')          // RFC 3339 Formats

    Chaining

    Date.today().add({ months: 1, days: 5 }).is().fri()        // Add 1 month and 5 days, then check if that date is a Friday.
    Date.parse('10-July-2004').next().friday().add(-1).month() // Take in a date, then move to the next Friday and subtract a month.

    Comparison

    Date.today().equals( Date.parse('today'))                  // true|false
    Date.parse('last Tues').equals(Date.today())               // true|false
    Date.equals(Date.today(), Date.parse('today'))             // true|false
    Date.compare(Date.today(), Date.parse('today'))            // 1 = greater, -1 = less than, 
    Date.today().compareTo(Date.parse('yesterday'))            // 1 = greater, -1 = less than, 0 = equal
    Date.today().between(startDate, endDate)                   // true|false

    Converting to String

    Format Description Example
    s The seconds of the minute between 0-59. "0" to "59"
    ss The seconds of the minute with leading zero if required. "00" to "59"
    m The minute of the hour between 0-59. "0" or "59"
    mm The minute of the hour with leading zero if required. "00" or "59"
    h The hour of the day between 1-12. "1" to "12"
    hh The hour of the day with leading zero if required. "01" to "12"
    H The hour of the day between 0-23. "0" to "23"
    HH The hour of the day with leading zero if required. "00" to "23"
    d The day of the month between 1 and 31. "1" to "31"
    dd The day of the month with leading zero if required. "01" to "31"
    ddd Abbreviated day name. Date.CultureInfo.abbreviatedDayNames. "Mon" to "Sun"
    dddd The full day name. Date.CultureInfo.dayNames. "Monday" to "Sunday"
    M The month of the year between 1-12. "1" to "12"
    MM The month of the year with leading zero if required. "01" to "12"
    MMM Abbreviated month name. Date.CultureInfo.abbreviatedMonthNames. "Jan" to "Dec"
    MMMM The full month name. Date.CultureInfo.monthNames. "January" to "December"
    yy Displays the year as a two-digit number. "99" or "07"
    yyyy Displays the full four digit year. "1999" or "2007"
    t Displays the first character of the A.M./P.M. designator. Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator "A" or "P"
    tt Displays the A.M./P.M. designator. Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator "AM" or "PM"
    S The ordinal suffix ("st, "nd", "rd" or "th") of the current day. "st, "nd", "rd" or "th"
    Custom Date and Time Format Specifiers
    Format Description Example
    d The CultureInfo shortDate Format Pattern "M/d/yyyy"
    D The CultureInfo longDate Format Pattern "dddd, MMMM dd, yyyy"
    F The CultureInfo fullDateTime Format Pattern "dddd, MMMM dd, yyyy h:mm:ss tt"
    m The CultureInfo monthDay Format Pattern "MMMM dd"
    r The CultureInfo rfc1123 Format Pattern "ddd, dd MMM yyyy HH:mm:ss GMT"
    s The CultureInfo sortableDateTime Format Pattern "yyyy-MM-ddTHH:mm:ss"
    t The CultureInfo shortTime Format Pattern "h:mm tt"
    T The CultureInfo longTime Format Pattern "h:mm:ss tt"
    u The CultureInfo universalSortableDateTime Format Pattern "yyyy-MM-dd HH:mm:ssZ"
    y The CultureInfo yearMonth Format Pattern "MMMM, yyyy"
    new Date().toString()                  // "Wed Oct 31 2007 16:18:10 GMT-0700 (Pacfic Daylight Time)"
    new Date().toString('M/d/yyyy')        // "10/31/2007"
    Date.today().toString('d-MMM-yyyy')    // "31-Oct-2007"
    new Date().toString('HH:mm')           // "16:18"
    Date.today().toString('MMMM dS, yyyy') // "April 12th, 2008"
    Date.today().toShortDateString()       // "10/31/2007". Culture specific as per Date.CultureInfo.shortDatePattern.
    Date.today().toLongDateString()        // "Wednesday, October 31, 2007". Culture specific as per Date.CultureInfo.longDatePattern.
    new Date().toShortTimeString()         // "4:18 PM". Culture specific as per Date.CultureInfo.shortTimePattern.
    new Date().toLongTimeString()          // "4:18:34 PM". Culture specific as per Date.CultureInfo.longTimePattern.

    Core

    Date.today().set({ day: 15 })          // Sets the day to the 15th of the current month and year. Other object values include year|month|day|hour|minute|second.
    
            Date.today().set({ year: 2007, month: 1, day: 20 })
    
    Date.today().add({ days: 2 })          // Adds 2 days to the Date. Other object values include year|month|day|hour|minute|second.
    
            Date.today().add({ years: -1, months: 6, hours: 3 })
    
    Date.today().addYears(1)               // Add 1 year.
    Date.today().addMonths(-2)             // Subtract 2 months.
    Date.today().addWeeks(1)               // Add 1 week
    Date.today().addHours(6)               // Add 6 hours.
    Date.today().addMinutes(-30)           // Subtract 30 minutes
    Date.today().addSeconds(15)            // Add 15 seconds.
    Date.today().addMilliseconds(200)      // Add 200 milliseconds.
    Date.today().moveToFirstDayOfMonth()   // Returns the first day of the current month.
    Date.today().moveToLastDayOfMonth()    // Returns the last day of the current month.
    new Date().clearTime()                 // Sets the time to 00:00 (start of the day).
    Date.today().setTimeToNow()            // Resets the time to the current time (now). The functional opposite of .clearTime()

    ISO 8601

    // Parse ISO 8601 string
    Date.parse('\"1997-07-16T19:20:15\"')  // ISO 8601 string format with wrapping double-quotes
    // Convert date to ISO 6801 string
    new Date().toISOString()               // Returns ISO 8601 string of date converted to it's UTC value. "2007-10-31T16:18:00Z"
    // Get UTC converted ISO week number
    Date.today().getISOWeek()              // Returns ISO 8601 week of year. Returns "01" to ("52" | "53") depending on the year. See also .getWeek()

    Misc

    Date.getMonthNumberFromName('March')   // 2 - CultureInfo specific. <static>
    Date.getDayNumberFromName('sat')       // 6 - CultureInfo specific. <static>
    Date.isLeapYear(2008)                  // true|false. <static>
    Date.getDaysInMonth(2007, 9)           // 31 <static>
    Date.today().getWeek()                 // Returns week of year. Returns 1 to (52 | 53) depending on the year
    Date.today().setWeek(1)                // Sets the week of the year to the Monday of the week set.
    var test = new Date();                 // Do something... like run a test...
    test.getElapsed()                      // Returns millisecond difference from now.
    Date.today().isDaylightSavingTime()    // true|false. Is within the Daylight Saving Time.
    Date.today().hasDaylightSavingTime()   // true|false. Is Daylight Saving Time observed.

    Saturday, April 13, 2013

    yii get base url

    Get Base Url YII Framework

    echo Yii::app()->request->baseUrl."<br/>" ;
    print_r(Yii::app()->request->baseUrl);
    echo "<br/>";
    var_dump(Yii::app()->getBaseUrl(true));
    echo "<br/>";
    echo Yii::app()->request->getBaseUrl(true);
    You're right, you can't use the Yii::app() methods inside the config's return array, but you can use Yii::getPathOfAlias() outside. Something like this might work:
    $webroot = Yii::getPathOfAlias('webroot');
    return array(
        ...
        'params'=>array(
            'paths' => array(
                'imageTemp'=> $webroot.'/files/temp-',
                'image'=> $webroot.'/files/',
                ...
            ),
        ),
    );
    return array(
        ...
        'urls'=>array(
            'paths' => array(
                'imageTemp'=> '/files/temp-',
                'image'=> '/files/',
                ...
            ),
        ),
    );