code-rag-bench/online-tutorials huggingface dataset:
Efficiency of Stop and Wait Protocol

22 Jun, 2022
Stop and Wait is a flow control protocol. In which the sender sends one packet and waits for the receiver to acknowledge and then it will send the next packet. In case if the acknowledgement is not received, the sender will retransmit the packet. This is the simplest one and easy to implement. but the main disadvantage is the efficiency is very low.  Total time taken to send one packet,
= Tt(data) + Tp(data) + Tq + Tpro + Tt(ack) + Tp(ack)

Since,
Tp(ack) = Tp(data)

And,
Tt(ack) << Tt(data).

So we can neglect Tt(ack)
Tq = 0 and Tpro = 0

Hence, 
Total time = Tt(data) + 2 * Tp 
Where,
Tt(data) : Transmission delay for Data packet
Tp(data) : propagation delay for Data packet
Tq: Queuing delay
Tpro: Processing delay
Tt(ack): Transmission delay for acknowledgment
Tp(ack) : Propagation delay for acknowledgment 
We know that the Efficiency (η),
= Useful time / Total cycle time.
= Tt / (Tt + 2*Tp)
= 1 / (1+2*(Tp/Tt))
= 1 / (1+2*a) 

where, 
a = Tp / Tt 
Throughput: Number of bits send per second, which is also known as Effective Bandwidth or Bandwidth utilization.
Throughput, 
= L/(Tt + 2*Tp)
= ((L/BW)*BW)/(Tt + 2*Tp)
= Tt/(Tt + 2*Tp) * BW
= 1/(1 + 2a) * BW

Hence, Throughput 
= η * BW

where,
BW : BandWidth
L : Size of Data packet 
Factors affecting Efficiency:
n = 1/(1 + 2*(Tp/Tt)
= 1/(1 + 2*(d/v)*(BW/L))

where,
d = distance between source and receiver 
v = velocity 
Lets see an example. Example: Given,
Tt = 1ms    
Tp = 2ms   
Bandwidth = 6 Mbps

Efficiency(η) 
= 1/(1 + 2*a)
= 1/(1 + 2*(2/1))
= 1/5  
= 20 %

Throughput 
= η * BW
= (1/5) * 6 
= 1.2 Mbps 
Note: As we can observe from the above given formula of Efficiency that:
On increasing the distance between source and receiver the Efficiency will decrease. Hence, Stop and Wait is only suitable for small area network like LAN. It is not suitable for MAN or WAN, as the efficiency will be very low.If we increase the size of the Data packet, the efficiency is going to increase. Hence, it is suitable not for small packets. Big data packets can be send by Stop and Wait efficiently.
On increasing the distance between source and receiver the Efficiency will decrease. Hence, Stop and Wait is only suitable for small area network like LAN. It is not suitable for MAN or WAN, as the efficiency will be very low.
If we increase the size of the Data packet, the efficiency is going to increase. Hence, it is suitable not for small packets. Big data packets can be send by Stop and Wait efficiently.
arifhbd120
pall58183
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
GSM in Wireless Communication
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
Matplotlib.figure.Figure.dpi() in Python

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 dpi method of figure module of matplotlib library is the resolution in dots per inch.
Syntax: fig.dpi
Parameters: This method does not accept any parameters.
Returns: This method returns resolution in dots per inch.
Below examples illustrate the matplotlib.figure.Figure.dpi function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np     fig = plt.figure()  nx = int(fig.get_figwidth() * fig.dpi)ny = int(fig.get_figheight() * fig.dpi)  data = np.random.random((ny, nx))plt.plot(data)   fig.suptitle('matplotlib.figure.Figure.dpi \function Example', fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function  import matplotlib.pyplot as pltfrom matplotlib import collections, colors, transformsimport numpy as np   nverts = 50npts = 100   r = np.arange(nverts)theta = np.linspace(0, 2 * np.pi, nverts)  xx = r * np.sin(theta)yy = r * np.cos(theta)  spiral = np.column_stack([xx, yy])   rs = np.random.RandomState(19680801)   xyo = rs.randn(npts, 2)   colors = [colors.to_rgba(c)          for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]   fig, ax1 = plt.subplots()   col = collections.RegularPolyCollection(    7, sizes = np.abs(xx) * 10.0, offsets = xyo,     transOffset = ax1.transData)  trans = transforms.Affine2D().scale(fig.dpi / 72.0)  col.set_transform(trans) ax1.add_collection(col, autolim = True)col.set_color(colors)  fig.suptitle('matplotlib.figure.Figure.dpi() function\ Example', fontweight ="bold")   plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
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
Convert integer to string in Python
How to handle a back button in an android activity?

This example demonstrates how do I handle back button in an android activity.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:text= "My Activity"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent"
      android:layout_marginVertical="25sp"
      android:layout_margin="23dp"/>
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Back to close the activity"
      android:id="@+id/button"
      android:layout_centerVertical="true"
      android:layout_margin="23dp"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
   Button button;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      button = findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            finish();
         }
      });
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Store unicode in a char variable in Java

To store Unicode in a char variable, simply create a char variable.
char c;
Now assign unicode.
char c = '\u00AB';
The following is the complete example that shows what will get displayed: when Unicode is stored in a char variable and displayed.
 Live Demo
public class Demo {
   public static void main(String []args) {
      int a = 79;
      System.out.println(a);
      char b = (char) a;
      System.out.println(b);
      char c = '\u00AB';
      System.out.println(c);
   }
}
79
O
«
How to Change Tkinter Frame Title?

Tkinter window is the native component of tkinter application that contains some frames, a group of widgets, and some other elements. A Tkinter frame has a group of too many widgets.
Let us suppose that we have created a frame with some widgets and now we want to rename the title of the application. Frame titles are a necessary part of any application. We can change the title of the frame using the title("title") method.
In this example, we will create an application that will contain an entry widget and a button. The button is used to rename the title of the window. Initially, we will create an instance of StringVar() and this can be used to capture the user input in the Entry widget. Then, by using the set() method, we will pass the captured variable to set the title of the frame.
#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the Geometry
win.geometry("750x250")
#Define a Variable to accept the input
var= StringVar()
#Define a function to change the title
def change_title():
win.title(var.get())
#Create an Entry widget
text=Entry(win,textvariable=var)
text.focus_set()
text.pack(pady=20)
#Pass the title in the function
var.set(win.title())
#Create a Button
Button(win, text= "Change", command= change_title).pack(pady=20)
win.mainloop()
By running the above code, we can display a window that contains a button and the frame object. Now, whenever we write some title in the entry widget and click the “Change” button, it will change the title of the frame.
Now, change the title of the frame by writing some text in the Entry widget and click the “Change” to display the reflected output.
How to print current date and time using Python?

You can get the current date and time using multiple ways. The easiest way is to use the datetime module. It has a function, now, that gives the current date and time. 
import datetime
now = datetime.datetime.now()
print("Current date and time: ")
print(str(now))
This will give the output −
2017-12-29 11:24:48.042720
You can also get the formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it.
You can use these directives in the strftime function as follows −
import datetime
now = datetime.datetime.now()

print("Current date and time: ")
print(now.strftime('%Y-%m-%d %H:%M:%S'))
print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y'))
This will give the output −
2017-12-29 12:19:13
12:19:13 on Friday, December the 29th, 2017
How does repetition operator work on list in Python?

We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a list, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together. Lists can be created using the repetition operator, *. For example,
numbers = [0] * 5
print numbers
This will give the output −
[0, 0, 0, 0, 0]
[0] is a list with one element, 0.  The repetition operator makes 5 copies of this list and joins them all together into a single list. Another example using multiple elements in the list.
numbers = [0, 1, 2] * 3
print numbers
This will give the output −
[0, 1, 2, 0, 1, 2, 0, 1, 2]
Note that Python creates shallow copies of the lists in this. So changing objects at one place will change them at all places they are repeated. If you don't want this behaviour, don't use repetition operator to create lists.
Range-based for loop in C++ - GeeksforGeeks

11 May, 2022
Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
Syntax :
for ( range_declaration : range_expression ) 
    loop_statement

Parameters :
range_declaration : 
a declaration of a named variable, whose type is the 
type of the element of the sequence represented by 
range_expression, or a reference to that type.
Often uses the auto specifier for automatic type 
deduction.

range_expression : 
any expression that represents a suitable sequence 
or a braced-init-list.

loop_statement : 
any statement, typically a compound statement, which
is the body of the loop.

C++ implementation :
// Illustration of range-for loop// using CPP code#include <iostream>#include <vector>#include <map>  //Driverint main() {    // Iterating over whole array    std::vector<int> v = {0, 1, 2, 3, 4, 5};    for (auto i : v)        std::cout << i << ' ';          std::cout << '\n';          // the initializer may be a braced-init-list    for (int n : {0, 1, 2, 3, 4, 5})        std::cout << n << ' ';          std::cout << '\n';       // Iterating over array    int a[] = {0, 1, 2, 3, 4, 5};         for (int n : a)        std::cout << n << ' ';          std::cout << '\n';          // Just running a loop for every array    // element    for (int n : a)          std::cout << "In loop" << ' ';          std::cout << '\n';          // Printing string characters    std::string str = "Geeks";    for (char c : str)         std::cout << c << ' ';              std::cout << '\n';      // Printing keys and values of a map    std::map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}});    for (auto i : MAP)        std::cout << '{' << i.first << ", "                   << i.second << "}\n";}
Output:
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
In loop In loop In loop In loop In loop In loop 
G e e k s 
{1, 1}
{2, 2}
{3, 3}

This article is contributed by Rohit Thapliyal. 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.
ChrisFedun
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
Virtual Function in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Polymorphism in C++
Check if two PDF documents are identical with Python - GeeksforGeeks

08 Mar, 2021
Python is an interpreted and general purpose programming language. It is a Object-Oriented and Procedural paradigms programming language. There are various types of modules imported in python such as difflib, hashlib.
difflib : It is a module that contains function that allows to compare set of data.
SequenceMatcher : It is used to compare pair of input sequences.
hash_file ( string $algo , string $filename , bool $binary = false ): It is a function which has the hash of a file.
object.hexdigest(): It is a function which returns string.
fileObject.read(size): It is a function that returns the specified number of bytes of a file.
Import module
Declare a function with 2 arguments which is for file.
Declare two objects for hashlib.sha1()
Open files
Read the file by breaking the line into smaller chunks
Now return both file such as h1.hexdigest() which is of 160 bits.
Use hash_file() function to store the hash of a file.
Compare and generate appropriate message
File 1
File 2
Program:
Python3
import hashlibfrom difflib import SequenceMatcher    def hash_file(fileName1, fileName2):      # Use hashlib to store the hash of a file    h1 = hashlib.sha1()    h2 = hashlib.sha1()      with open(fileName1, "rb") as file:          # Use file.read() to read the size of file        # and read the file in small chunks        # because we cannot read the large files.        chunk = 0        while chunk != b'':            chunk = file.read(1024)            h1.update(chunk)                  with open(fileName2, "rb") as file:          # Use file.read() to read the size of file a        # and read the file in small chunks        # because we cannot read the large files.        chunk = 0        while chunk != b'':            chunk = file.read(1024)            h2.update(chunk)          # hexdigest() is of 160 bits        return h1.hexdigest(), h2.hexdigest()    msg1, msg2 = hash_file("pd1.pdf ", "pd1.pdf")  if(msg1 != msg2):    print("These files are not identical")else:    print("These files are identical")
Output
These files are not identical
Picked
python-utility
Technical Scripter 2020
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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
How to get all the keys from a Scala map - GeeksforGeeks

29 Jul, 2019
In order to get all the keys from a Scala map, we need to use either keySet method (to get all the keys as a set) or we can use keys method and if you want to get the keys as an iterator, you need to use keysIterator method. Now, lets check some examples.Example #1:
// Scala program of keySet()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying keySet method        val result = m1.keySet                  // Displays output        println(result)          }}
Set(3, 4, 2)

Here, keySet method is utilized.Example #2:
// Scala program of keys()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying keys method        val result = m1.keys                  // Displays output        println(result)          }}
Set(3, 4, 2)

Here, keys method is utilized.Example #3:
// Scala program of keysIterator()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying keysIterator method        val result = m1.keysIterator                  // Displays output        println(result)          }}
non-empty iterator

Here, keysIterator method is utilized.
Scala
Scala-Map
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala Lists
Class and Object in Scala
Break statement in Scala
Scala String substring() method with example
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Scala | Arrays
Go switch

Use the switch statement to select one of many code blocks to be executed.
The switch statement in Go is similar to the ones in C, C++, Java, JavaScript, and PHP. The difference is that it only runs the matched case so it does not need a break statement.
This is how it works:
The expression is evaluated once
The value of the switch expression is compared with the values of each case
If there is a match, the associated block of code is executed
The default  keyword is optional. It 
specifies some code to run if there is no case 
match
The example below uses a weekday number to calculate the weekday name:
Result:
The default keyword specifies some code to run if there is no case match:
Result:
All the case values should have the same type as the switch expression. Otherwise, the compiler will raise an error:
Result:
Insert the missing parts to complete the following switch statement.
package main   
import ("fmt") 
func main() {
  var day = 2
  switch  {
  (1):
    fmt.Print("Saturday")
  (2):
    fmt.Print("Sunday")    
  }
}

Start the Exercise
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.
Convert JSON object to Java object using Gson library in Java?


A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert JSON to java objects. We can call the fromJson() method of Gson class to convert a JSON object to Java Object.
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
import com.google.gson.*;
public class JSONtoJavaObjTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      Emp emp = gson.fromJson("{'name':'raja','age':25}", Emp.class);
      System.out.println(emp.getName());
      System.out.println(emp.getAge());
   }
}
// Emp class
class Emp {
   String name;
   int age;
   public Emp() {
      super();
   }
   public Emp(String name, int age) {
      super();
      this.name = name;
      this.age = age;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   
   public void setAge(int age) {
      this.age = age;
   }
}
raja
25
Fastest way to Convert Integers to Strings in Pandas DataFrame - GeeksforGeeks

01 Aug, 2020
Pandas – An open-source library which is used by any programmer. It is a useful library that is used for analyzing the data and for manipulating the data. It is fast, flexible, and understandable, handles the missing data easily. Not only it provides but also enhances the performance of data manipulation and analysis tools with the powerful data structure.
There are four ways of converting integers to strings in pandas.
Method 1: map(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].map(str)
Method 2: apply(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].apply(str)
Method 3: astype(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].astype(str)
Method 4: values.astype(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].values.astype(str)
In order to find out the fastest method we find the time taken by each method required for converting integers to the string. The method which requires the minimum time for conversion is considered to be the fastest method.
import pandas as pdimport sysimport timeimport numpy as np  print('Version Of Python: ' + sys.version)print('Version Of Pandas: ' + pd.__version__)print('Version Of Numpy: ' + np.version.version)  frame1 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame2 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame3 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame4 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])    # Using map(str) methodt1 = time.time()frame1['random'] = frame1['random'].map(str)output1 = (time.time() - t1)  print('Time taken in seconds using map(str): ' + str(output1))  # Using apply(str) methodt2 = time.time()frame2['random'] = frame2['random'].apply(str)output2 = (time.time() - t2)  print('Time taken in seconds using apply(str): ' + str(output2))  # Using astype(str) methodt3 = time.time()frame3['random'] = frame3['random'].astype(str)output3 = (time.time() - t3)  print('Time taken in seconds using astype(str): ' + str(output3))  # Using values.astype(str) methodt4 = time.time()frame4['random'] = frame4['random'].values.astype(str)output4 = (time.time() - t4)  print('Time taken in seconds using values.astype(str): ' + str(output4))  l =[output1, output2, output3, output4]m =['map(str)', 'apply(str)', 'astype(str)', 'values.astype(str)']  # Fastest way to convert into stringminimum = min(l)k = l.index(minimum)fastest = m[k]  # It will print the fastest conversion method.print(fastest+" is the fastest method")
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to convert a bean to JSON object using Exclude Filter in Java?

The JsonConfig class can be used to configure the serialization process. We can use the setJsonPropertyFilter() method of JsonConfig to set the property filter when serializing to JSON. We need to implement a custom PropertyFilter class by overriding the apply() method of the PropertyFilter interface. It returns true if the property will be filtered out or false otherwise.
public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
public class ConvertBeanToJsonExcludeFilterTest {
   public static void main(String[] args) {
      Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad");
      JsonConfig jsonConfig = new JsonConfig();
      jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter());

      JSONObject jsonObj = JSONObject.fromObject(student, jsonConfig);
      System.out.println(jsonObj.toString(3)); //pretty print JSON
   }
   public static class Student {
      private String firstName, lastName, address;
      public int age;
      public Student(String firstName, String lastName, int age, String address) {
         super();
         this.firstName = firstName;
         this.lastName = lastName;
         this.age = age;
         this.address = address;
      }
      public String getFirstName() {
         return firstName;
      }
      public String getLastName() {
         return lastName;
      }
      public int getAge() {
         return age;
      }
      public String getAddress() {
         return address;
      }
   }
}
// CustomPropertyFilter class
class CustomPropertyFilter implements PropertyFilter {
   @Override
   public boolean apply(Object source, String name, Object value) {
      if(Number.class.isAssignableFrom(value.getClass()) ||        String.class.isAssignableFrom(value.getClass())) {
         return false;
      }
      return true;
   }
}
{
  "firstName": "Sai",
  "lastName": "Chaitanya",
  "address": "Hyderabad",
  "age": 20
}
How to get top activity name in activity stack?

This example demonstrate about How to get top activity name in activity stack.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<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:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken text view to show top activity name.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.P)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
      WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      ActivityManager result = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
      List<ActivityManager.RunningTaskInfo> services = result
      .getRunningTasks(Integer.MAX_VALUE);
      textView.setText("" +services.get(0).topActivity.toString());
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
How to print Narcissistic(Armstrong) Numbers with Python?

To print Narcissistic Numbers, let's first look at the definition of it. It is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 1, 153, 370 are all Narcissistic numbers. You can print these numbers by running the following code
def print_narcissistic_nums(start, end):
for i in range(start, end + 1):
   # Get the digits from the number in a list:
   digits = list(map(int, str(i)))
   total = 0
   length = len(digits)
   for d in digits:
      total += d ** length
   if total == i:
      print(i)
print_narcissistic_nums(1, 380)
This will give the output
1
2
3
4
5
6
7
8
9
153
370
371
Dart - Getters and Setters - GeeksforGeeks

14 Jul, 2020
Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. 
Getters or accessors are defined using the get keyword.
Setters or mutators are defined using the set keyword.
A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value.
Syntax: Defining a getter
 
Return_type  get identifier  
{  
    // statements
}  

Syntax: Defining a setter
 
set identifier  
{  
   // statements
}

Example 1:
The following example shows how you can use getters and setters in a Dart class:
Dart
// Dart Program in Dart to illustrate// getters and setters #GFGclass Student {    String name;    int age;          String get stud_name {       return name;    }          void set stud_name(String name) {       this.name = name;    }         void set stud_age(int age) {       if(age<= 0) {         print("Age should be greater than 5");       }  else {          this.age = age;       }    }         int get stud_age {       return age;        } }  void main() {    Student s1 = new Student();    s1.stud_name = 'Nitin';    s1.stud_age = 0;    print(s1.stud_name);    print(s1.stud_age); }
Output:
Age should be greater than 5  
Nitin
Null 

Example 2:
Dart
// Dart program in Dart to illustrate// getters and setters #GFGvoid main() {  var cat = new Cat();      // Is cat hungry? true  print("Is cat hungry? ${cat.isHungry}");      // Is cat cuddly? false  print("Is cat cuddly? ${cat.isCuddly}");        print("Feed cat.");  cat.isHungry = false;         // Is cat hungry? false  print("Is cat hungry? ${cat.isHungry}");       // Is cat cuddly? true  print("Is cat cuddly? ${cat.isCuddly}"); }  class Cat {  bool _isHungry = true;      bool get isCuddly => !_isHungry;      bool get isHungry => _isHungry;  bool set isHungry(bool hungry) => this._isHungry = hungry;}
Output:
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - BoxShadow Widget
Dart Tutorial
ListView Class in Flutter
How to Append or Concatenate Strings in Dart?
Flutter - Flexible Widget
Operators in Dart
Flutter - Stack Widget
C# | Total number of elements present in an array - GeeksforGeeks

04 Aug, 2021
Array.GetLength(Int32) Method is used to find the total number of elements present in the specified dimension of the Array. Syntax:  
public int GetLength (int dimension);
Here, dimension is a zero-based dimension of the Array whose length needs to be determined.Return value: The return type of this method is System.Int32. This method return a 32-bit integer that represents the number of elements in the specified dimension.Exception:This method will give IndexOutOfRangeException if the value of dimension is less than zero or if the value of dimension is equal to or greater than Rank.Below given are some examples to understand the implementation in a better way: Example 1:
CSharp
// C# program to illustrate the// use of GetLength() methodusing System; public class GFG {         // Main method    static public void Main()    {         // create and initialize array        int[] myarray = {445, 44, 66, 6666667, 78, 878, 1};         // Display the array        Console.WriteLine("The elements of myarray :");                 foreach(int i in myarray)        {            Console.WriteLine(i);        }         // Find the number of element in myarray        int result = myarray.GetLength(0);        Console.WriteLine("Total Elements: {0}", result);    }}
The elements of myarray :
445
44
66
6666667
78
878
1
Total Elements: 7
 
Example 2:
CSharp
// C# program to check arrays contain// same number of elements or notusing System; public class GFG {         // Main method    static public void Main()    {         // create and initializing array        int[] myarray1 = {100, 0, 400, 660, 700, 809, 0};        int[] myarray2 = {100, 0, 400, 660, 700};        int[] myarray3 = {100, 0, 400, 660, 700, 809, 0};         // Find the number of element in myarray        // using GetLength() method        int result1 = myarray1.GetLength(0);        int result2 = myarray2.GetLength(0);        int result3 = myarray3.GetLength(0);         // Check if myarray1, myarray2, myarray3        // contain the same number of elements or not        Console.WriteLine("myarray1 and myarray2: {0}",                             Equals(result1, result2));                                      Console.WriteLine("myarray1 and myarray3: {0}",                             Equals(result1, result3));    }}
myarray1 and myarray2: False
myarray1 and myarray3: True
 
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getlength?view=netcore-2.1 
gabaa406
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
SymPy | Subset.subset() in Python - GeeksforGeeks

28 Aug, 2019
Subset.subset() : subset() is a sympy Python library function that returns the subset represented by the current instance.
Syntax :sympy.combinatorics.subset.Subset.subset()
Return :the subset represented by the current instance.
Code #1 : subset() Example
# Python code explaining# SymPy.Subset.subset()  # importing SymPy librariesfrom sympy.combinatorics import Permutation, Cyclefrom sympy.combinatorics.subsets import Subset  # Using from # sympy.combinatorics.subset.Subsets.subset()  # Creating Subseta = Subset(['c', 'd'], ['geek', 'for', 'c', 'd'])  # subset valueprint ("Subset a subset : ", a.subset)
Output :
Subset a subset : [‘c’, ‘d’]
Code #2 : subset() Example
# Python code explaining# SymPy.Subset.subset()  # importing SymPy librariesfrom sympy.combinatorics import Permutation, Cyclefrom sympy.combinatorics.subsets import Subset  # Using from # sympy.combinatorics.subset.Subsets.subset()  # Creating Subseta = Subset([2, 3, 4], [1, 2, 3, 4, 5])  # subset valueprint ("Subset a subset : ", a.subset)
Output :
Subset a subset : [2, 3, 4]
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
GATE | GATE-CS-2006 | Question 60

17 Sep, 2021
Consider the following C code segment.
for (i = 0, i<n; i++){    for (j=0; j<n; j++)    {        if (i%2)        {            x += (4*j + 5*i);            y += (7 + 4*j);        }    }}
Which one of the following is false?(A) The code contains loop invariant computation(B) There is scope of common sub-expression elimination in this code(C) There is scope of strength reduction in this code(D) There is scope of dead code elimination in this codeAnswer: (D)Explanation: Question asks about false statement

4*j is common subexpression elimination so B is true.

5*i can be moved out of inner loop so can be i%2. 
Means, A is true as we have loop invariant computation.

Next, 4*j as well as 5*i can be replaced with a = - 4;
before j loop then a = a + 4; where 4*j is computed,
likewise for 5*i. C is true as there is scope of strength 
reduction. 

By choice elimination, we have D.
GATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE |Watch 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:0033:31 / 38:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mNG-F-8t3a4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 38
PHP | ord() Function

20 Mar, 2018
The ord() function is a inbuilt function in PHP that returns the ASCII value of the first character of a string. This function takes a character string as a parameter and returns the ASCII value of the first character of this string.
Syntax:
int ord($string)
Parameter: This function accepts a single parameter $string. This is a mandatory parameter from which we get an ASCII value.
Return value: This function returns an integer value which represents the ASCII value of the first character in the string passed to this function as a parameter.
Examples:
Input : Geeksforgeeks
Output : 71
Explanation: The ASCII value of G is 71

Input : twinkle
Output : 116
Explanation: The ASCII value of t is 116

Below programs illustrate the ord() function in PHP:
Program 1:
<?php// PHP program to illustrate the ord() function  // ASCII value of 't' is printed.echo ord("twinkle");?>
Output:
116

Program 2:
<?php// PHP program to illustrate the ord() function  // ASCII value of 'G' is printedecho ord("Geeksforgeeks");?>
Output:
71
Reference:http://php.net/manual/en/function.ord.php
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
VBScript Exit For statement

A Exit For Statement is used when we want to Exit the For Loop based on certain criteria. When Exit For is executed, the control jumps to next statement immediately after the For Loop.
The syntax for Exit For Statement in VBScript is −
 Exit For

The below example uses Exit For. If the value of the Counter reaches 4, the For Loop is Exited and control jumps to the next statement immediately after the For Loop.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a : a = 10
         For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2
            document.write("The value is i is : " & i)
            document.write("<br></br>")
         
         If i = 4 Then
            i = i*10  'This is executed only if i = 4
            document.write("The value is i is : " & i)
            Exit For 'Exited when i = 4
         End If	 
         Next
         
      </script>
   </body>
</html>
When the above code is executed, it prints the following output in the console.
The value is i is : 0

The value is i is : 2

The value is i is : 4

The value is i is : 40 


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Socket programming In Python

In bidirectional communications channel, sockets are two end points. Sockets can communicate between process on the same machine or on different continents.
Sockets are implemented by the different types of channel-TCP, UDP.
For creating Socket, we need socket module and socket.socket () function.
my_socket = socket.socket (socket_family, socket_type, protocol=0)

Different methods in Server Socket
my_socket.bind()

This method is used for binding address (hostname, port number pair) to socket.
my_socket.listen()

This method is used for set up and start TCP listener.
my_socket.accept()

This method is used for accepting TCP client connection, waiting until connection arrives (blocking).
my_socket.connect()

This method actively initiates TCP server connection.
my_socket.recv()

This method receives TCP message
my_socket.send()

This method transmits TCP message
my_socket.recvfrom()

This method receives UDP message
my_socket.sendto()

This method transmits UDP message
my_socket.close()

This method closes socket
my_socket.gethostname()

This method returns the hostname.
import socket
my_socket = socket.socket()      # Create a socket object
my_host = socket.gethostname()
my_port = 00000# Store a port for your service.
my_socket.bind((my_host, my_port))
my_socket.listen(5)      # Now wait for client connection.
while True:
   cl, myaddr = my_socket.accept()     # Establish connection with client.
   print ('Got connection from', myaddr)
   cl.send('Thank you for connecting')
   cl.close()     # Close the connection
import socket      # Import socket module
my_socket = socket.socket()      # Create a socket object
my_host = socket.gethostname()     # Get local machine name
my_port = 00000# Store a port for your service.
my_socket.connect((my_host, my_port))
print (my_socket.recv(1024))
my_socket.close
Batch Script - DISKPART

This batch command shows and configures the properties of disk partitions.
Diskpart

@echo off 
diskpart
The above command shows the properties of disk partitions. Following is an example of the output.
Microsoft DiskPart version 6.3.9600

Copyright (C) 1999-2013 Microsoft Corporation.
On computer: WIN-50GP30FGO75

 Print
 Add Notes
 Bookmark this page
Assertions in Python

An assertion is a sanity-check that you can turn on  or turn off when you are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]

If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature −
#!/usr/bin/python

def KelvinToFahrenheit(Temperature):
   assert (Temperature >= 0),"Colder than absolute zero!"
   return ((Temperature-273)*1.8)+32

print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is  executed, it produces the following result −
32.0
451
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print KelvinToFahrenheit(-5)
   File "test.py", line 4, in KelvinToFahrenheit
      assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page