To use amazon smtp in php using php mailer follow the steps below. Also download full phpmailer so that you have class.phpmailer.php and class.smtp.php
    <?php
    //Dowload phpmailer and include that first
    require_once('class.phpmailer.php');

    //Then do SMTP settings for it
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPAuth   = true; // SMTP Authentication true
    $mail->SMTPSecure = "tls"; // SMTP secure tls it will use its default port
    $mail->Host       = ""; // Amazon Hostname will be email-smtp.us-east-1.amazonaws.com
    $mail->Username   = ""; // Amazon SMTP Username
    $mail->Password   = ""// Amazon SMTP Password

    $mail->SetFrom('amazon@verifiedemail.com', 'Site Name or Sender Name'); // This is verified email otherwise it will not work
    $mail->Subject = ""; // Subject Here
    $body = ""; // Email Body Here
    $body = eregi_replace("[]",'',$body);
    $mail->MsgHTML($body);
    //Multiple or single recipient
    $mail->AddAddress("rajeev@mohitsharma.net", "Rajeev Singh");
    $mail->AddAddress("yashwant@mohitsharma.net", "Yashwant Singh");
    if (
    $mail->Send()) {
        echo
    "Your message sent";
    }
    else if(!
    $mail->Send()) {
        echo 
    $mail->ErrorInfo;
    }
    ?>
    5
    Average: 5 (1 vote)
    You can do this using below command. Open terminal and write the command below you will see the live view of the file and new entries will be shown in the end
    ubuntu~$: tail -f /path-to-logfile/filename.log
    5
    Average: 5 (1 vote)
    To use camera on website in image upload fields on mobile Use this:
    <input type="file" accept="image/*;capture=camera" />
    5
    Average: 5 (1 vote)

    to write source code in html pages use this plugin

    https://github.com/timheap/SecretSource

    5
    Average: 5 (1 vote)
    Create custom module and add following hook to display profile2 field don't have value
    function <modulename>_field_attach_view_alter(&$output, $context) {
      if ($context['entity_type'] != 'profile2' || $context['view_mode'] != 'page') {
        return;
      }
      $profile = $context['entity'];
      $instances = _field_invoke_get_instances('profile2', $profile->type, array('default' => TRUE, 'deleted' => FALSE));
      foreach ($instances as $field_name => $instance) {
        if (empty($profile->{$field_name}) && $field_name=='<field_name> or <nocondition all fields>') {
          $display = field_get_display($instance, 'page', $profile);
          if ($display['type'] == 'hidden') {
            continue;
          }
          $field = field_info_field($field_name);
          $output[$field_name] = array(
            '#theme' => 'field',
            '#title' => $instance['label'],
            '#label_display' => 'above',
            '#field_type' => $field['type'],
            '#field_name' => $field_name,
            '#bundle' => $profile->type,
            '#object' => $profile,
            '#items' => array(),
            '#entity_type' => 'profile2',
            '#weight' => $display['weight'],
            0 => array('#markup' => '&nbsp;'),
          );
        }
      }
    }
    5
    Average: 5 (1 vote)

    To install mavericks from bootable usb check here

    https://discussions.apple.com/message/23615133#23615133

    Plug in 8gb pendrive

    download mavericks in app store then

    sudo /Applications/Install\ OS\ X\ Mavericks.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Mavericks.app --nointeraction

    its will take 30 mins and your bootable mavericks usb is ready!!

    5
    Average: 5 (1 vote)

    Run these commands

    $: which node
    /usr/local/bin/node

    then run

    $: cd /usr/local/

    then run

    $: rm -r bin/node bin/node-waf include/node lib/node lib/pkgconfig/nodejs.pc share/man/man1/node.1

    Done

    0

    grep -r -l "some text here to search" .

    5
    Average: 5 (1 vote)

    See here

    http://www.chrishjorth.com/blog/free-aws-ec2-ubuntu-apache-php-mysql-setup/

    Opening Port 80 or http on ec2

    1. Click security group in left bar

    2. then select security group for instance

    3. then select inbound rule

    4 add rule for http and done

    0

    This will work need jquery and jquery parser plugin as mentioned on the page with bootstrap 3.x

    http://www.joshuawinn.com/opening-youtube-links-dynamically-in-a-twitter...

    5
    Average: 5 (1 vote)

    #states

    See here:

    https://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7

    #ajax
    See Here:

    https://drupal.org/node/752056

    5
    Average: 5 (1 vote)
    To add remote origin to repository Open terminal:
    cd repo_directory
    git remote add origin git@github.com:testcomp/testing.git
    git push origin master
    To remove remote from repository:
    $: git remote -v // Will list remote urls
    # origin  git@github.com:testcomp/testing.git (fetch)
    # origin  git@github.com:testcomp/testing.git (push)

    $: git remote rm origin

    $: git remote -v // Will list nothing now
    5
    Average: 5 (1 vote)
    To start mysql console on mac MAMP you can open the terminal and issue this command
    Terminal$: /Applications/MAMP/Library/bin/mysql --host=localhost -u root -p root
    5
    Average: 5 (1 vote)
    You can build your controller like below TestController
    var TestController = function($scope) {

        $scope.person = 1;

        $scope.persons =
        [
            { id: 1, name: "Mohit" },
            { id: 2, name: "Rajeev" },
            { id: 3, name: "Yashwant" },
            { id: 4, name: "Hamender" }
        ];      
    };
    Below is the how we can render the select in view. Mohit is selected by default there
    <select data-ng-model="person"
            data-ng-options="t.id as t.name for t in persons">              
    </select>
    Note: 1. data-ng-options will work only if data-ng-model is specified 2. if you don't want any value selected by default. You don't need to specity $scope.person=1
    5
    Average: 5 (1 vote)
    Go to Test Div
    $('a.derivate').click(function(){
        $('html, body').animate({
            scrollTop: $( $(this).attr('href') ).offset().top
        }, 500);
        return false;
    });
    It will scroll here
    5
    Average: 5 (1 vote)
    Use below function to calculate age
                    var currYear = d.getFullYear(),
                        currMonth = d.getMonth(),
                       currDay = d.getDate();

                    var checkAge = function(birthMonth, birthDay, birthYear) {
                        var age = currYear - birthYear;
                        if (currMonth < birthMonth - 1) {
                            age--;
                        }
                        if (birthMonth - 1 == currMonth && currDay < birthDay) {
                            age--;
                        }
                        return age;
                    };

                    var ageResult = checkAge(11, 10, 2000);

                   //ageResult contains calculated age. Arguments passed to checkDate Month, Day, Year
    5
    Average: 5 (1 vote)
    Create a service to add/remove cookie
    define(
        ['app'],
        function (app) {
            app.factory('$remember', function() {
                function fetchValue(name) {
                    var gCookieVal = document.cookie.split("; ");
                    for (var i=0; i < gCookieVal.length; i++)
                    {
                        // a name/value pair (a crumb) is separated by an equal sign
                        var gCrumb = gCookieVal[i].split("=");
                        if (name === gCrumb[0])
                        {
                            var value = '';
                            try {
                                value = angular.fromJson(gCrumb[1]);
                            } catch(e) {
                                value = unescape(gCrumb[1]);
                            }
                            return value;
                        }
                    }
                    // a cookie with the requested name does not exist
                    return null;
                }
                return function(name, values) {
                    if(arguments.length === 1) return fetchValue(name);
                    var cookie = name + '=';
                    if(typeof values === 'object') {
                        var expires = '';
                        cookie += (typeof values.value === 'object') ? angular.toJson(values.value) + ';' : values.value + ';';
                        if(values.expires) {
                            var date = new Date();
                            date.setTime( date.getTime() + (values.expires * 24 *60 * 60 * 1000));
                            expires = date.toGMTString();
                        }
                        cookie += (!values.session) ? 'expires=' + expires + ';' : '';
                        cookie += (values.path) ? 'path=' + values.path + ';' : '';
                        cookie += (values.secure) ? 'secure;' : '';
                    } else {
                        cookie += values + ';';
                    }
                    document.cookie = cookie;
                }
            });
        }
    );
    Use this service in your login controller like this
        app.controller("LoginCtl", ["$scope", '$remember', function($scope, $remember){
            $scope.remember = false;
            if ($remember('username') && $remember('password') ) {
                $scope.remember = true;
                $scope.username = $remember('username');
                $scope.password = $remember('password');
            }
            $scope.rememberMe = function() {
                if ($scope.remember) {
                    $remember('username', $scope.username);
                    $remember('password', $scope.password);
                } else {
                    $remember('username', '');
                    $remember('password', '');
                }
            };
        }]);
    and remember me checkbox look like this
    <label>
    <input type="checkbox" name="remember" data-ng-click="rememberMe()" data-ng-model="remember"> &nbsp; Remember Me
    </label>
    5
    Average: 5 (1 vote)
    You can do this using below code in custom module
    /**
    * Altering Date Popup to remove labels and description for specific field
    */
    function <module_name>_date_popup_process_alter(&$element, &$form_state, $context) {
    if ($element['#name'] == '<fieldname>') {
      unset($element['date']['#description']);
      unset($element['date']['#title']);
    }
    }

    /**
    * To remove for all date fields remove if statement
    */
    5
    Average: 5 (1 vote)
    Create and function in ApplicationHelper and include that helper in ApplicationConroller sepcifying the name of helper metod
    #application_controller.rb

    class ApplicationController < ActionController::Base
          include ApplicationHelper
            helper_method :acessed_anywhere

    end

    #application_helper.rb

    module ApplicationHelper

      def acessed_anywhere

      end
    end
    5
    Average: 5 (1 vote)
    data = 'string with youtube.com and youtu.be  urls'
    pattern = '/(?:https?:\/\/)?(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=)?(\w{10,11})/i'

    // For example replace links with id

    newdata = data.gsub(pattern, "#{$2}")
    5
    Average: 5 (1 vote)
    This can be done simply by changing the source in the iframe tag with autoplay enabled:
    $('#clicked_item').click(function() {
        $("#wrapper_div_id iframe").attr('src', $("#wrapper_div_id iframe", parent).attr('src') + '?autoplay=1');
    });


    #clicked_item : ID of the item who click plays video
    #wrapper_div_id : ID of the div contaning video iframe or you can use iframe id directly

    5
    Average: 5 (1 vote)

    To save multiple select value in rails use text field on database and save comma seperated or serialized values there or if you have to use the values in search results you can create modal associations for the corresponding fields

    5
    Average: 5 (1 vote)
    You can do this simply
    #date to timestamp

    start_date = DateTime.now

    timestamp = start_date.to_time_to_i

    #Timestamp to date again

    start_date_again = Time.at(timestamp)
    0

    First install nscd

    mohit@mohit-Inspiron-580s:$ sudo apt-get install nscd

    Then

    mohit@mohit-Inspiron-580s:$ sudo /etc/init.d/nscd restart

    Done

    5
    Average: 5 (1 vote)
    You can delete duplicate values in column using below query replace the tablename and fieldname before using it
    DELETE temp1.*
    FROM cities AS temp1
       INNER JOIN (
          SELECT city
          FROM cities
          GROUP BY city
          HAVING COUNT(*) > 1
       ) AS temp2 ON temp2.city = temp1.city
    5
    Average: 5 (1 vote)
    You can use animate to decrease padding slowly by specifying slow in animate function.
     
    $('#link1').click(function() {
      $("#block").animate({
          'padding-top' : 0,
          'padding-right' : 0,
          'padding-bottom' : 0,
          'padding-left' : 0,
        }, "slow");
    });
    0

    The problem seems to be due to client_side_validations version

    so use

    gem 'client_side_validations', '3.1.0'

    in gemfile and run bundle update

    5
    Average: 5 (1 vote)
    To allow no password in phpmyadmin login you have to edit phpmyadmin config file and set allow no password to true to do this open terminal and first edit config file
    ubuntu@mypc$ sudo gedit /etc/phpmyadmin/config.inc.php

    Then find below line uncomment if commented and set TRUE, FALSE accordingly.

    $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
    5
    Average: 5 (1 vote)
    We use theme imagecache in drupal 6. but in drupal 7 we have to use core image style an that can be used as below:
    <?php
    $image
    = theme('image_style', array('style_name' => 'profile_picture', 'path' => 'path uri', 'alt' => 'alt text', 'title' => 'title'));
    ?>
    5
    Average: 5 (1 vote)
    To add html inside link_to use raw on title
    <%=link_to (raw("<span>Link Title</span>"), path) %>
    Removing Jetbrains IDE idea files git rm -r --cached .idea/
    0

    This is due to missing key in [] when you are creating form for child attributes. Multiple entries are there and this behaves as array instead of hash causing problem. Solution is to add key there you can use timestamp as ke as that is unique

    5
    Average: 5 (1 vote)
    To get key from value you can use below code:
    testhash = {:active => 1, :blocked => 2, :pending => 3}

    testhash.map{ |k,v| v==2 ? k.to_s.capitalize!  : nil }.compact

    It will display result "Blocked"
    5
    Average: 5 (1 vote)

    This is due to missing module file like my_module.rb in my_module directory for Module named MyModule

    or

    Due to duplicate class existence

    5
    Average: 5 (1 vote)
    To show table collation on mysql command line use following command
    mysql> show table status;
    5
    Average: 5 (1 vote)
    We can use observers with model to seperate some of the required functionality on paticular action To create a observer create observer file in models directory for example i have to create a observer for User model i can name it user_observer.rb it will send email on registration i have already created a mailer CustomMailer just call it here passing user object in it
    # models/user_observer.rb
    class UserObserver < ActiveRecord::Observer

      def after_create(user)
        # Send Registration Email
        CustomMailer.registration_email(user).deliver
      end
    end
    To enable this observer place below code in your environment file in config/environments/ directory
      #Adding observers in config/environments/development.rb
      config.active_record.observers = :user_observer
    5
    Average: 5 (1 vote)
    Open terminal and enter below command with path to the dump file
    apples-MacBook-Pro:~ apple$ /Applications/MAMP/Library/bin/mysql -u username -p databasename < "pathtodumpfile.sql"
    5
    Average: 5 (1 vote)
    To add custom advanced forum styles you can create a custom module which styles folder in it having new theme for advanced forum
    Use this hook in your module

    function <module_name>_ctools_plugin_directory($module, $plugin) {
      if ($module == 'advanced_forum') {
        return 'styles';
      }
    }

    create directory in your module

    styles/theme_name/<theme_files>

    You can copy any default theme from advanced_forum/styles
    5
    Average: 5 (1 vote)
    To uninstall RVM just execute following command in terminal use sudo rvm implode if don't have administrative previlages for the logged in user remove /etc/rvmrc and ~/.rvmrc after uninstalltion
    rvm implode
    # This will uninstall the RVM
    5
    Average: 5 (1 vote)
    To enable custom slugs in refinerycms goto config/initializers/pages.rb you can see a variable use_custom_slugs uncomment that line and set that true if its false if its not there just add
    config.use_custom_slugs = true
    5
    Average: 5 (1 vote)
    To change directory ownership in ubuntu Open terminal and give following command
    mohit@ubuntu$: chown -hR <username>  <directory_path/name>


    where <username> is the user to give ownership and <directory_path/name> is the directory or path to directory
    0
    To remove current password field in drupal just place this form alter in any custom module this will remove field and its validation also
    function <modulename>_form_alter(&$form, $form_state) {
      unset($form['account']['current_pass']);
      unset($form['account']['current_pass_required_values']);
      $form['#validate'] = array_diff($form['#validate'], array('user_validate_current_pass'));
    }
    5
    Average: 5 (1 vote)
    This error will come if you are missing method or don't have any record related to the path request so you need to handle this error simple add bang (!) in controller where you are getting data
    def request
        @request = Request.find_by_request_id!(params[:id])
        respond_to do |format|
           format.html {render :layout => "landing", :template => "requests/newrequest"}
           format.json { render :json => {:request => @request} }
        end
    end

    # ! rescue and  redirect to 404 page if no record exists for params[:id]
    5
    Average: 5 (1 vote)
      
       var mouse_in = false;
        $('#new_request').hover(function(){
            mouse_in=true;
        }, function(){
            mouse_in=false;
        });
        $("body").mouseup(function(){
            if(! mouse_in {
                $('.fullform').each(function() {
                    $(this).hide();
                });
            }
        });
     
    // This will hide some of the form elements with class fullform when clicked outside the form where form id is new_request

    <form id="new_request">
      <input type="text" name="username">
      <input type="text" name="email">
      <input type="text" name="age" class="fullform">
      <input type="text" name="city" class="fullform">
    </form>
    5
    Average: 5 (1 vote)

    To show hidden files type following command in terminal

    defaults write com.apple.finder AppleShowAllFiles -bool true

    To hide files again type below command in terminal

    defaults write com.apple.finder AppleShowAllFiles -bool false

    After executing these commands logout and login again to restart the finder

    0

    Open terminal and execute following command

    /Applications/MAMP/Library/bin/mysql -uroot -p

    Enter password if any your mysql console will be started then

    5
    Average: 5 (1 vote)
    Install gem using following command on windows 7
    gem install mysql2 -- \\\\\'--with-mysql-lib=\\\\\"c:\\Program Files\\MySQL\\MySQL Server 5.0\\lib\\opt\\\\\" --with-mysql-include=\\\\\"c:\\Program Files\\MySQL\\MySQL Server 5.0\\include\\\\\"\\\\\'
    on ubuntu
    sudo apt-get install libmysql-ruby libmysqlclient-dev
    http://instantrails.rubyforge.org/svn/trunk/InstantRails-win/InstantRail... this is to be placed in ruby/bin directory on windows libmysql.dll
    5
    Average: 5 (1 vote)
      page = Page.create(
        :title => 'Testpage',
        :link_url => '/testpath',
        :deletable => false,
        :position => ((Page.maximum(:position, :conditions => {:parent_id => nil}) || -1)+1),
        :menu_match => '^/testpath(\/|\/.+?|)$'
      )
      Page.default_parts.each do |default_page_part|
        page.parts.create(:title => default_page_part, :body => nil)
      end
    5
    Average: 5 (1 vote)
    To transfer file from one server to another using scp 1. Open terminal and connect to server via ssh
    mohit@ubuntu: ssh usrname@mohitsharma.net
    Enter password:

    username@mohitsharma.net ]:

    Go to directory from where file is to be transfered

    Then type following command

    username@mohitsharma.net ]: scp filename username@remoterhost:<pathtofile>

    Enter

    Add to known host yes

    Enter remote password

    its starts transfer and file will be transfered
    5
    Average: 5 (1 vote)
    To download file using scp you need ssh username, password and host 1. First open terminal and type
    mohit@ubuntu: scp <myusername>@<hostname>:<pathtofile>

    Press enter

    Yes to add to known hosts

    Enter ssh password and done file start downloading to you local

    mohit@ubuntu: ls
    file will be displayed to you

    Where

    <myusername> ssh username
    <hostname> like mohitsharma.net or whatever it is to be
    <pathtofile> file path with filename to download like /var/www/test.sql

    Note: use sudo with scp command if you don't have root permissions
    5
    Average: 5 (1 vote)
    You can do by adding these function in your controller or you can specify these as helper methods
    def get_browser
          if request.env['HTTP_USER_AGENT'].downcase.match(/crome/i)
            "Crome"
          elsif request.env['HTTP_USER_AGENT'].downcase.match(/msie/i)
            "Internet Explorer"
         elsif request.env['HTTP_USER_AGENT'].downcase.match(/konqueror/i)
            "Konqueror"
         elsif request.env['HTTP_USER_AGENT'].downcase.match(/firefox/i)
            "Mozilla"
         elsif request.env['HTTP_USER_AGENT'].downcase.match(/opera/i)
            "Opera"
         elsif request.env['HTTP_USER_AGENT'].downcase.match(/safari/i)
            "Safari"
          else
            "Unknown"
          end
        end
     
        def get_operating_system
          if request.env['HTTP_USER_AGENT'].downcase.match(/mac/i)
            "Mac"
          elsif request.env['HTTP_USER_AGENT'].downcase.match(/windows/i)
            "Windows"
          elsif request.env['HTTP_USER_AGENT'].downcase.match(/linux/i)
            "Linux"
          elsif request.env['HTTP_USER_AGENT'].downcase.match(/unix/i)
            "Unix"
          else
            "Unknown"
          end
        end
        def client_ip
          request.remote_ip
        end


    # You can simply call there by there name

    get_operating_system like this
    5
    Average: 5 (1 vote)
    To get month, year, day from datatime you can do that simply
    Suppose you have date  2012-02-20 08:56:00 UTC in post.published_at you have to extract day from it

    <%= post.published_at.strftime("%d") %> # Show 20

    If you have to extract month Jan, Feb like this

    <%= post.published_at.strftime("%b") %> # Show Feb

    if you have to extract year

    <%= post.published_at.strftime("%Y") %> # Show 2012

    Here is list of some date formats can be used


      %a - Abbrevated Day Name (Sun)
      %A - Full Day Name (Sunday)
      %b - Abrevatted Month Name  (Jan)
      %B - Full Month Name (January)
      %c - Local Date Time Representation
      %d - Day of the month
      %H - Hour of the day, 24-hour clock
      %I - Hour of the day, 12-hour clock
      %j -   Day of the year (001..366)
      %m - Month of the year (01..12)
      %M - Minute of the hour (00..59)
      %p -  Meridian indicator (AM  or  PM)
      %S - Second of the minute (00..60)
      %y - Year without a century (00..99)
      %Y - Year with century
      %Z - Time zone name
    5
    Average: 5 (1 vote)
    To install java on ubuntu follow the steps
    1. First to get update
    mohit sharama@ubuntu $:  sudo apt-get update

    2. Install jdk and plugin

    mohit sharama@ubuntu $: sudo apt-get install sun-java6-jdk sun-java6-plugin

    3. Check if its installed fine and version installed

    mohit sharama@ubuntu $:  java -version
    5
    Average: 5 (1 vote)
    First of all start terminal check this in launchpad or simply search in spotlight. When terminal is opened type following command and then enter database password
    apple@mohit$ /Applications/MAMP/Library/bin/mysql -uroot -p
    Enter Password:
    mysql>
    5
    Average: 5 (1 vote)
    This are two ways of doing this first is if file already placed on server then you can give filepath and tablename and run create this file import.php
    <?php
    $connec
    = mysql_connect(<hostname>,  <username>,<password>);
    mysql_select_db(<dbname>, $connec);

    $sql = "LOAD DATA LOCAL INFILE '<filepath>'
                        REPLACE
                        INTO TABLE <tablename>
                        FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
                        LINES TERMINATED BY '\r\n'
                        IGNORE 1 LINES
                        "
    ;
    mysql_query($sql);
    if(
    mysql_error()) {
        echo(
    mysql_error());
    } else {
        echo(
    "Import sucessfull data imported to mysql table.");
    }
    ?>

    Seocnd Way to upload and Import


    upload.php
        <form action="import.php" method="post" enctype="multipart/form-data">
    Upload Text File: <input type="file" name="file" />
    <input type="submit" name="Submit" value="Submit" />
    </form>
    import.php
    <?php
    $connec
    = mysql_connect(<hostname>,  <username>,<password>);
    mysql_select_db(<dbname>, $connec);
    if (
    $_FILES["file"]["type"] == "text/plain")
      {
      if (
    $_FILES["file"]["error"] > 0)
        {
        echo
    "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
      
    $sql = "LOAD DATA LOCAL INFILE '".$_FILES["file"]["tmp_name"]."'
                        REPLACE
                        INTO TABLE <tablename>
                        FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
                        LINES TERMINATED BY '\r\n'
                        IGNORE 1 LINES
                        "
    ;
    mysql_query($sql);
    if(
    mysql_error()) {
        echo(
    mysql_error());
    } else {
        echo(
    "Import sucessfull data imported to mysql table.");
    }
        }
      }
    else
    {
        echo
    "Invalid file type. Please make sure it is a text file.";
    }

    ?>
    5
    Average: 5 (1 vote)

    incompatible character encodings problem is due to two three reasons first of all check if you are using mysql2 gem

    if not then gem 'mysql2' in your gem file run bundle install and change the adapter to mysql2 in database.yml file.

    it this doesn't work then you can specify default encoding in config/environments.rb file

    Encoding.default_external = Encoding::UTF_8
    Encoding.default_internal = Encoding::UTF_8

    before Application.initialize statement

    5
    Average: 5 (1 vote)
    To install refinerycms with mysql support for refinerycms >= 2.0.0
    mohit@ubuntu$ refinerycms <nameofapp> -d mysql
    5
    Average: 5 (1 vote)
    To create new user in mysql using ssh connect to mysql with root user then follow the steps
    1. Create new user
    mysql> CREATE USER mohit@localhost IDENTIFIED BY '****';

    2. Grant previleges to newly created user
    mysql> GRANT ALL PRIVILEGES ON *.* TO mohit@localhost
    5
    Average: 5 (1 vote)
    To do this: Put Following code in routes.rb
      ActionController::Routing::Routes.draw do |map|
        blogs = BlogPost.all.collect{|p| p.cached_slug}.join("|")
        unless blogs.blank?
          map.connect ':id', :controller => 'redirect', :action => 'index', :requirements => { :id => Regexp.new(blogs) }
        end
      end

    It redirects only when path matches with old blog post paths
    Create a controller redirect have following code
    class RedirectController < ApplicationController
      helper_method :check_blog, :check_pages
      def index
        if check_blog
          redirect_to check_blog
        else
          redirect_to root_url
        end
      end
      def check_blog
        conn = ActiveRecord::Base.connection
        id = params[:id]
        sql = "SELECT count(id) as cnt FROM blog_posts WHERE cached_slug='#{id}'"
        res = conn.execute(sql)
        result = res.fetch_row.first
        if result != "0"
          return "/blog/" + id
        else
          return false
        end 
      end

    end

    where cached_slug contains old urls that is to be redirected to new one it match and send proper redirection
    5
    Average: 5 (1 vote)
    To fix this reinstall ruby with openssl
    $ rvm reinstall 1.9.2 --with-openssl-dir=/usr/local
    If the above does'nt fix then try
    $ rvm pkg install openssl
    $ rvm reinstall 1.9.2 --with-openssl-dir=$rvm_path/usr
    5
    Average: 5 (1 vote)
    To install blog in refinerycms follow these steps
    1.  Include refinerycms-blog in gemfile

    gem 'refinerycms-blog', '~> 1.6.2'

    2. Run bundle install

    ubuntu@rails$:  bundle install

    3. Next install blog plugin

    ubuntu@rails$: rails generate refinerycms_blog


    4. Run database migration

    ubuntu@rails$: rake db:migrate


    Done blog is installed sucessfully
    5
    Average: 5 (1 vote)
    To import wordpress pages and posts to refinerycms Follow the steps:
    1. First of all add gem "refinerycms-wordpress-import" to gemfile in rails

    gem 'refinerycms-wordpress-import', :git => 'git://github.com/mremolt/refinerycms-wordpress-import.git'

    2. Run Bundle install

    rails $ bundle install

    3. Next task is to export data from wordpress as xml file save the xmlfile to application root and run this is to add pages to refinerycms
    rails$ rake wordpress:reset_and_import_pages\[wordpress.xml\]

    4. If you have to import blog posts also first install refinerycms-blog and then

    rails$ rake wordpress:reset_and_import_blog\[wordpress.xml\]
    Note: To install refinerycms-blog Click here
    Any problem with data import send your feedback
    5
    Average: 5 (1 vote)
    you can fix this by forcing encoding to UTF-8 I have overridden the layouts/application.html.erb for refinerycms ubuntu:$ rake refinery:override view=layouts/application
    Go to views/layouts/application.html.erb and change

      <%= yield %>

      to


      <%= yield.dup.force_encoding(Encoding::UTF_8) %>

      Fixed encoding problem for me you can also try to change db encoding that might work for you
    5
    Average: 5 (1 vote)
    This problem is due to port already used or not properly stopped. To work this properly first find the process id and then kill it and start the server again
    Follow the steps your output come like this:

    1. mohit@ubuntu:/home/app/alpha$ netstat -tulpn | grep :3000
    (Not all processes could be identified, non-owned process info
    will not be shown, you would have to be root to see it all.)
    tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      8540/ruby
    2. mohit@ubuntu:/home/app/alpha$ kill -9 8540
    3. mohit@ubuntu:/home/app/alpha$ rails s
    => Booting WEBrick
    => Rails 3.0.11 application starting in development on http://0.0.0.0:3000
    => Call with -d to detach
    => Ctrl-C to shutdown server
    [2012-02-21 12:18:50] INFO  WEBrick 1.3.1
    [2012-02-21 12:18:50] INFO  ruby 1.9.2 (2011-07-09) [x86_64-linux]
    [2012-02-21 12:18:50] INFO  WEBrick::HTTPServer#start: pid=9210 port=3000
    5
    Average: 5 (1 vote)

    To check os name on server via ssh use following command

    [root@cl-t015-3442cl ~]# uname -a

    You can get output like this:

    Linux cl-t094-3442cl .privatedns.com 2.6.18-194.11.3.el5PAE #1 SMP Mon Aug 30 17:02:48 EDT 2010 i686 i686 i386 GNU/Linux

    5
    Average: 5 (1 vote)
    To remove mysql root password in ubuntu go to mysql command line and then remove it. To do this follow the steps 1. Open terminal and got to mysql
    mohit@ubuntu:$ mysql -h localhost -u root -p
    Enter password:
    mysql>
    2. Change the mysql password using following command
    mysql> SET PASSWORD FOR root@localhost=PASSWORD('');
    Query OK, 0 rows affected (0.03 sec)
    mysql>
    Your password sucessfully changed
    5
    Average: 5 (1 vote)
    This is a date format problem with gems so to fix this run following command
      root@ubuntu$ sudo sed -i 's/ 00:00:00.000000000Z//' /var/lib/gems/1.8/specifications/*
    5
    Average: 5 (1 vote)
    to validation multiple radio buttons using jquery use following code

    HTML Code

    <form name="radiotest" id="sitefrm">
    <div class="genderoption">
      <label><input type="radio" name="gender" class="gender"> Male </label>
      <label><input type="radio" name="gender" class="gender"> Female </label>
    </div>
    <div class="joboption">
      <label><input type="radio" name="job" class="job"> jQuery Developer </label>
      <label><input type="radio" name="job" class="job"> Drupal Developer </label>
      <label><input type="radio" name="job" class="job"> Ruby Developer </label>
      <label><input type="radio" name="job" class="job"> Wordpress Developer </label>
    </div>
    <input type = "submit" name="submit" value="Submit">
    </form>

    Jquery Code

    <script type="text/javascript">
    $(document).ready(function() {
    $('#sitefrm').submit(function() {
              var ret = true;
              var errs = 0;
              if(!$("input.gender:checked").val()) { alert("Please select gender"); errs++; }
              if(!$("input.job:checked").val()) {alert("Please select your job"); errs++; }
              if(errs > 0) {
                ret = false;
              }
              return ret;
          });
    });

    Note: I have user "input.gender:checked" there we can also use "input[@name=gender]:checked" but i found first one more accurate
    </script>
    5
    Average: 5 (1 vote)

    Follow there steps to always show the sidebar in ubuntu

    1. First of all install CompizConfig Settings Manager
    http://apt.ubuntu.com/p/compizconfig-settings-manager

    2. Open the manager type about:config in ubuntu search and open. To open ubuntu search you can use shortcut ALT+F2 from keyboard

    3. In behaviour tab on the opened window you see hide launcher dropdown select "never" from there and you are done

    5
    Average: 5 (1 vote)
    We can install these things simply using few commands on terminal. Follow these steps
    1. Login with root user and open terminal
    root@ubuntu:/ apt-get install mysql-server mysql-client

    Enter root mysql password two times

    2. Next to install apache2

    root@ubuntu:/ apt-get install apache2

    After installation verify if your sever working correctly visit http://127.0.0.1/ in browser

    3. Next to install PHP

    root@ubuntu:/  apt-get install php5 libapache2-mod-php5

    4. After installation restart apache2

    root@ubuntu:/  /etc/init.d/apache2 restart

    5. Go to server root and check php is working fine

    root@ubuntu:/var/www# vi test.php
    type following code
    <?php
    print phpinfo();
    ?>

    :wq
    root@ubuntu:/var/www#

    Go to address http://127.0.0.1/test.php Check the output its fine done php is installed correctly

    6. Integrating mysql with PHP

    root@ubuntu:/var/www#apt-get install php5-mysql

    Note: You can install other extensions like php5-mysql to check the available extensions
    root@ubuntu:/var/www# apt-cache search php5

    7. Restart apache2 again

    root@ubuntu:/var/www# /etc/init.d/apache2 restart

    8. Install phpmyadmin

    root@ubuntu:/var/www# apt-get install phpmyadmin
    5
    Average: 5 (1 vote)
    You can import export mysql database via ssh follow the steps mentioned below 1. Login to ssh using ssh client putty or via (ubuntu)terminal 2. To export/Import use following commands
    mohit@mohitsharma.net$ mysqldump -h servername -u user -p dbname > dbname.sql
    Hit Enter (Prompted for database password)

    Enter password: <type password and enter passord not visible>

    mohit@mohitsharma.net$



    where servername =  localhost or the name or server
                user =  database username
                dbname = database name

    For import there is are two changes (> replaced by < and mysqldump with mysql) also please upload sql file in current directory

    mohit@mohitsharma.net$ mysql -h servername -u user -p dbname < dbname.sql
    Hit Enter (Prompted for database password)
    5
    Average: 5 (1 vote)

    This error comes due to incorrect temporary directory setup. You can fix this by setting correct tmp directory from drupal file system

    Administer > Site configuration > File system and setup correct tmp directory path there

    /tmp or d:\wamp\tmp etc.

    Note: This error comes when we use database from different server exported to different server as the path stored in database and that does not match the new server configuration

    5
    Average: 5 (1 vote)
    Drupal 7 has imagecache in its core so this function can be replaced by theme_image_style For example:
    <?php print theme('imagecache', '<presetname>', '<pathtoimage>', '<alt>', '<title>'); ?>
    Can be Written as
    <?php
    print theme('image_style', array('style_name' => '<presetname>', 'path' => '<pathtoimage>', 'alt' => '', 'title' => '', 'width' => '', 'height' => '')));
    ?>
    5
    Average: 5 (1 vote)

    Check the detailed explanation here

    http://help.godaddy.com/article/4057

    5
    Average: 5 (1 vote)
    To show result from first 5 or 10 records on the basis of some condtion from mysql database use following query:
    SELECT id FROM
    (SELECT id, status FROM data
    ORDER BY created_at DESC
    LIMIT 0, 5)  AS t WHERE t.status = 'failed'

    Where data is table name and status is field name contains status "failed" or "success" if there are 5 consecutive it will display 5 records otherwise failed-success in last 5 records

    Note: You can change the limit from 5 to 10, 20 etc depends upon your requirement
    5
    Average: 5 (1 vote)
    You can do this by using following code
    puts YAML::dump(<object or array name to print>)
    5
    Average: 5 (1 vote)
    To get mysql dump via ssh use following command
    Terminal $ mysqldump -h mysqlhost -u username -p databasename > dumpfile.sql

    Enter mysql Password:
    0
    To setup phpmyadmin on site upload phpmyadmin from any wamp installation found in www/app directory or you can download phpmyadmin from http://www.phpmyadmin.net/home_page/downloads.php After uploading create config.inc.php from config.sample.inc.php and go to the directory http://www.mohitsharma.net/phpmyadmin/ like this you will be prompted for username and password in this case
    $cfg['Servers'][$i]['auth_type']     = 'cookie';
    if you have to access directly you can add auth_type as
    $cfg['Servers'][$i]['auth_type']     = 'config';
    and add the information in configuration file
    5
    Average: 5 (1 vote)

    form_for is used for model fields and its assign proper actions on the basis of new post and edit post to the form

    Where form_tag is used in case when you have to render fields other than model or your custom fields form

    0
    To access server via ssh in ubuntu 1. Open terminal first 2. Write following command
    $ ssh <serverusername>@<serverhost>

    Is give some message connection can't established type 'yes' to continue

    then enter password

    your ssh password:

    <serverusername>@<serverhost>$

    You are connected now To start mysql prompt

    <serverusername>@<serverhost>$mysql -h <mysqlhost> -u <mysqluser> -p

    press enter then enter password:

    mysql>

    if you see the above prompt you are connected

    where,
       <serverusername> ssh user name
       <serverhost> hostname
       <mysqlhost> mysql hostname
      <mysqluser> mysql username

    Note: when you type password characters will not be shown to you
    5
    Average: 5 (1 vote)
    To add new field to a table open terminal window go to rails app directory
    $ rails generate migration <fieldname>_to_<tablename> <fieldname>:<datatype>

    $ rake db:migrate //You are done


    Where,
               <fieldname> name of field
                <tablename> name of table to add field
                <datatype> datatype of field (string, text, integer, float etc)
    5
    Average: 5 (1 vote)
    To show blank selection option in rails application form select use the code below where @agencies shows the whole list and :include_blank add a blank in dropdown
      

    <%= select_tag "agency", options_from_collection_for_select(@agencies, "id", "name", agency),  :style => "width:100px;", :include_blank => true, :selected => nil %>
    5
    Average: 5 (1 vote)
    To install git completely on ubuntu use following command on terminal
    sudo apt-get install git-core git-gui git-doc
    5
    Average: 5 (1 vote)

    To start script console in ruby on rails use following commands

    Use ruby "script/console" for rails version earlier then 2.3.x

    User "rails console" for rails version 3.x

    Note: Don't use double quotes with the commands

    5
    Average: 5 (1 vote)
    To install lamp server:
    Open Terminal >

    $ sudo apt-get install lamp-server^
    To install Filezilla:
    Open Terminal>

    $ sudo aptitude install filezilla

    and start from Application>Internet>Filezilla
    0
    You can show search block in drupal 7 by using dashboard module its enabled by default. You can go to dashboard and select the search form block configure it and show it in the region where you need it. If you need to show it programatically You can use following code
    <?php
              $searchblock
    = module_invoke('search', 'block_view', 'search');
              print
    render($searchblock );
    ?>
    5
    Average: 5 (1 vote)
    To count checked checkboxes using jquer use following code for example
    <ul class="departments">
    <li><label>Drupal Development<input type="checkbox" name="department[]" /> </label></li>
    <li><label>Wordpress Development<input type="checkbox" name="department[]" /></label></li>
    <li><label>Joomla Development<input type="checkbox" name="department[]" /></label></li>
    <li><label>Jquery Development<input type="checkbox" name="department[]" /></label></li>
    <li><input type="submit" name="count" value="count" id="edit-count" /></li>
    </ul>

    Jquery code to count checked elementson clicking count button

    <script type="text/javascript">
    $(document).ready(function() {
    $('#edit-count').click(function() {
      var count = $('.departments input:checked').length;
      alert(count);
    });
    });
    </script>
    5
    Average: 5 (1 vote)
    To solve the problem of mysql_fetch_array(): supplied argument is not a valid MySQL result resource You can use query like this no resource error then
    <?php

    $count_query
    = @mysql_query("select pid from portfolio where category=". $cid);
    $pids = array();
    if (
    $count_query) {
      while (
    $count_result = @mysql_fetch_array($count_query)) {
       
    $pids[] = $count_result['pid'];
      }
    }
    ?>
    5
    Average: 5 (1 vote)
    To validate email using jquery you can use following script
    $(document).ready(function() {
    $('#comment-submit').click(function() {
        var emailaddress = $('#comment-email').val();
        var emailexp = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if (emailaddress == '')  {
                  alert('Please enter email.');
                  $('#comment-email').focus();
                  return false;
                }
                else if(!emailexp.test(emailaddress)) {
                  alert('Please enter valid email address.');
                  $('#comment-email').focus();
                  return false;
                 }
                 else {
                   return true;
                 }
             });
    });
    where "#comment-submit" is id of button when it is clicked email text box "#comment-email" will be validated first before submission
    5
    Average: 5 (1 vote)
    To remove special characters from string use preg_replace like this
    <?php
      $mydata
    = 'this is @ test & Strings';

     
    $mydata = preg_replace("/[^a-zA-Z0-9s]/", "", $mydata);

     
    //print $mydata; will output "thisistestStrings"
    ?>
    5
    Average: 5 (1 vote)
    Put this function in template.php of your theme file of drupal
    <?php

    function <themename>_menu_local_task($link, $active = FALSE) {
     
    $testlink = trim(strip_tags($link));
        if (
    $testlink == 'Find Experts') {
        return
    '<li style="display:none;">'. $link ."</li>\n";
        }
        else {
        return
    '<li '. ($active ? 'class="active" ' : '') .'>'. $link ."</li>\n";
        }
    }

    ?>
    0

    You can check the detailed description here

    http://linuxadminzone.com/quickly-check-your-mail-server-using-telnet-ma...

    0
    To restart services on ubuntu server user service restart command For example you have to start mail server use following command in ssh
      service postfix restart
    5
    Average: 5 (1 vote)
    To check on services on ubuntu server Login to ssh via Putty run following command :
    service --status-all
    This will list all the services currently running on the server
    5
    Average: 5 (1 vote)
    SELECT nid
    FROM node n
    INNER JOIN (
    SELECT max( tn.nid ) AS nids
    FROM term_node tn
    INNER JOIN term_data td
    WHERE td.tid = tn.tid
    AND td.vid =1
    GROUP BY tn.tid
    ) t ON n.nid = t.nids
    ORDER BY n.created
    5
    Average: 5 (1 vote)

    You can convert xlsx to xls online on following website please select and upload file then select the converted format enter your email id the converted file download link sent to the mail

    http://www.zamzar.com/

    5
    Average: 5 (1 vote)
    Replace myvideo.swf with the path to you flash movie if you have to display youtube video simply replace myvideo.swf with video path
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="660" height="449" id="myvideo" align="left">
        <param name="movie" value="myvideo.swf"/>
        <!--[if !IE]>-->
        <object data="myvideo.swf" width="660" height="449" type="application/x-shockwave-flash" >
            <param name="movie" value="myvideo.swf"/>
        <!--<![endif]-->
            <a href="http://www.adobe.com/go/getflash">
             Download Flash Player
            </a>
        <!--[if !IE]>-->
        </object>
        <!--<![endif]-->
    </object>
    5
    Average: 5 (1 vote)
    You can user LIKE in db_query in drupal using following way:
    Generally you use %s in db_query in drupal but with like you have to use %%s So a demo query with like looks like this in drupal:
    <?php
    db_query
    ('select name from {my_table} where name like "%%%s%"', $name);

    ?>
    0

    To integrate vbulleting with drupal use following module

    http://drupal.org/project/drupalvb

    It supports upto vbulletin 3.8

    If you have to integrate vbulletin 4 download the patched module below

    AttachmentSize
    drupalvb.zip Patched Drupal32.55 KB
    5
    Average: 5 (1 vote)
    There are many ways to check if an element exists or not using jquery:
    if ($('#elementid').length > 0) {
       //your jquery code here
    }

    or simply
    if ($('#elementid').length) {
       //your jquery code here
    }


    Also

    if ($('#elementid').size()) {
       //your jquery code here
    }
    5
    Average: 5 (1 vote)
    You can use the below code with the css to highlight keywords in the search results
    Css Styles:
    <style type="text/css">
    .search_highlight {
      background-color:#ffffcc;
    }

    PHP Code to highlight search results
    <?php
    $keywords
    = <SEARCH KEYWORD>; //Keyword to highlight.
    $searchresults = <RETURNED STRING>; //Result of search.
    preg_replace("|($keywords)|Ui", "<span class='search_highlight'>$1</span>", $searchresults);
    ?>
    5
    Average: 5 (1 vote)
    Use the following code to show the followers list you can theme your output by using suitable HTML inside foreach()
    <?php
    //Replace <SCREENNAME> with twitter screen name
    $twitter_url = "http://api.twitter.com/1/statuses/followers/<SCREENNAME>.json";

    $chrequest = curl_init();

    curl_setopt($chrequest, CURLOPT_URL, $twitter_url);

    curl_setopt($chrequest, CURLOPT_RETURNTRANSFER, 1);

    $curloutput = curl_exec($chrequest);

    curl_close($chrequest);

    $res = json_decode($curloutput, true);
    $output = '<ul>';
    foreach(
    $res as $followers){

    $thumbnail = $followers['profile_image_url'];

    $profile_path = $followers['screen_name'];

    $twittername = $followers['name'];

    $output .= '<li><a title="'. $twittername .'" href="http://www.twitter.com/'. $profile_path.'"><img class="twit-pic" src="'. $thumbnail .'" border="0" alt="" width="40" /></a></li>';

    $output = '</ul>';

    print
    $output;
    ?>
    5
    Average: 5 (1 vote)
    To create custom node in drupal via code follow the steps:
    <?php
        $node
    = new stdClass();
       
    $node->type = 'job'; //Content Type of node
       
    $node->status = 1;
       
    $node->created = time();
       
    $node->changed = time();
           
    $node->title = "Custom Node";
           
    $node->body = "this is test job description";
          
    //In case of cck fields $node->job_company[0]['value'] = "Test"; like this
       
    node_save($node);
    ?>

    To update custom node in drupal via code follow the steps:
    <?php
           
    //In case of update we have nid so that we can load earlier node change values and then save
       
    $node = node_load($earlier_nid);
           
    $node->title = "Custom Node";
           
    $node->body = "this is test job description";
           
    //In case of cck fields $node->job_company[0]['value'] = "Test"; like this
       
    node_save($node);
    ?>
    5
    Average: 5 (1 vote)
    To install openoffice writer on ubuntu server login via ssh and run following command:
    root@www:~# apt-get install openoffice.org-writer

    //Command is apt-get install openoffice.org-writer
    It will install the package on the server
    5
    Average: 5 (1 vote)
    To embed pdf file in html you can use embed and iframe tag in following way
    Using embed tag:

    <embed src="http://www.mohitsharma.net/test.pdf#zoom=63&navpanes=0&toolbar=0" style="width:620px;height:770px;" type="application/pdf" name="plugin"></embed>
    Where #zoom=60 , toolbar=0 are the parameters to add them to adobe reader settings

    You can check list of parameters here
    Using iframe tag:

    <iframe src="http://www.mohitsharma.net/test.pdf" style="width:620px;height:800px;"></iframe>
    0
    To detect browser in php follow the steps:
    1. Download the class file Click Here
    2. Create Browser class object and call getBrowser() function.

    <?php
    include 'Browser.php';
    $getbrowser= new Browser();
    $browser_name = $getbrowser->getBrowser();
    $browser_version = $browser->getVersion();

    //You can use $browser_name and $browser_version in conditions to excute code in specific browsers
    ?>
    5
    Average: 5 (1 vote)
    To get base path in jquery from drupal is a simple process you can do this in following way
    <?php
    //In a custom module create a hook_init()
    function testcustom_init() {
     
    //this will add base path to drupal object
     
    drupal_add_js( array( 'basepath' => base_path() ), 'setting' );
    }

    ?>
    To access base path in jquery you can simply use:
      var path = Drupal.settings.basepath;
    5
    Average: 5 (1 vote)
    enctype in drupal form is specified where we have to upload files or media In drupal form you can specify in following way
    <?php
    function resumeupload_test_form() {
     
    $form['field_resume'] = array(
       
    '#type' => 'file',
       
    '#title' => t('CV Uploader'),
       
    '#required' => TRUE,
       
    '#size' => 22,
      );
     
    $form['upload'] = array(
       
    '#type' => 'submit',
       
    '#value' => t('Upload'),
      );

     
    //This is how enctype is specified
     
    $form['#attributes'] = array('enctype' => "multipart/form-data");
      return
    $form;
    }

    ?>
    5
    Average: 5 (1 vote)
    Base path in drupal can be added by using base_path() function You can do this in following way
    <?php

    $imagepath
    = base_path() . path_to_theme() .'/images/test.png';

    //$imagepath gives the path to the image in you drupal theme images folder

    echo '<img src="'. $imagepath .'" alt="test image" title ="test image">';

    ?>
    To include css and javascript in template files from theme
    <?php
    <link href="<?php print base_path(). path_to_theme();?>
    /css/styles.css" rel="stylesheet" type="text/css" />
    <script src="<?php print base_path(). path_to_theme();?>/js/test.js"></script>
    ?>
    5
    Average: 5 (1 vote)
    To create template file for form in drupal you can use hook_theme() For Example: Create a custom module i have created a module name custom_profile so hook is replaced by custom_profile
    <?php
    /**
    * Implementation of hook_theme()
    */
    function custom_profile_theme() {
      return array(
       
    'custom_profile_publications' => array(
         
    'arguments' => array('form' => NULL),
         
    'template' => 'create-publication',
        ),
      );
    }
    // Where custom_profile_publications is form id
    // arguments form is the argument passes to the tpl file
    // create-publication is the tpl file created inside the module tpl file named as create-publication.tpl.php
    // user $form and drupal_render() in the template file
    ?>
    5
    Average: 5 (1 vote)
    To increment/decrement date in php you can use simple process as follows:
    <?php
    $your_date
    = '2011-05-20';

    //You need to increment it by 2 day

    //Convert to time stamp first

    $your_date_ts = strtotime($your_date);

    //Increment By 2 Day

    $your_date_dt = strtotime('+2 day', $your_date_ts);

    echo
    date('Y-m-d', $your_date_dt);

    //Increment By 2 Week

    $your_date_tw = strtotime('+2 week', $your_date_ts);

    echo
    date('Y-m-d', $your_date_tw);

    //Similar process is followed for decrement just user -2 day or -2 week in place of +1 day or +1 week

    //Decrement By 2 Day

    $your_date_dd = strtotime('-2 day', $your_date_ts));

    echo
    date('Y-m-d', $your_date_dd);

    //Decrement By 2 Week

    $your_date_wd = strtotime('-2 week', $your_date_ts);

    echo
    date('Y-m-d', $your_date_wd);
    ?>
    5
    Average: 5 (1 vote)
    You can do this by simply using following function
    <?php

    $user_ip
    = ip_address();

    ?>
    For more information check: http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/ip_add...
    0
    You can do this in following way using the following javascript function pass the phone number you can use your custom code instead of alert messages
    function val_phone_number (number) {
        var regexp = /^\+(?:[0-9] ?){6,14}[0-9]$/;
        if (regexp.test(number)) {
           alert("Phone number is valid");
        } else {
           alert("Phone number is invalid");
        }
    }
    Note: The number starts with (+) plus sign, followed by the country code and number. For e.g : +65 6538 1111
    5
    Average: 5 (1 vote)
    You can do this using jQuery in following way:
    // First method
    $('#edit-country-id').is(':checked');

    // where edit-country-id is id of element need to be checked

    // Second method
    $('#countryinfo').attr('checked');

    // where countryinfo is id of element need to be checked
    0
    You can print gmap using javascript by using following procedure. First of all create html file printmap.html and place it in the root directory or on the path that is accessible.
    <script type="text/javascript">
      var map_content =  window.opener.document.getElementById("mapDiv");
      document.write(map_content.innerHTML);
      window.print();
    </script>
    On the page where we have gmap place a link or button as needed I'm using simple link here mapDiv is the div id in which the map is placed
    <a href="javascript:void(0);" class="printmap" onclick="window.open('/printmap.html')">Print This Map</a>
    5
    Average: 5 (1 vote)
    You have to create a custom module for it. Create a upload form first:
    <?php
     
    function modulename_upload_form(){
       
    $form['#attributes'] = array('enctype' => 'multipart/form-data');
       
    $form['data_file'] = array(
           
    '#type' => 'file',
           
    '#title' => t('Select File')
        );
       
    $form['submit'] = array(
           
    '#type' => 'submit',
           
    '#value' => t('Upload');
        );
        return
    $form;
      }
    ?>
    Then Create Form Submit Function which can do the actual process
    <?php
    function modulename_upload_form_submit($form, &$form_state) {
    //You can define these limitations as per your requirements 
     
    $limitations = array ('file_size' => 1000000, 'extensions' => 'jpg gif pdf', 'resolution' => '', 'user_size' => '') ;

     
    $validations = array(
       
    'file_validate_extensions' => array($limitations['extensions']),
       
    'file_validate_image_resolution' => array($limitations['resolution']),
       
    'file_validate_size' => array(
           
    $limitations['file_size'],
           
    $limitations['user_size']
        ),
      );

     
    // Now this fuinctions save the file to files directory If some other path you can mention instead
     
    if ($file = file_save_upload('data_file', $validations, file_directory_path())) {
       
    // Here we can get $file object which can be used to save path into database or do some other processing
     
    }
    }
    ?>
    0

    Steps to do this:

    1. Download and install following module http://drupal.org/project/auto_nodetitle

    2. After installation go to admin/content/types and edit appropriate content type

    3. You can see a fieldset Automatic title generation select the radio button automatically generate title and hide title field

    4. That it Done !!

    5
    Average: 5 (1 vote)
    We can find nid from node internal path by using following function $node = menu_get_object(); We can specify the path by using following syntax
    <?php
    menu_get_object
    ($type = 'node', $position = 1, $path = '/student/2010/testing');
    ?>
    0
    You can check if div exists on the web page by checking its length via jquery if ( $("#mydiv").length ) { //Do appropriate action here. }
    5
    Average: 5 (1 vote)
    You can do this by using jquery toggle function Here is the Html
    <a href="#" id="showmenu">Click Here</a>
    <div id="content_div" style="display:none;position:absolute;">
    <ul>
      <li>Link 1</li>
      <li>Link 2</li>
      <li>Link 3</li>
      <li>Link 4</li>
      <li>Link 5</li>
      <li>Link 6</li>
      <li>Link 7</li>
      <li>Link 8</li>
    </div>
    Here is the js code:
    <script language="javascript">
    $('#showmenu').click(function() {
      $('#content_div').toggle('slow');
    });
    </script>
    Note: Please include Jquery.js
    4
    Average: 4 (1 vote)
    The code under can be used to create new user. We can also add profile fields values if we are using profile module there. Also extra role can be assigned to the user by mentioning role id and the name of role in the roles array
    <?php
      $name
    = 'mohit';
     
    $password = '****';
     
    $email = 'mytestemail@test.com';
     
    $firstname = 'Mohit'; //Only if profile is used
     
    $lastname = 'Sharma'//Only if profile is used
     
    $siteuser = array(
       
    'name' => $name,
       
    'mail' => $email,
       
    'status' => 1,
       
    'pass' => $password,
       
    'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',
                        
    4 => 'Customer'), //Extra Role
       
    'profile_firstname' => $firstname, //Profile fields If we are using
       
    'profile_lastname' => $lastname//Profile fields If we are using
     
    );
     
    $newuser = user_save('', $siteuser);

     
    //Login after user is created
     
    $myaccount = user_authenticate($siteuser);
    ?>
    5
    Average: 5 (1 vote)
    You can do that using following code in drupal : In the below code I'm saving the position field in Work History Category the below function is custom form submit function you can create the form
    <?php
    function {modulename}_change_submit($form, &$form_state) {
     
    $uid $form_state['values']['uid'];
     
    $siteuser = user_load(array('uid' => $uid));
     
    profile_load_profile($siteuser);
     
    $profile_user = (array)$siteuser;
     
    $new_user_edit['profile_position'] = $form_state['values']['position'];
     
    profile_save_profile($profile_user, $siteuser, "Work History");
    }
    ?>
    0
    pageX and pageY didn't work in IE browsers as IE missing these attributes so we need to add those manually as it is called it will not give any error. So in IE we have clientX and clientY we are using that to add pageX and pageY to event.
    function fixIEevents(ev) {
      if ( ev.pageX == null && e.clientX != null ) {
        var bd = document.body;
        ev.pageX = ev.clientX + (ev && ev.scrollLeft || bd.scrollLeft || 0);
        ev.pageY = ev.clientY + (ev && ev.scrollTop || bd.scrollTop || 0);
      }
      return e;
    }
    you can call fixing function like this

    event  = fixIEevents(event);
    5
    Average: 5 (1 vote)
    Theme is not able to load properly and its showing this error alternatively use following jquery code in the head of the document.
    <script language="javascript">
    $(document).ready(function() {
    Galleria.loadTheme('JavaScript/galleria.classic.js');
    </script>
    });
    0

    There are two ways:

    FIRST METHOD
    To do this you can create a page.tpl for the page by copying page.tpl.php and renaming it like page-
    .tpl.php and remove $messages variable from the page tpl file.

    SECOND METHOD

    Alternate and simple way is to add code in theme_preprocess_page(&$vars) in template.php

    if(arg(0) == 'thanks') {
    unset($vars['messages']);
    }

    0
    Use following jquery code to do so?
    <script language="javascript">
    $(document).ready(function () {
        $('.drop_div').hover(function(){
          var mouse_over=true;
        }, function(){
          var mouse_over=false;
        });

        $("body").mouseup(function(){
          if(! mouse_over) $('.drop_div').hide();
        });
    });
    </script>
    Any problem in implementation contact us
    5
    Average: 5 (1 vote)

    Check the list of drupal seo modules here

    http://www.leveltendesign.com/article/drupal-seo-modules

    0
    It seems that there will be some issue with line height in safari. Try by making elements margin 0. like
    .check p {
      margin:0px;
    }
    or
    h1,h2 {
      margin:0px;
    }

    or you can write seperate css styles for safari with in following block in your css file

    @media screen and (-webkit-min-device-pixel-ratio:0) {
       /* Your Safari Specific css goes here */
    }

    Note: The above block will also work for Opera
    4
    Average: 4 (1 vote)

    There may be many reasons of favicon not showing in IE you don't have proper favicon.ico file or due to path problem.

    So generate your favicon icon from here
    http://www.favicon.cc/
    You can upload image and generate and download icon from here In drupal you can upload from theme configuration Clear the IE cache and site cache If it still does'nt work download and install http://drupal.org/project/favicon

    Another method you can give absolute path for icon and put icon in your root directory

    <link rel="shortcut icon" href="http://www.uoogames.com/favicon.ico" />

    Remember remove shortcut icon from theme configuration if you are adding this code in page tpls head section

    4
    Average: 4 (1 vote)

    You need to use modalframe_close_dialog($args);

    where $args is the array containing list of arguments you need to pass to the script. Also if you want to reload the parent window you have to user window.location.reload(); in your submitcallback function

    4
    Average: 4 (1 vote)
    You can create node by using your own function to call the node form inside it anywhere on drupal pages.
    <?php
    /**
    * Replace these values in your code
    * <type> => Content type type.
    * <modulename> => Name of module.
    */
    function <modulename>_<type>_node_form() {
      global
    $user;
     
    module_load_include('inc', 'node', 'node.pages');
     
    $node = array(
       
    'uid' => $user->uid,
       
    'name' => $user->name,
       
    'type' => '<type>',
      );
      return
    drupal_get_form('<type>_node_form', $node);
    }
    /**
    * Removing Extra fields if you want to remove those using form alter.
    * You can add other fields also
    */
    function <modulename>_form_alter($form_id, &$form) {
       if (
    '<type>_node_form' == $form_id) {
         if (
    $_GET['q'] != 'node/add/<type>') {
          
    $remove_fields = array(
            
    'menu',
            
    'body_filter',
            
    'attachments',
           );
           foreach (
    $remove_fields as $field) {
             if (isset(
    $form[$field])) {
               unset(
    $form[$field]);
             }
           }
         }
       }
    }
    ?>
    5
    Average: 5 (1 vote)
    You can get country list array using following function :
    <?php
    //Simple array of countries
    $list = location_get_iso3166_list(); //Defined inside location.inc

    //Options list to use in form
    $options = array_merge(array('' => t('Please select'), 'xx' => t('NOT LISTED')), location_get_iso3166_list());

    $form['yourcountry'] = array(
     
    '#type' => 'select',
     
    '#title' => t('Your Country'),
     
    '#options' => $options,
    );
    ?>
    5
    Average: 5 (1 vote)
    You can use the following code:
    var mouse_inside_div = false; //globally declared

    $(document).ready(function()
    {
        $('#div_id').hover(function(){   
            mouse_inside_div=true;
        }, function(){
            mouse_inside_div=false;
        });

        $('body').mouseup(function(){
            if(! mouse_inside_div) $('#div_id').hide();
        });
    });


    where #div_id is used as id of the div to hide when clicked outside it
    5
    Average: 5 (1 vote)
    You can create download link in many ways one of the way is as below:
    Create a file download.php like below
    <?php
      
    // The file path where the file exists
      
    $filepath = "http://mohitsharma.net/downloads/".$_GET['filename']."";
      
    header("Pragma: public");
      
    header("Expires: 0");
      
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      
    //setting content type of page
      
    header("Content-Type: application/force-download");
      
    header("Content-Disposition: attachment; filename=".basename($filepath ));
      
    header("Content-Description: File Transfer");
      
    //Read File it will start downloading
      
    @readfile($filepath);
     
     
    ?>
    Use following link to download
    <a href="http://mohitsharma.net/download.php?filename=test.doc">Download</a>
    5
    Average: 5 (1 vote)

    You can skip form validation on drupal forms using skip_validation module

    http://drupal.org/project/skip_validation

    5
    Average: 5 (1 vote)

    Processing image with jquery

    http://blogfreakz.com/tutorial/image-processing-application-with-jquery/

    5
    Average: 5 (1 vote)
    You can use hook_forms($form_id) to do this You can call forms using this code with passing data to it
    <?php
    function hpsolan_forms_page($data = array()) {
      for (
    $i=0; $i < count($data); $i++) {
       
    $output  = drupal_get_form("hpsolan_message_form_" . $i, $data[$i]);
      }
      return
    $output;
    }
    ?>
    Use hook_forms() if form does not found it will look here
    <?php
    function hpsolan_forms($form_id) {
     
    $forms = array();
      if (
    strpos($form_id, 'hpsolan_message_form_') === 0) {
       
    $forms[$form_id] = array(
         
    'callback' => 'hpsolan_message_form',
        );
      }
      return
    $forms;
    }
    ?>
    The orignal form which is called
    <?php
    function hpsolan_message_form($form_state, $thing) {
     
    $form = array();

     
    $form['to'] = array(
       
    '#type' => 'textfield',
       
    '#title' => t('To'),
      );
     
    $form['message'] = array(
       
    '#type' => 'textarea',
       
    '#title' => t('Message'),
       
    '#cols' => 80,
       
    '#rows' => 5,
      );
      return
    $form;
    }
    ?>
    5
    Average: 5 (1 vote)

    You can handle timezone using date module

    Check it at following link

    http://drupal.org/node/291799

    5
    Average: 5 (1 vote)
    JQuery Code
    var consult_days = $('.consult_days input:checked').map(function(i,n) {
        return $(n).val();
      }).get();
    if (consult_days.length==0) {
      consult_days = 'none';
    }
    var week_days = $('.week_days input:checked').map(function(i,n) {
        return $(n).val();
      }).get();
    if (week_days.length==0) {
      week_days = 'none';
    }
    $.get("/consultation/save", {'c_days[]':consult_days, 'w_days[]':week_days},
         function(response){
           alert(response);
      });
    HTML code
    <form>
    <ul class="consult_days"><li><input type="checkbox" value="Everyday" id="edit-consult-days-Everyday" name="consult_days[Everyday]"> Everyday</li><li><input type="checkbox" value="Every Week Day" id="edit-consult-days-Every-Week-Day" name="consult_days[Every Week Day]"> Every Week Day</li><li><input type="checkbox" value="Weekends Only" id="edit-consult-days-Weekends-Only" name="consult_days[Weekends Only]"> Weekends Only</li></ul>

    <ul class="week_days"><li><input type="checkbox" value="Monday" id="edit-week-days-Monday" name="week_days[Monday]"> Monday</li><li><input type="checkbox" value="Tuesday" id="edit-week-days-Tuesday" name="week_days[Tuesday]"> Tuesday</li><li><input type="checkbox" value="Wednesday" id="edit-week-days-Wednesday" name="week_days[Wednesday]"> Wednesday</li><li><input type="checkbox" value="Thursday" id="edit-week-days-Thursday" name="week_days[Thursday]"> Thursday</li><li><input type="checkbox" value="Friday" id="edit-week-days-Friday" name="week_days[Friday]"> Friday</li></ul>
    5
    Average: 5 (1 vote)

    Check it on the following link

    http://svnbook.red-bean.com/en/1.1/ch04s04.html

    5
    Average: 5 (1 vote)
    We can change drupal theme for specific page using following function in module
    <?php
    function <modulename>_init() {
      global
    $custom_theme;
       if (
    arg(0) == '<argument1>' && arg(1) == '<argument2>') {
       
    $custom_theme = variable_get('theme_default', '0');
       
    init_theme();
      }
    }
    ?>
    where => Name of module => First argument, => Second argument. *You can add these conditions as per your requirement.
    5
    Average: 5 (1 vote)
    Use it in following way..
    <?php 
       $request
    = drupal_http_request('http://mohitsharma.net/',
        array(
    'Content-Type' => 'application/x-www-form-urlencoded'),
       
    'POST',
       
    'post1=value1&post2=value2');
    ?>
    5
    Average: 5 (1 vote)

    Check it at following link
    http://kmwoley.com/blog/?p=345

    4
    Average: 4 (1 vote)

    Check this tutorial at the following link:

    http://www.jaypan.com/blog/ubercart-creating-line-items-tutorial

    5
    Average: 5 (1 vote)
    You can do this in following way. You can add email and user picture field to profile edit form
    <?php
     
    if ($form_id == 'profile_node_form') {
          require_once
    drupal_get_path('module', 'user') .'/user.pages.inc';
        require_once
    drupal_get_path('module', 'node') .'/node.pages.inc';
        global
    $user;
         
    $form += array('account' => array());
         
    // Get the node form
         
    $node_form = drupal_retrieve_form('user_profile_form', $form_state, $user);
         
    drupal_prepare_form('user_profile_form', &$node_form, &$form_state);
       
    $form['picture'] = $node_form['picture'];
       
    $form['locale'] = $node_form['locale'];
         
    $form['email'] = array(
           
    '#type' => 'textfield',
           
    '#title' => t('E-mail address'),
           
    '#default_value' => $user->mail,
           
    '#required' => TRUE,
          );
       
    $form['locale']['language']['#type'] = 'select';
          if (
    $user->uid) {
           
    $form['#submit'][] = 'profile_user_submit';
           
    $form['#validate'][] = 'users_validate_picture';
         }
       
    $form['#attributes'] = array('enctype' => 'multipart/form-data');
       }
    ?>
    5
    Average: 5 (1 vote)

    Check it at the following link

    http://drupal.org/node/552074

    5
    Average: 5 (1 vote)
    Install weather and location module after that use following function to return weather condition on the basis of lattitude and longitude of the place.
    <?php
    function get_weather_condition($lat, $lon) {
     
    $station = weather_get_icao_from_lat_lon($lat, $lon);
     
    $config = _weather_get_config(WEATHER_DEFAULT_BLOCK, 1);
     
    $config = array_merge($config, $station);
     
    $config['real_name'] = $config['name'];
     
    $metar = weather_get_metar($config['icao']);
     
    $weather_block = theme('weather', $config, $metar);
      return
    $weather_block;
    }
    $lat = 53.139457;
    $lon = 113.3480934;
    print
    get_weather_condition($lat, $lon);
    ?>
    5
    Average: 5 (1 vote)
    Use the following function in template.php also modify the condition as per your requiement
    <?php
    function phptemplate_breadcrumb($breadcrumb) {
      if (!empty(
    $breadcrumb)) {
        if (
    $breadcrumb[1] == l(t('Search'),t('search'))) {
           return
    '';                                                               
        }
        else {
       
    // For other pages
       
    return '<div class="breadcrumb">'. implode(' &raquo; ', $breadcrumb) .'</div>';
        }
      }
    }
    ?>
    4
    Average: 4 (1 vote)

    Check the following link

    http://drupal.org/node/45295

    4
    Average: 4 (1 vote)
    You can start mysql from putty by using this command
    mysql -h localhost -u root -p ****
    -h => host -u => username -p => password
    5
    Average: 5 (1 vote)
    You Can use this function to do so
    <?php
    function remove_element($arr_content,$arr_value) {

       return
    array_values(array_diff($arr_content, array($arr_value)));

    }
    ?>
    4
    Average: 4 (1 vote)

    check it here

    https://adwords.google.com/select/KeywordToolExternal

    4
    Average: 4 (1 vote)

    Check the code on the following link

    http://javascript.internet.com/text-effects/auto-popup-window.html

    5
    Average: 5 (1 vote)
    To remove space between image and div you have to user vertical-align:top; for image
    <div class="newdiv">
    <img src="test.jpg" alt="test" title="test" style="vertical-align:top;"/>
    </div>
    0
    Use the following code
    <?php
    $domain
    = fetch_domain_name('http://www.facebook.com');
    print
    $domain; //it will output "facebook"
    function fetch_domain_name($path){
       
    $check = preg_match("/(.*:\/\/)\w{0,}(.*)\.(.*)/", $path, $output);
       
    $output[2] = str_replace(".","",$output[2]);
        return
    $output[2];
    }
    ?>
    4
    Average: 4 (1 vote)

    Check it at the given link

    http://www.easypagez.com/maps/ieworking.html

    4
    Average: 4 (1 vote)

    like this

    opener.document.getElementById("edit-fbconnect-feed").checked = true;

    5
    Average: 5 (1 vote)

    http://www.sthurlow.com/python/lesson01/

    3
    Average: 3 (1 vote)
    You can do this by using following code
    function staticNew() {
        // Check if counter is already intialized
        if ( typeof staticNew.counter == 'undefined' ) {
            // Initialize variable to 0
            staticNew.counter = 0;
        }

        // Show the static value each time the function is called
        alert(++staticNew.counter);
    }
    4
    Average: 4 (1 vote)

    check it here

    http://webdesign.about.com/od/localization/l/blhtmlcodes-fr.htm

    3
    Average: 3 (1 vote)
    Add the following code in head section of page.tpl.php
    <head>
    ---------
    ---------
    <link rel="shortcut icon" href="<?php print base_path().path_to_theme(); ?>/favicon.ico" type="image/x-icon" />
    </head>
    5
    Average: 5 (1 vote)

    Check it here

    http://codesnippets.joyent.com/posts/show/231

    more on regular expression

    http://regexlib.com/Search.aspx?k=URL

    5
    Average: 5 (1 vote)
    Here is the code used to extract emails from string or page content
    <?php
    //$string will be simple string or page content

       
    $regx="/([\s]*)([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*([ ]+|)@([ ]+|)([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,}))([\s]*)/i";            
    preg_match_all($regx, $string, $match);
    // here $match is array returned with all the email ids
    ?>
    5
    Average: 5 (1 vote)

    Check it here

    http://www.weberdev.com/get_example-4625.html

    5
    Average: 5 (1 vote)
    To get First and last day date for week of current month use following code:
    <?php
    $week_days
    = get_month_weekdays();

    $first_day_date = $week_days['start'];
    $end_day_date = $week_days['end'];
    function
    get_month_weekdays() {
     
    $wk_num get_current_week_number(time());
     
    $first = 1;   
     
    $yr = date('Y', time());
     
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
     
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
     
    $week_days['start'] = date('d-m-Y', $mon_ts);
     
    $week_days['end']  = date('d-m-Y', strtotime('+6 days', strtotime($week_days['start'])));
      return
    $week_days;
    }

    function
    check_is_leap_year($year) {
      if (((
    $year % 4) == 0 && ($year % 100)!=0) || ($year % 400)==0) {
        return
    1;
      } else {
        return
    0;
      }
    }
    function
    check_iso_week_days($yday, $wday) {
      return
    $yday - (($yday - $wday + 382) % 7) + 3;
    }
    function
    get_current_week_number($timestamp) {
      
    $d = GETDATE($timestamp);
      
    $days = check_iso_week_days($d[ "yday"], $d[ "wday"]);
       if (
    $days < 0) {
        
    $d[ "yday"] += 365 + check_is_leap_year(--$d[ "year"]);
        
    $days = check_iso_week_days($d[ "yday"], $d[ "wday"]);
       }
       else {
        
    $d[ "yday"] -= 365 + check_is_leap_year($d[ "year"]);
        
    $d2 = check_iso_week_days($d[ "yday"], $d[ "wday"]);
         if (
    0 <= $d2) {
          
    $days = $d2;
         }
       }
       return (int)(
    $days / 7) + 1;
    }
    ?>
    5
    Average: 5 (1 vote)

    Check this page and implement it to add file management functionality in tinymce

    http://drupal.org/node/186328

    4
    Average: 4 (1 vote)

    Just checkout here:
    http://www.brunildo.org/test/img_center.html

    0

    A small module can do this intergrating all the related codes in it

    you can check it and it works for you

    AttachmentSize
    wysiwyg_panels.zip1.96 KB
    4
    Average: 4 (1 vote)
    Use this custom code wheather in a page.tpl.php file or you can use it in creating a new drupal block and showing block in the particular region Place the flag images in you theme folder named like fr.png for (French) en.png for (English) etc.
    <?php
    $lang_links
    = array();
    foreach (
    language_list() as $language) {
     
    //genrate the image name
     
    $image = '/'. $language->language.'.png';
     
    //adding link information to the array
     
    $lang_links[$language->language] = array('href' => $_GET['q'], 'title' => $language->native, 'image' => $image, 'name' =>    $language->name, 'options' => array('language' => $language, 'attributes' => array('class' => 'language_link'), 'html' => true));
    }
    // Allow modules to provide translations for specific paths for the links
    drupal_alter('translation', $lang_links, $_GET['q']);
    foreach (
    $lang_links as $datalink) {
     
    $flag = '<img title="'. $datalink['name'].'" alt="'. $link['title'] .'" src="' .base_path().path_to_theme().$datalink['image'] .'"/>';
     
    $output .= l($flag, $link['href'], $link['options']);
    }
    print
    $output;
    ?>
    Note: Remember to install languages and enable the path prefix option from the configuration settings
    5
    Average: 5 (1 vote)
    Install and configure open_flash_chart api : http://drupal.org/node/193583 Install charts module : http://drupal.org/project/charts After that create you can add following code to display charts
    <?php
    function flash_chart_example()
    {
           
    $sample_chart = array(
           
    '#title'        => t('Title of chart')
           
    '#plugin'       => 'openflashchart',
           
    '#type'         => 'line2D',
           
    '#height'       => 600,         // in pixels
           
    '#width'        => 650,         // in pixels

           
    array(
              array(
    '#value' => 10, '#label' => t('Sun')),
              array(
    '#value' => 25, '#label' => t('Mon')),
              ),
            );

            return
    charts_chart($sample_chart);
    }
    ?>
    Important : Use compatible version of open-flash-chart.swf and swfobject.js
    4
    Average: 4 (1 vote)
    We can do this by using form_alter on the taxonomy form field like this :
    <?php
    if (isset($form['taxonomy'][$vid])) {
    $tree = taxonomy_get_tree($vid);
     
    $parent = array();
     
    $term_options[''] = $form['taxonomy'][$vid]['#options'][''];
      foreach (
    $tree as $term) {
       
    $obj = new stdClass();
       
    $obj->option[$term->tid] = $term->name;
      
        if(
    $ptid = $term->parents[0]) {
         
    $term_options[$parent[$ptid]][] = $obj;
        } else {
         
    $parent[$term->tid] = $term->name;
         
    $term_options[$term->name] = array();
        }
      
      }
     
    $form['taxonomy'][$vid]['#options'] = $term_options;
    }
    ?>
    Or If there is only one vocabulary associated then
    <?php
    if (isset($form['taxonomy'])) {
    $tree = taxonomy_get_tree($vid);
     
    $parent = array();
     
    $term_options[''] = $form['taxonomy']['#options'][''];
      foreach (
    $tree as $term) {
       
    $obj = new stdClass();
       
    $obj->option[$term->tid] = $term->name;
      
        if(
    $ptid = $term->parents[0]) {
         
    $term_options[$parent[$ptid]][] = $obj;
        } else {
         
    $parent[$term->tid] = $term->name;
         
    $term_options[$term->name] = array();
        }
      
      }
     
    $form['taxonomy']['#options'] = $term_options;
    }
    ?>
    4
    Average: 4 (1 vote)
    <?php
    while($irow = mysql_fetch_array($iresult, MYSQL_ASSOC))
    {
     
    $image_query = "SELECT image FROM table";
     
    $image_result = mysql_query($image_query);
     
    $image = mysql_fetch_assoc($image_iresult);

      echo
    "<img src='" . $image['image'] . "' name='comm' width='75px' height='60px' id='mainimage' />";
    }
    ?>
    3
    Average: 3 (1 vote)
    This can be done in this way:-
    <?php
    $strings
    = array('AB10BC99', 'AR1012', 'ab12bc99');
    foreach (
    $strings as $testcase) {
        if (
    ctype_xdigit($testcase)) {
            echo
    "The string $testcase consists of all hexadecimal digits.\n";
        } else {
            echo
    "The string $testcase does not consist of all hexadecimal digits.\n";
        }
    }
    ?>
    4
    Average: 4 (1 vote)
    you can do in this way:-
    <?php
    header
    ("Content-Type: image/jpeg");
    header('Expires: "' . gmdate("D, d M Y H:i:s",
     
    $expirationDate) . '"');
    imagepng($image, NULL);
    ?>
    5
    Average: 5 (1 vote)
    this can be done like this
    <?php
    class Foo {

      public function
    __isset($name) {
        echo
    "Foo:__isset($name) invoked\n";

        return
    'bar'===$name;
      }

      public function
    __get($name) {
        echo
    "Foo:__get($name) invoked\n";
        return
    'lalala';
      }
    }

    $foo = new Foo;
    var_dump(empty($foo->dummy));
    var_dump(empty($foo->bar));
    ?>
    5
    Average: 5 (1 vote)
    Use php code in field configration like this and it will display select field with option groups
    <?php
    return array(
     
    'OptGroupname 1' => array(
       
    1 => 'Option 1',
       
    2 => 'Option 2',
      ),
     
    'OptGroupname 2' => array(
       
    3 => 'Option 3',
       
    4 => 'Option 4',
      ),
     
    'OptGroupname 3' => array(
       
    5 => 'Option 5',
       
    6 => 'Option 6',
       
    7 => 'Option 7',
      ),
    );
    ?>
    0
    This can be done by using javascript onclick event handling. Here is the example.
    <input type="checkbox" value="test" title="Test Checkbox" onclick="return false;"/>
    0

    HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorerRunMRU.

    0
    Add following code in you template.php file and create a page tpl file names as page-blog.tpl.php
    <?php
    function THEMENAME_preprocess_page(&$vars) {
      if (
    $vars['node']->type == 'blog') {
       
    $vars['template_file'] = 'page-blog';
      }
    }
    ?>
    Here, THEMENAME is the name of the theme you are using
    0

    http://drupal.org/project/dynamic_persistent_menu

    install the module and show the block in the particular region with selecting the menu from the configuration of the block

    0
    In Drupal's includes/common.inc, you find at line 590. you see following code you need to replace the code as given below so just replace the above on with on at the bottom:
    <?php
    if ($errno & (E_ALL ^ E_NOTICE)) {

    //this will be changes to

    if ($errno & (E_ALL & ~E_NOTICE & ~E_DEPRECATED)) {
    ?>
    0
    When php is upgraded to version 5.3 drupal starts giving for ereg is deprecated so we have to change this ereg so that we don't encounter with the problem Change it in following way:
    <?php
    ereg
    ('\.([^\.]*$)', $this->file_src_name, $ext);
    ?>

    Change this code so that it will becomes:
    <?php preg_match('/\.([^\.]*$)/', $sourcename, $ext); ?>

    Simply we replaces the ereg function and some changes in regular expression
    In similar way we need to change function ereg_replace():
    <?php
    $sourcename_content
    = ereg_replace('[^A-Za-z0-9_]', '', $sourcename_content); ?>

    Will becomes:
    <?php
    $sourcename_content
    = preg_replace('/[^A-Za-z0-9_]/', '', $sourcename_content); ?>

    for case-insenstive:
    <?php
    eregi
    ('\.([^\.]*$)', $sourcename, $ext); ?>

    will be changed to
    <?php
    preg_match
    ('/\.([^\.]*$)/i', $sourcename, $ext);
    ?>
    0


    Use overflow:auto;

    0
    For creating ftp accounts you can use any of ftp server. Follow the instructions
    Create a FTP user group. eg: ftpaccount
    [root@hpsolan ~]#/usr/sbin/groupadd ftpaccount

    Add a new user to this group, and set the default path of that user to /home/user/.
    [root@hpsolan ~]#/usr/sbin/adduser -g ftpaccounts -d /home/user/ testuser

    Set a password for the newley created user.
    [root@hpsolan ~]#passwd testuser

    Set ownership of /home/user to the testuser and ftpaccounts.
    [root@hpsolan ~]#chown testuser:ftpaccounts /home/user

    Give Read/Write access to testuser and all members in ftpaccounts
    [root@hpsolan ~]#chmod 775 /home/user

    Edit /etc/vsftpd/vsftpd.conf file and make sure 'local_enable=YES' is uncommented.

    Restart the vsftpd service.
    [root@hpsolan ~]#/etc/init.d/vsftpd restart
    0
    Just edit .htaccess file in your Drupal root directory. For example, I added the following two lines. php_value post_max_size 100M php_value upload_max_filesize 100M php_value memory_limit 96M (this is vital for Drupal 6)
    # PHP 4, Apache 2.
    <IfModule sapi_apache2.c>
      php_value magic_quotes_gpc                0
      php_value register_globals                0
      php_value session.auto_start              0
      php_value mbstring.http_input             pass
      php_value mbstring.http_output            pass
      php_value mbstring.encoding_translation   0
    php_value post_max_size 100M
    php_value upload_max_filesize 200M
    php_value memory_limit 96M
    </IfModule>

    # PHP 5, Apache 1 and 2.
    <IfModule mod_php5.c>
      php_value magic_quotes_gpc                0
      php_value register_globals                0
      php_value session.auto_start              0
      php_value mbstring.http_input             pass
      php_value mbstring.http_output            pass
      php_value mbstring.encoding_translation   0
    php_value post_max_size 100M
    php_value upload_max_filesize 100M
    php_value memory_limit 96M
    </IfModule>
    5
    Average: 5 (1 vote)
    There are several way to insert blocks into a page in Drupal. We can use panels, or we can add a region in the theme, or we can call the blocks programmatically with php. Just As Follows
    <?php
    $block
    = module_invoke('modulename', 'block', 'view', 0);
    print
    $block['content'];
     
    ?>
    Refer http://api.drupal.org/api/function/module_invoke.
    4
    Average: 4 (1 vote)
    var text1 = $(data).text(); Simply
    0
    This might work for you
    <?php
    function <name_of_theme>_preprocess_page(&$variables, $hooks) {
      if ((
    arg(0) == 'node') && (arg(1) == 'add' || arg(2) == 'page')) {
       
    $variables['template_files'][] =  'page-node-add-page';
      }
    }
    ?>
    0