Chrome Extension

Devsheet Bot

@Devsheet

Hey there, I am devsheet personal AI Bot. You can talk to me in the future.

  • Define a new component in Vue.js
    Vue.component('component_name', {
        props: ['prop_name'],
        template: '<div class="root"></div>',
        data: function() {
            return {}
        },
        methods: {
        },
        created: function() {
        }
    });
  • Create table with constraints MySQL query
    CREATE TABLE table_name(
        Id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
        Column1 char(40) DEFAULT NULL,
        Column2 varchar(100) DEFAULT '',
        Date timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY(Id),
        UNIQUE (Column1)
    )
  • Create new component in React
    // CREATE CLASS NAMED AS COMPOENT NAME
    class ComponentName extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                prop_name: 'value',
                prop_name2: `Hello ${this.props.name}, `
            }
    
            this.onChange = this.onChange.bind(this); //IF YOU WANT TO USE 'this' KEYWORD
        }
        
        onChange(e) {
            this.setState({
                prop_name: e.target.value
            })
        }
    
        render() {
            return (
                <div>
                    <p className="sample_class">{ this.state.prop_name }</p>
                    <input className="input_ctrl" name="name" placeholder="Enter text" onChange={this.onChange} />
                </div>
            )
        }
    }
    
    ReactDOM.render(<ComponentName name="Your name" />, document.getElementById('app'));
  • Create rounded shape style button using CSS
    .rounded_button {
       padding: 1.2rem 2.5rem;
       font-size: 1rem;
       background: #207ef9;
       color: #fff;
       border-radius: 40px;
       border: 0;
       letter-spacing: 1px;
       cursor: pointer;
       outline: 0;
    }
    
    .rounded_button:hover {
       opacity: .9;
    }
  • Show iframe only after fully loaded in HTML
    <iframe style="display:none;" onload="this.style.display = 'block';" src="https://example.com" ></iframe>
  • Start php server from terminal on MacOS
    php -S locahost:8080
  • Insert data into table mysql query
    INSERT INTO table_name (Column1, Column2, Column3)
    VALUES(1, 'Value2', 'Value3')
    
    or
    
    INSERT INTO table_name
    SET
    Column1 = 'Value1',
    Column2 = 'Value2',
    Column3 = 'Value3'
  • Convert characters to lowercase using strtolower() function in PHP
    <?php
       echo strtolower("WORLD IS BEAUTIFUL");
    ?>
  • Check empty string in PHP
    if (empty($str)) {
       echo "String is empty";
    } else {
       echo "String is not empty"
    }
  • Calculate length of a string using strlen() function in php
    <?php
       echo strlen("foo bar"); 
    ?>
  • Convert all characters to lowercase using toLowerCase() method in javascript
    var str = "World Is Beautiful";
    console.log(str.toLowerCase());
  • Array.forEach() in javascript
    var myarray = ['1', '2', '3'];
    
    myarray.forEach(function(item, index) {
        console.log("item is : ", item, ", index is : ", index)
    });
  • nl2br() function in PHP
    <?php
       echo nl2br("First line.\nSecond line.\nThird Line");
    ?>
  • Drop table SQL query
    DROP TABLE table_name;
  • Rename table SQL command
    RENAME old_table_name TO new_table_name;
  • Add columns, alter table SQL query
    ALTER TABLE table_name ADD (Column_name1 data_type, Column_name2 data_type (size));
  • Truncate table SQL query
    TRUNCATE TABLE table_name;
  • Delete from table SQL query
    DELETE FROM table_name;
    
    /* dellete based on condition */
    
    DELETE FROM table_name WHERE column_name = 'value'
  • UPDATE TABLE SQL query
    UPDATE table_name 
    SET
    column_name1 = value1
    column_name2 = value2
    column_name3 = value3
  • Open IOS app simulator from terminal
    open -a Simulator.app
  • Bottom box shadow only to element in CSS
    .bottom-box-shadow {
        -webkit-box-shadow: 0 8px 6px -6px rgba(0,0,0,0.7);
           -moz-box-shadow: 0 8px 6px -6px rgba(0,0,0,0.7);
                box-shadow: 0 8px 6px -6px rgba(0,0,0,0.7);
    }
  • Converting class objects to JSON string in Flutter
    class Employee {
      final String name;
      final String email;
    
      Employee(this.name, this.email);
    
      Employee.fromJson(Map<String, dynamic> json)
          : name = json['name'],
            email = json['email'];
    
      Map<String, dynamic> toJson() =>
        {
          'name': name,
          'email': email,
        };
    }
    
    //Now CONVERT SIMPLE JSON TO FLUTTER OBJECT 
    Map employeeMap = jsonDecode(jsonString);
    var employee = Employee.fromJson(employeeMap);
    
    //CONVERT FLUTTER OBJECT TO SIMPLE JSON STRING
    String json = jsonEncode(employee);
  • .each() jQuery
    var all_divs = $("div");
    
    all_divs.each(function(index, item) {
       //DO SOMETHING HERE
    })
  • Install dependencies using pip from requirement.txt file in Python
    pip install -r requirements.txt
  • Hide title from BottomNavigationBar in Flutter
    BottomNavigationBar(
        showSelectedLabels: false,
        showUnselectedLabels: false,
        items: <BottomNavigationBarItem> []
    );
  • Add box shadow to container in flutter
    new Container(
        height: 200.0,
        decoration: new BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Colors.red,
                blurRadius: 25.0, // soften the shadow
                spreadRadius: 5.0, //extend the shadow
                offset: Offset(
                  15.0, // Move to right 10  horizontally
                  15.0, // Move to bottom 10 Vertically
                ),
              )
            ],
        );
        child: new Text("Hello world"),
    );
  • Add border to widget in Flutter
    //ADD BORDER TO ALL SIDES
    Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.red,
          width: 3.0,
        ),
      ),
    )
    
    //ADD BORDER TO SPECIFIC SIDES
    Container(
      decoration: BoxDecoration(
        border: Border(
          left: BorderSide(
            color: Colors.red,
            width: 3.0,
          ),
          top: BorderSide(
            color: Colors.blue,
            width: 3.0,
          ),
        ),
      ),
    )
  • For loop Angular
    <div *ngFor="let item of items">
        <span>{{item.name}}</span>
        <span>{{item.description}}</span>
    </div>
  • Django template loop n times
    //CODE FOR VIEW
    render(request, 'page.html', {'range': range(10)}) // TO START RANGE FROM ONE use range(1,11)
    
    
    //CODE FOR TEMPLATE
    {% for i in range %}
         ...
    {% endfor %}
  • JQueryUI datepicker
    <!doctype html>
    <html lang="en">
    <head>
      <link rel="stylesheet" href="path_to_base_css/jquery-ui.css">
    
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="path_to_jqueryui_js/jquery-ui.js"></script>
      <script>
         $( function() {
            $( "#mydatepicker" ).datepicker({
                dateFormat: 'yy-mm-dd'
            });
         });
      </script>
    </head>
    <body>
     
    <p>Date: <input type="text" id="mydatepicker"></p>
     
     
    </body>
    </html>
  • Autocomplete using jQueryUI
    <html lang="en">
    <head>
      <link rel="stylesheet" href="path_to_jquery_ui_lib/jquery-ui.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="path_tojqueryui_lib/jquery-ui.js"></script>
      <script>
      $( function() {
        //SEARCH INTO LOCAL ARRAY LIST
        var fruits = [
          "Apple", "Orange", "Banana", "Papaya"
        ];
        $( "#autocomplete_input" ).autocomplete({
          source: fruits
        });
    
    
        //IF YOU WANT TO LOAD THE LIST FROM THE SERVER USE BELOW CODE
        // API RETURNS JSON - [{"id": "23", "label": "label name", "property1": "value1"}]
        $( "#autocomplete_input" ).autocomplete({
            source: "/api/get_items_api.php",
            minLength: 2, //MINIMUM CHARACTERS REQUIRED FOR SEARCH
            select: function( event, ui ) {
                console.log(ui.item.property_name);
            }
        });
      });
      </script>
    </head>
    <body>
     
      <div class="ui-widget">
         <label for="tags">Autocomplete jQueryUI: </label>
         <input id="autocomplete_input">
      </div>
    </body>
    </html>
  • Text ellipsis for multi lines in CSS
    .multi_line_ellipsis {
        display: -webkit-box;
        max-height: 3rem;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;
        -webkit-line-clamp: 2;
        font-size: 1.4rem;
        font-weight: 500;
        line-height: 1.6rem;
    }
  • Create python virtual environment command
    virtualenv venv -p python3
  • Select rows from table SQL query
    //select all rows from table
    SELECT * FROM table_name
    
    //select rows based on a condition
    SELECT * FROM table_name WHERE column_name='value'
  • $.ajax jQuery
    $.ajax({
        url: 'YourRestEndPoint',
        method: 'POST',
        headers: {
            'Authorization':'Token xxxxxxxxxxxxx',
            'Content-Type':'application/json'
        },
        data: { "key": "value" },
        dataType: 'application/json',
        processData: false, //IF YOU ARE SENDING FORM DATA
        contentType: false,
        success: function(data){
          console.log('success: ', data);
        },
        error: function(data) {
            console.log('error: ', data);
        }
    });
  • $.get jQuery
    $.get("API_URL", {"key": "value"}, function(data, status) {
        console.log("data : ", data, "status : ", status);
    });
  • INNER JOIN SQL Query
    SELECT 
    Column1 FROM tbl1,
    Column2 From tbl1,
    Column1 FROM tbl2
    FROM 
    table1 as tbl1
    INNER JOIN 
    table2 as tbl2
    ON tbl1.column_tbl1 = tbl2.column_tbl2
  • Return JSON from a PHP script
    <?php
        header('Content-Type: application/json'); 
    
        $json_data = array("key" => "value");
        echo json_encode($json_data);
    ?>
  • Add unique key constraint on existing column Sql query
    ALTER TABLE Employee
    ADD UNIQUE (ID);
  • Create or update records Mysql/Sql
    INSERT INTO UserDetail(UserId, About) 
    VALUES (1,'This is about insert text') 
    ON DUPLICATE KEY UPDATE About = 'This is about update text';
  • Install composer for php
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php -r "if (hash_file('sha384', 'composer-setup.php') === 'a5c698ffe4b8e849a443b120cd5ba38043260d5c4023dbf93e1558871f1f07f58274fc6f4c93bcfd858c6bd0775cd8d1') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
    php composer-setup.php
    php -r "unlink('composer-setup.php');"
  • Create models in Django
    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=30)
        experience = models.IntegerField()
        is_active = models.BooleanField()
        auto_field = models.AutoField() //INTEGER FIELD THAT automatically increments
        emaill = models.EmailField(max_length=100) //CharField that checks - provided value is a valid email
        description = models.TextField() //Used to store large text value
        created_date = models.DateTimeField()
  • Django runserver command
    python manage.py runserver 9090
  • Database migration commands in django
    //TO CREATE MIGRATIONS
    python manage.py makemigrations
    
    //TO APPLY MIGRATIONS
    python manage.py migrate
  • Retrieving all objects in Django
    all_entries = Entry.objects.all();
  • Create or save object data in Django
    //ONE LINE SYNTAX TO SAVE DATA 
    person = Person.objects.create(first_name="John", last_name="Deo")
    
    
    //YOU CAN ALSO USE BELOW CODE TO SAVE DATA
    person = Person(first_name="John", last_name="Deo")
    person.save()
  • Convert HTML code to plain text in PHP
    <?php
        $html_code = '<p>Hello world</p>'
        echo strip_tags($html_code);
    ?>
  • Allow or limit a view to superuser only Django
    from django.contrib.auth.decorators import user_passes_test
    
    @user_passes_test(lambda u: u.is_superuser)
    def score_reset(request):
        return "View"
  • Replace characters globally Javascript
    //Case sensitive
    var str = "Color is Green and green is a cold color";
    var result = str.replace(/green/g, "blue");
    //output - Color is Green and blue is a cold color
    
    //Applly for case insensitive
    var res = str.replace(/green/gi, "blue");
    //output - Color is blue and blue is a cold colors
  • Sort array using Array.sort() in javascript
    //SORT ARRAY ALPHABETICALLY
    var arr = ["Joe", "Victor", "Henna"];
    arr.sort();
    
    //SORT ARRAY NUMERICALLY
    var numeric_arr = [50, 20, 40, 60, 10, 30];
    numeric_arr.sort(function(a, b) { return a - b }); //ASCENDING ORDER
    numeric_arr.sort(function(a, b) { return b - a }); //DESCENDING ORDER
  • Create form data in Javascript
    var form = document.getElementsByTagName("form")[0];
    var formData = new FormData(form);
    
    formData.get("title"); //TO GET A KEY(KEY NAME WILL BE name attribute defined in your input controls)
    formData.set("title", "This is new title"); //TO SET NEW VALUE TO A KEY
    
    formData.delete("about"); //TO DELETE A KEY FROM FORM DATA
  • Add class to an element in javascript
    var element = document.getElementById("element_id");
    element.classList.add("className"); // ADD CLASS TO ELEMENT
    
    element.classList.remove("className"); //REMOVE CLASS FROM ELEMENT
  • Create random string in Javascript
    Math.random().toString(36).substring(2, 15)
  • Get Pseudo elements using Javascript
    var elem = window.getComputedStyle(document.querySelector('.element'), ':before');
    elem.getPropertyValue('color');
  • Get and set cookie in PHP
    setcookie(name, value, expire, path, domain, secure, httponly);
    
    setcookie("CookieName", "CookieValue", 2147483647, "/"); //SET COOKIE THAT EXPIRES IN 2038
    
    print($_COOKIE["CookieName"]); //USER FOR GETTING COOKIE
  • indexOf and lastIndexOf a string in javascript
    var str = "Check where grapes found";
    str.indexOf("grapes"); //It will return 12 as the index
    
    var str = "grapes are not grapes until found";
    str.lastIndexOf("grapes"); // Return last index of 'grapes' in str var
  • MIN() and MAX() functions in SQL
    SELECT MIN(column_name) FROM table_name WHERE condition;
    
    SELECT MAX(column_name) FROM table_name WHERE condition;
  • Add accept range header to play mp4 file on IOS devices in Django
    import os
    import re
    import mimetypes
    from wsgiref.util import FileWrapper
    
    from django.http.response import StreamingHttpResponse
    
    range_re = re.compile(r'bytess*=s*(d+)s*-s*(d*)', re.I)
    
    class RangeFileWrapper(object):
        def __init__(self, filelike, blksize=8192, offset=0, length=None):
            self.filelike = filelike
            self.filelike.seek(offset, os.SEEK_SET)
            self.remaining = length
            self.blksize = blksize
    
        def close(self):
            if hasattr(self.filelike, 'close'):
                self.filelike.close()
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.remaining is None:
                # If remaining is None, we're reading the entire file.
                data = self.filelike.read(self.blksize)
                if data:
                    return data
                raise StopIteration()
            else:
                if self.remaining <= 0:
                    raise StopIteration()
                data = self.filelike.read(min(self.remaining, self.blksize))
                if not data:
                    raise StopIteration()
                self.remaining -= len(data)
                return data
    
    
    def stream_video(request, filename):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        file_path = os.path.join(BASE_DIR, "app_name/static/video/" + filename)
    
        range_header = request.META.get('HTTP_RANGE', '').strip()
        range_match = range_re.match(range_header)
        size = os.path.getsize(file_path)
        content_type, encoding = mimetypes.guess_type(file_path)
        content_type = content_type or 'application/octet-stream'
        if range_match:
            first_byte, last_byte = range_match.groups()
            first_byte = int(first_byte) if first_byte else 0
            last_byte = int(last_byte) if last_byte else size - 1
            if last_byte >= size:
                last_byte = size - 1
            length = last_byte - first_byte + 1
            resp = StreamingHttpResponse(RangeFileWrapper(open(file_path, 'rb'), offset=first_byte, length=length), status=206, content_type=content_type)
            resp['Content-Length'] = str(length)
            resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
        else:
            resp = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')), content_type=content_type)
            resp['Content-Length'] = str(size)
        resp['Accept-Ranges'] = 'bytes'
        return resp
  • Bar chart with circular shape from corner in Chart.js
    Chart.elements.Rectangle.prototype.draw = function() {
        var ctx = this._chart.ctx;
        var vm = this._view;
        var left, right, top, bottom, signX, signY, borderSkipped, radius;
        var borderWidth = vm.borderWidth;
        var cornerRadius = 20;
    
        if (!vm.horizontal) {
            left = vm.x - vm.width / 2;
            right = vm.x + vm.width / 2;
            top = vm.y;
            bottom = vm.base;
            signX = 1;
            signY = bottom > top? 1: -1;
            borderSkipped = vm.borderSkipped || 'bottom';
        } else {
            left = vm.base;
            right = vm.x;
            top = vm.y - vm.height / 2;
            bottom = vm.y + vm.height / 2;
            signX = right > left? 1: -1;
            signY = 1;
            borderSkipped = vm.borderSkipped || 'left';
        }
    
        if (borderWidth) {
            var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
            borderWidth = borderWidth > barSize? barSize: borderWidth;
            var halfStroke = borderWidth / 2;
            var borderLeft = left + (borderSkipped !== 'left'? halfStroke * signX: 0);
            var borderRight = right + (borderSkipped !== 'right'? -halfStroke * signX: 0);
            var borderTop = top + (borderSkipped !== 'top'? halfStroke * signY: 0);
            var borderBottom = bottom + (borderSkipped !== 'bottom'? -halfStroke * signY: 0);
            if (borderLeft !== borderRight) {
                top = borderTop;
                bottom = borderBottom;
            }
            if (borderTop !== borderBottom) {
                left = borderLeft;
                right = borderRight;
            }
        }
    
        ctx.beginPath();
        ctx.fillStyle = vm.backgroundColor;
        ctx.strokeStyle = vm.borderColor;
        ctx.lineWidth = borderWidth;
        var corners = [
            [left, bottom],
            [left, top],
            [right, top],
            [right, bottom]
        ];
    
        var borders = ['bottom', 'left', 'top', 'right'];
        var startCorner = borders.indexOf(borderSkipped, 0);
        if (startCorner === -1) {
            startCorner = 0;
        }
    
        function cornerAt(index) {
            return corners[(startCorner + index) % 4];
        }
    
        var corner = cornerAt(0);
        ctx.moveTo(corner[0], corner[1]);
    
        for (var i = 1; i < 4; i++) {
            corner = cornerAt(i);
            nextCornerId = i+1;
            if(nextCornerId == 4){
                nextCornerId = 0
            }
    
            nextCorner = cornerAt(nextCornerId);
    
            width = corners[2][0] - corners[1][0];
            height = corners[0][1] - corners[1][1];
            x = corners[1][0];
            y = corners[1][1];
            
            var radius = cornerRadius;
            
            if(radius > height/2){
                radius = height/2;
            }if(radius > width/2){
                radius = width/2;
            }
    
            ctx.moveTo(x + radius, y);
            ctx.lineTo(x + width - radius, y);
            ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
            ctx.lineTo(x + width, y + height - radius);
            ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
            ctx.lineTo(x + radius, y + height);
            ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
            ctx.lineTo(x, y + radius);
            ctx.quadraticCurveTo(x, y, x + radius, y);
        }
    
        ctx.fill();
        if (borderWidth) {
            ctx.stroke();
        }
    }; 
    
    //NOW DRAW YOUR CHART
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
           labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
           datasets: [{
                label: '# of Votes',
                data: [90, 60, 30, 50, 30, 80],
                borderWidth: 0,
                backgroundColor: "#00AAFB",
           }]
        },
        options: {
           scales: {
                xAxes: [{
                   barThickness: 15,
                }],
                yAxes: [{
                   ticks: {
                      beginAtZero: true
                   }
                }]
           }
        }
    });
  • Hide gridlines in Chart.js
    var ctx = document.getElementById('myChart').getContext('2d');
    
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
           labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
           datasets: [{
                label: '# of Votes',
                data: [90, 60, 30, 50, 30, 80],
           }]
        },
        options: {
           scales: {
                xAxes: [{
                   gridLines: {
                      display: false
                   }
                }],
                yAxes: [{
                   gridLines: {
                      display: false
                   }
                }]
           }
        }
    });
  • Create bar chart in Chart.js
    var ctx = document.getElementById('myChart').getContext('2d');
    
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
           labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
           datasets: [{
                label: '# of Votes',
                data: [90, 60, 50, 50, 100],
                backgroundColor: "#00AAFB",
           }]
        },
        options: {
           scales: {
                xAxes: [{
                   gridLines: {
                      display: false
                   }
                }],
                yAxes: [{
                   ticks: {
                      beginAtZero: true, 
                   },
                   gridLines: {
                      display: false
                   }
                }]
           }
        }
    });
  • Create line chart in Chart.js
    var ctx = document.getElementById("line_chart").getContext('2d');
    
    var myLineChart = new Chart(ctx, {
       type: 'line',
       data: {
          labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
          datasets: [{
             label: "hello",
             data: [40, 50, 80, 20],
             backgroundColor: "rgba(0,0,0,0)",
             borderColor: "#319fe2"
          }]
       },
       options: {
          
       }
    });
  • Create pie chart in Chart.js
    var ctx = document.getElementById("pie_chart").getContext('2d');
    
    var myChart = new Chart(ctx, {
       type: 'pie',
       data: {
          labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
          datasets: [{
             labels: "Pie chart",
             data: [20, 50, 40, 30],
             backgroundColor: ["red", "blue", "orange", "green"]
          }]
       }
    });
  • Map State to Props using React + Redux
    import React from "react";
    import { connect } from "react-redux";
    
    const mapStateToProps = state => {
        return { articles: state.articles };
    }
    
    const ConnectedList = ({ articles }) => (
        <ul>
            { articles.map(article => (
                <li className="item" key={article.id}>{ article.title }</li>
            )) }
        </ul>
    );
    
    const List = connect(mapStateToProps)(ConnectedList);
    
    
    class FirstComponent extends React.Component {
        render() {
            return (
                <div>
                    <div className="Hello">Hello ankit this i</div>
                    <List></List>
                </div>
            );
        }
    }
    
    export default FirstComponent;
  • Add Unique Constraints on Column in MySQL
    -- WHILE CREATING TABLE ON SINGLE COLUMN
    CREATE TABLE table_name(
        column_name_1  data_type UNIQUE
    );
    
    -- OR YOU CAN ADD LIKE BELOW
    CREATE TABLE table_name(
       column_name_1 data_type,
       UNIQUE(column_name_1)
    );
    
    -- ADD BY COMBINING MORE THAN ONE COLUMN WHILE CREATING TABLE
    CREATE TABLE table_1(
       column_name_1 data_type,
       column_name_2 data type,
       UNIQUE(column_name_1,column_name_2)
    );
  • MySQL Foreign key constraint
    --TABLE WITHOUT FOREIGN KEY
    CREATE TABLE Student(
        Id INT AUTO_INCREMENT PRIMARY KEY,
        FullName VARCHAR(100) NOT NULL
    )
    
    --TABLE WITH FOREIGN KEY
    CREATE TABLE StudentDetails(
        Id INT AUTO_INCREMENT PRIMARY KEY,
        EmailId varchar(100) NOT NULL,
        StudentId INT,
        CONSTRAINT fk_Student FOREIGN KEY (StudentId) REFERENCES Student(Id)
    )
  • Left side box shadow only in CSS
    .element {
        -webkit-box-shadow: -5px 0 5px -5px #333;
        -moz-box-shadow: -5px 0 5px -5px #333;
        box-shadow: -5px 0 5px -5px #333;
    }
    
    /* FOR INSET CASE */
    .elemnt_inset_left_shaow {
        -webkit-box-shadow: 7px 0 4px -4px #333 inset;
        -moz-box-shadow: 7px 0 4px -4px #333 inset;
        box-shadow: 7px 0 4px -4px #333 inset;
    }
  • Create skew background using CSS
    .skew_container  {
       max-width: 500px;
       margin: 50px auto;
       overflow: hidden;
       padding-bottom: 4%;
    }
    
    .skew_container .skew_bg {
       height: 260px;
       background: #115edb;
       text-align: center;
       padding-top: 130px;
       margin-top: -9%;
       transform: skew(0deg, 10deg); /*THIS WILL DO THE MAGIC*/
    }
    
    .skew_container .skew_bg .content {
       color: #fff;
       font-size: 30px;
       transform: skew(0deg, -10deg); /* MAKE CONTENT HORIZENTAL */
    }
  • Hide datasets label in Chart.js
    var ctx = document.getElementById("mychart").getContext('2d');
    
    var myChart = new Chart(ctx, {
       type: 'line',
       data: {
          labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
          datasets: [{
             labels: "This will be hide",
             data: [20, 50, 40, 30],
             backgroundColor: ["red", "blue", "orange", "green"]
          }]
       },
       options: {
          legend: {
             display: false //This will do the task
          }
       }
    });
  • Render components after asynchronous call in React
    class CardComponent extends Component {
        componentDidMount() {
            const self = this;
            api.getData(data => self.setState({ articleData: data }));
        }
    
        render() {
            return (
                <div>
                    <h1>{'This will always render'}</h1>
                    { this.state && this.state.articleData &&
                        <div>{'This will render after the return of the async call'}</div>
                    }
                </div>
            )
        }
    }
  • Allow CORS in PHP
    <?php
        header("Access-Control-Allow-Origin: *");
    ?>
  • document.add
    document.addEventListener("click", function(){
        console.log("I am clicked")
    });
    
    //OR ADD EVENT ON A PARTICULAR EVENT
    var button = document.getElementById("button");
    button.addEventListener("click", function() {
        console.log("I am clicked on a button");
    });
  • Query selectors in Javascript
    //TO SELECT THE VERY FIRST ELEMENT
    var element = document.querySelector(".element_class");
    //YOU CAN ALSO PASS CHILD HIERARCHY INTO IT
    var child_element = document.querySelector(".element_class .child_class");
    
    //TO SELECT ALL ELEMENTS BY CLASS YOU CAN USE BELOW QUERY SELECTOR
    var all_elements = document.querySelectorAll(".element_class");
    
    //YOU CAN SLECT ELLEMENTS BY ITS CLASS NAMEs, OR IDs, or BY USING ELEMENTS NAMES LIKE
    var all_divs_opn_webpage = document.querySelectorAll("div");
  • Add service worker to your website
    //CREATE SERVICE WORKER FILE ON ROOT NAMED AS service-worker.js(Name does not matter)
    var cacheName = 'my-web-cache';
    var filestoCache = [
        '/css/style.css',
        '/css/main.css',
        '/js/main.js',
        '/images/logo.png'
    ];
    
    self.addEventListener('install', function(event) {
        event.waitUntil(
          caches.open(cacheName)
            .then(function(cache) {
              console.log('Opened cache');
              return cache.addAll(filestoCache);
            })
        );
    });
    
    
    //CALL SERVICE WORKER FILE AND INSTALL IT(GENERALLY FORM inde.html or other pages)
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
            navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            }, function(err) {
                console.log('ServiceWorker registration failed: ', err);
            });
        });
    }
  • Loop through object javascript
    var items = {
        "item_1": "1",
        "item_2": "2",
        "item_3": "3"
    }
    for (var item in items) {
        console.log(items[item]);
    }
  • [Javascript] Add new item at first position of array using unshift() method
    var items = ["Apple", "Banana", "Orange"];
    items.unshift("Papaya", "Watermelon");
  • Get all child elements of parent element in javascript
    var parent = document.getElementById("parent_id");
    var childrens = parent.children;
    //RETURNS ALL CHILD ELEMENTS HTMLCollection ARRAY
  • Add CSS class dynamically in React
    class Hello extends React.Component {
        render() {
            return (
                <div>
                    <div className={"first_class " + (this.state.val ? "true_class" : "false_class") + " another_class" }>First Method</div>
                    <div className={`container box ${this.state.something}`}>Second Method</div>
                    <div className={'container box ' + this.state.something}>Third Method</div>
                </div>
            );
        }
    }
  • jQuery Animation
    $("button").click(function() {
        $(".element").animate({
            left: '50px',
            height: '350px',
            width: '350px'
        });
    }, "slow");
    Search history ×