title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Concatenate two columns of Pandas dataframe - GeeksforGeeks
01 Aug, 2020 Let’s discuss how to Concatenate two columns of dataframe in pandas python. We can do this by using the following functions : concat() append() join() Example 1 : Using the concat() method. # importing the moduleimport pandas as pd # creating 2 DataFrameslocation = pd.DataFrame({'area': ['new-york', 'columbo', 'mumbai']})food = pd.DataFrame({'food': ['pizza', 'crabs', 'vada-paw']}) # concatenating the DataFramesdet = pd.concat([location, food], join = 'outer', axis = 1) # displaying the DataFrameprint(det) Output : Example 2 : Using the append() method. # importing the moduleimport pandas as pd # creating 2 DataFramesfirst = pd.DataFrame([['one', 1], ['three', 3]], columns =['name', 'word'])second = pd.DataFrame([['two', 2], ['four', 4]], columns =['name', 'word']) # concatenating the DataFramesdt = first.append(second, ignore_index = True) # displaying the DataFrameprint(dt) Output : Example 3 : Using the .join() method. # importing the moduleimport pandas as pd # creating 2 DataFrameslocation = pd.DataFrame({'area' : ['new-york', 'columbo', 'mumbai']})food = pd.DataFrame({'food': ['pizza', 'crabs', 'vada-paw']}) # concatenating the DataFramesdt = location.join(food) # displaying the DataFrameprint(dt) Output : For the three methods to concatenate two columns in a DataFrame, we can add different parameters to change the axis, sort, levels etc. Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26263, "s": 26235, "text": "\n01 Aug, 2020" }, { "code": null, "e": 26389, "s": 26263, "text": "Let’s discuss how to Concatenate two columns of dataframe in pandas python. We can do this by using the following functions :" }, { "code": null, "e": ...
numpy.logical_and() in Python - GeeksforGeeks
29 Nov, 2018 numpy.logical_and(arr1, arr2, out=None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘logical_and’) : This is a logical function and it helps user to find out the truth value of arr1 AND arr2 element-wise. Both the arrays must be of same shape. Parameters : arr1 : [array_like]Input array.arr2 : [array_like]Input array. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result. **kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function. where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone. Return : An array with Boolean results of arr1 and arr2 element-wise(of the same shape). Code 1 : Working # Python program explaining# logical_and() functionimport numpy as np # inputarr1 = [1, 3, False, 4]arr2 = [3, 0, True, False] # outputout_arr = np.logical_and(arr1, arr2) print ("Output Array : ", out_arr) Output : Output Array : [ True False False False] Code 2 : Value Error if input array’s have different shapes # Python program explaining# logical_and() functionimport numpy as np # inputarr1 = [8, 2, False, 4]arr2 = [3, 0, True, False, 8] # outputout_arr = np.logical_and(arr1, arr2) print ("Output Array : ", out_arr) Output : ValueError:operands could not be broadcast together with shapes (4,) (5,) References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_and.html#numpy.logical_and. Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python sum() function in Python
[ { "code": null, "e": 26039, "s": 26011, "text": "\n29 Nov, 2018" }, { "code": null, "e": 26309, "s": 26039, "text": "numpy.logical_and(arr1, arr2, out=None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘logical_and’) : This is a logical function and it he...
How to Use write.table in R? - GeeksforGeeks
19 Dec, 2021 In this article, we will learn how to use the write.table() in the R Programming Language. The write.table() function is used to export a dataframe or matrix to a file in the R Language. This function converts a dataframe into a text file in the R Language and can be used to write dataframe into a variety of space-separated files for example CSV( comma separated values) files. Syntax: write.table( df, file) where: df: determines the dataframe to be converted. file: determines the file name to write data into with full path. Example: Here, we will write a dataframe into a space-separated text file in the R Language by using write.table(). R # create sample dataframesample_data <- data.frame( name= c("Geeks1", "Geeks2", "Geeks3", "Geeks4", "Geeks5", "Geeks6"), value= c( 11, 15, 10, 23, 32, 53 ) ) # write dataframe into a space separated text filewrite.table( sample_data, file='sample.txt') Output: To write a dataframe into a text file separated by a manual symbol, we use the sep parameter to determine the symbol that separates the data in the text file. In this way, we can write comma-separated-values, tab-separated values, etc. Syntax: write.table( df, file, sep) where: df: determines the dataframe to be converted. file: determines the file name to write data into with full path. sep: determines with a symbol for separation. Default is a space. Example: Here, we will write a dataframe into a comma-separated text file in the R Language by using write.table() function with sep parameter. R # create sample dataframesample_data <- data.frame( name= c("Geeks1", "Geeks2", "Geeks3", "Geeks4", "Geeks5", "Geeks6"), value= c( 11, 15, 10, 23, 32, 53 ) ) # write dataframe into a space separated text filewrite.table( sample_data, file='sample.txt', sep=",") Output: Picked R-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n19 Dec, 2021" }, { "code": null, "e": 26867, "s": 26487, "text": "In this article, we will learn how to use the write.table() in the R Programming Language. The write.table() function is used to export a dataframe or matrix to a ...
How to Implement SuperBottomBar in Android App? - GeeksforGeeks
23 Apr, 2021 In this article, we are going to implement bottom navigation like there in Spotify. We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, Snapchat, etc. In this article, let’s learn how to implement an easy stylish SuperBottomBar functional Bottom Navigation Bar in the Android app. For Creating a Basic Bottom Navigation bar refer to Bottom Navigation Bar in Android. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency and JitPack Repository Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation ‘com.github.ertugrulkaragoz:SuperBottomBar:0.4’ Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section. allprojects { repositories { ... maven { url “https://jitpack.io” } } } After adding this dependency sync your project and now we will move towards its implementation. Step 3: Working with the menu file Refer to How to Create Menu Folder & Menu File in Android Studio and create a menu file. Below is the code for the menu.xml file. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/home_super_bottom_bar" android:icon="@drawable/ic_home_black_24dp" android:title="Home" /> <item android:id="@+id/radio_super_bottom_bar" android:icon="@drawable/ic_message_black_24dp" android:title="Chat" /> <item android:id="@+id/search_super_bottom_bar" android:icon="@drawable/ic_search_black_24dp" android:title="Search" /> <item android:id="@+id/library_super_bottom_bar" android:icon="@drawable/ic_library_books_black_24dp" android:title="Book" /> <item android:id="@+id/profile_super_bottom_bar" android:icon="@drawable/ic_person_black_24dp" android:title="Profile" /> </menu> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="bottom" android:orientation="vertical" tools:context=".MainActivity"> <me.ertugrul.lib.SuperBottomBar android:id="@+id/bottomBar" android:layout_width="match_parent" android:layout_height="55dp" app:sbb_menu="@menu/menu" /> </LinearLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. We have just set a listener to the BottomBar. Java import android.os.Bundle;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import me.ertugrul.lib.OnItemSelectedListener;import me.ertugrul.lib.SuperBottomBar; public class MainActivity extends AppCompatActivity { SuperBottomBar botttomBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise the layout botttomBar = findViewById(R.id.bottomBar); // when we click on any item the show the toast message as selected botttomBar.setOnItemSelectListener(new OnItemSelectedListener() { @Override public void onItemSelect(int i) { Toast.makeText(MainActivity.this, "Selected", Toast.LENGTH_LONG).show(); } }); }} Output: Android-Bars Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n23 Apr, 2021" }, { "code": null, "e": 26802, "s": 26381, "text": "In this article, we are going to implement bottom navigation like there in Spotify. We all have come across apps that have a Bottom Navigation Bar. Some popular ex...
Find weight of MST in a complete graph with edge-weights either 0 or 1 - GeeksforGeeks
24 Dec, 2021 Given an undirected weighted complete graph of N vertices. There are exactly M edges having weight 1 and rest all the possible edges have weight 0. The array arr[][] gives the set of edges having weight 1. The task is to calculate the total weight of the minimum spanning tree of this graph. Examples: Input: N = 6, M = 11, arr[][] = {(1 3), (1 4), (1 5), (1 6), (2 3), (2 4), (2 5), (2 6), (3 4), (3 5), (3 6) } Output: 2 Explanation: This is the minimum spanning tree of the given graph: Input: N = 3, M = 0, arr[][] { } Output: 0 Explanation: This is the minimum spanning tree of the given graph: Approach: For the given graph of N nodes to be Connected Components, we need exactly N-1 edges of 1-weight edges. Following are the steps: Store the given graph in the map for all the edges of weight 1.Use set to store the vertices which are not included in any of the 0-weight Connected Components.For each vertex currently stored in the set, do a DFS Traversal and increase the count of Components by 1 and remove all the visited vertices during DFS Traversal from the set.During the DFS Traversal, include the 0-weight vertices in a vector and 1-weight vertices in another set. Run a DFS Traversal for all the vertices included in the vector.Then, the total weight of the minimum spanning tree is given the count of components – 1. Store the given graph in the map for all the edges of weight 1. Use set to store the vertices which are not included in any of the 0-weight Connected Components. For each vertex currently stored in the set, do a DFS Traversal and increase the count of Components by 1 and remove all the visited vertices during DFS Traversal from the set. During the DFS Traversal, include the 0-weight vertices in a vector and 1-weight vertices in another set. Run a DFS Traversal for all the vertices included in the vector. Then, the total weight of the minimum spanning tree is given the count of components – 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to find weight of// minimum spanning tree in a// complete graph where edges// have weight either 0 or 1#include <bits/stdc++.h>using namespace std; // To store the edges of the given// graphmap<int, int> g[200005];set<int> s, ns; // A utility function to perform// DFS Traversalvoid dfs(int x){ vector<int> v; v.clear(); ns.clear(); // Check those vertices which // are stored in the set for (int it : s) { // Vertices are included if // the weight of edge is 0 if (!g[x][it]) { v.push_back(it); } else { ns.insert(it); } } s = ns; for (int i : v) { dfs(i); }} // A utility function to find the// weight of Minimum Spanning Treevoid weightOfMST(int N){ // To count the connected // components int cnt = 0; // Inserting the initial vertices // in the set for (int i = 1; i <= N; ++i) { s.insert(i); } // Traversing vertices stored in // the set and Run DFS Traversal // for each vertices for (; s.size();) { // Incrementing the zero // weight connected components ++cnt; int t = *s.begin(); s.erase(t); // DFS Traversal for every // vertex remove dfs(t); } cout << cnt - 1;} // Driver's Codeint main(){ int N = 6, M = 11; int edges[][M] = { { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 4 }, { 3, 5 }, { 3, 6 } }; // Insert edges for (int i = 0; i < M; ++i) { int u = edges[i][0]; int v = edges[i][1]; g[u][v] = 1; g[v][u] = 1; } // Function call find the weight // of Minimum Spanning Tree weightOfMST(N); return 0;} // Java Program to find weight of // minimum spanning tree in a // complete graph where edges // have weight either 0 or 1 import java.util.*; class GFG{ // To store the edges // of the given graphstatic HashMap<Integer, Integer>[] g = new HashMap[200005];static HashSet<Integer> s = new HashSet<>();static HashSet<Integer> ns = new HashSet<>(); // A utility function to // perform DFS Traversalstatic void dfs(int x) { Vector<Integer> v = new Vector<>(); v.clear(); ns.clear(); // Check those vertices which // are stored in the set for (int it : s) { // Vertices are included if // the weight of edge is 0 if (g[x].get(it) != null) { v.add(it); } else { ns.add(it); } } s = ns; for (int i : v) { dfs(i); }} // A utility function to find the// weight of Minimum Spanning Treestatic void weightOfMST(int N) { // To count the connected // components int cnt = 0; // Inserting the initial vertices // in the set for (int i = 1; i <= N; ++i) { s.add(i); } Vector<Integer> qt = new Vector<>(); for (int t : s) qt.add(t); // Traversing vertices stored in // the set and Run DFS Traversal // for each vertices while (!qt.isEmpty()) { // Incrementing the zero // weight connected components ++cnt; int t = qt.get(0); qt.remove(0); // DFS Traversal for every // vertex remove dfs(t); } System.out.print(cnt - 4);} // Driver's Codepublic static void main(String[] args) { int N = 6, M = 11; int edges[][] = {{1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}}; for (int i = 0; i < g.length; i++) g[i] = new HashMap<Integer, Integer>(); // Insert edges for (int i = 0; i < M; ++i) { int u = edges[i][0]; int v = edges[i][1]; g[u].put(v, 1); g[v].put(u, 1); } // Function call find the weight // of Minimum Spanning Tree weightOfMST(N);}} // This code is contributed by gauravrajput1 # Python3 Program to find weight of# minimum spanning tree in a# complete graph where edges# have weight either 0 or 1 # To store the edges of the given# graph g = [dict() for i in range(200005)]s = set()ns = set() # A utility function to perform# DFS Traversaldef dfs(x): global s, g, ns v = [] v.clear(); ns.clear(); # Check those vertices which # are stored in the set for it in s: # Vertices are included if # the weight of edge is 0 if (x in g and not g[x][it]): v.append(it); else: ns.add(it); s = ns; for i in v: dfs(i); # A utility function to find the# weight of Minimum Spanning Treedef weightOfMST( N): # To count the connected # components cnt = 0; # Inserting the initial vertices # in the set for i in range(1,N + 1): s.add(i); # Traversing vertices stored in # the set and Run DFS Traversal # for each vertices while(len(s) != 0): # Incrementing the zero # weight connected components cnt += 1 t = list(s)[0] s.discard(t); # DFS Traversal for every # vertex remove dfs(t); print(cnt) # Driver's Codeif __name__=='__main__': N = 6 M = 11; edges = [ [ 1, 3 ], [ 1, 4 ], [ 1, 5 ], [ 1, 6 ], [ 2, 3 ], [ 2, 4 ], [ 2, 5 ], [ 2, 6 ], [ 3, 4 ], [ 3, 5 ], [ 3, 6 ] ]; # Insert edges for i in range(M): u = edges[i][0]; v = edges[i][1]; g[u][v] = 1; g[v][u] = 1; # Function call find the weight # of Minimum Spanning Tree weightOfMST(N); # This code is contributed by pratham76 // C# Program to find weight of // minimum spanning tree in a // complete graph where edges // have weight either 0 or 1 using System;using System.Collections;using System.Collections.Generic; class GFG{ // To store the edges // of the given graphstatic Dictionary<int,int> [] g = new Dictionary<int,int>[200005];static HashSet<int> s = new HashSet<int>();static HashSet<int> ns = new HashSet<int>(); // A utility function to // perform DFS Traversalstatic void dfs(int x) { ArrayList v = new ArrayList(); ns.Clear(); // Check those vertices which // are stored in the set foreach (int it in s) { // Vertices are included if // the weight of edge is 0 if (g[x].ContainsKey(it)) { v.Add(it); } else { ns.Add(it); } } s = ns; foreach(int i in v) { dfs(i); }} // A utility function to find the// weight of Minimum Spanning Treestatic void weightOfMST(int N) { // To count the connected // components int cnt = 0; // Inserting the initial vertices // in the set for (int i = 1; i <= N; ++i) { s.Add(i); } ArrayList qt = new ArrayList(); foreach(int t in s) qt.Add(t); // Traversing vertices stored in // the set and Run DFS Traversal // for each vertices while (qt.Count != 0) { // Incrementing the zero // weight connected components ++cnt; int t = (int)qt[0]; qt.RemoveAt(0); // DFS Traversal for every // vertex remove dfs(t); } Console.Write(cnt - 4);} // Driver's Codepublic static void Main(string[] args) { int N = 6, M = 11; int [,]edges = {{1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}}; for (int i = 0; i < 11; i++) g[i] = new Dictionary<int, int>(); // Insert edges for (int i = 0; i < M; ++i) { int u = edges[i, 0]; int v = edges[i, 1]; g[u][v] = 1; g[v][u] = 1; } // Function call find the weight // of Minimum Spanning Tree weightOfMST(N);}} // This code is contributed by rutvik_56 <script> // Javascript program to find weight of// minimum spanning tree in a// complete graph where edges// have weight either 0 or 1 // To store the edges// of the given graphlet g = new Array(200005);for(let i = 0; i < 200005; i++) g[i] = new Map(); let s = new Set();let ns = new Set(); // A utility function to// perform DFS Traversalfunction dfs(x){ let v = []; // Check those vertices which // are stored in the set for(let it of s.values()) { // Vertices are included if // the weight of edge is 0 if (g[x].get(it) != null) { v.push(it); } else { ns.add(it); } } s = ns; for(let i of v.values()) { dfs(i); }} // A utility function to find the// weight of Minimum Spanning Treefunction weightOfMST(N){ // To count the connected // components let cnt = 0; // Inserting the initial vertices // in the set for(let i = 1; i <= N; ++i) { s.add(i); } let qt = [] for(let t of s.values()) qt.push(t); // Traversing vertices stored in // the set and Run DFS Traversal // for each vertices while (qt.length != 0) { // Incrementing the zero // weight connected components ++cnt; let t = qt[0]; qt.shift(); // DFS Traversal for every // vertex remove dfs(t); } document.write(cnt - 4);} // Driver's Codelet N = 6, M = 11;let edges = [ [ 1, 3 ], [ 1, 4 ], [ 1, 5 ], [ 1, 6 ], [ 2, 3 ], [ 2, 4 ], [ 2, 5 ], [ 2, 6 ], [ 3, 4 ], [ 3, 5 ], [ 3, 6 ] ]; // Insert edgesfor(let i = 0; i < M; ++i){ let u = edges[i][0]; let v = edges[i][1]; g[u].set(v, 1); g[v].set(u, 1);} // Function call find the weight// of Minimum Spanning TreeweightOfMST(N); // This code is contributed by unknown2108 </script> 2 Time Complexity :O(N*log N + M) where N is the number of vertices and M is the number of edges.Auxiliary Space: O(N) GauravRajput1 rutvik_56 pratham76 unknown2108 pankajsharmagfg ashutoshsinghgeeksforgeeks Graph Minimum Spanning Tree Algorithms Graph Greedy Recursion Sorting Greedy Recursion Sorting Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Breadth First Search or BFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Depth First Search or DFS for a Graph Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
[ { "code": null, "e": 25941, "s": 25913, "text": "\n24 Dec, 2021" }, { "code": null, "e": 26233, "s": 25941, "text": "Given an undirected weighted complete graph of N vertices. There are exactly M edges having weight 1 and rest all the possible edges have weight 0. The array arr[]...
Path Testing in Software Engineering - GeeksforGeeks
02 Jul, 2020 Path Testing is a method that is used to design the test cases. In path testing method, the control flow graph of a program is designed to find a set of linearly independent paths of execution. In this method Cyclomatic Complexity is used to determine the number of linearly independent paths and then test cases are generated for each path. It give complete branch coverage but achieves that without covering all possible paths of the control flow graph. McCabe’s Cyclomatic Complexity is used in path testing. It is a structural testing method that uses the source code of a program to find every possible executable path. Path Testing Process: Control Flow Graph:Draw the corresponding control flow graph of the program in which all the executable paths are to be discovered. Cyclomatic Complexity:After the generation of the control flow graph, calculate the cyclomatic complexity of the program using the following formula.McCabe's Cyclomatic Complexity = E - N + 2P Where, E = Number of edges in control flow graph N = Number of vertices in control floe graph P = Program factor McCabe's Cyclomatic Complexity = E - N + 2P Where, E = Number of edges in control flow graph N = Number of vertices in control floe graph P = Program factor Make Set:Make a set of all the path according to the control floe graph and calculated cyclomatic complexity. The cardinality of set is equal to the calculated cyclomatic complexity. Create Test Cases:Create test case for each path of the set obtained in above step. Path Testing Techniques: Control Flow Graph:The program is converted into control flow graph by representing the code into nodes and edges. Decision to Decision path:The control flow graph can be broken into various Decision to Decision paths and then collapsed into individual nodes. Independent paths:Independent path is a path through a Decision to Decision path graph which cannot be reproduced from other paths by other methods.Advantages of Path Testing:Path testing method reduces the redundant tests.Path testing focuses on the logic of the programs.Path testing is used in test case design.My Personal Notes arrow_drop_upSave Advantages of Path Testing: Path testing method reduces the redundant tests.Path testing focuses on the logic of the programs.Path testing is used in test case design. Path testing method reduces the redundant tests. Path testing focuses on the logic of the programs. Path testing is used in test case design. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functional vs Non Functional Requirements Software Engineering | Classical Waterfall Model Differences between Verification and Validation Software Testing | Basics Software Requirement Specification (SRS) Format Levels in Data Flow Diagrams (DFD) Difference between Alpha and Beta Testing Software Engineering | White box Testing Software Engineering | Seven Principles of software testing Software Engineering | Integration Testing
[ { "code": null, "e": 26145, "s": 26117, "text": "\n02 Jul, 2020" }, { "code": null, "e": 26487, "s": 26145, "text": "Path Testing is a method that is used to design the test cases. In path testing method, the control flow graph of a program is designed to find a set of linearly i...
PLSQL | CURRENT_TIMESTAMP Function - GeeksforGeeks
24 Oct, 2019 The PLSQL CURRENT_TIMESTAMP function is used to return the current date and time in session time zone. The time zone used is the time zone of the current SQL session as set by the ALTER SESSION command. The CURRENT_TIMESTAMP function returns a value of TIMESTAMP WITH TIME ZONE while the CURRENT_DATE function returns a value of DATE without time zone data.The CURRENT_TIMESTAMP function accepts no parameters. Syntax: CURRENT_TIMESTAMP Parameters Used:The CURRENT_TIMESTAMP function accepts no parameters. Return Value:The CURRENT_TIMESTAMP function returns a value of the current timestamp in TIMESTAMP WITH TIME ZONE data type. Supported Versions of Oracle/PLSQL: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: Using the CURRENT_TIMESTAMP function to show the current timestamp in the session time zone. ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'; SELECT CURRENT_TIMESTAMP FROM dual; Output: Session altered. CURRENT_TIMESTAMP 22-OCT-19 07.28.32.374935 AM +00:00 Example-2: Using the CURRENT_TIMESTAMP function to show the current timestamp using altered session time zone. ALTER SESSION SET TIME_ZONE = '-10:00'; SELECT CURRENT_TIMESTAMP FROM dual; Output: Session altered. CURRENT_TIMESTAMP 21-OCT-19 09.31.40.273270 PM -10:00 The new date and time was adjusted about -10 hours as expected. Advantage:The CURRENT_TIMESTAMP function returns a value of TIMESTAMP WITH TIME ZONE while the CURRENT_DATE function returns a value of DATE without time zone data. SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n24 Oct, 2019" }, { "code": null, "e": 25924, "s": 25513, "text": "The PLSQL CURRENT_TIMESTAMP function is used to return the current date and time in session time zone. The time zone used is the time zone of the current SQL sessi...
C++ Program to cyclically rotate an array by one
09 Jul, 2022 Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4} Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element of array with x. C++ // C++ code for program // to cyclically rotate// an array by one# include <iostream>using namespace std; void rotate(int arr[], int n){ int x = arr[n - 1], i; for (i = n - 1; i > 0; i--) arr[i] = arr[i - 1]; arr[0] = x;} // Driver codeint main() { int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is "; for (i = 0; i < n; i++) cout << arr[i] << ' '; rotate(arr, n); cout << "Rotated array is"; for (i = 0; i < n; i++) cout << arr[i] << ' '; return 0;} // This code is contributed by jit_t Given array is 1 2 3 4 5 Rotated array is 5 1 2 3 4 Time Complexity: O(n) As we need to iterate through all the elements Auxiliary Space: O(1)The above question can also be solved by using reversal algorithm. Another approach: We can use two pointers, say i and j which point to first and last element of array respectively. As we know in cyclic rotation we will bring last element to first and shift rest in forward direction, so start swaping arr[i] and arr[j] and keep j fixed and i moving towards j. Repeat till i is not equal to j. C++ #include <iostream>using namespace std; void rotate(int arr[], int n){ int i = 0, j = n-1; // i and j pointing to first and last element respectively while(i != j){ swap(arr[i], arr[j]); i++; }} // Driver codeint main() { int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; for (i = 0; i < n; i++) cout << arr[i] << " "; rotate(arr, n); cout << "\nRotated array is\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; return 0;} Given array is 1 2 3 4 5 Rotated array is 5 1 2 3 4 Time Complexity: O(n)Auxiliary Space: O(1) Program to cyclically rotate an array by one | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersProgram to cyclically rotate an array by one | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ZNqWgwwpgLU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please refer complete article on Program to cyclically rotate an array by one for more details! sachinvinod1904 rotation Arrays C++ C++ Programs School Programming Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem What is Data Structure: Types, Classifications and Applications Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2022" }, { "code": null, "e": 91, "s": 28, "text": "Given an array, cyclically rotate the array clockwise by one. " }, { "code": null, "e": 103, "s": 91, "text": "Examples: " }, { "code": null, "...
Operations on Lists in R Programming
25 Aug, 2020 Lists in R language, are the objects which comprise elements of diverse types like numbers, strings, logical values, vectors, list within a list and also matrix and function as its element. A list is generated using list() function. It is basically a generic vector that contains different objects. R allows its users to perform various operations on lists which can be used to illustrate the data in different forms. Lists in R can be created by placing the sequence inside the list() function. R # Creating a list.Geek_list <- list("Geek", "RList”, c(65, 21, 80), TRUE, 27.02, 10.3)print(Geek_list) Output: [[1]] [1] "Geek" [[2]] [1] "RList" [[3]] [1] 65 21 80 [[4]] [1] TRUE [[5]] [1] 27.02 [[6]] [1] 10.3 Name can be assigned to the elements of the list and those names can be used to access the elements. R # Creating a ListGeek_list <- list(c("Geeks", "For", "Geeks"), matrix(c(1:9), nrow = 3), list("Geek", 12.3)) # Naming each element of the listnames(Geek_list) <- c("This_is_a_vector", "This_is_a_Matrix", "This_is_a_listwithin_the_list") # Printing the listprint(Geek_list) Output: $This_is_a_vector [1] "Geeks" "For" "Geeks" $This_is_a_Matrix [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 $This_is_a_listwithin_the_list $This_is_a_listwithin_the_list[[1]] [1] "Geek" $This_is_a_listwithin_the_list[[2]] [1] 12.3 In order to access the list elements, use the index number, and in case of named list, elements can be accessed using its name also. R # Creating a ListGeek_list <- list(c("Geeks", "For", "Geeks"), matrix(c(1:9), nrow = 3), list("Geek", 12.3)) # Naming each element of the listnames(Geek_list) <- c("This_is_a_vector", "This_is_a_Matrix", "This_is_a_listwithin_the_list") # To access the first element of the list. print(Geek_list[1]) # To access the third element. print(Geek_list[3]) # To access the list element using the name of the element. print(Geek_list$This_is_a_Matrix) Output: $This_is_a_vector [1] "Geeks" "For" "Geeks" $This_is_a_listwithin_the_list $This_is_a_listwithin_the_list[[1]] [1] "Geek" $This_is_a_listwithin_the_list[[2]] [1] 12.3 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 In R, a new element can be added to the list, the existing element can be deleted or updated. R # Creating a ListGeek_list <- list(c("Geeks", "For", "Geeks"), matrix(c(1:9), nrow = 3), list("Geek", 12.3)) # Naming each element of the listnames(Geek_list) <- c("This_is_a_vector", "This_is_a_Matrix", "This_is_a_listwithin_the_list") # To add a new element.Geek_list[4] <- "New element"print(Geek_list) # To remove the last element. Geek_list[4] <- NULL # To print the 4th Element. print(Geek_list[4]) # To update the 3rd Element. Geek_list[3] <- "updated element"print(Geek_list[3]) Output: $This_is_a_vector [1] "Geeks" "For" "Geeks" $This_is_a_Matrix [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 $This_is_a_listwithin_the_list $This_is_a_listwithin_the_list[[1]] [1] "Geek" $This_is_a_listwithin_the_list[[2]] [1] 12.3 [[4]] [1] "New element" $ NULL $This_is_a_listwithin_the_list [1] "updated element" Many lists can be merged in one list by which all the list elements are placed inside one list. R # Firstly, create two lists. list1 <- list(1, 2, 3, 4, 5, 6, 7)list2 <- list("Geeks", "For", "Geeks") # Then to merge these two lists. merged_list <- c(list1, list2)print(merged_list) Output: [[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 [[4]] [1] 4 [[5]] [1] 5 [[6]] [1] 6 [[7]] [1] 7 [[8]] [1] "Geeks" [[9]] [1] "For" [[10]] [1] "Geeks" In order to perform arithmetic operations, lists should be converted to vectors using unlist() function. R # Firstly, create lists. list1 <- list(1:5)print(list1)list2 <-list(11:15)print(list2) # Now, convert the lists to vectors. v1 <- unlist(list1)v2 <- unlist(list2)print(v1)print(v2) # Now add the vectors result_vector <- v1+v2print(result_vector) Output: [[1]] [1] 1 2 3 4 5 [[1]] [1] 11 12 13 14 15 [1] 1 2 3 4 5 [1] 11 12 13 14 15 [1] 12 14 16 18 20 Picked R-List R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2020" }, { "code": null, "e": 218, "s": 28, "text": "Lists in R language, are the objects which comprise elements of diverse types like numbers, strings, logical values, vectors, list within a list and also matrix and function a...
How to create a Dictionary App in ReactJS ?
05 Aug, 2021 In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch information from an API and display it and some basics of how React actually works. Also, we will learn about how to use React icons. Let’s begin. Approach: Our app contains two sections, one for taking the user input and the other is for displaying the data. Whenever a user searches for a word, we store that input in a state and trigger an API call based on the searched keyword parameter. After that when the API call is made, we simply store that API response in another state variable, and then we finally display the information accordingly. Prerequisites: The pre-requisites for this project are: React Functional Components React Hooks React Axios & API javascript ES6 Creating a React application and installing some npm packages: Step 1: Create a react application by typing the following command in the terminal: npx create-react-app dictionary-app Step 2: Now, go to the project folder i.e dictionary-app by running the following command: cd dictionary-app Step 3: Let’s install some npm packages required for this project: npm install axios npm install react-icons --save Project Structure: It should look like this: Example: It is the only component of our app that contains all the logic. We will be using a free opensource API (no auth required) called ‘Free Dictionary API’ to fetch all the required data. Our app contains two sections i.e a section for taking the user input and a search button, the other is for displaying the data. Apart from displaying the information that we received, we will also have a speaker button that lets users listen to the phonetics. Now write down the following code in the App.js file. Here, the App is our default component where we have written our code. Here, the filename is App.js and App.css Javascript import { React, useState } from "react";import Axios from "axios";import "./App.css";import { FaSearch } from "react-icons/fa";import { FcSpeaker } from "react-icons/fc"; function App() { // Setting up the initial states using react hook 'useState' const [data, setData] = useState(""); const [searchWord, setSearchWord] = useState(""); // Function to fetch information on button // click, and set the data accordingly function getMeaning() { Axios.get( `https://api.dictionaryapi.dev/api/v2/entries/en_US/${searchWord}` ).then((response) => { setData(response.data[0]); }); } // Function to play and listen the // phonetics of the searched word function playAudio() { let audio = new Audio(data.phonetics[0].audio); audio.play(); } return ( <div className="App"> <h1>Free Dictionary</h1> <div className="searchBox"> // Taking user input <input type="text" placeholder="Search..." onChange={(e) => { setSearchWord(e.target.value); }} /> <button onClick={() => { getMeaning(); }} > <FaSearch size="20px" /> </button> </div> {data && ( <div className="showResults"> <h2> {data.word}{" "} <button onClick={() => { playAudio(); }} > <FcSpeaker size="26px" /> </button> </h2> <h4>Parts of speech:</h4> <p>{data.meanings[0].partOfSpeech}</p> <h4>Definition:</h4> <p>{data.meanings[0].definitions[0].definition}</p> <h4>Example:</h4> <p>{data.meanings[0].definitions[0].example}</p> </div> )} </div> );} export default App; HTML @import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap');@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,400;0,600;0,800;1,300&display=swap'); .App { height: 100vh; width: 100vw; display: flex; flex-direction: column; align-items: center; background-color: #f6f6f6; background-image: linear-gradient(315deg, #f6f6f6 0%, #e9e9e9 74%); font-family:'Poppins', sans-serif;} h1 { text-align: center; font-size: 3em; font-family: 'Pacifico', cursive; color: #4DB33D; padding: 1.5em;} h2{ font-size: 30px; text-decoration: underline; padding-bottom: 20px;} h4{ color: #4DB33D;} input{ width: 400px; height: 38px; font-size: 20px; padding-left: 10px;} .searchBox > button{ background-color: #4DB33D; height: 38px; width: 60px; border: none; color: white; box-shadow: 0px 3px 2px #439e34; cursor: pointer; padding: 0;} .showResults{ width: 500px; padding: 20px;} .showResults > h2 > button{ background: none; border: none; cursor: pointer;} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: adnanirshad158 React-Questions Web-API ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Aug, 2021" }, { "code": null, "e": 340, "s": 28, "text": "In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch informatio...
Python | Pandas Series.divide()
15 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.divide() function performs floating division of series and other, element-wise (binary operator truediv). It is equivalent to series / other, but with support to substitute a fill_value for missing data in one of the inputs. Syntax: Series.divide(other, level=None, fill_value=None, axis=0) Parameter :other : Series or scalar valuefill_value : Fill existing missing (NaN) values.level : Broadcast across a level, matching Index values on the passed MultiIndex level Returns : result : Series Example #1: Use Series.divide() function to perform floating division of the given series object with a scalar. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.divide() function to perform floating division of the given series object with a scalar. # perform floating divisionresult = sr.divide(other = 2) # Print the resultprint(result) Output :As we can see in the output, the Series.divide() function has successfully performed the floating division of the given series object with a scalar. Example #2 : Use Series.divide() function to perform floating division of the given series object with a scalar. The given series object contains some missing values. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.divide() function to perform floating division of the given series object with a scalar. We are going to fill 50 at the place of all the missing values. # perform floating division# fill 50 at the place of missing valuesresult = sr.divide(other = 2, fill_value = 50) # Print the resultprint(result) Output : As we can see in the output, the Series.divide() function has successfully performed the floating division of the given series object with a scalar. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based index...
Loader in C/C++
18 Nov, 2018 Loader is the program of the operating system which loads the executable from the disk into the primary memory(RAM) for execution. It allocates the memory space to the executable module in main memory and then transfers control to the beginning instruction of the program . Example: akash @aix(/ u / akash) #cat./ ak1.cpp#include<stdio.h>int main(){ printf("Testing of Loader !"); return 0;} Compiling by xlC compiler: akash @aix(/ u / akash) #xlC – o ak1.out./ ak1.cpp akash @aix(/ u / akash) #ls – lrt ak1 * -rw – rw – r– 1 akash dev 74 Nov 12 06 : 10 ak1.cpp– rwxrwxr – x 1 akash dev 8562 Nov 12 06 : 34 ak1.out akash @aix(/ u / akash) # What really happens while running the executable: One could also use strace command for the same. akash@aix(/u/akash)# truss ./ak1.outexecve(“./ak1.out”, 0x2FF20A00, 0x200138A8) argc: 1read_sysconfig(0xF06F8278, 0x00000010, 0xFFFFFFF9, 0x10000000, 0x200007BC, 0x000000C0, 0x06010000, 0xF076A0F0) = 0x00000000sbrk(0x00000000) = 0x20000998vmgetinfo(0x2FF20350, 7, 16) = 0sbrk(0x00000000) = 0x20000998sbrk(0x00000008) = 0x20000998__libc_sbrk(0x00000000) = 0x200009A0loadquery(2, 0x200009C8, 0x00001000) = 0__loadx(0x0A040000, 0xF06F599C, 0x00000000, 0xF05BE208, 0x20001D20) = 0xF05BFD64loadbind(0, 0xF0760BBC, 0xF06D0E54) = 0kfcntl(0, F_GETFL, 0x00000000) = 67110914kfcntl(1, F_GETFL, 0x00000000) = 67110914kfcntl(2, F_GETFL, 0x00000000) = 67110914kfcntl(2, F_GETFL, 0x00000000) = 67110914kioctl(1, 22528, 0x00000000, 0x00000000) = 0Testing of Loader !kwrite(1, ” T e s t i n g o f L”.., 19) = 19kfcntl(1, F_GETFL, 0x00000070) = 67110914kfcntl(2, F_GETFL, 0x2FF22FFC) = 67110914_exit(0) The first call which is displayed is ‘execve()‘ which actually is the loader . This loader creates the process which involves: Reading the file and creating an address space for the process. Page table entries for the instructions, data and program stack are created and the register set is initialized. Then, Executes a jump instruction to the first instruction of the program which generally causes a page fault and the first page of your instructions is brought into memory. Below two points are not related to loader and are for just more information: Another thing we got is the kwrite call with the argument value which one passed to the printf function in our program. kwrite is system call which actually gets called from the printf function with the value passed to it and this is function is responsible to display the value to console with value passed to it. We also got the _exit(0) call at last instruction which is the _exit system call with argument status as 0 which signifies to return back to operating system with successful signal. This _exit got called from return(0) statement. system-programming C Language C++ Compiler Design CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Nov, 2018" }, { "code": null, "e": 327, "s": 53, "text": "Loader is the program of the operating system which loads the executable from the disk into the primary memory(RAM) for execution. It allocates the memory space to the execut...
Iterated Logarithm log*(n)
08 Dec, 2021 Iterated Logarithm or Log*(n) is the number of times the logarithm function must be iteratively applied before the result is less than or equal to 1. Applications: It is used in the analysis of algorithms (Refer Wiki for details) C++ Java Python3 C# PHP Javascript // Recursive CPP program to find value of// Iterated Logarithm#include <bits/stdc++.h>using namespace std; int _log(double x, double base){ return (int)(log(x) / log(base));} double recursiveLogStar(double n, double b){ if (n > 1.0) return 1.0 + recursiveLogStar(_log(n, b), b); else return 0;} // Driver codeint main(){ int n = 100, base = 5; cout << "Log*(" << n << ") = " << recursiveLogStar(n, base) << "\n"; return 0;} // Recursive Java program to// find value of Iterated Logarithmimport java.io.*; class GFG{static int _log(double x, double base){ return (int)(Math.log(x) / Math.log(base));} static double recursiveLogStar(double n, double b){ if (n > 1.0) return 1.0 + recursiveLogStar(_log(n, b), b); else return 0;} // Driver codepublic static void main (String[] args){ int n = 100, base = 5; System.out.println("Log*(" + n + ") = " + recursiveLogStar(n, base));}} // This code is contributed by jit_t # Recursive Python3 program to find value of# Iterated Logarithmimport math def _log(x, base): return (int)(math.log(x) / math.log(base)) def recursiveLogStar(n, b): if(n > 1.0): return 1.0 + recursiveLogStar(_log(n, b), b) else: return 0 # Driver codeif __name__=='__main__': n = 100 base = 5 print("Log*(", n, ") = ", recursiveLogStar(n, base)) # This code is contributed by# Sanjit_Prasad // Recursive C# program to// find value of Iterated Logarithm using System; public class GFG{static int _log(double x, double baset){ return (int)(Math.Log(x) / Math.Log(baset));} static double recursiveLogStar(double n, double b){ if (n > 1.0) return 1.0 + recursiveLogStar(_log(n, b), b); else return 0;} // Driver code static public void Main (){ int n = 100, baset = 5; Console.WriteLine("Log*(" + n + ") = " + recursiveLogStar(n, baset));}} // This code is contributed by ajit. <?php// Recursive PhP program to find// value of Iterated Logarithm function _log($x, $base){ return (int)(log($x) / log($base));} function recursiveLogStar($n, $b){ if ($n > 1.0) return 1.0 + recursiveLogStar(_log($n, $b), $b); else return 0;} // Driver code$n = 100; $base = 5;echo "Log*(" , $n , ")"," = ",recursiveLogStar($n, $base), "\n"; // This code is contributed by ajit?> <script> // Javascript program to// find value of Iterated Logarithm function _log( x, base){ return (Math.log(x) / Math.log(base));} function recursiveLogStar(n, b){ if (n > 1.0) return 1.0 + recursiveLogStar(_log(n, b), b); else return 0;} // Driver code let n = 100, base = 5; document.write("Log*(" + n + ") = " + recursiveLogStar(n, base)); // This code is contributed by sanjoy_62.</script> Output : Log*(100) = 2 Iterative Implementation : C++ Java Python3 C# Javascript // Iterative CPP function to find value of// Iterated Logarithmint iterativeLogStar(double n, double b){ int count = 0; while (n >= 1) { n = _log(n, b); count++; } return count;} // Iterative Java function to find value of// Iterated Logarithmpublic static int iterativeLogStar(double n, double b){ int count = 0; while (n >= 1) { n = _log(n, b); count++; } return count;} // This code is contributed by pratham76 # Iterative Python function to find value of# Iterated Logarithm def iterativeLogStar(n, b): count = 0 while(n >= 1): n = _log(n, b) count = count + 1 return count # This code is contributed by# Sanjit_Prasad // Iterative C# function to find value of// Iterated Logarithmstatic int iterativeLogStar(double n, double b){ int count = 0; while (n >= 1) { n = _log(n, b); count++; } return count;} // This code is contributed by rutvik_56 <script> // Iterative javascript function to find// value of Iterated Logarithmfunction iterativeLogStar(n, b){ var count = 0; while (n >= 1) { n = _log(n, b); count++; } return count;} // This code is contributed by 29AjayKumar </script> This article is contributed by Abhishek rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Sanjit_Prasad rutvik_56 pratham76 sanjoy_62 29AjayKumar Analysis Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Dec, 2021" }, { "code": null, "e": 204, "s": 54, "text": "Iterated Logarithm or Log*(n) is the number of times the logarithm function must be iteratively applied before the result is less than or equal to 1." }, { "code": nu...
NLP: Building Text Cleanup and PreProcessing Pipeline | by Dinesh Yadav | Towards Data Science
Natural Language Processing, in short NLP, is subfield of Machine learning / AI which deals with linguistics and human languages. NLP deals with interactions between computers and human languages. In other words, it enables and programs computers to understand human languages and process & analyse large amount of natural language data. But before a computer program can understand and interpret human language, a lot of pre-processing goes behind the scenes. Have you ever wondered what happens behind the scenes for sentiment analysis, text classification, tweet analysis etc.? Thanks to pre-processing, programs can easily transform language or text into a more assimilable form so that machine learning algorithms can perform better. These are used most often in sentiment analysis, feedback classification, translation, summarization etc. In many cases, pre-processing steps improves the accuracy of algorithms. Usually, input data is presented in natural form, which is in the format of text, sentences, comments, paragraphs, tweets etc. Before such input can be passed to machine learning algorithms, it needs some clean-up or pre-processing so algorithms can focus on main/important words instead of words which adds minimal to no value.Enough said, lets deep dive into NLP pre-processing techniques. In this example, I am using python as the programming language. Often, unstructured text contains a lot of noise, especially if you use techniques like web or screen scraping. HTML tags are typically one of these components which don’t add much value towards understanding and analysing text so they should be removed. We will use BeautifulSoup library for HTML tag clean-up. # importsfrom bs4 import BeautifulSoup# function to remove HTML tagsdef remove_html_tags(text): return BeautifulSoup(text, 'html.parser').get_text()# call functionremove_html_tags( ‘<html> \ <h1>Article Heading</h1> \ <p>First sentence of some important article. And another one. And then the last one</p></html>’) Output: ' Article Heading First sentence of some important article. And another one. And then the last one' Accented characters are important elements which are used to signify emphasis on a particular word during pronunciation or understanding. In some instances, the accent mark also clarifies the meaning of a word, which might be different without the accent. While their use in English is largely limited but there are very good chances that you will come across accented characters/letters in a free text corpus. Words such as résumé, café, prótest, divorcé, coördinate, exposé, latté etc. Accents might get induced because of someone keyboard default setting or typing style. Handling accented characters gets more important, especially if you only want to analyse the English language. Hence, we need to make sure that these characters are converted and standardized into ASCII characters. A simple example — converting é to e. # importsimport unicodedata# function to remove accented charactersdef remove_accented_chars(text): new_text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore') return new_text# call functionremove_accented_chars('Sómě Áccěntěd těxt. Some words such as résumé, café, prótest, divorcé, coördinate, exposé, latté.') Output: 'Some Accented text. Some words such as resume, cafe, protest, divorce, coordinate, expose, latte.' Contractions are shortened versions of words or syllables. They are created by removing specific, one or more letters from words. Often more than word are combined to create a contraction. In writing, an apostrophe is used to indicate the place of missing letters. In English language/text, contractions often exist in either written or spoken forms. Nowadays, many editors will induce contractions by default. For examples do not to don’t, I would to I’d, you are to you’re. Converting each contraction to its expanded, original form helps with text standardization. For removing contractions, I am leveraging a standard set of contractions available in the contractions library. # importsfrom contractions import CONTRACTION_MAP # from contractions.pyimport re # function to expand contractionsdef expand_contractions(text, map=CONTRACTION_MAP): pattern = re.compile('({})'.format('|'.join(map.keys())), flags=re.IGNORECASE|re.DOTALL) def get_match(contraction): match = contraction.group(0) first_char = match[0] expanded = map.get(match) if map.get(match) else map.get(match.lower()) expanded = first_char+expanded[1:] return expanded new_text = pattern.sub(get_match, text) new_text = re.sub("'", "", new_text) return new_text# call function expand_contractions(“Y’all i’d contractions you’re expanded don’t think.”) Output: 'You all i would contractions you are expanded do not think.' Another way can be: # importsfrom pycontractions import Contractionscont = Contractions(kv_model=model)cont.load_models()# function to expand contractionsdef expand_contractions(text): text = list(cont.expand_texts([text], precise=True))[0] return text Special characters, as you know, are non-alphanumeric characters. These characters are most often found in comments, references, currency numbers etc. These characters add no value to text-understanding and induce noise into algorithms. Thankfully, regular-expressions (regex) can be used to get rid of these characters and numbers. # importsimport re# function to remove special charactersdef remove_special_characters(text): # define the pattern to keep pat = r'[^a-zA-z0-9.,!?/:;\"\'\s]' return re.sub(pat, '', text) # call functionremove_special_characters(“007 Not sure@ if this % was #fun! 558923 What do# you think** of it.? $500USD!”) Output: '007 Not sure if this was fun! 558923 What do you think of it.? 500USD!' As you saw above, the text is retained. But sometimes these might not be required. Since we are dealing with text, so the number might not add much information to text processing. So, numbers can be removed from text. We can use regular-expressions (regex) to get rid of numbers. This step can be combined with above one to achieve in single step. # importsimport re# function to remove numbersdef remove_numbers(text): # define the pattern to keep pattern = r'[^a-zA-z.,!?/:;\"\'\s]' return re.sub(pattern, '', text) # call functionremove_numbers(“007 Not sure@ if this % was #fun! 558923 What do# you think** of it.? $500USD!”) Output: ' Not sure if this was fun! What do you think of it.? USD!' This can be clubbed with step of removing special characters. Removing punctuation is fairly easy. It can be achieved by using string.punctuation and keeping everything which is not in this list. # importsimport string# function to remove punctuationdef remove_punctuation(text): text = ''.join([c for c in text if c not in string.punctuation]) return text# call functionremove_punctuation('Article: @First sentence of some, {important} article having lot of ~ punctuations. And another one;!') Output: 'Article First sentence of some important article having lot of punctuations And another one' Stemming is the process of reducing inflected/derived words to their word stem, base or root form. The stem need not be identical to original word. There are many ways to perform stemming such as lookup table, suffix-stripping algorithms etc. These mainly rely on chopping-off ‘s’, ‘es’, ‘ed’, ‘ing’, ‘ly’ etc from the end of the words and sometimes the conversion is not desirable. But nonetheless, stemming helps us in standardizing text. # importsimport nltk# function for stemmingdef get_stem(text): stemmer = nltk.porter.PorterStemmer() text = ' '.join([stemmer.stem(word) for word in text.split()]) return text# call functionget_stem("we are eating and swimming ; we have been eating and swimming ; he eats and swims ; he ate and swam ") Output: 'we are eat and swim ; we have been eat and swim ; he eat and swim ; he ate and swam' Though stemming and lemmatization both generate the root form of inflected/desired words, but lemmatization is an advanced form of stemming. Stemming might not result in actual word, whereas lemmatization does conversion properly with the use of vocabulary, normally aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma. Before using lemmatization, we should be aware that it is considerably slower than stemming, so performance should be kept in mind before choosing stemming or lemmatization. # importsimport spacynlp = spacy.load('en',parse=True,tag=True, entity=True)# function to remove special charactersdef get_lem(text): text = nlp(text) text = ' '.join([word.lemma_ if word.lemma_ != '-PRON-' else word.text for word in text]) return text# call functionget_lem("we are eating and swimming ; we have been eating and swimming ; he eats and swims ; he ate and swam ") Output: 'we be eat and swim ; we have be eat and swim ; he eat and swim ; he eat and swam' Stopwords are often added to sentences to make them grammatically correct, for example, words such as a, is, an, the, and etc. These stopwords carry minimal to no importance and are available plenty on open texts, articles, comments etc. These should be removed so machine learning algorithms can better focus on words which define the meaning/idea of the text. We are using list from nltk.corpus and this list can further be enhanced by adding or removing custom words based on the situation at hand. # importsimport nltkfrom nltk.tokenize import ToktokTokenizertokenizer = ToktokTokenizer()stopword_list = nltk.corpus.stopwords.words('english')# custom: removing words from liststopword_list.remove('not')# function to remove stopwordsdef remove_stopwords(text): # convert sentence into token of words tokens = tokenizer.tokenize(text) tokens = [token.strip() for token in tokens] # check in lowercase t = [token for token in tokens if token.lower() not in stopword_list] text = ' '.join(t) return text# call functionremove_stopwords("i am myself you the stopwords list and this article is not should removed") Output: 'stopwords list article not removed' Extra whitespaces and tabs do not add any information to text processing. Handling these should be fairly easy. # importsimport re# function to remove special charactersdef remove_extra_whitespace_tabs(text): #pattern = r'^\s+$|\s+$' pattern = r'^\s*|\s\s*' return re.sub(pattern, ' ', text).strip()# call functionremove_extra_whitespace_tabs(' This web line has \t some extra \t tabs and whitespaces ') Output: 'This web line has some extra tabs and whitespaces' Changing case to lower can be achieved by using lower function. # function to remove special charactersdef to_lowercase(text): return text.lower()# call functionto_lowercase('ConVert THIS string to LOWER cASe.') Output: 'convert this string to lower case.' Some of these steps can be combined in a single step. Also, note that few of these might not be required depending upon the context and requirement. Furthermore, we can define a new function encapsulating all of the above pre-processing functions to form a text-normalizer pipeline. These steps should give you a good idea about how to build your clean-up and pre-processing strategies. After these pre-processing steps, the corpus of text is ready for NLP algorithms such as Word2Vec, GloVe etc. These pre-processing steps will definitely improve the model’s accuracy. Hope you liked this article, and if so, then please say so in comments. If you would like to share any suggestion on any approach, then feel free to say so in comments and I will revert right away.
[ { "code": null, "e": 509, "s": 171, "text": "Natural Language Processing, in short NLP, is subfield of Machine learning / AI which deals with linguistics and human languages. NLP deals with interactions between computers and human languages. In other words, it enables and programs computers to under...
Develop Your Weather Application with Python in Less Than 10 Lines | by Bharath K | Towards Data Science
Weather is one of the most crucial aspects of our life. It dictates the different kinds of activities that we would like to plan throughout the day, week, or month. One of the older methods of reading weather patterns is to look at the sky and predict whether it would stay sunny, rain, or have a humid weather condition. This method might not be the most effective if you are not well-versed with climatic such as me and always end up getting your predictions wrong. The other method includes waiting and watching news channels for their daily reports to analyze the weather. However, these ways seem a bit outdated for the modern era we live in today. There are different devices and tools that will allow you to interpret the current weather conditions from satellite reports and numerous scientific studies. In this article, we will make use of such API technologies with Python to create your own weather reporting application in less than ten lines of code. So, without further ado, let us get started on accomplishing this project. For this project, we will utilize Python and a weather reporting service that provides us with an API key to interpret the daily weather conditions of any particular place. One of the few library requirements that we will need for this project is the request module that is available in Python. If you don’t have it already, feel free to install the following module with a simple pip install command and import the library as shown below. This tool will allow us to directly access HTTP links for the required weather API applications. import requests Now, we will require an API key from a website that stores information about the weather and forecasts them with accurate results. The Open Weather Map website provides a scientific yet simplistic approach for utilizing their technology in our Python code to quickly yield the desired results of weather forecasting. To generate your own API key, simply log in to the following website and create an account for totally free. You can either use one of their suggested API keys or generate one of your own. Paste this generated API key in a variable of your choice, as shown below. API_Key = "" Our next step is to allow the user to enter their desired location for which they want to analyze or view the weather conditions. We can perform the following action with an input command allowing the user to type in the required location. Note that you are allowed to type only locations that actually exist. If you mistype the name of the location or of a location that does not exist, you will receive an error message that will be displayed. We will now create a variable that will store the default URL location to the weather access website. For the final URL, we will combine the default path of the open weather map website with the API key that we have previously generated and stored in the API_Key variable. Finally, in the weather data variable, we will use the requests library to get the weather data and store the information accordingly. location = input("Enter Your Desired Location: ")weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid="final_url = weather_url + API_Keyweather_data = requests.get(final_url).json() Now that we have successfully collected our weather information in the respective variable, we can proceed to display the required data to the user. The following action can be done with the print statement, as shown in the below code snippet. print(weather_data) You may notice that the information that is displayed from the print statement does not look as pretty as you might have expected it to, as the data collected and displayed are in the raw format. Hence, we can make use of the Data pretty printer module to allow us to print the useful information in a more presentable and readable manner for the user. from pprint import pprintpprint(weather_data) In the next section of this article, we will look at the complete code for constructing our weather app as well as analyze the numerous improvements and advancements that we can make to this project. With the discussion of all of the elementary code snippets from our previous section, we can combine them together to construct our final code block for this project. Feel free to use the following code provided below to experiment with various locations. Below is a result to show the effective working of this project. import requestsfrom pprint import pprintAPI_Key = ""location = input("Enter Your Desired Location: ")weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid="final_url = weather_url + API_Keyweather_data = requests.get(final_url).json()pprint(weather_data) Enter Your Desired Location: Bangalore{'base': 'stations', 'clouds': {'all': 15}, 'cod': 200, 'coord': {'lat': 12.9762, 'lon': 77.6033}, 'dt': 1641477819, 'id': 1277333, 'main': {'feels_like': 294.17, 'grnd_level': 912, 'humidity': 45, 'pressure': 1013, 'sea_level': 1013, 'temp': 294.78, 'temp_max': 296.05, 'temp_min': 294.78}, 'name': 'Bengaluru', 'sys': {'country': 'IN', 'id': 2040609, 'sunrise': 1641431598, 'sunset': 1641472610, 'type': 2}, 'timezone': 19800, 'visibility': 10000, 'weather': [{'description': 'few clouds', 'icon': '02n', 'id': 801, 'main': 'Clouds'}], 'wind': {'deg': 118, 'gust': 8.31, 'speed': 4.81}} One of the unique variations that the users can try out with the project is to display the weather report of your location whenever you start the program. And continue to display it for every few hours to rapidly check the climatic variation to plan your schedule accordingly. You can set your desired location as required in the code and construct the project in a fashion similar to the reminder application that I have covered previously in one of my articles. Feel free to check it out from the link provided below. towardsdatascience.com Another additional improvement that the users can make is to construct a GUI application for displaying the weather conditions accordingly. If you are not well acquainted with Graphic tools with Python, you can check out one of my previous articles to learn more about seven of the best GUI’s with starter codes. towardsdatascience.com “Wherever you go, no matter what the weather, always bring your own sunshine.” — Anthony J. D’Angelo Weather, as discussed previously, plays a crucial role in our daily life. Hence, it is highly beneficial to develop a weather application that will help us track this integral element of nature successfully so that we can all plan our schedules accordingly and choose what would be the best course of action to go about in our daily life. In this article, we learned how to construct a weather report application in about ten lines of Python code. We looked into the simple API key generation and used the request module to access the required information for displaying the accurate weather reports of the particular location. We also analyzed some of the additional improvements that we can accustom to this project to make it more appealing and useful. If you want to get notified about my articles as soon as they go up, check out the following link to subscribe for email recommendations. If you wish to support other authors and me, then subscribe to the below link. bharath-k1297.medium.com If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible. Check out some of my other articles in relation to the topic covered in this piece that you might also enjoy reading! towardsdatascience.com towardsdatascience.com towardsdatascience.com Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day!
[ { "code": null, "e": 487, "s": 165, "text": "Weather is one of the most crucial aspects of our life. It dictates the different kinds of activities that we would like to plan throughout the day, week, or month. One of the older methods of reading weather patterns is to look at the sky and predict whe...
The basics of Monte Carlo integration | by Victor Cumer | Towards Data Science
We all remember the integrals we had to compute manually in hight school. To do so, we had to compute a series of more or less complexe operations to find the antiderivative functions’ expressions before applying substraction through the desired interval. However, you may also remember that integrating a function is graphically equivalent to calculating the area under the curve of that function. The principle of numerical integration lies on this second statement. The idea is to estimate the integral of a function, over a defined interval, only knowing the function expression. For such an aim, Monte Carlo methods are a great help. Monte Carlo integration is a technique for numerical integration using random numbers. Let’s try to integrate a univariate function f. We will denote by F the value of the integral. As we said in the introduction, this integral can be interpreted as the area below the function’s curve. Let’s take the following function as an example: The figure 1 is the graphical representation of f and the integral we’d like to compute. Let’s say a=-2 and b=5. If we take a random point x_i between a and b, we can multiply f(x_i) by (b-a) to get the area of a rectangle of width (b-a) and height f(x_i). The idea behind Monte Carlo integration is to approximate the integral value (gray area on figure 1) by the averaged area of rectangles computed for random picked x_i. This is illustrated in figure 2 below. By adding up the area of the rectangles and averaging the sum, the resulting number gets closer and closer to the actual result of the integral. In fact, the rectangles which are too large compensate for the rectangles which are too small. So it seems that the empirical mean of f(x) could be a good estimator for the integral. This idea is formalized with the following formula, which is the Monte Carlo estimator (N is the number of random draws for X): In this formula, X is a random variable, and so is FN. The law of large numbers gives us that as N approaches infinity, the Monte Carlo estimator converges in probability to F, the true value of the integral: Another important result we get from the Monte Carlo estimator is the variance of the estimator: σ^2 / N where σ is the standard deviation of the function values, and N is the number of samples x_i. It means we need 4 times more samples to reduce the error of the estimator by 2. In the following two parts, we will give concrete examples of implementation for integration in python (2D and 3D) with the crude method first, and then we will explain a variance reduction solution: importance sampling. The crude Monte Carlo method is the most basic application of the concept described above: Random draws x_i are made over X following a uniform law. We compute the sum of f(x_i), multiply it by (b-a) and divide by the number of samples N. To illustrate the process, let’s take a concrete use case: we want to integrate the beta distribution function beta(x, 50, 50) over the interval [0 ; 0.55] as it is described on figure 3 below. If X is a random variable that follows this beta law, this integral corresponds to P(X <= 0.55), which can be calculated exactly with the cumulative density function (c.d.f.) of the beta(x, 50, 50) density law: it gives 0.8413. We will try to approach this number through Monte Carlo integration. As describe earlier, we will do N = 10 000 random draws of x_i using the uniform distribution. Then, we compute the integral estimation and the associated error using the following formulas: The blue points correspond to the 10 000 values of f(x_i) computed from the uniform draws we made over X. We can already notice that because the draws were made uniformly over X (i.e. the horizontal axe), we have quite some space and less overlapping between the points when the slope of the curve increases. Another way to compute the integral is to make a geometric approximation of the integral. Indeed, by using uniform random draws over both x and y axes, we map a 2D rectangle that correspond to the desired range [x_min ; x_max] and compute the ratio of points under the curve over the total points drawn in the rectangle. This ratio would converge to the area under the curve with N, the number of draws. This idea is illustrated in figure 5. The idea behind Importance Sampling is very simple: as the error of the Monte Carlo estimator is proportional to the standard deviation of f(x) divided by the square root of the number of samples, we should find a cleverer method to chose x_i than the uniform law. Importance Sampling is in fact a way to draw x_i to reduce the variance of f(x). Indeed, for the function beta(x, 50, 50) we noticed a lot of x_i over [0 ; 0.55] will give a f(x) ~ 0, while only few values of x around 0.5 will give f(x) ~ 8. The key idea of Importance Sampling is that we use a probability density function (p.d.f.) to draw samples over X that will give more chance to high values of f(x) to be computed, and then we weight the sum of f(x) by the chance that x happened (i.e. the value of the p.d.f.). Following this idea, the integral we try to approximate will became: with: N: number of samples f: function to integrate g: p.d.f. chosen for the random draws over X G: the inverse function of g And the variance of f used to compute error of the estimator becomes: Back to our use case with the beta(x,50,50) distribution function, it seems that using a normal distribution centered at 0.5 as the g function could help us. The links between f and g are shown on figure 6 below. Figure 7 below shows the results of using such a method to integrate beta(x,50,50) over [0 ; 0.55]. The density of the points also shows the relevance to use of the Gaussian p.d.f compared to the uniform law to choose x_i: the x_i points are concentrated in areas of interest, where f(x_i) != 0. Here is the summary of integral values and relative errors. We reduce x4 the error with the Importance Sampling method. Figure 8 takes an example of 3D jointplot mapped on a 2D space (x_A, x_B). This example is taken from the analysis of Bayesian A/B tests. The blue contour plot corresponds to beta distribution functions for 2 different variants (A and B). The idea is to compute the probability that variation B is better than variation A by calculating the integral of the joint posterior f, the blue contour plot on the graph, for x_A and x_B values that are over the orange line (i.e. values where x_B >= x_A ). Thus, let’s compute the integral that corresponds to the area below the blue 3D bell for values of x_A and x_B that respect x_B >= x_A (upper to the orange line on the graph). This time we will draw N = 100 000 samples. Integral value: 0.7256321849276118Calculation error: 0.01600479134298051 Integral value: 0.7119836088517515Calculation error: 0.0018557917512560286 The importance sampling method enabled to reach an almost x10 more precise result with the same amount of samples. The crude method and importance sampling belong to a large range of Monte Carlo integration methods. Here you have all the material to implement these two techniques in python with no more than usual libraries as numpy and scipy. Keep in mind that Monte Carlo integration is particularly useful for higher-dimensional integrals. With the example we came through, we got a x10 improvement regarding precision for the 3D case, while it was a x4 improvement for the 2D case.
[ { "code": null, "e": 898, "s": 172, "text": "We all remember the integrals we had to compute manually in hight school. To do so, we had to compute a series of more or less complexe operations to find the antiderivative functions’ expressions before applying substraction through the desired interval....
How to Iterate Python Dictionary ? - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Python dictionary stores the data in a key-value pair format, it allows the developers to store a large amount/variety of data; therefore, there were several ways to iterate over them. In this tutorials, we are going to see how to Iterate over dictionary Python in different ways. As a dictionary stores the data as key-value pair, it allows us to loop through the keys or values. The following dictionary consists of persons information such as user_name,first_name and last_name. Lets try to iterate this. persons = { 'user_name':'chandra', 'first_name':'chandra shekhar', 'last_name':'goka' } We could loop through dictionary using a for loop like below. persons = { 'user_name':'chandra', 'first_name':'chandra shekhar', 'last_name':'goka' } #Looping thorough key,values for key,value in persons.items(): print(f"Key: {key} - Value: {value}") On the above for loop we created names for the two variables key and value (you can choose any names for these). items() method returns the key-value pair for a specific iteration and the the loop assigns key-values into the key,value variables for the each iteration. Output: Key: user_name - Value: chandra Key: first_name - Value: chandra shekhar Key: last_name - Value: goka The key() method is used to get the key from a dictionary, using which we can loop though the keys. The below dictionary is a collection of favorite subject of each person. Lets loop though this Dictionary using keys. favorite_subjects={ 'chandra':'Computers', 'panvith':'Physics', 'jon':'Mathematics', 'robert':'Computers' } for name,fav_subject in favorite_subjects.items(): print(f"{name} likes {fav_subject}") Output: chandra panvith jon robert From Python 3.7 looping through a dictionary gives the items the same way the items were inserted. If you would like to read the items in an sorted order, we can do this by applying sorted() method on it. favorite_subjects={ 'chandra':'Computers', 'panvith':'Physics', 'jon':'Mathematics', 'robert':'Computers' } #Keys in Order for name in sorted(favorite_subjects.keys()): print(name) Output: chandra jon panvith robert Just like loop though the keys, we can also loop through the values of a dictionary using values() method. favorite_subjects={ 'chandra':'Computers', 'panvith':'Physics', 'jon':'Mathematics', 'robert':'Computers' } for fav_subject in favorite_subjects.values(): print(fav_subject) Output: Computers Physics Mathematics Computers favorite_subjects= { 'chandra':'Computers', 'panvith':'Physics', 'jon':'Mathematics', 'robert':'Computers' } #Values in Order for fav_subject in sorted(favorite_subjects.values()): print(fav_subject) Output: Computers Computers Mathematics Physics As you can see on the above output, there was a duplicate subject (Computer), we can remove the duplicates while iterating the dictionary values like below. Using set() method we can remove the duplicates – You can see more about set function here. favorite_subjects= { 'chandra':'Computers', 'panvith':'Physics', 'jon':'Mathematics', 'robert':'Computers' } #Remove duplicates in values for fav_subject in sorted(set(favorite_subjects.values())): print(fav_subject) Output: Computers Mathematics Physics Python Set data structure in depth Python dictionary Happy Learning 🙂 Python Dictionary Methods and Usages How to sort python dictionary by key ? Python – How to remove key from dictionary ? Python – How to merge two dict in Python ? How to read JSON file in Python ? How to create Python Iterable class ? How to access for loop index in Python 5 Ways to Iterate ArrayList in Java What are Python default function parameters ? What are different Python Data Types Python raw_input read input from keyboard Python How to read input from keyboard Python Tuple Data Structure in Depth What are the different ways to Sort Objects in Python ? Python List Data Structure In Depth Python Dictionary Methods and Usages How to sort python dictionary by key ? Python – How to remove key from dictionary ? Python – How to merge two dict in Python ? How to read JSON file in Python ? How to create Python Iterable class ? How to access for loop index in Python 5 Ways to Iterate ArrayList in Java What are Python default function parameters ? What are different Python Data Types Python raw_input read input from keyboard Python How to read input from keyboard Python Tuple Data Structure in Depth What are the different ways to Sort Objects in Python ? Python List Data Structure In Depth Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, ...
Teradata - Table Types
Teradata supports the following table types to hold temporary data. Derived Table Volatile Table Global Temporary Table Derived tables are created, used and dropped within a query. These are used to store intermediate results within a query. The following example builds a derived table EmpSal with records of employees with salary greater than 75000. SELECT Emp.EmployeeNo, Emp.FirstName, Empsal.NetPay FROM Employee Emp, (select EmployeeNo , NetPay from Salary where NetPay >= 75000) Empsal where Emp.EmployeeNo = Empsal.EmployeeNo; When the above query is executed, it returns the employees with salary greater than 75000. *** Query completed. One row found. 3 columns returned. *** Total elapsed time was 1 second. EmployeeNo FirstName NetPay ----------- ------------------------------ ----------- 103 Peter 83000 Volatile tables are created, used and dropped within a user session. Their definition is not stored in data dictionary. They hold intermediate data of the query which is frequently used. Following is the syntax. CREATE [SET|MULTISET] VOALTILE TABLE tablename <table definitions> <column definitions> <index definitions> ON COMMIT [DELETE|PRESERVE] ROWS CREATE VOLATILE TABLE dept_stat ( dept_no INTEGER, avg_salary INTEGER, max_salary INTEGER, min_salary INTEGER ) PRIMARY INDEX(dept_no) ON COMMIT PRESERVE ROWS; When the above query is executed, it produces the following output. *** Table has been created. *** Total elapsed time was 1 second. The definition of Global Temporary table is stored in data dictionary and they can be used by many users/sessions. But the data loaded into global temporary table is retained only during the session. You can materialize up to 2000 global temporary tables per session. Following is the syntax. CREATE [SET|MULTISET] GLOBAL TEMPORARY TABLE tablename <table definitions> <column definitions> <index definitions> CREATE SET GLOBAL TEMPORARY TABLE dept_stat ( dept_no INTEGER, avg_salary INTEGER, max_salary INTEGER, min_salary INTEGER ) PRIMARY INDEX(dept_no); When the above query is executed, it produces the following output. *** Table has been created. *** Total elapsed time was 1 second. Print Add Notes Bookmark this page
[ { "code": null, "e": 2698, "s": 2630, "text": "Teradata supports the following table types to hold temporary data." }, { "code": null, "e": 2712, "s": 2698, "text": "Derived Table" }, { "code": null, "e": 2727, "s": 2712, "text": "Volatile Table" }, { ...
C++ String Library - back
It returns a reference to the last character of the string. Following is the declaration for std::string::back. char& back(); const char& back() const; none It returns a reference to the last character of the string. if an exception is thrown, there are no changes in the string. In below example for std::string::back. #include <iostream> #include <string> int main () { std::string str ("sairamkrishna mammahe."); str.back() = '!'; std::cout << str << '\n'; return 0; } sairamkrishna mammahe! Print Add Notes Bookmark this page
[ { "code": null, "e": 2663, "s": 2603, "text": "It returns a reference to the last character of the string." }, { "code": null, "e": 2715, "s": 2663, "text": "Following is the declaration for std::string::back." }, { "code": null, "e": 2729, "s": 2715, "text": ...
Optimal sequence for AVL tree insertion (without any rotations) - GeeksforGeeks
26 Oct, 2021 Given an array of integers, the task is to find the sequence in which these integers should be added to an AVL tree such that no rotations are required to balance the tree.Examples : Input : array = {1, 2, 3} Output : 2 1 3 Input : array = {2, 4, 1, 3, 5, 6, 7} Output : 4 2 6 1 3 5 7 Approach : Sort the given array of integers. Create the AVL tree from the sorted array by following the approach described here. Now, find the level order traversal of the tree which is the required sequence. Adding numbers in the sequence found in the previous step will always maintain the height balance property of all the nodes in the tree. Below is the implementation of the above approach : C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* A Binary Tree node */struct TNode { int data; struct TNode* left; struct TNode* right;}; struct TNode* newNode(int data); /* Function to construct AVL tree from a sorted array */struct TNode* sortedArrayToBST(vector<int> arr, int start, int end){ /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end) / 2; struct TNode* root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid + 1, end); return root;} /* Helper function that allocates a new node with the given data and NULL to the left and the right pointers. */struct TNode* newNode(int data){ struct TNode* node = new TNode(); node->data = data; node->left = NULL; node->right = NULL; return node;} // This function is used for testing purposevoid printLevelOrder(TNode *root){ if (root == NULL) return; queue<TNode *> q; q.push(root); while (q.empty() == false) { TNode *node = q.front(); cout << node->data << " "; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); }} /* Driver program totest above functions */int main(){ // Assuming the array is sorted vector<int> arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.size(); /* Convert List to AVL tree */ struct TNode* root = sortedArrayToBST(arr, 0, n - 1); printLevelOrder(root); return 0;} // Java implementation of the approachimport java.util.*;class solution{ /* A Binary Tree node */ static class TNode { int data; TNode left; TNode right;} /* Function to con AVL tree from a sorted array */ static TNode sortedArrayToBST(int arr[], int start, int end){ /* Base Case */ if (start > end) return null; /* Get the middle element and make it root */ int mid = (start + end) / 2; TNode root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root.left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root.right = sortedArrayToBST(arr, mid + 1, end); return root;} /* Helper function that allocates a new node with the given data and null to the left and the right pointers. */static TNode newNode(int data){ TNode node = new TNode(); node.data = data; node.left = null; node.right = null; return node;} // This function is used for testing purposestatic void printLevelOrder(TNode root){ if (root == null) return; Queue<TNode > q= new LinkedList<TNode>(); q.add(root); while (q.size()>0) { TNode node = q.element(); System.out.print( node.data + " "); q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); }} /* Driver program totest above functions */public static void main(String args[]){ // Assuming the array is sorted int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.length; /* Convert List to AVL tree */ TNode root = sortedArrayToBST(arr, 0, n - 1); printLevelOrder(root); }}//contributed by Arnab Kundu # Python3 code to print order of# insertion into AVL tree to# ensure no rotations # Tree Nodeclass Node: def __init__(self, d): self.data = d self.left = None self.right = None # Function to convert sorted array# to a balanced AVL Tree/BST# Input : sorted array of integers# Output: root node of balanced AVL Tree/BSTdef sortedArrayToBST(arr): if not arr: return None # Find middle and get its floor value mid = int((len(arr)) / 2) root = Node(arr[mid]) # Recursively construct the left # and right subtree root.left = sortedArrayToBST(arr[:mid]) root.right = sortedArrayToBST(arr[mid + 1:]) # Return the root of the # constructed tree return root # A utility function to print the# Level Order Traversal of AVL Tree# using a Queuedef printLevelOrder(root): if not root: return q = [] q.append(root) # Keep printing the top element and # adding to queue while it is not empty while q != []: node = q.pop(0) print(node.data, end=" ") # If left node exists, enqueue it if node.left: q.append(node.left) # If right node exists, enqueue it if node.right: q.append(node.right) # Driver Codearr = [1, 2, 3, 4, 5, 6, 7]root = sortedArrayToBST(arr)printLevelOrder(root) # This code is contributed# by Adikar Bharath // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ /* A Binary Tree node */public class TNode{ public int data; public TNode left; public TNode right;} /* Function to con AVL treefrom a sorted array */static TNode sortedArrayToBST(int []arr, int start, int end){ /* Base Case */ if (start > end) return null; /* Get the middle element and make it root */ int mid = (start + end) / 2; TNode root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root.left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root.right = sortedArrayToBST(arr, mid + 1, end); return root;} /* Helper function that allocatesa new node with the given dataand null to the left andthe right pointers. */static TNode newNode(int data){ TNode node = new TNode(); node.data = data; node.left = null; node.right = null; return node;} // This function is used for testing purposestatic void printLevelOrder(TNode root){ if (root == null) return; Queue<TNode > q = new Queue<TNode>(); q.Enqueue(root); while (q.Count > 0) { TNode node = q.Peek(); Console.Write( node.data + " "); q.Dequeue(); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); }} /* Driver code */public static void Main(){ // Assuming the array is sorted int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.Length; /* Convert List to AVL tree */ TNode root = sortedArrayToBST(arr, 0, n - 1); printLevelOrder(root);}} /* This code contributed by PrinciRaj1992 */ <script> // Javascript implementation of the approach /* A Binary Tree node */class TNode{ constructor() { this.data = 0; this.left = null; this.right = null; }} /* Function to con AVL treefrom a sorted array */function sortedArrayToBST(arr, start, end){ /* Base Case */ if (start > end) return null; /* Get the middle element and make it root */ var mid = parseInt((start + end) / 2); var root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root.left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root.right = sortedArrayToBST(arr, mid + 1, end); return root;} /* Helper function that allocatesa new node with the given dataand null to the left andthe right pointers. */function newNode(data){ var node = new TNode(); node.data = data; node.left = null; node.right = null; return node;} // This function is used for testing purposefunction printLevelOrder(root){ if (root == null) return; var q = []; q.push(root); while (q.length > 0) { var node = q[0]; document.write( node.data + " "); q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); }} /* Driver code */// Assuming the array is sortedvar arr = [1, 2, 3, 4, 5, 6, 7];var n = arr.length; /* Convert List to AVL tree */var root = sortedArrayToBST(arr, 0, n - 1);printLevelOrder(root); // This code is contributed by itsok. </script> 4 2 6 1 3 5 7 Time Complexity: O(N)Auxiliary Space: O(N) andrew1234 lkcbharath princiraj1992 itsok pankajsharmagfg sagartomar9927 ashutoshsinghgeeksforgeeks AVL-Tree Advanced Data Structure Algorithms Binary Search Tree Binary Search Tree Algorithms AVL-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extendible Hashing (Dynamic approach to DBMS) Ternary Search Tree Proof that Dominant Set of a Graph is NP-Complete 2-3 Trees | (Search, Insert and Deletion) Quad Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS A* Search Algorithm
[ { "code": null, "e": 24095, "s": 24067, "text": "\n26 Oct, 2021" }, { "code": null, "e": 24280, "s": 24095, "text": "Given an array of integers, the task is to find the sequence in which these integers should be added to an AVL tree such that no rotations are required to balance ...
Use aggregate functions on rows in Power BI | by Nikola Ilic | Towards Data Science
Aggregate functions are one of the main building blocks in Power BI. Being used explicitly in measures, or implicitly defined by Power BI, there is no single Power BI report which doesn’t use some sort of aggregate functions. Aggregating means combining values in your data performing some mathematical operation. That can be SUM, AVERAGE, MAXIMUM, MINIMUM, COUNT, COUNT DISTINCT, MEAN, STANDARD DEVIATION, etc. However, in-depth observation of aggregate functions is not in the scope of this article. Here, I wanted to demonstrate how you can use aggregate functions in an unconventional way, since I believe it can be useful in some specific scenarios. By default, aggregations are being calculated on columns. Let’s take a look at following basic example: This is a typical example of SUM aggregate function. Numbers are being aggregated on Year and Month level, and finally, in the end, we can see the total of individual values in the table. We could also perform AVERAGE to find average values, MIN or MAX to find the minimum and maximum values, etc. Pretty straightforward and probably already known for most of the people who ever worked with Power BI or Excel. But, what if we wanted to perform aggregations on rows instead of columns? Is it possible to do that? And if yes, how? Let’s head over to a Power BI and check immediately. I have an Excel file as a data source and a dummy table which contains data about the customer and first date within a single year when he made a purchase: As you can see, some customers made a purchase in every single year, some have gaps, some came in later years, etc. Now, I want to retrieve the earliest date when a customer made a purchase, so I can later perform analysis based on that date (for example, to analyze how many customers made first purchase in February 2017). I know, most of you would probably go with Power Query transformation and Unpivoting years’ columns, something like this: And you get a nice new look of the table, with all dates grouped by customer: However, an additional workload is necessary to build a separate column which will hold data about the earliest date (or MIN date) for every single customer, so we can later use this column for filtering purposes, or even for building a relationship to a date dimension. What if I tell you that you can do this with a single line of code and without any additional transformations? First, I will close the Power Query editor and go straight to the Power BI Data view: You see that this table looks exactly the same as in Excel. Now, I choose to create a new column and, when prompted, enter following DAX code: First Purchase Date = MINX({Sheet2[2016],Sheet2[2017],Sheet2[2018],Sheet2[2019]},[Value]) Let’s stop here for the moment and explain what we are doing. So, we want to extract the minimum date from every single row. We could do that by using multiple nested IF statements and using MIN aggregate function. Since MIN function accepts only two arguments, we would have multiple levels of nested IF statements, which is quite ugly and pretty much hardly readable. The magic here is in the curly brackets! By using them, we are telling DAX that we want it to create a table from the list within the curly brackets, and using MINX iterator aggregate function, we are simply iterating through this table and pulling minimum value from it. How cool and elegant is that! It worked like a charm and here is the resulting column: You can easily spot that DAX returned expected values, so now we can use this column as an axis in our charts, create regular date hierarchies on it, or we can even create a relationship between First Purchase Date and date dimension in our data model if we like to. Power BI and DAX are full of hidden gems. In complete honesty, I have to admit that you might not face a scenario like this every single day, but in some specific situations, it’s good to know that you can perform aggregate functions on row level in a very simple, yet powerful manner — using a literally single line of code! Become a member and read every story on Medium! Subscribe here to get more insightful data articles!
[ { "code": null, "e": 398, "s": 172, "text": "Aggregate functions are one of the main building blocks in Power BI. Being used explicitly in measures, or implicitly defined by Power BI, there is no single Power BI report which doesn’t use some sort of aggregate functions." }, { "code": null, ...
Disable a dropdown item with Bootstrap
To disable to dropdown item in Bootstrap, use the .disabled class with the .dropdown-menu class. You can try to run the following code to disable dropdown item − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Beverages</h2> <p>The following are the beverages available in India:</p> <div class = "dropdown"> <button class = "btn btn-primary dropdown-toggle" type = "button" data-toggle="dropdown">Beverages <span class="caret"></span></button> <ul class = "dropdown-menu"> <li><a href = "#">Gatorade</a></li> <li class = "disabled"><a href = "#">Sting</a></li> <li><a href = "#">Red Bull</a></li> <li><a href = "#">Pepsi</a></li> <li><a href = "#">Coca Cola</a></li> </ul> </div> </div> </body> </html>
[ { "code": null, "e": 1159, "s": 1062, "text": "To disable to dropdown item in Bootstrap, use the .disabled class with the .dropdown-menu class." }, { "code": null, "e": 1224, "s": 1159, "text": "You can try to run the following code to disable dropdown item −" }, { "code"...
Quickly label data in Jupyter Lab | by Dennis Bakhuis | Towards Data Science
Asking a random person what a Data Scientist does, he or she might answer that a Data Scientist provides data-driven solutions using state-of-the-art algorithms. If that random person happens to be (or know) a Data Scientist, he or she will most probably respond with the joke: 80% of the time a Data Scientist is cleaning the data and 20% of the time the Data Scientist complains about having to clean the data. Jokes aside, Data Scientists do spend a lot of time cleaning and tuning datasets, and in general are always on a lookout to improve the process. Especially when a task is a bit less exciting such as labeling. ‘I find the process of data labeling very rewarding (and even addictive). Each time I label an example, I feel like my knowledge, experience, and skill are transferred into the model. I sincerely cannot understand when data scientists complain about being asked to do that.’ — Andriy Burkov For a NLP project we needed a tool for labeling short text into one or more categories. After a short five minutes of ‘lets write it ourselves’, you quickly come to the conclusion that there is probably something already offered in the Python community. Indeed, there are many like Label Studio or Prodi.gy, which are indeed great solutions, but much to general in our taste. Searching a bit longer, we found exactly the tool we had in mind: Pigeon created by Anastasis Germanidis. It was plain simple: in Jupyter you feed a list of text and a list of labels to a function and a widget pops up to walk through each example. The results are given again as a list. The only downside is that it did not support multi-labels yet. The great thing about sharing code on Github is that everybody can fork it and make changes. Unfortunately, Anastasis did not respond to an email to discuss changes and a pull request. Therefore, we decided to publish the changes as PigeonXT, an extended version of Pigeon. PigeonXT currently support the following annotation tasks: binary / multi-class classification multi-label classification regression tasks captioning tasks Anything that can be displayed on Jupyter (text, images, audio, graphs, etc.) can be displayed by pigeon by providing the appropriate display_fn argument. Additionally, custom hooks can be attached to each row update (example_process_fn), or when the annotating task is complete(final_process_fn). As with the original Pigeon, the extended PigeonXT is uploaded to the Python Package Index and can be installed using pip. In this blob post we present a couple of examples. To run these I suggest to first create a new environment. We are managing environment using the Miniconda and the complete procedure is described here. To create a new environment and install the requirements, type the following in a shell: conda create --name pigeon python=3.7conda activate pigeonconda install nodejspip install numpy pandas jupyterlab ipywidgetsjupyter nbextension enable --py widgetsnbextensionjupyter labextension install @jupyter-widgets/jupyterlab-managerpip install pigeonXT-jupyter To start Jupyter Lab, just type the following in the same shell: jupyter lab All examples can also be found in in the notebook on my Github page. Multi-class classification, or binary if only two labels are provided is dead easy: Annotating multiple classes to the same example is called multi-label annotation and is almost identical to the previous example: Classification of any kind of structure which can interact with Jupyter (images, audio, movies) can also be labeled with the same ease: While the custom hooks might again add to much complexity, here is an example for a use-case. When having a DataFrame of 1000 examples to label, it might be to much to do in one go. Not only physically in time, but also to prevent from going crazy of boredom. There, you can write a wrapper around the annotation function to select a portion and save the portion to disk. The next time, it checks for the output, and continuous where you have stopped. This part is written in the wrapper and the final_processing function. As an example for a row-based hook-function, we change the labels to their numerical equivalents and update the DataFrame with each row. You can now see the DataFrame be filled with each step. There are many useful tools for labeling data. Most of the tools I found were very complete but therefore also relatively complex. We were looking for a simple tool which is usable right from Jupyter. Pigeon was already a great tool but we had to add some functionality for our needs. We also enjoyed the small endeavor of creating/changing a new Python package and sharing it with the community. Please let me know if you have any questions or just find it useful.
[ { "code": null, "e": 669, "s": 47, "text": "Asking a random person what a Data Scientist does, he or she might answer that a Data Scientist provides data-driven solutions using state-of-the-art algorithms. If that random person happens to be (or know) a Data Scientist, he or she will most probably r...
C# Class Members (Fields and Methods)
Fields and methods inside classes are often referred to as "Class Members": Create a Car class with three class members: two fields and one method. // The class class MyClass { // Class members string color = "red"; // field int maxSpeed = 200; // field public void fullThrottle() // method { Console.WriteLine("The car is going as fast as it can!"); } } In the previous chapter, you learned that variables inside a class are called fields, and that you can access them by creating an object of the class, and by using the dot syntax (.). The following example will create an object of the Car class, with the name myObj. Then we print the value of the fields color and maxSpeed: class Car { string color = "red"; int maxSpeed = 200; static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); Console.WriteLine(myObj.maxSpeed); } } Try it Yourself » You can also leave the fields blank, and modify them when creating the object: class Car { string color; int maxSpeed; static void Main(string[] args) { Car myObj = new Car(); myObj.color = "red"; myObj.maxSpeed = 200; Console.WriteLine(myObj.color); Console.WriteLine(myObj.maxSpeed); } } Try it Yourself » This is especially useful when creating multiple objects of one class: class Car { string model; string color; int year; static void Main(string[] args) { Car Ford = new Car(); Ford.model = "Mustang"; Ford.color = "red"; Ford.year = 1969; Car Opel = new Car(); Opel.model = "Astra"; Opel.color = "white"; Opel.year = 2005; Console.WriteLine(Ford.model); Console.WriteLine(Opel.model); } } Try it Yourself » You learned from the C# Methods chapter that methods are used to perform certain actions. Methods normally belongs to a class, and they define how an object of a class behaves. Just like with fields, you can access methods with the dot syntax. However, note that the method must be public. And remember that we use the name of the method followed by two parantheses () and a semicolon ; to call (execute) the method: class Car { string color; // field int maxSpeed; // field public void fullThrottle() // method { Console.WriteLine("The car is going as fast as it can!"); } static void Main(string[] args) { Car myObj = new Car(); myObj.fullThrottle(); // Call the method } } Try it Yourself » Why did we declare the method as public, and not static, like in the examples from the C# Methods Chapter? The reason is simple: a static method can be accessed without creating an object of the class, while public methods can only be accessed by objects. Remember from the last chapter, that we can use multiple classes for better organization (one for fields and methods, and another one for execution). This is recommended: class Car { public string model; public string color; public int year; public void fullThrottle() { Console.WriteLine("The car is going as fast as it can!"); } } class Program { static void Main(string[] args) { Car Ford = new Car(); Ford.model = "Mustang"; Ford.color = "red"; Ford.year = 1969; Car Opel = new Car(); Opel.model = "Astra"; Opel.color = "white"; Opel.year = 2005; Console.WriteLine(Ford.model); Console.WriteLine(Opel.model); } } Try it Yourself » The public keyword is called an access modifier, which specifies that the fields of Car are accessible for other classes as well, such as Program. You will learn more about Access Modifiers in a later chapter. Tip: As you continue to read, you will also learn more about other class members, such as constructors and properties. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 76, "s": 0, "text": "Fields and methods inside classes are often referred to as \"Class Members\":" }, { "code": null, "e": 148, "s": 76, "text": "Create a Car class with three class members:\ntwo fields and one method." }, { "code": null, "e": 39...
How to remove a column from matrix in R by using its name?
To remove a column from matrix in R by using its name, we can follow the below steps − First of all, create a matrix First of all, create a matrix Then, add names to columns of the matrix. Then, add names to columns of the matrix. After that, subset the matrix by deselecting the desired column with negation and single square brackets for subsetting. After that, subset the matrix by deselecting the desired column with negation and single square brackets for subsetting. Let’s create a matrix as shown below − M<-matrix(rnorm(75),ncol=3) M On executing, the above script generates the below output(this output will vary on your system due to randomization) − [,1] [,2] [,3] [1,] 0.34927825 0.36395550 -1.4312211 [2,] 0.78629719 -0.45147440 -0.1596172 [3,] 0.88492110 -0.16546013 -1.7026552 [4,] -2.28671282 -1.84818688 1.3984903 [5,] 0.02194021 -0.54682956 -2.5447857 [6,] 1.51718583 -0.34319221 -1.7286530 [7,] -0.04924026 -0.88751938 -0.1783474 [8,] -0.07423773 -0.27037703 0.3952588 [9,] 1.14769892 -1.71712705 0.1677618 [10,] 0.71949312 -0.73954427 0.4089844 [11,] -0.33954351 -0.01039998 0.6405262 [12,] 0.11824754 2.27291701 0.2234398 [13,] 0.37339259 -0.50529084 1.0764492 [14,] 0.05557717 -0.61960682 0.4721451 [15,] 1.87575124 1.66763649 0.8596300 [16,] -0.57575272 -0.44936940 0.6154190 [17,] 0.85030730 -1.21989570 1.5136665 [18,] 1.19599580 0.33216810 -0.3205572 [19,] 0.64010472 -0.26696943 1.3040537 [20,] 0.74811799 0.65594635 -1.2104943 [21,] -0.27932027 -1.41589620 -0.1530550 [22,] -0.37549109 -1.08739383 0.7536317 [23,] 0.07836645 1.14317049 -1.1269287 [24,] 0.44175649 0.21147460 -1.3777469 [25,] 1.11577514 0.28621068 0.0819287 Add the column names Using colnames function to add the column names to matrix M − M<-matrix(rnorm(75),ncol=3) colnames(M)<-c("First","Second","Third") M First Second Third [1,] -0.63798951 -0.08312581 -0.29548313 [2,] 0.81035121 0.32946453 0.26934501 [3,] 1.17310898 -0.16824116 1.44146054 [4,] -1.46085561 -1.01480047 0.48119221 [5,] -0.60117020 -0.71335771 0.56736308 [6,] 1.39032577 0.45488133 1.12518802 [7,] 1.24992297 -0.79274785 0.88435795 [8,] -0.46766814 -0.61113426 0.87081178 [9,] -0.50900441 0.32142161 0.06270336 [10,] 0.53407605 0.75097220 0.62138186 [11,] -0.31153258 -0.19474785 1.31048238 [12,] -0.90701432 0.25399274 -0.51568591 [13,] 0.48485802 -0.19454370 -0.84981770 [14,] 0.22094696 -1.04421982 -1.08446966 [15,] 0.28317116 -0.07426917 0.41447679 [16,] 0.60986979 2.20385278 1.02703888 [17,] -1.03122232 -0.26323809 -0.22929783 [18,] -1.39070018 3.28175028 0.31980456 [19,] 0.20176785 1.64951864 -0.51179577 [20,] -0.46897146 1.16688302 -1.76417685 [21,] 0.43936821 -0.70327534 0.05285094 [22,] -0.69668353 0.65657864 0.04483215 [23,] 0.05226474 0.14180989 1.31808786 [24,] 0.16654568 0.74867083 1.16400816 [25,] -1.16417323 -0.42192382 0.87543185 Remove the column from matrix using column name Subset the matrix by deselecting the Second column with negation and single square brackets as shown below − M<-matrix(rnorm(75),ncol=3) colnames(M)<-c("First","Second","Third") M<M[,colnames(M)!="Second"] M First Third [1,] 0.34927825 -1.4312211 [2,] 0.78629719 -0.1596172 [3,] 0.88492110 -1.7026552 [4,] -2.28671282 1.3984903 [5,] 0.02194021 -2.5447857 [6,] 1.51718583 -1.7286530 [7,] -0.04924026 -0.1783474 [8,] -0.07423773 0.3952588 [9,] 1.14769892 0.1677618 [10,] 0.71949312 0.4089844 [11,] -0.33954351 0.6405262 [12,] 0.11824754 0.2234398 [13,] 0.37339259 1.0764492 [14,] 0.05557717 0.4721451 [15,] 1.87575124 0.8596300 [16,] -0.57575272 0.6154190 [17,] 0.85030730 1.5136665 [18,] 1.19599580 -0.3205572 [19,] 0.64010472 1.3040537 [20,] 0.74811799 -1.2104943 [21,] -0.27932027 -0.1530550 [22,] -0.37549109 0.7536317 [23,] 0.07836645 -1.1269287 [24,] 0.44175649 -1.3777469 [25,] 1.11577514 0.0819287
[ { "code": null, "e": 1149, "s": 1062, "text": "To remove a column from matrix in R by using its name, we can follow the below steps −" }, { "code": null, "e": 1179, "s": 1149, "text": "First of all, create a matrix" }, { "code": null, "e": 1209, "s": 1179, "te...
Array of list in C++ with Examples - GeeksforGeeks
24 Jan, 2022 What is an array? An array in any programming language is a data structure that is used to store elements or data items of similar data types at contiguous memory locations and elements can be accessed randomly using indices of an array. Arrays are efficient when we want to store a large number of elements that too of similar data types. What is a list? In C++, a list is a sequence container that allows non-contiguous memory allocation. If we compare a vector with a list, then a list has slow traversal as compared to a vector but once a position has been found, insertion and deletion are quick. Generally, a list in C++ is a doubly-linked list. Functions used with List: front(): Returns the value of the first element in the list. back(): Returns the value of the last element in the list. push_front(x): Adds a new element ‘x’ at the beginning of the list. push_back(x): Adds a new element ‘x’ at the end of the list. pop_front(): Removes the first element of the list, and reduces the size of the list by 1. pop_back(): Removes the last element of the list, and reduces the size of the list by 1. Array of lists C++ allows us a facility to create an array of lists. An array of lists is an array in which each element is a list on its own. Syntax: list<dataType> myContainer[N]; Here,N: The size of the array of the lists.dataType: A dataType. It signifies that each list can store elements of this data type only. Example 1: Below is the C++ program to implement an array of lists. C++ // C++ program to demonstrate the// working of array of lists in C++#include <bits/stdc++.h>using namespace std; // Function to print list elements// specified at the index, "index"void print(list<int>& mylist, int index){ cout << "The list elements stored at the index " << index << ": \n"; // Each element of the list is a pair on // its own for (auto element : mylist) { // Each element of the list is a pair // on its own cout << element << '\n'; } cout << '\n';} // Function to iterate over all the arrayvoid print(list<int>* myContainer, int n){ cout << "myContainer elements:\n\n"; // Iterating over myContainer elements // Each element is a list on its own for (int i = 0; i < n; i++) { print(myContainer[i], i); }} // Driver codeint main(){ // Declaring an array of lists // In list each element is of type int list<int> myContainer[3]; // listing values to the list stored // at the index 0 // 15 <-> 5 <-> 10 <-> 20 myContainer[0].push_front(5); myContainer[0].push_back(10); myContainer[0].push_front(15); myContainer[0].push_back(20); // listing values to the list stored // at the index 1 // 40 <-> 30 <-> 35 <-> 45 myContainer[1].push_front(30); myContainer[1].push_back(35); myContainer[1].push_front(40); myContainer[1].push_back(45); // listing values to the list stored // at the index 2 // 60 <-> 50 <-> 55 <-> 65 myContainer[2].push_front(50); myContainer[2].push_back(55); myContainer[2].push_front(60); myContainer[2].push_back(65); // Calling print function to iterate // over myContainer elements print(myContainer, 3); return 0;} myContainer elements: The list elements stored at the index 0:1551020 The list elements stored at the index 1:40303545 The list elements stored at the index 2:60505565 Example 2: Below is the C++ program to implement an array of lists. C++ // C++ program to demonstrate the// working of array of lists in C++#include <bits/stdc++.h>using namespace std; // Function to print list elements// specified at the index, "index"void print(list<string>& mylist, int index){ cout << "The list elements stored at the index " << index << ": \n"; // Each element of the list is a pair // on its own for (auto element : mylist) { // Each element of the list is a pair // on its own cout << element << '\n'; } cout << '\n';} // Function to iterate over all the arrayvoid print(list<string>* myContainer, int n){ cout << "myContainer elements:\n\n"; // Iterating over myContainer elements // Each element is a list on its own for (int i = 0; i < n; i++) { print(myContainer[i], i); }} // Driver codeint main(){ // Declaring an array of lists // In list each element is of type string list<string> myContainer[3]; // listing values to the list stored // at the index 0 // "GeeksforGeeks" <-> "C++" <-> // "Python" <-> "C" myContainer[0].push_front("C++"); myContainer[0].push_back("Python"); myContainer[0].push_front("GeeksforGeeks"); myContainer[0].push_back("C"); // listing values to the list stored // at the index 1 // "Nainwal" <-> "Java" <-> "C#" <-> "GFG" myContainer[1].push_front("Java"); myContainer[1].push_back("C#"); myContainer[1].push_front("Nainwal"); myContainer[1].push_back("GFG"); // listing values to the list stored // at the index 2 // "HTML" <-> "Swift" <-> "R" <-> "CSS" myContainer[2].push_front("Swift"); myContainer[2].push_back("R"); myContainer[2].push_front("HTML"); myContainer[2].push_back("CSS"); // Calling print function to iterate // over myContainer elements print(myContainer, 3); return 0;} myContainer elements: The list elements stored at the index 0:GeeksforGeeksC++PythonC The list elements stored at the index 1:NainwalJavaC#GFG The list elements stored at the index 2:HTMLSwiftRCSS simmytarika5 Arrays cpp-array cpp-list STL Arrays C++ Arrays STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Move all negative numbers to beginning and positive to end with constant extra space Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) Multidimensional Arrays in C / C++
[ { "code": null, "e": 24741, "s": 24713, "text": "\n24 Jan, 2022" }, { "code": null, "e": 24759, "s": 24741, "text": "What is an array?" }, { "code": null, "e": 25081, "s": 24759, "text": "An array in any programming language is a data structure that is used to...
Android | What is Toast and How to use it with Examples - GeeksforGeeks
01 May, 2019 Pre-requisites: Android App Development Fundamentals for Beginners Guide to Install and Set up Android Studio Android | Starting with first app/android project Android | Running your first Android app This article aims to tell What is Toast and How to use it to display messages in an android app. A Toast is a feedback message. It takes a very little space for displaying while overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If user wants permanent visible message, Notification can be used. Another type of Toast is custom Toast, in which images can be used instead of a simple message. Example: Toast class: Toast class provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity). Constants of Toast class Methods of Toast class In this example “This a simple toast message” is a Toast message which is displayed by clicking on ‘CLICK’ button. Every time when you click your toast message appears. Steps to create an Android Application with Toast Message: Step 1: Create an XML file and a Java File. Please refer the pre-requisites to learn more about this step. Step 2: Open “activity_main.xml” file and add a Button to show Toast message in a Constraint Layout.Also, Assign ID to button component as shown in the image and the code below. The assigned ID to the button helps to identify and to use in Java files.android:id="@+id/id_name"Here the given ID is Button01This will make the UI of the Application. Also, Assign ID to button component as shown in the image and the code below. The assigned ID to the button helps to identify and to use in Java files. android:id="@+id/id_name" Here the given ID is Button01 This will make the UI of the Application. Step 3: Now, after the UI, this step will create the Backend of the App. For this, Open “MainActivity.java” file and instantiate the component (Button) created in the XML file using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.General Syntax:ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);Syntax for used component (Click Button):Button btn = (Button)findViewById(R.id.Button01); ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent); Syntax for used component (Click Button): Button btn = (Button)findViewById(R.id.Button01); Step 4: This step involves setting up the operations to display the Toast Message. These operations are as follows:Add the listener on Button and this Button will show a toast message.btn.setOnClickListener(new View.OnClickListener() {});Now, Create a toast message. The Toast.makeText() method is a pre-defined method which creates a Toast object.Syntax:public static Toast makeText (Context context, CharSequence text, int duration) Parameters: This method accepts three parameters:context: The first parameter is a Context object which is obtained by calling getApplicationContext(). Context context = getApplicationContext(); text: The second parameter is your text message to be displayed.CharSequence text=”Your text message here”duration: The last parameter is the time duration for the message.int duration=Toast.LENGTH_LONG;Therefore the code to make a Toast message is:Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG); Display the created Toast Message using the show() method of the Toast class.Syntax:public void show ()The code to show the Toast message:Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG) .show(); Add the listener on Button and this Button will show a toast message.btn.setOnClickListener(new View.OnClickListener() {});Now, Create a toast message. The Toast.makeText() method is a pre-defined method which creates a Toast object.Syntax:public static Toast makeText (Context context, CharSequence text, int duration) Parameters: This method accepts three parameters:context: The first parameter is a Context object which is obtained by calling getApplicationContext(). Context context = getApplicationContext(); text: The second parameter is your text message to be displayed.CharSequence text=”Your text message here”duration: The last parameter is the time duration for the message.int duration=Toast.LENGTH_LONG;Therefore the code to make a Toast message is:Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG); Display the created Toast Message using the show() method of the Toast class.Syntax:public void show ()The code to show the Toast message:Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG) .show(); Add the listener on Button and this Button will show a toast message.btn.setOnClickListener(new View.OnClickListener() {}); btn.setOnClickListener(new View.OnClickListener() {}); Now, Create a toast message. The Toast.makeText() method is a pre-defined method which creates a Toast object.Syntax:public static Toast makeText (Context context, CharSequence text, int duration) Parameters: This method accepts three parameters:context: The first parameter is a Context object which is obtained by calling getApplicationContext(). Context context = getApplicationContext(); text: The second parameter is your text message to be displayed.CharSequence text=”Your text message here”duration: The last parameter is the time duration for the message.int duration=Toast.LENGTH_LONG;Therefore the code to make a Toast message is:Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG); Syntax: public static Toast makeText (Context context, CharSequence text, int duration) Parameters: This method accepts three parameters: context: The first parameter is a Context object which is obtained by calling getApplicationContext(). Context context = getApplicationContext(); Context context = getApplicationContext(); text: The second parameter is your text message to be displayed.CharSequence text=”Your text message here” CharSequence text=”Your text message here” duration: The last parameter is the time duration for the message.int duration=Toast.LENGTH_LONG; int duration=Toast.LENGTH_LONG; Therefore the code to make a Toast message is: Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG); Display the created Toast Message using the show() method of the Toast class.Syntax:public void show ()The code to show the Toast message:Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG) .show(); Syntax: public void show () The code to show the Toast message: Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG) .show(); Step 5: Now Run the app and operate as follows:When the app is opened, it displays a “Click” button.Click the Click button.Then “This a toast message” will be displayed on the screen as a Toast Message. When the app is opened, it displays a “Click” button. Click the Click button. Then “This a toast message” will be displayed on the screen as a Toast Message. Complete Code to display a simple Toast Message: activity_main.xml MainActivity.java <?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- add button for generating Toast message --> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="209dp" android:onClick="onClick" android:text="Click" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="OnClick" /> </android.support.constraint.ConstraintLayout> package org.geeksforgeeks.simpleToast_Example; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Defining the object for button Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Bind the components to their respective objects // by assigning their IDs // with the help of findViewById() method Button btn = (Button)findViewById(R.id.Button01); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Displaying simple Toast message Toast.makeText(getApplicationContext(), "This a toast message", Toast.LENGTH_LONG) .show(); } }); }} Output: If there is a need to set position of a Toast message, then setGravity() method can be used. public void setGravity (int gravity, int xOffset, int yOffset) Parameters: This method accepts three parameters: gravity: This sets the position of the Toast message. Following constants can be used to specify the position of a Toast:1.TOP 2.BOTTOM 3.LEFT 4.RIGHT 5.CENTER 6.CENTER_HORIZONTAL 7.CENTER_VERTICAL Every constant specifies the position in X and Y axis, except CENTER constant which sets position centered for both horizontal and vertical direction. 1.TOP 2.BOTTOM 3.LEFT 4.RIGHT 5.CENTER 6.CENTER_HORIZONTAL 7.CENTER_VERTICAL Every constant specifies the position in X and Y axis, except CENTER constant which sets position centered for both horizontal and vertical direction. xOffset: This is the offset value that tells how much to shift the Toast message horizontally on the x axis. yOffset: This is the offset value that tells how much to shift the Toast message vertically on the y axis. For example: 1. To display the Toast at the center: toast.setGravity(Gravity.CENTER, 0, 0); 2. To display the Toast at the top, centered horizontally: toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 0); 3. To display the Toast at the top, centered horizontally, but 30 pixels down from the top: toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 30); 4. To display the Toast at the bottom, rightmost horizontally: toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); Example: Here, in the below example, the Toast is displayed at the Bottom-Right position. Syntax: Toast t = Toast.makeText(getApplicationContext(), "This a positioned toast message", Toast.LENGTH_LONG); t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); t.show(); Complete Code: activity_main.xml MainActivity.java <?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- add a button to display positioned toast message --> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="209dp" android:onClick="onClick" android:text="Click" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="OnClick" /> </android.support.constraint.ConstraintLayout> package org.geeksforgeeks.positionedToast_Example; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Defining the object for button Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Binding the components to their respective objects // by assigning their IDs // with the help of findViewById() method Button btn = (Button)findViewById(R.id.Button01); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Displaying posotioned Toast message Toast t = Toast.makeText(getApplicationContext(), "This a positioned toast message", Toast.LENGTH_LONG); t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); t.show(); } }); }} android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 26347, "s": 26319, "text": "\n01 May, 2019" }, { "code": null, "e": 26363, "s": 26347, "text": "Pre-requisites:" }, { "code": null, "e": 26414, "s": 26363, "text": "Android App Development Fundamentals for Beginners" }, { "code": n...
Lodash _.range() Method - GeeksforGeeks
09 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.range() method is used to create an array of numbers progressing from the given start value up to, but not including the end value. A step of -1 is used if a negative value of start is specified without an end or step. If the end is not specified, it’s set to start with the start then set to 0. Syntax: _.range( start, end, step ) Parameters: This method accepts three parameters as mentioned above and described below: start: It is a number that specifies the start of the range. It is an optional value. The default value is 0. end: It is a number that specifies the end of the range. step: It is a number that specifies the amount that the value in the range is incremented or decremented. The default value is 1. Return Value: It returns an array with the given range of numbers. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // Using the _.range() method let range_arr = _.range(5); // Printing the output console.log(range_arr); Output: [0, 1, 2, 3, 4] Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Using the _.range() method// with the step taken as 2let range_arr = _.range(0,10,2); // Printing the output console.log(range_arr); Output: [0, 2, 4, 6, 8] Example 3: Javascript // Requiring the lodash library const _ = require("lodash"); // Using the _.range() method// with the step taken as -2let range_arr = _.range(-1,-11,-2); // Printing the output console.log(range_arr); Output: [-1, -3, -5, -7, -9] JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to detect browser or tab closing in JavaScript ? How to get character array from string in JavaScript? How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25220, "s": 25192, "text": "\n09 Sep, 2020" }, { "code": null, "e": 25360, "s": 25220, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": n...
How to assign an id to a child tag of the cloned html ? - GeeksforGeeks
14 Dec, 2021 Here we use in basic HTML, CSS, JavaScript, jQuery and Bootstrap to build this small example project. jQuery is the open-source library which simplifies create and navigation of web application. We are going to use three jQuery methods such as clone(), append() and attr() method for solving this example. clone() method make a copy of select element attr() method for change the name of attribute like id, class etc append() method is for append the last child of each element in the jQuery collection Here we are going to clone the bootstrap card which has an id named as ‘cloneme’ and having child tags such as ‘<b>’, ‘<button>’,'<p>’ tag. Steps:- When the user presses the ‘click me’ button in the UI section of the web page, then it’s going to run on click listener callback.Inside this callback function, we simply make a copy of HTML tag with id ‘cloneme’. You can also take HTML tag with attribute class.After cloning the Html code, we are going to change the ID of child tag of <b> and <button> tag by finding the tag using its attribute name such as id, class.After finding the tag using its attribute name, then we are going change its attribute name by jQuery attr() method.Attach the clone HTML code to the destination. When the user presses the ‘click me’ button in the UI section of the web page, then it’s going to run on click listener callback. Inside this callback function, we simply make a copy of HTML tag with id ‘cloneme’. You can also take HTML tag with attribute class. After cloning the Html code, we are going to change the ID of child tag of <b> and <button> tag by finding the tag using its attribute name such as id, class. After finding the tag using its attribute name, then we are going change its attribute name by jQuery attr() method. Attach the clone HTML code to the destination. HTML <!DOCTYPE html><html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>geeksforgeeks</title></head> <body> <h1 style="margin-top:10px;color:green;text-align:center;"> GeeksForGeeks </h1> <button type="button" class="btn btn-success" id="clickme" style="display: block; margin-left: auto; margin-right: auto; justify-content: center;">Click Me</button> <hr style="color:green; border: 2px solid"> <div id="cloneme" style="margin-left:10px;display:none; margin-top:10px;"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20210117221201/download9.png" alt="GeeksForGeeks"> <div class="card-body"> <p class="card-text" style="text-align:center;"> <b id="setID">My Id is 0</b></p> <p> GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> <button type="button" id="cancel" class="btn btn-success" style="justify-content:center;margin-left:auto; margin-right:auto;"> Cancel </button> </div> </div> </div> <div id="bucket" class="container-fluid"> <div> <script src="script.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> let c = 0 function IDgenerate() { return c++ } $("#clickme").on("click", function() { var cn = IDgenerate(); //clone the html code let clone = $("#cloneme").clone() //change the css of parent clone.css("display", "inline-block") //change the id attribute of child tag '<b>' clone.find('#setID').attr("id", cn) //change the text inside the child tag '<b>' clone.find("#" + cn).text("My ID is " + cn) //change the id attribute of child tag '<button>' clone.find("#cancel").attr("id", "cancel" + cn) //add on click listener to the cancel button clone.find("#cancel" + cn).on("click", function() { clone.css("display", "none") }) // append the clone to the destination $("#bucket").append(clone) }) </script></body> </html> Working model of the project varshagumber28 jQuery-Questions Picked Technical Scripter 2020 JQuery Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? jQuery | parent() & parents() with Examples jQuery | attr() Method Difference Between JavaScript and jQuery jQuery | focus() with Examples How to submit a form using ajax in jQuery ?
[ { "code": null, "e": 26954, "s": 26926, "text": "\n14 Dec, 2021" }, { "code": null, "e": 27260, "s": 26954, "text": "Here we use in basic HTML, CSS, JavaScript, jQuery and Bootstrap to build this small example project. jQuery is the open-source library which simplifies create and...
jQuery | blur() with Examples - GeeksforGeeks
12 Feb, 2019 The blur() is an inbuilt method is jQuery that is used to remove focus from the selected element. This method start the blur event or it can be attached a function to run when a blur event occurs.Syntax: $(selector).blur(function) Parameter: It accepts an optional parameter “function”.Return Value: It does not return anything, it simply trigger the blur event on the selected element. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function() { $("input").blur(); $("p").html("This is blur method that is used!!!"); }); }); </script></head> <body> <!--enter value and click on the button --> Enter Value: <input type="text"> <br> <br> <button id="btn">start blur event!!!</button> <p style="color:green"></p></body> </html> Output:Before entering any value to the “Enter Value” box-After entering a value of “GeeksforGeeks” to the “Enter Value” box-After clicking the “start blur event” button- Code #2:In the below code, function is passed to the blur method. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> <!-- jQuery code to show blur method --> $(document).ready(function() { $("input").blur(function() { $(this).css("background-color", "#ADFF2F"); }); }); </script></head> <body> <!-- Enter a value to the field and click outside to see the change --> Enter Value: <input type="text" name="fullname"></body> </html> Output:Before entering any value to the “Enter Value” box- After entering a value of “GeeksforGeeks” to the “Enter Value” box- After clicking the mouse button anywhere on the screen- jQuery-Events JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 42078, "s": 42050, "text": "\n12 Feb, 2019" }, { "code": null, "e": 42282, "s": 42078, "text": "The blur() is an inbuilt method is jQuery that is used to remove focus from the selected element. This method start the blur event or it can be attached a function...
Groovy - split()
Splits this String around matches of the given regular expression. String[] split(String regex) regex - the delimiting regular expression. It returns the array of strings computed by splitting this string around matches of the given regular expression. Following is an example of the usage of this method − class Example { static void main(String[] args) { String a = "Hello-World"; String[] str; str = a.split('-'); for( String values : str ) println(values); } } When we run the above program, we will get the following result − Hello World 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2305, "s": 2238, "text": "Splits this String around matches of the given regular expression." }, { "code": null, "e": 2335, "s": 2305, "text": "String[] split(String regex)\n" }, { "code": null, "e": 2378, "s": 2335, "text": "regex - the d...
Erdos Renyl Model (for generating Random Graphs) - GeeksforGeeks
24 Nov, 2021 In graph theory, the Erdos–Rényi model is either of two closely related models for generating random graphs. There are two closely related variants of the Erdos–Rényi (ER) random graph model. In the G(n, M) model, a graph is chosen uniformly at random from the collection of all graphs which have n nodes and M edges. For example, in the G(3, 2) model, each of the three possible graphs on three vertices and two edges are included with probability 1/3.In the G(n, p) model, a graph is constructed by connecting nodes randomly. Each edge is included in the graph with probability p independent from every other edge. Equivalently, all graphs with n nodes and M edges have equal probability of A graph generated by the binomial model of Erdos and Rényi (p = 0.01) The parameter p in this model can be thought of as a weighting function; as p increases from 0 to 1, the model becomes more and more likely to include graphs with more edges and less and less likely to include graphs with fewer edges. In particular, the case p = 0.5 corresponds to the case where all graphs on n vertices are chosen with equal probability.The article will basically deal with the G (n,p) model where n is the no of nodes to be created and p defines the probability of joining of each node to the other. Properties of G(n, p)With the notation above, a graph in G(n, p) has on average edges. The distribution of the degree of any particular vertex is binomial: Where n is the total number of vertices in the graph. Since as and np= constant This distribution is Poisson for large n and np = const. In a 1960 paper, Erdos and Rényi described the behaviour of G(n, p) very precisely for various values of p. Their results included that: If np < 1, then a graph in G(n, p) will almost surely have no connected components of size larger than O(log(n)). If np = 1, then a graph in G(n, p) will almost surely have a largest component whose size is of order . If np c > 1, where c is a constant, then a graph in G(n, p) will almost surely have a unique giant component containing a positive fraction of the vertices. No other component will contain more than O(log(n)) vertices. If , then a graph in G(n, p) will almost surely contain isolated vertices, and thus be disconnected. If , then a graph in G(n, p) will almost surely be connected.Thus is a sharp threshold for the connectedness of G(n, p).Further properties of the graph can be described almost precisely as n tends to infinity. For example, there is a k(n) (approximately equal to 2log2(n)) such that the largest clique in G(n, 0.5) has almost surely either size k(n) or k(n) + 1.Thus, even though finding the size of the largest clique in a graph is NP-complete, the size of the largest clique in a “typical” graph (according to this model) is very well understood. Interestingly, edge-dual graphs of Erdos-Renyi graphs are graphs with nearly the same degree distribution, but with degree correlations and a significantly higher clustering coefficient.Next I’ll describe the code to be used for making the ER graph. For implementation of the code below, you’ll need to install the netwrokx library as well you’ll need to install the matplotlib library. Following you’ll see the exact code of the graph which has been used as a function of the networkx library lately in this article.Erdos_renyi_graph(n, p, seed=None, directed=False)Returns a G(n,p) random graph, also known as an Erd?s-Rényi graph or a binomial graph.The G(n,p) model chooses each of the possible edges with probability p.The functions binomial_graph() and erdos_renyi_graph() are aliases of this function.Parameters: n (int) – The number of nodes.p (float) – Probability for edge creation.seed (int, optional) – Seed for random number generator (default=None).directed (bool, optional (default=False)) – If True, this function returns a directed graph.#importing the networkx library>>> import networkx as nx #importing the matplotlib library for plotting the graph>>> import matplotlib.pyplot as plt >>> G= nx.erdos_renyi_graph(50,0.5)>>> nx.draw(G, with_labels=True)>>> plt.show()Figure 1: For n=50, p=0.5The above example is for 50 nodes and is thus a bit unclear.When considering the case for lesser no of nodes (for example 10), you can clearly see the difference.Using the codes for various probabilities, we can see the difference easily:>>> I= nx.erdos_renyi_graph(10,0)>>> nx.draw(I, with_labels=True)>>> plt.show()Figure 2: For n=10, p=0>>> K=nx.erdos_renyi_graph(10,0.25)>>> nx.draw(K, with_labels=True)>>> plt.show()Figure 3: For n=10, p=0.25>>>H= nx.erdos_renyi_graph(10,0.5)>>> nx.draw(H, with_labels=True)>>> plt.show()Figure 4: For n=10, p=0.5This algorithm runs in O() time. For sparse graphs (that is, for small values of p), fast_gnp_random_graph() is a faster algorithm.Thus the above examples clearly define the use of erdos renyi model to make random graphs and how to use the foresaid using the networkx library of python.Next we will discuss the ego graph and various other types of graphs in python using the library networkx.ReferencesYou can read more about the same at Thus is a sharp threshold for the connectedness of G(n, p).Further properties of the graph can be described almost precisely as n tends to infinity. For example, there is a k(n) (approximately equal to 2log2(n)) such that the largest clique in G(n, 0.5) has almost surely either size k(n) or k(n) + 1.Thus, even though finding the size of the largest clique in a graph is NP-complete, the size of the largest clique in a “typical” graph (according to this model) is very well understood. Interestingly, edge-dual graphs of Erdos-Renyi graphs are graphs with nearly the same degree distribution, but with degree correlations and a significantly higher clustering coefficient. Next I’ll describe the code to be used for making the ER graph. For implementation of the code below, you’ll need to install the netwrokx library as well you’ll need to install the matplotlib library. Following you’ll see the exact code of the graph which has been used as a function of the networkx library lately in this article. Erdos_renyi_graph(n, p, seed=None, directed=False) Returns a G(n,p) random graph, also known as an Erd?s-Rényi graph or a binomial graph.The G(n,p) model chooses each of the possible edges with probability p.The functions binomial_graph() and erdos_renyi_graph() are aliases of this function. Parameters: n (int) – The number of nodes.p (float) – Probability for edge creation.seed (int, optional) – Seed for random number generator (default=None).directed (bool, optional (default=False)) – If True, this function returns a directed graph. #importing the networkx library>>> import networkx as nx #importing the matplotlib library for plotting the graph>>> import matplotlib.pyplot as plt >>> G= nx.erdos_renyi_graph(50,0.5)>>> nx.draw(G, with_labels=True)>>> plt.show() Figure 1: For n=50, p=0.5 The above example is for 50 nodes and is thus a bit unclear.When considering the case for lesser no of nodes (for example 10), you can clearly see the difference.Using the codes for various probabilities, we can see the difference easily: >>> I= nx.erdos_renyi_graph(10,0)>>> nx.draw(I, with_labels=True)>>> plt.show() Figure 2: For n=10, p=0 >>> K=nx.erdos_renyi_graph(10,0.25)>>> nx.draw(K, with_labels=True)>>> plt.show() Figure 3: For n=10, p=0.25 >>>H= nx.erdos_renyi_graph(10,0.5)>>> nx.draw(H, with_labels=True)>>> plt.show() Figure 4: For n=10, p=0.5 This algorithm runs in O() time. For sparse graphs (that is, for small values of p), fast_gnp_random_graph() is a faster algorithm.Thus the above examples clearly define the use of erdos renyi model to make random graphs and how to use the foresaid using the networkx library of python.Next we will discuss the ego graph and various other types of graphs in python using the library networkx. ReferencesYou can read more about the same at https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model http://networkx.readthedocs.io/en/networkx-1.10/index.html.This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave . This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Graph Mathematical Mathematical Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24930, "s": 24902, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25040, "s": 24930, "text": "In graph theory, the Erdos–Rényi model is either of two closely related models for generating random graphs." }, { "code": null, "e": 25124, "s": ...
Area of largest Circle that can be inscribed in a SemiCircle - GeeksforGeeks
10 Feb, 2022 Given a semicircle with radius R, the task is to find the area of the largest circle that can be inscribed in the semicircle.Examples: Input: R = 2 Output: 3.14 Input: R = 8 Output: 50.24 Approach: Let R be the radius of the semicircle For Largest circle that can be inscribed in this semicircle, the diameter of the circle must be equal to the radius of the semi-circle. So, if the radius of the semi-circle is R, then the diameter of the largest inscribed circle will be R.Hence the radius of the inscribed circle must be R/2Therefore the area of the largest circle will be For Largest circle that can be inscribed in this semicircle, the diameter of the circle must be equal to the radius of the semi-circle. So, if the radius of the semi-circle is R, then the diameter of the largest inscribed circle will be R. Hence the radius of the inscribed circle must be R/2 Therefore the area of the largest circle will be Area of circle = pi*Radius2 = pi*(R/2)2 since the radius of largest circle is R/2 where R is the radius of the semicircle Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to find the biggest circle// which can be inscribed within the semicircle #include <bits/stdc++.h>using namespace std; // Function to find the area// of the circlefloat circlearea(float R){ // Radius cannot be negative if (R < 0) return -1; // Area of the largest circle float a = 3.14 * R * R / 4; return a;} // Driver codeint main(){ float R = 2; cout << circlearea(R) << endl; return 0;} // Java Program to find the biggest circle// which can be inscribed within the semicircleclass GFG{ // Function to find the area // of the circle static float circlearea(float R) { // Radius cannot be negative if (R < 0) return -1; // Area of the largest circle float a = (float)((3.14 * R * R) / 4); return a; } // Driver code public static void main (String[] args) { float R = 2; System.out.println(circlearea(R)); }} // This code is contributed by AnkitRai01 # Python3 Program to find the biggest circle# which can be inscribed within the semicircle # Function to find the area# of the circledef circlearea(R) : # Radius cannot be negative if (R < 0) : return -1; # Area of the largest circle a = (3.14 * R * R) / 4; return a; # Driver codeif __name__ == "__main__" : R = 2; print(circlearea(R)) ; # This code is contributed by AnkitRai01 // C# Program to find the biggest circle// which can be inscribed within the semicircleusing System; class GFG{ // Function to find the area // of the circle static float circlearea(float R) { // Radius cannot be negative if (R < 0) return -1; // Area of the largest circle float a = (float)((3.14 * R * R) / 4); return a; } // Driver code public static void Main (string[] args) { float R = 2; Console.WriteLine(circlearea(R)); }} // This code is contributed by AnkitRai01 <script> // Javascript Program to find the biggest circle// which can be inscribed within the semicircle // Function to find the area// of the circlefunction circlearea(R){ // Radius cannot be negative if (R < 0) return -1; // Area of the largest circle var a = 3.14 * R * R / 4; return a;} // Driver codevar R = 2;document.write(circlearea(R)); // This code is contributed by rutvik_56.</script> 3.14 ankthon rutvik_56 sagar0719kumar Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Equation of circle when three points on the circle are given Program to find slope of a line Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26671, "s": 26643, "text": "\n10 Feb, 2022" }, { "code": null, "e": 26808, "s": 26671, "text": "Given a semicircle with radius R, the task is to find the area of the largest circle that can be inscribed in the semicircle.Examples: " }, { "code": null...
Node.js vs Java - GeeksforGeeks
08 Jun, 2021 Node.js: Node.js a library that is used to create runtime applications. It was initially written by Rayn Dahl for using the JavaScript outside the browser and later on it was managed by Joyent. Node.js is used for both front-end and back-end and developers can build mobile applications as well. With its capabilities, It can handle the server-side, a user can request a packet and at the same time, it can access the database. JavaScript has plenty of frameworks that are based on Express.js and Node.js. But when depending on the type of application these frameworks are decided to be used. This is an advantage of node.js that it can connect to devices using APIs and can connect to libraries written in other languages too.Example: Printing ‘Welcome to GeeksforGeeks’ in Node.js. javascript // Syntax to printconsole.log("Welcome to GeeksforGeeks"); Java: Java was developed at Sun Microsystems by James Gosling and later on, Oracle took it over. Java is an object-oriented language whose most of its syntax is derived from C++ and its concepts remain the same with some modifications. Whole Java comes in a bundle with JDK called Java Development Kit, and it is enough for a java program to be get run. The code written in Java is converted into byte code which can be run on any machine irrespective of the operating system that has Java and this one of the biggest advantages of this language. Java has a huge community, and it supports networking and GUI. Many games are built on Java and are used extensively. Several frameworks are built on Java for web development, for Server-sideexample Spring.Example: Printing ‘Welcome to GeeksforGeeks’ in Java. Java // Syntax to printSystem.out.println("Welcome to GeeksforGeeks"); Difference between Node.js and Java: divyak roneetmichael Node.js-Misc Difference Between Java JavaScript Node.js Web Technologies Java 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 25243, "s": 25215, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26029, "s": 25243, "text": "Node.js: Node.js a library that is used to create runtime applications. It was initially written by Rayn Dahl for using the JavaScript outside the browser and late...
Find rows which are not in other dataframe in R - GeeksforGeeks
07 Apr, 2021 To find rows present in one dataframe that are not present in the other is known as set-difference. In this article, we will see different ways to do the same. In this method simply the sql query to find set-difference is passed Syntax: sqldf(“sql query”) Our query will be sqldf(‘SELECT * FROM df1 EXCEPT SELECT * FROM df2’). It will exclude all the rows from df1 that are also present in df2 and will return only rows that are only present in df1. Example 1: R require(sqldf)df1 <- data.frame(a = 1:5, b=letters[1:5])df2 <- data.frame(a = 1:3, b=letters[1:3]) print("df1 is ")print(df1) print("df2 is ")print(df2) res <- sqldf('SELECT * FROM df1 EXCEPT SELECT * FROM df2')print("rows from df1 which are not in df2")print(res) Example 2: R require(sqldf)df1 <- data.frame(name = c("kapil","sachin","rahul"), age=c(23,22,26))df2 <- data.frame(name = c("kapil"), age = c(23)) print("df1 is ")print(df1) print("df2 is ")print(df2) res <- sqldf('SELECT * FROM df1 EXCEPT SELECT * FROM a2')print("rows from df1 which are not in df2")print(res) This is an R built-in function to find the set difference of two dataframes. Syntax: setdiff(df1,df2) It will return rows in df1 that are not present in df2. Example 1: R df1 <- data.frame(a = 1:5, b=letters[1:5], c= c(1,3,5,7,9))df2 <- data.frame(a = 1:5, b=letters[1:5], c = c(2,4,6,8,10)) print("df1 is ")print(df1) print("df2 is ")print(df2) res <-setdiff(df1, df2)print("rows from df1 which are not in df2")print(res) Output: Example 2: R df1 <- data.frame(name = c("kapil","sachin","rahul"), age=c(23,22,26))df2 <- data.frame(name = c("kapil","rahul", "sachin"), age = c(23, 22, 26)) print("df1 is ")print(df1) print("df2 is ")print(df2) res <- setdiff(df1, df2)print("rows from df1 which are not in df2")print(res) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25322, "s": 25162, "text": "To find rows present in one dataframe that are not present in the other is known as set-difference. In this article, we will see different ways to do the same." ...
Deploy TensorFlow models | Towards Data Science
Learn how to deploy your model to production Updated to tensorflow 1.7 Okay, you have a model and you want to make it accessible from the web. There are several ways you can do that, but the faster and the most robust is TensorFlow serving. How it works? Basically TensorFlow serving creates a gRPC server where you can send and get a response from your model. You don’t really know the magic behind it to be a wizard. These are the steps we are going to do: Make a stupid model as an example, train and store it Fetch the variables you need from your stored model Build the tensor info from them Create the model signature Create and save a model builder Download a Docker image with TensorFlow serving already compile on it Run the docker image with the correct configuration Create a client in order to send the gRPC request Make an API Test it Code can be found here. We just need a model to play with. Below there is a very basic model that just take as input and target two random arrays. import tensorflow as tfimport numpy as npimport os, sysDATA_SIZE = 100SAVE_PATH = './save'EPOCHS = 1000LEARNING_RATE = 0.01MODEL_NAME = 'test'if not os.path.exists(SAVE_PATH): os.mkdir(SAVE_PATH)data = (np.random.rand(DATA_SIZE, 2), np.random.rand(DATA_SIZE, 1))test = (np.random.rand(DATA_SIZE // 8, 2), np.random.rand(DATA_SIZE // 8, 1))tf.reset_default_graph()x = tf.placeholder(tf.float32, shape=[None, 2], name='inputs')y = tf.placeholder(tf.float32, shape=[None, 1], name='targets')net = tf.layers.dense(x, 16, activation=tf.nn.relu)net = tf.layers.dense(net, 16, activation=tf.nn.relu)pred = tf.layers.dense(net, 1, activation=tf.nn.sigmoid, name='prediction')loss = tf.reduce_mean(tf.squared_difference(y, pred), name='loss')train_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(loss)checkpoint = tf.train.latest_checkpoint(SAVE_PATH)should_train = checkpoint == Nonewith tf.Session() as sess: sess.run(tf.global_variables_initializer()) if should_train: print("Training") saver = tf.train.Saver() for epoch in range(EPOCHS): _, curr_loss = sess.run([train_step, loss], feed_dict={x: data[0], y: data[1]}) print('EPOCH = {}, LOSS = {:0.4f}'.format(epoch, curr_loss)) path = saver.save(sess, SAVE_PATH + '/' + MODEL_NAME + '.ckpt') print("saved at {}".format(path)) else: print("Restoring") graph = tf.get_default_graph() saver = tf.train.import_meta_graph(checkpoint + '.meta') saver.restore(sess, checkpoint) loss = graph.get_tensor_by_name('loss:0') test_loss = sess.run(loss, feed_dict={'inputs:0': test[0], 'targets:0': test[1]}) print(sess.run(pred, feed_dict={'inputs:0': np.random.rand(10,2)})) print("TEST LOSS = {:0.4f}".format(test_loss)) Remember: If you use tf.layers.dense the actual output is called with the name that you provide + the function name (lol) x = tf.placeholder(tf.float32, shape=[None, 2], name='inputs')...pred = tf.layers.dense(net, 1, activation=tf.nn.sigmoid, name='prediction') If you run the code it will create the ./save folder if it does not exist or it will just evaluate the model on the test set if there is already one stored instance. # training the model...EPOCH = 997, LOSS = 0.0493EPOCH = 998, LOSS = 0.0495EPOCH = 999, LOSS = 0.0497saved at ./save/test.ckpt If we run the script again we see RestoringTEST LOSS = 0.0710 Perfect! Now we have our saved model Let’s create a file called serve.py that will handle the logic behind serving our TF model. The first thing to do is to get the variables we need from the stored graph. import tensorflow as tfimport osSAVE_PATH = './save'MODEL_NAME = 'test'VERSION = 1SERVE_PATH = './serve/{}/{}'.format(MODEL_NAME, VERSION)checkpoint = tf.train.latest_checkpoint(SAVE_PATH)tf.reset_default_graph()with tf.Session() as sess: # import the saved graph saver = tf.train.import_meta_graph(checkpoint + '.meta') # get the graph for this session graph = tf.get_default_graph() sess.run(tf.global_variables_initializer()) # get the tensors that we need inputs = graph.get_tensor_by_name('inputs:0') predictions = graph.get_tensor_by_name('prediction/Sigmoid:0') Now we have our variables inputs and predictions . We need to build the tensor info from them that will be used to create the signature definition that will be passed to the SavedModelBuilder instance. Very easily # create tensors infomodel_input = tf.saved_model.utils.build_tensor_info(inputs)model_output = tf.saved_model.utils.build_tensor_info(predictions) Now we can finally create the model signature that identifies what the serving is going to expect from the client. In our case # build signature definitionsignature_definition = tf.saved_model.signature_def_utils.build_signature_def( inputs={'inputs': model_input}, outputs={'outputs': model_output}, method_name= tf.saved_model.signature_constants.PREDICT_METHOD_NAME) Here we are calling a utils function from TF that takes the inputs and outputs and the method_name . The last one is just a constant that says what is going to do, in our case we want to PREDICT, they are defined as: Create a SavedModelBuilder instance and pass all the information we need. builder = tf.saved_model.builder.SavedModelBuilder(SERVE_PATH)builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_definition })# Save the model so we can serve it with a model server :)builder.save() In add_meta_graph_and_variables we pass the current session, an array of tags that I have no idea of why we need them, the SERVING constant and the signature_def_map. Again, for the last one, I have no idea of why we need it but basically we are passing a dictionary where we tell that for the DEFAULT_SERVING_SIGNATURE_DEF_KEY we have that signature definition ( the one defined before in “Create the model signature” section). The full script is here. Run the script and it creates the serve dir: First of all, install docker. Don’t follow the TensorFlow docs since they explain how to setup a docker image and compile TF serving that takes forever. Now the doc is broken, check here: https://github.com/tensorflow/tensorflow/issues/19006 Some guy made a docker image with everything already compile on it, so we are going to use that one. The image link: https://hub.docker.com/r/epigramai/model-server/ Run this command with the correct params docker run -it -p <PORT>:<PORT> — name <CONTAINER_NAME> -v <ABSOLUTE_PATH_TO_SERVE_DIR>:<SERVE_DIR> epigramai/model-server:light-universal-1.7 — port=<PORT> — model_name=<MODEL_NAME> — model_base_path=<MODEL_DIR> In our case docker run -it -p 9000:9000 --name tf-serve -v $(pwd)/serve/:/serve/ epigramai/model-server:light-universal-1.7 --port=9000 --model_name=test --model_base_path=/serve/test If every works, you should see something like this: How to do that? Well again, the doc is not really good. So we will use a library that will make things easier. Run this command to install it using pip , in my case I am using python3 pip3 install git+ssh://git@github.com/epigramai/tfserving-python-predict-client.git Let’s create a new file called client.py import numpy as npfrom predict_client.prod_client import ProdClientHOST = '0.0.0.0:9000'# a good idea is to place this global variables in a shared fileMODEL_NAME = 'test'MODEL_VERSION = 1client = ProdClient(HOST, MODEL_NAME, MODEL_VERSION)req_data = [{'in_tensor_name': 'inputs', 'in_tensor_dtype': 'DT_FLOAT', 'data': np.random.rand(1,2)}]prediction = client.predict(req_data, request_timeout=10)print(prediction) Before run it, be sure you have started the docker container. After lunch the script you should see something like this: {'outputs': array([[ 0.53334153]])} A dictionary with outputs as key and the correct prediction as value It’s time to finally make our model accesible from the web. We will use Flask to create the HTTP server. Let’s refactor our client.py The client must accept a HTTP call, convert the response data to a numpy array, call the model and return a JSON containing the prediction. Below the final code. import numpy as npfrom predict_client.prod_client import ProdClientfrom flask import Flaskfrom flask import requestfrom flask import jsonifyHOST = 'localhost:9000'MODEL_NAME = 'test'MODEL_VERSION = 1app = Flask(__name__)client = ProdClient(HOST, MODEL_NAME, MODEL_VERSION)def convert_data(raw_data): return np.array(raw_data, dtype=np.float32)def get_prediction_from_model(data): req_data = [{'in_tensor_name': 'inputs', 'in_tensor_dtype': 'DT_FLOAT', 'data': data}] prediction = client.predict(req_data, request_timeout=10) return prediction@app.route("/prediction", methods=['POST'])def get_prediction(): req_data = request.get_json() raw_data = req_data['data'] data = convert_data(raw_data) prediction = get_prediction_from_model(data) # ndarray cannot be converted to JSON return jsonify({ 'predictions': prediction['outputs'].tolist() })if __name__ == '__main__': app.run(host='localhost',port=3000) Finally! Me made it! Its time to try it out, open your favore HTTP client, in my case postman, and try to send a JSON with data as key and a vector as value using a POST request to localhost:3000/prediction After send it we have the response Perfect! It works. The final code can be found here We have seen the best way to serve a TensorFlow model and make it accessible through HTTP request using Flask. Maybe you can also find worth reading this my other articles: https://towardsdatascience.com/reinforcement-learning-cheat-sheet-2f9453df7651 https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428 Thank you for reading,
[ { "code": null, "e": 217, "s": 172, "text": "Learn how to deploy your model to production" }, { "code": null, "e": 243, "s": 217, "text": "Updated to tensorflow 1.7" }, { "code": null, "e": 413, "s": 243, "text": "Okay, you have a model and you want to make it...
Create Reproducible Data Science and Machine Learning Environments using Conda | by Elizabeth Ter Sahakyan | Towards Data Science
Data science and machine learning projects have dependencies that we rely on to make our code run, like pandas or numpy. These dependencies get updated over time and have different versions which can cause code to break if the wrong version is used. If you work with other team members, you also need to maintain the same local development environment on different computers for the code to run successfully. To create reproducible environments for projects, it’s good practice to use an environment manager that keeps track of all the dependencies — like Conda. Conda is an open source package management system and environment management system that runs on Windows, macOS and Linux. Conda quickly installs, runs and updates packages and their dependencies. Conda easily creates, saves, loads and switches between environments on your local computer. It was created for Python programs, but it can package and distribute software for any language. - Anaconda Documentation This article will help you develop a better workflow for managing your environments using Conda. Feel free to skip over any of the sections and jump to the code you need! Installing Anaconda Creating and activating a Conda environment Installing and uninstalling dependencies Exporting a Conda environment Using Conda with JupyterLab Deactivating or deleting a Conda environment Summary of commands Example workflow for reproducible environments If you don’t already have Anaconda installed, follow the instructions here to install it for your operating system. You should see Anaconda-Navigator in your applications once it’s installed. You can either create a brand new Conda environment for when you’re starting a new project or recreate an existing environment from a yaml file. To create a new Conda environment, open up your terminal and type the following command: conda create -n datasci-env You will see the following prompt asking you to proceed. Type y to continue creating the environment. If you have an existing file containing project dependencies, you can recreate the environment by running the following: conda env create -f environment.yaml In this case, the first line of the yaml file will set the name of the environment. The name of an environment created with the following yaml file will be called datasci-env. Once your environment is created, you can activate it using: conda activate datasci-env You can distinguish whether an environment is activated or not by looking at the left hand side of your terminal. You should see it change from base to datasci-env like below: We can check the version of python in our newly created Conda environment with the following command: python --versionOR python3 --version Note: By default macOS Catalina has python as Python 2, so in order to run anything in Python 3 you must use python3 This is what you’ll see when running those commands in your terminal: This means this conda environment we just created is running version Python 3.7.3. If this is the python version you want, you can skip over the next section and move on to installing dependencies. If you need a different version of python for your environment you will need to specify the version at the time of installation. First, let’s deactivate the environment we just created: conda deactivate If we want to create a Python 3.5 environment for example, we can run the following command: conda create -n datasci-env-py35 python=3.5 Below I’m confirming that conda installed the proper version of python by activating the environment and running python3 --version. You can list all available environments using: conda env list First, make sure the correct environment is activated (it should appear in parentheses or brackets on the left side of your terminal). Installing dependencies in the wrong place can cause problems if you’re working on multiple projects, so it’s important to make sure you’re in the correct environment. Now you should be able to install your dependencies using conda install. Let’s try it with some popular data science libraries: conda install pandas matplotlib numpy scikit-learn You’ll receive another prompt asking you to proceed and after typing y you should see all of the packages install successfully. If you need to install a specific version of a package, you can just name the version when installing: conda install pandas=0.25.1 This command above also works to downgrade libraries and packages after you’ve installed them. If you want to uninstall a package, you can use the following: conda uninstall PACKAGE_NAME You can check all packages and versions in your current environment using conda list which will display the following: Notes:- If the conda install command doesn’t work for the library you’re trying to install you can try googling how to install that specific one.- Be careful of upgrading your python version when installing dependencies. You can see above that the installation upgraded my python version to 3.8.2. Now that we have an environment with a few dependencies installed, we can export them for versioning and reproducibility. Ideally, you’ll be exporting these files to your project directory and pushing them to github to have a proper record of the version history. You can either export a txt or yaml file depending on your needs. First make sure you have the conda environment activated and that you’re in the correct project directory in your terminal. To export the dependencies to a txt file, run the following: # with condaconda list --export > requirements.txt# with pippip freeze > requirements.txt To export the dependencies to a yaml file, run the following: conda env export > environment.yaml# OR if you run into issues, try --no-buildsconda env export --no-builds > environment.yaml After running any of these commands, you should see a new file appear in your project’s directory containing all of the dependencies. You should push this file to github so that your teammates or yourself at a later date can access and recreate the exact project environment. If you’re working with a team, you might want to update the environment on your end at some point if others make changes by installing new dependencies. You can update an existing conda environment from a yaml file using: conda env update --file environment.yaml If you want to use conda environments inside JupyterLab, you’ll need to create a specific kernel for that environment. First install jupyterlab andipykernel inside your environment, then create a new kernel: conda install -c conda-forge jupyterlab ipykernelipython kernel install --user --name=datasci-env Note: the name of the kernel can be different from the environment but you should keep them the same so you can remember which kernel is linked to which environment. Now you should be able to launch JupyterLab from your terminal using the following command: jupyter lab And once JupyterLab is launched you can open up a new or existing notebook, click the kernels on the top right corner, and select your new kernel from the dropdown. If you don’t see the kernel, try restarting Jupyter. If you want to list the kernels you have available in terminal: jupyter kernelspec list When you’re done using a conda environment, you can deactivate it in your terminal with the following command: conda deactivate Your terminal should now show (base) as the environment on the left: If you’re done with a project and no longer need an environment, you can remove it using the following command: conda env remove -n datasci-env # create new environmentconda create -n ENV_NAME# create new environment with different version of pythonconda create -n ENV_NAME python=VERSION# create environment from existing environment.yamlconda env create -f environment.yaml# update existing environment from environment.yamlconda env update --file environment.yaml# activate environmentconda activate ENV_NAME# deactivate environmentconda deactivate# delete/remove environmentconda env remove -n ENV_NAME# list all environmentsconda env list# export requirements.txt with condaconda list --export > requirements.txt# export requirements.txt with pippip freeze > requirements.txt# export environment.yamlconda env export > environment.yaml# export environment.yaml with no buildsconda env export --no-builds > environment.yaml# install dependenciesconda install PACKAGE_NAMEORconda install -c conda-forge PACKAGE_NAME# install dependencies with a specific versionconda install PACKAGE_NAME=VERSION# uninstall dependenciesconda uninstall PACKAGE_NAME# list all dependenciesconda list# create ipython kernel (for jupyter and jupyterlab)conda install -c conda-forge jupyterlab ipykernelipython kernel install --user --name=KERNEL_NAME# list all ipython kernelsjupyter kernelspec list# uninstall/remove existing ipython kerneljupyter kernelspec uninstall KERNEL_NAME Create new Github repo for projectClone repo locally using git clonecd into project directoryCreate a new Conda envActivate envInstall dependenciesWork on project in Jupyter or other IDE(optional) if working in Jupyter create kernel from envExport conda env to yaml or txt fileSave codeCreate .gitignore to avoid files you don’t want to add to gitAdd files to git using git add .Push environment file and code to Github Create new Github repo for project Clone repo locally using git clone cd into project directory Create a new Conda env Activate env Install dependencies Work on project in Jupyter or other IDE (optional) if working in Jupyter create kernel from env Export conda env to yaml or txt file Save code Create .gitignore to avoid files you don’t want to add to git Add files to git using git add . Push environment file and code to Github To reproduce environment: Clone repo on a different computerCreate environment from yaml or txt file (don’t have to use Conda)Run code Clone repo on a different computer Create environment from yaml or txt file (don’t have to use Conda) Run code Note: If you plan on deploying your project you will probably want to maintain a separate deployment environment that contains only the dependencies needed for the deployed aspects. You should now be able to create, activate, and install dependencies into conda environments to create reproducible data science and machine learning environments. Feel free to connect with me on twitter @elizabethets or LinkedIn!
[ { "code": null, "e": 735, "s": 172, "text": "Data science and machine learning projects have dependencies that we rely on to make our code run, like pandas or numpy. These dependencies get updated over time and have different versions which can cause code to break if the wrong version is used. If yo...
Apache Solr - Core
A Solr Core is a running instance of a Lucene index that contains all the Solr configuration files required to use it. We need to create a Solr Core to perform operations like indexing and analyzing. A Solr application may contain one or multiple cores. If necessary, two cores in a Solr application can communicate with each other. After installing and starting Solr, you can connect to the client (web interface) of Solr. As highlighted in the following screenshot, initially there are no cores in Apache Solr. Now, we will see how to create a core in Solr. One way to create a core is to create a schema-less core using the create command, as shown below − [Hadoop@localhost bin]$ ./Solr create -c Solr_sample Here, we are trying to create a core named Solr_sample in Apache Solr. This command creates a core displaying the following message. Copying configuration to new core instance directory: /home/Hadoop/Solr/server/Solr/Solr_sample Creating new core 'Solr_sample' using command: http://localhost:8983/Solr/admin/cores?action=CREATE&name=Solr_sample&instanceD ir = Solr_sample { "responseHeader":{ "status":0, "QTime":11550 }, "core":"Solr_sample" } You can create multiple cores in Solr. On the left-hand side of the Solr Admin, you can see a core selector where you can select the newly created core, as shown in the following screenshot. Alternatively, you can create a core using the create_core command. This command has the following options − Let’s see how you can use the create_core command. Here, we will try to create a core named my_core. [Hadoop@localhost bin]$ ./Solr create_core -c my_core On executing, the above command creates a core displaying the following message − Copying configuration to new core instance directory: /home/Hadoop/Solr/server/Solr/my_core Creating new core 'my_core' using command: http://localhost:8983/Solr/admin/cores?action=CREATE&name=my_core&instanceD ir = my_core { "responseHeader":{ "status":0, "QTime":1346 }, "core":"my_core" } You can delete a core using the delete command of Apache Solr. Let’s suppose we have a core named my_core in Solr, as shown in the following screenshot. You can delete this core using the delete command by passing the name of the core to this command as follows − [Hadoop@localhost bin]$ ./Solr delete -c my_core On executing the above command, the specified core will be deleted displaying the following message. Deleting core 'my_core' using command: http://localhost:8983/Solr/admin/cores?action=UNLOAD&core = my_core&deleteIndex = true&deleteDataDir = true&deleteInstanceDir = true { "responseHeader" :{ "status":0, "QTime":170 } } You can open the web interface of Solr to verify whether the core has been deleted or not. 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
[ { "code": null, "e": 2224, "s": 2024, "text": "A Solr Core is a running instance of a Lucene index that contains all the Solr configuration files required to use it. We need to create a Solr Core to perform operations like indexing and analyzing." }, { "code": null, "e": 2357, "s": 2...
How to use Selenium webdriver to click google search?
We can click on Google search with Selenium webdriver. First of all we need to identify the search edit box with help of any of the locators like id, class,name, xpath or css. Then we will input some text with the sendKeys() method. Next we have to identify the search button with help of any of the locators like id, class, name, xpath or css and finally apply click() method on it or directly apply submit() method. We will wait for the search results to appear with presenceOfElementLocatedexpected condition. We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class. This concept comes from the explicit wait condition in synchronization. Let us try to implement the below scenario. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; public class SearchAction{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.google.com/"); // identify element WebElement p=driver.findElement(By.name("q")); //enter text with sendKeys() then apply submit() p.sendKeys("Selenium Java"); // Explicit wait condition for search results WebDriverWait w = new WebDriverWait(driver, 5); w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//ul"))); p.submit(); driver.close(); } }
[ { "code": null, "e": 1238, "s": 1062, "text": "We can click on Google search with Selenium webdriver. First of all we need to identify the search edit box with help of any of the locators like id, class,name, xpath or css." }, { "code": null, "e": 1575, "s": 1238, "text": "Then w...
Methods vs. Functions in C++ with Examples - GeeksforGeeks
01 Jun, 2020 A method is a procedure or function in OOPs Concepts. Whereas, a function is a group of reusable code which can be used anywhere in the program. This helps the need for writing the same code again and again. It helps programmers in writing modular codes. Methods: A method also works the same as that of function.A method is defined inside a class. For Example: main() in JavaA method can be private, public, or protected.The method is invoked by its reference/object only. For Example: If class has obj as an object name, then the method is called by:obj.method(); A method is able to operate on data that is contained within the classEach object has it’s own method which is present in the class. A method also works the same as that of function. A method is defined inside a class. For Example: main() in Java A method can be private, public, or protected. The method is invoked by its reference/object only. For Example: If class has obj as an object name, then the method is called by:obj.method(); obj.method(); A method is able to operate on data that is contained within the class Each object has it’s own method which is present in the class. Functions: A function is a block of statements that takes specific input, does some computations, and finally produces the output.A function is defined independently. For Example: main() in C++By default a function is public.It can be accessed anywhere in the entire program.It is called by its name itself.It has the ability to return values if needed.If a function is defined, it will be the same for every object that has been created. A function is a block of statements that takes specific input, does some computations, and finally produces the output. A function is defined independently. For Example: main() in C++ By default a function is public. It can be accessed anywhere in the entire program. It is called by its name itself. It has the ability to return values if needed. If a function is defined, it will be the same for every object that has been created. Below is the program to illustrate functions and methods in C++: Program 1: // C++ program to illustrate functions#include "bits/stdc++.h"using namespace std; // Function Call to print array elementsvoid printElement(int arr[], int N){ // Traverse the array arr[] for (int i = 0; i < N; i++) { cout << arr[i] << ' '; }} // Driver Codeint main(){ // Given array int arr[] = { 13, 15, 66, 66, 37, 8, 8, 11, 52 }; // length of the given array arr[] int N = sizeof(arr) / sizeof(arr[0]); // Function Call printElement(arr, N); return 0;} 13 15 66 66 37 8 8 11 52 Program 2: // C++ program to illustrate methods// in class#include "bits/stdc++.h"using namespace std; // Class GfGclass GfG {private: string str = "Welcome to GfG!"; public: // Method to access the private // member of class void printString() { // Print string str cout << str << '\n'; }}; // Driver Codeint main(){ // Create object of class GfG GfG g; // Accessing private member of // class GfG using public methods g.printString(); return 0;} Welcome to GfG! Program 3: // C++ program to illustrate methods// and functions#include <iostream>using namespace std; // Function call to return stringstring offering(bool a){ if (a) { return "Apple."; } else { return "Chocolate."; }} // Class Declarationclass GFG {public: // Method for class GFG void guest(bool op) { if (op == true) { cout << "Yes, I want fruit!\n"; } else { cout << "No, Thanks!\n"; } }}; // Driver Codeint main(){ bool n = true; cout << "Will you eat fruit? "; // Create an object of class GFG GFG obj; // Method invoking using an object obj.guest(n); if (n == true) { // Append fruit using function // calling cout << "Give an " + offering(n); } // Giving fruit..Function calling else { // Append fruit using function // calling cout << "Give a " + offering(n); } return 0;} Will you eat fruit? Yes, I want fruit! Give an Apple. CPP-Functions C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ Convert string to char array in C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 24123, "s": 24095, "text": "\n01 Jun, 2020" }, { "code": null, "e": 24378, "s": 24123, "text": "A method is a procedure or function in OOPs Concepts. Whereas, a function is a group of reusable code which can be used anywhere in the program. This helps the nee...
How to reduce a matrix in R to echelon form?
The echelon form of a matrix is the matrix that has the following characteristics: 1. The first non-zero element in each row, called the leading entry, is 1. 2. Each leading entry is in a column to the right of the leading entry in the previous row. 3. Rows with all zero elements, if any, are below rows having a non-zero element. In R, we can use echelon function of matlib package to find the echelon form of the matrix. Live Demo > M<-matrix(rpois(25,10),ncol=5) > M [,1] [,2] [,3] [,4] [,5] [1,] 8 11 3 10 13 [2,] 9 9 7 15 11 [3,] 10 13 10 14 13 [4,] 7 11 11 12 17 [5,] 13 10 9 20 13 Live Demo > V<-rpois(5,2) > V [1] 4 2 4 1 2 Loading matlib package and finding the echelon form of matrix M: > library(matlib) > echelon(M,V,verbose=TRUE,fractions=TRUE) Initial matrix: [,1] [,2] [,3] [,4] [,5] [,6] [1,] 8 11 3 10 13 4 [2,] 9 9 7 15 11 2 [3,] 10 13 10 14 13 4 [4,] 7 11 11 12 17 1 [5,] 13 10 9 20 13 2 row: 1 exchange rows 1 and 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 13 10 9 20 13 2 [2,] 9 9 7 15 11 2 [3,] 10 13 10 14 13 4 [4,] 7 11 11 12 17 1 [5,] 8 11 3 10 13 4 multiply row 1 by 1/13 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 9 9 7 15 11 2 [3,] 10 13 10 14 13 4 [4,] 7 11 11 12 17 1 [5,] 8 11 3 10 13 4 multiply row 1 by 9 and subtract from row 2 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 0 27/13 10/13 15/13 2 8/13 [3,] 10 13 10 14 13 4 [4,] 7 11 11 12 17 1 [5,] 8 11 3 10 13 4 multiply row 1 by 10 and subtract from row 3 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 0 27/13 10/13 15/13 2 8/13 [3,] 0 69/13 40/13 -18/13 3 32/13 [4,] 7 11 11 12 17 1 [5,] 8 11 3 10 13 4 multiply row 1 by 7 and subtract from row 4 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 0 27/13 10/13 15/13 2 8/13 [3,] 0 69/13 40/13 -18/13 3 32/13 [4,] 0 73/13 80/13 16/13 10 -1/13 [5,] 8 11 3 10 13 4 multiply row 1 by 8 and subtract from row 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 0 27/13 10/13 15/13 2 8/13 [3,] 0 69/13 40/13 -18/13 3 32/13 [4,] 0 73/13 80/13 16/13 10 -1/13 [5,] 0 63/13 -33/13 -30/13 5 36/13 row: 2 exchange rows 2 and 4 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 0 73/13 80/13 16/13 10 -1/13 [3,] 0 69/13 40/13 -18/13 3 32/13 [4,] 0 27/13 10/13 15/13 2 8/13 [5,] 0 63/13 -33/13 -30/13 5 36/13 multiply row 2 by 13/73 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 10/13 9/13 20/13 1 2/13 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 69/13 40/13 -18/13 3 32/13 [4,] 0 27/13 10/13 15/13 2 8/13 [5,] 0 63/13 -33/13 -30/13 5 36/13 multiply row 2 by 10/13 and subtract from row 1 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 -11/73 100/73 -27/73 12/73 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 69/13 40/13 -18/13 3 32/13 [4,] 0 27/13 10/13 15/13 2 8/13 [5,] 0 63/13 -33/13 -30/13 5 36/13 multiply row 2 by 69/13 and subtract from row 3 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 -11/73 100/73 -27/73 12/73 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 0 -200/73 -186/73 -471/73 185/73 [4,] 0 27/13 10/13 15/13 2 8/13 [5,] 0 63/13 -33/13 -30/13 5 36/13 multiply row 2 by 27/13 and subtract from row 4 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 -11/73 100/73 -27/73 12/73 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 0 -200/73 -186/73 -471/73 185/73 [4,] 0 0 -110/73 51/73 -124/73 47/73 [5,] 0 63/13 -33/13 -30/13 5 36/13 multiply row 2 by 63/13 and subtract from row 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 -11/73 100/73 -27/73 12/73 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 0 -200/73 -186/73 -471/73 185/73 [4,] 0 0 -110/73 51/73 -124/73 47/73 [5,] 0 0 -573/73 -246/73 -265/73 207/73 row: 3 exchange rows 3 and 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 -11/73 100/73 -27/73 12/73 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 0 -573/73 -246/73 -265/73 207/73 [4,] 0 0 -110/73 51/73 -124/73 47/73 [5,] 0 0 -200/73 -186/73 -471/73 185/73 multiply row 3 by -73/573 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 -11/73 100/73 -27/73 12/73 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 -110/73 51/73 -124/73 47/73 [5,] 0 0 -200/73 -186/73 -471/73 185/73 multiply row 3 by 11/73 and add to row 1 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 274/191 -172/573 21/191 [2,] 0 1 80/73 16/73 130/73 -1/73 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 -110/73 51/73 -124/73 47/73 [5,] 0 0 -200/73 -186/73 -471/73 185/73 multiply row 3 by 80/73 and subtract from row 2 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 274/191 -172/573 21/191 [2,] 0 1 0 -48/191 730/573 73/191 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 -110/73 51/73 -124/73 47/73 [5,] 0 0 -200/73 -186/73 -471/73 185/73 multiply row 3 by 110/73 and add to row 4 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 274/191 -172/573 21/191 [2,] 0 1 0 -48/191 730/573 73/191 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 0 257/191 -574/573 19/191 [5,] 0 0 -200/73 -186/73 -471/73 185/73 multiply row 3 by 200/73 and add to row 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 274/191 -172/573 21/191 [2,] 0 1 0 -48/191 730/573 73/191 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 0 257/191 -574/573 19/191 [5,] 0 0 0 -262/191 -2971/573 295/191 row: 4 exchange rows 4 and 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 274/191 -172/573 21/191 [2,] 0 1 0 -48/191 730/573 73/191 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 0 -262/191 -2971/573 295/191 [5,] 0 0 0 257/191 -574/573 19/191 multiply row 4 by -191/262 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 274/191 -172/573 21/191 [2,] 0 1 0 -48/191 730/573 73/191 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 257/191 -574/573 19/191 multiply row 4 by 274/191 and subtract from row 1 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 -2249/393 226/131 [2,] 0 1 0 -48/191 730/573 73/191 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 257/191 -574/573 19/191 multiply row 4 by 48/191 and add to row 2 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 -2249/393 226/131 [2,] 0 1 0 0 874/393 13/131 [3,] 0 0 1 82/191 265/573 -69/191 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 257/191 -574/573 19/191 multiply row 4 by 82/191 and subtract from row 3 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 -2249/393 226/131 [2,] 0 1 0 0 874/393 13/131 [3,] 0 0 1 0 -152/131 16/131 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 257/191 -574/573 19/191 multiply row 4 by 257/191 and subtract from row 5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 -2249/393 226/131 [2,] 0 1 0 0 874/393 13/131 [3,] 0 0 1 0 -152/131 16/131 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 0 -1595/262 423/262 row: 5 multiply row 5 by -262/1595 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 -2249/393 226/131 [2,] 0 1 0 0 874/393 13/131 [3,] 0 0 1 0 -152/131 16/131 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 0 1 -266/1003 multiply row 5 by 2249/393 and add to row 1 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 0 331/1595 [2,] 0 1 0 0 874/393 13/131 [3,] 0 0 1 0 -152/131 16/131 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 0 1 -266/1003 multiply row 5 by 874/393 and subtract from row 2 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 0 331/1595 [2,] 0 1 0 0 0 1099/1595 [3,] 0 0 1 0 -152/131 16/131 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 0 1 -266/1003 multiply row 5 by 152/131 and add to row 3 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 0 331/1595 [2,] 0 1 0 0 0 1099/1595 [3,] 0 0 1 0 0 -296/1595 [4,] 0 0 0 1 2971/786 -295/262 [5,] 0 0 0 0 1 -266/1003 multiply row 5 by 2971/786 and subtract from row 4 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 0 331/1595 [2,] 0 1 0 0 0 1099/1595 [3,] 0 0 1 0 0 -296/1595 [4,] 0 0 0 1 0 -197/1595 [5,] 0 0 0 0 1 -266/1003
[ { "code": null, "e": 1145, "s": 1062, "text": "The echelon form of a matrix is the matrix that has the following characteristics:" }, { "code": null, "e": 1220, "s": 1145, "text": "1. The first non-zero element in each row, called the leading entry, is 1." }, { "code": nu...
Visualising the World’s Carbon Dioxide Emissions with Python | by Adam Symington | Towards Data Science
For some reason, climate change has been in the news a lot recently. Specifically the link between carbon dioxide emissions from our cars, factories, ships, planes (to name a few) and the warming of our planet via the greenhouse effect. The image above shows the world’s short cycle carbon dioxide emissions in 2018. Aside from looking fantastic and almost artistic, it provides useful context for where the world’s emissions are actually coming from. The map clearly shows the world’s emissions are dominated by North America, Europe, China and India. Zooming in on different areas reveal loads of interesting features, in North America and Europe there are bright areas on highlighting major cities, all linked with bright areas corresponding to the main roads. At sea, the major shipping lanes can be picked out, e.g. China — Singapore — Malacca Strait — Suez Canal stands out as a particularly bright line. There are also a series of curved lines corresponding to the major air routes, in particular leading between North America and Europe. Population density can be used to explain a lot of this map however there are some notable exceptions. For example, parts of South America are brighter than expected and West Africa is perhaps a bit dimmer than expected. In contrast, the Nile, where 95% of Egypt's population lives, is lit up like a Christmas tree. With that said it is important to note that these maps are purely qualitative and not quantitative so it is important to be careful about what conclusions are drawn from them. So how do we go about plotting the map? The first step is to fetch the data. The data is available from the EDGARv6.0 website (link) under the citation Crippa et al. (2021) (link) and is available for download and use as long as the appropriate citations are used. There are a number of datasets that you can choose from and I will explore some of these in future articles. In this article we will look at short cycle carbon dioxide emissions from 2018 (sadly 2018 is the most recent dataset). An important thing to note is that this dataset includes emissions from all fossil carbon dioxide sources, such as fossil fuel combustion, non-metallic mineral processes (e.g. cement production), metal (ferrous and non-ferrous) production processes, urea production, agricultural liming and solvents use. Large scale biomass burning with Savannah burning, forest fires, and sources and sinks from land-use, land-use change and forestry (LULUCF) are excluded. A full description of their methods can be found here. So download the data and store it wherever you like to execute you code. I have read the data into a pandas.DataFrame and printed the resulting DataFrame to see what we are dealing with. The data is very simple and consists of an emission value in units of tonnes per year for a particular latitude / longitude pair. import pandas as pd co2 = pd.read_csv("v50_CO2_excl_short-cycle_org_C_2018.txt", delimiter=';') print(co2) lat lon emission 0 88.1 -50.7 11.0301 1 88.1 -50.6 15.7066 2 88.1 -50.5 19.1943 3 88.1 -50.4 22.0621 4 88.1 -50.3 24.5536 ... ... ... ... 2191880 -77.8 166.5 11459.2000 2191881 -77.8 166.6 694.4980 2191882 -77.9 166.3 2133.1000 2191883 -77.9 166.4 1389.0000 2191884 -77.9 166.5 7887.5100 [2191885 rows x 3 columns] It can also be fun to investigate where the most polluted areas are. co2 = co2.sort_values('emission', ascending=False) print(co2[:10]) lat lon emission 798909 41.0 122.5 355301000.0 1098659 31.2 121.3 330941000.0 1129717 30.1 115.0 209367000.0 1124042 30.3 114.1 82808100.0 407743 53.4 59.0 68397600.0 1282838 24.2 120.4 62984400.0 845540 39.5 116.2 57421000.0 337844 55.9 37.7 56890200.0 795787 41.1 123.4 55067700.0 1301463 23.4 86.3 50850200.0 Perhaps unsurprisingly, the majority of these can be found in China although there are a few notable contributions from India, Russia and Taiwan. Plotting the data shows that the data does not cover the whole world and there are missing values for parts of the Pacific and Southern Oceans. This is hardly surprising as those Oceans are vast and often devoid of human impact. I have just used a scatter plot here for the latitude and longitude values. A few things to note about the plots going forward. The points are set to 0.05 because if left to the default value of 1 they overlap. The edge of a scatter point is a separate thing to the point itself and cannot be smaller than 1. So these have to be turned off. Also important to note, when plotting latitude and longitude values, latitude is y and longitude is x. import matplotlib.pyplot as plt fig = plt.figure() fig.set_size_inches(7, 3.5) plt.scatter(co2['lon'], co2['lat'], s=0.05, edgecolors='none') plt.show() Colouring the points according to the emission value is a good way to get a sense of what the data is actually going to look like. Unfortunately the plot is dominated by low emissions values. fig = plt.figure() fig.set_size_inches(7, 3.5) cols = plt.scatter(co2['lon'], co2['lat'], c=co2['emission'], s=0.05, edgecolors='none') plt.colorbar(cols) plt.show() Exploring the data (which I have largely omitted for brevity) shows it is dominated by values in the range of 0–1000 tonnes of carbon dioxide per year and there are a small number of values a few orders of magnitude greater. import numpy as np print(co2.emission.value_counts()) print() print("Min value: ", np.amin(co2.emission)) print("Max value: ", np.amax(co2.emission)) 347.2490 30310 248.0350 27141 297.6420 22373 396.8560 17280 148.8210 17257 ... 42337.8000 1 42129.7000 1 260.5530 1 42128.7000 1 95.1692 1 Name: emission, Length: 1215854, dtype: int64 Min value: 8.016030000000001e-07 Max value: 355301000.0 With this in mind we are going to plot the values on a log scale. I try to avoid log plots if possible because the resulting plot can be hard to interpret and the data is often meaningless. However, log plots are good when there is a small population of values orders of magnitude greater than the majority and also in plots where you are trying to show multiplicative factors. Our data fits into both of these categories so it is appropriate in this case. There is also a contextual reason for a log plot. We want to know where carbon dioxide emissions are coming from and if we used the plot above we would conclude that emissions are evenly distributed around the world. We know that emissions in London are probably higher than the middle of the Atlantic so we need a way to distinguish between the small numbers of high values and vast numbers of low values. Matplotlib has a built in log scale which is utilised in the block below. from matplotlib import colors fig = plt.figure() fig.set_size_inches(7, 3.5) cols = plt.scatter(co2['lon'], co2['lat'], c=co2['emission'], norm=colors.LogNorm()) plt.colorbar(cols) plt.show() The world as we know it is now starting to show itself so it is now time to start making it look pretty. While viridis is scientifically the perfect colourmap (https://www.youtube.com/watch?v=xAoljeRJ3lU), I want something fiery to show carbon dioxide emissions because they cause global warming, which is potentially fiery. So we are going to switch it to to afmhot_r (the _r means the colourmap is reversed and maps low values to light colours and large values to dark colours). I have reversed it because the background is white and we want the large emissions values to stand out. fig = plt.figure() fig.set_size_inches(7, 3.5) plt.scatter(co2['lon'], co2['lat'], s=0.05, edgecolors='none', c=co2['emission'], norm=colors.LogNorm(), cmap='afmhot_r') plt.show() The map is starting to take shape, now onto projections. There are numerous geographical projections, the one shown in the opening image is known as the Robinson projection and while there is debate, it is often regarded as the most realistic. Until now we have been relying on plotting the values with a standard scatter plot (which vaguely corresponds to the mercator projection). This is technically fine however not appropriate if we want to properly map the emissions data to a geographical projection. So the latitude / longitude values need to be converted to into shapely points which can then be transformed into the projection we want. The data can then be reprojected with a library called cartopy within the subplots function. Feel free to apply whatever style changes you want, for example I like dark mode so I have changed the background to black and flipped the colourmap so large values are lighter. When initially plotting this map I was perfectly happy with the plot shown above but I thought it was best to check what it should look like by looking at the original publishers plot. The image shown below was generated by the original publishers. For reasons that I cannot quite establish, they have chosen an odd series of values for their colour scale, namely 0.0, 0.06, 6, 60, 600, 3000, 6000, 24000, 45000, 120000. Lack of explanation aside I thought it would be interesting to replicate this plot because these are the climate pros and probably know a lot more than I do, hence there is probably a good reason for it. As before we will use afmhot as our colourmap but this time we will map it to 10 colours and normalise those 10 colours to the 10 values in the key in the image above (0.0, 0.06, 6, 60, 600, 3000, 6000, 24000, 45000, 120000). Objects that use colormaps in matplotlib by default linearly map the colors in the colormap from the minimum value in the dataset to the maximum value in the dataset at discrete intervals determined by the number of colours in the colourmap. The BoundaryNorm class allows you to map colours in a colourmap to a set of custom values. In the code below we are creating a colourmap with 10 colours and a BoundaryNorm object which will map the values in our data to the colourmap according to the pre-defined levels. The above image gives a rough visualisation of what is happening. The colourmap is generated with 10 colours and values within our emissions dataset will be coloured according to the values in the above image. For example, values equal to or greater than 120000 tonnes of carbon dioxide per year will be coloured white. Now, armed with our new colormap and normalised boundaries we can replot the map, this time mapping values to colours in a way more reminiscent of what the original authors have done. The final thing to do is to provide a colourbar so that our reader can understand what they are actually looking at. I sometimes don’t bother with this step but it is still useful to think know about. There we have it, a beautiful map showing the where the world’s carbon dioxide emissions come from. This is the first of many articles planned to show how to make geospatial data look fantastic, please subscribe so you don’t miss them. I also love feedback so please let me know how you would do it differently or suggest changes to make it look even more awesome. I post data visualisations every week on my twitter account, have a look if geospatial data vis is your thing https://twitter.com/PythonMaps References Crippa, M., Guizzardi, D., Schaaf, E., Solazzo, E., Muntean, M., Monforti-Ferrario, F., Olivier, J.G.J., Vignati, E.: Fossil CO2 and GHG emissions of all world countries — 2021 Report, in prep. Crippa, M., Solazzo, E., Huang, G., Guizzardi, D., Koffi, E., Muntean, M., Schieberle, C., Friedrich, R. and Janssens-Maenhout, G.: High resolution temporal profiles in the Emissions Database for Global Atmospheric Research. Sci Data 7, 121 (2020). doi:10.1038/s41597–020–0462–2. IEA (2019) World Energy Balances, www.iea.org/data-and-statistics, All rights reserved, as modified by Joint Research Centre, European Commission. Jalkanen, J. P., Johansson, L., Kukkonen, J., Brink, A., Kalli, J., & Stipa, T. (2012). Extension of an assessment model of ship traffic exhaust emissions for particulate matter and carbon monoxide. Atmospheric Chemistry and Physics, 12(5), 2641–2659. doi:10.5194/acp-12–2641–2012 Johansson, L., Jalkanen, J.-P., & Kukkonen, J. (2017). Global assessment of shipping emissions in 2015 on a high spatial and temporal resolution. Atmospheric Environment, 167, 403–415. doi:10.1016/j.atmosenv.2017.08.042
[ { "code": null, "e": 1704, "s": 166, "text": "For some reason, climate change has been in the news a lot recently. Specifically the link between carbon dioxide emissions from our cars, factories, ships, planes (to name a few) and the warming of our planet via the greenhouse effect. The image above s...
How to simulate a stock market with less than 10 lines of Python code | by Gianluca Malato | Towards Data Science
Stochastic processes theory is wonderful and full of theoretical opportunities for those who are interested in quantitative trading. Sometimes, in order to test a trading strategy, simulating a stock market could be useful. Let’s see how theory comes into help and how to convert it into practice using Python. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. More than the price, when it comes to modeling a stock market, the most important object we can model is the return. If we consider a particular day n and its previous day n-1 the return is calculated as: Starting from this definition, we can calculate the price time series using the following formula: So, knowing the start price p0, we can calculate future prices using the sequence of returns. The problem is that the returns are stochastic objects, so each realization of the returns will give us a different time series for the prices. The stochastic behavior of the price is modeled in this way. So, if we want to simulate price time series, we need to make some assumptions about the returns and then apply the formula above. Geometric Brownian Motion is one of these assumptions. GBM is a particular model of the stock market in with the returns are uncorrelated and normally distributed. We can mathematically translate this sentence as: that is, the returns are normally distributed with mean μ and standard deviation σ. Keep in mind that these parameters are time-independent, so the process is called “stationary”. μ is the mean value of the returns. If it’s positive, we have a bullish trend. If it’s negative, we have a bearish trend. The higher the absolute value of this parameter, the stronger the trend. σ is the volatility of the returns. The higher this value if compared with μ, the more erratic the price. Going back to portfolio theory, the Sharpe ratio with risk-free return equal to 0 is μ/σ. For those of you who, like me, love the math behind statistics, if we switch to a continuous time we can write this stochastic differential equation (SDE): where W is the Wiener process. This model is often used in financial mathematics because it’s the simplest stock market model you can build. For example, it’s the theoretical base of Nobel-award Black-Sholes options theory. However, this model has been proven not to be completely correct, because stock market returns aren’t normally distributed nor are stationary, but it’s a good point to start from. The SDE can be analytically solved under, for example, Ito’s interpretation, but in reality we never have a continuous time, since the transactions are discrete and finite. So, if we want to simulate a GBM, we can simply discretize the time keeping the normality of the returns. It is mathematically equivalent to numerically solving the SDE using Euler-Maruyama method. The idea is, then, very simple: generate n normally distributed random variables and calculate future prices starting from a start price. Let’s see how to do it in Python in less than 10 lines of code. First, let’s import some useful libraries: import numpy as npimport matplotlib.pyplot as plt Now, we have to define μ, σ and the start price. We can use, for example, these values: mu = 0.001sigma = 0.01start_price = 5 Now it comes the simulation part. First, we need to set the seed of the numpy random number generator in order to make reproducible results. Then we generate, for example, 100 values for the returns and finally we build the price time series starting from the start price. np.random.seed(0)returns = np.random.normal(loc=mu, scale=sigma, size=100)price = start_price*(1+returns).cumprod() Finally, we can plot these results: plt.plot(price) That’s it. 9 lines total. It really looks like a stock price, doesn’t it? We could, for example, increase the value of μ and see what happens. For example, with μ=0.004, we have: As we can see, a higher value of μ leads us to a stronger bullish trend. Simulating a stock market in Python using Geometric Brownian Motion is very simple, but when we do this exercise we need to keep in mind that the stock market is not always normally distributed nor it is stationary. We could, for example, apply a time dependence on μ and σ or use a different probability distribution for the returns. Gianluca Malato is an Italian Data Scientist and a fiction author. He is the founder of YourDataTeacher.com, an online school of data science, machine learning and data analysis.
[ { "code": null, "e": 483, "s": 172, "text": "Stochastic processes theory is wonderful and full of theoretical opportunities for those who are interested in quantitative trading. Sometimes, in order to test a trading strategy, simulating a stock market could be useful. Let’s see how theory comes into...
Dart Programming - String
The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units. String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes. Triple quotes are used to represent multi-line strings. The syntax of representing string values in Dart is as given below − String variable_name = 'value' OR String variable_name = ''value'' OR String variable_name = '''line1 line2''' OR String variable_name= ''''''line1 line2'''''' The following example illustrates the use of String data type in Dart. void main() { String str1 = 'this is a single line string'; String str2 = "this is a single line string"; String str3 = '''this is a multiline line string'''; String str4 = """this is a multiline line string"""; print(str1); print(str2); print(str3); print(str4); } It will produce the following Output − this is a single line string this is a single line string this is a multiline line string this is a multiline line string Strings are immutable. However, strings can be subjected to various operations and the resultant string can be a stored as a new value. The process of creating a new string by appending a value to a static string is termed as concatenation or interpolation. In other words, it is the process of adding a string to another string. The operator plus (+) is a commonly used mechanism to concatenate / interpolate strings. void main() { String str1 = "hello"; String str2 = "world"; String res = str1+str2; print("The concatenated string : ${res}"); } It will produce the following output − The concatenated string : Helloworld You can use "${}" can be used to interpolate the value of a Dart expression within strings. The following example illustrates the same. void main() { int n=1+1; String str1 = "The sum of 1 and 1 is ${n}"; print(str1); String str2 = "The sum of 2 and 2 is ${2+2}"; print(str2); } It will produce the following output − The sum of 1 and 1 is 2 The sum of 2 and 2 is 4 The properties listed in the following table are all read-only. Returns an unmodifiable list of the UTF-16 code units of this string. Returns true if this string is empty. Returns the length of the string including space, tab and newline characters. The String class in the dart: core library also provides methods to manipulate strings. Some of these methods are given below − Converts all characters in this string to lower case. Converts all characters in this string to upper case. Returns the string without any leading and trailing whitespace. Compares this object to another. Replaces all substrings that match the specified pattern with a given value. Splits the string at matches of the specified delimiter and returns a list of substrings. Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive. Returns a string representation of this object. Returns the 16-bit UTF-16 code unit at the given index. 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2633, "s": 2525, "text": "The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units." }, { "code": null, "e": 2845, "s": 2633, "text": "String values in Dart can be represented using either single or double or ...
Ant - Property Files
Setting properties directly in the build file is fine, if you are working with a handful of properties. However, for a large project, it makes sense to store the properties in a separate property file. Storing the properties in a separate file offers the following benefits − It allows you to reuse the same build file, with different property settings for different execution environment. For example, build properties file can be maintained separately for DEV, TEST, and PROD environments. It allows you to reuse the same build file, with different property settings for different execution environment. For example, build properties file can be maintained separately for DEV, TEST, and PROD environments. It is useful, when you do not know the values for a property (in a particular environment) up-front. This allows you to perform the build in other environments, where the property value is known. It is useful, when you do not know the values for a property (in a particular environment) up-front. This allows you to perform the build in other environments, where the property value is known. There is no hard and fast rule, but typically the property file is named as build.properties and is placed along-side the build.xml file. You could create multiple build properties files based on the deployment environments - such as build.properties.dev and build.properties.test. The contents of the build property file are similar to the normal java property file. They contain one property per line. Each property is represented by a name and a value pair. The name and value pairs are separated by an equals (=) sign. It is highly recommended that the properties are annotated with proper comments. Comments are listed using the hash (#) character. The following example shows a build.xml file and its associated build.properties file − Given below is an example for build.xml file. <?xml version="1.0"?> <project name="Hello World Project" default="info"> <property file="build.properties"/> <target name="info"> <echo>Apache Ant version is ${ant.version} - You are at ${sitename} </echo> </target> </project> An example for build.properties file is mentioned below − # The Site Name sitename=www.tutorialspoint.com buildversion=3.3.2 In the above example, sitename is a custom property which is mapped to the website name. You can declare any number of custom properties in this fashion. Another custom property listed in the above example is the buildversion, which, in this instance, refers to the version of the build. In addition to the above, Ant comes with a number of predefined build properties, which are listed in the previous section, but is given below once again for your reference. ant.file The full location of the build file. ant.version The version of the Apache Ant installation. basedir The basedir of the build, as specified in the basedir attribute of the project element. ant.java.version The version of the JDK that is used by Ant. ant.project.name The name of the project, as specified in the name attribute of the project element. ant.project.default-target The default target of the current project. ant.project.invoked-targets Comma separated list of the targets that were invoked in the current project. ant.core.lib The full location of the Ant jar file. ant.home The home directory of Ant installation. ant.library.dir The home directory for Ant library files - typically ANT_HOME/lib folder. The example presented in this chapter uses the ant.version built-in property. 20 Lectures 2 hours Deepti Trivedi 19 Lectures 2.5 hours Deepti Trivedi 139 Lectures 14 hours Er. Himanshu Vasishta 30 Lectures 1.5 hours Pushpendu Mondal 65 Lectures 6.5 hours Ridhi Arora 10 Lectures 2 hours Manish Gupta Print Add Notes Bookmark this page
[ { "code": null, "e": 2299, "s": 2097, "text": "Setting properties directly in the build file is fine, if you are working with a handful of properties. However, for a large project, it makes sense to store the properties in a separate property file." }, { "code": null, "e": 2373, "s":...
Floor and Ceil from a BST - GeeksforGeeks
01 Jul, 2021 Given a binary tree and a key(node) value, find the floor and ceil value for that particular key value. Floor Value Node: Node with the greatest data lesser than or equal to the key value. Ceil Value Node: Node with the smallest data larger than or equal to the key value. For example, Let’s consider the Binary Tree below – 8 / \ 4 12 / \ / \ 2 6 10 14 Key: 11 Floor: 10 Ceil: 12 Key: 1 Floor: -1 Ceil: 2 Key: 6 Floor: 6 Ceil: 6 Key: 15 Floor: 14 Ceil: -1 There are numerous applications where we need to find the floor/ceil value of a key in a binary search tree or sorted array. For example, consider designing a memory management system in which free nodes are arranged in BST. Find the best fit for the input request. Algorithm: Imagine we are moving down the tree, and assume we are root node. The comparison yields three possibilities, A) Root data is equal to key. We are done, root data is ceil value. B) Root data < key value, certainly the ceil value can't be in left subtree. Proceed to search on right subtree as reduced problem instance. C) Root data > key value, the ceil value may be in left subtree. We may find a node with is larger data than key value in left subtree, if not the root itself will be ceil node. Here is the code for ceil value: C++ C Java Python C# Javascript // Program to find ceil of a given value in BST#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, left child and right child */class node {public: int key; node* left; node* right;}; /* Helper function that allocates a new node with the given key andNULL left and right pointers.*/node* newNode(int key){ node* Node = new node(); Node->key = key; Node->left = NULL; Node->right = NULL; return (Node);} // Function to find ceil of a given input in BST. If input is more// than the max key in BST, return -1int Ceil(node* root, int input){ // Base case if (root == NULL) return -1; // We found equal key if (root->key == input) return root->key; // If root's key is smaller, ceil must be in right subtree if (root->key < input) return Ceil(root->right, input); // Else, either left subtree or root has the ceil value int ceil = Ceil(root->left, input); return (ceil >= input) ? ceil : root->key;} // Driver program to test above functionint main(){ node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(10); root->right->right = newNode(14); for (int i = 0; i < 16; i++) cout << i << " " << Ceil(root, i) << endl; return 0;} // This code is contributed by rathbhupendra // Program to find ceil of a given value in BST#include <stdio.h>#include <stdlib.h> /* A binary tree node has key, left child and right child */struct node { int key; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given key andNULL left and right pointers.*/struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return (node);} // Function to find ceil of a given input in BST. If input is more// than the max key in BST, return -1int Ceil(struct node* root, int input){ // Base case if (root == NULL) return -1; // We found equal key if (root->key == input) return root->key; // If root's key is smaller, ceil must be in right subtree if (root->key < input) return Ceil(root->right, input); // Else, either left subtree or root has the ceil value int ceil = Ceil(root->left, input); return (ceil >= input) ? ceil : root->key;} // Driver program to test above functionint main(){ struct node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(10); root->right->right = newNode(14); for (int i = 0; i < 16; i++) printf("%d %d\n", i, Ceil(root, i)); return 0;} // Java program to find ceil of a given value in BST class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree { Node root; // Function to find ceil of a given input in BST. // If input is more than the max key in BST, // return -1 int Ceil(Node node, int input) { // Base case if (node == null) { return -1; } // We found equal key if (node.data == input) { return node.data; } // If root's key is smaller, // ceil must be in right subtree if (node.data < input) { return Ceil(node.right, input); } // Else, either left subtree or root // has the ceil value int ceil = Ceil(node.left, input); return (ceil >= input) ? ceil : node.data; } // Driver Code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(8); tree.root.left = new Node(4); tree.root.right = new Node(12); tree.root.left.left = new Node(2); tree.root.left.right = new Node(6); tree.root.right.left = new Node(10); tree.root.right.right = new Node(14); for (int i = 0; i < 16; i++) { System.out.println(i + " " + tree.Ceil(tree.root, i)); } }} // This code has been contributed by Mayank Jaiswal # Python program to find ceil of a given value in BST # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Function to find ceil of a given input in BST. If input# is more than the max key in BST, return -1def ceil(root, inp): # Base Case if root == None: return -1 # We found equal key if root.key == inp : return root.key # If root's key is smaller, ceil must be in right subtree if root.key < inp: return ceil(root.right, inp) # Else, either left subtre or root has the ceil value val = ceil(root.left, inp) return val if val >= inp else root.key # Driver program to test above functionroot = Node(8) root.left = Node(4)root.right = Node(12) root.left.left = Node(2)root.left.right = Node(6) root.right.left = Node(10)root.right.right = Node(14) for i in range(16): print "% d % d" %(i, ceil(root, i)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // C# program to find ceil of a given value in BST public class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree { public static Node root; // Function to find ceil of a given input in BST. If input is more // than the max key in BST, return -1 public virtual int Ceil(Node node, int input) { // Base case if (node == null) { return -1; } // We found equal key if (node.data == input) { return node.data; } // If root's key is smaller, ceil must be in right subtree if (node.data < input) { return Ceil(node.right, input); } // Else, either left subtree or root has the ceil value int ceil = Ceil(node.left, input); return (ceil >= input) ? ceil : node.data; } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(8); BinaryTree.root.left = new Node(4); BinaryTree.root.right = new Node(12); BinaryTree.root.left.left = new Node(2); BinaryTree.root.left.right = new Node(6); BinaryTree.root.right.left = new Node(10); BinaryTree.root.right.right = new Node(14); for (int i = 0; i < 16; i++) { Console.WriteLine(i + " " + tree.Ceil(root, i)); } }} // This code is contributed by Shrikant13 <script> // Javascript program to find ceil// of a given value in BST class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } let root; // Function to find ceil of // a given input in BST. // If input is more than the max // key in BST, // return -1 function Ceil(node,input) { // Base case if (node == null) { return -1; } // We found equal key if (node.data == input) { return node.data; } // If root's key is smaller, // ceil must be in right subtree if (node.data < input) { return Ceil(node.right, input); } // Else, either left subtree or root // has the ceil value let ceil = Ceil(node.left, input); return (ceil >= input) ? ceil : node.data; } // Driver Code root =new Node(8) root.left =new Node(4) root.right =new Node(12) root.left.left =new Node(2) root.left.right =new Node(6) root.right.left =new Node(10) root.right.right =new Node(14) for (let i = 0; i < 16; i++) { document.write(i + " " + Ceil(root, i)+"<br>"); } // This code is contributed by unknown2108 </script> Output: 0 2 1 2 2 2 3 4 4 4 5 6 6 6 7 8 8 8 9 10 10 10 11 12 12 12 13 14 14 14 15 -1 Iterative Approach – 1. If tree is empty, i.e. root is null, return back to calling function. 2. If current node address is not null, perform the following steps : (a) If current node data matches with the key value - We have found both our floor and ceil value. Hence, we return back to calling function. (b) If data in current node is lesser than the key value - We assign the current node data to the variable keeping track of current floor value and explore the right subtree, as it may contain nodes with values greater than key value. (c) If data in current node is greater than the key value - We assign the current node data to the variable keeping track of current ceil value and explore the left subtree, as it may contain nodes with values lesser than key value. 3. Once we reach null, we return back to the calling function, as we have got our required floor and ceil values for the particular key value. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find floor and ceil of a given key in BST#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, left child and right child */struct Node { int data; Node *left, *right; Node(int value) { data = value; left = right = NULL; }}; // Helper function to find floor and ceil of a given key in BSTvoid floorCeilBSTHelper(Node* root, int key, int& floor, int& ceil){ while (root) { if (root->data == key) { ceil = root->data; floor = root->data; return; } if (key > root->data) { floor = root->data; root = root->right; } else { ceil = root->data; root = root->left; } } return;} // Display the floor and ceil of a given key in BST.// If key is less than the min key in BST, floor will be -1;// If key is more than the max key in BST, ceil will be -1;void floorCeilBST(Node* root, int key){ // Variables 'floor' and 'ceil' are passed by reference int floor = -1, ceil = -1; floorCeilBSTHelper(root, key, floor, ceil); cout << key << ' ' << floor << ' ' << ceil << '\n';} // Driver program to test above functionint main(){ Node* root = new Node(8); root->left = new Node(4); root->right = new Node(12); root->left->left = new Node(2); root->left->right = new Node(6); root->right->left = new Node(10); root->right->right = new Node(14); for (int i = 0; i < 16; i++) floorCeilBST(root, i); return 0;} // Java program to find floor and ceil// of a given key in BSTimport java.io.*; // A binary tree node has key,// left child and right childclass Node{ int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree{ Node root;int floor;int ceil; // Helper function to find floor and// ceil of a given key in BSTpublic void floorCeilBSTHelper(Node root, int key){ while (root != null) { if (root.data == key) { ceil = root.data; floor = root.data; return; } if (key > root.data) { floor = root.data; root = root.right; } else { ceil = root.data; root = root.left; } } return;} // Display the floor and ceil of a// given key in BST. If key is less// than the min key in BST, floor// will be -1; If key is more than// the max key in BST, ceil will be -1;public void floorCeilBST(Node root, int key){ // Variables 'floor' and 'ceil' // are passed by reference floor = -1; ceil = -1; floorCeilBSTHelper(root, key); System.out.println(key + " " + floor + " " + ceil);} // Driver codepublic static void main(String[] args){ BinaryTree tree = new BinaryTree(); tree.root = new Node(8); tree.root.left = new Node(4); tree.root.right = new Node(12); tree.root.left.left = new Node(2); tree.root.left.right = new Node(6); tree.root.right.left = new Node(10); tree.root.right.right = new Node(14); for(int i = 0; i < 16; i++) { tree.floorCeilBST(tree.root, i); }}} // This code is contributed by RohitOberoi # Python3 program to find floor and# ceil of a given key in BST # A binary tree node has key,#. left child and right childclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Helper function to find floor and# ceil of a given key in BSTdef floorCeilBSTHelper(root, key): global floor, ceil while (root): if (root.data == key): ceil = root.data floor = root.data return if (key > root.data): floor = root.data root = root.right else: ceil = root.data root = root.left # Display the floor and ceil of a given# key in BST. If key is less than the min# key in BST, floor will be -1; If key is# more than the max key in BST, ceil will be -1;def floorCeilBST(root, key): global floor, ceil # Variables 'floor' and 'ceil' # are passed by reference floor = -1 ceil = -1 floorCeilBSTHelper(root, key) print(key, floor, ceil) # Driver codeif __name__ == '__main__': floor, ceil = -1, -1 root = Node(8) root.left = Node(4) root.right = Node(12) root.left.left = Node(2) root.left.right = Node(6) root.right.left = Node(10) root.right.right = Node(14) for i in range(16): floorCeilBST(root, i) # This code is contributed by mohit kumar 29 // C# program to find floor and ceil// of a given key in BSTusing System; // A binary tree node has key,// left child and right childpublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node root;int floor;int ceil; // Helper function to find floor and// ceil of a given key in BSTpublic int floorCeilBSTHelper(Node root, int key){ while (root != null) { if (root.data == key) { ceil = root.data; floor = root.data; return 0; } if (key > root.data) { floor = root.data; root = root.right; } else { ceil = root.data; root = root.left; } } return 0;} // Display the floor and ceil of a// given key in BST. If key is less// than the min key in BST, floor// will be -1; If key is more than// the max key in BST, ceil will be -1;public void floorCeilBST(Node root, int key){ // Variables 'floor' and 'ceil' // are passed by reference floor = -1; ceil = -1; floorCeilBSTHelper(root, key); Console.WriteLine(key + " " + floor + " " + ceil);} // Driver codestatic public void Main(){ BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(8); BinaryTree.root.left = new Node(4); BinaryTree.root.right = new Node(12); BinaryTree.root.left.left = new Node(2); BinaryTree.root.left.right = new Node(6); BinaryTree.root.right.left = new Node(10); BinaryTree.root.right.right = new Node(14); for(int i = 0; i < 16; i++) { tree.floorCeilBST(BinaryTree.root, i); }}} // This code is contributed by avanitrachhadiya2155 <script> // Javascript program to find floor and ceil// of a given key in BST // A binary tree node has key,// left child and right childclass Node{ constructor(d) { this.data = d; this.left = null; this.right = null; }} var root = null;var floor;var ceil; // Helper function to find floor and// ceil of a given key in BSTfunction floorCeilBSTHelper(root, key){ while (root != null) { if (root.data == key) { ceil = root.data; floor = root.data; return 0; } if (key > root.data) { floor = root.data; root = root.right; } else { ceil = root.data; root = root.left; } } return 0;} // Display the floor and ceil of a// given key in BST. If key is less// than the min key in BST, floor// will be -1; If key is more than// the max key in BST, ceil will be -1;function floorCeilBST(root, key){ // Variables 'floor' and 'ceil' // are passed by reference floor = -1; ceil = -1; floorCeilBSTHelper(root, key); document.write(key + " " + floor + " " + ceil + "<br>");} // Driver coderoot = new Node(8);root.left = new Node(4);root.right = new Node(12);root.left.left = new Node(2);root.left.right = new Node(6);root.right.left = new Node(10);root.right.right = new Node(14); for(var i = 0; i < 16; i++){ floorCeilBST(root, i);} // This code is contributed by rrrtnx.</script> Output : 0 -1 2 1 -1 2 2 2 2 3 2 4 4 4 4 5 4 6 6 6 6 7 6 8 8 8 8 9 8 10 10 10 10 11 10 12 12 12 12 13 12 14 14 14 14 15 14 -1 Time Complexity: O(N) Space Complexity: O(1) YouTubeGeeksforGeeks502K subscribersFloor and Ceil Value from a Binary Search Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=FnA9XGfydNI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Exercise:1. Modify the above code to find the floor value of the input key in a binary search tree.2. Write a neat algorithm to find floor and ceil values in a sorted array. Ensure to handle all possible boundary conditions. This article is contributed by Venki. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 rathbhupendra tridib_samanta RohitOberoi mohit kumar 29 avanitrachhadiya2155 unknown2108 rrrtnx Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inorder Successor in Binary Search Tree Red-Black Tree | Set 2 (Insert) Find the node with minimum value in a Binary Search Tree Optimal Binary Search Tree | DP-24 Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Advantages of BST over Hash Table Lowest Common Ancestor in a Binary Search Tree. Difference between Binary Tree and Binary Search Tree Find k-th smallest element in BST (Order Statistics in BST) Inorder predecessor and successor for a given key in BST
[ { "code": null, "e": 25248, "s": 25220, "text": "\n01 Jul, 2021" }, { "code": null, "e": 25352, "s": 25248, "text": "Given a binary tree and a key(node) value, find the floor and ceil value for that particular key value." }, { "code": null, "e": 25521, "s": 25352,...
Obtain the Previous Index and Next Index in an ArrayList using the ListIterator in Java
The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively in the ListIterator Interface. The previousIndex() method returns the index of the element that is returned by the previous() method while the nextIndex() method returns the index of the element that is returned by the next() method. Neither of these methods require any parameters. A program that demonstrates this is given as follows Live Demo import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Amy"); aList.add("Peter"); aList.add("Justin"); aList.add("Emma"); aList.add("James"); System.out.println("The ArrayList elements are: "+ aList); ListIterator<String> li = aList.listIterator(); System.out.println("The previous index is: " + li.previousIndex()); System.out.println("The next index is: " + li.nextIndex()); } } The output of the above program is as follows The ArrayList elements are: [Amy, Peter, Justin, Emma, James] The previous index is: -1 The next index is: 0 Now let us understand the above program. The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed. The previous index and next index in an is obtained using the methods previousIndex() and nextIndex() respectively. A code snippet which demonstrates this is as follows ArrayList<String> aList = new ArrayList<String>(); aList.add("Amy"); aList.add("Peter"); aList.add("Justin"); aList.add("Emma"); aList.add("James"); System.out.println("The ArrayList elements are: "+ aList); ListIterator<String> li = aList.listIterator(); System.out.println("The previous index is: " + li.previousIndex()); System.out.println("The next index is: " + li.nextIndex());
[ { "code": null, "e": 1222, "s": 1062, "text": "The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively in the ListIterator Interface." }, { "code": null, "e": 1474, "s": 1222, "text": "The previousIndex() me...
Finding gcd of two strings in JavaScript
In the number system, the Greatest Common Divisor (GCD) of two numbers is that greatest number which divides both the numbers. Similarly, if we apply this concept to strings, the gcd of two strings is the greatest substring (greatest in length) that is present in both the strings. For example − If the two strings are − const str1 = 'abcabc'; const str2 = 'abc'; Then the gcd of these strings will be − const gcd = 'abc'; We are required to write a JavaScript function that takes in two strings str1 and str2 and computes and returns their gcd. The code for this will be − Live Demo const str1 = 'abcabc'; const str2 = 'abc'; const findGCD = (str1 = '', str2 = '') => { if (str1 + str2 !== str2 + str1){ // not possible // no common element return ""; } else if (str1 == str2){ return str1; } else if (str1.length > str2.length){ return findGCD(str1.slice(str2.length), str2); } else { return findGCD(str2.slice(str1.length), str1); } }; console.log(findGCD(str1, str2)); And the output in the console will be − abc
[ { "code": null, "e": 1344, "s": 1062, "text": "In the number system, the Greatest Common Divisor (GCD) of two numbers is that greatest number which divides both the numbers. Similarly, if we apply this concept to strings, the gcd of two strings is the greatest substring (greatest in length) that is ...
Buddy Memory Allocation Program | Set 1 (Allocation) - GeeksforGeeks
28 Jan, 2022 Prerequisite – Buddy System Question: Write a program to implement the buddy system of memory allocation in Operating Systems.Explanation – The buddy system is implemented as follows- A list of free nodes, of all the different possible powers of 2, is maintained at all times (So if total memory size is 1 MB, we’d have 20 free lists to track-one for blocks of size 1 byte, 1 for 2 bytes, next for 4 bytes and so on). When a request for allocation comes, we look for the smallest block bigger than it. If such a block is found on the free list, the allocation is done (say, the request is of 27 KB and the free list tracking 32 KB blocks has at least one element in it), else we traverse the free list upwards till we find a big enough block. Then we keep splitting it in two blocks-one for adding to the next free list (of smaller size), one to traverse down the tree till we reach the target and return the requested memory block to the user. If no such allocation is possible, we simply return null. Example: Let us see how the algorithm proceeds by tracking a memory block of size 128 KB. Initially, the free list is: {}, {}, {}, {}, {}, {}, {}, { (0, 127) } Request: 32 bytes No such block found, so we traverse up and split the 0-127 block into 0-63, 64-127; we add 64-127 to list tracking 64 byte blocks and pass 0-63 downwards; again it is split into 0-31 and 32-63; since we have found the required block size, we add 32-63 to list tracking 32 byte blocks and return 0-31 to user. List is: {}, {}, {}, {}, {}, { (32, 63) }, { (64, 127) }, {} Request: 7 bytes No such block found-split block 32-63 into two blocks, namely 32-47 and 48-63; then split 32-47 into 32-39 and 40-47; finally, return 32-39 to user (internal fragmentation of 1 byte occurs) List is: {}, {}, {}, { (40, 47) }, { (48, 63) }, {}, { (64, 127) }, {} Request: 64 bytes Straight up memory segment 64-127 will be allocated as it already exists. List is: {}, {}, {}, { (40, 47) }, { (48, 63) }, {}, {}, {} Request: 56 bytes Result: Not allocated The result will be as follows: Figure – Buddy Allocation-128 shows the starting address of next possible block (if main memory size ever increases) Implementation – C++ Java C# Javascript #include<bits/stdc++.h>using namespace std; // Size of vector of pairsint size; // Global vector of pairs to store// address ranges available in free listvector<pair<int, int>> free_list[100000]; // Map used as hash map to store the starting// address as key and size of allocated segment// key as valuemap<int, int> mp; void initialize(int sz){ // Maximum number of powers of 2 possible int n = ceil(log(sz) / log(2)); size = n + 1; for(int i = 0; i <= n; i++) free_list[i].clear(); // Initially whole block of specified // size is available free_list[n].push_back(make_pair(0, sz - 1));} void allocate(int sz){ // Calculate index in free list // to search for block if available int n = ceil(log(sz) / log(2)); // Block available if (free_list[n].size() > 0) { pair<int, int> temp = free_list[n][0]; // Remove block from free list free_list[n].erase(free_list[n].begin()); cout << "Memory from " << temp.first << " to " << temp.second << " allocated" << "\n"; // map starting address with // size to make deallocating easy mp[temp.first] = temp.second - temp.first + 1; } else { int i; for(i = n + 1; i < size; i++) { // Find block size greater than request if(free_list[i].size() != 0) break; } // If no such block is found // i.e., no memory block available if (i == size) { cout << "Sorry, failed to allocate memory \n"; } // If found else { pair<int, int> temp; temp = free_list[i][0]; // Remove first block to split it into halves free_list[i].erase(free_list[i].begin()); i--; for(; i >= n; i--) { // Divide block into two halves pair<int, int> pair1, pair2; pair1 = make_pair(temp.first, temp.first + (temp.second - temp.first) / 2); pair2 = make_pair(temp.first + (temp.second - temp.first + 1) / 2, temp.second); free_list[i].push_back(pair1); // Push them in free list free_list[i].push_back(pair2); temp = free_list[i][0]; // Remove first free block to // further split free_list[i].erase(free_list[i].begin()); } cout << "Memory from " << temp.first << " to " << temp.second << " allocated" << "\n"; mp[temp.first] = temp.second - temp.first + 1; } }} // Driver codeint main(){ // Uncomment following code for interactive IO /* int total,c,req; cin>>total; initialize(total); while(true) { cin>>req; if(req < 0) break; allocate(req); }*/ initialize(128); allocate(32); allocate(7); allocate(64); allocate(56); return 0;} // This code is contributed by sarthak_eddy import java.io.*;import java.util.*; class Buddy { // Inner class to store lower // and upper bounds of the allocated memory class Pair { int lb, ub; Pair(int a, int b) { lb = a; ub = b; } } // Size of main memory int size; // Array to track all // the free nodes of various sizes ArrayList<Pair> arr[]; // Else compiler will give warning // about generic array creation @SuppressWarnings("unchecked") Buddy(int s) { size = s; // Gives us all possible powers of 2 int x = (int)Math.ceil(Math.log(s) / Math.log(2)); // One extra element is added // to simplify arithmetic calculations arr = new ArrayList[x + 1]; for (int i = 0; i <= x; i++) arr[i] = new ArrayList<>(); // Initially, only the largest block is free // and hence is on the free list arr[x].add(new Pair(0, size - 1)); } void allocate(int s) { // Calculate which free list to search to get the // smallest block large enough to fit the request int x = (int)Math.ceil(Math.log(s) / Math.log(2)); int i; Pair temp = null; // We already have such a block if (arr[x].size() > 0) { // Remove from free list // as it will be allocated now temp = (Pair)arr[x].remove(0); System.out.println("Memory from " + temp.lb + " to " + temp.ub + " allocated"); return; } // If not, search for a larger block for (i = x + 1; i < arr.length; i++) { if (arr[i].size() == 0) continue; // Found a larger block, so break break; } // This would be true if no such block was found // and array was exhausted if (i == arr.length) { System.out.println("Sorry, failed to allocate memory"); return; } // Remove the first block temp = (Pair)arr[i].remove(0); i--; // Traverse down the list for (; i >= x; i--) { // Divide the block in two halves // lower index to half-1 Pair newPair = new Pair(temp.lb, temp.lb + (temp.ub - temp.lb) / 2); // half to upper index Pair newPair2 = new Pair(temp.lb + (temp.ub - temp.lb + 1) / 2, temp.ub); // Add them to next list // which is tracking blocks of smaller size arr[i].add(newPair); arr[i].add(newPair2); // Remove a block to continue the downward pass temp = (Pair)arr[i].remove(0); } // Finally inform the user // of the allocated location in memory System.out.println("Memory from " + temp.lb + " to " + temp.ub + " allocated"); } public static void main(String args[]) throws IOException { int initialMemory = 0, val = 0; // Uncomment the below section for interactive I/O /*Scanner sc=new Scanner(System.in); initialMemory = sc.nextInt(); Buddy obj = new Buddy(initialMemory); while(true) { val = sc.nextInt();// Accept the request if(val <= 0) break; obj.allocate(val);// Proceed to allocate }*/ initialMemory = 128; // Initialize the object with main memory size Buddy obj = new Buddy(initialMemory); obj.allocate(32); obj.allocate(7); obj.allocate(64); obj.allocate(56); }} using System;using System.Collections.Generic; public class Buddy{ // Inner class to store lower // and upper bounds of the // allocated memory class Pair { public int lb, ub; public Pair(int a, int b) { lb = a; ub = b; } } // Size of main memory int size; // Array to track all // the free nodes of various sizes List<Pair> []arr; // Else compiler will give warning // about generic array creation Buddy(int s) { size = s; // Gives us all possible powers of 2 int x = (int)Math.Ceiling(Math.Log(s) / Math.Log(2)); // One extra element is added // to simplify arithmetic calculations arr = new List<Pair>[x + 1]; for (int i = 0; i <= x; i++) arr[i] = new List<Pair>(); // Initially, only the largest block is free // and hence is on the free list arr[x].Add(new Pair(0, size - 1)); } void allocate(int s) { // Calculate which free list to search // to get the smallest block // large enough to fit the request int x = (int)Math.Ceiling(Math.Log(s) / Math.Log(2)); int i; Pair temp = null; // We already have such a block if (arr[x].Count > 0) { // Remove from free list // as it will be allocated now temp = (Pair)arr[x][0]; arr[x].RemoveAt(0); Console.WriteLine("Memory from " + temp.lb + " to " + temp.ub + " allocated"); return; } // If not, search for a larger block for (i = x + 1; i < arr.Length; i++) { if (arr[i].Count == 0) continue; // Found a larger block, so break break; } // This would be true if no such block // was found and array was exhausted if (i == arr.Length) { Console.WriteLine("Sorry, failed to" + " allocate memory"); return; } // Remove the first block temp = (Pair)arr[i][0]; arr[i].RemoveAt(0); i--; // Traverse down the list for (; i >= x; i--) { // Divide the block in two halves // lower index to half-1 Pair newPair = new Pair(temp.lb, temp.lb + (temp.ub - temp.lb) / 2); // half to upper index Pair newPair2 = new Pair(temp.lb + (temp.ub - temp.lb + 1) / 2, temp.ub); // Add them to next list which is // tracking blocks of smaller size arr[i].Add(newPair); arr[i].Add(newPair2); // Remove a block to continue // the downward pass temp = (Pair)arr[i][0]; arr[i].RemoveAt(0); } // Finally inform the user // of the allocated location in memory Console.WriteLine("Memory from " + temp.lb + " to " + temp.ub + " allocated"); } // Driver Code public static void Main(String []args) { int initialMemory = 0; initialMemory = 128; // Initialize the object with main memory size Buddy obj = new Buddy(initialMemory); obj.allocate(32); obj.allocate(7); obj.allocate(64); obj.allocate(56); }} // This code is contributed by 29AjayKumar <script> // Inner class to store lower// and upper bounds of the allocated memoryclass Pair{ constructor(a, b) { this.lb = a; this.ub = b; }} let size;let arr; function Buddy(s){ size = s; // Gives us all possible powers of 2 let x = Math.ceil(Math.log(s) / Math.log(2)); // One extra element is added // to simplify arithmetic calculations arr = new Array(x + 1); for(let i = 0; i <= x; i++) arr[i] =[]; // Initially, only the largest block is free // and hence is on the free list arr[x].push(new Pair(0, size - 1));} function allocate(s){ // Calculate which free list to search to get the // smallest block large enough to fit the request let x = Math.floor(Math.ceil( Math.log(s) / Math.log(2))); let i; let temp = null; // We already have such a block if (arr[x].length > 0) { // Remove from free list // as it will be allocated now temp = arr[x].shift(); document.write("Memory from " + temp.lb + " to " + temp.ub + " allocated<br>"); return; } // If not, search for a larger block for(i = x + 1; i < arr.length; i++) { if (arr[i].length == 0) continue; // Found a larger block, so break break; } // This would be true if no such block was // found and array was exhausted if (i == arr.length) { document.write("Sorry, failed to " + "allocate memory<br>"); return; } // Remove the first block temp = arr[i].shift(0); i--; // Traverse down the list for(; i >= x; i--) { // Divide the block in two halves // lower index to half-1 let newPair = new Pair(temp.lb, temp.lb + Math.floor( (temp.ub - temp.lb) / 2)); // half to upper index let newPair2 = new Pair(temp.lb + Math.floor( (temp.ub - temp.lb + 1) / 2), temp.ub); // Add them to next list which is // tracking blocks of smaller size arr[i].push(newPair); arr[i].push(newPair2); // Remove a block to continue // the downward pass temp = arr[i].shift(0); } // Finally inform the user // of the allocated location in memory document.write("Memory from " + temp.lb + " to " + temp.ub + " allocated<br>");} // Driver codelet initialMemory = 0, val = 0; // Uncomment the below section for interactive I/O/*Scanner sc=new Scanner(System.in); initialMemory = sc.nextInt(); Buddy obj = new Buddy(initialMemory); while(true) { val = sc.nextInt();// Accept the request if(val <= 0) break; obj.allocate(val);// Proceed to allocate }*/ initialMemory = 128; // Initialize the object with main memory sizeBuddy(initialMemory);allocate(32);allocate(7);allocate(64);allocate(56); // This code is contributed by rag2127 </script> Memory from 0 to 31 allocated Memory from 32 to 39 allocated Memory from 64 to 127 allocated Sorry, failed to allocate memory Time Complexity – If the main memory size is n, we have log(n) number of different powers of 2 and hence log(n) elements in the array (named arr in the code) tracking free lists. To allocate a block, we only need to traverse the array once upwards and once downwards, hence time complexity is O(2log(n)) or simply O(logn) ak21 29AjayKumar sarthak_eddy rag2127 rkbhola5 Operating Systems-Memory Management Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for FCFS CPU Scheduling | Set 1 Page Replacement Algorithms in Operating Systems Program for Round Robin scheduling | Set 1 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Introduction of Deadlock in Operating System Semaphores in Process Synchronization CPU Scheduling in Operating Systems Difference between Process and Thread Inter Process Communication (IPC) Introduction of Operating System - Set 1
[ { "code": null, "e": 24474, "s": 24446, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25477, "s": 24474, "text": "Prerequisite – Buddy System Question: Write a program to implement the buddy system of memory allocation in Operating Systems.Explanation – The buddy system is imp...
Using the Pandas Data Frame as a Database. | by Tanu N Prabhu | Towards Data Science
Let us understand how to use the pandas data frame as a database. Before starting let me quickly tell about the pandas data frame: It is a python library that provides high performance, and easy-to-use data structure for data analysis tools for python programming language. Below is an article that explains the primitive manipulations performed on the pandas data frame. towardsdatascience.com Let’s get started, this is a programming tutorial so I recommend you guys to practice side by side with me. I favor using Google Colab or Jupyter notebooks. To brief out, I will teach you guys how to use the pandas data frame as a database to store data and perform some rudimentary operations on it. This data frame has almost all the features compared to a database. It almost resembles a database. Also to get the full code visit my GitHub Repository below: github.com Creating a pandas data frame Creating a pandas data frame 2. Adding a row to the data frame 3. Deleting a row from the data frame 4. Accessing the value of a row from the data frame 5. Changing the value of a row in the data frame To create the data frame, first you need to import it, and then you have to specify the column name and the values in the order shown below: import pandas as pd Let’s create a new data frame. I am storing the company name, Founders, Founded and Number of Employees. You can store the data of your choice inside the data frame. df = pd.DataFrame({‘Company Name’:[‘Google’, ‘Microsoft’, ‘SpaceX’,‘Amazon’,‘Samsung’]‘Founders’:[‘Larry Page, Sergey Brin’, ‘Bill Gates, Paul Allen’,’Elon Musk’,’Jeff Bezos’, ‘Lee Byung-chul’],‘Founded’: [1998, 1975, 2002, 1994, 1938],‘Number of Employees’: [‘103,459’, ‘144,106’, ‘6,500’, ‘647,500’, ‘320,671’]})df # used to print the data frame df, or use print(df) both are same Don’t worry there is nothing complicated here, it’s just the values that might confuse you as they are just Company name, founders, founded, etc. Be careful with the brackets it can make your life miserable if you mess with it. Think now you want to add a new row to the data frame, all you can do is add the new row to the end of the data frame or any specific location of your choice. Case 1: Adding a row at the end of the data frame: To append the row at the end of the data frame, you need to use the “append method” by passing the values you want to append. Below is the official documentation of append function: pandas.pydata.org Let's create a new data frame with new values and then append that to the end of the existing data frame. df1 = pd.DataFrame({‘Company Name’:[‘WhatsApp’], ‘Founders’:[‘Jan Koum, Brian Acton’], ‘Founded’: [2009], ‘Number of Employees’: [‘50’] })df1 df1 is a new data frame that we want to append to the existing data frame df df = df.append(df1, ignore_index=True)df Case 2: Adding a new row at a specific location Let us now add a new row of values at index 3, meaning below “SpaceX” company. To do this, we can use the pandas “iloc method” by specifying the index and the values to be added. Below is the documentation of iloc method pandas.pydata.org df.iloc[3] = [‘YouTube’, ‘Chad Hurley, Steve Chen, Jawed Karim’, 2005, ‘2,800’]df With the help of iloc we can add a new row anywhere within the data frame. Some times there might be few cases where you actually need to remove unnecessary data from the database or data frame. To do so, the “drop method” in pandas gets the job done. Let’s see two cases such as deleting a row with its index and deleting a row with the help of a value. Below is the documentation of pandas drop method: pandas.pydata.org Case 1: Deleting a row with its index Now this can be done by mentioning the index inside the drop method df = df.drop([df.index[5]])df As seen above the index 5 i.e WhatsApp company’s row was removed completely. Case 2: Deleting a row with the help of a value. Now let us see how can we delete a row with its value. df = df[df.Founders != ‘Chad Hurley, Steve Chen, Jawed Karim’]df Now the YouTube company’s row is deleted with the help of providing its values. Accessing the value from the data frame is pretty trivial, all you have to do is use “loc method”. The loc method accepts the index as the parameter, by specifying it you can retrieve the value from it. Below is the documentation of loc method: pandas.pydata.org Now, let us think that we need to access the 3nd-row values, to do call loc[2] and your job is done. The rows are stored from the 0th index hence 3rd-row index is 2 (0, 1, 2). df.loc[2]Company Name SpaceX Founders Elon Musk Founded 2002 Number of Employees 6,500Name: 2, dtype: object This can be done by using the “at” method. To use the “at” method all you have to do is specify its index and the location of the column name and then the value that you need to change. Below is the documentation of the “at” method: pandas.pydata.org For example, let's think that I want to change the number of employees of Microsoft to 200,000 (I am sorry Microsoft I have to do this for my tutorial). df.at[1, ‘Number of Employees’] = ‘200,000’df There you go this is how you can use the pandas data frame as a database. You have successfully completed all the steps of the tutorial. I hope you have enjoyed reading it. There are plenty of more operations, functions or methods that can be performed on a data frame. I cannot explain every operation in one stretch, let me know if you guys need more tutorials about these concepts. Also, if you guys have some doubt, contact me or post a response on the comment section, I will respond quickly. Don’t forget to read all the documentation link of the official pandas data frame that I have provided in this tutorial. Until then see you. Have a good day.
[ { "code": null, "e": 112, "s": 46, "text": "Let us understand how to use the pandas data frame as a database." }, { "code": null, "e": 418, "s": 112, "text": "Before starting let me quickly tell about the pandas data frame: It is a python library that provides high performance, a...
Find the next occurrence of pattern in string in Julia - findnext() Method - GeeksforGeeks
23 Feb, 2021 The findnext() is an inbuilt function in julia that is used to return the next occurrence of the specified pattern in a specified string starting from the specified position. Syntax: findnext(pattern::AbstractString, string::AbstractString, start::Integer) Parameters: pattern::AbstractString: Specified pattern string::AbstractString: Specified string start::Integer: It is the start position from where matching going to be performed. Returns: It returns the next occurrence of the specified pattern in a specified string starting from the specified position. Example 1: Python # Julia program to illustrate# the use of String findnext() method # Here the pattern is "g", String is# "geeks" and position is 1Println(findnext("g", "geeks", 1)) # Here the pattern is "G", String is# "GeeksforGeeks" and position is 6Println(findnext("G", "GeeksforGeeks", 6)) # Here the pattern is "e", String is# "GeeksforGeeks" and position is 5Println(findnext("G", "GeeksforGeeks", 5)) # Here the pattern is "k", String is# "GeeksforGeeks" and position is 2Println(findnext("G", "GeeksforGeeks", 2)) Output: Example 2: Python # Julia program to illustrate# the use of String findnext() method # Here the pattern is "23", String is# "12345" and position is 1Println(findnext("23", "12345", 1)) # Here the pattern is "23", String is# "12345" and position is 2Println(findnext("23", "12345", 2)) # Here the pattern is "3", String is# "12345" and position is 5Println(findnext("3", "12345", 5)) # Here the pattern is "123", String is# "123123123" and position is 4Println(findnext("123", "123123123", 4)) Output: arorakashish0911 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Get array dimensions and size of a dimension in Julia - size() Method Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Exception handling in Julia Getting the maximum value from a list in Julia - max() Method Working with Excel Files in Julia Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Working with Date and Time in Julia Getting the absolute value of a number in Julia - abs() Method
[ { "code": null, "e": 24544, "s": 24516, "text": "\n23 Feb, 2021" }, { "code": null, "e": 24720, "s": 24544, "text": "The findnext() is an inbuilt function in julia that is used to return the next occurrence of the specified pattern in a specified string starting from the specifie...
Multiply two polynomials in C++
The coefficients of each term of the polynomial are given in an array. We need to multiply the two polynomials. Let's see an example. Input A = [1, 2, 3, 4] B = [4, 3, 2, 1] Output 4x6 + 11x5 + 20x4 + 30x3 + 20x2 + 11x1 + 4 Initialise two polynomials. Initialise two polynomials. Create a new array with a length of two polynomials. Create a new array with a length of two polynomials. Iterate over the two polynomials.Take one term from the first polynomial and multiply it with all the terms in the second polynomial.Store the result in the resultant polynomial. Iterate over the two polynomials. Take one term from the first polynomial and multiply it with all the terms in the second polynomial. Take one term from the first polynomial and multiply it with all the terms in the second polynomial. Store the result in the resultant polynomial. Store the result in the resultant polynomial. Following is the implementation of the above algorithm in C++ #include <bits/stdc++.h> using namespace std; int *multiplyTwoPolynomials(int A[], int B[], int m, int n) { int *productPolynomial = new int[m + n - 1]; for (int i = 0; i < m + n - 1; i++) { productPolynomial[i] = 0; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { productPolynomial[i + j] += A[i] * B[j]; } } return productPolynomial; } void printPolynomial(int polynomial[], int n) { for (int i = n - 1; i >= 0; i--) { cout << polynomial[i]; if (i != 0) { cout << "x^" << i; cout << " + "; } } cout << endl; } int main() { int A[] = {1, 2, 3, 4}; int B[] = {4, 3, 2, 1}; int m = 4; int n = 4; cout << "First polynomial: "; printPolynomial(A, m); cout << "Second polynomial: "; printPolynomial(B, n); int *productPolynomial = multiplyTwoPolynomials(A, B, m, n); cout << "Product polynomial: "; printPolynomial(productPolynomial, m + n - 1); return 0; } If you run the above code, then you will get the following result. First polynomial: 4x^3 + 3x^2 + 2x^1 + 1 Second polynomial: 1x^3 + 2x^2 + 3x^1 + 4 Product polynomial: 4x^6 + 11x^5 + 20x^4 + 30x^3 + 20x^2 + 11x^1 + 4
[ { "code": null, "e": 1196, "s": 1062, "text": "The coefficients of each term of the polynomial are given in an array. We need to multiply the two polynomials. Let's see an example." }, { "code": null, "e": 1202, "s": 1196, "text": "Input" }, { "code": null, "e": 1236,...
Address of a function in C or C++ - GeeksforGeeks
20 May, 2018 We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of a function by just writing the function’s name without parentheses. Please refer function pointer in C for details. Address of function main() is 004113C0Address of function funct() is 00411104 In C/C++, name of a function can be used to find address of function. // C program to addresses of a functions// using its name#include<stdio.h> void funct(){ printf("GeeksforGeeks");} int main(void){ printf("address of function main() is :%p\n", main); printf("address of function funct() is : %p\n", funct); return 0;} address of function main() is :0x40053c address of function funct() is : 0x400526 C-Functions C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24232, "s": 24204, "text": "\n20 May, 2018" }, { "code": null, "e": 24511, "s": 24232, "text": "We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of ...
Float floatToIntBits() method in Java with examples
26 Oct, 2018 The floatToIntBits() method in Float Class is a built-in function in java that returns a representation of the specified floating-point value according to the IEEE 754 floating-point “single format” bit layout. Syntax: public static int floatToIntBits(float val) Parameter: The method accepts only one parameter val which specifies a floating-point number to be converted into integer bits. Return Values: The function returns the integer bits that represent the floating-point number. Below are the special cases: If the argument is positive infinity, the result is 0x7f800000. If the argument is negative infinity, the result is 0xff800000. If the argument is NaN, the result is 0x7fc00000. Below programs illustrates the use of Float.floatToIntBits() method: Program 1: // Java program to demonstrate// Float.floatToIntBits() methodimport java.lang.*; class Gfg1 { public static void main(String args[]) { float val = 1.5f; // function call int answer = Float.floatToIntBits(val); // print System.out.println(val + " in int bits: " + answer); }} 1.5 in int bits: 1069547520 Program 2: // Java program to demonstrate// Float.floatToIntBits() method import java.lang.*; class Gfg1 { public static void main(String args[]) { float val = Float.POSITIVE_INFINITY; float val1 = Float.NEGATIVE_INFINITY; float val2 = Float.NaN; // function call int answer = Float.floatToIntBits(val); // print System.out.println(val + " in int bits: " + answer); // function call answer = Float.floatToIntBits(val1); // print System.out.println(val1 + " in int bits: " + answer); // function call answer = Float.floatToIntBits(val); // print System.out.println(val2 + " in int bits: " + answer); }} Infinity in int bits: 2139095040 -Infinity in int bits: -8388608 NaN in int bits: 2139095040 Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#floatToIntBits(float) java-basics Java-Float Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java Initialize an ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Oct, 2018" }, { "code": null, "e": 239, "s": 28, "text": "The floatToIntBits() method in Float Class is a built-in function in java that returns a representation of the specified floating-point value according to the IEEE 754 floatin...
React Native Text Input Component
25 May, 2021 In this article, We are going to see how to create a TextInput in react-native. For this, we are going to use the TextInput component. It is a basic component that is used to collect data from users. For creating a TextInput in react native we have to import the TextInput component from React Native. import { TextInput } from 'react-native' Syntax: <TextInput // Define TextInput property /> Props for TextInput Component: allowFontScaling: This property will specify if the fonts will scale to respect Text Size accessibility settings. The default value for this is true. autoCapitalize: This property is used to automatically capitalize the letters. We can pass none, sentences, words, Characters as a parameter for it. By Default, It capitalizes the first letter of each sentence. autoCompleteType: This property will provide autofill for the input by giving suggestions. Some values that autoCompleteType support are: off, password, username, postal-code, ’email’, street-address, cc-number, cc-exp-month, name, etc. By default, autoCompleteType is true in all android devices. To disable autocomplete, we need to make it false. autoCorrect: This property takes a boolean value. It corrects the input field automatically but if it is false, it will not correct it. The default value is true. autoFocus: If it is true, It will focus the input on componentDidMount. In the default case, it will be false, blurOnSubmit: It is used to blur the input field on submission. For single-line fields, the default value is true but for multiline fields it is false. caretHidden: In default case, it is false. But if it is true, the caret will be hidden. clearButtonMode: It is used when we want the clear button to appear on the right side of the text view. This is for only the single-line TextInput components. The default value is never. clearTextOnFocus: This property is used when we want to clear the text field automatically when the editing begins. contextMenuHidden: In default case, it is false. But if it is true, the context menu will be hidden. dataDetectorTypes: This property is used to determine the type of data that is converted to clickable URLs in the text input. By default, no data types are detected. defaultValue: This property will provide an initial value when the user starts typing. It is useful for use-cases where users do not want to write the entire value. disableFullscreenUI: In the default case, it is false. This property allows users to edit the text inside the full-screen text input mode. To disable this feature we need to make it true. editable: If we do not want the user to edit the text input then we can make this editable value false. It will not allow users to edit text from the front end. By default, the value is true. enablesReturnKeyAutomatically: This property will let the keyboard automatically enable the return key when there is text else the return key will be disabled. The default value of this is false. importantForAutofill: This tells which fields to be included in the view structure for autofill purposes. By default, it is auto. inlineImageLeft: It is used to render the image on the left. inlineImagePadding: This property is used for providing padding between the inline image and the textInput. keyboardAppearance: It is used to specify the color of the keyboard. The color can be the default, light, and dark. keyboardType: This property is used to determine the type of keyboard that is going to open. maxFontSizeMultiplier: When allowFontScaling is enabled, this is used to specify the largest scale a font can reach. maxLength: It is used when we do not want to exceed the particular number of characters. So we provide a fixed maximum length to it. multiline: This allows to have multiple lines in text input. By default, the value is false. numberOfLines: It is used when we want the fixed number of lines in the TextInput. onBlur: It is used when the text input is blurred by calling a callback function where we write stuff. onChange: Whenever there is any change in the TextInput, this will call a callback function. onChangeText: Whenever there is any change in the text of TextInput, this will call a callback function. onContentSizeChange: When the text input’s content size changes ,it calls a callback function. onEndEditing: When the text input’s ends, it calls a callback function. onPressOut: It is a callback function that is called when a key is released. onFocus: When the text input is focused, it calls a callback function. onKeyPress: It calls a callback function when a key is pressed where we perform the task. onLayout: It is a function that is invoked when the layout changes. onScroll: It is a function that is invoked on content scroll. onSelectionChange: When the text input selection is changed. It calls for a callback function to perform the related task. onSubmitEditing: When the text input’s submit button is pressed. It calls a callback function to perform a task related to it. placeholder: It provides the strings which will be rendered for the first before entering the text input. placeholderTextColor: It provides the text color of the placeholder. returnKeyLabel: It sets the return key to the label. returnKeyType: It determines the look of the return key. Some values of returnKeyType are ‘done’, ‘go’, ‘next’, ‘search’, ‘send’, ‘none’, ‘previous’, ‘default’, ’emergency-call’, ‘google’, ‘join’, ‘route’, ‘yahoo’. scrollEnabled: It enables the scrolling of the text view. By default, it is true. secureTextEntry: It is used to secure sensitive data like passwords by obscuring the entered text. The default value is false. selectTextOnFocus: It is used to select all text will automatically, when we focus the TextInput. showSoftInputOnFocus: If this is false, then when we focused the field. It prevents the soft keyboard from showing. The default value for this is true. spellCheck: It enables the spell-check style (i.e. red underlines). To disable this we have to make this false. The default value of this is inherited from autoCorrect. textAlign: This property is used to align the input text. Values for textAlign are: left, right and center. textContentType: It gives the information about the content that users enter. passwordRules: It is used when we have certain requirements for the passwords, we give this requirement to OS. style: It is the custom style for input text. All the text styles are not supported in this. underlineColorAndroid: It gives the color to the underline of TextInput. value: It is the value for the text input. Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init myapp Step 2: Now create a project by the following command. expo init myapp Step 3: Now go into your project folder i.e. myappcd myapp Step 3: Now go into your project folder i.e. myapp cd myapp Project Structure: Example: Now let’s implement the TextInput component. Inside that component whenever there is any text change it calls the function handleText that will set the name state to text. This text will be written in the Text component. App.js import React, { Component } from 'react';import {View,Text,TextInput } from 'react-native'; export default class App extends Component { state={ name:"", } handleText=(text)=>{ this.setState({name:text}); } render() { return ( <View> <TextInput style={{height: 50, borderColor: 'red', borderWidth: 3,margin:10, fontSize:35,}} onChangeText={(text) =>this.handleText(text)} placeholder="Enter Name" value={this.state.text} /> <Text style={{fontSize:32,color:'green'}}> Your name is :{this.state.name} </Text> </View> ); }} Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/textinput Picked React-Native 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) Difference Between PUT and PATCH Request ReactJS | Router How to float three div side by side using CSS? Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 May, 2021" }, { "code": null, "e": 229, "s": 28, "text": "In this article, We are going to see how to create a TextInput in react-native. For this, we are going to use the TextInput component. It is a basic component that is used to ...
How to center the absolutely positioned element in div using CSS ?
03 Nov, 2021 In this article, we will know how to centre the absolutely positioned element using the <div> tag in CSS, & will understand their implementation through the examples. Sometimes we need to place an element into the centre with absolute position, relative to its nearest positioned ancestor in HTML to make it look more presentable. For centring an absolute positioned element in div we use the following examples. Example 1: This example demonstrates the centring of an absolute positioned element using the <div> tag. HTML <!DOCTYPE html><html> <head> <style> #content { position: absolute; left: 50%; transform: translateX(-50%) } </style></head> <body> <div id="content"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> </div></body> </html> Output: Here, the left is given 50% to place it in the centre horizontal. Transform is used to pull back the item with half of its width to place it exactly in the centre from the middle of the element. left: 50% is relative to the parent element while the translate transform is relative to the elements width/height. Example 2: This example demonstrates the centring of the absolutely positioned element in horizontal & vertical directions in the <div> tag. HTML <!DOCTYPE html><html> <head> <style> .content { height: 400px; position: relative; border: 4px solid green; } .content img { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } </style></head> <body> <p> Centering an absolute positioned element inside a div both horizontally and vertically </p> <div class="content"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> </div></body> </html> Output: Here left and the top is given 50% to place it in the centre horizontally and vertically. Transform is used to pull back the item with half of its width to place it exactly in the centre from the middle of the element. Therefore transform: translate is given -50% for both horizontal and vertical to adjust it centrally. ysachin2314 sweetyty bhaskargeeksforgeeks CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Nov, 2021" }, { "code": null, "e": 441, "s": 28, "text": "In this article, we will know how to centre the absolutely positioned element using the <div> tag in CSS, & will understand their implementation through the examples. Sometime...
First Come, First Serve – CPU Scheduling | (Non-preemptive)
26 Apr, 2022 FCFS Scheduling: Simplest CPU scheduling algorithm that schedules according to arrival times of processes. First come first serve scheduling algorithm states that the process that requests the CPU first is allocated the CPU first. It is implemented by using the FIFO queue. When a process enters the ready queue, its PCB is linked onto the tail of the queue. When the CPU is free, it is allocated to the process at the head of the queue. The running process is then removed from the queue. FCFS is a non-preemptive scheduling algorithm. Characteristics of FCFS: FCFS supports non-preemptive and preemptive CPU scheduling algorithm. Tasks are always executed on a First-come, First-serve concept. FCFS is easy to implement and use. This algorithm is not much efficient in performance, and the wait time is quite high. The waiting time for first process is 0 as it is executed first. The waiting time for upcoming process can be calculated by: wt[i] = ( at[i – 1] + bt[i – 1] + wt[i – 1] ) – at[i] where wt[i] = waiting time of current process at[i-1] = arrival time of previous process bt[i-1] = burst time of previous process wt[i-1] = waiting time of previous process at[i] = arrival time of current process The Average waiting time can be calculated by: Average Waiting Time = (sum of all waiting time)/(Number of processes) Example-1: Consider the following table of arrival time and burst time for five processes P1, P2, P3, P4 and P5. The First come First serve CPU Scheduling Algorithm will work on the basis of steps as mentioned below: Step 0: At time = 0, The process begins with P1 As it has arrival time 0 Step 1: At time = 1, The process P2 arrives But process P1 still executing, Thus, P2 kept in a waiting table and wait for its execution. Step 3: At time = 2, The process P3 arrives and kept in a waiting queue While process P1 is still executing as its burst time is 4. Step 4: At time = 3, The process P4 arrives and kept in the waiting queue While process P1 is still executing as its burst time is 4 Step 5: At time = 4, The process P1 completes its execution Process P5 arrives in waiting queue while process P2 starts executing Step 6: At time = 5, The process P2 completes its execution Step 7: At time = 7, Process P3 starts executing, it has burst time of 1 thus, it completes execution at time interval 8 Step 8: At time 8, The process of P3 completes its execution Process P4 starts executing, it has burst time of 2 thus, it completes execution at time interval 10. Step 9: At time 10, The process P4 completes its execution Process P5 starts executing, it has burst time of 5 thus, it completes execution at time interval 15. Step 10: At time 15, Process P5 will finish its execution. The overall execution of the processes will be as shown below: Gantt chart for above execution: Gantt chart for First come First serve Scheduling Waiting Time = Start time – Arrival time P1 = 0 – 0 = 0P2 = 4 – 1 = 3P3 = 7 – 2 = 5P4 = 8 – 3 = 5P5 = 10 – 4 = 6 Average waiting time = 0 + 3 + 5 + 5+ 6 / 5 = 19 / 5 = 3.8 Program for First Come First Serve algorithm: C++ Java Python3 C# // C++ program to Calculate Waiting// Time for given Processes#include <iostream>using namespace std; // Function to Calculate waiting time// and average waiting timevoid CalculateWaitingTime(int at[], int bt[], int N){ // Declare the array for waiting // time int wt[N]; // Waiting time for first process // is 0 wt[0] = 0; // Print waiting time process 1 cout << "PN\t\tAT\t\t" << "BT\t\tWT\n\n"; cout << "1" << "\t\t" << at[0] << "\t\t" << bt[0] << "\t\t" << wt[0] << endl; // Calculating waiting time for // each process from the given // formula for (int i = 1; i < 5; i++) { wt[i] = (at[i - 1] + bt[i - 1] + wt[i - 1]) - at[i]; // Print the waiting time for // each process cout << i + 1 << "\t\t" << at[i] << "\t\t" << bt[i] << "\t\t" << wt[i] << endl; } // Declare variable to calculate // average float average; float sum = 0; // Loop to calculate sum of all // waiting time for (int i = 0; i < 5; i++) { sum = sum + wt[i]; } // Find average waiting time // by dividing it by no. of process average = sum / 5; // Print Average Waiting Time cout << "\nAverage waiting time = " << average;} // Driver codeint main(){ // Number of process int N = 5; // Array for Arrival time int at[] = { 0, 1, 2, 3, 4 }; // Array for Burst Time int bt[] = { 4, 3, 1, 2, 5 }; // Function call to find // waiting time CalculateWaitingTime(at, bt, N); return 0;} // Java program to Calculate Waiting// Time for given Processesclass GFG{ // Function to Calculate waiting time// and average waiting timestatic void CalculateWaitingTime(int at[], int bt[], int N){ // Declare the array for waiting // time int []wt = new int[N]; // Waiting time for first process // is 0 wt[0] = 0; // Print waiting time process 1 System.out.print("P.No.\tArrival Time\t" + "Burst Time\tWaiting Time\n"); System.out.print("1" + "\t\t" + at[0]+ "\t\t" + bt[0]+ "\t\t" + wt[0] +"\n"); // Calculating waiting time for // each process from the given // formula for (int i = 1; i < 5; i++) { wt[i] = (at[i - 1] + bt[i - 1] + wt[i - 1]) - at[i]; // Print the waiting time for // each process System.out.print(i + 1+ "\t\t" + at[i] + "\t\t" + bt[i]+ "\t\t" + wt[i] +"\n"); } // Declare variable to calculate // average float average; float sum = 0; // Loop to calculate sum of all // waiting time for (int i = 0; i < 5; i++) { sum = sum + wt[i]; } // Find average waiting time // by dividing it by no. of process average = sum / 5; // Print Average Waiting Time System.out.print("Average waiting time = " + average);} // Driver codepublic static void main(String[] args){ // Number of process int N = 5; // Array for Arrival time int at[] = { 0, 1, 2, 3, 4 }; // Array for Burst Time int bt[] = { 4, 3, 1, 2, 5 }; // Function call to find // waiting time CalculateWaitingTime(at, bt, N);}} // This code is contributed by 29AjayKumar # Python3 program to Calculate Waiting# Time for given Processes # Function to Calculate waiting time# and average waiting timedef CalculateWaitingTime(at, bt, N): # Declare the array for waiting # time wt = [0]*N; # Waiting time for first process # is 0 wt[0] = 0; # Print waiting time process 1 print("P.No.\tArrival Time\t" , "Burst Time\tWaiting Time"); print("1" , "\t\t" , at[0] , "\t\t" , bt[0] , "\t\t" , wt[0]); # Calculating waiting time for # each process from the given # formula for i in range(1,5): wt[i] = (at[i - 1] + bt[i - 1] + wt[i - 1]) - at[i]; # Print the waiting time for # each process print(i + 1 , "\t\t" , at[i] , "\t\t" , bt[i] , "\t\t" , wt[i]); # Declare variable to calculate # average average = 0.0; sum = 0; # Loop to calculate sum of all # waiting time for i in range(5): sum = sum + wt[i]; # Find average waiting time # by dividing it by no. of process average = sum / 5; # Print Average Waiting Time print("Average waiting time = " , average); # Driver codeif __name__ == '__main__': # Number of process N = 5; # Array for Arrival time at = [ 0, 1, 2, 3, 4 ]; # Array for Burst Time bt = [ 4, 3, 1, 2, 5 ]; # Function call to find # waiting time CalculateWaitingTime(at, bt, N); # This code is contributed by 29AjayKumar // C# program to Calculate Waiting// Time for given Processesusing System; class GFG{ // Function to Calculate waiting time// and average waiting timestatic void CalculateWaitingTime(int []at, int []bt, int N){ // Declare the array for waiting // time int []wt = new int[N]; // Waiting time for first process // is 0 wt[0] = 0; // Print waiting time process 1 Console.Write("P.No.\tArrival Time\t" + "Burst Time\tWaiting Time\n"); Console.Write("1" + "\t\t" + at[0]+ "\t\t" + bt[0]+ "\t\t" + wt[0] +"\n"); // Calculating waiting time for // each process from the given // formula for (int i = 1; i < 5; i++) { wt[i] = (at[i - 1] + bt[i - 1] + wt[i - 1]) - at[i]; // Print the waiting time for // each process Console.Write(i + 1+ "\t\t" + at[i] + "\t\t" + bt[i]+ "\t\t" + wt[i] +"\n"); } // Declare variable to calculate // average float average; float sum = 0; // Loop to calculate sum of all // waiting time for (int i = 0; i < 5; i++) { sum = sum + wt[i]; } // Find average waiting time // by dividing it by no. of process average = sum / 5; // Print Average Waiting Time Console.Write("Average waiting time = " + average);} // Driver codepublic static void Main(String[] args){ // Number of process int N = 5; // Array for Arrival time int []at = { 0, 1, 2, 3, 4 }; // Array for Burst Time int []bt = { 4, 3, 1, 2, 5 }; // Function call to find // waiting time CalculateWaitingTime(at, bt, N);}} // This code is contributed by 29AjayKumar PN AT BT WT 1 0 4 0 2 1 3 3 3 2 1 5 4 3 2 5 5 4 5 6 Average waiting time = 3.8 Complexity Analysis: Time Complexity: O(N) Auxiliary Space: O(N) Advantages of FCFS: The simplest and basic form of CPU Scheduling algorithm Easy to implement First come first serve method Disadvantages of FCFS: As it is a Non-preemptive CPU Scheduling Algorithm, hence it will run till it finishes the execution. Average waiting time in the FCFS is much higher than the others Not very efficient due to its simplicity Processes which are at the end of the queue, have to wait longer to finish. 29AjayKumar ldsouza2504 pankajsharmagfg simmytarika5 surinderdawra388 kashishkumar2 Algorithms Operating Systems Operating Systems Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Difference between BFS and DFS Recursion Cache Memory in Computer Organization LRU Cache Implementation 'crontab' in Linux with Examples Cd cmd command Memory Management in Operating System
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Apr, 2022" }, { "code": null, "e": 69, "s": 52, "text": "FCFS Scheduling:" }, { "code": null, "e": 589, "s": 69, "text": "Simplest CPU scheduling algorithm that schedules according to arrival times of processes. ...
Python | Convert case of elements in a list of strings
13 Feb, 2019 Given a list of strings, write a Python program to convert all string from lowercase/uppercase to uppercase/lowercase. Input : ['GeEk', 'FOR', 'gEEKS'] Output: ['geeks', 'for', 'geeks'] Input : ['fun', 'Foo', 'BaR'] Output: ['FUN', 'FOO', 'BAR'] Method #1 : Convert Uppercase to Lowercase using map function # Python code to convert all string# from uppercase to lowercase. # Using map functionout = map(lambda x:x.lower(), ['GeEk', 'FOR', 'gEEKS']) # Converting it into listoutput = list(out) # printing outputprint(output) ['geek', 'for', 'geeks'] Method #2: Convert Lowercase to Uppercase using List comprehension # Python code to convert all string# from uppercase to lowercase. # Initialisationinput = ['fun', 'Foo', 'BaR'] # Convertinglst = [x.upper() for x in input] # printing outputprint(lst) ['FUN', 'FOO', 'BAR'] Python list-programs python-list python-string 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 | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2019" }, { "code": null, "e": 147, "s": 28, "text": "Given a list of strings, write a Python program to convert all string from lowercase/uppercase to uppercase/lowercase." }, { "code": null, "e": 275, "s": 147, ...
Ripper Algorithm
26 Nov, 2020 RIPPER Algorithm : It stands for Repeated Incremental Pruning to Produce Error Reduction. The Ripper Algorithm is a Rule-based classification algorithm. It derives a set of rules from the training set. It is a widely used rule induction algorithm. Uses of Ripper Algorithm: It works well on datasets with imbalanced class distributions. In a dataset, if we have several records out of which most of the records belong to a particular class and the remaining records belong to different classes then the dataset is said to have an imbalanced distribution of class.It works well with noisy datasets as it uses a validation set to prevent model overfitting. It works well on datasets with imbalanced class distributions. In a dataset, if we have several records out of which most of the records belong to a particular class and the remaining records belong to different classes then the dataset is said to have an imbalanced distribution of class. It works well with noisy datasets as it uses a validation set to prevent model overfitting. Case I: Training records belong to only two classes Among the records given, it identifies the majority class ( which has appeared the most ) and takes this class as the default class. For example: if there are 100 records and 80 belong to Class A and 20 to Class B. then Class A will be default class. For the other class, it tries to learn/derive various rules to detect that class. Case II: Training records have more than two classes ( Multiple Classes ) Consider all the classes that are available and then arrange them on the basis of their frequency in a particular order ( say increasing). Consider the classes are arranged as – C1,C2,C3,......,Cn C1 - least frequent Cn - most frequent The class with the maximum frequency (Cn) is taken as the default class. How the rule is Derived: In the first instance, it tries to derive rules for those records which belong to class C1. Records belonging to C1 will be considered as positive examples(+ve) and other classes will be considered as negative examples(-ve). Sequential Covering Algorithm is used to generate the rules that discriminate between +ve and -ve examples. Next, at this junction Ripper tries to derive rules for C2 distinguishing it from the other classes. This process is repeated until stopping criteria is met, which is- when we are left with Cn (default class). Ripper extracts rules from minority class to the majority class. Rule Growing in RIPPER Algorithm: Ripper makes use of general to a specific strategy of growing rules. It starts from an empty rule and goes on adding the best conjunct to the rule antecedent. For evaluation of conjuncts the metric is chosen is FOIL’s Information Gain. Using this the best conjunct is chosen. Stopping Criteria for adding the conjuncts – when the rule starts covering the negative (-ve) examples. The new rule is pruned based on its performance on the validation set. Rule Pruning Using RIPPER: We need to identify whether a particular rule should be pruned or not. To determine this a metric is used, which is – (P-N)/(P+N) P = number of positive examples in the validation set covered by the rule. N = number of negative examples in the validation set covered by the rule. Whenever a conjunct is added or removed we calculate the value of the above metric for the original rule (before adding/removing) and the new rule (after adding/removing). If the value of the new rule is better than the original rule then we can add/remove the conjunct. Otherwise, the conjunct will not be added/removed. Pruning is done starting from the rightmost end. For example: Consider a rule – ABCD ---> Y ,where A,B,C,D are conjuncts and Y is the class. First it will remove the conjunct D and measure the metric value. If the quality of the metric is improved the conjunct D is removed. If the quality does not improve then the pruning is checked for CD,BCD and so on. Building the Ruleset in RIPPER Algorithm: After a rule is derived, all the positive and negative examples covered by the rule are eliminated. The rule is then added into the ruleset until it doesn’t violate the stopping condition. The stopping criteria which we can use are – A) Minimum description length principle: For transferring the information from one end to another end you require a minimum number of bits. We want the rule to be represented using a minimum number of bits. If the new rule increases the total description length of the ruleset by d bits ( by default d is 64 bits), then RIPPER stops adding rules into the ruleset. B) Error Rate – We will consider the rule and calculate its error rate (misclassification) w.r.t the validation set. The error rate of a particular rule should not exceed more than 50%. This is how a RIPPER Algorithm works. For any queries do leave a comment down below. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 47, "s": 28, "text": "RIPPER Algorithm :" }, { "code": null, "e": 276, "s": 47, "text": "It stands for Repeated Incremental Pruning to Produce Error Reduction. The Ripper Algorit...
Python | Split list into lists by particular value
25 Apr, 2019 The splitting of lists is quite common utility nowadays and there can be many applications and use cases of the same. Along with these always come the variations. One such variation can be split the list by particular value. Let’s discuss a certain way in which list split can be performed. Method : Using list comprehension + zip() + slicing + enumerate() This problem can be solved in two parts, in first part we get the index list by which split has to be performed using enumerate function. And then we can join the values according to the indices using zip and list slicing. # Python3 code to demonstrate# Split list into lists by particular value# Using list comprehension + zip() + slicing + enumerate() # initializing listtest_list = [1, 4, 5, 6, 4, 5, 6, 5, 4] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + zip() + slicing + enumerate()# Split list into lists by particular valuesize = len(test_list)idx_list = [idx + 1 for idx, val in enumerate(test_list) if val == 5] res = [test_list[i: j] for i, j in zip([0] + idx_list, idx_list + ([size] if idx_list[-1] != size else []))] # print resultprint("The list after splitting by a value : " + str(res)) The original list : [1, 4, 5, 6, 4, 5, 6, 5, 4] The list after splitting by a value : [[1, 4, 5], [6, 4, 5], [6, 5], [4]] Python list-programs Python Python Programs 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
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Apr, 2019" }, { "code": null, "e": 345, "s": 54, "text": "The splitting of lists is quite common utility nowadays and there can be many applications and use cases of the same. Along with these always come the variations. One such va...
How to pass an array by value in C ?
21 Dec, 2018 In C, array name represents address and when we pass an array, we actually pass address and the parameter receiving function always accepts them as pointers (even if we use [], refer this for details). How to pass array by value, i.e., how to make sure that we have a new copy of array when we pass it to function?This can be done by wrapping the array in a structure and creating a variable of type of that structure and assigning values to that array. After that, passing the variable to some other function and modifying it as per requirements. Note that array members are copied when passed as parameter, but dynamic arrays are not. So this solution works only for non-dynamic arrays (created without new or malloc). Let’s see an example to demonstrate the above fact using a C program: // C program to demonstrate passing an array// by value using structures.#include<stdio.h>#include<stdlib.h> # define SIZE 5 // A wrapper for array to make sure that array// is passed by value.struct ArrayWrapper{ int arr[SIZE];}; // An array is passed by value wrapped in tempvoid modify(struct ArrayWrapper temp){ int *ptr = temp.arr; int i; // Display array contents printf("In 'modify()', before modification\n"); for (i = 0; i < SIZE; ++i) printf("%d ", ptr[i]); printf("\n"); // Modify the array for (i = 0; i < SIZE; ++i) ptr[i] = 100; // OR *(ptr + i) printf("\nIn 'modify()', after modification\n"); for (i = 0; i < SIZE; ++i) printf("%d ", ptr[i]); // OR *(ptr + i)} // Driver codeint main(){ int i; struct ArrayWrapper obj; for (i=0; i<SIZE; i++) obj.arr[i] = 10; modify(obj); // Display array contents printf("\n\nIn 'Main', after calling modify() \n"); for (i = 0; i < SIZE; ++i) printf("%d ", obj.arr[i]); // Not changed printf("\n"); return 0;} Output: In 'modify()', before modification 10 10 10 10 10 In 'modify()', after modification 100 100 100 100 100 In 'Main', after calling modify() 10 10 10 10 10 This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Arrays C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C What is the purpose of a function prototype? C Language Introduction Command line arguments in C/C++
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Dec, 2018" }, { "code": null, "e": 256, "s": 54, "text": "In C, array name represents address and when we pass an array, we actually pass address and the parameter receiving function always accepts them as pointers (even if we use [...
Particle Swarm Optimization (PSO) – An Overview
23 Jun, 2021 The process of finding optimal values for the specific parameters of a given system to fulfill all design requirements while considering the lowest possible cost is referred to as an optimization. Optimization problems can be found in all fields of science. Conventional optimization algorithms (Deterministic algorithms) have some limitations such as: single-based solutions converging to local optima unknown search space issues To overcome these limitations, many scholars and researchers have developed several metaheuristics to address complex/unsolved optimization problems. Example: Particle Swarm Optimization, Grey wolf optimization, Ant colony Optimization, Genetic Algorithms, Cuckoo search algorithm, etc. The Introduction to Particle Swarm Optimization (PSO) article explained the basics of stochastic optimization algorithms and explained the intuition behind particle swarm optimization (PSO). This article aims to deep dive into particle swarm optimization (PSO). Particle Swarm Optimization (PSO) is a powerful meta-heuristic optimization algorithm and inspired by swarm behavior observed in nature such as fish and bird schooling. PSO is a Simulation of a simplified social system. The original intent of PSO algorithm was to graphically simulate the graceful but unpredictable choreography of a bird flock. In nature, any of the bird’s observable vicinity is limited to some range. However, having more than one birds allows all the birds in a swarm to be aware of the larger surface of a fitness function. Let’s mathematically model, the above-mentioned principles to make the swarm find the global minima of a fitness function Each particle in particle swarm optimization has an associated position, velocity, fitness value. Each particle keeps track of the particle_bestFitness_value particle_bestFitness_position. A record of global_bestFitness_position and global_bestFitness_value is maintained. Fig 1: Data structure to store Swarm population Fig 2: Data structure to store ith particle of Swarm Parameters of problem: Number of dimensions (d) Lower bound (minx) Upper bound (maxx) Hyperparameters of the algorithm: Number of particles (N) Maximum number of iterations (max_iter) Inertia (w) Cognition of particle (C1) Social influence of swarm (C2) Algorithm: Step1: Randomly initialize Swarm population of N particles Xi ( i=1, 2, ..., n) Step2: Select hyperparameter values w, c1 and c2 Step 3: For Iter in range(max_iter): # loop max_iter times For i in range(N): # for each particle: a. Compute new velocity of ith particle swarm[i].velocity = w*swarm[i].velocity + r1*c1*(swarm[i].bestPos - swarm[i].position) + r2*c2*( best_pos_swarm - swarm[i].position) b. If velocity is not in range [minx, max] then clip it if swarm[i].velocity < minx: swarm[i].velocity = minx elif swarm[i].velocity[k] > maxx: swarm[i].velocity[k] = maxx c. Compute new position of ith particle using its new velocity swarm[i].position += swarm[i].velocity d. Update new best of this particle and new best of Swarm if swarm[i].fitness < swarm[i].bestFitness: swarm[i].bestFitness = swarm[i].fitness swarm[i].bestPos = swarm[i].position if swarm[i].fitness < best_fitness_swarm best_fitness_swarm = swarm[i].fitness best_pos_swarm = swarm[i].position End-for End -for Step 4: Return best particle of Swarm simmytarika5 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI k-nearest neighbor algorithm in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2021" }, { "code": null, "e": 310, "s": 52, "text": "The process of finding optimal values for the specific parameters of a given system to fulfill all design requirements while considering the lowest possible cost is referred ...
queue::swap() in C++ STL
08 Aug, 2019 Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed. queue::swap()swap() function is used to exchange the contents of two queues but the queues must be of same type, although sizes may differ. Syntax: queue1.swap(queue2) OR swap(queue1, queue2) Parameters: queue1 is the first queue object. queue2 is the second queue object. Return value: None Examples: Input : queue1 = {1, 2, 3, 4} queue2 = {5, 6, 7, 8} queue1.swap(queue2); Output : queue1 = {5, 6, 7, 8} queue2 = {1, 2, 3, 4} Input : queue1 = {'a', 'b', 'c', 'd', 'e'} queue2 = {'f', 'g', 'h', 'i'} queue1.swap(queue2); Output : queue1 = {'f', 'g', 'h', 'i'} queue2 = {'a', 'b', 'c', 'd', 'e'} Errors and Exceptions 1. It throws an error if the queues are not of the same type.2. It has a basic no exception throw guarantee otherwise. // CPP program to illustrate// Implementation of swap() function#include <bits/stdc++.h>using namespace std; int main(){ // Take any two queues queue<char> queue1, queue2; int v = 96; for (int i = 0; i < 5; i++) { queue1.push(v + 1); v++; } for (int i = 0; i < 4; i++) { queue2.push(v + 1); v++; } // Swap elements of queues queue1.swap(queue2); // Print the first queue cout << "queue1 = "; while (!queue1.empty()) { cout << queue1.front() << " "; queue1.pop(); } // Print the second set cout << endl << "queue2 = "; while (!queue2.empty()) { cout << queue2.front() << " "; queue2.pop(); } return 0;} Output: queue1 = f g h i queue2 = a b c d e Time complexity: Linear i.e. O(n) AnshumanSrivastava1 cpp-queue STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Aug, 2019" }, { "code": null, "e": 329, "s": 53, "text": "Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO)...
What is first child in CSS ?
15 Mar, 2021 The first-child is a pseudo class in CSS which represents the first element among a group of sibling elements. The :first-child Selector is used to target the first child element of it’s parent for styling. Syntax: :first-child { //property } Example: HTML <!DOCTYPE html> <html> <head> <style> p:first-child { background: limegreen; color: white; font-style: italic; font-size: 1.875em; } </style> </head> <body> <p>I am first child.</p> <p>I am second child.</p> <p>I am third child.</p> <p>I am last child.</p></body> </html> Output: CSS-Questions CSS-Selectors Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery Installation of Node.js on Linux 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
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2021" }, { "code": null, "e": 235, "s": 28, "text": "The first-child is a pseudo class in CSS which represents the first element among a group of sibling elements. The :first-child Selector is used to target the first child elem...
Properties getProperty(key, defaultValue) method in Java with Examples - GeeksforGeeks
30 Sep, 2019 The getProperty(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue. Syntax: public String getProperty(String key, String defaultValue) Parameters: This method accepts two parameter: key: whose mapping is to be checked in this Properties object. defaultValue: which is the default mapping of the key Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns the defaultValue. Below programs illustrate the getProperty(key, defaultValue) method: Program 1: // Java program to demonstrate// getProperty(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Properties: " + properties.toString()); // Getting the value of Pen System.out.println("Value of Pen: " + properties .getProperty("Pen", 200)); // Getting the value of Phone System.out.println("Value of Phone: " + properties .getProperty("Phone", 200)); }} Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400} Value of Pen: 10 Value of Phone: 200 Program 2: // Java program to demonstrate// getProperty(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, "100RS"); properties.put(2, "500RS"); properties.put(3, "1000RS"); // Print Properties details System.out.println("Current Properties: " + properties.toString()); // Getting the value of 1 System.out.println("Value of 1: " + properties .getProperty(1, "200RS")); // Getting the value of 5 System.out.println("Value of 5: " + properties .getProperty(5, "200RS")); }} Current Properties: {3=1000RS, 2=500RS, 1=100RS} Value of 1: 100RS Value of 5: 200RS References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getProperty-java.lang.String-java.lang.String- Akanksha_Rai Java - util package Java-Functions Java-Properties Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n30 Sep, 2019" }, { "code": null, "e": 25534, "s": 25225, "text": "The getProperty(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This...
Python program to Recursively scrape all the URLs of the website - GeeksforGeeks
26 Mar, 2020 In this tutorial we will see how to we can recursively scrape all the URLs from the website Recursion in computer science is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller instances at programming time. Note: For more information, refer to Recursion Requests :Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs.pip install requests pip install requests Beautiful Soup:Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree.pip install beautifulsoup4 pip install beautifulsoup4 Code : from bs4 import BeautifulSoupimport requests # listsurls=[] # function createddef scrape(site): # getting the request from url r = requests.get(site) # converting the text s = BeautifulSoup(r.text,"html.parser") for i in s.find_all("a"): href = i.attrs['href'] if href.startswith("/"): site = site+href if site not in urls: urls.append(site) print(site) # calling it self scrape(site) # main functionif __name__ =="__main__": # website to be scrape site="http://example.webscraping.com//" # calling function scrape(site) Output : python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25577, "s": 25549, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25669, "s": 25577, "text": "In this tutorial we will see how to we can recursively scrape all the URLs from the website" }, { "code": null, "e": 25946, "s": 25669, "text":...
response.ok - Python requests - GeeksforGeeks
31 Jul, 2020 response.ok returns True if status_code is less than 400, otherwise False. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.ok out of a response object. To illustrate use of response.ok, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC. Download and Install Python 3 Latest Version How to install requests in Python – For windows, linux, mac # import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print if status code is less than 400print(response.ok) Save above file as request.py and run using Python request.py Check that True which matches the condition of request being less than or equal to 400. There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. requests.status_code If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n31 Jul, 2020" }, { "code": null, "e": 25974, "s": 25537, "text": "response.ok returns True if status_code is less than 400, otherwise False. Python requests are generally used to fetch the content from a particular resource URI. ...
C# Program to Get the Environment Variables Using Environment Class - GeeksforGeeks
16 Nov, 2021 In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the Operating System using the Environment class and GetEnvironmentVariable() method is one of them. This method is used to find the environment variables. It is overloaded in two different ways: 1. GetEnvironmentVariable(String): This method is used to find the environment variables of the current process. It will find all the environment variables with their values. Always remember the name of the environment variable is case sensitive in macOS and Linux but in Windows, they do not case sensitive. Syntax: public static string? GetEnvironmentVariable (string varstring); Where varstring parameter is of string type and it will represent the name of the environment variable. Return: This method will return the name of the environment variable. Or return null when the environment variable is not found. Exceptions: This method will throw the following exception: SecurityException: This exception occurs only when the caller does not have the given permission to perform this operation. ArgumentNullException: This exception occurs when the variable is null. 2. GetEnvironmentVariable(String, EnvironmentVariableTarget): This method is used to find the environment variables of the current process, or from the Windows OS registry key for the local machine or current user. Always remember the name of the environment variable is case sensitive in macOS and Linux but in Windows, they do not case sensitive. Syntax: public static string? GetEnvironmentVariable (string varstr, EnvironmentVariableTarget t); This method will two parameters named varstr and t. Here, varstr represents the name of the environment variable and t represents the EnvironmentVariableTarget value. Return: This method will return the name of the environment variable. Or return null when the environment variable is not found. Exceptions: This method will throw the following exception: SecurityException: This exception occurs only when the caller does not have the given permission to perform this operation. ArgumentNullException: This exception occurs when the variable is null. ArgumentException: This exception occurs when the target is not valid EnvironmentVariableTarget value. Example: C# // C# program to illustrate how to find the // environment variables Using Environment Classusing System;using System.Collections; class GFG{ static public void Main(){ // Create a IDictionary to get the environment variables IDictionary data = Environment.GetEnvironmentVariables(); // Display the details with key and value foreach (DictionaryEntry i in data) { Console.WriteLine("{0}:{1}", i.Key, i.Value); }}} Output: USER:priya GOPATH:/Users/priya/Documents/go rvm_stored_umask:022 rvm_version:1.29.12 (latest) HOME:/Users/priya rvm_bin_path:/Users/priya/.rvm/bin Press any key to continue... CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n16 Nov, 2021" }, { "code": null, "e": 26260, "s": 25547, "text": "In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operat...
How to fix number of visible items in HTML dropdown and allow multiple selections ? - GeeksforGeeks
24 Aug, 2020 Drop down menu provides a list of options to choose from. The HTML <select> tag is used to create a drop down list. When the number of options in a drop-down list is large, fixing the number of visible items may be useful. This can be done by using the “size” attribute of <select> tag. In the following example, 2 items are visible at a time because the value of the size attribute is set to 2. Example 1: <!DOCTYPE html><html> <body> Choose a language:<br> <select id="language" size="2" > <option value="C">C</option> <option value="C++">C++</option> <option value="Java">Java</option> <option value="Python">Python</option> <option value="R">R</option> <option value="HTML">HTML</option> <option value="JavaScript">JavaScript</option> </select></body> </html> Output: In the above example, only one item can be selected from the list. To enable multiple selections, a “multiple” attribute is used. In the following example, multiple options can be selected by holding the Ctrl button (Windows) or Command (Mac): Example 2: <!DOCTYPE html><html> <body> Choose a language:<br> <select id="language" size="4" multiple> <option value="C">C</option> <option value="C++">C++</option> <option value="Java">Java</option> <option value="Python">Python</option> <option value="R">R</option> <option value="HTML">HTML</option> <option value="JavaScript">JavaScript</option> </select> <p> Hold ctrl (windows) or Command (Mac) to select multiple option </p> </body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26069, "s": 26041, "text": "\n24 Aug, 2020" }, { "code": null, "e": 26185, "s": 26069, "text": "Drop down menu provides a list of options to choose from. The HTML <select> tag is used to create a drop down list." }, { "code": null, "e": 26358, ...
Sexy Prime - GeeksforGeeks
06 May, 2021 In mathematics, Sexy Primes are prime numbers that differ from each other by six. For example, the numbers 5 and 11 are both sexy primes, because they differ by 6. If p + 2 or p + 4 (where p is the lower prime) is also prime.They can be grouped as: Sexy prime pairs: It is of the form (p, p + 6), where p and p + 6 are prime numbers. Eg. (11, 17) is a sexy prime pairs. Sexy prime triplets: Triplets of primes (p, p + 6, p + 12) such that p + 18 is composite are called sexy prime triplets. Eg. (7, 13, 19) is a Sexy prime triplets. Sexy prime quadruplets: Sexy prime quadruplets (p, p + 6, p + 12, p + 18) can only begin with primes ending in a 1 in their decimal representation (except for the quadruplet with p = 5). Eg. (41, 47, 53, 59) is a Sexy prime quadruplets. Sexy prime quintuplets: In an arithmetic progression of five terms with common difference 6, one of the terms must be divisible by 5, because the two numbers are relatively prime. Thus, the only sexy prime quintuplet is (5, 11, 17, 23, 29); no longer sequence of sexy primes is possible. Given a range of the form [L, R]. The task is to print all the sexy prime pairs in the range. Examples: Input : L = 6, R = 59 Output : (7, 13) (11, 17) (13, 19) (17, 23) (23, 29) (31, 37) (37, 43) (41, 47) (47, 53) (53, 59) Input : L = 1, R = 19 Output : (5, 11) (7, 13) (11, 17) (13, 19) Sexy Prime within a range [L, R] can be generated using Sieve Of Eratosthenes. The idea is to generate bool array of Sieve and run a loop of i from L to R – 6 (inclusive) and check whether i and i + 6 are prime or not. If both are prime, print both number.Below is the implementation of this approach: C++ Java Python 3 C# PHP Javascript // CPP Program to print sexy prime in a range.#include <bits/stdc++.h>using namespace std; // Print the sexy prime in a rangevoid sexyprime(int l, int r){ // Sieve Of Eratosthenes for generating // prime number. bool prime[r + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= r; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= r; i += p) prime[i] = false; } } // From L to R - 6, checking if i, // i + 6 are prime or not. for (int i = l; i <= r - 6; i++) if (prime[i] && prime[i + 6]) cout << "(" << i << ", " << i + 6 << ") "; } // Driven Programint main(){ int L = 6, R = 59; sexyprime(L, R); return 0;} // Java code to print sexy prime in a range.import java.util.Arrays;import java.util.Collections; class GFG{ // Print the sexy prime in a range public static void sexyprime(int l, int r) { // Sieve Of Eratosthenes for generating // prime number. boolean [] prime= new boolean[r + 1]; // memset(prime, true, sizeof(prime)); Arrays.fill(prime, true); for (int p = 2; p * p <= r; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= r; i += p) prime[i] = false; } } // From L to R - 6, checking if i, // i + 6 are prime or not. for (int i = l; i <= r - 6; i++) if (prime[i] && prime[i + 6]) System.out.print( "(" + i + ", " + (i + 6) + ") "); } // Driver program to test above methods public static void main(String[] args) { int L = 6, R = 59; sexyprime(L, R); }} // This code is contributed by Chhavi # Python 3 Program to print# sexy prime in a range. # Print the sexy prime in a rangedef sexyprime(l, r) : # Sieve Of Eratosthenes # for generating # prime number. prime=[True] * (r + 1) p = 2 while(p * p <= r) : # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range( p * 2, r+1 ,p) : prime[i] = False p = p + 1 # From L to R - 6, checking if i, # i + 6 are prime or not. for i in range( l,r - 6 + 1) : if (prime[i] and prime[i + 6]) : print("(", i , ",", i + 6,")", end="") # Driven ProgramL = 6R = 59sexyprime(L, R) # This code is contributed by Nikita Tiwari. // C# code to print sexy// prime in a range.using System; class GFG{ // Print the sexy // prime in a range public static void sexyprime(int l, int r) { // Sieve Of Eratosthenes // for generating prime number. int[] prime = new int[r + 1]; // memset(prime, true, // sizeof(prime)); for (int i = 0; i < r + 1; i++) prime[i] = 1; for (int p = 2; p * p <= r; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == 1) { // Update all multiples of p for (int i = p * 2; i <= r; i += p) prime[i] = 0; } } // From L to R - 6, checking // if i, i + 6 are prime or not. for (int i = l; i <= r - 6; i++) if (prime[i] == 1 && prime[i + 6] == 1) Console.Write("(" + i + ", " + (i + 6) + ") "); } // Driver Code public static void Main() { int L = 6, R = 59; sexyprime(L, R); }} // This code is contributed by mits <?php// PHP Program to print// sexy prime in a range. // Print the sexy// prime in a rangefunction sexyprime($l, $r){ // Sieve Of Eratosthenes for // generating prime number. $prime = array_fill(0, $r + 1, true); for ($p = 2; $p * $p <= $r; $p++) { // If prime[p] is not // changed, then it // is a prime if ($prime[$p] == true) { // Update all // multiples of p for ($i = $p * 2; $i <= $r; $i += $p) $prime[$i] = false; } } // From L to R - 6, // checking if i, // i + 6 are prime or not. for ($i = $l; $i <= $r - 6; $i++) if ($prime[$i] && $prime[$i + 6]) echo "(" , $i , ", ", $i + 6 , ") ";} // Driver Code$L = 6;$R = 59;sexyprime($L, $R); // This code is contributed// by ajit.?> <script> // Javascript Program to print sexy prime in a range. // Print the sexy prime in a rangefunction sexyprime(l, r){ // Sieve Of Eratosthenes for generating // prime number. var prime = Array(r+1).fill(true); for (var p = 2; p * p <= r; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i <= r; i += p) prime[i] = false; } } // From L to R - 6, checking if i, // i + 6 are prime or not. for (var i = l; i <= r - 6; i++) if (prime[i] && prime[i + 6]) document.write( "(" + i + ", " + (i + 6) + ") "); } // Driven Programvar L = 6, R = 59;sexyprime(L, R); </script> Output: (7, 13) (11, 17) (13, 19) (17, 23) (23, 29) (31, 37) (37, 43) (41, 47) (47, 53) (53, 59) jit_t Mithun Kumar Akanksha_Rai rrrtnx number-theory Prime Number sieve Mathematical number-theory Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 26007, "s": 25979, "text": "\n06 May, 2021" }, { "code": null, "e": 26258, "s": 26007, "text": "In mathematics, Sexy Primes are prime numbers that differ from each other by six. For example, the numbers 5 and 11 are both sexy primes, because they differ by 6....
Dynamic EditText in Kotlin - GeeksforGeeks
11 Nov, 2021 EditText is used to get input from the user. EditText is commonly used in login or registration screens. we alreadylearn how to create an EditText using layout. In this article, we will learn about how to create android EditText programmatically in kotlin. At first, we will create a new android application. Then, we will create an EditText dynamically.If you already created the project then ignore step 1. 1. Create New Project After creating project we will modify xml files then. Open res/layout/activity_main.xml file and add code into it. <?xml version="1.0" encoding="utf-8"?><LinearLayout android:id="@+id/activity_main" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <LinearLayout android:id="@+id/editTextLinearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> </LinearLayout> <Button android:id="@+id/buttonShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show text"> </Button> </LinearLayout> So in activity_main.xml file, we created a LinearLayout, having id editTextLinearLayout, we use this LinearLayout as a container for crearting EditText. Open app/src/main/java/net.geeksforgeeks.dynamicedittextkotlin/MainActivity.kt fileand add below code into it. package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport android.widget.LinearLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val editLinearLayout = findViewById<LinearLayout>(R.id.editTextLinearLayout) val buttonShow = findViewById<Button>(R.id.buttonShow) // Create EditText val editText = EditText(this) editText.setHint("Enter something") editText.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) editText.setPadding(20, 20, 20, 20) // Add EditText to LinearLayout editLinearLayout?.addView(editText) buttonShow?.setOnClickListener { Toast.makeText( this@MainActivity, editText.text, Toast.LENGTH_LONG).show() } }} Here, we are created EditText Dynamically in kotlin. Then, Adding this EditText into LinearLayout, having id editTextLinearLayout. and a toast message is also shown when button is click. As, AndroidManifest.xml file is very important file in android application, so below is the code of manifest file. Code inside src/main/AndroidManifest.xml file would look like below. <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.geeksforgeeks.dynamicedittextkotlin"> <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> Now, run your application. you will get output as shown below. You can find the complete code here:https://github.com/missyadavmanisha/DynamicEditTextKotlin simmytarika5 Android-View Kotlin Android Picked Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android UI Layouts Kotlin Array Services in Android with Example Android RecyclerView in Kotlin
[ { "code": null, "e": 25237, "s": 25209, "text": "\n11 Nov, 2021" }, { "code": null, "e": 25494, "s": 25237, "text": "EditText is used to get input from the user. EditText is commonly used in login or registration screens. we alreadylearn how to create an EditText using layout. In...
StringBuilder append() Method in Java With Examples - GeeksforGeeks
15 Oct, 2018 The java.lang.StringBuilder.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the append() method can be used by the passing of various types of arguments: StringBuilder append(boolean a) :The java.lang.StringBuilder.append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence.Syntax :public StringBuilder append(boolean a)Parameter: This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.Return Value: The method returns a reference to this object.Examples:Input: string_buffer = "We are Indians" boolean a = true Output: We are Indians true Below program illustrates the java.lang.StringBuilder.append() method:// Java program to illustrate the// StringBuilder append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder("Welcome to Geeksforgeeks "); System.out.println("Input: " + sb1); // Appending the boolean value sb1.append(true); System.out.println("Output: " + sb1); System.out.println(); StringBuilder sb2 = new StringBuilder("We fail- "); System.out.println("Input: " + sb2); // Appending the boolean value sb2.append(false); System.out.println("Output: " + sb2); }}Output:Input: Welcome to Geeksforgeeks Output: Welcome to Geeksforgeeks true Input: We fail- Output: We fail- false java.lang.StringBuilder.append(char a): This is an inbuilt method in Java which is used to append the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuilder sequence.Syntax :public StringBuilder append(char a)Parameter: The method accepts a single parameter a which is the Char value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuilder = I love my Country char a = A Output: I love my Country ABelow programs illustrate the java.lang.StringBuilder.append(char a) method.// Java program to illustrate the// java.lang.StringBuilder.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Welcome geeks!"); System.out.println( sbf); /* Here it appends the char argument as string to the StringBuilder */ sbf.append('T'); System.out.println("Result after"+ " appending = " + sbf); sbf = new StringBuilder("hello world-"); System.out.println(sbf); /* Here it appends the char argument as string to the String Builder */ sbf.append('#'); System.out.println("Result after appending = " + sbf); }}Output:Welcome geeks! Result after appending = Welcome geeks!T hello world- Result after appending = hello world-# StringBuilder append(char[] astr): The java.lang.StringBuilder.append(char[] astr) is the inbuilt method which appends the string representation of the char array argument to this StringBuilder sequence.Syntax :public StringBuilder append(char[] astr)Parameter: The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples:Input : StringBuffer = I love my Country char[] astr = 'I', 'N', 'D', 'I', 'A' Output: I love my Country INDIA Below program illustrates the java.lang.StringBuilder.append(char[] astr) method:// Java program to illustrate the// java.lang.StringBuilder.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are geeks "); System.out.println(sbf); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Appends string representation of char array to this String Builder */ sbf.append(astr); System.out.println("Result after"+ " appending = " + sbf); sbf = new StringBuilder("We are -"); System.out.println(sbf); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Appends string representation of char array to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks Result after appending = We are geeks GEEkS We are - Result after appending = We are -abcd StringBuilder append(char[] cstr, int iset, int ilength) : This method appends the string representation of a subarray of the char array argument to this sequence. The Characters of the char array cstr, starting at index iset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of ilength.Syntax :public StringBuilder append(char[] cstr, int iset, int ilenght)Parameter : This method accepts three parameters:cstr – This refers to the Char sequence.iset – This refers to the index of the first char to append.ilenght – This refers to the number of chars to append.Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuilder.append(char[] cstr, int iset, int ilength) method.// Java program to illustrate the// append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Geeks"); System.out.println("String Builder "+ "before = " + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's','q','q' }; /* appends the string representation of char array argument to this String Builder with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the String Builder after appending System.out.println("After appending String Builder = " + sb); }}Output:String Builder before = Geeks After appending String Builder = GeeksforGeeks StringBuilder append(double a): This method simply appends the string representation of the double argument to this StringBuilder sequence.Syntax :public StringBuilder append(double val)Parameter: The method accepts a single parameter val which refers to the decimal value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuffer = my Country Double a = 54.82 Output: my Country 54.82Below program illustrates the java.lang.StringBuilder.append(double val) method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); // Char array Double astr = new Double(36.47); /* Here it appends string representation of Double argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Double(27.38); /* Here it appends string representation of Double argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 36.47 We are lost - Result after appending = We are lost -27.38 StringBuilder append(float val): This method appends the string representation of the float argument to this sequence.Syntax :public StringBuilder append(float val)Parameter: The method accepts a single parameter val which is the float value whose string representation is to be appended.Return Value: StringBuilder.append(float val) method returns a reference the string object after the operation is performed.Examples :Input : StringBuilder = I love my Country float a = 5.2 Output: I love my Country 5.2Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this String Builder sbf.append(astr); System.out.println("Result after appending = "+sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 6.47 We are lost - Result after appending = We are lost -27.38 StringBuilder append(int val) This method simply appends the string representation of the int argument to this StringBuilder sequence.Syntax :public StringBuilder append(int val)Parameter: The method accepts a single parameter val which is an integer value on which the operation is supposed to be performed.Return Value: The method returns a reference to this object.Examples :Input : StringBuilder = I love my Country int a = 55 Output: I love my Country 55Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Integer astr = new Integer(827); /* Here it appends string representation of Integer argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this StringBuilder sbf.append(astr); System.out.println("Result after appending = "+sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 827 We are lost - Result after appending = We are lost -515 StringBuilder append(Long val) : This method simply appends the string representation of the long argument to this StringBuilder sequence.Syntax :public StringBuilder append(Long val)Parameter: The method accepts a single parameter val which is the long value.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuilder = I love my Country Long a = 591995 Output: I love my Country 591995Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Long astr = new Long(827); /* Here it appends string representation of Long argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Long(515); /* Here it appends string representation of Long argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 827 We are lost - Result after appending = We are lost -515 StringBuilder append(CharSequence a): This method is used to append the specified CharSequence to this sequence.Syntax :public StringBuilder append(CharSequence a)Parameter: The method accepts a single parameter a which is the CharSequence value.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuilder = "I love my Country" CharSequence a = " India" Output : I love my Country India Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); CharSequence chSeq = "geeks"; // Appends the CharSequence sbf.append(chSeq); // Print the String Builder after appending System.out.println("After append = " + sbf); }}Output:String Builder = Geeksfor After append = Geeksforgeeks StringBuilder append(CharSequence chseq, int start, int end) : This method is used to append a subsequence of the specified CharSequence to this StringBuilder.Syntax :StringBuilder append(CharSequence chseq, int start, int end)Parameter : The method accepts three parameters:chseq(CharSequence): This refers to the CharSequence value.start(Integer): This refers to the starting index of the subsequence to be appended..end(Integer): This refers to the end index of the subsequence to be appended.Return Value : The method returns the string after the append operation is performed.Examples :Input : StringBuilder = Geeksforgeeks CharSequence chseq = abcd1234 int start = 2 int end = 7 Output :Geeksforgeekscd123 Below program illustrates the java.lang.StringBuilder.append() method:// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are the "); System.out.println("String builder= " + sbf); CharSequence chSeq = "wegeekss"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println("After append string"+ " buffer = " + sbf); }}Output:String builder= We are the After append string buffer = We are the geeks StringBuilder append(Object obj) : This method is used to append the string representation of the Object argument to the StringBuilder.Syntax :StringBuilder append(Object obj)Parameter: The method accepts a single parameter obj which refers to the object needed to be appended.Return Value: The method returns the string after performing the append operation.Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); Object objectvalue = "geeks"; // Here it appends the Object value sbf.append(objectvalue); System.out.println("After appending result is = "+sbf); }}Output:String Builder = Geeksfor After appending result is = Geeksforgeeks StringBuilder append(String istr) : This method is used to append the specified string to this StringBuilder.Syntax :StringBuilder append(String istr)Parameter: The method accepts a single parameter istr of String type which refer to the value to be appended.Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); String strvalue = "geeks"; // Here it appends the Object value sbf.append(strvalue); System.out.println("After appending result is = "+sbf); }}Output:String Builder = Geeksfor After appending result is = Geeksforgeeks StringBuilder append(StringBuilder sbf) : This method is used to append the specified StringBuilder to this sequence or StringBuilder.Syntax:public StringBuilder append(StringBuilder sbf)Parameter: The method accepts a single parameter sbf refers to the StringBuilder to append.Return Value : The method returns StringBuilder to this sequence.Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf1 = new StringBuilder("Geeks"); System.out.println("String Builder 1 = " + sbf1); StringBuilder sbf2 = new StringBuilder("forgeeks "); System.out.println("String Builder 2 = " + sbf2); // Here it appends String Builder2 to String Builder1 sbf1.append(sbf2); System.out.println("After appending the result is = "+sbf1); }}Output:String Builder 1 = Geeks String Builder 2 = forgeeks After appending the result is = Geeksforgeeks StringBuilder append(boolean a) :The java.lang.StringBuilder.append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence.Syntax :public StringBuilder append(boolean a)Parameter: This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.Return Value: The method returns a reference to this object.Examples:Input: string_buffer = "We are Indians" boolean a = true Output: We are Indians true Below program illustrates the java.lang.StringBuilder.append() method:// Java program to illustrate the// StringBuilder append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder("Welcome to Geeksforgeeks "); System.out.println("Input: " + sb1); // Appending the boolean value sb1.append(true); System.out.println("Output: " + sb1); System.out.println(); StringBuilder sb2 = new StringBuilder("We fail- "); System.out.println("Input: " + sb2); // Appending the boolean value sb2.append(false); System.out.println("Output: " + sb2); }}Output:Input: Welcome to Geeksforgeeks Output: Welcome to Geeksforgeeks true Input: We fail- Output: We fail- false Syntax : public StringBuilder append(boolean a) Parameter: This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended. Return Value: The method returns a reference to this object. Examples: Input: string_buffer = "We are Indians" boolean a = true Output: We are Indians true Below program illustrates the java.lang.StringBuilder.append() method: // Java program to illustrate the// StringBuilder append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder("Welcome to Geeksforgeeks "); System.out.println("Input: " + sb1); // Appending the boolean value sb1.append(true); System.out.println("Output: " + sb1); System.out.println(); StringBuilder sb2 = new StringBuilder("We fail- "); System.out.println("Input: " + sb2); // Appending the boolean value sb2.append(false); System.out.println("Output: " + sb2); }} Input: Welcome to Geeksforgeeks Output: Welcome to Geeksforgeeks true Input: We fail- Output: We fail- false java.lang.StringBuilder.append(char a): This is an inbuilt method in Java which is used to append the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuilder sequence.Syntax :public StringBuilder append(char a)Parameter: The method accepts a single parameter a which is the Char value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuilder = I love my Country char a = A Output: I love my Country ABelow programs illustrate the java.lang.StringBuilder.append(char a) method.// Java program to illustrate the// java.lang.StringBuilder.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Welcome geeks!"); System.out.println( sbf); /* Here it appends the char argument as string to the StringBuilder */ sbf.append('T'); System.out.println("Result after"+ " appending = " + sbf); sbf = new StringBuilder("hello world-"); System.out.println(sbf); /* Here it appends the char argument as string to the String Builder */ sbf.append('#'); System.out.println("Result after appending = " + sbf); }}Output:Welcome geeks! Result after appending = Welcome geeks!T hello world- Result after appending = hello world-# Syntax : public StringBuilder append(char a) Parameter: The method accepts a single parameter a which is the Char value whose string representation is to be appended. Return Value: The method returns a string object after the append operation is performed.Examples : Input : StringBuilder = I love my Country char a = A Output: I love my Country A Below programs illustrate the java.lang.StringBuilder.append(char a) method. // Java program to illustrate the// java.lang.StringBuilder.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Welcome geeks!"); System.out.println( sbf); /* Here it appends the char argument as string to the StringBuilder */ sbf.append('T'); System.out.println("Result after"+ " appending = " + sbf); sbf = new StringBuilder("hello world-"); System.out.println(sbf); /* Here it appends the char argument as string to the String Builder */ sbf.append('#'); System.out.println("Result after appending = " + sbf); }} Welcome geeks! Result after appending = Welcome geeks!T hello world- Result after appending = hello world-# StringBuilder append(char[] astr): The java.lang.StringBuilder.append(char[] astr) is the inbuilt method which appends the string representation of the char array argument to this StringBuilder sequence.Syntax :public StringBuilder append(char[] astr)Parameter: The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples:Input : StringBuffer = I love my Country char[] astr = 'I', 'N', 'D', 'I', 'A' Output: I love my Country INDIA Below program illustrates the java.lang.StringBuilder.append(char[] astr) method:// Java program to illustrate the// java.lang.StringBuilder.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are geeks "); System.out.println(sbf); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Appends string representation of char array to this String Builder */ sbf.append(astr); System.out.println("Result after"+ " appending = " + sbf); sbf = new StringBuilder("We are -"); System.out.println(sbf); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Appends string representation of char array to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks Result after appending = We are geeks GEEkS We are - Result after appending = We are -abcd Syntax : public StringBuilder append(char[] astr) Parameter: The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended. Return Value: The method returns a string object after the append operation is performed.Examples: Input : StringBuffer = I love my Country char[] astr = 'I', 'N', 'D', 'I', 'A' Output: I love my Country INDIA Below program illustrates the java.lang.StringBuilder.append(char[] astr) method: // Java program to illustrate the// java.lang.StringBuilder.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are geeks "); System.out.println(sbf); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Appends string representation of char array to this String Builder */ sbf.append(astr); System.out.println("Result after"+ " appending = " + sbf); sbf = new StringBuilder("We are -"); System.out.println(sbf); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Appends string representation of char array to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = " + sbf); }} We are geeks Result after appending = We are geeks GEEkS We are - Result after appending = We are -abcd StringBuilder append(char[] cstr, int iset, int ilength) : This method appends the string representation of a subarray of the char array argument to this sequence. The Characters of the char array cstr, starting at index iset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of ilength.Syntax :public StringBuilder append(char[] cstr, int iset, int ilenght)Parameter : This method accepts three parameters:cstr – This refers to the Char sequence.iset – This refers to the index of the first char to append.ilenght – This refers to the number of chars to append.Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuilder.append(char[] cstr, int iset, int ilength) method.// Java program to illustrate the// append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Geeks"); System.out.println("String Builder "+ "before = " + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's','q','q' }; /* appends the string representation of char array argument to this String Builder with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the String Builder after appending System.out.println("After appending String Builder = " + sb); }}Output:String Builder before = Geeks After appending String Builder = GeeksforGeeks Syntax : public StringBuilder append(char[] cstr, int iset, int ilenght) Parameter : This method accepts three parameters: cstr – This refers to the Char sequence. iset – This refers to the index of the first char to append. ilenght – This refers to the number of chars to append. Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuilder.append(char[] cstr, int iset, int ilength) method. // Java program to illustrate the// append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Geeks"); System.out.println("String Builder "+ "before = " + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's','q','q' }; /* appends the string representation of char array argument to this String Builder with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the String Builder after appending System.out.println("After appending String Builder = " + sb); }} String Builder before = Geeks After appending String Builder = GeeksforGeeks StringBuilder append(double a): This method simply appends the string representation of the double argument to this StringBuilder sequence.Syntax :public StringBuilder append(double val)Parameter: The method accepts a single parameter val which refers to the decimal value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuffer = my Country Double a = 54.82 Output: my Country 54.82Below program illustrates the java.lang.StringBuilder.append(double val) method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); // Char array Double astr = new Double(36.47); /* Here it appends string representation of Double argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Double(27.38); /* Here it appends string representation of Double argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 36.47 We are lost - Result after appending = We are lost -27.38 Syntax : public StringBuilder append(double val) Parameter: The method accepts a single parameter val which refers to the decimal value whose string representation is to be appended. Return Value: The method returns a string object after the append operation is performed.Examples : Input : StringBuffer = my Country Double a = 54.82 Output: my Country 54.82 Below program illustrates the java.lang.StringBuilder.append(double val) method. // Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); // Char array Double astr = new Double(36.47); /* Here it appends string representation of Double argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Double(27.38); /* Here it appends string representation of Double argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }} We are geeks and its really Result after appending = We are geeks and its 36.47 We are lost - Result after appending = We are lost -27.38 StringBuilder append(float val): This method appends the string representation of the float argument to this sequence.Syntax :public StringBuilder append(float val)Parameter: The method accepts a single parameter val which is the float value whose string representation is to be appended.Return Value: StringBuilder.append(float val) method returns a reference the string object after the operation is performed.Examples :Input : StringBuilder = I love my Country float a = 5.2 Output: I love my Country 5.2Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this String Builder sbf.append(astr); System.out.println("Result after appending = "+sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 6.47 We are lost - Result after appending = We are lost -27.38 Syntax : public StringBuilder append(float val) Parameter: The method accepts a single parameter val which is the float value whose string representation is to be appended. Return Value: StringBuilder.append(float val) method returns a reference the string object after the operation is performed. Examples : Input : StringBuilder = I love my Country float a = 5.2 Output: I love my Country 5.2 Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this String Builder sbf.append(astr); System.out.println("Result after appending = "+sbf); }} We are geeks and its really Result after appending = We are geeks and its 6.47 We are lost - Result after appending = We are lost -27.38 StringBuilder append(int val) This method simply appends the string representation of the int argument to this StringBuilder sequence.Syntax :public StringBuilder append(int val)Parameter: The method accepts a single parameter val which is an integer value on which the operation is supposed to be performed.Return Value: The method returns a reference to this object.Examples :Input : StringBuilder = I love my Country int a = 55 Output: I love my Country 55Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Integer astr = new Integer(827); /* Here it appends string representation of Integer argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this StringBuilder sbf.append(astr); System.out.println("Result after appending = "+sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 827 We are lost - Result after appending = We are lost -515 public StringBuilder append(int val) Parameter: The method accepts a single parameter val which is an integer value on which the operation is supposed to be performed. Return Value: The method returns a reference to this object. Examples : Input : StringBuilder = I love my Country int a = 55 Output: I love my Country 55 Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Integer astr = new Integer(827); /* Here it appends string representation of Integer argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this StringBuilder sbf.append(astr); System.out.println("Result after appending = "+sbf); }} We are geeks and its really Result after appending = We are geeks and its 827 We are lost - Result after appending = We are lost -515 StringBuilder append(Long val) : This method simply appends the string representation of the long argument to this StringBuilder sequence.Syntax :public StringBuilder append(Long val)Parameter: The method accepts a single parameter val which is the long value.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuilder = I love my Country Long a = 591995 Output: I love my Country 591995Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Long astr = new Long(827); /* Here it appends string representation of Long argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Long(515); /* Here it appends string representation of Long argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); }}Output:We are geeks and its really Result after appending = We are geeks and its 827 We are lost - Result after appending = We are lost -515 Syntax : public StringBuilder append(Long val) Parameter: The method accepts a single parameter val which is the long value. Return Value: The method returns a string object after the append operation is performed.Examples : Input : StringBuilder = I love my Country Long a = 591995 Output: I love my Country 591995 Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuilder sbf = new StringBuilder("We are geeks and its "); Long astr = new Long(827); /* Here it appends string representation of Long argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); System.out.println("We are lost -"); sbf = new StringBuilder("We are lost -"); astr = new Long(515); /* Here it appends string representation of Long argument to this StringBuilder*/ sbf.append(astr); System.out.println("Result after appending = "+sbf); }} We are geeks and its really Result after appending = We are geeks and its 827 We are lost - Result after appending = We are lost -515 StringBuilder append(CharSequence a): This method is used to append the specified CharSequence to this sequence.Syntax :public StringBuilder append(CharSequence a)Parameter: The method accepts a single parameter a which is the CharSequence value.Return Value: The method returns a string object after the append operation is performed.Examples :Input : StringBuilder = "I love my Country" CharSequence a = " India" Output : I love my Country India Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); CharSequence chSeq = "geeks"; // Appends the CharSequence sbf.append(chSeq); // Print the String Builder after appending System.out.println("After append = " + sbf); }}Output:String Builder = Geeksfor After append = Geeksforgeeks Syntax : public StringBuilder append(CharSequence a) Parameter: The method accepts a single parameter a which is the CharSequence value. Return Value: The method returns a string object after the append operation is performed. Examples : Input : StringBuilder = "I love my Country" CharSequence a = " India" Output : I love my Country India Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); CharSequence chSeq = "geeks"; // Appends the CharSequence sbf.append(chSeq); // Print the String Builder after appending System.out.println("After append = " + sbf); }} String Builder = Geeksfor After append = Geeksforgeeks StringBuilder append(CharSequence chseq, int start, int end) : This method is used to append a subsequence of the specified CharSequence to this StringBuilder.Syntax :StringBuilder append(CharSequence chseq, int start, int end)Parameter : The method accepts three parameters:chseq(CharSequence): This refers to the CharSequence value.start(Integer): This refers to the starting index of the subsequence to be appended..end(Integer): This refers to the end index of the subsequence to be appended.Return Value : The method returns the string after the append operation is performed.Examples :Input : StringBuilder = Geeksforgeeks CharSequence chseq = abcd1234 int start = 2 int end = 7 Output :Geeksforgeekscd123 Below program illustrates the java.lang.StringBuilder.append() method:// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are the "); System.out.println("String builder= " + sbf); CharSequence chSeq = "wegeekss"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println("After append string"+ " buffer = " + sbf); }}Output:String builder= We are the After append string buffer = We are the geeks Syntax : StringBuilder append(CharSequence chseq, int start, int end) Parameter : The method accepts three parameters: chseq(CharSequence): This refers to the CharSequence value. start(Integer): This refers to the starting index of the subsequence to be appended.. end(Integer): This refers to the end index of the subsequence to be appended. Return Value : The method returns the string after the append operation is performed. Examples : Input : StringBuilder = Geeksforgeeks CharSequence chseq = abcd1234 int start = 2 int end = 7 Output :Geeksforgeekscd123 Below program illustrates the java.lang.StringBuilder.append() method: // Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are the "); System.out.println("String builder= " + sbf); CharSequence chSeq = "wegeekss"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println("After append string"+ " buffer = " + sbf); }} String builder= We are the After append string buffer = We are the geeks StringBuilder append(Object obj) : This method is used to append the string representation of the Object argument to the StringBuilder.Syntax :StringBuilder append(Object obj)Parameter: The method accepts a single parameter obj which refers to the object needed to be appended.Return Value: The method returns the string after performing the append operation.Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); Object objectvalue = "geeks"; // Here it appends the Object value sbf.append(objectvalue); System.out.println("After appending result is = "+sbf); }}Output:String Builder = Geeksfor After appending result is = Geeksforgeeks Syntax : StringBuilder append(Object obj) Parameter: The method accepts a single parameter obj which refers to the object needed to be appended. Return Value: The method returns the string after performing the append operation. Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); Object objectvalue = "geeks"; // Here it appends the Object value sbf.append(objectvalue); System.out.println("After appending result is = "+sbf); }} String Builder = Geeksfor After appending result is = Geeksforgeeks StringBuilder append(String istr) : This method is used to append the specified string to this StringBuilder.Syntax :StringBuilder append(String istr)Parameter: The method accepts a single parameter istr of String type which refer to the value to be appended.Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); String strvalue = "geeks"; // Here it appends the Object value sbf.append(strvalue); System.out.println("After appending result is = "+sbf); }}Output:String Builder = Geeksfor After appending result is = Geeksforgeeks StringBuilder append(String istr) Parameter: The method accepts a single parameter istr of String type which refer to the value to be appended. Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("Geeksfor"); System.out.println("String Builder = " + sbf); String strvalue = "geeks"; // Here it appends the Object value sbf.append(strvalue); System.out.println("After appending result is = "+sbf); }} String Builder = Geeksfor After appending result is = Geeksforgeeks StringBuilder append(StringBuilder sbf) : This method is used to append the specified StringBuilder to this sequence or StringBuilder.Syntax:public StringBuilder append(StringBuilder sbf)Parameter: The method accepts a single parameter sbf refers to the StringBuilder to append.Return Value : The method returns StringBuilder to this sequence.Below program illustrates the java.lang.StringBuilder.append() method.// Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf1 = new StringBuilder("Geeks"); System.out.println("String Builder 1 = " + sbf1); StringBuilder sbf2 = new StringBuilder("forgeeks "); System.out.println("String Builder 2 = " + sbf2); // Here it appends String Builder2 to String Builder1 sbf1.append(sbf2); System.out.println("After appending the result is = "+sbf1); }}Output:String Builder 1 = Geeks String Builder 2 = forgeeks After appending the result is = Geeksforgeeks Syntax: public StringBuilder append(StringBuilder sbf) Parameter: The method accepts a single parameter sbf refers to the StringBuilder to append. Return Value : The method returns StringBuilder to this sequence.Below program illustrates the java.lang.StringBuilder.append() method. // Java program to illustrate the// java.lang.StringBuilder.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf1 = new StringBuilder("Geeks"); System.out.println("String Builder 1 = " + sbf1); StringBuilder sbf2 = new StringBuilder("forgeeks "); System.out.println("String Builder 2 = " + sbf2); // Here it appends String Builder2 to String Builder1 sbf1.append(sbf2); System.out.println("After appending the result is = "+sbf1); }} String Builder 1 = Geeks String Builder 2 = forgeeks After appending the result is = Geeksforgeeks Java-lang package Java-StringBuilder Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26238, "s": 26210, "text": "\n15 Oct, 2018" }, { "code": null, "e": 26471, "s": 26238, "text": "The java.lang.StringBuilder.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the appe...
How to find the Entry with largest Value in a C++ Map - GeeksforGeeks
17 Mar, 2020 Given a map in C++, the task is to find the entry in this map with the highest value. Examples: Input: Map = {ABC = 10, DEF = 30, XYZ = 20} Output: DEF = 30 Input: Map = {1 = 40, 2 = 30, 3 = 60} Output: 3 = 60 Approach Iterate the map entry by entry with help of iteratorsmap::iterator itr; for (itr = some_map.begin(); itr != some_map.end(); ++itr) { // operations } Store the first entry in a reference variable to compare to initially.If the current entry’s value is greater than the reference entry’s value, then store the current entry as the reference entry.Repeat this process for all the entries in the map.In the end, the reference variable has the required entry with the highest value in the map.Print this entry Iterate the map entry by entry with help of iteratorsmap::iterator itr; for (itr = some_map.begin(); itr != some_map.end(); ++itr) { // operations } map::iterator itr; for (itr = some_map.begin(); itr != some_map.end(); ++itr) { // operations } Store the first entry in a reference variable to compare to initially. If the current entry’s value is greater than the reference entry’s value, then store the current entry as the reference entry. Repeat this process for all the entries in the map. In the end, the reference variable has the required entry with the highest value in the map. Print this entry Below is the implementation of the above approach: // C++ program to find the Entry// with largest Value in a Map #include <bits/stdc++.h>using namespace std; // Function to print the Mapvoid printMap(map<int, int> sampleMap){ map<int, int>::iterator itr; for (itr = sampleMap.begin(); itr != sampleMap.end(); ++itr) { cout << itr->first << " = " << itr->second << ", "; } cout << endl;} // Function tp find the Entry// with largest Value in a Mappair<int, int> findEntryWithLargestValue( map<int, int> sampleMap){ // Reference variable to help find // the entry with the highest value pair<int, int> entryWithMaxValue = make_pair(0, 0); // Iterate in the map to find the required entry map<int, int>::iterator currentEntry; for (currentEntry = sampleMap.begin(); currentEntry != sampleMap.end(); ++currentEntry) { // If this entry's value is more // than the max value // Set this entry as the max if (currentEntry->second > entryWithMaxValue.second) { entryWithMaxValue = make_pair( currentEntry->first, currentEntry->second); } } return entryWithMaxValue;} // Driver codeint main(){ // Map map<int, int> sampleMap; sampleMap.insert(pair<int, int>(1, 40)); sampleMap.insert(pair<int, int>(2, 30)); sampleMap.insert(pair<int, int>(3, 60)); // Printing map cout << "Map: "; printMap(sampleMap); // Get the entry with largest value pair<int, int> entryWithMaxValue = findEntryWithLargestValue(sampleMap); // Print the entry cout << "Entry with highest value: " << entryWithMaxValue.first << " = " << entryWithMaxValue.second << endl; return 0;} Map: 1 = 40, 2 = 30, 3 = 60, Entry with highest value: 3 = 60 cpp-map C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25368, "s": 25340, "text": "\n17 Mar, 2020" }, { "code": null, "e": 25454, "s": 25368, "text": "Given a map in C++, the task is to find the entry in this map with the highest value." }, { "code": null, "e": 25464, "s": 25454, "text": "Exam...
GATE | GATE-CS-2004 | Question 22 - GeeksforGeeks
14 Feb, 2018 How many 8-bit characters can be transmitted per second over a 9600 baud serial communication link using asynchronous mode of transmission with one start bit, eight data bits, two stop bits, and one parity bit ?(A) 600(B) 800(C) 876(D) 1200Answer: (B)Explanation: Background required – Physical Layer in OSI Stack In serial Communications, information is transferred in or out one bit at a time.The baud rate specifies how fast data is sent over a serial line. It’s usually expressed in units of bits-per-second (bps). Each block (usually a byte) of data transmitted is actually sent in a packet or frame of bits. Frames are created by appending synchronization and parity bits to our data. "9600 baud" means that the serial port is capable of transferring a maximum of 9600 bits per second. Total Data To send = 1 bit(start) + 8 bits(char size) + 1 bit(Parity) + 2 bits(Stop) = 12 bits. Number of 8-bit characters that can be transmitted per second = 9600/12 = 800. This explanation is contributed by Pranjul Ahuja. Quiz of this Question GATE-CS-2004 GATE-GATE-CS-2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25740, "s": 25712, "text": "\n14 Feb, 2018" }, { "code": null, "e": 26055, "s": 25740, "text": "How many 8-bit characters can be transmitted per second over a 9600 baud serial communication link using asynchronous mode of transmission with one start bit, eigh...
Replace a character at a specific index in a String in Java - GeeksforGeeks
29 May, 2021 Given a String, the task is to replace a character at a specific index in this string in Java. Examples: Input: String = "Geeks Gor Geeks", index = 6, ch = 'F' Output: "Geeks For Geeks." Input: String = "Geeks", index = 0, ch = 'g' Output: "geeks" Method 1: Using String Class There is no predefined method in String Class to replace a specific character in a String, as of now. However, this can be achieved indirectly by constructing a new String with 2 different substrings, one from beginning till the specific index – 1, the new character at the specific index and the other from the index + 1 till the end.Below is the implementation of the above approach: Java public class GFG { public static void main(String args[]) { // Get the String String str = "Geeks Gor Geeks"; // Get the index int index = 6; // Get the character char ch = 'F'; // Print the original string System.out.println("Original String = " + str); str = str.substring(0, index) + ch + str.substring(index + 1); // Print the modified string System.out.println("Modified String = " + str); }} Original String = Geeks Gor Geeks Modified String = Geeks For Geeks Method 2: Using StringBuilder Unlike String Class, the StringBuilder class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.Below is the implementation of the above approach: Java public class GFG { public static void main(String args[]) { // Get the String String str = "Geeks Gor Geeks"; // Get the index int index = 6; // Get the character char ch = 'F'; // Print the original string System.out.println("Original String = " + str); StringBuilder string = new StringBuilder(str); string.setCharAt(index, ch); // Print the modified string System.out.println("Modified String = " + string); }} Original String = Geeks Gor Geeks Modified String = Geeks For Geeks Method 3: Using StringBuffer Like StringBuilder, the StringBuffer class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter. StringBuffer is thread-safe. StringBuilder is faster when compared to StringBuffer, but is not thread-safe. Below is the implementation of the above approach: Java public class GFG { public static void main(String args[]) { // Get the String String str = "Geeks Gor Geeks"; // Get the index int index = 6; // Get the character char ch = 'F'; // Print the original string System.out.println("Original String = " + str); StringBuffer string = new StringBuffer(str); string.setCharAt(index, ch); // Print the modified string System.out.println("Modified String = " + string); }} Original String = Geeks Gor Geeks Modified String = Geeks For Geeks shivanirudramaina Java-lang package Java-String-Programs Java-StringBuilder Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26326, "s": 26298, "text": "\n29 May, 2021" }, { "code": null, "e": 26421, "s": 26326, "text": "Given a String, the task is to replace a character at a specific index in this string in Java." }, { "code": null, "e": 26432, "s": 26421, "tex...
Matplotlib.figure.Figure.add_subplot() in Python - GeeksforGeeks
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The add_subplot() method figure module of matplotlib library is used to add an Axes to the figure as part of a subplot arrangement. Syntax: add_subplot(self, *args, **kwargs) Parameters: This accept the following parameters that are described below: projection : This parameter is the projection type of the Axes. sharex, sharey : These parameters share the x or y axis with sharex and/or sharey. label : This parameter is the label for the returned axes. Returns: This method return the axes of the subplot. Below examples illustrate the matplotlib.figure.Figure.add_subplot() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom mpl_toolkits.axisartist.axislines import Subplot fig = plt.figure(figsize =(4, 4)) ax = Subplot(fig, 111)fig.add_subplot(ax) ax.axis["left"].set_visible(False)ax.axis["bottom"].set_visible(False) fig.suptitle('matplotlib.figure.Figure.add_subplot() \function Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) xdata = np.random.random([2, 10]) xdata1 = xdata[0, :]xdata2 = xdata[1, :] ydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3 fig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange') ax.set_xlim([0, 1])ax.set_ylim([0, 1])fig.suptitle('matplotlib.figure.Figure.add_subplot() \function Example\n\n', fontweight ="bold") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26243, "s": 26215, "text": "\n30 Apr, 2020" }, { "code": null, "e": 26554, "s": 26243, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, whic...
HTML | <td>colspan Attribute
29 Apr, 2019 The HTML <td> colspan Attribute is used to specify the number of columns a table should span. Syntax: <td colspan="number"> Attribute Values: It contains the numeric value which specifies the number of columns a cell should span. Example: This Example illustrates the use of colspan attribute in Tabledata Element. <!DOCTYPE html><html> <head> <title> HTML <td>colspan Attribute </title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML <td>colspan Attribute </h2> <table> <tr> <th>Name</th> <th>Expense</th> </tr> <tr> <td>Arun</td> <td>₹10</td> </tr> <tr> <td>Priya</td> <td>₹8</td> </tr> <!-- The last row --> <tr> <!-- This td will span two columns, that is a single column will take up the space of 2 --> <td colspan="2"> Sum: ₹18 </td> </tr> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <td>colspan Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux 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
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2019" }, { "code": null, "e": 122, "s": 28, "text": "The HTML <td> colspan Attribute is used to specify the number of columns a table should span." }, { "code": null, "e": 130, "s": 122, "text": "Syntax:" }...
Java Program to add minutes to current time using Calendar.add() method
Import the following package for Calendar class in Java. import java.util.Calendar; Firstly, create a Calendar object and display the current date and time. Calendar calendar = Calendar.getInstance(); System.out.println("Current Date and Time = " + calendar.getTime()); Now, let us increment the minutes using the calendar.add() method and Calendar.HOUR_OF_DAY constant. calendar.add(Calendar.MINUTE, 10); Live Demo import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); // Add 10 minutes to current date calendar.add(Calendar.MINUTE, 10); System.out.println("Updated Date = " + calendar.getTime()); } } Current Date = Thu Nov 22 16:24:27 UTC 2018 Updated Date = Thu Nov 22 16:34:27 UTC 2018
[ { "code": null, "e": 1244, "s": 1187, "text": "Import the following package for Calendar class in Java." }, { "code": null, "e": 1271, "s": 1244, "text": "import java.util.Calendar;" }, { "code": null, "e": 1344, "s": 1271, "text": "Firstly, create a Calendar ...
How to manage image resolution of a graph in Matplotlib
An Image contains a 2-D matrix RGB data points which can be defined by the dots point per inch [ DPI ] of the image. The resolution of the image is important because a hi-resolution image will have much more clarity. We have a method ‘plt.savefig()’ in Matplotlib which determines the size of the image in terms of its pixels. Ideally it is having an ‘dpi’ parameter. Let’s see how we can manage the resolution of a graph in Matplotlib. import matplotlib.pyplot as plt import numpy as np #Prepare the data for histogram np.random.seed(1961) nd = np.random.normal(13, 5, 1000) #Define the size of the plot plt.figure(figsize=(8,6)) plt.hist(nd) plt.grid() #set the dpi value to 300 plt.savefig('histogram_img.png', dpi=300) plt.show() plt.figure(figsize=(18,12)) plt.hist(nd) plt.grid() #Set the dpi value to 150 plt.savefig('histogram_100.png', dpi=150) plt.show() Running the above code will generate the output as,
[ { "code": null, "e": 1404, "s": 1187, "text": "An Image contains a 2-D matrix RGB data points which can be defined by the dots point per inch [ DPI ] of the image. The resolution of the image is important because a hi-resolution image will have much more clarity." }, { "code": null, "e":...
Flutter – Managing Form Input Focus
04 Jan, 2021 In this article, we will see how we can manage Form Input Focus in Flutter. When a TextField widget is selected and is taking input, it is said to have focus. Users may shift focus to a TextField simply by tapping on it. Suppose we have a messaging application, when the user navigates to the messaging screen, we can set the focus to the TextField where we type the message. This allows our user to begin typing the message as soon as the screen is visible, without manually tapping on the TextField. Note: We need to manage the lifecycle of focus nodes using a State object as focus nodes are long-lived objects. We can focus on the TextField as soon as it’s visible using the autofocus property. It has the following syntax: Syntax: TextField( autofocus: true, ); We can also focus on a text field on a button tap using focusNode property. It involves three steps: Step 1: Create a FocusNode. The following syntax can be used to focus node: Syntax: FocusNode gfgFocusNode; @override void initState() { super.initState(); gfgFocusNode = FocusNode(); Step 2: Passing the FocusNode to the TextField. You can use the @override decorator with the Widget builder to pass the focus node as shown below. @override Widget build(BuildContext context) { return TextField( focusNode: gfgFocusNode, ); } Step 3: Use requestFocus() to give the focus to the TextField on button tap. The requestFocous() method can be used to focus on the TextField when the form is tapped as shown below: onPressed: () => gfgFocusNode.requestFocus() Example: Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("GFG | Input Focus"), backgroundColor: Color.fromRGBO(15, 157, 88, 1), ), body: InputForm(), ), ); }} // Defining a custom Form widgetclass InputForm extends StatefulWidget { @override _InputFormState createState() => _InputFormState();} // Defining a corresponding State class// This class holds data related to the InputFormclass _InputFormState extends State<InputForm> { // Defining the focus node FocusNode focusNode1; FocusNode focusNode2; @override void initState() { super.initState(); // To manage the lifecycle, creating focus nodes in // the initState method focusNode1 = FocusNode(); focusNode2 = FocusNode(); } // Called when the object is removed // from the tree permanently @override void dispose() { // Clean up the focus nodes // when the form is disposed focusNode1.dispose(); focusNode2.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ TextField( // The first TextField is focused // on as soon as the app starts autofocus: true, focusNode: focusNode1, decoration: InputDecoration( labelText: "First", labelStyle: TextStyle(fontSize: 25.0), ), ), SizedBox( height: 50.0, ), TextField( // The second TextField is focused // on when a user taps the second button focusNode: focusNode2, decoration: InputDecoration( labelText: "Second", labelStyle: TextStyle(fontSize: 25.0), ), ), SizedBox( height: 150.0, ), RaisedButton( onPressed: () { // When the button is pressed, // give focus to the first TextField // using focusNode1. focusNode1.requestFocus(); }, color: Color.fromRGBO(15, 157, 88, 1), textColor: Colors.white, child: Text( "Focus on First Text Field", style: TextStyle( color: Colors.white, ), ), ), SizedBox( height: 50.0, ), RaisedButton( onPressed: () { // When the button is pressed, // give focus to the second // TextField using focusNode2. focusNode2.requestFocus(); }, color: Color.fromRGBO(15, 157, 88, 1), child: Text( "Focus on Second Text Field", style: TextStyle( color: Colors.white, ), ), ) ], ), ); }} Output: Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ListView Class in Flutter Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget Flutter Tutorial Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2021" }, { "code": null, "e": 249, "s": 28, "text": "In this article, we will see how we can manage Form Input Focus in Flutter. When a TextField widget is selected and is taking input, it is said to have focus. Users may shift ...
Sum of elements in given range from Array formed by infinitely concatenating given array
03 Aug, 2021 Given an array arr[](1-based indexing) consisting of N positive integers and two positive integers L and R, the task is to find the sum of array elements over the range [L, R] if the given array arr[] is concatenating to itself infinite times. Examples: Input: arr[] = {1, 2, 3}, L = 2, R = 8Output: 14Explanation:The array, arr[] after concatenation is {1, 2, 3, 1, 2, 3, 1, 2, ...} and the sum of elements from index 2 to 8 is 2 + 3 + 1 + 2 + 3 + 1 + 2 = 14. Input: arr[] = {5, 2, 6, 9}, L = 10, R = 13Output: 22 Naive Approach: The simplest approach to solve the given problem is to iterate over the range [L, R] using the variable i and add the value of arr[i % N] to the sum for each index. After completing the iteration, print the value of the sum as the resultant sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the sum of elements// in a given range of an infinite arrayvoid rangeSum(int arr[], int N, int L, int R){ // Stores the sum of array elements // from L to R int sum = 0; // Traverse from L to R for (int i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum cout << sum;} // Driver Codeint main(){ int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = sizeof(arr) / sizeof(arr[0]); rangeSum(arr, N, L, R); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find the sum of elements // in a given range of an infinite array static void rangeSum(int arr[], int N, int L, int R) { // Stores the sum of array elements // from L to R int sum = 0; // Traverse from L to R for (int i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum System.out.println(sum); } // Driver Code public static void main(String[] args) { int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.length; rangeSum(arr, N, L, R); }} // This code is contributed by Potta Lokesh # Python 3 program for the above approach # Function to find the sum of elements# in a given range of an infinite arraydef rangeSum(arr, N, L, R): # Stores the sum of array elements # from L to R sum = 0 # Traverse from L to R for i in range(L - 1,R,1): sum += arr[i % N] # Print the resultant sum print(sum) # Driver Codeif __name__ == '__main__': arr = [5, 2, 6, 9 ] L = 10 R = 13 N = len(arr) rangeSum(arr, N, L, R) # This code is contributed by divyeshrabadiya07 // C# program for the above approachusing System;class GFG { // Function to find the sum of elements // in a given range of an infinite array static void rangeSum(int[] arr, int N, int L, int R) { // Stores the sum of array elements // from L to R int sum = 0; // Traverse from L to R for (int i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum Console.Write(sum); } // Driver Code public static void Main(string[] args) { int[] arr = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.Length; rangeSum(arr, N, L, R); }} // This code is contributed by ukasp. <script> // Javascript program for the above approach // Function to find the sum of elements// in a given range of an infinite arrayfunction rangeSum(arr, N, L, R){ // Stores the sum of array elements // from L to R let sum = 0; // Traverse from L to R for(let i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum document.write(sum);} // Driver Codelet arr = [ 5, 2, 6, 9 ];let L = 10, R = 13;let N = arr.length rangeSum(arr, N, L, R); // This code is contributed by _saurabh_jaiswal </script> 22 Time Complexity: O(R – L) Auxiliary Space: O(1) Efficient Approach: The above approach can also be optimized by using the Prefix Sum. Follow the steps below to solve the problem: Initialize an array, say prefix[] of size (N + 1) with all elements as 0s. Traverse the array, arr[] using the variable i and update prefix[i] to sum of prefix[i – 1] and arr[i – 1]. Now, the sum of elements over the range [L, R] is given by: the sum of elements in the range [1, R] – sum of elements in the range [1, L – 1]. Initialize a variable, say leftSum as ((L – 1)/N)*prefix[N] + prefix[(L – 1)%N] to store the sum of elements in the range [1, L-1]. Similarly, initialize another variable rightSum as (R/N)*prefix[N] + prefix[R%N] to store the sum of elements in the range [1, R]. After completing the above steps, print the value of (rightSum – leftSum) as the resultant sum of elements over the given range [L, R]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the sum of elements// in a given range of an infinite arrayvoid rangeSum(int arr[], int N, int L, int R){ // Stores the prefix sum int prefix[N + 1]; prefix[0] = 0; // Calculate the prefix sum for (int i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 int leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R int rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum cout << rightsum - leftsum;} // Driver Codeint main(){ int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = sizeof(arr) / sizeof(arr[0]); rangeSum(arr, N, L, R); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find the sum of elements// in a given range of an infinite arraystatic void rangeSum(int arr[], int N, int L, int R){ // Stores the prefix sum int prefix[] = new int[N+1]; prefix[0] = 0; // Calculate the prefix sum for (int i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 int leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R int rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum System.out.print( rightsum - leftsum);} // Driver Codepublic static void main (String[] args){ int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.length; rangeSum(arr, N, L, R); }} // This code is contributed by shivanisinghss2110 # Python 3 program for the above approach # Function to find the sum of elements# in a given range of an infinite arraydef rangeSum(arr, N, L, R): # Stores the prefix sum prefix = [0 for i in range(N + 1)] prefix[0] = 0 # Calculate the prefix sum for i in range(1,N+1,1): prefix[i] = prefix[i - 1] + arr[i - 1] # Stores the sum of elements # from 1 to L-1 leftsum = ((L - 1) // N) * prefix[N] + prefix[(L - 1) % N] # Stores the sum of elements # from 1 to R rightsum = (R // N) * prefix[N] + prefix[R % N] # Print the resultant sum print(rightsum - leftsum) # Driver Codeif __name__ == '__main__': arr = [5, 2, 6, 9] L = 10 R = 13 N = len(arr) rangeSum(arr, N, L, R) # This code is contributed by SURENDRA_GANGWAR. // C# program for the above approachusing System; class GFG{ // Function to find the sum of elements// in a given range of an infinite arraystatic void rangeSum(int []arr, int N, int L, int R){ // Stores the prefix sum int []prefix = new int[N+1]; prefix[0] = 0; // Calculate the prefix sum for (int i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 int leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R int rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum Console.Write( rightsum - leftsum);} // Driver Codepublic static void Main (String[] args){ int []arr = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.Length; rangeSum(arr, N, L, R); }} // This code is contributed by shivanisinghss2110 <script> // JavaScript program for the above approach // Function to find the sum of elements// in a given range of an infinite arrayfunction rangeSum(arr, N, L, R) { // Stores the prefix sum let prefix = new Array(N + 1); prefix[0] = 0; // Calculate the prefix sum for (let i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 let leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R let rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum document.write(rightsum - leftsum);} // Driver Code let arr = [5, 2, 6, 9];let L = 10, R = 13;let N = arr.length;rangeSum(arr, N, L, R); </script> 22 Time Complexity: O(N)Auxiliary Space: O(N) lokeshpotta20 ukasp _saurabh_jaiswal ipg2016107 SURENDRA_GANGWAR shivanisinghss2110 array-range-queries prefix prefix-sum Arrays Mathematical prefix-sum Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Aug, 2021" }, { "code": null, "e": 299, "s": 54, "text": "Given an array arr[](1-based indexing) consisting of N positive integers and two positive integers L and R, the task is to find the sum of array elements over the range [L, ...
Subsequences generated by including characters or ASCII value of characters of given string
09 Jul, 2021 Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contains characters or ASCII value of the characters from the given string. Examples: Input: str = “ab” Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Possible subsequences of the string generated by including either the characters or the ASCII value of the characters from the given string are { 98, b, a, 97, ab, 97b, a98, 9798 }. Therefore, the required output is { b, 98, a, ab, a98, 97, 97b, 9798 }. Input: str = “a” Output: a 97 Approach: Follow the steps below to solve the problem: Iterate over each character of the given string using variable i to generate all possible subsequences of the string. For every ith character, the following three operations can be performed: Include the ith character of str in a subsequence.Do not include the ith character of str in a subsequence.Include the ASCII value of ith character of str in a subsequence. Include the ith character of str in a subsequence. Do not include the ith character of str in a subsequence. Include the ASCII value of ith character of str in a subsequence. Therefore, the recurrence relation to solve this problem is as follows: FindSub(str, res, i) = { FindSub(str, res, i + 1), FindSub(str, res + str[i], i + 1), FindSub(str, res + ASCII(str[i]), i + 1) } res = subsequence of the string i = index of a character in str Using the above recurrence relation, print all possible subsequences based on the given conditions. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function to print subsequences containing// ASCII value of the characters or the// the characters of the given stringvoid FindSub(string str, string res, int i){ // Base Case if (i == str.length()) { // If length of the // subsequence exceeds 0 if (res.length() > 0) { // Print the subsequence cout << res << " "; } return; } // Stores character present at // i-th index of str char ch = str[i]; // If the i-th character is not // included in the subsequence FindSub(str, res, i + 1); // Including the i-th character // in the subsequence FindSub(str, res + ch, i + 1); // Include the ASCII value of the // ith character in the subsequence FindSub(str, res + to_string(int(ch)), i + 1);} // Driver Codeint main(){ string str = "ab"; string res = ""; // Stores length of str int N = str.length(); FindSub(str, res, 0);} // This code is contributed by ipg2016107 // Java program to implement// the above approachclass GFG { // Function to print subsequences containing // ASCII value of the characters or the // the characters of the given string static void FindSub(String str, String res, int i) { // Base Case if (i == str.length()) { // If length of the // subsequence exceeds 0 if (res.length() > 0) { // Print the subsequence System.out.print(res + " "); } return; } // Stores character present at // i-th index of str char ch = str.charAt(i); // If the i-th character is not // included in the subsequence FindSub(str, res, i + 1); // Including the i-th character // in the subsequence FindSub(str, res + ch, i + 1); // Include the ASCII value of the // ith character in the subsequence FindSub(str, res + (int)ch, i + 1); ; } // Driver Code public static void main(String[] args) { String str = "ab"; String res = ""; // Stores length of str int N = str.length(); FindSub(str, res, 0); }} # Python3 program to implement# the above approach # Function to print subsequences containing# ASCII value of the characters or the# the characters of the given stringdef FindSub(string , res, i) : # Base Case if (i == len(string)): # If length of the # subsequence exceeds 0 if (len(res) > 0) : # Print the subsequence print(res, end=" "); return; # Stores character present at # i-th index of str ch = string[i]; # If the i-th character is not # included in the subsequence FindSub(string, res, i + 1); # Including the i-th character # in the subsequence FindSub(string, res + ch, i + 1); # Include the ASCII value of the # ith character in the subsequence FindSub(string, res + str(ord(ch)), i + 1); # Driver Codeif __name__ == "__main__" : string = "ab"; res = ""; # Stores length of str N = len(string); FindSub(string, res, 0); # This code is contributed by AnkitRai01 // C# program to implement// the above approachusing System; class GFG{ // Function to print subsequences containing// ASCII value of the characters or the// the characters of the given stringstatic void FindSub(string str, string res, int i){ // Base Case if (i == str.Length) { // If length of the // subsequence exceeds 0 if (res.Length > 0) { // Print the subsequence Console.Write(res + " "); } return; } // Stores character present at // i-th index of str char ch = str[i]; // If the i-th character is not // included in the subsequence FindSub(str, res, i + 1); // Including the i-th character // in the subsequence FindSub(str, res + ch, i + 1); // Include the ASCII value of the // ith character in the subsequence FindSub(str, res + (int)ch, i + 1);} // Driver Codepublic static void Main(String[] args){ string str = "ab"; string res = ""; // Stores length of str int N = str.Length; FindSub(str, res, 0);}} // This code is contributed by AnkitRai01 <script> // JavaScript program to implement// the above approach // Function to print subsequences containing// ASCII value of the characters or the// the characters of the given stringfunction FindSub(str, res, i){ // Base Case if (i === str.length) { // If length of the // subsequence exceeds 0 if (res.length > 0) { // Print the subsequence document.write(res + " "); } return; } // Stores character present at // i-th index of str var ch = str[i]; // If the i-th character is not // included in the subsequence FindSub(str, res, i + 1); // Including the i-th character // in the subsequence FindSub(str, res + ch, i + 1); // Include the ASCII value of the // ith character in the subsequence FindSub(str, res + ch.charCodeAt(0), i + 1);} // Driver Codevar str = "ab";var res = ""; // Stores length of strvar N = str.length; FindSub(str, res, 0); // This code is contributed by rdtank </script> b 98 a ab a98 97 97b 9798 Time Complexity: O(3N) Auxiliary Space: O(N) ankthon ipg2016107 rdtank abhishek0719kadiyan strings subsequence Dynamic Programming Mathematical Recursion Strings Strings Dynamic Programming Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Find if there is a path between two vertices in an undirected graph Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jul, 2021" }, { "code": null, "e": 273, "s": 54, "text": "Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contains characters or ASCII va...
Python – Itertools.starmap()
13 Apr, 2022 The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is starmap().Note: For more information, refer to Python Itertools When an iterable is contained within another iterable and certain function has to be applied on them, starmap() is used. The starmap() considers each element of the iterable within another iterable as a separate item. It is similar to map(). This function comes under the category terminating iterators.Syntax : starmap(function, iterable) The function can be a built-in one or user-defined or even a lambda function. To understand the difference between map() and starmap() look at the code snippets below : Python3 li =[(2, 5), (3, 2), (4, 3)] new_li = list(map(pow, li)) print(new_li) TypeError Traceback (most recent call last) in 1 li=[(2, 5), (3, 2), (4, 3)] ----> 2 new_li=list(map(pow, li)) 3 print(new_li) TypeError: pow expected at least 2 arguments, got 1 Here, the map considers each tuple within the list as a single argument and thus the error raises. The starmap() overcomes this issue. Look at the code snippet below: Python3 from itertools import starmap li =[(2, 5), (3, 2), (4, 3)] new_li = list(starmap(pow, li)) print(new_li) [32, 9, 64] The internal working of the starmap() can be implemented as given below. def startmap(function, iterable): for it in iterables: yield function(*it) Here ‘it’ also denotes an iterable.Let us look at another example that differentiates map() and starmap(). We can apply a function to each element in the iterable using map(). To say we need to add a constant number to each element in the lists, we can use map(). Python3 li =[2, 3, 4, 5, 6, 7] # adds 2 to each element in listans = list(map(lambda x:x + 2, li)) print(ans) [4, 5, 6, 7, 8, 9] What if we want to add different numbers to different elements of the list ? Now, starmap() must be used. Python3 from itertools import starmap li =[(2, 3), (3, 1), (4, 6), (5, 3), (6, 5), (7, 2)] ans = list(starmap(lambda x, y:x + y, li)) print(ans) [5, 4, 10, 8, 11, 9] Practical example of using starmap():Consider a list containing coordinates of various triangles. We are supposed to apply Pythagoras theorem and find output which coordinates form a right-angled triangle. It can be implemented as given below : Python3 from itertools import starmap co_ordinates =[(2, 3, 4), (3, 4, 5), (6, 8, 10), (1, 5, 7), (7, 4, 10)] # Set true if coordinates form# a right-triangle else falseright_triangles = list(starmap(lambda x, y, z:True if ((x * x)+(y * y))==(z * z) else False, co_ordinates)) print("tuples which form right angled triangle :", right_triangles, end ="\n\n") print("The right triangle coordinates are :", end ="") # to print the coordinatesfor i in range (0, len(right_triangles)): if right_triangles[i]== True: print(co_ordinates[i], end =" ") sooda367 sweetyty Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2022" }, { "code": null, "e": 309, "s": 28, "text": "The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings ver...
Memory Organisation in Computer Architecture
13 Feb, 2020 The memory is organized in the form of a cell, each cell is able to be identified with a unique number called address. Each cell is able to recognize control signals such as “read” and “write”, generated by CPU when it wants to read or write address. Whenever CPU executes the program there is a need to transfer the instruction from the memory to CPU because the program is available in memory. To access the instruction CPU generates the memory request. Memory Request:Memory request contains the address along with the control signals. For Example, When inserting data into the stack, each block consumes memory (RAM) and the number of memory cells can be determined by the capacity of a memory chip. Example: Find the total number of cells in 64k*8 memory chip. Size of each cell = 8 Number of bytes in 64k = (2^6)*(2^10) Therefore, the total number of cells = 2^16 cells With the number of cells, the number of address lines required to enable one cell can be determined. Word Size:It is the maximum number of bits that a CPU can process at a time and it depends upon the processor. Word size is a fixed size piece of data handled as a unit by the instruction set or the hardware of a processor. Word size varies as per the processor architectures because of generation and the present technology, it could be low as 4-bits or high as 64-bits depending on what a particular processor can handle. Word size is used for a number of concepts like Addresses, Registers, Fixed-point numbers, Floating-point numbers. Technical Scripter 2019 Computer Organization & Architecture GATE CS Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Computer Architecture | Flynn's taxonomy I2C Communication Protocol Architecture of Distributed Shared Memory(DSM) ARM processor and its Features Direct Access Media (DMA) Controller in Computer Architecture Layers of OSI Model Three address code in Compiler Types of Operating Systems ACID Properties in DBMS Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Feb, 2020" }, { "code": null, "e": 508, "s": 52, "text": "The memory is organized in the form of a cell, each cell is able to be identified with a unique number called address. Each cell is able to recognize control signals such as ...
Remove duplicates from a string using STL in C++
28 May, 2019 Given a string S, remove duplicates in this string using STL in C++ Examples: Input: Geeks for geeks Output: Gefgkors Input: aaaaabbbbbb Output: ab Approach:The consecutive duplicates of the string can be removed using the unique() function provided in STL. Below is the implementation of the above approach. #include <bits/stdc++.h>using namespace std; int main(){ string str = "aaaaabbbbbb"; sort(str.begin(), str.end()); // Using unique() method auto res = unique(str.begin(), str.end()); cout << string(str.begin(), res) << endl;} ab cpp-strings STL C++ cpp-strings STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Inheritance in C++ vector erase() and clear() in C++ Substring in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Object Oriented Programming in C++ Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ 2D Vector In C++ With User Defined Size
[ { "code": null, "e": 53, "s": 25, "text": "\n28 May, 2019" }, { "code": null, "e": 121, "s": 53, "text": "Given a string S, remove duplicates in this string using STL in C++" }, { "code": null, "e": 131, "s": 121, "text": "Examples:" }, { "code": null,...
int() function in Python
21 Sep, 2021 Python int() function returns an integer from a given object or converts a number in a given base to decimal. int(string, base) string : consists of 1’s and 0’s base : (integer value) base of the number. Returns an integer value, which is equivalent of binary string in the given base. TypeError : Returns TypeError when any data type other than string or integer is passed in its equivalent position. Python3 # Python3 program for implementation# of int() functionnum = 13 String = '187' # Stores the result value of# binary "187" and num additionresult_1 = int(String) + numprint("int('187') + 13 = ", result_1, "\n") # Example_2str = '100' print("int('100') with base 2 = ", int(str, 2))print("int('100') with base 4 = ", int(str, 4))print("int('100') with base 8 = ", int(str, 8))print("int('100') with base 16 = ", int(str, 16)) Output : int('187') + 13 = 200 int('100') with base 2 = 4 int('100') with base 4 = 16 int('100') with base 8 = 64 int('100') with base 16 = 256 Python3 # Python3 program for implementation# of int() function # "111" taken as the binary stringbinaryString = "111" # Stores the equivalent decimal# value of binary "111"Decimal = int(binaryString, 2) print("Decimal equivalent of binary 111 is", Decimal) # "101" taken as the octal stringoctalString = "101" # Stores the equivalent decimal# value of binary "101"Octal = int(octalString, 8) print("Decimal equivalent of octal 101 is", Octal) Output : Decimal equivalent of binary 111 is 7 Decimal equivalent of octal 101 is 65 Python3 # Python3 program to demonstrate# error of int() function # when the binary number is not# stored in as stringbinaryString = 111 # it returns an error for passing an# integer in place of stringdecimal = int(binaryString, 2) print(decimal) Output : TypeError: int() can't convert non-string with explicit base Python3 try: var = "Geeks" print(int(var))except ValueError as e: print(e) Output: invalid literal for int() with base 10: ‘Geeks’ It is used in all the standard conversions. For example conversion of binary to decimal, octal to decimal, hexadecimal to decimal. rajatrj20 kumar_satyam Python-Built-in-functions Python 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 Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Sep, 2021" }, { "code": null, "e": 164, "s": 54, "text": "Python int() function returns an integer from a given object or converts a number in a given base to decimal." }, { "code": null, "e": 182, "s": 164, "tex...
How to add Slider in Next.js ?
15 Nov, 2021 In this article, we are going to learn how we can add File Dropper in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally. Approach: To add our Slider we are going to use the react-range package. The react-range package helps us to integrate sliders anywhere in our app. So first, we will install the react-range package and then we will add a slider on our homepage. Create NextJS Application: You can create a new NextJs project using the below command: npx create-next-app gfg Install the required package: Now we will install the react-range package using the below command: npm i react-range Project Structure: It will look like this. Adding the Slider: After installing the react-range package we can easily add Slider in our app. For this example, we are going to add a slider to our homepage. Add the below content in the index.js file: Javascript import * as React from 'react';import { Range } from 'react-range'; export default class Slider extends React.Component { state = { values: [50] }; render() { return ( <> <h3>GeeksforGeeks- Slider</h3> <Range step={0.1} min={0} max={100} values={this.state.values} onChange={(values) => this.setState({ values })} renderTrack={({ props, children }) => ( <div {...props} style={{ ...props.style, height: '6px', width: '100%', backgroundColor: '#ccc' }} > {children} </div> )} renderThumb={({ props }) => ( <div {...props} style={{ ...props.style, height: '42px', width: '42px', backgroundColor: '#999' }} /> )} /> </> ); }} Explanation: In the above example first, we are importing our Range component from the installed package. After that, we are creating a state to store the starting value. Then, we are adding our Range component. In the range component, we are setting the minimum value, maximum value, onChange function, and current Value. Steps to run the application: Run the below command in the terminal to run the app. npm run dev Next.js React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Nov, 2021" }, { "code": null, "e": 336, "s": 28, "text": "In this article, we are going to learn how we can add File Dropper in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for dif...
Nice and Renice Command in Linux with Examples
29 Aug, 2021 nice command in Linux helps in execution of a program/process with modified scheduling priority. It launches a process with a user-defined scheduling priority. In this, if we give a process a higher priority, then Kernel will allocate more CPU time to that process. Whereas the renice command allows you to change and modify the scheduling priority of an already running process. Linux Kernel schedules the process and allocates CPU time accordingly for each of them. 1. To check the nice value of a process. ps -el | grep terminal The eight highlighted value is the nice value of the process. 2. To set the priority of a process nice -10 gnome-terminal This will set the nice value of the mentioned process. 3. To set the negative priority for a process nice --10 gnome-terminal This will set the negative priority for the process. 4.changing priority of the running process. sudo renice -n 15 -p 77982 This will change the priority of the process with pid 77982. 5. To change the priority of all programs of a specific group. renice -n 10 -g 4 This command will set all the processes of gid 4 priority to 10. 6. To change the priority of all programs of a specific user. sudo renice -n 10 -u 2 This will set all the processes of user 2 to 10. adnanirshad158 simmytarika5 linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples 'crontab' in Linux with Examples TCP Server-Client implementation in C Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C Docker - COPY Instruction
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Aug, 2021" }, { "code": null, "e": 522, "s": 52, "text": "nice command in Linux helps in execution of a program/process with modified scheduling priority. It launches a process with a user-defined scheduling priority. In this, if we...
How to show calendar only click on icon using JavaScript ?
03 Aug, 2021 Bootstrap is one of the widely preferred CSS frameworks for the development of an interactive user interface. Bootstrap comes bundled with a wide range of components, plugin, and utilities that make designing a webpage much easier. The date-picker is one such interactive feature provided by Bootstrap to select a date from a drop-down calendar which is directly reflected in the input field eliminating the hassle to enter the date manually. Date picker can be customized as per user requirements. Whether the calendar opening in a form of a drop-down on clicking the icon only or focussing on the input field entirely, it depends on the need of the user. However, both options are open for one to choose from. The drop-down calendar is available as a small overlay and automatically disappears once the user clicks anywhere outside the calendar on the web page. This functioning of the calendar is made possible through jQuery and JavaScript functions. Below are the examples for Date-picker which displays the calendar when clicked on the icon. Approach 1: The calendar icon is appended to the input field where the date is to input using the input-group-prepend class. The span for the icon is set using the input-group-text class. The icon when clicked triggers the setDatepicker() function and the setDatepicker() function accepts the current event as an argument. Next, the class name of the root (parent) of the icon is obtained using the parent() and attr() method of JavaScript. As the class-name is obtained next the space in the class-name is replaced by ‘.’. This step is important as the class name is required in the class selector in the jQuery datepicker() function. The datepicker() function specifies the format of date, orientation of the calendar, closing and autofocus behaviour. Once the calendar is displayed the user can choose the date and it is reflected in the input field. html <!DOCTYPE html><html> <head> <!-- Importing jquery cdn --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <!-- Importing icon cdn --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Importing core bootstrap cdn --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> <!-- Importing datepicker cdn --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"> </script></head> <body> <!-- Container class contains the date field --> <div class="container" style="max-width: 250px;"> <div class="form-group m-1"> <label class="font-weight-bold" for="dob"> Date of Birth: </label> <!-- Input field along with calendar icon and --> <div class="input-group date"> <!-- Sets the calendar icon --> <span class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-calendar" onclick="setDatepicker(this)"> </i> </span> </span> <!-- Accepts the input from calendar --> <input class="form-control" type="text" name="dob" id="dob" value=""> </div> </div> </div> <!-- JavaScript to control the actions of the date picker --> <script type="text/javascript"> function setDatepicker(_this) { /* Get the parent class name so we can show date picker */ let className = $(_this).parent() .parent().parent().attr('class'); // Remove space and add '.' let removeSpace = className.replace(' ', '.'); // jQuery class selector $("." + removeSpace).datepicker({ format: "dd/mm/yyyy", // Positioning where the calendar is placed orientation: "bottom auto", // Calendar closes when cursor is // clicked outside the calendar autoclose: true, showOnFocus: "false" }); } </script></body> </html> Output Approach 2: The second approach is comparatively easier. It accomplishes the target in fewer lines of code. This code mainly makes use of jQuery. The date-picker button Image also serves the same purpose as the icon in the previous example. The buttonImageOnly does not only add an image to the button but it also adds an image to the document. As we click in the image the calendar is displayed and the user can select the date which is immediately reflected in the input field. The button image in this is pre-downloaded and stored in the local device. The calendar closes when clicked outside the calendar. html <html> <head> <!-- Importing jquery cdn --> <link href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="Stylesheet" type="text/css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"> </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <!-- JavaScript function to display the calendar --> <script language="javascript"> $(document).ready(function () { $("#txtdate").datepicker({ showOn: "button", // Button image stored on local device buttonImage: "./icons8-calendar-48.png", buttonImageOnly: true }); }); </script> <!-- Customizing the datepicker button image --> <style type="text/css"> .ui-datepicker-trigger { max-height: 28px; } </style></head> <body> <form class="form-group"> Date : <input id="txtdate" type="text" class="form-control"> </form></body></html> Output jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. Bootstrap-Misc HTML-Misc JavaScript-Misc jQuery-Misc Picked Bootstrap CSS HTML JavaScript JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to make Bootstrap table with sticky table head? How to Align modal content box to center of any screen? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 261, "s": 28, "text": "Bootstrap is one of the widely preferred CSS frameworks for the development of an interactive user interface. Bootstrap comes bundled with a wide range of components, plugin, ...
C program to store Student records as Structures and Sort them by Name
17 Jan, 2019 Given student’s records with each record containing id, name and age of a student. Write a C program to read these records and display them in sorted order by name. Examples: Input: Student Records= { {Id = 1, Name = bd, Age = 12 }, {Id = 2, Name = ba, Age = 10 }, {Id = 3, Name = bc, Age = 8 }, {Id = 4, Name = aaz, Age = 9 }, {Id = 5, Name = az, Age = 10 } } Output: {{Id = 4, Name = aaz, Age = 9 }, {Id = 5, Name = az, Age = 10 }, {Id = 2, Name = ba, Age = 10 }, {Id = 3, Name = bc, Age = 8 }, {Id = 1, Name = bd, Age = 12 } } Approach: This problem is solved in following steps: Create a structure with fields id, name and age. Read the students records in the structure Define a comparator by setting up rules for comparison. Here names can be sorted by the help of strcmp() method. Now sort the structure based on the defined comparator with the help of qsort() method. Print the sorted students records. Program: // C program to read Student records// like id, name and age,// and display them in sorted order by Name #include <stdio.h>#include <stdlib.h>#include <string.h> // struct person with 3 fieldsstruct Student { char* name; int id; char age;}; // setting up rules for comparison// to sort the students based on namesint comparator(const void* p, const void* q){ return strcmp(((struct Student*)p)->name, ((struct Student*)q)->name);} // Driver programint main(){ int i = 0, n = 5; struct Student arr[n]; // Get the students data arr[0].id = 1; arr[0].name = "bd"; arr[0].age = 12; arr[1].id = 2; arr[1].name = "ba"; arr[1].age = 10; arr[2].id = 3; arr[2].name = "bc"; arr[2].age = 8; arr[3].id = 4; arr[3].name = "aaz"; arr[3].age = 9; arr[4].id = 5; arr[4].name = "az"; arr[4].age = 10; // Print the Unsorted Structure printf("Unsorted Student Records:\n"); for (i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].id, arr[i].name, arr[i].age); } // Sort the structure // based on the specified comparator qsort(arr, n, sizeof(struct Student), comparator); // Print the Sorted Structure printf("\n\nStudent Records sorted by Name:\n"); for (i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].id, arr[i].name, arr[i].age); } return 0;} Unsorted Student Records: Id = 1, Name = bd, Age = 12 Id = 2, Name = ba, Age = 10 Id = 3, Name = bc, Age = 8 Id = 4, Name = aaz, Age = 9 Id = 5, Name = az, Age = 10 Student Records sorted by Name: Id = 4, Name = aaz, Age = 9 Id = 5, Name = az, Age = 10 Id = 2, Name = ba, Age = 10 Id = 3, Name = bc, Age = 8 Id = 1, Name = bd, Age = 12 Note: The structures can be sorted according to any field, based on the rules defined in the comparator function. To know more about comparator function. refer Comparator function of qsort() in C C-Struct-Union-Enum Sorting Quiz C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jan, 2019" }, { "code": null, "e": 217, "s": 52, "text": "Given student’s records with each record containing id, name and age of a student. Write a C program to read these records and display them in sorted order by name." }, {...
Problem on Time Speed and Distance
13 Sep, 2021 Question 1: A racing car covers a certain distance at a speed of 320 km/hr in 5 hours. To cover the same distance in 5/3 hours it must travel at a speed of: Solution: Given Distance is constant. So, Speed is inversely proportional to time. Ratio of time 5 : 5/3 Ratio of time becomes 3 : 1 Then, Ratio of speed 1 : 3 1 unit -> 320 km/hr 3 unit -> 320 x 3 = 960 km/hr is required speed Question 2: A train running at a speed of 36 km/hr and 100 meter long. Find the time in which it passes a man standing near the railway line is : Solution: Speed = 36 km/hr Change in m/s So, speed = 36 * 5/18 = 10 m/s Time required = Distance/speed = 100/10 = 10 second Question 3: If an employee walks 10 km at a speed of 3 km/hr, he will be late by 20 minutes. If he walks at 4 km/hr, how early from the fixed time he will reach ? Solution: Time taken at 3 km/hr = Distance/speed = 10/3 Actual time is obtained by subtracting the late time So, Actual time = 10/3 – 1/3 = 9/3 = 3 hour Time taken at 4 km/hr = 10/4 hr Time difference = Actual time – time taken at 4 km/hr = 3 – 10/4 = 1/2 hour Hence, he will be early by 30 minutes. Question 4: The diameter of each wheel of a truck is 140 cm, If each wheel rotates 300 times per minute then the speed of the truck (in km/hr) (take pi=22/7) Solution: Circumference of the wheel= 2 * 22/7 * r = 2 * 22/7 * 140/2 = 440 cm Speed of the car = (440 * 300 * 60)/(1000 * 100 ) = 79.2 km/hr Question 5: A man drives at the rate of 18 km/hr, but stops at red light for 6 minutes at the end of every 7 km. The time that he will take to cover a distance of 90 km is Solution: Total Red light at the end of 90 km = 90/7 = 12 Red light + 6 km Time taken in 12 stops= 12 x 6 = 72 minutes Time taken by the man to cover the 90 km with 18 km/hr without stops = 90/18 = 5 hours Total time to cover total distance = 5 hour + 1 hour 12 minute = 6 hour 12 minute Question 6: Two jeep start from a police station with a speed of 20 km/hr at intervals of 10 minutes.A man coming from opposite direction towards the police station meets the jeep at an interval of 8 minutes.Find the speed of the man. Solution: Jeep Jeep + man Ratio of time 10 min : 8 min Ratio of speed 8 : 10 4 : 4+1 Here, 4 units -> 20 km/hr 1 unit -> 5 km/hr Speed of the man = 1 unit = 1 x 5 = 5 km/hr Question 7: Two city A and B are 27 km away. Two buses start from A and B in the same direction with speed 24 km/hr and 18 km/hr respectively. Both meet at point C beyond B. Find the distance BC. Solution: Relative speed = 24 – 18 = 6 km/hr Time required by faster bus to overtake the slower bus = Distance/time =27/6 hr Distance between B and C= 18*(27/6)= 81 km Question 8: A man travels 800 km by train at 80 km/hr, 420 km by car at 60 km/hr and 200 km by cycle at 20 km/hr. What is the average speed of the journey? Solution: Avg. Speed = Total distance/time taken (800 + 420 + 200) / [(800/80) + (420/60) + (200/20)] =>1420 / (10 + 7 + 10) =>1420/27 =>1420/27 km/hr Question 9: Ram and Shyam start at the same with speed 10 km/hr and 11 km/hr respectively. If Ram takes 48 minutes longer than Shyam in covering the journey, then find the total distance of the journey. Solution: Speed Ratio 10 : 11 Time ratio 11 : 10 Ram takes 1 hour means 60 minutes more than Shyam. But actual more time = 48 minute. 60 unit -> 48 min 1 unit -> 4/5 Distance travelled by them= Speed x time = 11 x 10 = 110 unit Actual distance travelled = 110 x 4/5 = 88 km Question 10: A person covered a certain distance at some speed. Had he moved 4 km/hr faster, he would have taken 30 minutes less. If he had moved 3 km/hr slower, he would have taken 30 minutes more. Find the distance (in km) Solution: Distance = [S1S2/ (S1– S2)] x T S1 = initial speed S2 = new speed Distance travelled by both are same so put equal [S (S + 4) / 4 ] * (30/60) =[ S (S – 3)/ 3 ]* (30/60) S = 24 Put in 1st Distance=(24 * 28) / 4 * (30/60) = 84 km Question 11: Ram and Shyam start from the same place P at same time towards Q, which are 60km apart. Ram’s speed is 4 km/hr more than that of Shyam.Ram turns back after reaching Q and meet Shyam at 12 km distance from Q.Find the speed of Shyam. Solution: Let the speed of the Shyam = x km/hr Then Ram speed will be = (x + 4) km/hr Total distance covered by Ram = 60 + 12 = 72 km Total distance covered by Shyam = 60 – 12 = 48 km Acc. to question, their run time are same. 72/ (x + 4) = 48/ x 72x = 48x + 192 24x= 192 x= 8 Shyam speed is 8 km/hr Question 12: A and B run a kilometre and A wins by 20 second. A and C run a kilometre and A wins by 250 m. When B and C run the same distance, B wins by 25 second. The time taken by A to run a kilometre is Solution: Let the time taken by A to cover 1 km = x sec Time taken by B and C to cover the same distance are x + 20 and x + 45 respectively Given A travels 1000 then C covers only 750. Distance A(1000) C(750) Ratio 4 : 3 Time 3 : 4 A/C = 3/4 = x/(x+45) 3x + 135 = 4x x =135 Time taken by A is 2 min 15 second PreetamKalal theInjuredLion gopalsakhwala18 rajnikant123 gouthamlucky68 Placements QA - Placements Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 20 Puzzles Commonly Asked During SDE Interviews Amazon WOW Interview Experience for SDE 1 (2021) Programming Language For Placement - C++, Java or Python? TCS Ninja Interview Experience and Interview Questions Interview Preparation Mixture and Alligation Problems on Work and Wages
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Sep, 2021" }, { "code": null, "e": 296, "s": 54, "text": "Question 1: A racing car covers a certain distance at a speed of 320 km/hr in 5 hours. To cover the same distance in 5/3 hours it must travel at a speed of: Solution: Given D...
Python – Print the last word in a sentence
23 Nov, 2021 Given a string, the task is to write a Python program to print the last word in that string. Examples: Input: sky is blue in color Output: color Explanation: color is last word in the sentence. Input: Learn algorithms at geeksforgeeks Output: geeksforgeeks Explanation: color is last word in the sentence. Approach #1: Using For loop + String Concatenation Scan the sentence Take an empty string, newstring. Traverse the string in reverse order and add character to newstring using string concatenation. Break the loop till we get first space character. Reverse newstring and return it (it is the last word in the sentence). Below is the implementation of the above approach: Python3 # Function which returns last worddef lastWord(string): # taking empty string newstring = "" # calculating length of string length = len(string) # traversing from last for i in range(length-1, 0, -1): # if space is occurred then return if(string[i] == " "): # return reverse of newstring return newstring[::-1] else: newstring = newstring + string[i] # Driver codestring = "Learn algorithms at geeksforgeeks"print(lastWord(string)) Output: geeksforgeeks Approach #2: Using split() method As all the words in a sentence are separated by spaces. We have to split the sentence by spaces using split(). We split all the words by spaces and store them in a list. The last element in the list is the answer Below is the implementation of the above approach: Python3 # Function which returns last worddef lastWord(string): # split by space and converting # string to list and lis = list(string.split(" ")) # length of list length = len(lis) # returning last element in list return lis[length-1] # Driver codestring = "Learn algorithms at geeksforgeeks"print(lastWord(string)) Output: geeksforgeeks adnanirshad158 Python string-programs Python Python Programs 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 Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Nov, 2021" }, { "code": null, "e": 146, "s": 53, "text": "Given a string, the task is to write a Python program to print the last word in that string." }, { "code": null, "e": 156, "s": 146, "text": "Examples:" ...
Longest subsequence where every character appears at-least k times
22 Jun, 2022 Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times. Examples: Input : str = "geeksforgeeks" k = 2 Output : geeksgeeks Every character in the output subsequence appears at-least 2 times. Input : str = "aabbaabacabb" k = 5 Output : aabbaabaabb Method 1 (Brute force) We generate all subsequences. For every subsequence count distinct characters in it and find the longest subsequence where every character appears at-least k times. Method 2 (Efficient way) 1. Find the frequency of the string and store it in an integer array of size 26 representing the alphabets. 2. After finding the frequency iterate the string character by character and if the frequency of that character is greater than or equal to the required number of repetitions then print that character then and there only. C++ Java Python3 C# Javascript // C++ program to Find longest subsequence where// every character appears at-least k times#include<bits/stdc++.h>using namespace std; const int MAX_CHARS = 26; void longestSubseqWithK(string str, int k) { int n = str.size(); // Count frequencies of all characters int freq[MAX_CHARS] = {0}; for (int i = 0 ; i < n; i++) freq[str[i] - 'a']++; // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0 ; i < n ; i++) if (freq[str[i] - 'a'] >= k) cout << str[i]; } // Driver codeint main() { string str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); return 0;} // Java program to Find longest subsequence where// every character appears at-least k times class GFG { static final int MAX_CHARS = 26; static void longestSubseqWithK(String str, int k) { int n = str.length(); // Count frequencies of all characters int freq[] = new int[MAX_CHARS]; for (int i = 0; i < n; i++) { freq[str.charAt(i) - 'a']++; } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0; i < n; i++) { if (freq[str.charAt(i) - 'a'] >= k) { System.out.print(str.charAt(i)); } } } // Driver code static public void main(String[] args) { String str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); }} // This code is contributed by Rajput-Ji # Python3 program to Find longest subsequence where# every character appears at-least k times MAX_CHARS = 26 def longestSubseqWithK(s, k): n = len(s) # Count frequencies of all characters freq = [0]*MAX_CHARS for i in range(n): freq[ord(s[i]) - ord('a')]+=1 # Traverse given string again and print # all those characters whose frequency # is more than or equal to k. for i in range(n ): if (freq[ord(s[i]) - ord('a')] >= k): print(s[i],end="") # Driver codeif __name__ == "__main__": s = "geeksforgeeks" k = 2 longestSubseqWithK(s, k) // C# program to Find longest subsequence where// every character appears at-least k timesusing System;public class GFG { static readonly int MAX_CHARS = 26; static void longestSubseqWithK(String str, int k) { int n = str.Length; // Count frequencies of all characters int []freq = new int[MAX_CHARS]; for (int i = 0; i < n; i++) { freq[str[i]- 'a']++; } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0; i < n; i++) { if (freq[str[i] - 'a'] >= k) { Console.Write(str[i]); } } } // Driver code static public void Main() { String str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); }} // This code is contributed by Rajput-Ji <script> // Javascript program to find longest subsequence// where every character appears at-least k timeslet MAX_CHARS = 26; function longestSubseqWithK(str, k){ let n = str.length; // Count frequencies of all characters let freq = new Array(MAX_CHARS); for(let i = 0; i < freq.length; i++) { freq[i] = 0 } for(let i = 0; i < n; i++) { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for(let i = 0; i < n; i++) { if (freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] >= k) { document.write(str[i]); } }} // Driver codelet str = "geeksforgeeks";let k = 2; longestSubseqWithK(str, k); // This code is contributed by avanitrachhadiya2155 </script> geeksgeeks This code has a time complexity of O(n) where n is the size of the string. Auxiliary Space: O(n), where n is the length of the string. This is because when string is passed to any function it is passed by value and creates a copy of itself in stack. Method 3 (Efficient way – Using HashMap) C++ Java Python3 Javascript // C++ program to Find longest subsequence where every// character appears at-least k times#include <bits/stdc++.h>using namespace std; void longestSubseqWithK(string str, int k){ int n = str.size(); map<char, int> hm; // Count frequencies of all characters for (int i = 0; i < n; i++) { char c = str[i]; hm++; } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0; i < n; i++) { char c = str[i]; if (hm >= k) { cout << c; } }} // Driver codeint main(){ string str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); return 0;} // This code is contributed by rakeshsahni /*package whatever //do not write package name here */// Java program to Find longest subsequence where every// character appears at-least k times import java.io.*;import java.util.HashMap; class GFG { static void longestSubseqWithK(String str, int k) { int n = str.length(); HashMap<Character, Integer> hm = new HashMap<>(); // Count frequencies of all characters for (int i = 0; i < n; i++) { char c = str.charAt(i); if (hm.containsKey(c)) hm.put(c, hm.get(c) + 1); else hm.put(c, 1); } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0; i < n; i++) { char c = str.charAt(i); if (hm.get(c) >= k) { System.out.print(c); } } } // Driver code static public void main(String[] args) { String str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); }} // This code is contributed by Chandan-Bedi # Python3 program to Find longest subsequence where every# character appears at-least k timesdef longestSubseqWithK(Str, k): n = len(Str) hm = {} # Count frequencies of all characters for i in range(n): c = Str[i] if(c in hm): hm += 1 else: hm = 1 # Traverse given string again and print # all those characters whose frequency # is more than or equal to k. for i in range(n): c = Str[i] if (hm >= k): print(c,end="") # Driver codeStr = "geeksforgeeks"k = 2longestSubseqWithK(Str, k) # This code is contributed by shinjanpatra <script> // JavaScript program to Find longest subsequence where every// character appears at-least k timesfunction longestSubseqWithK(str, k){ let n = str.length; let hm = new Map(); // Count frequencies of all characters for (let i = 0; i < n; i++) { let c = str[i]; if(hm.has(c)){ hm.set(c,hm.get(c)+1); } else hm.set(c,1); } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (let i = 0; i < n; i++) { let c = str[i]; if (hm.get(c) >= k) { document.write(c); } }} // Driver codelet str = "geeksforgeeks";let k = 2;longestSubseqWithK(str, k); // This code is contributed by shinjanpatra<script> geeksgeeks Time complexity: O(n*log(n)). This is because the time complexity of inserting an element in map is O(log(n)). Auxiliary Space: O(n), where n is the length of the string. This is because when string is passed to any function it is passed by value and creates a copy of itself in stack. YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pSjFRi_v8iY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji ukasp PranjalRanjan2 avanitrachhadiya2155 chandanbedi22 vikas0713 rakeshsahni simmytarika5 shinjanpatra anandkumarshivam2266 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Reverse words in a given string What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Reverse string in Python (6 different ways) Remove duplicates from a given string stringstream in C++ and its Applications Sort string of characters Given a string, find its first non-repeating character
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jun, 2022" }, { "code": null, "e": 173, "s": 53, "text": "Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times." }, { "code": null, "e": 184, "s": 173...
Python code formatting using Black
05 Aug, 2021 Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black comes into play, Black ensures code quality. Linters such as pycodestyle or flake8 show whether your code is according to PEP8 format, which is the official Python style guide. But the problem is that it gives a burden to the developers to fix this formatting style. Here Black comes into play not only does it report format errors but also fixes them. To quote the project README: Black is the uncompromising Python code formatter. By using it, you agree to cede control over minutiae of hand-formatting. In return, Black gives you speed, determinism, and freedom from pycodestyle nagging about formatting. You will save time and mental energy for more important matters. Note: Black can be easily integrated with many editors such as Vim, Emacs, VSCode, Atom or a version control system like GIT. Black requires Python 3.6.0+ with pip installed : $ pip install black It is very simple to use black. Run the below command in the terminal. $ black [file or directory] This will reformat your code using the Black codestyle.Example 1:Let’s create an unformatted file name “sample.py” and we want to format it using black. Below is the implementation. Python3 def is_unique( s ): s = list(s ) s.sort() for i in range(len(s) - 1): if s[i] == s[i + 1]: return 0 else: return 1 if __name__ == "__main__": print( is_unique(input()) ) After creating this file run the below command. Output file: Python3 def is_unique(s): s = list(s) s.sort() for i in range(len(s) - 1): if s[i] == s[i + 1]: return 0 else: return 1 if __name__ == "__main__": print(is_unique(input())) In the above example, both are the same piece code but after using black it is formatted and thus easy to understand. Example 2: Let’s create another file “sample1.py” containing the following code. Python3 def function(name, default=None, *args, variable="1123", a, b, c, employee, office, d, e, f, **kwargs): """This is function is created to demonstrate black""" string = 'GeeksforGeeks' j = [1, 2, 3] After writing the above command again in the terminal. Output file: Python3 def function( name, default=None, *args, variable="1123", a, b, c, employee, office, d, e, f, **kwargs): """This is function is created to demonstrate black""" string = "GeeksforGeeks" j = [1, 2, 3] prakharojha12 python-modules python-utility Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Aug, 2021" }, { "code": null, "e": 397, "s": 54, "text": "Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you ...
A sorting algorithm that slightly improves on selection sort
29 Apr, 2021 As we know, selection sort algorithm takes the minimum on every pass on the array, and place it at its correct position.The idea is to take also the maximum on every pass and place it at its correct position. So in every pass, we keep track of both maximum and minimum and array becomes sorted from both ends. Examples: First example: 7 8 5 4 9 2 Input :pass 1:|7 8 5 4 9 2| pass 2: 2|8 5 4 7|9 pass 3: 2 4|5 7|8 9 Output :A sorted array: 2 4 5 7 8 9 second example: 23 78 45 8 32 56 1 Input :pass 1:|23 78 45 8 32 56 1| pass 2: 1|23 45 8 32 56 |78 pass 3: 1 8|45 23 32|56 78 pass 4: 1 8 23 |32|45 56 78 in a case of odd elements, so one element left for sorting, so sorting stops and the array is sorted. Output : A sorted array: 1 8 23 32 45 56 78 C++ Java Python3 C# Javascript // C++ program to implement min max selection// sort.#include <iostream>using namespace std; void minMaxSelectionSort(int* arr, int n){ for (int i = 0, j = n - 1; i < j; i++, j--) { int min = arr[i], max = arr[i]; int min_i = i, max_i = i; for (int k = i; k <= j; k++) { if (arr[k] > max) { max = arr[k]; max_i = k; } else if (arr[k] < min) { min = arr[k]; min_i = k; } } // shifting the min. swap(arr[i], arr[min_i]); // Shifting the max. The equal condition // happens if we shifted the max to arr[min_i] // in the previous swap. if (arr[min_i] == max) swap(arr[j], arr[min_i]); else swap(arr[j], arr[max_i]); }} // Driver codeint main(){ int arr[] = { 23, 78, 45, 8, 32, 56, 1 }; int n = sizeof(arr) / sizeof(arr[0]); minMaxSelectionSort(arr, n); printf("Sorted array:\n"); for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; return 0;} // Java program to implement min max selection// sort.class GFG{static void minMaxSelectionSort(int[] arr, int n){ for (int i = 0, j = n - 1; i < j; i++, j--) { int min = arr[i], max = arr[i]; int min_i = i, max_i = i; for (int k = i; k <= j; k++) { if (arr[k] > max) { max = arr[k]; max_i = k; } else if (arr[k] < min) { min = arr[k]; min_i = k; } } // shifting the min. swap(arr, i, min_i); // Shifting the max. The equal condition // happens if we shifted the max to arr[min_i] // in the previous swap. if (arr[min_i] == max) swap(arr, j, min_i); else swap(arr, j, max_i); }} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void main(String[] args){ int arr[] = { 23, 78, 45, 8, 32, 56, 1 }; int n = arr.length; minMaxSelectionSort(arr, n); System.out.printf("Sorted array:\n"); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println("");}} // This code is contributed by Princi Singh # Python3 program to implement min# max selection sort. def minMaxSelectionSort(arr, n): i = 0 j = n - 1 while(i < j): min = arr[i] max = arr[i] min_i = i max_i = i for k in range(i, j + 1, 1): if (arr[k] > max): max = arr[k] max_i = k elif (arr[k] < min): min = arr[k] min_i = k # shifting the min. temp = arr[i] arr[i] = arr[min_i] arr[min_i] = temp # Shifting the max. The equal condition # happens if we shifted the max to # arr[min_i] in the previous swap. if (arr[min_i] == max): temp = arr[j] arr[j] = arr[min_i] arr[min_i] = temp else: temp = arr[j] arr[j] = arr[max_i] arr[max_i] = temp i += 1 j -= 1 print("Sorted array:", end = " ") for i in range(n): print(arr[i], end = " ") # Driver codeif __name__== '__main__': arr = [23, 78, 45, 8, 32, 56, 1] n = len(arr) minMaxSelectionSort(arr, n) # This code is contributed by# Surendra_Gangwar // C# program to implement min max selection// sort.using System; class GFG{static void minMaxSelectionSort(int[] arr, int n){ for (int i = 0, j = n - 1; i < j; i++, j--) { int min = arr[i], max = arr[i]; int min_i = i, max_i = i; for (int k = i; k <= j; k++) { if (arr[k] > max) { max = arr[k]; max_i = k; } else if (arr[k] < min) { min = arr[k]; min_i = k; } } // shifting the min. swap(arr, i, min_i); // Shifting the max. The equal condition // happens if we shifted the max to arr[min_i] // in the previous swap. if (arr[min_i] == max) swap(arr, j, min_i); else swap(arr, j, max_i); }} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void Main(String[] args){ int []arr = { 23, 78, 45, 8, 32, 56, 1 }; int n = arr.Length; minMaxSelectionSort(arr, n); Console.Write("Sorted array:\n"); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine("");}} // This code is contributed by Rajput-Ji <script> // Javascript program to implement min// max selection sort.function swap(arr, xp, yp){ var temp = arr[xp]; arr[xp] = arr[yp]; arr[yp] = temp;} function minMaxSelectionSort(arr, n){ for(var i = 0, j = n - 1; i < j; i++, j--) { var min = arr[i]; var max = arr[i]; var min_i = i; var max_i = i; for(var k = i; k <= j; k++) { if (arr[k] > max) { max = arr[k]; max_i = k; } else if (arr[k] < min) { min = arr[k]; min_i = k; } } // Shifting the min. swap(arr, i, min_i); // Shifting the max. The equal condition // happens if we shifted the max to arr[min_i] // in the previous swap. if (arr[min_i] == max) swap(arr, j, min_i); else swap(arr, j, max_i); }} // Driver codevar arr = [ 23, 78, 45, 8, 32, 56, 1 ];var n = 7; minMaxSelectionSort(arr, n); document.write("Sorted array:\n");for(var i = 0; i < n; i++) document.write(arr[i] + " "); document.write("<br>"); // This code is contributed by akshitsaxenaa09 </script> Output: Sorted array: 1 8 23 32 45 56 78 This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SURENDRA_GANGWAR princi singh Rajput-Ji akshitsaxenaa09 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Longest Common Prefix using Sorting Sort a nearly sorted (or K sorted) array Segregate 0s and 1s in an array Sorting in Java Find whether an array is subset of another array Quick Sort vs Merge Sort Quickselect Algorithm Stability in sorting algorithms Find all triplets with zero sum
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Apr, 2021" }, { "code": null, "e": 362, "s": 52, "text": "As we know, selection sort algorithm takes the minimum on every pass on the array, and place it at its correct position.The idea is to take also the maximum on every pass and...
Comments in Ruby - GeeksforGeeks
25 Jan, 2022 Statements that are not executed by the compiler and interpreter are called Comments. During coding proper use of comments makes maintenance easier and finding bugs easily.In Ruby, there are two types of comments: Single – line comments.Multi – line comments. Single – line comments. Multi – line comments. Here, we are going to explain both types of comment with their syntax and example: It is represented by # sign. It is used to denote single line comment in Ruby. Its the most easiest typed comments. When we need only one line of a comment in Ruby then we can use the characters ‘#’ preceding the comment. Example : Ruby # Ruby program to show single line comments #!/usr/bin/ruby -w # This is a single line comment.puts "Single line comment above" Output: Single line comment above If our comment is extending in more than one line than we can use a multiline comment.In Ruby, Multi- Line Comment started by using =begin and ended by using =end syntax.Syntax : =begin continues continues . . . Comment ends =end Example : Ruby # Ruby program to show multi line comments#!/usr/bin/ruby -w puts "Multi line comments below" =beginComment line 1Comment line 2 Comment line 3=end Output: Multi line comments below We can also execute single line comments by using the above syntax as shown below: =begin Comment line 1 =end sumitgumber28 Ruby-Basics Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Enumerator each_with_index function How to Make a Custom Array of Hashes in Ruby? Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | String concat Method Ruby | pop() function Ruby For Beginners Ruby | String empty? Method Ruby | Array shift() function Ruby | Class Method and Variables Ruby on Rails Introduction
[ { "code": null, "e": 23595, "s": 23567, "text": "\n25 Jan, 2022" }, { "code": null, "e": 23811, "s": 23595, "text": "Statements that are not executed by the compiler and interpreter are called Comments. During coding proper use of comments makes maintenance easier and finding bug...
Computer Vision module application for finding a target in a live camera - GeeksforGeeks
14 Dec, 2021 NOTE: Using an online compiler is not going to work here. Please install Python 2.7x and cv2, argparse modules to actually try out this example. For most of us, who are big fans of all those action movies, and games like Modern Warfare, Black Ops, and so on, it has always been a dream to have the opportunity of saying “Target acquired...Waiting for approval”.Team Alpha you are permitted to fire, Mission is a go. Let’s blow it guys!!! Hurrah!” Of course, well, you can’t always get what you want-But, at least now, I can get you close enough to your dream. All you need for this lesson is Python 2.7, cv2 module and it would be great if you have a nice video recorder with the help of which you can get the live video stream. Anyways, it won’t matter even if you don’t have one. Step – 1: Check your weapons Download Python 2.7 and ensure that you have the cv2 module (please note that the cv module is old and has been replaced by cv2 ) and the argparse module. For this : import cv2 as cv import argparse If this does not give an error, then you are good to go... Step – 2: Mission details Now that you have your weapons with you, it’s time for you to ensure that you have all the mission details required. First, we need to specify our target. So, our target is: Now that you have your target with you, it’s time to set up a test field. Get several printouts of the target and paste them at several places in your house. Now, if you really want to get the feel, make a quadcopter, fix a small camera in it, and record the whole house properly and ensure that you cover the places where you have pasted the targets. In case if you don’t want to go through all this trouble, just grab a camera and record your house yourself. I would recommend you keep the video short. Step – 3: Buckle up! We have a mission to complete! Okay. This is Alpha 1 reporting on duty! Send us the mission coordinates! You have the target, now you need to acquire it! So, for this, we are going to use the Computer Vision module (cv2).Code Snippet: Direct Code Link: https://ide.geeksforgeeks.org/xfUet4 import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the video file") args = vars(ap.parse_args()) # load the video camVideo = cv2.VideoCapture(args["video"]) # keep looping while True: # grab the current frame and initialize the status text (grabbed, frame) = camVideo.read() status = "No Target in sight" # check to see if we have reached the end of the # video if not grabbed: break # convert the frame to grayscale, blur it, and detect edges gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #grayscale blurred = cv2.GaussianBlur(gray, (7, 7), 0) #blur edged = cv2.Canny(blurred, 50, 150) #canny edge detection # find contours in the edge map (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # loop over the contours for cnt in cnts: approx=cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True), True) if len(approx)==5: cv2.drawContours(frame, [approx], -1, (0, 0, 255), 4) status = "Target(s) in sight!" # draw the status text on the frame cv2.putText(frame, status, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0, 0, 255), 2) # show the frame and record if a key is pressed cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the 's' key is pressed, stop the loop if key == ord("s"): break # cleanup the input recorded video and close any open windows camVideo.release() cv2.destroyAllWindows() Code explained: We loop over each frame of the recorded video and for detection of our target we convert it to gray-scale, blur it, and finally use the canny edge detection method to find the outlined image. Remember that, camVideo.read() will return a tuple with the first element specifying whether the frame was read successfully or not, the second element is the actual frame we will be working on! Now, once you have the frame, we will use contour approximation and then check the number of elements in the output obtained from the previous step. If the number of elements is 5, then we have the regular pentagon that we were looking for, and hence we update the status. Now this all was quite easy and basic. If you really want to build one such program then you should have a look at various filters to remove noise effects from the frame to get a more accurate result. The best thing you can do is keep experimenting! Try this exercise at your house, record the video and share your results with us... Signing off! Peace! Stay safe About the author: Vishwesh Shrimali is an Undergraduate Mechanical Engineering student at BITS Pilani. He fulfills all the requirements not taught in his branch- white hat hacker, network security operator, and an ex – Competitive Programmer. As a firm believer in the power of Python, his majority of work has been in the same language. Whenever he gets some time apart from programming, attending classes, watching CSI Cyber, he goes for a long walk and plays guitar in silence. His motto of life is – “Enjoy your life, ‘cause it’s worth enjoying!” If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. punamsingh628700 GBlog Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Working with csv files in Python SDE SHEET - A Complete Guide for SDE Preparation XML parsing in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python
[ { "code": null, "e": 24820, "s": 24792, "text": "\n14 Dec, 2021" }, { "code": null, "e": 24965, "s": 24820, "text": "NOTE: Using an online compiler is not going to work here. Please install Python 2.7x and cv2, argparse modules to actually try out this example." }, { "cod...
Fix for java.math.BigInteger cannot be cast to java.lang.Integer?
You can typecast with the help of method intValue(). The syntax is as follows − Integer yourVariableName=((BigInteger) yourBigIntegerValue).intValue(); Here is the Java code to convert java.math.BigInteger cast to java.lang.Integer. The code is as follows − Live Demo import java.math.BigInteger; public class BigIntegerToInteger { public static void main(String []args) { BigInteger bigValue [] = new BigInteger[5]; bigValue[0] = new BigInteger("6464764"); bigValue[1] = new BigInteger("212112221122"); bigValue[2] = new BigInteger("76475"); bigValue[3] = new BigInteger("94874747"); bigValue[4] = new BigInteger("2635474"); for(int i = 0; i< bigValue.length; i++) { Integer value = ((BigInteger) bigValue[i]).intValue(); System.out.println("Integer value is:"+value); } } } Here is the sample output − Integer value is:6464764 Integer value is:1658823618 Integer value is:76475 Integer value is:94874747 Integer value is:2635474
[ { "code": null, "e": 1142, "s": 1062, "text": "You can typecast with the help of method intValue(). The syntax is as follows −" }, { "code": null, "e": 1214, "s": 1142, "text": "Integer yourVariableName=((BigInteger) yourBigIntegerValue).intValue();" }, { "code": null, ...
SQLAlchemy ORM - Adding Objects
In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table. We have declared Customer class that has been mapped to customers table. We have to declare an object of this class and persistently add it to the table by add() method of session object. c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com') session.add(c1) Note that this transaction is pending until the same is flushed using commit() method. session.commit() Following is the complete script to add a record in customers table − from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key=True) name = Column(String) address = Column(String) email = Column(String) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com') session.add(c1) session.commit() To add multiple records, we can use add_all() method of the session class. session.add_all([ Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'), Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'), Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')] ) session.commit() Table view of SQLiteStudio shows that the records are persistently added in customers table. The following image shows the result − 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2507, "s": 2340, "text": "In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table." }, { "code": null, "e": 2695, "s": 2507, "text": "We have declare...
How do I set a minimum window size in Tkinter?
A Tkinter window can be initialized after running the application. Generally, the width and the height of the window is resizable which can be minimized. In order to set the window size to its minimum value, assign the value of width and height in minsize(height, width) method. The method can be invoked with the window or frame object. #Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Minimize the window win.minsize(150, 100) #Create a text label Label(win, text= "Window Size is minimized to 150x100",font=('Helvetica bold',20)).pack(pady=20) win.mainloop() Running the above code will set the window size to its minimum.
[ { "code": null, "e": 1216, "s": 1062, "text": "A Tkinter window can be initialized after running the application. Generally, the width and the height of the window is resizable which can be minimized." }, { "code": null, "e": 1400, "s": 1216, "text": "In order to set the window s...