code-rag-bench/online-tutorials huggingface dataset:
File Searching using Python

Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.
In the below example we are searching for a file named smpl.htm starting at the root directory named “D:\”. The os.walk() function searches the entire directory and each of its subdirectories to locate this file. As the result we see that the file is present in both the main directory and also in a subdirectory. We are running this program in a windows OS.
import os

def find_files(filename, search_path):
   result = []

# Wlaking top-down from the root
   for root, dir, files in os.walk(search_path):
      if filename in files:
         result.append(os.path.join(root, filename))
   return result

print(find_files("smpl.htm","D:"))
Running the above code gives us the following result −
['D:TP\\smpl.htm', 'D:TP\\spyder_pythons\\smpl.htm']
MongoDB query to remove a specific document

To remove a specific document, use remove() in MongoDB. Let us create a collection with documents −
> db.demo56.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e272e0bcfb11e5c34d89917")
}
> db.demo56.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e272e10cfb11e5c34d89918")
}
> db.demo56.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e272e13cfb11e5c34d89919")
}
Display all documents from a collection with the help of find() method −
> db.demo56.find();
This will produce the following output −
{ "_id" : ObjectId("5e272e0bcfb11e5c34d89917"), "Name" : "Chris" }
{ "_id" : ObjectId("5e272e10cfb11e5c34d89918"), "Name" : "David" }
{ "_id" : ObjectId("5e272e13cfb11e5c34d89919"), "Name" : "Bob" }
Following is the query to remove a specific document −
> db.demo56.remove({_id:ObjectId("5e272e10cfb11e5c34d89918")});
WriteResult({ "nRemoved" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo56.find();
This will produce the following output −
{ "_id" : ObjectId("5e272e0bcfb11e5c34d89917"), "Name" : "Chris" }
{ "_id" : ObjectId("5e272e13cfb11e5c34d89919"), "Name" : "Bob" }
How to Resize an image in Android using Picasso on Kotlin?

This example demonstrates how to Resize an image in Android using Picasso on Kotlin.
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.
<LinearLayout 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"
   android:orientation="vertical"
   android:paddingStart="16dp"
   android:paddingTop="16dp"
   android:paddingEnd="16dp"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>
Step 3 − Add the following dependency to build.gradle(Module:app)
implementation 'com.squareup.picasso:picasso:2.5.2'
Step 4 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.Picasso
class MainActivity : AppCompatActivity() {
   private lateinit var imageView: ImageView
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      imageView = findViewById(R.id.imageView)
      val url = "https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg"
      Picasso.with(this).load(url).resize(600, 500).into(imageView)
   }
}
Step 5 − 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.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
   <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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
POJO vs Java Beans

As we know that in Java POJO refers to the Plain old Java object.POJO and Bean class in Java shares some common features which are as follows −
Both classes must be public i.e accessible to all.
Both classes must be public i.e accessible to all.
Properties or variables defined in both classes must be private i.e. can't be accessed directly.
Properties or variables defined in both classes must be private i.e. can't be accessed directly.
Both classes must have default constructor i.e no argument constructor.
Both classes must have default constructor i.e no argument constructor.
Public Getter and Setter must be present in both the classes in order to access the variables/properties.
Public Getter and Setter must be present in both the classes in order to access the variables/properties.
The only difference between both the classes is Java make java beans objects serialized so that the state of a bean class could be preserved in case required.So due to this a Java Bean class must either implements Serializable or Externalizable interface.
Due to this it is stated that all JavaBeans are POJOs but not all POJOs are JavaBeans.
public class Employee implements java.io.Serializable {
   private int id;
   private String name;
   public Employee(){}
   public void setId(int id){this.id=id;}
   public int getId(){return id;}
   public void setName(String name){this.name=name;}
   public String getName(){return name;}
}
public class Employee {
   String name;
   public String id;
   private double salary;
   public Employee(String name, String id,double salary) {
      this.name = name;
      this.id = id;
      this.salary = salary;
   }
   public String getName() {
      return name;
   }
   public String getId() {
      return id;
   }
   public Double getSalary() {
      return salary;
   }
}
Unix / Linux Shell - The case...esac Statement

You can use multiple if...elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Shell supports case...esac statement which handles exactly this situation, and it does so more efficiently than repeated if...elif statements.
The basic syntax of the case...esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
case word in
   pattern1)
      Statement(s) to be executed if pattern1 matches
      ;;
   pattern2)
      Statement(s) to be executed if pattern2 matches
      ;;
   pattern3)
      Statement(s) to be executed if pattern3 matches
      ;;
   *)
     Default condition to be executed
     ;;
esac

Here the string word is compared against every pattern until a match is found. The statement(s) following the matching pattern executes. If no matches are found, the case statement exits without performing any action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should jump to the end of the entire case statement. This is similar to break in the C programming language.
#!/bin/sh

FRUIT="kiwi"

case "$FRUIT" in
   "apple") echo "Apple pie is quite tasty." 
   ;;
   "banana") echo "I like banana nut bread." 
   ;;
   "kiwi") echo "New Zealand is famous for kiwi." 
   ;;
esac
Upon execution, you will receive the following result −
New Zealand is famous for kiwi.

A good use for a case statement is the evaluation of command line arguments as follows −
#!/bin/sh

option="${1}" 
case ${option} in 
   -f) FILE="${2}" 
      echo "File name is $FILE"
      ;; 
   -d) DIR="${2}" 
      echo "Dir name is $DIR"
      ;; 
   *)  
      echo "`basename ${0}`:usage: [-f file] | [-d directory]" 
      exit 1 # Command to come out of the program with status 1
      ;; 
esac 
Here is a sample run of the above program −
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Apache Pig - Order By

The ORDER BY operator is used to display the contents of a relation in a sorted order based on one or more fields.
Given below is the syntax of the ORDER BY operator.
grunt> Relation_name2 = ORDER Relatin_name1 BY (ASC|DESC);

Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.
student_details.txt
001,Rajiv,Reddy,21,9848022337,Hyderabad
002,siddarth,Battacharya,22,9848022338,Kolkata
003,Rajesh,Khanna,22,9848022339,Delhi 
004,Preethi,Agarwal,21,9848022330,Pune 
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar 
006,Archana,Mishra,23,9848022335,Chennai 
007,Komal,Nayak,24,9848022334,trivendram 
008,Bharathi,Nambiayar,24,9848022333,Chennai

And we have loaded this file into Pig with the relation name student_details as shown below.
grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')
   as (id:int, firstname:chararray, lastname:chararray,age:int, phone:chararray, city:chararray);
Let us now sort the relation in a descending order based on the age of the student and store it into another relation named order_by_data using the ORDER BY operator as shown below.
grunt> order_by_data = ORDER student_details BY age DESC;
Verify the relation order_by_data using the DUMP operator as shown below.
grunt> Dump order_by_data; 
It will produce the following output, displaying the contents of the relation order_by_data.
(8,Bharathi,Nambiayar,24,9848022333,Chennai)
(7,Komal,Nayak,24,9848022334,trivendram)
(6,Archana,Mishra,23,9848022335,Chennai) 
(5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar)
(3,Rajesh,Khanna,22,9848022339,Delhi) 
(2,siddarth,Battacharya,22,9848022338,Kolkata)
(4,Preethi,Agarwal,21,9848022330,Pune) 
(1,Rajiv,Reddy,21,9848022337,Hyderabad)


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Draw ellipse in C graphics - GeeksforGeeks

06 Dec, 2019
Program to draw ellipse in C using graphics.h header file.graphics.h library is used to include and facilitate graphical operations in program. C graphics using graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them.Examples:
Input : x=250, y=200, start_angle = 0,
        end_angle = 360, x_rad = 100, y_rad = 50
Output :


Input : x=250, y=200, start_angle = 0, 
        end_angle = 180, x_rad = 80, y_rad = 150
Output :


Explanation :The header file graphics.h contains ellipse() function which is described below :
void ellipse(int x, int y, int start_angle, int end_angle, int x_radius, int y_radius)
In this function x, y is the location of the ellipse. x_radius and y_radius decide the radius of form x and y.start_angle is the starting point of angle and end_angle is the ending point of angle. The value of angle can vary from 0 to 360 degree.
// C Implementation for drawing ellipse#include <graphics.h>  int main(){    // gm is Graphics mode which is a computer display    // mode that generates image using pixels.    // DETECT is a macro defined in "graphics.h" header file    int gd = DETECT, gm;      // location of ellipse    int x = 250, y = 200;      // here is the starting angle    // and end angle    int start_angle = 0;    int end_angle = 360;      // radius from x axis and y axis    int x_rad = 100;    int y_rad = 50;      // initgraph initializes the graphics system    // by loading a graphics driver from disk    initgraph(&gd, &gm, "");      // ellipse function    ellipse(x, y, start_angle,     end_angle, x_rad, y_rad);      getch();      // closegraph function closes the graphics    // mode and deallocates all memory allocated    // by graphics system .    closegraph();      return 0;}
Output:


Akanksha_Rai
computer-graphics
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
time() function in C
Flex (Fast Lexical Analyzer Generator )
C Program to Swap two Numbers
Print system time in C++ (3 different ways)

There are different ways by which system day, date and time can be printed in Human Readable Form.
Using time() − It is used to find the current calendar time and have arithmetic data type that store timelocaltime() − It is used to fill the structure with date and timeasctime() − It converts Local time into Human Readable Format
Day Month Date hour:month:second Year
#include<iostream>
#include<ctime> // used to work with date and time
using namespace std;
int main() {
   time_t t; // t passed as argument in function time()
   struct tm * tt; // decalring variable for localtime()
   time (&t); //passing argument to time()
   tt = localtime(&t);
   cout << "Current Day, Date and Time is = "<< asctime(tt);
   return 0;
}
if we run the above program then it will generate the following output
Current Day, Date and Time is = Tue Jul 23 19:05:50 2019
Chrono library is used to measure elapsed time in seconds, milliseconds, microseconds and nanoseconds
#include <chrono>
#include <ctime>
#include <iostream>
Using namespace std;
int main() {
   auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());
   cout << ctime(&givemetime) << endl;
}
if we run the above program then it will generate the following output
Current Day, Date and Time is = Tue Jul 23 19:05:50 2019
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
   time_t givemetime = time(NULL);
   printf("%s", ctime(&givemetime)); //ctime() returns given time
   return 0;
}
if we run the above program then it will generate the following output
Tue Jul 23 20:14:42 2019
Replace string in SQL Server - GeeksforGeeks

27 Nov, 2020
Let us suppose we need to update or replace any string value in any table, we could use the below methods –
Replace String in SQL Server Example :In below example, we have a string variable, and then we are going to replace a part of a string with a new string using the Replace Function.
SQL Server Query to Replace String –
DECLARE @String_Value varchar(50)
SET @String_Value = 'This provides free and excellent knowledge on SQL Server.'
SELECT REPLACE (@String_Value, 'This', 'Geeksforgeeks');
Output :
Geeksforgeeks provides free and excellent knowledge on SQL Server.
Let us suppose we have below table named “geek_demo” :
Replace String Example :In below example, we will replace a string in SQL Server SELECT Statement using the REPLACE Function while selecting data from the SQL Server table.
SQL Server Query to replace part of a string –
SELECT TOP 1000 [Name], [Salary], [City], [email], 
REPLACE([email], 'xyz.com', 'gfg.org') AS [New EmailID]
FROM [geek_demo]
Output :
Replace String in SQL Example :In the below example, we will replace string in SQL UPDATE Statement using the REPLACE Function in Update Statement.
SQL Server Query to replace part of a string –
UPDATE [geek_demo]
SET [email] = REPLACE([email], 'xyz.com', 'gfg.org');
Result :
(8 row(s) affected)
Now let us see the Updated table –
SELECT TOP 1000 [Name], [Salary], [City], [email]
FROM [geek_demo];
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Composite Key in SQL
SQL using Python
SQL | DROP, TRUNCATE
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
What is a Domain Name System?

The acronym for Domain Name System is DNS. It is a naming system that works hierarchically and is decentralized for computers, servers (web servers), services, resources, network devices and components that are present on large networks such as the public Internet.
For example, in layman terms, it is a phonebook for computers on the Internet.
It translates and maps alphabetic domain names (websites' web addresses or names) to the numeric Internet Protocol (IP) addresses of computers or servers. And it also does the reverse process. DNS uses User Datagram Protocol (UDP). DNS service uses port number 53.
Technically, computers or technically the routers (default gateway) use DNS servers to contact to get any domains translated and converted to an IP address of the server hosting a website. The entry for DNS servers could be few or many, as there would be multiple DNS servers. The examples are OpenDNS servers, or Google DNS servers.
It is a system that uses at least one DNS server to resolve DNS-names. DNS is used because computers and servers do not understand human-readable alphabetic domain names, where humans do not understand and remember numeric IP addresses, which the computers and servers can.
DNS service or server is an Internet service in general, thus maps or translates human readable domain names (website names or URL, Uniform Resource Locator) into machine or Computer readable IP (Internet Protocol) addresses.
Domain name = www.example.com whose Server IP address is,
say = 253.136.27.2
The working of DNS is explained below in stepwise manner −
Step 1 − Every website has a domain name/ IP address associated with it.
Step 2 − Now IP is a bit complicated to share (as no one wants to write 192.168.224.23 or some random IP to access Tutorials point) so people came up with an idea of domain names which basically stores the IP address mapped to their name.
Step 3 − Now, a DNS translates every domain name to its IP address so every browser can access that particular website.
Step 4 − DNS has eased the process of web surfing as we write tutorialspoint.com to reach a website instead of some complicated 32-128 bit address.
Given below is the diagram of DNS −
Coin Change 2 in C++

Suppose we have coins of different denominations and a total amount of money. we have to Write a module to compute the number of combinations that make up that amount. we can assume that we have infinite number of each kind of coin. So if the amount is 5 and coins are [1, 2, 5], then there are four combinations. (1+1+1+1+1), (1+1+1+2), (1+2+2), (5)
To solve this, we will follow these steps −
create one array dp of size amount + 1
dp[0] := 1
n := size of coins array
for i in range 0 to n – 1for j in range coins[i] to amountdp[j] := dp[j – coins[i]]
for j in range coins[i] to amountdp[j] := dp[j – coins[i]]
dp[j] := dp[j – coins[i]]
return dp[amount]
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int change(int amount, vector<int>& coins) {
      vector <int> dp(amount + 1);
      dp[0] = 1;
      int n = coins.size();
      for(int i = 0; i < n; i++){
         for(int j = coins[i]; j <= amount; j++){
            dp[j] += dp[j - coins[i]];
         }
      }
      return dp[amount];
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,5};
   cout << (ob.change(5, v));
}
5
[1,2,5]
4
How to change the font color of a text using JavaScript?

To change the font color of a text, use the fontcolor() method. This method causes a string to be displayed in the specified color as if it were in a <font color="color"> tag. 
You can try to run the following code to change the font color of a text using JavaScript −
Live Demo
<html>
   <head>
      <title>JavaScript String fontcolor() Method</title>
   </head>

   <body>
      <script>
         var str = new String("Demo Text");
         document.write(str.fontcolor( "blue" ));
         alert(str.fontcolor( "blue" ));
      </script>
   </body>
</html>
C++ String Library - clear

It erases the contents of the string, which becomes an empty string.
Following is the declaration for std::string::clear.
void clear();
void clear() noexcept;
none
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::clear.
#include <iostream>
#include <string>

int main () {
   char c;
   std::string str;
   std::cout << "Please type some lines of text. Enter a start (*) to finish:\n";
   do {
      c = std::cin.get();
      str += c;
      if (c=='\n') {
         std::cout << str;
         str.clear();
      }
   } while (c!='*');
   return 0;
}
The sample output should be like this −
Please type some lines of text. Enter a start (*) to finish:
sairam.krishna *

 Print
 Add Notes
 Bookmark this page
Aptitude - Tables

Tables are very commonly used to represent the set of related data. Tabulation is a very popular technique of data interpretation in which a set of questions are derived from a given table of data/ observations.
For example, using the above table, you want to check in percentage of sugar in April.
Quantity of suger used in April = 210 Kg
Total quantity of food items used in april month = (260+290+210+245+375+460) kg
= 1860 kg
Required % = (210/1840*100)% = 11.4%


    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
How to read and write a file using Javascript?

You cannot read or write files in JS on client side(browsers). This can be done on serverside using the fs module in Node.js. It provides sync and async functions to read and write files on the file system. Let us look at the exmaples of reading and writing files using the fs module on node.js
Let us create a js file named main.js having the following code −
var fs = require("fs");
console.log("Going to write into existing file");
// Open a new file with name input.txt and write Simply Easy Learning! to it.
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("Data written successfully!");
   console.log("Let's read newly written data");
   // Read the newly written file and print all of its content on the console
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});
Now run the main.js to see the result −
$ node main.js
Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!
You can read more about how fs module works in node and how to use it at https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm.
Grouping Matching in Perl

From a regular-expression point of view in Perl, there is no difference between the following two expressions except that the former is slightly clearer.
$string =~ /(\S+)\s+(\S+)/;
and
$string =~ /\S+\s+\S+/;
However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string.
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows −
 Live Demo
#!/usr/bin/perl
$time = "12:05:30";
$time =~ m/(\d+):(\d+):(\d+)/;
my ($hours, $minutes, $seconds) = ($1, $2, $3);
print "Hours : $hours, Minutes: $minutes, Second: $seconds\n";
When above program is executed, it produces the following result −
Hours : 12, Minutes: 05, Second: 30
When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this −
 Live Demo
#!/usr/bin/perl
$date = '03/26/1999';
$date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#;
print "$date\n";
When above program is executed, it produces the following result −
1999/03/26
Tryit Editor v3.7

Tryit: HTML responsive page
How to gray out (disable) a Tkinter Frame?

A Tkinter frame widget can contain a group of widgets. We can change the state of widgets in the frame by enabling or disabling the state of its underlying frame. To disable all the widgets inside that particular frame, we have to select all the children widgets that are lying inside that frame using winfor_children() and change the state using state=(‘disabled’ or ‘enable’) attribute.
In this example, we will create a button and an entry widget. Initially, the state of entry widget is disabled. But when we click the button, it will enable all the widgets in the frame.
#Import the required Libraries
from tkinter import *
from tkinter import ttk

#Define a Function to enable the frame
def enable(children):
   for child in children:
      child.configure(state='enable')

#Create an instance of tkinter frame
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x250")

#Creates top frame
frame1 = LabelFrame(win, width= 400, height= 180, bd=5)
frame1.pack()

#Create an Entry widget in Frame2
entry1 = ttk.Entry(frame1, width= 40)
entry1.insert(INSERT,"Enter Your Name")
entry1.pack()
entry2= ttk.Entry(frame1, width= 40)
entry2.insert(INSERT, "Enter Your Email")
entry2.pack()

#Creates bottom frame
frame2 = LabelFrame(win, width= 150, height=100)
frame2.pack()

#Create a Button to enable frame
button1 = ttk.Button(frame2, text="Enable", command=lambda: enable(frame1.winfo_children()))
button1.pack()
for child in frame1.winfo_children():
   child.configure(state='disable')

win.mainloop()
Running the above code will display a window that contains two Label Frames. Each frame contains an entry widget and a button to enable or disable the frame.
When we click the "Enable" button, it will activate Frame1.
How to know the current position within a file in Python?

You can get the current position of the file object using the tell method. For example, if there is a file called my_file with text Hello\nworld,
f = open('my_file.txt', 'r')
f.readline()
print f.tell()
f.close()
The above code will give the output as 6 as it would be pointing just at the beginning of the word 'world'.
Convert a number into negative base representation in C++

In this tutorial, we will be discussing a program to convert a number into its negative base representation.
For this we will be provided with a number and the corresponding negative base. Our task is to convert the given number into its negative base equivalent. We are allowing only values between -2 and -10 for negative base values.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//converting integer into string
string convert_str(int n){
   string str;
   stringstream ss;
   ss << n;
   ss >> str;
   return str;
}
//converting n to negative base
string convert_nb(int n, int negBase){
   //negative base equivalent for zero is zero
   if (n == 0)
      return "0";
   string converted = "";
   while (n != 0){
      //getting remainder from negative base
      int remainder = n % negBase;
      n /= negBase;
      //changing remainder to its absolute value
      if (remainder < 0) {
         remainder += (-negBase);
         n += 1;
      }
      // convert remainder to string add into the result
      converted = convert_str(remainder) + converted;
   }
   return converted;
}
int main() {
   int n = 9;
   int negBase = -3;
   cout << convert_nb(n, negBase);
   return 0;
}
100
Tryit Editor v3.7

Tryit: HTML table - striped rows and columns
MongoDB query to return only embedded document?

It is not possible to return only embedded document. However, it will return all the documents from a collection. Let us first implement the following query to create a collection with documents
>db.queryToEmbeddedDocument.insertOne({"UserName":"Larry","PostDetails":[{"UserMessage":"Hello","UserLikes":8},{"UserMessage":"Hi","UserLikes":6},{"UserMessage":"Good Morning","UserLikes":12},{"UserMessage":"Awesome","UserLikes":4}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c988a9f330fd0aa0d2fe4bd")
}
Following is the query to display all documents from a collection with the help of find() method
> db.queryToEmbeddedDocument.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"),
   "UserName" : "Larry",
   "PostDetails" : [
      {
         "UserMessage" : "Hello",
         "UserLikes" : 8
      },
      {
         "UserMessage" : "Hi",
         "UserLikes" : 6
      },
      {
         "UserMessage" : "Good Morning",
         "UserLikes" : 12
      },
      {
         "UserMessage" : "Awesome",
         "UserLikes" : 4
      }
   ]
}
Following is the query to return all the documents from a collection
> db.queryToEmbeddedDocument.find({"PostDetails.UserLikes": {$gte: 8}},{PostDetails:1}).pretty();
This will produce the following output
{
   "_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"),
   "PostDetails" : [
      {
         "UserMessage" : "Hello",
         "UserLikes" : 8
      },
      {
         "UserMessage" : "Hi",
         "UserLikes" : 6
      },
      {
         "UserMessage" : "Good Morning",
         "UserLikes" : 12
      },
      {
         "UserMessage" : "Awesome",
         "UserLikes" : 4
      }
   ]
}
Look at the above sample output, we are getting all the documents while we want only those documents in which “UserLikes” are greater than or equal to 8.
How to specify Decimal Precision and scale number in MySQL database using PHPMyAdmin?

You need to select a database when you are creating a table. Right now, I have a sample database. The snapshot is as follows:
Now you need to give the table name as well as the number of columns you want:
After that you need to press Go button. Now, the following section would be visible:
The DECIMAL requires two parameter i.e. Total Number of Digit and second one is DigitAfterDecimalPoint.
The structure of DECIMAL is as follows:
DECIMAL(X,Y)
Here, X is TotalNumberOfDigit and Y is DigitAfterDecimalPoint.
Let us see an example:
DECIMAL(6,4)
Above, we will be having 6 digit sand 2 digit safter decimal point. For example, the valid range can be 24.5678 or 560.23 etc.
Here is the setup in phpmyAdmin. The snapshot is as follows:
After giving column name for a table, you need to use “Save” button. Here is the structure of table:
There are two columns in the table DecimalPrecisionDemo. One is Id which is of type int and second one is Amount of type DECIMAL(6,4).
The Floyd-Warshall algorithm in Javascript

Djikstra's algorithm is used to find distance/path of the shortest path from one node to all other nodes. There are cases where we need to find shortest paths from all nodes to all other nodes. This is where the All pairs shortest path algorithms come in handy. The most used all pairs shortest path algorithm is Floyd Warshall algorithm.
Floyd Warshall algorithm works as follows −
We initialize an N x N matrix of distances to be Infinity.
Then for each edge u, v, we update this matrix to be showing the weight of this edge and for edges v, v we update the weight to be 0.
We create 3 nested loops with iterators I, j and k. for every node I's distance to every node j, we consider using k as intermediate points and update the distance if we find a less than existing arr[i][j].
Instead of using a matrix, we'll use an object as we don't need to keep track of index in case we are using complex objects to represent each node.
Now let us look at the implementation of the same −
floydWarshallAlgorithm() {
   let dist = {};
   for (let i = 0; i < this.nodes.length; i++) {
      dist[this.nodes[i]] = {};
      // For existing edges assign the dist to be same as weight
      this.edges[this.nodes[i]].forEach(e => (dist[this.nodes[i]][e.node] = e.weight));
      this.nodes.forEach(n => {
         // For all other nodes assign it to infinity
         if (dist[this.nodes[i]][n] == undefined)
         dist[this.nodes[i]][n] = Infinity;
         // For self edge assign dist to be 0
         if (this.nodes[i] === n) dist[this.nodes[i]][n] = 0;
      });
   }
   this.nodes.forEach(i => {
      this.nodes.forEach(j => {
         this.nodes.forEach(k => {
            // Check if going from i to k then from k to j is better
            // than directly going from i to j. If yes then update
            // i to j value to the new value
            if (dist[i][k] + dist[k][j] < dist[i][j])
               dist[i][j] = dist[i][k] + dist[k][j];
            });
         });
      });
      return dist;
   }
}
You can test this using −
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");

g.addEdge("A", "C", 100);
g.addEdge("A", "B", 3);
g.addEdge("A", "D", 4);
g.addEdge("D", "C", 3);

console.log(g.floydWarshallAlgorithm());
This will give the output −
{
   A: { C: 7, B: 3, D: 4, A: 0 },
   B: { A: 3, B: 0, C: 10, D: 7 },
   C: { A: 7, D: 3, B: 10, C: 0 },
   D: { A: 4, C: 3, B: 7, D: 0 }
}
Decimal to Binary conversion using C Programming

How to convert a decimal number to a binary number by using the function in the C programming language?
In this program, we are calling a function to binary in main(). The called function to binary will perform actual conversion.
The logic we are using is called function to convert decimal number to binary number is as follows −
while(dno != 0){
   rem = dno % 2;
   bno = bno + rem * f;
   f = f * 10;
   dno = dno / 2;
}
Finally, it returns the binary number to the main program.
Following is the C program to convert a decimal number to a binary number −
 Live Demo
#include<stdio.h>
long tobinary(int);
int main(){
   long bno;
   int dno;
   printf(" Enter any decimal number : ");
   scanf("%d",&dno);
   bno = tobinary(dno);
   printf("\n The Binary value is : %ld\n\n",bno);
   return 0;
}
long tobinary(int dno){
   long bno=0,rem,f=1;
   while(dno != 0){
      rem = dno % 2;
      bno = bno + rem * f;
      f = f * 10;
      dno = dno / 2;
   }
   return bno;;
}
When the above program is executed, it produces the following result −
Enter any decimal number: 12
The Binary value is: 1100
Now, try to convert binary numbers to decimal numbers.
Following is the C program to convert binary number to decimal number −
 Live Demo
#include
#include <stdio.h>
int todecimal(long bno);
int main(){
   long bno;
   int dno;
   printf("Enter a binary number: ");
   scanf("%ld", &bno);
   dno=todecimal(bno);
   printf("The decimal value is:%d\n",dno);
   return 0;
}
int todecimal(long bno){
   int dno = 0, i = 0, rem;
   while (bno != 0) {
      rem = bno % 10;
      bno /= 10;
      dno += rem * pow(2, i);
      ++i;
   }
   return dno;
}
When the above program is executed, it produces the following result −
Enter a binary number: 10011
The decimal value is:19
How to clear screen using Java?

Following is the code to clear screen using Java −
 Live Demo
public class Demo{
   public static void main(String[] args){
      System.out.print("\033[H\033[2J");
      System.out.flush();
   }
}
The screen would be cleared
A class named Demo contains the main function. Here, the ANSI escape code is written, that clears the screen. The flush function resets the cursor to the top of the window screen.
Redux - Store

A store is an immutable object tree in Redux. A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer.
Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below −
import { createStore } from 'redux';
import reducer from './reducers/reducer'
const store = createStore(reducer);

A createStore function can have three arguments. The following is the syntax −
createStore(reducer, [preloadedState], [enhancer])

A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance store with third-party capabilities.
A store has three important methods as given below −
It helps you retrieve the current state of your Redux store.
The syntax for getState is as follows −
store.getState()

It allows you to dispatch an action to change a state in your application.
The syntax for dispatch is as follows −
store.dispatch({type:'ITEMS_REQUEST'})

It helps you register a callback that Redux store will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically.
The syntax for dispatch is as follows −
store.subscribe(()=>{ console.log(store.getState());})

Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code −
const unsubscribe = store.subscribe(()=>{console.log(store.getState());});
unsubscribe();


    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    129 Lectures 
     19.5 hours 

 Ghulam Abbas

    31 Lectures 
     3 hours 

 Saumitra Vishal

    55 Lectures 
     4 hours 

 Saumitra Vishal
 Print
 Add Notes
 Bookmark this page
BabylonJS - WireFrame

With wireframe, you get the skeleton of the 3D model with only lines and vertices. Let us now see how to apply wireframe for any shape.
materialforbox.wireframe = true;

<!doctype html>
<html>
   <head>
      <meta charset = "utf-8">
      <title>BabylonJs - Basic Element-Creating Scene</title>
      <script src = "babylon.js"></script>
      <style>
         canvas {width: 100%; height: 100%;}
      </style>
   </head>

   <body>
      <canvas id = "renderCanvas"></canvas>
      <script type = "text/javascript">
         var canvas = document.getElementById("renderCanvas");
         var engine = new BABYLON.Engine(canvas, true);
         
         var createScene  = function() {
            var scene = new BABYLON.Scene(engine);
            scene.clearColor = new BABYLON.Color3(0, 1, 0);
            scene.ambientColor = new BABYLON.Color3(0.3, 0.3, 0.3);
            
            var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
            camera.attachControl(canvas, true);
            
            var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
            light.intensity = 0.7;	
            
            var materialforbox = new BABYLON.StandardMaterial("texture1", scene);
            
            var box = BABYLON.Mesh.CreateBox("box", '3', scene);	
            box.material  = materialforbox;
            materialforbox.wireframe = true;
            return scene;
         };
         var scene = createScene();
         engine.runRenderLoop(function() {
            scene.render();
         });
      </script>
   </body>
</html>
 Print
 Add Notes
 Bookmark this page
How to filter String list by starting value in Java?

Let’s first create a String list −
List list = new ArrayList<>();
list.add("wxy");
list.add("zabc");
list.add("ddd2");
list.add("def");
list.add("ghi");
list.add("wer");
list.add("uij");
list.add("wqy");
To filter String list by starting value, use filter() and startsWith() −
list.stream().filter((b) -> b.startsWith("w"))
The following is an example to filter string list by starting value −
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(final String[] args) {
      List list = new ArrayList<>();
      list.add("wxy");
      list.add("zabc");
      list.add("ddd2");
      list.add("def");
      list.add("ghi");
      list.add("wer");
      list.add("uij");
      list.add("wqy");
      System.out.println("List beginning with letter w = ");
      list.stream().filter((b) -> b.startsWith("w"))
      .forEach(System.out::println);
   }
}
List beginning with letter w =
wxy
wer
wqy
Tryit Editor v3.7

Tryit: Responsive form
A Time Complexity Question - GeeksforGeeks

27 Dec, 2021
What is the time complexity of following function fun()? Assume that log(x) returns log value in base 2. 
C++
C
Java
Python3
C#
Javascript
void fun(){    int i, j;    for (i = 1; i <= n; i++)        for (j = 1; j <= log(i); j++)            cout << "GeeksforGeeks";} // This code is contributed by SHUBHAMSINGH10.
void fun(){    int i, j;    for (i = 1; i <= n; i++)        for (j = 1; j <= log(i); j++)            printf("GeeksforGeeks");}
static void fun(){    int i, j;    for (i = 1; i <= n; i++)        for (j = 1; j <= log(i); j++)            System.out.printf("GeeksforGeeks");} // This code is contributed by umadevi9616
import mathdef fun():    i = 0    j = 0    for i in range(1, n + 1):        for j in range(1,math.log(i) + 1):            print("GeeksforGeeks") # This code is contributed by SHUBHAMSINGH10.
static void fun(){    int i, j;    for (i = 1; i <= n; i++)        for (j = 1; j <= log(i); j++)            Console.Write("GeeksforGeeks");} // This code is contributed by umadevi9616
const fun(){    let i, j;    for (i = 1; i <= n; i++)        for (j = 1; j <= Math.log(i); j++)            document.write("GeeksforGeeks");} // This code is contributed by SHUBHAMSINGH10.
Time Complexity of the above function can be written as θ(log 1) + θ(log 2) + θ(log 3) + . . . . + θ(log n) which is θ(log n!)Order of growth of ‘log n!’ and ‘n log n’ is same for large values of n, i.e., θ(log n!) = θ(n log n). So time complexity of fun() is θ(n log n).The expression θ(log n!) = θ(n log n) can be easily derived from following Stirling’s approximation (or Stirling’s formula). 
log n! = n*log n - n = O(n*log(n)) 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Sources: http://en.wikipedia.org/wiki/Stirling%27s_approximation
vroghelia6
umadevi9616
SHUBHAMSINGH10
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Analysis of different sorting techniques
Analysis of Algorithms | Big-O analysis
Analysis of Algorithms | Set 4 (Analysis of Loops)
Difference between Big Oh, Big Omega and Big Theta
Cyclomatic Complexity
Time complexities of different data structures
Complexity Analysis of Binary Search
Difference between Context Free Grammar and Regular Grammar - GeeksforGeeks

31 May, 2021

Noam Chomsky has divided grammar into four types :
Type
Name
0
1
2
3
Chomsky Hierarchy
1. Context Free Grammar :
Language generated by Context Free Grammar is accepted by Pushdown Automata
It is a subset of Type 0 and Type 1 grammar and a superset of Type 3 grammar.
Also called phase structured grammar.
Different context-free grammars can generate the same context-free language.
Classification of Context Free Grammar is done on the basis of the number of parse trees.
Only one parse tree->Unambiguous.
More than one parse tree->Ambiguous.
Productions are in the form –
A->B;
A∈N i.e A is a non-terminal.
B∈V*(Any string).
Example –
S –> AB
A –> a
B –> b
2. Regular Grammar :
It is accepted by Finite State Automata.
It is a subset of Type 0 ,Type 1 and Type 2 grammar.
The language it generates is called Regular Language.
Regular languages are closed under operations like Union, Intersection, Complement etc.
They are the most restricted form of grammar.
Productions are in the form –
V –> VT / T (left-linear grammar)
  (or)
V –> TV /T (right-linear grammar)
Example –
1. S –> ab. 
2. S -> aS | bS | ∊ 
Difference Between Context Free Grammar and Regular Grammar:

GATE CS


Theory of Computation & Automata

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Regular Expressions, Regular Grammar and Regular Languages
Phases of a Compiler
Difference between Clustered and Non-clustered index
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Pumping Lemma in Theory of Computation
Introduction of Finite Automata
Turing Machine in TOC