Posts

Showing posts from 2018

An error occurred while installing nokogiri (1.8.4), and Bundler cannot continue.

An error occurred while installing nokogiri (1.8.4), and Bundler cannot continue. Try this first and then bundle install again   sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev

Missing script i18nliner-handlebars

Missing script i18nliner-handlebars Add this lines into your package.json file "handlebars": "~1",  "ember-template-compiler": "~1.8",  "i18nliner-handlebars": "~0.1",  "minimist": "~1.1" //ignore if your package.json already have this line

If we are getting problem with FFMPEG || ffmpeg thumbnailer error in rails

If we are getting problem with FFMPEG  || ffmpeg thumbnailer error in rails Safely Remove FFMPEG First sudo apt-get --purge remove ffmpeg sudo apt-get --purge autoremove sudo apt-get install ppa-purge sudo ppa-purge ppa:jon-severinsson/ffmpeg sudo add-apt-repository ppa:mc3man/trusty-media sudo apt-get update sudo apt-get dist-upgrade sudo apt-get install ffmpeg And try if you still have problem then, apt-get update apt-get install build-essential git curl gawk useradd -m guest su guest cd export LOCAL_BREW_ENV="$HOME/my_graphviz" mkdir -p "$LOCAL_BREW_ENV" git clone https://github.com/Linuxbrew/brew.git "$LOCAL_BREW_ENV" export PATH="$LOCAL_BREW_ENV/bin:$LOCAL_BREW_ENV/sbin:$PATH" export MANPATH="$LOCAL_BREW_ENV/share/man:$MANPATH" export INFOPATH="$LOCAL_BREW_ENV/share/info:$INFOPATH" export HOMEBREW_CACHE="$LOCAL_BREW_ENV/var/cache" export HOMEBREW_LOGS="$LOCAL_BREW_ENV/va

flash message in javascript

In html file - <button class="click-here">Click here to show message</button> <div id="status-area"></div> In javascript file -  (function($) {     $.fn.flash_message = function(options) {              options = $.extend({         text: 'Done',         time: 1000,         how: 'before',         class_name: ''       }, options);              return $(this).each(function() {         if( $(this).parent().find('.flash_message').get(0) )           return;                  var message = $('<span />', {           'class': 'flash_message ' + options.class_name,           text: options.text         }).hide().fadeIn('fast');                  $(this)[options.how](message);                  message.delay(options.time).fadeOut('normal', function() {           $(this).remove();         });                });     }; })(jQuery); Add some css-

how to delete associated record in laravel

There are two ways to delete associated record or related record. First way is  Suppose we have two models Category and Product. we have association like category has many products. our Category model like this class Category extends Model {     /**      * Get the comments for the blog post.      */     public function products()     {         return $this->hasMany('App\Product', 'category_id');     } } our Product model like this class Product extends Model {     /**      * Get the comments for the blog post.      */     public function category()     {         return $this->belongsTo('App\Category');     } } so write this in your category model. public static function boot() {         parent::boot();         static::deleting(function($category) { // before delete() method call this              $category->products()->delete();              // do the rest of the cleanup.

how to run rake task from console

how to run rake task from console In your file_name.rake namespace rake_task   namespace first_rake     task task_first do       // some code     end     task task_second do        // some code     end   end end Now run this task rake rake_task:first_rake:task_first

Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))

use Illuminate\Support\Facades\Schema;  public function boot()   {      Schema::defaultStringLength(191);    }

laravel: command not found

export PATH="$HOME/.composer/vendor/bin:$PATH" source ~/.bash_profile

send data to view from controller in laravel

There are many ways to send data to views from controller i am assuming $data you have to send in view return view('layout',['data' => $data]); return view('layout',compact('data'));  return view('layout')->with(compact('data'));  return view('layout')->withData($data);  return view('layout')->with('data',$data);

Base table or view not found: 1146 Table 'links.blogs' doesn't exist

make sure you are using create instead of table. use Schema::create to create new. Schema::create('links', function (Blueprint $table) {       $table->increments('id');       $table->timestamps(); }); some this like this

create table through migration in laravel

php artisan make:migration create_YOUR_TABLE_NAME_table --create=YOUR_TABLE_NAME For example i am creating links table php artisan make:migration create_links_table --create=links this command will generate migration like this Schema::create('links', function (Blueprint $table) {       $table->increments('id');       $table->timestamps(); });

Laravel Error 500 Whoops, looks like something went wrong – Exception

php artisan key:generate generate key php artisan config:clear clear project cache php artisan config:cache php artisan serve start server again

What is Sequence | SQL Tutorial 18

What is Sequence A Sequence is Database Object and its completely independent object. Use - Sequence are used to generate sequential integers values. and we can also create primary key values by using sequences. Example-   Suppose you are submitting bank application form with fields name, surname, dob, gender and so on.. when you click on submit records is stored in a table. but there is one more column in a table that is serial number of customer that is automatically maintained. Syntax- create sequence sequence_name; // its will start with 1 and incremented by 1 by default. 1,2,3 Now suppose we have to generate value from 100 and incremented by 10.\ create sequence emp_no Start With 100 Incremented By 10; if You want to know current value of the sequence- CURRVAL if You want to know next value of the sequence-  NEXTVAL Practice-  Step-1 - create a table create table employee( emp_id number, name varchar2(100), dob date, salary number); Step-2- creat

What is Synonyms | SQL Tutorial 19

What is Synonyms Synonyms is a permanent alias name for table Types of synonyms- public synonyms - is used by all authenticate users. private synonyms - is only used by owner of the object. By Default a synonyms to be created as private synonyms. Syntax-  create synonyms synonyms_name For table_name; create synonyms eit For employee_info_table; // now you can use synonyms instead of table name like... select * from eit; Practice-  Step-1 - create a table create table employee( emp_id number, name varchar2(100), dob date, salary number); Step-2- create a synonyms create synonyms emp for employee // by default you can not create synonym you have to connect to DBA. Step-3- conn system // enter your password step-4- grant create synonyms to rahul (use your oracle name here) step-5 conn rahul/7533 Step-6- create synonyms again create synonyms emp for employee  Now apply some operation  select * from emp;

Uploading Images With Carrierwave to S3 on Rails

Uploading Images With Carrierwave to S3 on Rails In your gem file gem 'carrierwave', '0.10.0' gem "mini_magick" gem "fog" Run bundle install In app/models/Your_model_name.rb   mount_uploader :your_field_name, ImageUploader app/uploaders/image_uploader.rb class ImageUploader < CarrierWave::Uploader::Base     include CarrierWave::MiniMagick     storage :fog     def store_dir     "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"   end     version :large do     process resize_to_limit: [800, 800]   end     version :medium, :from_version => :large do     process resize_to_limit: [500, 500]   end     version :thumb, :from_version => :medium do     process resize_to_fit: [100, 100]   end     version :square do     process :resize_to_fill => [500, 500]   end   end Create a file in ditectory config/initializers/s3.rb CarrierWave.co

An error occurred while installing rmagick (2.16.0), and Bundler cannot continue

An error occurred while installing rmagick (2.16.0), and Bundler cannot continue You have to install library of rmagick in your system. sudo apt-get install imagemagick libmagickcore-dev libmagickwand-dev

NoMethodError: undefined method `has_many?'

NoMethodError: undefined method `has_many?' In your gem file-  group :test do     gem 'capybara', '~> 2.1.0'     gem 'shoulda-matchers', '~> 3.0' end Run - bundle install in your spec_helper-  Shoulda::Matchers.configure do |config|   config.integrate do |with|     with.test_framework :rspec     with.library :rails   end end In to do TodoItem model require 'spec_helper' describe TodoItem do   it { should belong_to(:todo_list) } end In to do TodoList Model require 'spec_helper' describe TodoList do   it { should have_many(:todo_items) } end

flow of co related sub query

Image

What is co related sub query | SQL Tutorial 17

Image
What is co related sub query Co-related sub query  - if a sub query depends on output generated by outer query. Use-     Get Department details which is having no employee right now.    Get Product details which sold to any single Customer. Co-related sub query Uses two operator EXISTS- get object details   if having something then use EXISTS operator between Inner and outer query. NOT EXISTS- get object details   if not having something then use NOT   EXISTS  operator between Inner and outer query. Syntax - select ..... from table_name where EXISTS/NOT EXISTS ( select..... from table_name2 where table1.pkcolum = table2fkcolum  ); Example get department details where having at least 1 employee select d.* from dept d where EXISTS (select e.empno from emp e where e.deptno =  d.deptno); get department details where not having at least 1 employee select d.* from dept d where NOT EXISTS (select e.empno from emp e where e.deptno =  d.deptno);

What is sub query | SQL Tutorial 16

What is sub query Sub query is a query with in other query is known is Sub query Use if you want to get data from table1 by using value form table2 we will go for subquery not for joins. syntax. select * from table_name where....(select * from table_name where...(select * from table_name)...)... // Inner most query execute first Type of Sub Query Single row sub query - the sub query which is returning only one output value. example- get department name of employee 708. select dname from department where deptno = (select deptno from employee where empno=708) example-  get department detailsof employee 708. select * from department where deptno = (select deptno from employee where empno=708) Multi row sub query - the sub query which is returning more than one output value. example-  get department detailsof employee 708.709 select dname from department where dept_no IN (select deptno from employee where empno IN( 708, 709)); If we want

What is Data Integrity Constraints | SQL Tutorial 15

What is Data Integrity Constraints Data Integrity means apply some business rules on data fields . for Example-  Employee id must be unique and not null. Employee salary should not be zero etc. Employee Table e_id             e_name             e_sal        e_designation                        100             Rahul                25000       software developer          // (valid record) 0                 duke                30000         manager            // (invalid because E_id must be greater than 0) 101             Shweta            0                Designer           // (invalid because E_sal must be greater than 0)        So this are basic standard that we must have to Follow. so we have constraints for avoiding invalid insertion of invalid record. Types of Data Integrity Constraints- Keys Constraints Unique not null primary key Domain constraints Check Referential Integrity Constraints Foreign Key Unique Key constraints - its

get Fifth highest paid employee details in sql | limit | offset

Get Fifth highest paid employee details in sql SELECT * FROM employee ORDER BY salary ASC LIMIT 1 OFFSET 5.  ORDER BY salary ASC - by this we are arranging salary in Ascending order. LIMIT 1 - By this we are fetching only one employee details. OFFSET 5 - By this we are start fetching record from 5th number record.

What are joins | SQL Tutorial 14

What are Joins Joins are used when we have to fetch data from multiple table with multiple conditions on column. we can also do this by Set Operators but there are a limitation set operator always work on single column and single column data. Example- we want to display name of employee and department of employee. so we have to fetch data from employee table and department table . Types of JOINS- Cross joins/cartesian product. Equi joins/Inner joins. Self joins outer joins. What is cross join or cartesian product cross join concept is similar to cartesian product in mathematics. suppose we have to tables with this data. table_a = {x, y, z}; table_b = {10, 20}; if we apply cross join here then we will get data like this. table_a x table_b = {(x, 10), (x, 20), (y, 10), (y, 20), (z, 10), (z, 20)} What is Equi join if we want to get only valid combination of records then we use Equi joins because in cross join we are getting all combination of data. sup

What is Logical Operator | SQL Tutorial 13

What is Logical Operator AND vs OR Logical operators are used to check certain condition or multiple condition. . For Example- If we want to check two or more than two condition in a single query and all condition must be true then we use - AND OPERATOR If we want to check two or more than two condition in a single query and any one condition will be true then we use -  OR OPERATOR AND ____ if we are looking for employee whose is manager and salary is greater than 50000. means here are two condition employee job is manager and salary is greater than 50000 Select * from employee where job="manager" AND salary>=50000; if we are looking for employee whose is manager and salary is greater than 50000 and city is indore. means here are two condition  employee job is manager  and  salary is greater than 50000 and city is indore Select * from employee where job="manager" AND salary>=50000 AND city="indore"; // it wil

What is Negation Operator | SQL Tutorial 12

What is Negation Operator NOT LIKE VS NOT BETWEEN VS NOT IN VS IS NOT NULL Negation Operator NOT BETWEEN, IS NOT NULL, NOT LIKE,NOT IN these operators are just opposite of special Operator. For Example- if we want to display salary not greater than 2000 and not less than 10000 use- BETWEEN if we want to display all employee whose surname is not null use- IS NULL if we want to display all employee whose firstname is not Rahul use- LIKE if we want to display all customer who are not in MUMBAI and Channai use- IN (Specific list) NOT BETWEEN _________ if we dont want record within a range then we use Between operator example if want all employee details whose salary is not between 5000 to 10000. Select * from employee where salary NOT BETWEEN '5000' AND '10000'; NOT IN __ if we dont want to display record with specific list. Example- List of employee whose salary is not 10000, 50000, 70000. select * from employee where salary NOT IN(

What is Special Operator | SQL Tutorial 11

What is Special Operator LIKE VS BETWEEN VS IN VS IS NULL Special Operator BETWEEN, IS NULL, LIKE,IN these operators are used when we display record with specific range, limit, or any specific record. For Example- if we want to display salary greater than 2000 and less than 10000 use- BETWEEN if we want to display all employee whose surname is null use- IS NULL if we want to display all employee whose firstname is Rahul use- LIKE if we want to display all customer who are MUMBAI and Channai use- IN (Specific list) BETWEEN _________ if we want record within a range then we use Between operator example if want all employee details whose salary between 5000 to 10000. Select * from employee where salary BETWEEN '5000' AND '10000'; IN __ if we want to display record with specific list. Example- List of employee whose salary is 10000, 50000, 70000. select * from employee where salary IN(10000, 50000, 70000); IS NULL _______ sel

What is Relational Operator | SQL Tutorial 10

What is Relational Operator When we have to fetch record within some condition then we use Relational Operator. for example Highest paid employee, number of employee whose salary is greater than 20000. LIKE: select * from employee where sal>20000;   //it will return all employee whose salary is greater than 20000.

What is Arithmetic Operator | SQL Tutorial 9

What is Arithmetic Operator Arithmetic Operator's are used to perform Arithmetic operation like +, -, *, /. For Example sum of salary, average salary etc. select 100+200 from student; // yes you can specify any table name here but we are printing more record means output 300 will be printed total number of records present in the table like:   100+200 //is the output title ------------- 300 300 300 .. and so on until visit all row of table Best way to do this select 100+200 from DUAl; //dual is a predefined table 100+200 ________    300 Another Example: _______________ Display 10% of current salary: select sal, (0.10*sal) "10 % of salary" from employee;

What is operators is sql | SQL Tutorial 8

What is operators is sql  The symbols which are used to perform logical and mathematical operations in SQL are called SQL operators. There are three types of Operators used in SQL. Basically when we have to perform any operation to fetch our Desired output then we use Operators. for example- sum of salary, average salary, highest paid employee etc. Types of Operators- Arithmetic Operators - Perform =, -, *, /,  % Relational Operators - ==, <=, >= , > , <  Special Operators - To Get Range, List, Null- Use BETWEEN, IN, IS NULL, LIKE  Negation Operators - its Reverse of Special Operators- NOT BETWEEn, NOT IN, NOL NULL, NOT LIKE. Logical Operators -  To Specify condition and selection is OR, AND

Show Escape or Enter and tab in column or row in Rails

Show Escape or Enter and tab in column or row in Rails @users.each do |user|      raw(user.address.gsub(/\n/, '<br>'))   end //assuming you have \n or enter in your record and if you have another Special character then replace that character wiht respective html tag

Custom order of Record | | Order as specified || order_as_specified

Custom order of Record | | Order as specified || order_as_specified Install gem gem 'order_as_specified' bundle install or gem install order_as_specified write this line at top of your model / /that model you have to fetch record in custom order extend OrderAsSpecified Now in your controller method ids=[1,3,5,6,7,4,2] // assuming you have 7 record with this id's & and you want records in this order then Model.where(id: ids).order_as_specified(id: ids) //this will give you record in custom order Here is Working Example def index    premia1 = []    premia2 = []    PremiumInstruction.all.select{|pi| premia1 << pi.premium}    Premium.all.select{|p| premia2 << p if p.premium_instructions.blank?}    permia = premia2 + premia1.uniq //add both array    ids = permia.pluck(:id) //getting ids from array into an array //learn about pluck in other post    @collection = Premium.where(id: ids). order_as_specified (id: ids) end Here we

Send email in rails

Sending Emails Using ActionMailer and Gmail Create new rails application rails new new_app_name rails g scaffold user name:string email:string contact:string rake db:migrate rails g mailer example_mailer In  app/mailers/user_mailer.rb class UserMailer < ActionMailer::Base    def sample_email(user)     @user = user     mail(to: @user.email, subject: 'Sample Email, text:"simple text"')   end end app/views/user_mailer/sample_email.html.erb <!DOCTYPE html> <html>   <head>     <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />   </head>   <body>     <h1>Hi <%= @user.name %></h1>     <p>       Sample mail sent using smtp.     </p>   </body> </html> /config/application.yml gmail_username: 'username@admin.com' gmail_password: 'Gmail password' /config/environments/production.rb config.action_mailer.deliver

Generate Controller, views into specific folder

Generate Controller, views into specific folder rails generate scaffold_controller api/v1/users

Searching on Select Box and Check Box || List

Searching on Select Box and Check Box Searching on List <input type="text" id="myInput" onkeyup="filterFunction()" placeholder="Search.." > <ul id="myulli">   <li><a href="#">abc</a></li>   <li><a href="#">xyz</a></li>  <li><a href="#">demo</a></li> <li><a href="#">testing</a></li> </ul> <script> function filterFunction(){    var input, filter, ul, li, a, i;    input = document.getElementById("myInput");    filter = input.value.toUpperCase();    div = document.getElementById("myulli");    a = div.getElementsByTagName("li");    console.log(a);    for (i = 0; i < a.length; i++) {        if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {            a[i].style.display = "";        }