code-rag-bench/online-tutorials huggingface dataset:
Draw sun using Turtle module in Python - GeeksforGeeks

01 Oct, 2020
Prerequisite: Turtle Programming in Python
In this article, let’s learn how to draw the Sun using turtle in Python. Turtle is an inbuilt module in Python. It helps draw pattens by providing a screen and turtle (pen) as tools. To move the turtle as desired functions defined within the module like forward(), backward(), right(), left() etc. will be employed.
Approach:
Import turtle module
Set up a screen for turtle.
Instantiate a turtle object.
For making sun, define a method for circle along with radius and color.
Define a function for creating sun rays.
Below is the implementation of the above approach.
Python3
import turtle    screen = turtle.Screen()  # background colorscreen.bgcolor("lightpink")  # turtle objecty = turtle.Turtle()  # define function# for drawing rays of Sundef drawFourRays(t, length, radius):          for i in range(4):        t.penup()        t.forward(radius)        t.pendown()        t.forward(length)        t.penup()        t.backward(length + radius)        t.left(90)    # Draw circle# to make suny.penup()y.goto(85, 110)y.fillcolor("yellow")y.pendown()y.begin_fill()y.circle(45)y.end_fill()  # Use the defined# function to draw raysy.penup()y.goto(85, 169)y.pendown()drawFourRays(y, 85, 54)y.right(45)drawFourRays(y, 85, 54)y.left(45)  # To keep the# output window activeturtle.done()
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to change JLabel background and foreground color in Java?

To change the JLabel foreground and background color, use the following methods:
JLabel label;
label.setForeground(new Color(120, 90, 40));
label.setBackground(new Color(100, 20, 70));
The following is an example to change JLabel background and foreground color:
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import javax.swing.border.Border;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      label = new JLabel("This is demo label!",JLabel.RIGHT);
      label.setVerticalAlignment(JLabel.TOP);
      label.setFont(new Font("Verdana", Font.PLAIN, 15));
      label.setForeground(new Color(120, 90, 40));
      label.setBackground(new Color(100, 20, 70));
      Border border = BorderFactory.createLineBorder(Color.ORANGE);
      label.setBorder(border);
      frame.add(label);
      frame.setSize(600,300);
      frame.setVisible(true);
   }
}
How to add separator to numbers using MySQL views?

Let us first create a table −
mysql> create table DemoTable
(
   StudentId int
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(343898456);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(222333444);
Query OK, 1 row affected (0.22 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| 343898456 |
| 222333444 |
+-----------+
2 rows in set (0.00 sec)
Here is the query to create view −
mysql> create view myView_DemoTable as select format(StudentId, 0) AS `StudentId` from DemoTable;
Query OK, 0 rows affected (0.18 sec)
Let us check the records of view table:
mysql> select *from myView_DemoTable;
This will produce the following output −
+-------------+
| StudentId   |
+-------------+
| 343,898,456 |
| 222,333,444 |
+-------------+
2 rows in set (0.04 sec)
Tryit Editor v3.7

Tryit: Background image and background-size: cover
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

07 Sep, 2018
A bit-stuffing based framing protocol uses an 8-bit delimiter pattern of 01111110. If the output bit-string after stuffing is 01111100101, then the input bit-string is(A) 0111110100(B) 0111110101(C) 0111111101(D) 0111111111Answer: (B)Explanation: Bit Stuffing is used to create framing.
8-bit delimiter pattern is 01111110. 

The output bit-string after stuffing is 01111100101.

The above highlighted bit is stuffed bit.  
So input bit-string must be 0111110101.
Alternative approach –The given delimiter pattern is 01111110. Delimiters are used to define the beginning and end of data.Since delimiters are special bit-patterns used for special purposes, they must be avoided in the encoded form of the input data. To achieve this, Bit Stuffing is used.On the sending side, any time five consecutive 1’s have been transmitted from the body of the message (i.e., excluding when the sender is trying to transmit the distinguished 01111110 delimiter sequence), the sender inserts a 0 before transmitting the next bit.If the receiver gets five consecutive 1’s, it makes its decision based on the next bit it sees (i.e., the bit following the five 1s).If the next bit is a 0, it must have been stuffed, and so the receiver removes it.If the next bit is a 1, then one of two things is true: Either this is the end-of-frame marker or an error has been introduced into the bit stream.Going further and reading the next bit distinguishes these two cases. If the next bit is 0, then it is the end of frame marker (delimiter 01111110), and if the next bit is a 1 then there is must be an error in the frame and it is discarded.So, For the data sequence 0111111101Encoding would be – 01111101101Here the bold 0 is stuffed to distinguish it from the delimiter sequence.Coming back to the question, the encoded string is – 01111100101 and when the receiver senses that it has received 5 consecutive 1’s thenIf the next bit is 0, then it is stuffedIf the next bit is 1, then next to next bit would tell if the frame has ended or there is an error.In this case, the next bit is 0 which means it was stuffed, so the corresponding input sequence is- 0111110101.Therefore, option (B) is correct.
This explanation is provided by Chirag Manwani. Quiz of this Question
KAPILGAHLOT
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2010 | Question 33
Lifting state up in React.js

Often there will be a need to share state between different components. The common approach to share state between two components is to move the state to common parent of the two components. This approach is called as lifting state up in React.js
With the shared state, changes in state reflect in relevant components simultaneously. This is a single source of truth for shared state components.
We have a App component containing PlayerContent and PlayerDetails component. PlayerContent shows the player name buttons. PlayerDetails shows the details of the in one line.
The app component contains the state for both the component. The selected player is shown once we click on the one of the player button.
import React from 'react';
import PlayerContent from './PlayerContent';
import PlayerDetails from './PlayerDetails';
import './App.css';
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = { selectedPlayer:[0,0], playerName: ''};
      this.updateSelectedPlayer = this.updateSelectedPlayer.bind(this);
   }
   updateSelectedPlayer(id, name) {
      var arr = [0, 0, 0, 0];
      arr[id] = 1;
      this.setState({
         playerName: name,
         selectedPlayer: arr
      });
   }
   render () {
      return (
         <div>
            <PlayerContent active={this.state.selectedPlayer[0]}
            clickHandler={this.updateSelectedPlayer} id={0} name="David"/>
            <PlayerContent active={this.state.selectedPlayer[1]}
            clickHandler={this.updateSelectedPlayer} id={1} name="Steve"/>
            <PlayerDetails name={this.state.playerName}/>
         </div>
      );
   }
}
export default App;
import React , { Component} from 'react';
class PlayerContent extends Component {
   render () {
      return (
         <button onClick={() => {this.props.clickHandler(this.props.id, this.props.name)}} style={{color: this.props.active? 'red': 'blue'}}>{this.props.name}
         </button>
      );
   }
}
export default PlayerContent;
import React, { Component } from 'react';
class PlayerDetails extends Component {
   render () {
      return (
         <div>{this.props.name}
         </div>
      );
   }
}
export default PlayerDetails;
the output displays as −
How to lock screen orientation on all android devices programmatically?

This example demonstrates how do I lock screen orientation on all android devices programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Screen Orientation Lock"
      android:textSize="24sp"
      android:textStyle="bold"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      int currentOrientation = getResources().getConfiguration().orientation;
      if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      }else {
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      }
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Getting the highest value of a column in MongoDB?

To get the highest value of a column in MongoDB, you can use sort() along with limit(1). The syntax is as follows −
db.yourCollectionName.find().sort({"yourFieldName":-1}).limit(1);
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.gettingHighestValueDemo.insertOne({"Value":1029});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b885705caea966c5574")
}
> db.gettingHighestValueDemo.insertOne({"Value":3029});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b8d5705caea966c5575")
}
> db.gettingHighestValueDemo.insertOne({"Value":1092});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b925705caea966c5576")
}
> db.gettingHighestValueDemo.insertOne({"Value":18484});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b955705caea966c5577")
}
> db.gettingHighestValueDemo.insertOne({"Value":37474});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b9c5705caea966c5578")
}
> db.gettingHighestValueDemo.insertOne({"Value":88474});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900ba75705caea966c5579")
}
> db.gettingHighestValueDemo.insertOne({"Value":1938474});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900bab5705caea966c557a")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.gettingHighestValueDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c900b885705caea966c5574"), "Value" : 1029 }
{ "_id" : ObjectId("5c900b8d5705caea966c5575"), "Value" : 3029 }
{ "_id" : ObjectId("5c900b925705caea966c5576"), "Value" : 1092 }
{ "_id" : ObjectId("5c900b955705caea966c5577"), "Value" : 18484 }
{ "_id" : ObjectId("5c900b9c5705caea966c5578"), "Value" : 37474 }
{ "_id" : ObjectId("5c900ba75705caea966c5579"), "Value" : 88474 }
{ "_id" : ObjectId("5c900bab5705caea966c557a"), "Value" : 1938474 }
Here is the query to get the highest value of a column in MongoDB −
> db.gettingHighestValueDemo.find().sort({"Value":-1}).limit(1);
The following is the output displaying the highest value −
{ "_id" : ObjectId("5c900bab5705caea966c557a"), "Value" : 1938474 }
How to define the number of breaks in base R histogram?

To define the number of breaks in base R histogram, we can use breaks argument along
with hist function.
Use a vector with normal distribution and the histogram of the same vector with ten
breaks −
 Live Demo
x<-rnorm(10000)
hist(x,breaks=10)
Use a vector with normal distribution and the histogram of the same vector with fifty breaks −
 Live Demo
x<-rnorm(10000)
hist(x,breaks=50)
Use a vector with normal distribution and the histogram of the same vector with twohundred breaks −
 Live Demo
x<-rnorm(10000)
hist(x,breaks=200)
Use a vector with normal distribution and the histogram of the same vector with fifty breaks −
 Live Demo
x<-rnorm(10000)
hist(x,breaks=50)
How to use MySQL JOIN without ON condition?

We can use ‘cross join’ without on condition. Cross join gives the result in cartesian product form. For instance, if in one table there are 3 records and another table has 2 records, then the first record will match with all the second table records. Then, the same process will be repeated for second record and so on.
Creating the first table
mysql> CREATE table ForeignTableDemo
   - > (
   - > Id int,
   - > Name varchar(100),
   - > FK int
   - > );
Query OK, 0 rows affected (0.47 sec)
Creating the second table
mysql> CREATE table PrimaryTableDemo
   - > (
   - >  FK int,
   - > Address varchar(100),
   - > primary key(FK)
   - > );
Query OK, 0 rows affected (0.47 sec)
mysql> ALTER table ForeignTableDemo add constraint FKConst foreign key(FK) references PrimaryTableDemo(FK);
Query OK, 0 rows affected (1.54 sec)
Records: 0  Duplicates: 0  Warnings: 0
To add records into the second table.
mysql> INSERT into PrimaryTableDemo values(1,'US');
Query OK, 1 row affected (0.10 sec)

mysql> INSERT into PrimaryTableDemo values(2,'UK');
Query OK, 1 row affected (0.14 sec)

mysql>  INSERT into PrimaryTableDemo values(3,'Unknown');
Query OK, 1 row affected (0.08 sec)
Displaying records of the second table.
mysql> SELECT * from PrimaryTableDemo;
The following is the output of the above query.
+----+---------+
| FK | Address |
+----+---------+
|  1 | US      |
|  2 | UK      |
|  3 | Unknown |
+----+---------+
3 rows in set (0.00 sec)

To add records into the first table.
mysql>  INSERT into ForeignTableDemo values (1,'John',1);
Query OK, 1 row affected (0.20 sec)

mysql>  INSERT into ForeignTableDemo values (2,'Bob',2);
Query OK, 1 row affected (0.27 sec)
Displaying records using the SELECT command.
mysql> SELECT * from ForeignTableDemo;
The following is the output.
+------+------+------+
| Id   | Name | FK   |
+------+------+------+
|    1 | John |    1 |
|    2 | Bob  |    2 |
+------+------+------+
2 rows in set (0.00 sec)

We have made a foreign key constraint for all the tables. Now, to use ‘cross join’ without ON, let us see the syntax.
mysql> SELECT ForeignTableDemo.Id, ForeignTableDemo.Name, PrimaryTableDemo.Address
   - > from ForeignTableDemo
   - > cross join PrimaryTableDemo;
Here is the output.
+------+------+---------+
| Id   | Name | Address |
+------+------+---------+
|    1 | John | US      |
|    2 | Bob  | US      |
|    1 | John | UK      |
|    2 | Bob  | UK      |
|    1 | John | Unknown |
|    2 | Bob  | Unknown |
+------+------+---------+
6 rows in set (0.00 sec)
Conversion of J-K Flip-Flop into D Flip-Flop - GeeksforGeeks

22 Apr, 2020
Prerequisite – Flip-flop
1. JK Flip-Flop:JK Flip-Flip is basically a gated SR flip-flop which has an additional input that is clock input. It prevents the invalid output that may be obtained when both the inputs are 1.
2. D Flip-Flop:D Flip-Flop is a modified SR flip-flop which has an additional inverter. It prevents the inputs from becoming the same value.
Conversion of J-K Flip-Flop into D Flip-Flop:
Step-1:We construct the characteristic table of D flip-flop and excitation table of JK flip-flop.
Step-2:Using the K-map we find the boolean expression of J and K in terms of D.J = D
K = D' 
J = D
K = D' 
Step-3:We construct the circuit diagram of the conversion of JK flip-flop into D flip-flop.
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to memory and memory units
Analog to Digital Conversion
Introduction of Sequential Circuits
Restoring Division Algorithm For Unsigned Integer
Latches in Digital Logic
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Char.Parse(String) Method in C#

The Char.Parse(String) method in C# is used to convert the value of the specified string to its equivalent Unicode character.
Following is the syntax −
public static char Parse (string str);
Above, the string str is a string that contains a single character or null.
Let us now see an example to implement the Char.Parse(String) method −
using System;
public class Demo {
   public static void Main(){
      string str ="a";
      char res = Char.Parse(str);
      Console.WriteLine("Value = "+str);
      Console.WriteLine("Equivalent Unicode character = "+res);
   }
}
This will produce the following output −
Value = a
Equivalent Unicode character = a
Let us now see another example −
using System;
public class Demo {
   public static void Main(){
      string str ="#";
      char res = Char.Parse(str);
      Console.WriteLine("Value = "+str);
      Console.WriteLine("Equivalent Unicode character = "+res);
   }
}
This will produce the following output −
Value = #
Equivalent Unicode character = #
How to Import Python Packages in Julia? - GeeksforGeeks

10 Aug, 2021
Julia is a high-level, high-performance, dynamic programming language for numerical computing.  Users can import arbitrary Python modules and libraries into Julia. PyCall package is provided for calling Python from Julia code. You can use PyCall from any Julia code, including within Julia modules. And add this package to the Julia environment with Pkg.add (“PyCall”).
PyCall provides many routines for manipulating Python objects in Julia via a type PyObject. In most cases, PyCall automatically makes the appropriate type conversions to Julia types based on runtime inspection of the Python objects.
To Import Python Packages in Julia. Follow the steps below:
Step 1: using Pkg  
Step 2: Pkg.add(“PyCall”)  
Step 3: using PyCall  
Step 4: @pyimport python_library_name 
or  
Step 4: pyimport(“python_library_name”)  
Example 1:
Julia
# Julia program to import math python packageusing Pkg # add PyCall packagePkg.add("PyCall")   # use PyCallusing PyCall        # import python library@pyimport math      print(math.sin(90))
 Output:
Example 1
 
Example 2: 
Julia
# Julia program to import numpy python libraryusing Pkg # add PyCall packagePkg.add("PyCall")      # use PyCall packageusing PyCall           # import python library@pyimport numpy        # or np = pyimport("numpy") # define array using numpyarray1 = numpy.array([1, 2, 3, 4,                      5, 6, 7, 8, 9])   # print arrayprint(array1)print('\n') # print array meanprint(numpy.mean(array1))
 Output:
Example 2
 
Use the following to run packages that are not standard (and are local to your Python IDLE) or using a different environment instead of the standard python env that Julia chooses when @pyimport is invoked. After executing the following two lines, stop and restart the Julia REPL. Note that the location provided corresponds to the directory where your python.exe is located. In my case it was C:\\Users\\hi\\AppData\\Local\\Programs\\Python\\Python37. 
Julia
ENV["PYTHON"]="C:\\Users\\hi\\AppData\\Local\\Programs\\Python\\Python37"Pkg.build("PyCall")
Once you have restarted Julia, you can use the usual pyimport to call the respective package local to your installation.  Let’s look at an example where I have a package named “cantera” for thermochemical calculations installed in my local environment. I would then use: 
Julia
@pyimport cantera as ctct.Solution("gri30.xml")
rsuryanarayan
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Getting the maximum value from a list in Julia - max() Method
Get array dimensions and size of a dimension in Julia - size() Method
Functions in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Importing data from Files in Julia
Working with Text Files in Julia
Calculate exponential of a value in Julia - exp(), exp10(), exp2(), expm1() and frexp() Methods
Working with Date and Time in Julia
Julia global Keyword | Creating a global variable in Julia
Getting first element of an array in Julia - first() Method
How to plot a bar graph in Matplotlib from a Pandas series?

To plot a bar graph from a Pandas series in matplotlib, we can take the following Steps −
Make a dictionary of different keys, between the range 1 to 10.
Make a dictionary of different keys, between the range 1 to 10.
Make a dataframe using Pandas data frame.
Make a dataframe using Pandas data frame.
Create a bar plot using plot() method with kind="bar".
Create a bar plot using plot() method with kind="bar".
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = {'y=1/x': [1 / i for i in range(1, 10)],
   'y=x': [i for i in range(1, 10)],
   'y=x^2': [i * i for i in range(1, 10)],
   'y=x^3': [i * i * i for i in range(1, 10)]}
df = pd.DataFrame(d)
df.plot(kind='bar')
plt.show()
SVG - Rect

<rect> element is used to draw rectangle which is axis aligned with the current user co-ordinate system.
Following is the syntax declaration of <rect> element. We've shown main attributes only.
<rect
   x="x-axis co-ordinate"
   y="y-axis co-ordinate"
   
   width="length"
   height="length"
   
   rx="length"
   ry="length"
   
   style="style information"
   class="style class" >
</rect>
<html>
   <title>SVG Rectangle</title>
   <body>
      
      <h1>Sample SVG Rectangle Image</h1>
      
      <svg width="800" height="800">
         <g>
            <text x="0" y="15" fill="black" >
            Rectangle #1: Without opacity.</text>
            
            <rect x="100" y="30" width="300" height="100" 
            style="fill:rgb(121,0,121);stroke-width:3;stroke:rgb(0,0,0)"></rect> 
         </g> 
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9  and higher also supports SVG image rendering.
<html>
   <title>SVG Rectangle</title>
   <body>
      
      <h1>Sample SVG Rectangle Image</h1>
      
      <svg width="800" height="800">
         <g>
            <text x="0" y="15" fill="black" >
            Rectangle #2: With opacity </text>
            
            <rect x="100" y="30" width="300" height="100" 
            style="fill:rgb(121,0,121);stroke-width:3;stroke:rgb(0,0,0);
            stroke-opacity:0.5;opacity:0.5"> </rect>
         </g>
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9  and higher also supports SVG image rendering.
<html>
   <title>SVG Rectangle</title>
   <body>
      
      <h1>Sample SVG Rectangle Image</h1>
      
      <svg width="570" height="200">
         <g>
            <text x="0" y="15" fill="black" >
            Rectangle #3: With Rounded Corner </text>
            
            <rect x="100" y="100" rx="10" ry="10" width="300" height="100" 
            style="fill:rgb(121,0,121);stroke-width:3;stroke:rgb(0,0,0);"></rect>
         </g>
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Generate all combinations of a specific size from a single set in PHP

To generate all combinations of a specific size from a single set, the code is as follows −
 Live Demo
function sampling($chars, $size, $combinations = array()) {
   # in case of first iteration, the first set of combinations is the same as the set of characters
   if (empty($combinations)) {
      $combinations = $chars;
   }
   # size 1 indicates we are done
   if ($size == 1) {
      return $combinations;
   }
   # initialise array to put new values into it
   $new_combinations = array();
   # loop through the existing combinations and character set to create strings
   foreach ($combinations as $combination) {
      foreach ($chars as $char) {
         $new_combinations[] = $combination . $char;
      }
   }
   # call the same function again for the next iteration as well
   return sampling($chars, $size - 1, $new_combinations);
}
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);
This will produce the following output −
array(9) { [0]=> string(2) "aa" [1]=> string(2) "ab" [2]=> string(2) "ac" [3]=> string(2) "ba" [4]=> string(2) "bb" [5]=> string(2) "bc" [6]=> string(2) "ca" [7]=> string(2) "cb" [8]=> string(2) "cc" }
The first iteration indicates the same set of characters to be displayed. If the size is 1, then the combination is displayed. An array is initialized as ‘new_combinations’ and it is looped through using the ‘forloop’ and every character in that string is concatenated with every other character. The function ‘sampling’ is called with the parameters (string, the size of the string and the array).
Reverse Integer in Python

Suppose we have one 32-bit signed integer number. We have to take the number and reverse the digits. So if the number is like 425, then the output will be 524. Another thing we have to keep in mind that the number is signed, so there may be some negative numbers. So if the number is –425, then it will be –524.
Here we have some assumptions. We have assumed that we are using in the domain of 32-bit signed integer. So the range will be [-232 to 232 – 1]. So if the number is not in range, then the function will return 0.
To solve this, we will use the Python Code. At first we will convert the given integer into string. So if the first character in the string is ‘-’, then the number is negative number, so reverse from index 1 to index length – 1. And finally convert them to integer before returning it, for positive number, simply reverse the string and make it integer before returning. In each case we will check whether the number is in range of 32-bit integers. If it exceeds the range, then simply return 0.
Let us see the implementation to get better understanding
 Live Demo
class Solution(object):
   def reverse(self, x):
      """
      :type x: int
      :rtype: int
      """
      x = str(x)
      if x[0] == '-':
         a = int('-' + x[-1:0:-1])
         if a >= -2147483648 and a<= 2147483647:
            return a
         else:
            return 0
         else:
            a = int(x[::-1])
            if a >= -2147483648 and a<= 2147483647:
               return a
            else:
               return 0
ob1 = Solution()
print(ob1.reverse(-425))
print(ob1.reverse(-425))
-524
Difference between Delete and truncate in sql query

Delete and truncate both commands can be used to delete data of the table. 
Delete is a DML command whereas truncate is DDL command. Truncate can be used to delete the entire data of the table without maintaining the integrity of the table. On the other hand , delete statement can be used for deleting the specific data. With delete command we can’t bypass the integrity enforcing mechanisms.
1
Basic 
It is used to delete specific data 
It is used to delete the entire data of the table 
2
       Where clause 
We can use with where clause 
It can’t be used with where clause 
3
Locking 
It locks the table row before deleting the row 
It locks the entire table 
4
Rollback 
We can rollback the changes.
We can’t rollback the changes 
5
Performance
It is slower than truncate 
It is faster than delete 
//TRUNCATE Query
TRUNCATE TABLE tableName;
//Delete
DELETE FROM tableName WHERE condition;
Declare static variables and methods in an abstract class in Java

If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.
A static variable is a class variable. A single copy of the static variable is created for all instances of the class. It can be directly accessed in a static method.
An abstract class in Java is a class that cannot be instantiated. It is mostly used as the base for subclasses to extend and implement the abstract methods and override or access the implemented methods in abstract class.
 Live Demo
abstract class Parent {
   static void display() {
      System.out.println("Static method in an abstract class");
   }
   static int x = 100;
}
public class Example extends Parent {
   public static void main(String[] args) {
      Parent obj = new Example();
      obj.display();
      System.out.print(Parent.x);
   }
}
The output is as follows −
Static method in an abstract class
100
Resolve usage of quotes ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use?

In MySQL, you can use two different types of quotation marks which is backtick and another is single quotes or double quotes. In this case, maybe you are using single quotes to the column name that’s why you are getting error. You need to use the backtick symbol (` `) instead of single quotes. Backtick can be used with column names while single quotes can be used for strings.
To understand the above error, let us create a table. The query to create a table is as follows −
mysql> create table Backtick_SymbolDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),  
   -> FileName varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.81 sec)
The error occurs if we use single quotes instead of backtick symbol around the column as shown below. Here, we have inserted a value with single quotes and the error is visible −
mysql> insert into Backtick_SymbolDemo(`Name`,'FileName') values('John','Sum.cpp');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''FileName') values('John','Sum.cpp')' at line 1
To avoid this error either use the backtick symbol around the all column name or do not use both the backtick or single quotes.
The query to insert record is as follows. Here is the use of the backtick symbol around both column name.
mysql> insert into Backtick_SymbolDemo(`Name`,`FileName`) values('John','Sum.cpp');
Query OK, 1 row affected (0.12 sec)
Here is the insert record without using the backtick symbol. The query is as follows −
mysql> insert into Backtick_SymbolDemo(Name,FileName) values('Larry','SocketProgram.java');
Query OK, 1 row affected (0.23 sec)
mysql> insert into Backtick_SymbolDemo(Name,FileName) values('Mike','UserCreationScript.sql');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from Backtick_SymbolDemo;
The following is the output −
+----+-------+------------------------+
| Id | Name  | FileName               |
+----+-------+------------------------+
|  1 | John  | Sum.cpp                |
|  2 | Larry | SocketProgram.java     |
|  3 | Mike  | UserCreationScript.sql |
+----+-------+------------------------+
3 rows in set (0.00 sec)
ISRO | ISRO CS 2008 | Question 75

13 Jun, 2018
How many comparisons are needed to sort an array of length 5 if a straight selection sort is used and array is already in the opposite order?(A) 1(B) 5(C) 10(D) 20Answer: (C)Explanation: Consider the array: 5 4 3 2 1
1st iteration will compare 4 numbers with the 52nd iteration will compare 3 numbers with the 43rd iteration will compare 2 numbers with the 34th iteration i will compare 1 number with the 2
So, the total number of comparisons is 4 + 3 + 2 + 1 = 10It can be viewed as the sum of the sequence of the first (n-1) numbers starting by 1
S = ((1 + (n-1) )*(n-1) )/2S = 10
Option (C) is correct.Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2011 | Question 56
ISRO | ISRO CS 2018 | Question 17
ISRO | ISRO CS 2011 | Question 70
ISRO | ISRO CS 2007 | Question 12
ISRO | ISRO CS 2015 | Question 7
ISRO | ISRO CS 2013 | Question 15
ISRO | ISRO CS 2009 | Question 27
ISRO | ISRO CS 2017 - May | Question 14
ISRO | ISRO CS 2017 - May | Question 21
ISRO | ISRO CS 2013 | Question 52
PHP | opendir() Function

11 Jul, 2018
The opendir() function in PHP is an inbuilt function which is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.
The opendir() function is used to open up a directory handle to be used in subsequent with other directory functions such as closedir(), readdir(), and rewinddir().
Syntax:
opendir($path, $context)
Parameters Used: The opendir() function in PHP accepts two parameters.
$path : It is a mandatory parameter which specifies the path of the directory to be opened.
$context : It is an optional parameter which specifies the behavior of the stream.
Return Value: It returns a directory handle resource on success, or FALSE on failure.
Errors And Exceptions:
A PHP error of level E_WARNING is generated and opendir() returns FALSE if the path is not a valid directory or the directory cannot be opened due to permission restrictions or filesystem errors.The error output of opendir() can be suppressed by prepending ‘@’ to the front of the function name.
A PHP error of level E_WARNING is generated and opendir() returns FALSE if the path is not a valid directory or the directory cannot be opened due to permission restrictions or filesystem errors.
The error output of opendir() can be suppressed by prepending ‘@’ to the front of the function name.
Below programs illustrate the opendir() function:Program 1:
<?php  // Opening a directory$dir_handle = opendir("/user/gfg/docs/");  if(is_resource($dir_handle)){     echo("Directory Opened Successfully.");}   // closing the directoryclosedir($dir_handle);  else{    echo("Directory Cannot Be Opened.");}   ?>
Output:
Directory Opened Successfully.

Program 2:
<?php  // opening a directory and reading its contents$dir_handle = opendir("user/gfg/sample.docx");  if(is_resource($dir_handle)) {     while(($file_name = readdir($dir_handle)) == true)     {         echo("File Name: " . $file_Name);        echo "<br>" ;     }       // closing the directory    closedir($dir_handle);}else{echo("Directory Cannot Be Opened.");}?>
Output:
File Name: sample.docx

Reference: http://php.net/manual/en/function.opendir.php
PHP-file-handling
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to delete an array element based on key in PHP?
PHP in_array() Function
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
GATE | GATE-CS-2006 | Question 65

14 Feb, 2018
Consider three processes, all arriving at time zero, with total execution time of 10, 20 and 30 units, respectively. Each process spends the first 20% of execution time doing I/O, the next 70% of time doing computation, and the last 10% of time doing I/O again. The operating system uses a shortest remaining compute time first scheduling algorithm and schedules a new process either when the running process gets blocked on I/O or when the running process finishes its compute burst. Assume that all I/O operations can be overlapped as much as possible. For what percentage of time does the CPU remain idle?
(A) 0%(B) 10.6%(C) 30.0%(D) 89.4%Answer: (B)Explanation:
Shortest remaining time ( SRT ) scheduling algorithm selects the process for execution which has the smallest amount of time remaining until completion.
Let three processes be p0, p1 and p2. Their execution time is 10, 20 and 30 respectively.
p0 spends first 2 time units in I/O, 7 units of CPU time and finally 1 unit in I/O.p1 spends first 4 units in I/O, 14 units of CPU time and finally 2 units in I/O.p2 spends first 6 units in I/O, 21 units of CPU time and finally 3 units in I/O.
AT- Arrival Time, IO-input/output, BT-Burst Time
first process p0 will spend 2 units in IO, next 7 units in BT, then process p1 will spend 14 units in BT (as its 4 units of IO has been spent already when previous process was running) and ten process p2 will spend 21 units in BT (as its 6 units of IO has been spent already when previous processes were running) and atlast 3 units in IO (process p0,p1,p2’s last IO included.)
idle   p0    p1     p2    idle
0    2     9     23     44     47

Total time spent = 47
Idle time = 2 + 3 = 5
Percentage of idle time = (5/47)*100 = 10.6 %

See Question 2 of https://www.geeksforgeeks.org/operating-systems-set-15/
This solution is contributed by Nitika BansalQuiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2010 | Question 54
GATE | GATE-CS-2015 (Set 1) | Question 19
GATE | GATE CS 2018 | Question 43
GATE | Gate IT 2008 | Question 59
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2006 | Question 45
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2013 | Question 25
GATE | GATE-CS-2003 | Question 77
Python | Ways to sum list of lists and return sum list

29 Jul, 2019
The list is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary. Given a list of lists, the program to suppose to return the sum as the final list.
Let’s see some of the methods to sum a list of list and return list.
Method # 1: Using Naive method
# Python code to demonstrate# sum of list of list# using naive method  # Declaring initial list of listL = [[1, 2, 3],     [4, 5, 6],     [7, 8, 9]]          # Printing list of listprint("Initial List - ", str(L))  # Using naive methodres = list()for j in range(0, len(L[0])):    tmp = 0    for i in range(0, len(L)):        tmp = tmp + L[i][j]    res.append(tmp)      # printing resultprint("final list - ", str(res))
Initial List -  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
final list -  [12, 15, 18]

 Method #2: Using numpy arrayA numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays.
# Python code to demonstrate# sum of list of list# using numpy array functionsimport numpy as np  # Declaring initial list of listList = np.array([[1, 2, 3],                 [4, 5, 6],                 [7, 8, 9]])          # Printing list of listprint("Initial List - ", str(List))  # Using numpy sumres = np.sum(List, 0)      # printing resultprint("final list - ", str(res))
Initial List -  [[1 2 3]
                 [4 5 6]
                 [7 8 9]]
final list -  [12 15 18]

 Method #3: Using zip() and list comprehension
# Python code to demonstrate# sum of list of list using # zip and list comprehension  # Declaring initial list of listList = [[1, 2, 3],        [4, 5, 6],        [7, 8, 9]]          # Printing list of listprint("Initial List - ", str(List))  # Using list comprehensionres = [sum(i) for i in zip(*List)]      # printing resultprint("final list - ", str(res))
Initial List -  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
final list -  [12, 15, 18]

nidhi_biet
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
PHP | array_map() Function

06 Jan, 2018
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
Syntax:
array_map(functionName,arr1,arr2...)

Parameters used:This function takes 2 compulsory parameter functionName and arr1 and the rest are optional.
functionName(mandatory): This parameter defines the name of the user-defined function according to which the values in the array will be modified.
arr1(mandatory): This parameter specifies the array to be modified.
arr2(mandatory): This parameter specifies the array to be modified.
The functionName parameter is compulsory and we can pass any number of arrays to this function named arr1, arr2.. arrn and so on.
Return type : This function returns an array containing all the elements of arr1 after applying the user_function() to each one.
Below program illustrates the working of array_map() function in PHP:
<?php  function fun1($v){  return ($v + 7);     // add 7 }  function fun2($v1,$v2){    if ($v1 == $v2) return 1;         else return 0;  }  $arr1 = array(1, 2, 3, 4, 5);$arr2 = array(1, 3, 3, 4, 8);  print_r(array_map("fun1", $arr1));  print_r(array_map("fun2", $arr1, $arr2));    ?>
Output:
Array
(
    [0] => 8
    [1] => 9
    [2] => 10
    [3] => 11
    [4] => 12
)
Array
(
    [0] => 1
    [1] => 0
    [2] => 1
    [3] => 1
    [4] => 0
)

Creating an array of arrays using array_map(): We can also use the array_map() function in PHP to create array of arrays. To do this we have to pass null as parameter in place of functionName parameter and the list of arrays to create an array of arrays.
Below program illustrates how to create an array of arrays:
<?php$a = array(1, 2, 3);$b = array("one", "two", "three");  $result = array_map(null, $a, $b);  print_r($result);?>
Output:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
        )

)

PHP-array
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to create footer to stay at the bottom of a Web page?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
ReactJS | Router
Kotlin while loop

24 Sep, 2021
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines.
While loop – It consists of a block of code and a condition. First of all the condition is evaluated and if it is true then execute the code within the block. It repeats until the condition becomes false because every time the condition is checked before entering into the block. The while loop can be thought of as repeating of if statements.
The syntax of while loop- 
while(condition) {
           // code to run
}
Flowchart- 
Kotlin program to print numbers from 1 to 10 using while loop:In below program, we print the numbers using while loop. First, initialize the variable number by 1. Put the expression (number <= 10) in while loop and checks is it true or not?. If true, enters in the block and execute the print statement and increment the number by 1. This repeats until the condition becomes false. 
Java
fun main(args: Array<String>) {    var number = 1     while(number <= 10) {        println(number)        number++;    }}
Output: 
1
2
3
4
5
6
7
8
9
10
Kotlin program to print the elements of an array using while loop: In the below program we create an array(names) and initialize with different number of strings and also initialize a variable index by 0. The size of an array can be calculated by using arrayName.size. Put the condition (index < names.size) in the while loop. If index value less than or equal to array size then it enters into the block and print the name stored at the respective index and also increment the index value after each iteration. This repeats until the condition becomes false. 
Java
fun main(args: Array<String>) {    var names = arrayOf("Praveen","Gaurav","Akash","Sidhant","Abhi","Mayank")    var index = 0     while(index < names.size) {        println(names[index])        index++    }}
Output: 
Praveen
Gaurav
Akash
Sidhant
Abhi
Mayank
 
rajeev0719singh
simmytarika5
Kotlin Control-flow
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How many ways a String object can be created in java?

You can create a String by −
Step 1 − Assigning a string value wrapped in " " to a String type variable.
String message = "Hello Welcome to Tutorialspoint";
Step 2 − Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor.
String message = new String ("Hello Welcome to Tutorialspoint");
Step 3 − Passing a character array to the String constructor.
char arr[] = {'H','e','l','l','o'};
String message = new String(arr);