code-rag-bench/online-tutorials huggingface dataset:
What is serialization in C#.NET?

Serialization converts objects into a byte stream and brings it to a form that it can be written on stream. This is done to save it to memory, file or database.
Serialization can be performed as −
All the members, even members that are read-only, are serialized.
It serializes the public fields and properties of an object into XML stream conforming to a specific XML Schema definition language document.
Let us see an example. Firstly set the stream −
FileStream fstream = new FileStream("d:\\new.txt", FileMode.OpenOrCreate);
BinaryFormatter formatter=new BinaryFormatter();
Now create an object of the class and call the constructor which has three parameters −
Employee emp = new Employee(030, "Tom", “Operations”);

Perform serialization −
formatter.Serialize(fStream, emp);
Python DSA-exercises Archives - GeeksforGeeks

Check for balanced parentheses in Python
k-nearest neighbor algorithm in Python
Python Program for Tower of Hanoi
Generate a graph using Dictionary in Python
Python Program to Reverse a linked list
Python Library for Linked List
Python Program for N Queen Problem | Backtracking-3
Check whether the given string is Palindrome using Stack
Python program to reverse the content of a file and store it in another file
Priority Queue using Queue and Heapdict module in Python
How to accept all pending connection requests on LinkedIn using JavaScript ? - GeeksforGeeks

24 May, 2021
Many times we get a lot of connection requests over LinkedIn, and we want to accept all of them but for that, we have to click the accept button for each connection request. With the help of the following way, we can accept all of them at once using JavaScript helping us to save our time and effort.
Approach:
Make a variable connection that points to an array of all the pending connections.
Run a loop to iterate all the pending connection.
Then click on the accept button of that connection request using the JavaScript click function.
Steps:
Go to the LinkedIn page or click here.
If you are not Signed in. You should Sign in to your account.
Open the My Network tab visible on the page.
Click on the Show more button to see all the connection requests.Note: The show more button will only be visible if you have more than 3 connection requests. Keep on clicking until all the connection requests are visible.
Open the developer console by pressing F12 or CTRL+SHIFT+I
Copy and paste the following script on the console and hit enter.
Javascript
var connection = document    .querySelectorAll(    '.invitation-card__action-btn.artdeco-button--secondary'); for(var i = 0; i < connection.length; i = i + 1)  connection[i].click();
Output:
Before running script:
After running script:
Note: 
Please ensure that there is a stable internet connection available so that the script runs smoothly.
The script will only work when all the connections are visible.
This tutorial is for educational purposes only.
tanmaygoyalpro
JavaScript-Misc
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to change the aspect ratio of a plot in ggplot2 in R?

The aspect ratio of a chart can be changed in ggplot2 and this will be useful if we want a smaller image of the chart. Sometimes, we don’t have large space where the chart will be pasted therefore this functionality becomes useful. Mostly, in research reports we see charts that are of small size, hence R becomes helpful to create charts that can be pasted in the desired space. This can be done with the help of theme function.
Consider the below data frame −
> set.seed(100)
> x<-rpois(30,2)
> df<-data.frame(x)
Loading the ggplot2 package −
> library(ggplot2)
Creating the plot with aspect ratio 4/3 −
> ggplot(df,aes(x))+
+ geom_bar()+
+ theme(aspect.ratio=4/3)
Creating the plot with aspect ratio 16/9 −
> ggplot(df,aes(x))+
+ geom_bar()+
+ theme(aspect.ratio=16/9)
Creating the plot with aspect ratio 1, it gives us a square form −
> ggplot(df,aes(x))+
+ geom_bar()+
+ theme(aspect.ratio=1)
Redis - Server Flushall Command

Redis FLUSHALL deletes all the keys of all the existing databases, not just the currently selected one. This command never fails.
String reply.
Following is the basic syntax of Redis FLUSHALL command.
redis 127.0.0.1:6379> FLUSHALL 

redis 127.0.0.1:6379> FLUSHALL  
OK


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
JavaScript | Proxy() Object - GeeksforGeeks

14 Feb, 2019
The proxy object in JavaScript is used to define the custom behavior of fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Syntax:
var p = new Proxy(target, handler);
Parameter: The proxy object accept two parameters as mentioned above and described below:
target: A target object (can be any sort of object including a function, class, or even another proxy) to wrap with Proxy.
handler: An object whose properties are functions which define the behavior of the proxy when an operation is performed on it.
Example:
                        <script>const Person = {    Name: 'John Nash',    Age: 25};  const handler = {    // target represents the Person while prop represents        // proxy property.    get: function(target, prop) {        if (prop === 'FirstName') {            return target.Name.split(' ')[0];        }        if (prop === 'LastName') {            return target.Name.split(' ').pop();        }        else {            return Reflect.get(target,prop);        }    }};  const proxy1 = new Proxy(Person, handler);  document.write(proxy1 + "<br>");  // Though there is no Property as FirstName and LastName, // still we get them as if they were property not function.document.write(proxy1.FirstName + "<br>");document.write(proxy1.LastName  + "<br>");     </script>                    
Output:
[object Object]
John
Nash

Note: The above code can be run directly in terminal provided NodeJs is installed, else run it in a HTML file by pasting the above in script tag and check the output in console of any web browser.
javascript-object
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to randomize (shuffle) a JavaScript array?

To randomize a JavaScript array to display random elements, you can try to run the following code:
Live Demo
<html>    
   <body>              
      <script>  
         function randomFunc(myArr) {      
            var l = myArr.length, temp, index;  
            while (l > 0) {  
               index = Math.floor(Math.random() * l);  
               l--;  
               temp = myArr[l];          
               myArr[l] = myArr[index];          
               myArr[index] = temp;      
            }    
            return myArr;    
         }        
         var arr = [10, 20, 30, 40, 50];    
         document.write(randomFunc(arr));  
       </script>          
   </body>
</html>
20,50,40,30,10
Spring Boot - Admin Client

For monitoring and managing your microservice application via Spring Boot Admin Server, you should add the Spring Boot Admin starter client dependency and point out the Admin Server URI into the application properties file.
Note − For monitoring an application, you should enable the Spring Boot Actuator Endpoints for your Microservice application.
First, add the following Spring Boot Admin starter client dependency and Spring Boot starter actuator dependency in your build configuration file.
Maven users can add the following dependencies in your pom.xml file −
<dependency>
   <groupId>de.codecentric</groupId>
   <artifactId>spring-boot-admin-starter-client</artifactId>
   <version>1.5.5</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Gradle users can add the following dependencies in your build.gradle file.
compile group: 'de.codecentric', name: 'spring-boot-admin-starter-client', version: '1.5.5'
compile('org.springframework.boot:spring-boot-starter-actuator')
Now, add the Spring Boot Admin Server URL into your application properties file.
For properties file users, add the following properties in the application.properties file.
spring.boot.admin.url = http://localhost:9090/

For YAML users, add the following property in application.yml file.
spring:
   boot:
      admin:
         url: http://localhost:9000/

Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.
For Maven, you can use the command as shown −
mvn clean install

After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the command as shown −
gradle clean build

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the command shown −
java –jar <JARFILE> 

Now, the application has started on the Tomcat port 9090 as shown −
Now hit the following URL from your web browser and see your spring Boot application is registered with Spring Boot Admin Server.
http://localhost:9090/
Now, click the Details button and the see the actuator endpoints in Admin Server UI.

    102 Lectures 
     8 hours 

 Karthikeya T

    39 Lectures 
     5 hours 

 Chaand Sheikh

    73 Lectures 
     5.5 hours 

 Senol Atac

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac

    69 Lectures 
     5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python program to find Least Frequent Character in a String

When it is required to find the least frequent character in a string, ‘Counter’ is used to get the count of letters. The ‘min’ method is used to get the minimum of values in the string, i.e every letter’s count is stored along with the letter. The minimum is obtained.
Below is a demonstration of the same
from collections import Counter

my_str = "highland how"

print ("The string is : ")
print(my_str)

my_result = Counter(my_str)
my_result = min(my_result, key = my_result.get)

print ("The minimum of all characters in the string is : ")
print(my_result)
The string is :
highland how
The minimum of all characters in the string is :
a
The required packages are imported.
The required packages are imported.
A string is defined, and is displayed on the console.
A string is defined, and is displayed on the console.
The ‘Counter’ is used to get the count of every letter in the string.
The ‘Counter’ is used to get the count of every letter in the string.
This is assigned to a variable.
This is assigned to a variable.
The ‘min’ method is used to get the minimum of values.
The ‘min’ method is used to get the minimum of values.
This is assigned to the variable again.
This is assigned to the variable again.
This is displayed as output on the console.
This is displayed as output on the console.
Rexx - TIME

This method returns the local time in the 24-hour clock format as shown in the following program.
hh:mm:ss (hours, minutes, and seconds) 

TIME(options)

Options − This is the options for formatting the time value. They can be anyone of the following options −
Civil − This parameter returns the time in the format () wherein hh is hours, mm is minutes and xx is seconds
Civil − This parameter returns the time in the format () wherein hh is hours, mm is minutes and xx is seconds
Elapsed − This parameter returns the number of seconds and microseconds since the elapsed-time clock was started or reset
Elapsed − This parameter returns the number of seconds and microseconds since the elapsed-time clock was started or reset
Full − This parameter returns the number of microseconds since the date 1 January 0001
Full − This parameter returns the number of microseconds since the date 1 January 0001
Hours − This parameter returns the number of hours that have passed since midnight
Hours − This parameter returns the number of hours that have passed since midnight
Minutes − This parameter returns the number of minutes that have passed since midnight
Minutes − This parameter returns the number of minutes that have passed since midnight
Normal − This parameter returns the time in the default format hh:mm:ss
Normal − This parameter returns the time in the default format hh:mm:ss
Offset − This parameter returns the offset of the local time from UTC in microseconds.
Offset − This parameter returns the offset of the local time from UTC in microseconds.
This method returns the local time in the 24-hour clock format − hh:mm:ss (hours, minutes, and seconds).
/* Main program */ 
say TIME() 
say TIME("C") 
say TIME("H")
When we run the above program we will get the following result. This depends on the current time on the system.
The following program is just an example.
10:54:12 
10:54am 
10 

 Print
 Add Notes
 Bookmark this page
Greatest Common Divisor of Strings in Python

Suppose there are two strings A and B. We can say that A is divisible by B, when A is created by concatenating B one or more times. So if A = “abcabc”, and B = “abc”, then A is divisible by B. In this section, we will see what is the greatest common divisor of a String. So return the largest string that divides both of the strings. So if two strings are “ABABAB”, and “ABAB”, then GCD will be “AB”
To solve this, we will follow these steps −
temp := shorter string between A and B
m := length of temp
x := 1
res is an array and insert “” into the res
while A and B has substring of size x, then add the substring into the res, and increase x by 1
finally return the last element in the res array.
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def gcdOfStrings(self, str1, str2):
      if len(str1)<=len(str2):
         temp = str1
      else:
         temp = str2
      m = len(temp)
      x = 1
      res=[""]
      while x<=m:
         if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2:
            res.append(temp[:x])
         x+=1
      return res[-1]
ob1 = Solution()
print(ob1.gcdOfStrings("ABABAB","ABAB"))
"ABABAB"
"ABAB"
AB
Redis - Keys Type Command

Redis TYPE command is used to get the data type of the value stored in the key.
String reply, data type of the value stored in the key or none.
Following is the basic syntax of Redis TYPE command.
redis 127.0.0.1:6379> TYPE KEY_NAME 

First, create some keys in Redis and set some values in it.
redis 127.0.0.1:6379> SET tutorial1 redis 
OK 

Now, check the type of the key.
redis 127.0.0.1:6379> TYPE tutorial1 
string 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
What are event attributes in jQuery?

jQuery events have attributes such as for keyup and keydown events, if the Ctrl key was pressed, timestamp when the event created, etc.
The following are some of the event properties/attributes available:
You can try to run the following code to learn how to work with jQuery event attributes:
Live Demo
<html>

   <head>
      <title>jQuery Attributes</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $('div').bind('click', function( event ){
               alert('Event type is ' + event.type);
               alert('pageX : ' + event.pageX);
               alert('pageY : ' + event.pageY);
               alert('Target : ' + event.target.innerHTML);
            });
         });
      </script>
       
      <style>
         .div {
            margin:10px;
            padding:12px;
            border:2px solid #666;
            width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
       
   </body>
   
</html>
Implementation of Stack in JavaScript

Following is the code to implement stack in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   button {
      padding: 6px;
      margin: 4px;
   }
</style>
</head>
<body>
<h1>Implementation of Stack in JavaScript.</h1>
<div class="result"></div>
<br />
<input type="text" class="stackPush" /><button class="pushBtn">Push</button>
<button class="popBtn">Pop</button>
<button class="Btn">Display</button>
<h3>Click on the above buttons to perform stack operations</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let pushBtnEle = document.querySelector(".pushBtn");
   let popBtnEle = document.querySelector(".popBtn");
   class Stack {
      constructor() {
         this.items = [];
         this.top = 0;
      }
   }
   Stack.prototype.push = function (ele) {
      this.items[this.top] = ele;
      this.top += 1;
   };
   Stack.prototype.pop = function () {
      if (this.top === 0) {
         return "Underflow: no more elements to delete";
      }
      tempNum = this.items[this.top - 1];
      this.items.length -= 1;
      return tempNum;
   };
   Stack.prototype.display = function () {
      if (this.top == 0) {
         return "Stack is empty";
      }
      for (let i = 0; i < this.top; i++) {
         resEle.innerHTML += this.items[i] + " , ";
      }
   };
   let stack1 = new Stack();
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "";
      stack1.display();
   });
   pushBtnEle.addEventListener("click", () => {
      let ele = document.querySelector(".stackPush").value;
      resEle.innerHTML = ele + " is pushed to the stack";
      stack1.push(ele);
   });
   popBtnEle.addEventListener("click", () => {
      resEle.innerHTML = stack1.pop() + " is popped from the stack";
   });
</script>
</body>
</html>
On entering number in the field and clicking on ‘Push’ −
On clicking the ‘Pop’ button −
On clicking the ‘Display’ button when the stack is not empty −
How to check if a process is exited from the system after executing Stop-Process command in PowerShell?

After killing the process using Stop-Process command in PowerShell, you can determine if the process is really terminated from the system with HasExited function.
For example, we will kill Notepad process and check if Notepad process still exists in the system?
$notepad = Get-Process notepad | Stop-Process
if($notepad.HasExited){"Process is terminated"}
else{"Process is still running"}
Python Tutorial

Python is a popular programming language.
Python can be used on a server to create web applications.
With our "Try it Yourself" editor, you can edit Python code and view the result.
Click on the "Try it Yourself" button to see how it works.
In our File Handling section you will learn how to open, read, write, and 
delete files.
Python File Handling
In our database section you will learn how to access and work with MySQL and MongoDB databases:
Python MySQL Tutorial
Python MongoDB Tutorial
Insert the missing part of the code below to output "Hello World".
("Hello World")

Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All Python Examples
Test your Python skills with a quiz.
Python Quiz
You will also find complete function and method references:
Reference Overview
Built-in Functions
String Methods
List/Array Methods
Dictionary Methods
Tuple Methods
Set Methods
File Methods
Python Keywords
Python Exceptions
Python Glossary
Random Module
Requests Module
Math Module
CMath Module
Download Python from the official Python web site:
  https://python.org
Get certified by completing the PYTHON course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to List values for each Pandas group? - GeeksforGeeks

20 Aug, 2020
In this article, we’ll see how we can display all the values of each group in which a dataframe is divided. The dataframe is first divided into groups using the DataFrame.groupby() method. Then we modify it such that each group contains the values in a list.
First, Let’s create a Dataframe:
Python3
# import pandas libraryimport pandas as pd  # create a dataframedf = pd.DataFrame({'a': ['A', 'A', 'B',                          'B', 'B', 'C',                          'C', 'D'],                     'b': [1, 2, 5,                          3, 5, 4,                          8, 6]})# show the dataframe                  df
Output:
Method 1: Using DataFrame.groupby() and Series.apply() together.Example: We’ll create lists of all values of each group and store it in new column called “listvalues”.
Python3
# import pandas libraryimport pandas as pd  # create a dataframedf = pd.DataFrame({'a': ['A', 'A', 'B',                          'B', 'B', 'C',                          'C', 'D'],                     'b': [1, 2, 5,                          3, 5, 4,                          8, 6]})                   # convert values of each group# into a listgroups = df.groupby('a')['b'].apply(list)  print(groups)  # groups store in a new # column called listvaluesdf1 = groups.reset_index(name                          = 'listvalues')# show the dataframedf1
Output:
Method 2: Using DataFrame.groupby() and Series.agg().
Example: We use the lambda function inside the Series.agg() to convert the all values of a group to a list.
Python3
# import pandas libraryimport pandas as pd  # create a dataframedf = pd.DataFrame( {'a': ['A', 'A', 'B',                         'B', 'B', 'C',                          'C', 'D'],                     'b': [1, 2, 5,                          3, 5, 4,                         8, 6]}                 )# convert values of each group# into a listgroups = df.groupby('a').agg(lambda                             x: list(x))  print(groups)
Output:
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
C# - Passing Arrays as Function Arguments

You can pass an array as a function argument in C#. The following example demonstrates this −
using System;

namespace ArrayApplication {
   class MyArray {
      double getAverage(int[] arr, int size) {
         int i;
         double avg;
         int sum = 0;
         
         for (i = 0; i < size; ++i) {
            sum += arr[i];
         }
         avg = (double)sum / size;
         return avg;
      }
      static void Main(string[] args) {
         MyArray app = new MyArray();
         
         /* an int array with 5 elements */
         int [] balance = new int[]{1000, 2, 3, 17, 50};
         double avg;

         /* pass pointer to the array as an argument */
         avg = app.getAverage(balance, 5 ) ;

         /* output the returned value */
         Console.WriteLine( "Average value is: {0} ", avg );
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

CSS Grid Item
Tryit: The grid-area property
How to copy items from one location to another location using PowerShell?

To copy items in PowerShell, one needs to use the Copy-Item cmdlet. When you use the Copy-Item, you need to provide the source file name and the destination file or folder name.
In the below example, we will copy a single file from the D:\Temp to the D:\Temp1 location.
Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru
PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru
    Directory: D:\Temp1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       20-01-2020     12:10        1148809 PowerShellcommands.csv


In the above example, PowerShellCommands.csv file will be copied from the D:\Temp to the D:\Temp1 location. If the file already exists then it simply overwrites the file without any prompt or error or warning.
When you use the –Passthru parameter in the command, it displays the output in the console.
You can also rename items when you use the copy command. For that, you need to mention a new file name to the destination parameter.
Copy-Item -Path D:\Temp\PowerShellcommands.csv 
-Destination D:\Temp1\PowerShel lcommands1.csv -PassThru
PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\PowerShellcommands1.csv -PassThru
    Directory: D:\Temp1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       20-01-2020     12:10        1148809 PowerShellcommands1.csv
While copying item(s) to another location, their attributes are also copies with them.
When you copy files from the source folder to the destination folder, and if the destination folder doesn’t exist then files(s) won’t get copied and it will throw an exception of DirectoryNotFoundException.
For example, we will copy the above mentioned PowerShellcommands1.csv file to the unknown destination folder D:\Temp2 as shown below.
Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShel
lcommands.csv -PassThru
PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShellcommands.csv -PassThru
Copy-Item : Could not find a part of the path 'D:\Temp2\PowerShellcommands.csv'.
At line:1 char:1
+ Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
Assign value to unique number in list in Python

Many times we need to identify the elements in a list uniquely. For that we need to assign unique IDs to each element in the list. This can be achieved by the following two approaches using different inbuilt functions available in Python.
The enumerate function assigns unique ids to each element. But if the list already as duplicate elements then we need to create a dictionary of key value pairs form the list and assign unique values using the set function.
 Live Demo
# Given List
Alist = [5,3,3,12]
print("The given list : ",Alist)

# Assigning ids to values
enum_dict = {v: k for k, v in enumerate(set(Alist))}
list_ids = [enum_dict[n] for n in Alist]

# Print ids of the dictionary
print("The list of unique ids is: ",list_ids)
Running the above code gives us the following result −
The given list : [5, 3, 3, 12]
The list of unique ids is: [2, 0, 0, 1]
The map() function applies the same function again and again to the different parameters passed to it. But the count method returns the number of elements with the specified value. So we combine these two get the list of unique IDs for the elements of a given list in the below program.
from itertools import count

# Given List
Alist = [5,3,3,12]
print("The given list : ",Alist)

# Assign unique value to list elements
dict_ids = list(map({}.setdefault, Alist, count()))

# The result
print("The list of unique ids is: ",dict_ids)
Running the above code gives us the following result −
The given list : [5, 3, 3, 12]
The list of unique ids is: [0, 1, 1, 3]
Python program to check if the string is pangram

In this tutorial, we are going to write a program that checks whether a string is a pangram or not. Let's start the tutorial by talking about the pangram.
If a string contains all the alphabets whether small or caps then, the string is called panagram.
We can achieve the goal in different ways. Let's see two of them in this tutorial.
Try to write the program using the following steps.
1. Import the string module.
2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase Contains all the
alphabets as a string.
3. Initialize the string which we have to check for pangram.
4. Define a function called is_anagram(string, alphabets).
   4.1. Loop over the alphabets.
      4.1.1. If the character from alphabets is not in the string.
         4.1.1.1. Return False
   4.2. Return True
5. Print pangram if the returned value is true else print not pangram.
## importing string module
import string
## function to check for the panagram
def is_panagram(string, alphabets):
   ## looping over the alphabets
   for char in alphabets:
      ## if char is not present in string
      if char not in string.lower():
         ## returning false
         return False
   return True
## initializing alphabets variable
alphabets = string.ascii_lowercase
## initializing strings
string_one = "The Quick Brown Fox Jumps Over The Lazy Dog"
string_two = "TutorialsPoint TutorialsPoint"
print("Panagram") if is_panagram(string_one, alphabets) else print("Not Panagram")
print("Panagram") if is_panagram(string_two, alphabets) else print("Not Panagram")
If you run the above program, you will get the following results.
Panagram
Not Panagram
Let's see how to get the same results using sets data structure. See the steps below to get an idea.
1. Import the string module.
2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase contains all the alphabets as a string.
3. Initialize the string which we have to check for pangram.
4. Convert both alphabets and string(lower) to sets.
5. Print pangram if string set is greater than or equal to alphabets set else print not pangram.
Let's write the code.
 Live Demo
## importing string module
import string
## initializing alphabets variable
alphabets = string.ascii_lowercase
## initializing strings
string_one = "The Quick Brown Fox Jumps Over The Lazy Dog"
string_two = "TutorialsPoint TutorialsPoint"
print("Panagram") if set(string_one.lower()) >= set(alphabets) else print("Not Pana gram")
print("Panagram") if set(string_two.lower()) >= set(alphabets) else print("Not Pana gram")
If you run the above program, you will get the following results.
Panagram
Not Panagram
If you have any doubts regarding the tutorial, please do mention them in the comment section.
What is NgStyle in Angular 10 ? - GeeksforGeeks

30 Apr, 2021
In this article, we are going to see what is NgStyle in Angular 10 and how to use it.
NgStyle is used to add some style to an HTML element
Syntax:
<element [ngStyle] = "typescript_property">
Approach: 
Create the Angular app to be used
In app.component.html make an element and sets its class using ngStyle directive
Serve the angular app using ng serve to see the output
Example 1:
app.component.ts
import { Component, OnInit } from '@angular/core';  @Component({    selector: 'app-root',    templateUrl: './app.component.html'})export class AppComponent {    }
app.component.html
<div [ngStyle] ="{'background-color':'green'}">  GeeksforGeeks</div>  <div [ngStyle] ="{'color':'GREEN'}">  GeeksforGeeks</div>
Output:
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
C++ String Library - insert

It inserts additional characters into the string right before the character indicated by pos.
Following is the declaration for std::string::insert.
string& insert (size_t pos, const string& str);
string& insert (size_t pos, const string& str);
string& insert (size_t pos, const string& str);
pos − It is an insertion point.
pos − It is an insertion point.
str − It is a string object.
str − It is a string object.
It returns *this.
if an exception is thrown, there are no changes in the string.
In below example for std::string::insert.
#include <cassert>
#include <iterator>
#include <string>
using namespace std::literals;
int main() {
   std::string s = "xmplr";

   s.insert(0, 1, 'E');
   assert("Exmplr" == s);

   s.insert(2, "e");
   assert("Exemplr" == s);

   s.insert(6, "a"s);
   assert("Exemplar" == s);

   s.insert(8, " is an example string."s, 0, 14);
   assert("Exemplar is an example" == s);

   s.insert(s.cbegin() + s.find_first_of('n') + 1, ':');
   assert("Exemplar is an: example" == s);
 
   s.insert(s.cbegin() + s.find_first_of(':') + 1, 2, '=');
   assert("Exemplar is an:== example" == s);
   {
      std::string seq = " string";
      s.insert(s.begin() + s.find_last_of('e') + 1,
      std::begin(seq), std::end(seq));
      assert("Exemplar is an:== example string" == s);
   }

   s.insert(s.cbegin() + s.find_first_of('g') + 1, { '.' });
   assert("Exemplar is an:== example string." == s);
}
 Print
 Add Notes
 Bookmark this page
Python Program to get number of consecutive repeated substring - GeeksforGeeks

06 Jun, 2021
Given a substring K, the task is to write a Python Program to find the repetition of K string in each consecutive occurrence of K.
Example
Input : test_str = ‘geeksgeeks are geeksgeeksgeeks for all geeks’, K = “geeks”
Output : [2, 3, 1]
Explanation : First consecution of ‘geeks’ is 2. 
Input : test_str = ‘geeksgeeks are geeksgeeksgeeksgeeks for all geeks’, K = “geeks”
Output : [2, 4, 1]
Explanation : First consecution of ‘geeks’ is 2, next comes with 4 consecution of geeks.
Method 1: Using split() + count() + list comprehension
Works only for specific cases in which consecution is separated by spaces. In this, each word is splitted using split(), and each segment is evaluated for repetition count using count().
Python3
# Python3 code to demonstrate working of# Number of repeated substrings in consecution# Using split() + count() + list comprehension  # initializing stringtest_str = 'geeksgeeks are geeksgeeksgeeks for all geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing K K = "geeks"  # count() counts repetitionres = [sub.count(K) for sub in test_str.split(' ') if sub.count(K) != 0]  # printing resultprint("String repetitions : " + str(res))
Output:
The original string is : geeksgeeks are geeksgeeksgeeks for all geeks
String repetitions : [2, 3, 1]
Method 2: Using findall() + regex + len()
In this, all the runs are computed for repetition of substring, and then division of length by substring length gives the measure of repetition number.  
Python3
# Python3 code to demonstrate working of# Number of repeated substrings in consecution# Using findall() + regex + len()import re  # initializing stringtest_str = 'geeksgeeksaregeeksgeeksgeeksforallgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing K K = 'geeks'n = len(K)  # getting regexregx = re.compile(f'((?:{K})+)')  # getting repeats counts# findall finding all substring joined repetitionsres = [len(occ) // n for occ in regx.findall(test_str)]  # printing resultprint("String repetitions : " + str(res))
Output:
The original string is : geeksgeeks are geeksgeeksgeeks for all geeks
String repetitions : [2, 3, 1]
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
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
std::string::clear in C++

06 Jul, 2017
The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters.Parameters: noneReturn Value: none
void string ::clear ()
- Removes all characters (makes string empty)
- Doesn't throw any error
- Receives no parameters and returns nothing
// CPP code to illustrate// clear() function  #include <iostream>#include <string>using namespace std;  // Function to demo clear()void clearDemo(string str){    // Deletes all characters in string    str.clear();      cout << "After clear : ";    cout << str;}  // Driver codeint main(){    string str("Hello World!");      cout << "Before clear : ";    cout << str << endl;    clearDemo(str);      return 0;}
Output:
Before clear : Hello World!
After clear : 

Related Article: std::string::eraseThis article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) 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.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How addEventListener works for keydown on HTML 5 Canvas ?

30 Jan, 2020
The addEventListener() method is an inbuilt function in JavaScript which takes the event to listen for. The second argument to be called whenever the described event gets fired means the keydown event is fired whenever a key is pressed. This article explains the working of a keydown event listener on a canvas.
The canvas needs to be in focus on to catch key events. It is not possible to assign the keydown event to canvas because it is not possible to focus the canvas with the cursor. So, a workaround for this problem is to bring the canvas to focus.
Below example illustrates the working approach of addEventListner for keydown on canvas:
Example:
<!DOCTYPE html> <html>  <head>    <title>        Working of addeventlistener        for keydown on a canvas    </title>          <style>         body {            display: block;            margin-top: 8%;        }        h1 {             color:green;            text-align:center;         }                  /* Canvas decoration */        canvas {            display: block;            margin: 0 auto;            background: green;            border: 2px solid black;            height: 300px;             width: 300px;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <canvas id="canvas"></canvas>          <script>        var lastDownTarget, canvas;        window.onload = function() {            canvas = document.getElementById('canvas');                          /* For mouse event */            document.addEventListener('mousedown',                            function(event)             {                lastDownTarget = event.target;                alert('Mousedown Event');            }, false);                          /* For keyboard event */            document.addEventListener('keydown',                            function(event)             {                if(lastDownTarget == canvas) {                    alert('Keydown event! Key pressed: '                                      + event.key);                }            }, false);        }    </script></body>  </html>
Output: First, the canvas is brought to focus on using the mousedown event. After the canvas is brought to focus, the keydown event is fired.
CSS-Misc
HTML-Canvas
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Difference between SHA1 and SHA256 - GeeksforGeeks

28 Dec, 2020
1. SHA1 (Secure Hash Algorithm 1) :SHA1 refers to a cryptographic hash function that is proposed by United States National Security Agency. It takes an input and produces a output of 160 bits hash value. Furthermore the output produced by this function is converted into a 40 digits long hexadecimal number. It is known as U.S. Federal Information Processing Standard. It was first published in 1995. It is successor to SH0 published in 1993.
Example :
Data : Geeksforgeeks
SHA1 : bc7623b7a94ed3d8feaffaf7580df3eca4f5f5ca

2. SHA256 :SHA-256 is a more secure and newer cryptographic hash function that was launched in 2000 as a new version of SHA functions and was adopted as FIPS standard in 2002. It is allowed to use a hash generator tool to produce a SHA256 hash for any string or input value. Also, it generates 256 hash values, and the internal state size is 256 bit and the original message size is up to 264-1 bits.
Example :
Data : Geeksforgeeks
SHA256 : e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Difference between SHA1 and SHA256 :
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Introduction and IPv4 Datagram Header
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Python program to find occurrence to each character in given string - GeeksforGeeks

20 May, 2019
Given a string, the task is to write a program in Python which prints the number of occurrences of each character in a string.
There are multiple ways in Python, we can do this task. Let’s discuss a few of them.
Method #1: Using set() + count()
Iterate over the set converted string and get the count of each character in original string.
# Python3 code to program to find occurrence# to each character in given string  # initializing string inp_str = "GeeksforGeeks"  # using set() + count() to get count # of each element in string out = {x : inp_str.count(x) for x in set(inp_str )}   # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(out)) 
Occurrence of all characters in GeeksforGeeks is :
 {'o': 1, 'r': 1, 'e': 4, 's': 2, 'f': 1, 'G': 2, 'k': 2}

 Method #2: Using dictionary
# Python3 code to program to find occurrence# to each character in given string  # initializing string inp_str = "GeeksforGeeks"  # frequency dictionaryfreq = {}     for ele in inp_str:     if ele in freq:         freq[ele] += 1    else:         freq[ele] = 1    # printing result  print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq)) 
Occurrence of all characters in GeeksforGeeks is :
 {'e': 4, 'r': 1, 'o': 1, 'f': 1, 'G': 2, 's': 2, 'k': 2}

 Method #3: Using collections
# Python3 code to program to find occurrence# to each character in given stringfrom collections import Counter     # initializing string  in_str = "GeeksforGeeks"    # using collections.Counter() to get  # count of each element in string  oup = Counter(in_str)     # printing result  print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(oup)) 
Occurrence of all characters in GeeksforGeeks is :
 Counter({'e': 4, 's': 2, 'G': 2, 'k': 2, 'f': 1, 'r': 1, 'o': 1})

Python list-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 ?
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?
Check given matrix is magic square or not in C++

Here we will see, if a matrix is magic square or not, a magic square is a square matrix, where the sum of each row, each column, and each diagonal are same.
Suppose a matrix is like below −
This is a magic square, if we see, the sum of each row, column and diagonals are 15.
To check whether a matrix is magic square or not, we have to find the major diagonal sum and the secondary diagonal sum, if they are same, then that is magic square, otherwise not.
 Live Demo
#include <iostream>
#define N 3
using namespace std;
bool isMagicSquare(int mat[][N]) {
   int sum_diag = 0,sum_diag_second=0;
   for (int i = 0; i < N; i++)
      sum_diag = sum_diag + mat[i][i];
   for (int i = 0; i < N; i++)
      sum_diag_second = sum_diag_second + mat[i][N-1-i];
   if(sum_diag!=sum_diag_second)
      return false;
   for (int i = 0; i < N; i++) {
      int rowSum = 0;
      for (int j = 0; j < N; j++)
         rowSum += mat[i][j];
      if (rowSum != sum_diag)
         return false;
   }
   for (int i = 0; i < N; i++) {
      int colSum = 0;
      for (int j = 0; j < N; j++)
         colSum += mat[j][i];
      if (sum_diag != colSum)
      return false;
   }
   return true;
}
int main() {
   int mat[][N] = {{ 6, 1, 8 },
   { 7, 5, 3 },
   { 2, 9, 4 }};
   if (isMagicSquare(mat))
      cout << "It is Magic Square";
   else
   cout << "It is Not a magic Square";
}
It is Magic Square