code-rag-bench/online-tutorials huggingface dataset:
Python program to convert ASCII to Binary - GeeksforGeeks

31 Aug, 2021
In this article, we are going to discuss the conversion of ASCII to Binary in the Python programming language.
Binascii helps convert between binary and various ASCII-encoded binary representations.
a2b_uu() function:  Here the “uu” stands for “UNIX-to-UNIX encoding” which takes care of the data conversion from strings to binary and ASCII values according to the specified program. The a2b_uu() function is used to convert the specified ASCII format to its corresponding binary equivalent.
Syntax: a2b_uu(Text)
Parameter: This function accepts a single parameter which is illustrated below:
Text: This is the specified ASCII string that is going to be converted into its binary equivalent.
Return Values: This function returns the binary equivalent.
Python3
# Python program to illustrate the# conversion of ASCII to Binary  # Importing binascii moduleimport binascii  # Initializing a ASCII stringText = "21T9'(&ES(&$@0U,@4&]R=&%L"  # Calling the a2b_uu() function to# Convert the ascii string to binaryBinary = binascii.a2b_uu(Text)  # Getting the Binary valueprint(Binary)
Output:
b'GFG is a CS Portal'
Firstly, call string.encode() function to turn the specified string into an array of bytes and then call int.from_bytes(byte_array, byte_order) with byte_order as “big” to convert the byte_array into a binary integer. Finally, call bin(binary_int) to convert binary_int to a string of binary characters.
Python3
# Python program to illustrate the# conversion of ASCII to Binary  # Calling string.encode() function to# turn the specified string into an array# of bytesbyte_array = "GFG".encode()  # Converting the byte_array into a binary # integerbinary_int = int.from_bytes(byte_array, "big")  # Converting binary_int to a string of # binary charactersbinary_string = bin(binary_int)  # Getting the converted binary charactersprint(binary_string)
Output:
0b10001110100011001000111
Python string-programs
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 ?
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
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Year getValue() method in Java with Examples

01 Nov, 2019
The getValue() method of Year class in Java is used to get the integral value of the current Year object.
Syntax:
public int getValue()

Parameter: This method does not accepts any parameter.
Return Value: It returns an integer denoting the value of the current year object.
Below programs illustrate the getValue() method of Year in Java:
Program 1:
// Program to illustrate the getvalue() method  import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter;  public class GfG {    public static void main(String[] args)    {        // Creates a Year object        Year firstYear = Year.of(1997);          // Print the value of the current year        // using getValue() method        System.out.println(firstYear.getValue());    }}
1997

Program 2:
// Program to illustrate the getvalue() method  import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter;  public class GfG {    public static void main(String[] args)    {        // Creates a Year object        Year firstYear = Year.of(2018);          // Print the value of the current year        // using getValue() method        System.out.println(firstYear.getValue());    }}
2018

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#getValue–
Akanksha_Rai
Java-Functions
Java-time package
Java-Year
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memcached - Clear Data

Memcached flush_all command is used to delete all data (key-value pairs) from the Memcached server. It accepts an optional parameter called time that sets a time after which the Memcached data is to be cleared.
The basic syntax of Memcached flush_all command is as shown below −
flush_all [time] [noreply]

The above command always returns OK.
In the following example, we store some data into the Memcached server and then clear all the data.
set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END
flush_all
OK
get tutorialspoint
END

To clear data from a Memcached server, you need to use the Memcached flush method.
import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {
     
     // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("count", 900, "5").isDone());
      
      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("count"));
     
      // now increase the stored value
      System.out.println("Increment value:"+mcc.incr("count", 2));
     
      // now decrease the stored value
      System.out.println("Decrement value:"+mcc.decr("count", 1));
      
      // now get the final stored value
      System.out.println("Get from Cache:"+mcc.get("count"));
      
      // now clear all this data
      System.out.println("Clear data:"+mcc.flush().isDone());
   }
}
On compiling and executing the program, you get to see the following output −
Connection to server successfully
set status:true
Get from Cache:5
Increment value:7
Decrement value:6
Get from Cache:6
Python program to find IP Address

09 Nov, 2017
An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g., router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address).This article focus on How to get IP address of your computer in python.You have to first import socket library and then use
IP = socket.gethostbyname(hostname) 
and then print the value of the ip into the print() function your IP address as output as shown in the program given below.
# Python Program to Get IP Addressimport socket   hostname = socket.gethostname()   IPAddr = socket.gethostbyname(hostname)   print("Your Computer Name is:" + hostname)   print("Your Computer IP Address is:" + IPAddr)   
Output:
Your Computer Name is:pppContainer
Your Computer IP Address is:10.98.162.168

Related Post : Java program to find IP address of your computer
This article is contributed by ajay0007. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Computer Networks-IP Addressing
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.fork() method

11 Oct, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. 
os.fork() method in Python is used to create a child process. This method work by calling the underlying OS function fork(). This method returns 0 in the child process and child’s process id in the parent process. 
Note: os.fork() method is available only on UNIX platforms.
Syntax: os.fork()Parameter: No parameter is requiredReturn Type: This method returns an integer value representing child’s process id in the parent process while 0 in the child process.  
Code: Use of os.fork() method to create a child process  
Python3
# Python program to explain os.fork() method   # importing os module import os    # Create a child process# using os.fork() method pid = os.fork()  # pid greater than 0 represents# the parent process if pid > 0 :    print("I am parent process:")    print("Process ID:", os.getpid())    print("Child's process ID:", pid)  # pid equal to 0 represents# the created child processelse :    print("\nI am child process:")    print("Process ID:", os.getpid())    print("Parent's process ID:", os.getppid())    # If any error occurred while# using os.fork() method# OSError will be raised
I am Parent process
Process ID: 10793
Child's process ID: 10794

I am child process
Process ID: 10794
Parent's process ID: 10793
 
rajeev0719singh
gabaa406
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Triple list difference

29 Apr, 2019
The difference between 2 lists have been dealt previously, but sometimes, we can have more than two lists and we need to find the mutual differences of one list with every other list. This kind of problem has applications in many domains. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using map() + set() + list comprehension
The combination of above 3 functions can be used to perform this particular task. The map function can be used to convert the list to set by the set function and list comprehension can be used to get the new mutual difference list for each list.
# Python3 code to demonstrate# triple list difference # using map() + set() + list comprehension  # initializing lists test_list1 = [1, 5, 6, 4, 7]test_list2 = [8, 4, 3]test_list3 = [9, 10, 3, 5]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))print("The original list 3 : " + str(test_list3))  # using map() + set() + list comprehension# triple list difference temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))res1 = [ele for ele in test_list1 if ele not in temp2 and ele not in temp3]res2 = [ele for ele in test_list2 if ele not in temp1 and ele not in temp3]res3 = [ele for ele in test_list3 if ele not in temp2 and ele not in temp1]  # print resultprint("The mutual difference list are : "      + str(res1) + " " + str(res2) + " " + str(res3))
The original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
The mutual difference list are : [1, 6, 7] [8] [9, 10]

 
Method #2 : Using map() + set() + "-" operator
This problem can also be solved the minus operator, if one wishes not to use the list comprehension. The minus operator can perform the boolean match difference to compute the valid set difference.
# Python3 code to demonstrate# triple list difference # using map() + set() + "-" operator  # initializing lists test_list1 = [1, 5, 6, 4, 7]test_list2 = [8, 4, 3]test_list3 = [9, 10, 3, 5]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))print("The original list 3 : " + str(test_list3))  # using map() + set() + "-" operator# triple list difference temp1, temp2, temp3 = map(set, (test_list1, test_list2, test_list3))res1 = temp1 - temp2 - temp3res2 = temp2 - temp3 - temp1res3 = temp3 - temp1 - temp2res1, res2, res3 = map(list, (res1, res2, res3))  # print resultprint("The mutual difference list are : "      + str(res1) + " " + str(res2) + " " + str(res3))
The original list 1 : [1, 5, 6, 4, 7]
The original list 2 : [8, 4, 3]
The original list 3 : [9, 10, 3, 5]
The mutual difference list are : [1, 6, 7] [8] [9, 10]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Text Color Animation using HTML and CSS ?

11 Aug, 2021
The text color can be changed according to programmer’s choice using CSS @keyframes rule.
HTML Code: The following code snippet creates HTML div element which contains the text for modification.
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content=    "width=device-width, initial-scale=1.0">  <title>Text Color Animation</title></head><body>  <div>    <h2>GeeksforGeeks</h2>  </div></body></html>
CSS Code: The following code snippets demonstrates the design of the text using some basic CSS properties along with CSS @keyframes rule to change the color of the text to produce the animation effect.
<style>    body {        margin: 0;        padding: 0;    }     div {        position: absolute;        top: 50%;        left: 50%;        transform: translate(-50%, -50%);    }     h2 {        font-size: 5em;        font-family: serif;        color: transparent;        text-align: center;        animation: effect 2s linear infinite;    }     @keyframes effect {        0% {            background: linear-gradient(                #008000, #00FF00);            -webkit-background-clip: text;        }         100% {            background: linear-gradient(                #3CE7D7, #000FFF);            -webkit-background-clip: text;        }    }</style>
Complete Code: It is the combination of the above two code sections.
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Text Color Animation</title>     <style>        body {            margin: 0;            padding: 0;        }         div {            position: absolute;            top: 50%;            left: 50%;            transform: translate(-50%, -50%);        }         h2 {            font-size: 5em;            font-family: serif;            color: transparent;            text-align: center;            animation: effect 2s linear infinite;            \        }         @keyframes effect {            0% {                background: linear-gradient(                        #008000, #00FF00);                -webkit-background-clip: text;            }             100% {                background: linear-gradient(                        #3CE7D7, #000FFF);                -webkit-background-clip: text;            }        }    </style></head> <body>    <div>        <h2>GeeksforGeeks</h2>    </div></body> </html>
Output:
kapoorsagar226
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to select all child elements recursively using CSS?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
Convert Named Vector to DataFrame in R

06 Jun, 2021
In this article, we will see how to convert the named vector to Dataframe in the R Programming Language. 
Method 1:
Generally while converting a named vector to a dataframe we may face a problem. That is, names of vectors may get converted into row names, and data may be converted into a single column. So we need to convert the vector into a list then convert the list into a dataframe.
First, we will convert the vector into a list using as.list( ) method and passed it to data.frame( ) method in order to convert the vector into dataframe.
Example:
R
vector1 = c(1, "karthik", "IT")names(vector1) = c("id", "name", "branch")  df = data.frame(as.list(vector1))print(df)
Output :
Method 2: Using tibble library.
In tibble library there is a method called as_tibble( ) function. In order to use as_tibble( ) we need to install tibble library. To install package we can use install.packages( ) function by passing package name as parameter.
syntax : variable = as_tibble (as.list(vector)) 
Example:
R
library(tibble)vec1 = c("1", "karthik", "IT")names(vec1) = c("id", "name", "branch")  df=as_tibble(as.list(vec1))print(df)
Output:
Picked
R DataFrame-Programs
R Vector-Programs
R-DataFrame
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
<mat-expansion-panel> in Angular Material

25 Feb, 2021
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-expansion-panel> tag is a kind of dropdown which has collapse and expand functionalities.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatExpansionModule’ from ‘@angular/material/expansion’ in the app.module.ts file.
Then use <mat-accordion> tag as a parent tag for <mat-expansion-panel> tag.
Inside the <mat-accordion> tag we need to use <mat-expansion-panel> tag for every item.
For <mat-expansion-panel> tag we have many child tags which is been explained in the below table.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatExpansionModule } from '@angular/material';     import { AppComponent } from './example.component';     @NgModule({   declarations: [AppComponent],   exports: [AppComponent],   imports: [     CommonModule,     FormsModule,     MatExpansionModule    ], }) export class AppModule {}
app.component.html
<mat-accordion>  <mat-expansion-panel >    <mat-expansion-panel-header>      <mat-panel-title>         GEEKSFORGEEKS            </mat-panel-title>      <mat-panel-description>        Click here to expand the panel            </mat-panel-description>    </mat-expansion-panel-header>      <p>One stop portal to all Computer Science Subjects. </p>    </mat-expansion-panel>  </mat-accordion>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Explicitly define datatype in a Python function

29 Dec, 2020
Unlike other languages Java, C++, etc. Python is a strongly-typed dynamic language in which we don’t have to specify the data type of the function return value and function argument. It relates type with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions.
Example 1: We have a function to add 2 elements.
Python3
# function definitiondef add(num1, num2):    print("Datatype of num1 is ", type(num1))    print("Datatype of num2 is ", type(num2))    return num1 + num2  # calling the function without# explicitly declaring the datatypesprint(add(2, 3))  # calling the function by explicitly# defining the datatype as floatprint(add(float(2), float(3)))
Output:
Datatype of num1 is  <class 'int'>
Datatype of num2 is  <class 'int'>
5
Datatype of num1 is  <class 'float'>
Datatype of num2 is  <class 'float'>
5.0

Example 2: We have a function for string concatenation
Python3
# function definitiondef concatenate(num1, num2):    print("Datatype of num1 is ", type(num1))    print("Datatype of num2 is ", type(num2))    return num1 + num2  # calling the function without# explicitly declaring the datatypesprint(concatenate(111, 100))  # calling the function by explicitly# defining the datatype as floatprint(concatenate(str(111), str(100)))
Output:
Datatype of num1 is  <class 'int'>
Datatype of num2 is  <class 'int'>
211
Datatype of num1 is  <class 'str'>
Datatype of num2 is  <class 'str'>
111100

Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

HTML form attributes
Tryit: submit method POST
How to get all the processes on remote computers using PowerShell?

To get all running processes on the remote computer, you need to use – ComputerNameparameter in Get-process cmdlet, WMI class Win32_Process or using the Get-CimInstance cmdlet.
With –ComputerName parameter
Get-process -ComputerName Test-PC
To connect multiple computers use computer names separated by comma (,).
Get-process -ComputerName Test-PC, Win2k8

With WMI object to get processes on multiple remote computers.
Get-WmiObject Win32_Process -ComputerName Test-PC, Win2k8
Get-CimInstance cmdlet to get processes on remote computers.
Get-CimInstance Win32_Process -ComputerName Test-PC, Win2k8
C# Program to add a node after the given node in a Linked List

Set a LinkedList and add elements.
string [] students = {"Beth","Jennifer","Amy","Vera"};
LinkedList<string> list = new LinkedList<string>(students);
Firstly, add a new node at the end.
var newNode = list.AddLast("Emma");
Now, use the AddAfter() method to add a node after the given node.
list.AddAfter(newNode, "Matt");
The following is the complete code.
 Live Demo
using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Beth","Jennifer","Amy","Vera"};
      LinkedList<string> list = new LinkedList<string>(students);
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }

      // adding a node at the end
      var newNode = list.AddLast("Emma");

      // adding a new node after the node added above
      list.AddAfter(newNode, "Matt");

      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}
Beth
Jennifer
Amy
Vera
LinkedList after adding new nodes...
Beth
Jennifer
Amy
Vera
Emma
Matt
C++ Vector Library - front() Function

The C++ function std::vector::front() returns a reference to the first element of the vector.
Following is the declaration for std::vector::front() function form std::vector header.
reference front();
const_reference front() const;

None
Returns constant reference if object is constant qualified otherwise returns non-constant reference.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::front() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};

   cout << "First element of vector = " << v.front() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
First element of vector = 1

 Print
 Add Notes
 Bookmark this page
Python Design Patterns - Template

A template pattern defines a basic algorithm in a base class using abstract operation where subclasses override the concrete behavior. The template pattern keeps the outline of algorithm in a separate method. This method is referred as the template method.
Following are the different features of the template pattern −
It defines the skeleton of algorithm in an operation
It defines the skeleton of algorithm in an operation
It includes subclasses, which redefine certain steps of an algorithm.
It includes subclasses, which redefine certain steps of an algorithm.
class MakeMeal:

   def prepare(self): pass
   def cook(self): pass
   def eat(self): pass

   def go(self):
      self.prepare()
      self.cook()
      self.eat()

class MakePizza(MakeMeal):
   def prepare(self):
      print "Prepare Pizza"
   
   def cook(self):
      print "Cook Pizza"
   
   def eat(self):
      print "Eat Pizza"

class MakeTea(MakeMeal):
   def prepare(self):
      print "Prepare Tea"
	
   def cook(self):
      print "Cook Tea"
   
   def eat(self):
      print "Eat Tea"

makePizza = MakePizza()
makePizza.go()

print 25*"+"

makeTea = MakeTea()
makeTea.go()
The above program generates the following output −
This code creates a template to prepare meal. Here, each parameter represents the attribute to create a part of meal like tea, pizza, etc.
The output represents the visualization of attributes.

    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
MySQL Tryit Editor v1.0

SELECT NOW() + 1;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
C library function - memcpy()

The C library function void *memcpy(void *dest, const void *src, size_t n) copies n characters from memory area src to memory area dest.
Following is the declaration for memcpy() function.
void *memcpy(void *dest, const void * src, size_t n)
dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*.
src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*.
n − This is the number of bytes to be copied.
n − This is the number of bytes to be copied.
This function returns a pointer to destination, which is str1.
The following example shows the usage of memcpy() function.
#include <stdio.h>
#include <string.h>

int main () {
   const char src[50] = "http://www.tutorialspoint.com";
   char dest[50];
   strcpy(dest,"Heloooo!!");
   printf("Before memcpy dest = %s\n", dest);
   memcpy(dest, src, strlen(src)+1);
   printf("After memcpy dest = %s\n", dest);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Before memcpy dest = Heloooo!!
After memcpy dest = http://www.tutorialspoint.com


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Python program to count Even and Odd numbers in a List

26 Oct, 2018
Given a list of numbers, write a Python program to count Even and Odd numbers in a List.
Example:
Input: list1 = [2, 7, 5, 64, 14]
Output: Even = 3, odd = 2

Input: list2 = [12, 14, 95, 3]
Output: Even = 2, odd = 2
Example 1: count Even and Odd numbers from given list using for loop
Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. If the condition satisfies, then increase even count else increase odd count.
# Python program to count Even# and Odd numbers in a List  # list of numberslist1 = [10, 21, 4, 45, 66, 93, 1]  even_count, odd_count = 0, 0  # iterating each number in listfor num in list1:          # checking condition    if num % 2 == 0:        even_count += 1      else:        odd_count += 1          print("Even numbers in the list: ", even_count)print("Odd numbers in the list: ", odd_count)
Even numbers in the list:  3
Odd numbers in the list:  4

Example 2: Using while loop
# Python program to count Even and Odd numbers in a List  # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11]  even_count, odd_count = 0, 0num = 0  # using while loop     while(num < len(list1)):          # checking condition    if list1[num] % 2 == 0:        even_count += 1    else:        odd_count += 1          # increment num     num += 1      print("Even numbers in the list: ", even_count)print("Odd numbers in the list: ", odd_count)
Even numbers in the list:  3
Odd numbers in the list:  4

Example 3 : Using Python Lambda Expressions
# list of numberslist1 = [10, 21, 4, 45, 66, 93, 11]  odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))  # we can also do len(list1) - odd_counteven_count = len(list(filter(lambda x: (x%2 == 0) , list1)))  print("Even numbers in the list: ", even_count)print("Odd numbers in the list: ", odd_count)
Even numbers in the list:  3
Odd numbers in the list:  4

Example 4 : Using List Comprehension
# Python program to print odd Numbers in a List   # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11]   only_odd = [num for num in list1 if num % 2 == 1]odd_count = len(only_odd)   print("Even numbers in the list: ", len(list1) - odd_count)print("Odd numbers in the list: ", odd_count)
Even numbers in the list:  3
Odd numbers in the list:  4

Python list-programs
python-lambda
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.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Matplotlib.axes.Axes.grid() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.grid() function in axes module of matplotlib library is used to Configure the grid lines.
Syntax: Axes.grid(self, b=None, which=’major’, axis=’both’, **kwargs)
Parameters: This method accept the following parameters.
b : This parameter is an optional parameter, whether to show the grid lines or not.
which : This parameter is also an optional parameter and it is the grid lines to apply the changes on.
axis :This parameter is also an optional parameter and it is the axis to apply the changes on.
Returns:This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.grid() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function   import matplotlib.pyplot as pltimport numpy as np     fig, ax = plt.subplots()ax.plot([1, 2, 3])ax.grid()ax.set_title('matplotlib.axes.Axes.grid() Example\n',             fontsize = 12, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt    x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x    fig, [ax, ax1] = plt.subplots(2, 1,                               sharex = True)  ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1,                facecolor ='green',                alpha = 0.8)  ax.fill_between(x, y1, y2, where = y2 <= y1,                 facecolor ='black',                 alpha = 0.8)  ax.xaxis.grid(True, color ="black")ax.set_title('matplotlib.axes.Axes.grid() \Example\n\n Grid in X-axis',             fontsize = 12, fontweight ='bold')  ax1.plot(x, y1, x, y2, color ='black')ax1.fill_between(x, y1, y2, where = y2 >y1,                  facecolor ='green',                 alpha = 0.8)  ax1.fill_between(x, y1, y2, where = y2 <= y1,                 facecolor ='black',                  alpha = 0.8)  ax1.yaxis.grid(True, color ="black")ax1.set_title('Grid in y-axis',             fontsize = 12, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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
Java Applet | Draw a line using drawLine() method

18 Jan, 2019
This article shall be explaining the code to draw a line using paint in Java. This uses drawLine() method.
Syntax:
drawLine(int x1, int y1, int x2, int y2)
Parameters: The drawLine method takes four arguments:
x1 – It takes the first point’s x coordinate.
y1 – It takes first point’s y coordinate.
x2 – It takes second point’s x coordinate.
y2 – It takes second point’s y coordinate
Result: This method will draw a line starting from (x1, y1) co-ordinates to (x2, y2) co-ordinates.
Below programs illustrate the above problem:
Example:
// Java program to draw a line in Applet  import java.awt.*;import javax.swing.*;import java.awt.geom.Line2D;  class MyCanvas extends JComponent {      public void paint(Graphics g)    {          // draw and display the line        g.drawLine(30, 20, 80, 90);    }}  public class GFG1 {    public static void main(String[] a)    {          // creating object of JFrame(Window popup)        JFrame window = new JFrame();          // setting closing operation        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          // setting size of the pop window        window.setBounds(30, 30, 200, 200);          // setting canvas for draw        window.getContentPane().add(new MyCanvas());          // set visibility        window.setVisible(true);    }}
Output :
Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x1, x2, y1 and y2 coordinates can be changed by the programmer according to their need.
java-applet
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
PyQt5 QListWidget – Setting Edit Trigger Property

06 Aug, 2020
In this article we will see how we can set the edit trigger property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property describes actions which will initiate item editing.
In order to do this we will use setEditTriggers method with the list widget object.
Syntax : list_widget.setEditTriggers(et)
Argument : It takes edit triggers object argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")            # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting edit trigger property        list_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Difference between two lists

30 Jun, 2021
There are various ways in which the difference between two lists can be generated. In this article, we will see the two most important ways in which this can be done. One by using the set() method, and another by not using it.  
Examples:  
Input :
list1 = [10, 15, 20, 25, 30, 35, 40]
list2 = [25, 40, 35] 
Output :
[10, 20, 30, 15]
Explanation:
resultant list = list1 - list2
          
 Note: When you have multiple same elements then this would not work. In that case, this code will simply remove the same elements.In that case, you can maintain a count of each element in both lists.
 
In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator. For more reference on set visit Sets in Python.  
Example: 
Python3
# Python code t get difference of two lists# Using set()def Diff(li1, li2):    return list(set(li1) - set(li2)) + list(set(li2) - set(li1)) # Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]print(Diff(li1, li2))
Output :  
[10, 20, 30, 15]
 
In this method, we use the basic combination technique to copy elements from both the list with a regular check if one is present in the other or not.  
Example:
Python3
# Python code t get difference of two lists# Not using set()def Diff(li1, li2):    li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]    return li_dif # Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]li3 = Diff(li1, li2)print(li3)
Output : 
[10, 20, 30, 15]
ashishk2409
mihika0278
utsavp0213
akashdeep8757
python-list
python-set
Python
python-list
python-set
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | Add trailing Zeros to string

25 Jun, 2022
Sometimes, we wish to manipulate a string in such a way in which we might need to add additional zeros at the end of string; in case of filling the missing bits or any other specific requirement. The solution to this kind of problems is always handy and is good if one has knowledge of it. Let’s discuss certain ways in which this can be solved.
Method #1 : Using ljust() This task can be performed using the simple inbuilt string function of ljust in which we just need to pass no. of zeros required and the element to right pad, in this case being zero. 
Python3
# Python3 code to demonstrate# adding trailing zeros# using ljust() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # using ljust()# adding trailing zerores = test_string.ljust(N + len(test_string), '0') # print resultprint("The string after adding trailing zeros : " + str(res))
The original string : GFG
The string after adding trailing zeros : GFG0000
  Method #2 : Using format() String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case right. 
Python3
# Python3 code to demonstrate# adding trailing zeros# using format() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # using format()# adding trailing zero# N for number of elements, '0' for Zero, and '<' for trailingtemp = '{:<07}'res = temp.format(test_string) # print resultprint("The string after adding trailing zeros : " + str(res))
The original string : GFG
The string after adding trailing zeros : GFG0000
Method #3 : Without any built-in methods
Python3
# Python3 code to demonstrate# adding trailing zeros # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4  # adding trailing zerox = '0'*Nres = test_string+x # print resultprint("The string after adding trailing zeros : " + str(res))
The original string : GFG
The string after adding trailing zeros : GFG0000
simranarora5sos
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
TypeScript - String indexOf()

This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
string.indexOf(searchValue[, fromIndex])

searchValue − A string representing the value to search for.
searchValue − A string representing the value to search for.
fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Returns the index of the found occurrence, otherwise -1 if not found.
var str1 = new String( "This is string one" ); 
 
var index = str1.indexOf( "string" ); 
console.log("indexOf found String :" + index );   

var index = str1.indexOf( "one" ); 
console.log("indexOf found String :" + index );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
indexOf found String :8 
 
indexOf found String :15
How to use PSCustomObject in PowerShell foreach parallel loop?

To use the PSCustomObject inside the Foreach Parallel loop, we first need to consider how we are using the variables inside the loop.
$Out = "PowerShell"
ForEach-Object -Parallel{
   Write-Output "Hello.... $($using:Out)"
}
So let see if we can store or change a value in the $out variable.
$Out = @()
ForEach-Object -Parallel{
   $using:out = "Azure"
   Write-Output "Hello....$($using:out) "
}
Line |
   4 | $using:out = "Azure"
     | ~~~~~~~~~~
     | The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept
     | assignments, such as a variable or a property.
The error says that the expression is invalid so we can’t manipulate the variable directly. So we have another method that we can use a temporary variable for it.
$Out = @()
ForEach-Object -Parallel{
   $dict = $using:out
   $dict = "Azure"
   Write-Output "Hello....$dict"
}
Similarly, we can use the PSCustomObject using the Temporary variable as shown below.
$Out = @()
$vms = "Testvm1","Testvm2","Testvm3"
$vmout = $vms | ForEach-Object -Parallel{
   $dict = $using:out
   $dict += [PSCustomObject]@{
      VMName = $_
      Location = 'EastUS'
   }
   return $dict
}
Write-Output "VM Output"
$vmout
VMName Location
------ --------
Testvm1 EastUS
Testvm2 EastUS
Testvm3 EastUS
Internet Service Provider (ISP) hierarchy

08 Oct, 2020
Internet Service Provider (ISP) is a company which provides internet connection to end user, but there are basically three levels of ISP. There are 3 levels of Internet Service Provider (ISP): Tier-1 ISP, Tier-2 ISP, and Tier-3 ISP. 
These are explained as following below. 
Tier-1 ISP: These ISPs are at the top of the hierarchy and they have a global reach they do not pay for any internet traffic through their network instead lower-tier ISPs have to pay a cost for passing their traffic from one geolocation to another which is not under the reach of that ISPs. Generally, ISPs at the same level connect to each other and allow free traffic passes to each other. Such ISPs are called peers. Due to this cost is saved. They build infrastructure, such as the Atlantic Internet sea cables, to provide traffic to all other Internet service providers, not to end users. Examples: Some examples of tier 1 Internet providers: 
Examples: Some examples of tier 1 Internet providers: 
Cogent Communications,
Hibernia Networks,
AT&T

Tier-2 ISP: These ISPs are service provider who connect between tier 1 and tier 3 ISPs. They have regional or country reach and they behave just like Tier-1 ISP for Tier-3 ISPs. Examples: Examples of tier 2 ISPs: 
Examples: Examples of tier 2 ISPs: 
Vodafone,
Easynet,
BT

Tier-3 ISP: These ISPs are closest to the end users and helps them to connect to the internet by charging some money. These ISPs work on purchasing model. These ISPs have to pay some cost to Tier-2 ISPs based on traffic generated. Examples: Examples of Tier-3 ISPs: 
Examples: Examples of Tier-3 ISPs: 
Comcast,
Deutsche Telekom,
Verizon Communications 
 
dhawal_m55
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
GSM in Wireless Communication
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Data encryption standard (DES) | Set 1