code-rag-bench/online-tutorials huggingface dataset:
How to make a Country field in Django?

If you need to add a location field in your form or database, you can do that using charfield but it is still not that good idea. In Django, we have a third-party package called 'django-countries' that provides the country field. In this article, let's see how to use django-countries to add a Country field in Django.
First, create a Django project and an app.
Add the app in INSTALLED_APPS and set up urls.
Install the django-countries module −
pip install django-countries
In settings.py, add this −
INSTALLED_APPS += [ 'django_countries']
In app's urls.py −
from django.urls import path
from . import views

urlpatterns = [
   path('', views.home, name="home"),
]
First setup your urls.
In views.py −
from django.shortcuts import render
from django import forms
from .models import Data
class SalaryForm(forms.ModelForm):
   class Meta:
      model=Data
      fields="__all__"
def home(request):
   if request.method=='POST':
      form=SalaryForm(request.POST)
      if form.is_valid():
         form.save()

   else:
      form=SalaryForm()
   return render(request,'home.html',{'form':form})
Here we simply created a form and rendered it in GET request handler of our view. In POST handler, we save the form data.
Create a templates folder in app directory and a home.html in it. In home.html −
<!DOCTYPE html>
<html>
   <head>
      <title>
         TUT
      </title>
      <style>

      </style>
   </head>
   <body>
      <h2>FORM</h2>
      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
This is the front-end html of our form.
In models.py −
from django.db import models
from django_countries.fields import CountryField

# Create your models here.
class Data(models.Model):
   Name=models.CharField(max_length=100)
   salary = models.CharField(max_length=20)
   country_of_work = CountryField(blank=True)
Here we created a model in which we simply added a country field which will store the country data.
Now, make migrations and migrate. You are all done. Now, you can proceed to check the output.
HTML checked Attribute

The checked attribute in HTML is used to set that an <input> element is pre-selected when the page loads.
This works for input type radio and checkbox.
Let us work on the checked attribute for checkbox i.e. input type checkbox. Following is the syntax −
<input type=”checkbox” checked>
Above, we have set it checked since we wanted the checkbox to be selected when the web page loads. Let us now see an example to implement the checked attribute of the <input> element −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Register</h2>
<form action="" method="get">
   Id: <input type="text" name="id" placeholder="Enter UserId here..." size = "25"><br>
   Password: <input type="password" name="pwd" placeholder="Enter password here..."><br>
   DOB: <input type="date" name="dob" placeholder="Enter date of birth here..."><br>
   Telephone: <input type="tel" name="tel" placeholder="Enter mobile number here..."><br>
   Email: <input type="email" name="email" placeholder="Enter email here..." size = "35"><br><br>
   <input type="checkbox" name="vehicle" value="Bike" checked>Newsletter Subscription: <br>
   <button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
In the above example, we have a form with input elements and a button −
<form action="" method="get">
   Id: <input type="text" name="id" placeholder="Enter UserId here..." size = "25"><br>
   Password: <input type="password" name="pwd" placeholder="Enter password here..."><br>
   DOB: <input type="date" name="dob" placeholder="Enter date of birth here..."><br>
   Telephone: <input type="tel" name="tel" placeholder="Enter mobile number here..."><br>
   Email: <input type="email" name="email" placeholder="Enter email here..." size = "35"><br><br>
   <input type="checkbox" name="vehicle" value="Bike" checked>Newsletter Subscription: <br>
   <button type="submit" value="Submit">Submit</button>
</form>
We have set a checkbox using the input type checkbox. To set it checked when the web page loads, the checked attribute is used −
<input type="checkbox" name="vehicle" value="Bike" checked>Newsletter Subscription:
Tryit Editor v3.7

Tryit: The text-align-last property
map::begin() and end() in C++ STL

In this article we will be discussing the working, syntax and examples of map::begin() and map::end() functions in C++ STL.
Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.
map::begin() function is an inbuilt function in C++ STL, which is defined in  header file. begin() is used to access the element which is at the very beginning of the associated map container.
This function returns an iterator which points to the first element of the container. When the container has no values in it the iterator cannot be dereferenced
map_name.begin();
The function accepts no parameter.
This function returns an iterator which is pointing to the first value of the map container.
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.begin();
a:10
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
   for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
      cout << "\t" << i->first << "\t" << i->second << '\n';
   }
   return 0;
}
Elements of TP_1 after swap:
KEY    ELEMENT
1       10
2       20
3       30
4       40
map::end() function is an inbuilt function in C++ STL, which is defined in <map> header file. end() is used to access the element which is at after the last element in the container, or the past the last element.
This function returns an iterator which points to the element which is next to the last element of the container. When the container has no values in it the iterator cannot be dereferenced
Usually begin() and end() are used to iterate through the map container by giving them range.
map_name.end();
The function accepts no parameter.
This function returns an iterator which is pointing to the past the last value of the map container.
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.end();
error
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
   for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
      cout << "\t" << i->first << "\t" << i->second << '\n';
   }
   return 0;
}
Elements of TP_1 after swap:
KEY    ELEMENT
1       10
2       20
3       30
4       40
How to call a virtual function inside constructors in C++?

Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. This is because the virtual function you call is called from the Base class and not the derived class.
In C++ every class builds its version of the virtual method table prior to entering its own construction. So a call to the virtual method in the constructor will call the Base class' virtual method. Or if it has no implementation at that level, it'll produce a pure virtual method call. Once the Base is fully constructed, the compiler starts building Derived class, and overrides the method pointers to point Derived class' implementation. So for example, If you have the code −
#include<iostream>
using namespace std;

class Base {
public:
   Base() { f(); }
   virtual void f() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
   Derived() : Base() {}
   virtual void f() { std::cout << "Derived" << std::endl; }
};

int main() {
   Derived d;    
   return 0;
}
This will give the output −
Base
Yen's k-Shortest Path Algorithm in Data Structure

Instead of giving a single shortest path, Yen’s k-shortest path algorithm gives k shortest paths so that we can get the second shortest path and the third shortest path and so on.
Let us consider a scenario that we have to travel from place A to place B and there are multiple routes available between place A and place B, but we have to find the shortest path and neglect all the paths that are less considered in terms of its time complexity in order to reach the destination.
Let us understand with an example-
Consider the given example as the bridge which is having a peak of B. If someone wants to cross the bridge from A to C, then nobody will go to the peak to cross the bridge. So it would be a bit longer path from A to C.
There are multiple ways to get the shortest path. But we have to find the shortest path up to (k-1).
query= “””
MATCH(start: place{id:source}),*end: Place {Id:destination})
Call algo.kshortestPaths.stream(start,end,10, “distance”)
Yield nodeIDs, path costs, index
Return index.
   [node in algo.getNodeByID(nodeId[1.....-1]) | node.id] aS,
   Reduce (acc=0.0, cost in costs | acc+cost ) as total cost
“””
params= {“source”: Alex,Destination: “US”}
With driver.selection() as session:
  Row session.run(query, params)
  df = pd.DataFrame[dict(record) for record in rows])
pd.set_option(‘max_colwidth’, 100)
display(df)
Java Program to subtract year from current date

Firstly, you need to import the following package for Calendar class in Java
import java.util.Calendar;
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 decrement the year using the calendar.add() method and Calendar.YEAR constant. Set a negative value since we are decrementing here
calendar.add(Calendar.YEAR, -20);
The following is an example
 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());
      // Subtract 20 Years
      calendar.add(Calendar.YEAR, -20);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}
Current Date = Thu Nov 22 18:20:30 UTC 2018
Updated Date = Sun Nov 22 18:20:30 UTC 1998
Python | Intersection of two String

27 Nov, 2018
One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings.
There are various ways in Python, through which we can perform the Intersection of two strings.
Method #1 : Naive MethodCreate an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. This can be achieved by loops and if/else statements.
# Python3 code to demonstrate # string intersection# using naive method   # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks'  # using naive method to# get string intersectionres = ""for i in test_str1:    if i in test_str2 and not i in res:        res += i          # printing intersectionprint ("String intersection is : " + res)
Output :
String intersection is : eksfor

 Method #2 : Using set() + intersection()
Firstly, both the strings are converted into sets using set() and then intersection is performed using intersection(). Returns the sorted set.
# Python3 code to demonstrate # string intersection# using set() + intersection()  # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks'  # using set() + intersection() to# get string intersectionres = set(test_str1).intersection(test_str2)          # printing intersectionprint ("String intersection is : " + str(res))
Output :
String intersection is : {'e', 'f', 's', 'o', 'k', 'r'}

 
Method #3 : Using join()
join() performs the task similar to list comprehension in case of lists. This encapsulates whole intersection logic and joins together each element filtered through the intersection logic into one string, hence computing the intersection. It converts the strings into set and then computed & operation on them.
# Python3 code to demonstrate # string intersection# using join()  # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks'  # using join() to# get string intersectionres = ''.join(sorted(set(test_str1) &         set(test_str2), key = test_str1.index))          # printing intersectionprint ("String intersection is : " + str(res))
Output :
String intersection is : eksfor

Python string-programs
python-string
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
How to Make Java Regular Expression Case Insensitive in Java?

09 Mar, 2021
In this article, we will learn how to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract data from character sequences. Java Regular Expressions are case-sensitive by default. But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are two ways to make Regular Expression case-insensitive:
Using CASE_INSENSITIVE flagUsing modifier
Using CASE_INSENSITIVE flag
Using modifier
1. Using CASE_INSENSITIVE flag: The compile method of the Pattern class takes the CASE_INSENSITIVE flag along with the pattern to make the Expression case-insensitive. Below is the implementation:
Java
// Java program demonstrate How to make Java// Regular Expression case insensitive in Javaimport java.util.regex.Matcher;import java.util.regex.Pattern;  class GFG {    public static void main(String[] args)    {          // String        String str = "From GFG class. Welcome to gfg.";          // Create pattern to match along        // with the flag CASE_INSENSITIVE        Pattern patrn = Pattern.compile(            "gfg", Pattern.CASE_INSENSITIVE);          // All metched patrn from str case        // insensitive or case sensitive        Matcher match = patrn.matcher(str);          while (match.find()) {            // Print matched Patterns            System.out.println(match.group());        }    }}
GFG
gfg
2. Using modifier: The ” ?i “ modifier used to make a Java Regular Expression case-insensitive. So to make the Java Regular Expression case-insensitive we pass the pattern along with the ” ?i ” modifier that makes it case-insensitive. Below is the implementation:
Java
// Java program demonstrate How to make Java// Regular Expression case insensitive in Javaimport java.util.regex.Matcher;import java.util.regex.Pattern;  class GFG {    public static void main(String[] args)    {          // String        String str = "From GFG class. Welcome to gfg.";          // Create pattern to match along        // with the ?i modifier        Pattern patrn = Pattern.compile("(?i)gfg");          // All metched patrn from str case        // insensitive or case sensitive        Matcher match = patrn.matcher(str);          while (match.find()) {            // Print matched Patterns            System.out.println(match.group());        }    }}
GFG
gfg
java-regular-expression
Picked
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
Python | Sort JSON by value

12 Feb, 2019
Let’s see the different ways to sort the JSON data using Python.
What is JSON ?JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.
The task is to sort the JSON first by code, then by grade and then by enrollment_no .
Code #1: Sorting in Desc order
# Python code to demonstrate sorting in JSON.import json  data='''{     "Student":[        {           "enrollment_no":"9915103000",         "name":"JIIT",         "subject":[              {                 "code":"DBMS",               "grade":"C"            }         ]      },      {           "enrollment_no":"8815103057",         "name":"JSS",         "subject":[              {                 "code":"COA",               "grade":"A"            },            {                 "code":"CN",               "grade":"A+"            }         ]      }   ]}'''  # Parsing Json objectjson_parse = json.loads(data)   # iterating for it in json_parse['Student']:    for y in it['subject']:        print(y['code'],y['grade'],it['enrollment_no'],it['name'])
Output :
DBMS C 9915103000 JIIT
COA A 8815103057 JSS
CN A+ 8815103057 JSS
 Code #2 : By using External library such as Pandas (Sorting in Ascending order).
from pandas.io.json import json_normalize  df = json_normalize(json_parse['Student'],                               'subject',                     ['enrollment_no', 'name'])  df.sort_values(['code', 'grade', 'enrollment_no']).reset_index(drop=True)
Output:
  code grade  enrollment_no      name
0  CN     A+  8815103057         JSS
1  COA    A  8815103057         JSS
2  DBMS   C  9915103000        JIIT
JSON
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
C# | Getting the unique identifier for the current managed thread

01 Feb, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ManagedThreadId to check the unique identifier for the current managed thread. Or in other words, the value of ManagedThreadId property of a thread defines uniquely that thread within its process. The value of the ManagedThreadId property does not vary according to time.
Syntax:
public int ManagedThreadId { get; }
Return Value: This property returns a value that indicates a unique identifier for this managed thread. The return type of this property is System.Int32.
Example 1:
// C# program to illustrate the // use of ManagedThreadId propertyusing System;using System.Threading;  public class GFG {      // Main Method    static public void Main()    {        Thread T;          // Get the reference of main Thread        // Using CurrentThread property        T = Thread.CurrentThread;          // Display the unique id of the main         // thread Using ManagedThreadId property        Console.WriteLine("The unique id of the main "+                 "thread is: {0} ", T.ManagedThreadId);    }}
Output:
The unique id of the main thread is: 1 

Example 2:
// C# program to illustrate the // use of ManagedThreadId propertyusing System;using System.Threading;  public class GFG {      // Main method    public static void Main()    {        // Creating and initializing threads        Thread thr1 = new Thread(new ThreadStart(job));        Thread thr2 = new Thread(new ThreadStart(job));        Thread thr3 = new Thread(new ThreadStart(job));          Console.WriteLine("ManagedThreadId of thread 1 "+                        "is: {0}", thr1.ManagedThreadId);          Console.WriteLine("ManagedThreadId of thread 2 "+                        "is: {0}", thr2.ManagedThreadId);          Console.WriteLine("ManagedThreadId of thread 3 "+                        "is: {0}", thr3.ManagedThreadId);          // Running state        thr1.Start();        thr2.Start();        thr3.Start();    }      // Static method    public static void job()    {        Thread.Sleep(2000);    }}
Output:
ManagedThreadId of thread 1 is: 3
ManagedThreadId of thread 2 is: 4
ManagedThreadId of thread 3 is: 5

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.managedthreadid?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
C# | Delegates
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
HTML | <select> size Attribute

09 May, 2019
The HTML size Attribute is used to specifies the number of visible options in a drop-down list.
Note: If the value of the size attribute is greater than 1 but lower that the number of options in a DropDown List. so the Browser will automatically add the scrollbar for specifying that there are more options to view.
Syntax:
<select size = "value"> option values...</select> 
Attribute Values: It contains a numeric value which specify the number of visible options in the drop-down list. It has a Default value which is 4.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML select size Attribute</title></head>  <body>    <h1 style="color: green;">             GeeksforGeeks         </h1>      <h2>             HTML select size Attribute         </h2>    <p>Sorting Algorithms</p>    <select size="3">        <option value="merge">merge sort</option>        <option value="bubble">bubble sort</option>        <option value="selection">selection sort</option>        <option value="quick">quick sort</option>        <option value="insertion">insertion sort</option>    </select></body>  </html>
Output:
Supported Browsers: The browser supported by HTML Select size 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)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
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
Python | Padding a string upto fixed length

20 Mar, 2019
Given a string, the task is to pad string up to given specific length with whitespaces. Let’s discuss few methods to solve the given task.
Method #1: Using ljust()
# Python code to demonstrate# pad spaces in string# upto fixed length  # initialising stringini_string = "123abcjw"padding_size = 15  # printing string and its lengthprint ("initial string : ", ini_string, len(ini_string))  # code to pad spaces in stringres = ini_string.ljust(padding_size)  # printing string and its lengthprint ("final string : ", res, len(res))
initial string :  123abcjw 8
final string :  123abcjw        15

 Method #2: Using format
# Python code to demonstrate# pad spaces in string# upto fixed length  # initialising stringini_string = "123abcjw"  # printing string and its lengthprint ("initial string : ", ini_string, len(ini_string))  # code to pad spaces in stringres = "{:<15}".format(ini_string)  # printing string and its lengthprint ("final string : ", res, len(res))
initial string :  123abcjw 8
final string :  123abcjw        15

 Method #3: Using operators( * and +)
# Python code to demonstrate# pad spaces in string# upto fixed length  # initialising stringini_string = "123abcjw"padding_size = 15  # printing string and its lengthprint ("initial string : ", ini_string, len(ini_string))  # code to pad spaces in stringres = ini_string + " "*(padding_size - len(ini_string))  # printing string and its lengthprint ("final string : ", res, len(res))
initial string :  123abcjw 8
final string :  123abcjw        15

Python string-programs
Python
Python Programs
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
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 Program for Fibonacci numbers
How to Color Scatterplot by a variable in Matplotlib? - GeeksforGeeks

24 Jan, 2021
In this article, we are going to see how to color scatterplot by variable in Matplotlib. Here we will use matplotlib.pyplot.scatter() methods matplotlib library is used to draw a scatter plot. Scatter plots are widely used to represent relations among variables and how change in one affects the other. 
Syntax: matplotlib.pyplot.scatter(x_axis_data, y_axis_data,s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)
Example 1: Color Scatterplot by variable values.
In this example, We are going to see how to color scatterplot with their variable value. Here we will plot a simple scatterplot with x and y data, Then will use c attributes for coloring the point(Scatterplot variable points). 
Python3
import matplotlib.pyplot as plt   x =[5, 7, 8, 7, 2, 17, 2, 9,     4, 11, 12, 9, 6]   y =[99, 86, 87, 88, 100, 86,     103, 87, 94, 78, 77, 85, 86]   plt.scatter(x, y, c = 'red')   # To show the plot plt.show() 
Output:
Example 2: Color Scatterplot point with dependent values.
In this example, We will plot a variable depending on another variable. Sometimes we need precisely based visualization so in this case, It can help us to visualize the data that depend on another variable. Here we will use three different values for each point and use colormap with specific data.
Python3
import matplotlib.pyplot as plt   x =[5, 7, 8, 7, 3, 4, 5, 6, 7]  y =[99, 86, 87, 88, 4, 43, 34, 22, 12]  z = [1,2,3,4, 5, 6, 7, 8, 9]  plt.scatter(x, y, c = z , cmap = "magma")
Output:
 
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
Colouring the edges by weight in networkx (Matplotlib)

To color the edges by weight in networkx, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a graph with edges, name, or graph attributes.
Add nodes to the current graph.
Add edges to the current graph's nodes.
Iterate the given graph's edges and set some weight to them.
Draw current graphs with weights for edge color.
To display the figure, use show() method.
import random as rd
import matplotlib.pylab as plt
import networkx as nx

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])
for u, v, d in G.edges(data=True):
   d['weight'] = rd.random()
edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())
nx.draw(G, node_color='b', edge_color=weights, width=2, with_labels=True)

plt.show()
Python 3 - dictionary setdefault() Method

The method setdefault() is similar to get(), but will set dict[key] = default if key is not already in dict.
Following is the syntax for setdefault() method −
dict.setdefault(key, default = None)

key − This is the key to be searched. 
key − This is the key to be searched. 
default − This is the Value to be returned in case key is not found.
default − This is the Value to be returned in case key is not found.
This method returns the key value available in the dictionary and if given key is not available then it will return provided default value.
The following example shows the usage of setdefault() method.
#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.setdefault('Age', None))
print ("Value : %s" %  dict.setdefault('Sex', None))
print (dict)
When we run above program, it produces the following result −
Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}


    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
Macros and Preprocessors in C

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −
Some examples of Preprocessors −
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.
ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified.
#include <stdio.h>
int main() {
   printf("File :%s\n", __FILE__ );
   printf("Date :%s\n", __DATE__ );
   printf("Time :%s\n", __TIME__ );
   printf("Line :%d\n", __LINE__ );
   printf("ANSI :%d\n", __STDC__ );
}
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
How can we check the list of all triggers in a database?

With the help of the SHOW TRIGGERS statement, we can list all the triggers in a particular database. It can be illustrated with the help of the following example −
mysql> Show Triggers\G
*************************** 1. row ***************************
  Trigger: trigger_before_delete_sample
    Event: DELETE
    Table: sample
Statement: BEGIN

SET @count = if (@count IS NULL, 1, (@count+1));
INSERT INTO sample_rowaffected values (@count);
END

  Timing: BEFORE
 Created: 2017-11-21 12:31:58.70
sql_mode:

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERR
OR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
             Definer: root@localhost
character_set_client: cp850
collation_connection: cp850_general_ci
  Database Collation: latin1_swedish_ci
*************************** 2. row ***************************
  Trigger: before_inser_studentage
    Event: INSERT
    Table: student_age
Statement: IF NEW.age < 0 THEN SET NEW.age = 0;
END IF
  Timing: BEFORE
 Created: 2017-11-21 11:26:15.34
sql_mode:

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERR
OR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

             Definer: root@localhost
character_set_client: cp850
collation_connection: cp850_general_ci
  Database Collation: latin1_swedish_ci
2 rows in set (0.01 sec)
The above result set gives the list of triggers in the current database. Now, if we want to get the list of triggers in a particular database then we can use the following statement −
mysql> Show Triggers from tutorials\G
Empty set (0.00 sec)
The above result set shows that there is no trigger in the database named ‘tutorials’.
How to set the page-break behavior inside an element with JavaScript?

Use the pageBreakInside property in JavaScript to set the page-break behavior inside an element. Use the auto property to insert page break inside an element. Use auto or avoid property value to automatically insert page break inside an element, if needed, or avoid a page break, respectively.
Note − The changes would be visible while printing or viewing the print preview.
You can try to run the following code to return the page-break behavior inside an element with JavaScript −
<!DOCTYPE html>
<html>
   <body>
      <h1>Heading 1</h1>
      <p>This is demo text.</p>
      <p>This is demo text.</p>
      <p id = "myFooter">This if footer text.</p>
      <button type = "button" onclick="display()"> Set page-break </button>
     
      <script>
         function display() {
            document.getElementById("myFooter").style.pageBreakInside = "auto";
         }
      </script>
   </body>
</html>
Matlab-Matrix - Create a Matrix

In MATLAB, you can create a matrix by entering the elements in each row as comma. You can also create a matrix with space delimited numbers and by using the semicolons to mark the end of each row.
Let us create a simple matrix in MATLAB that has a single row and three elements. Each element should have a space or comma.
Consider the below mentioned elements to create a matrix.
m=[2, 4, 6]
On execution in MATLAB it will display the following −
>>m = [2, 4, 6]
 
m =

   2  4  6
>>

When you execute the code in MATLAB, the result of the matrix is displayed in the command window.
Let us now create a matrix with multiple rows. To do that, we need to separate each row with semicolon (;) as shown below −
m = [2 4 6; 3 6 9; 4 8 12]
Here 2 4 6 is the first row, 3 6 9 is the second row and 4 8 12 is the third row. The matrix will be as follows −
m = 2  4  6
    3  6  9
    4  8 12

Let us now execute the same in MATLAB command prompt, as mentioned below −
>> m = [2 4 6; 3 6 9; 4 8 12]

m =

   2  4  6
   3  6  9
   4  8 12
   
>>

The 3x3 matrix is displayed as shown above in MATLAB.
Besides creating matrix with the values of your choice you can also make use of the built-in MATLAB functions zeros, rand or ones to create a matrix as shown below −
This will create matrix with all zeros with the given row/column size.
Example
You can use MATLAB zeros function as follows −
m0 = zeros(3,3)
Output
You will get the following output −
>> m0 = zeros(3,3)

m0 =

   0  0  0
   0  0  0
   0  0  0
   
>>

The matrix created will have ones as the values.
Example
You can use MATLAB ones function as follows −
m1 = ones(3,3)
Output
You will get the following output −
>> m1 = ones(3,3)

m1 =
   1  1  1
   1  1  1
   1  1  1
   
>>

The function rand() allows you to create a matrix with random elements for the size given. Here is an example for the same.
Example
m1 = rand(3,3)
Output
Let us now execute the same in MATLAB to see the results. The output is as follows −
>> m1 = rand(3,3)

m1 =

   0.8147  0.9134  0.2785
   0.9058  0.6324  0.5469
   0.1270  0.0975  0.9575
   
>>


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Sum from array values with similar key in JavaScript

Let’s say, here is an array that contains some data about the stocks sold and purchased by
some company over a period of time.
const transactions = [
   ['AAPL', 'buy', 100],
   ['WMT', 'sell', 75],
   ['MCD', 'buy', 125],
   ['GOOG', 'sell', 10],
   ['AAPL', 'buy', 100],
   ['AAPL', 'sell', 100],
   ['AAPL', 'sell', 20],
   ['DIS', 'buy', 15],
   ['MCD', 'buy', 10],
   ['WMT', 'buy', 50],
   ['MCD', 'sell', 90]
];
We want to write a function that takes in this data and returns an object of arrays with key as
stock name (like ‘AAPL’, ‘MCD’) and value as array of two numbers, where the first element
represents the total buy and second element represents the total sell. Therefore, the code for
doing this will be −
const transactions = [
   ['AAPL', 'buy', 100],
   ['WMT', 'sell', 75],
   ['MCD', 'buy', 125],
   ['GOOG', 'sell', 10],
   ['AAPL', 'buy', 100],
   ['AAPL', 'sell', 100],
   ['AAPL', 'sell', 20],
   ['DIS', 'buy', 15],
   ['MCD', 'buy', 10],
   ['WMT', 'buy', 50],
   ['MCD', 'sell', 90]
];
const digestTransactions = (arr) => {
   return arr.reduce((acc, val, ind) => {
      const [stock, type, amount] = val;
      if(acc[stock]){
         const [buy, sell] = acc[stock];
         if(type === 'buy'){
            acc[stock] = [buy+amount, sell];
         }else{
            acc[stock] = [buy, sell+amount];
         }
         }else{
            if(type === 'buy'){
               acc[stock] = [amount, 0];
            }else{
               acc[stock] = [0, amount];
         }
      }
      return acc;
   }, {});
};
console.log(digestTransactions(transactions));
The output in the console will be −
{
   AAPL: [ 200, 120 ],
   WMT: [ 50, 75 ],
   MCD: [ 135, 90 ],
   GOOG: [ 0, 10 ],
   DIS: [ 15, 0 ]
}
Adding an image to SAP Adobe form from MIME repository

Note that Image must be uploaded from system to MIME beforehand.
Run Transaction SE78 → Upload (F5).
You have to declare 2 variables in the interface - global data with types string and xstring, You need to change the data declaration as below −
data: gv_bmp_watermark type xstring.
constants: gc_url_watermark type string
value '/BC/PUBLIC/MyImages/watermark100.bmp'.
You need to add the following under code initialization.
//* Read Images
data: lr_api type ref to if_mr_api.
lr_api = cl_mime_repository_api=>get_api( ).
lr_api->get( exporting i_url = gc_url_watermark
             importing e_content = gv_bmp_watermark).
You also need to change context node a bit as mentioned below −
Name: WATERMARK        
Graphic Type: GRAPHIC CONTENT        
Field: GV_BMP_WATERMARK        
MIME Type: 'image/bmp'
For more details, you can refer below lin −:
https://archive.sap.com/discussions/thread/3519383
https://wiki.scn.sap.com/wiki/display/profile/2007/11/01/Adding+Images+and+text+modules+in+Adobe+Forms
Python program to print all positive numbers in a range - GeeksforGeeks

26 Oct, 2018
Given start and end of a range, write a Python program to print all positive numbers in given range.
Example:
Input: start = -4, end = 5
Output: 0, 1, 2, 3, 4, 5 

Input: start = -3, end = 4
Output: 0, 1, 2, 3, 4
Example #1: Print all positive numbers from given list using for loop
Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num is greater than or equeal to 0. If the condition satisfies, then only print the number.
# Python program to print positive Numbers in given range  start, end = -4, 19  # iterating each number in listfor num in range(start, end + 1):          # checking condition    if num >= 0:        print(num, end = " ")
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
 Example #2: Taking range limit from user input
# Python program to print positive Numbers in given range  start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: "))  # iterating each number in listfor num in range(start, end + 1):          # checking condition    if num >= 0:        print(num, end = " ")
Output:
Enter the start of range: -215
Enter the end of range: 5
0 1 2 3 4 5 
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python Program to Reverse the Content of a File using Stack - GeeksforGeeks

04 Feb, 2022
Given a file, the task is to print as well as store the lines of that file in reverse order using Stack.Examples:  
Input :
I am
new to this
world of
Python.

Output :
Python.
world of
new to this
I am


Input :
1
2
3
4
5
Output :
5
4
3
2
1
Approach:  
Create an empty stack.  
One by one push every line of the file to the stack.  
One by one pop each line from the stack and put them back to the file.  
Below is the implementation.Input File: 
 
Python3
# Python3 code to reverse the lines# of a file using Stack.       # Creating Stack class (LIFO rule)class Stack:         def __init__(self):                 # Creating an empty stack        self._arr = []             # Creating push() method.    def push(self, val):        self._arr.append(val)      def is_empty(self):                 # Returns True if empty        return len(self._arr) == 0     # Creating Pop method.    def pop(self):                 if self.is_empty():            print("Stack is empty")            return                 return self._arr.pop() # Creating a function which will reverse# the lines of a file and Overwrites the# given file with its contents line-by-line# reverseddef reverse_file(filename):          S = Stack()    original = open(filename)         for line in original:        S.push(line.rstrip("\n"))         original.close()                output = open(filename, 'w')         while not S.is_empty():        output.write(S.pop()+"\n")         output.close()  # Driver Codefilename = "GFG.txt" # Calling the reverse_file functionreverse_file(filename)  # Now reading the content of the filewith open(filename) as file:        for f in file.readlines():            print(f, end ="")
Output: 
This is a World of Geeks.
Welcome to GeeksforGeeks.
 
 
gulshankumarar231
Python DSA-exercises
Python file-handling-programs
python-file-handling
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Charset defaultCharset() method in Java with Examples - GeeksforGeeks

29 Mar, 2019
The defaultCharset() method is a built-in method of the java.nio.charset which returns the charset object for the default charset. The default charset is basically determined by the Java virtual machine and it basically depends on the charset which is in the underlying operating system of the machine. In short, the result will vary from machine to machine.
Syntax:
public static Charset defaultCharset()
Parameters: The function does not accepts any parameter.
Return Value: The function returns a charset object for the default charset.
Below is the implementation of the above function:
Program 1:
// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map;  public class GFG {      public static void main(String[] args)    {          // Get the default charset of the machine        Charset cs = Charset.defaultCharset();          System.out.println("The default charset of the machine is :" + cs.displayName());    }}
The default charset of the machine is :US-ASCII

Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/Charset.html#defaultCharset()
Java-Charset
Java-Functions
Java-NIO package
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
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
Python | Numpy matrix.max() - GeeksforGeeks

15 Apr, 2019
With the help of Numpy matrix.max() method, we can get the maximum value from given matrix.
Syntax : matrix.max()
Return : Return maximum value from given matrix
Example #1 :In this example we can see that we are able to get the maximum value from a given matrix with the help of method matrix.max().
# import the important module in pythonimport numpy as np          # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]')          # applying matrix.max() methodgeeks = gfg.max()    print(geeks)
64

Example #2 :
# import the important module in pythonimport numpy as np          # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')          # applying matrix.max() methodgeeks = gfg.max()    print(geeks)
9

Python numpy-Matrix Function
Python-numpy
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
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
DivideByZeroException Class in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.
 Live Demo
using System;
namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;
      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in <a9b37148b4814c1a849bf4ee94fbe889>:0
Result: 0