code-rag-bench/online-tutorials huggingface dataset:
Python os.dup2() Method

Python method dup2() duplicates file descriptor fd to fd2, closing the latter first if necessary.
Note − New file description would be assigned only when it is available. In the following example given below, 1000 would be assigned as a duplicate fd in case when 1000 is available.
Following is the syntax for dup2() method −
os.dup2(fd, fd2);

fd − This is File descriptor to be duplicated.
fd − This is File descriptor to be duplicated.
fd2 − This is Duplicate file descriptor.
fd2 − This is Duplicate file descriptor.
This method returns a duplicate of file descriptor.
The following example shows the usage of dup2() method.
#!/usr/bin/python

import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, "This is test")

# Now duplicate this file descriptor as 1000
fd2 = 1000
os.dup2(fd, fd2);

# Now read this file from the beginning using fd2.
os.lseek(fd2, 0, 0)
str = os.read(fd2, 100)
print "Read String is : ", str

# Close opened file
os.close( fd )

print "Closed the file successfully!!"
When we run above program, it produces following result −
Read String is :  This is test
Closed the file successfully!!


    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
Visualizing High Dimensional Data | by Himanshu Sharma | Towards Data Science

Data visualization helps in identifying hidden patterns, associations, and trends between different columns of data. We create different types of charts, plots, graphs, etc. in order to understand what data is all about and how different columns are related to each other.
It is easy to visualize data that have lower dimensions but when it comes to data having higher dimensions it is very difficult to analyze or visualize them because it is not possible to show a large number of dimensions in a visualization.
But what if I tell you that there is a python toolbox it not only creates visually appealing visualizations but also facilitates dimensionality reduction in a single function call.
Hypertools is an open-source python toolbox that creates visualizations from high dimensional datasets by reducing the dimensionality by itself. It is built on top of mainly matplotlib, sklearn, and seaborn. In this article, we will explore some of the visualizations that we can create using hypertools.
Let’s get started...
We will start by installing hypertools using pip. The command given below will do that.
pip install hypertools
In this step, we will import the required library that will be used for creating visualizations.
import hypertools as hyp
Now we will start creating different visualizations and see how hypertools work.
Basic Plot
Basic Plot
# data loadingbasic = hyp.load('weights_sample')# Creating plotbasic.plot(fmt='.')
2. Cluster Plot
clust = hyp.load('mushrooms')# Creating plotclust.plot(n_clusters=10)
3. Corpus Plots
This plot is used for textual datasets.
text = ['i am from India', 'India is in asia', 'Asia is the largest continent',        'There are 7 continents', 'Continents means earth surfaces ', 'Surfaces covers land area',        'land area is largest in asia']# creating plothyp.plot(text, '*', corpus=text)
4. UMAP
from sklearn import datasetsdata = datasets.load_digits(n_class=6)df = digits.datahue = data.target.astype('str')hyp.plot(df, '.', reduce='UMAP', hue=hue, ndims=2)
5. Animated Plots
ani = hyp.load('weights_avg')# plotani.plot(animate=True, chemtrails=True)
Go ahead try this with different datasets and create beautiful visualizations to interpret data. In case you find any difficulty please let me know in the response section.
This article is in collaboration with Piyush Ingale.
Reference: https://hypertools.readthedocs.io/en/latest/
Thanks for reading! If you want to get in touch with me, feel free to reach me at hmix13@gmail.com or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
Different ways to start a Task in C#

To start a task in C#, follow any of the below given ways.
Use a delegate to start a task.
Task t = new Task(delegate { PrintMessage(); });
t.Start();

Use Task Factory to start a task.
Task.Factory.StartNew(() => {Console.WriteLine("Welcome!"); });

You can also use Lambda.
Task t = new Task( () => PrintMessage() );
t.Start();
MySQL SELECT from two tables with a single query

Use UNION to select from two tables. Let us first create a table −
mysql> create table DemoTable1
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.90 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1(FirstName) values('Chris') ;
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1(FirstName) values('Adam');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1(FirstName) values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Adam      |
|  3 | Sam       |
+----+-----------+
3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
);
Query OK, 0 rows affected (1.75 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2(FirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable2(FirstName) values('Tom');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2(FirstName) values('Bob');
Query OK, 1 row affected (0.50 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | John      |
|  2 | Tom       |
|  3 | Bob       |
+----+-----------+
3 rows in set (0.00 sec)
Following is the query to select from two tables using MySQL UNION −
mysql> (select *from DemoTable1)
   union
   (select *from DemoTable2)
   order by FirstName;
This will produce the following output −
+----+-----------+
| Id | FirstName |
+----+-----------+
|  2 | Adam      |
|  3 | Bob       |
|  1 | Chris     |
|  1 | John      |
|  3 | Sam       |
|  2 | Tom       |
+----+-----------+
6 rows in set (0.00 sec)
Explain JavaScript "this" keyword?

The JavaScript this keyword references the object to which it belongs. It can refer to the global object if alone or inside a function. It refers to the owner object if inside a method and refers to the HTML element that received the event in an event listener.
Following is the code for the JavaScript this Identifier −
 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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript this Identifier</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see which object 'this' refers to in multiple
context
</h3>
<script>
   let thisRef = this;
   let sampleEle = document.querySelector(".sample");
   function test() {
      return this;
   }
   let testObj = {
      a: 22,
      check() {
         return this;
      },
   };
   document.querySelector(".Btn").addEventListener(
      "click",
      () => {
         sampleEle.innerHTML = "This inside normal function = " + test() + "<br>";
         sampleEle.innerHTML += "This inside a method = " + testObj.check() + "<br>";
         sampleEle.innerHTML += "This without any scope = " + thisRef + "<br>";
      },
      false
   );
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “CLICK HERE” button −
Add Two Numbers in Python

Suppose we have given two non-empty linked lists. These two lists are representing two non-negative integer numbers. The digits are stored in reverse order. Each of their nodes contains only one digit. Add the two numbers and return the result as a linked list. We are taking the assumption that the two numbers do not contain any leading zeros, except the number 0 itself. So if the numbers are 120 + 230, then the linked lists will be [0 → 2 → 1] + [0 → 3 → 2] = [0 → 5 → 3] = 350.
To solve this, we will follow these steps
Take two lists l1 and l2. Initialize head and temp as null
c := 0
while l1 and l2 both are non-empty listsif l1 is non-empty, then set a := 0, otherwise set a := l1.valif l2 is non-empty, then set b := 0, otherwise set b := l2.valn := a + b + cif n > 9, then c := 1 otherwise 0node := create a new node with value n mod 10if head is nullhead := node and temp := nodeotherwisehead.next := node, and head := nodel1 := next node of l1, if l1 existsl2 := next node of l2, if l2 exists
if l1 is non-empty, then set a := 0, otherwise set a := l1.val
if l2 is non-empty, then set b := 0, otherwise set b := l2.val
n := a + b + c
if n > 9, then c := 1 otherwise 0
node := create a new node with value n mod 10
if head is nullhead := node and temp := node
head := node and temp := node
head := node and temp := node
otherwisehead.next := node, and head := node
head.next := node, and head := node
l1 := next node of l1, if l1 exists
l2 := next node of l2, if l2 exists
if c is non-zero, thennode := new node with value 1, next of head := node
node := new node with value 1, next of head := node
return temp
Let us see the following implementation to get a better understanding
 Live Demo
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution:
   def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
      head = None
      temp = None
      c = 0
      while l1 or l2:
         if not l1:
            a= 0
         else:
            a = l1.val
         if not l2:
            b=0
         else:
            b = l2.val
         n = a +b + c
         c = 1 if n>9 else 0
         node = ListNode(n%10)
         if not head:
            head = node
            temp = node
         else:
            head.next = node
            head = node
         l1 = l1.next if l1 else None
         l2 = l2.next if l2 else None
      if c:
         node = ListNode(1)
         head.next = node
      return temp
ob1 = Solution()
l1 = make_list([0,2,1])
l2 = make_list([0,3,2])
print_list(ob1.addTwoNumbers(l1, l2))
[0,2,1]
[0,3,2]
[0,5,3]
Scala - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Scala is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
The following arithmetic operators are supported by Scala language. For example, let us assume variable A holds 10 and variable B holds 20, then −
Show Examples
The following relational operators are supported by Scala language. For example let us assume variable A holds 10 and variable B holds 20, then −
Show Examples
The following logical operators are supported by Scala language. For example, assume variable A holds 1 and variable B holds 0, then −
Show Examples
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

The Bitwise operators supported by Scala language is listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Show Examples
There are following assignment operators supported by Scala language −
Show Examples
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Take a look at the following table. Operators with the highest precedence appear at the top of the table and those with the lowest precedence appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
CharMatcher Class in Java

The CharMatcher class determines a true or false value for any Java char value, just as Predicate does for any Object.
Create the following java program using any editor of your choice in say C:/> Guava.
Following is the GuavaTester.java code −
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
public class GuavaTester {
   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();
      tester.testCharMatcher();
   }
   private void testCharMatcher() {
      System.out.println(CharMatcher.DIGIT.retainFrom("mahesh123")); // only the digits
      System.out.println(CharMatcher.WHITESPACE.trimAndCollapseFrom(" Mahesh Parashar ", ' '));
      // trim whitespace at ends, and replace/collapse whitespace into single spaces
      System.out.println(CharMatcher.JAVA_DIGIT.replaceFrom("mahesh123", "*"));
      // star out all digits                  
      System.out.println(CharMatcher.JAVA_DIGIT.or(CharMatcher.JAVA_LOWER_CASE).retainFrom("mahesh123"));
      // eliminate all characters that aren't digits or lowercase
   }
}

Compile the class using javac compiler as follows
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result −
C:\Guava>java GuavaTester
This will produce the following output −
123
Mahesh Parashar
mahesh***
mahesh123
JavaScript String - split() Method

This method splits a String object into an array of strings by separating the string into substrings.
Its syntax is as follows −
string.split([separator][, limit]);

separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string.
separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string.
limit − Integer specifying a limit on the number of splits to be found.
limit − Integer specifying a limit on the number of splits to be found.
The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array.
Try the following example.
<html>
   <head>
      <title>JavaScript String split() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = "Apples are round, and apples are juicy.";
         var splitted = str.split(" ", 3);
         document.write( splitted );
      </script>      
   </body>
</html>
Apples,are,round, 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Jupyter Notebook Not Rendering on GitHub? Here’s a Simple Solution. | by Sidney Kung | Towards Data Science

Have you ever tried to preview your Jupyter Notebook file and received this pesky error message after about 20+ seconds of waiting?
About 70% of the time, we see this message. As if it’s a gamble to see whether your .ipynb file will render or not.
Good news, this “Sorry, something went wrong. Reload?” message doesn’t have an impact on your actual commit. It’s just an issue on GitHub’s end because it’s unable to render a preview of the file.
After much research, it seems that no one on the internet is quite sure about why this problem is occurring. People speculate that it could the a problem with the file size, or perhaps the type of browser that the viewer is using.
Regardless of what may be causing this problem, don’t worry. I have the answer to your prayers!
Nbviewer is a web application that lets you enter the URL of a Jupyter Notebook file on GitHub, then it renders that notebook as a static HTML web page. This gives you a stable link to that page which you can share with others.
In addition to always successfully rendering a Jupyter Notebook, it also has other advantages for users.
On the rare occasion that an .ipynb file actually loads on Github, it sometimes fails to display certain objects.
For instance, GitHub isn’t able to load Folium maps. When we try to generate a map of Los Angeles, we get this error:
Output of folium.__version__
However if we use nbviewer, the full interactive map loads without a problem. See for yourself!
Additionally, this website’s features aren’t exclusive to Python, you can use this to display files containing other programming languages such as Ruby and Julia.
Overall, this is a great solution if you’re the only technical professional on the team, and you need to be able to easily and quickly distribute a Jupyter Notebook to your coworkers who may not have a learning environment installed. Unfortunately, you still can’t share files on private repositories.
So, next time you find yourself waiting 20+ seconds for a code file to render on GitHub, remember that nbviewer is here to make your life a bit easier!
Check if the String starts with specified prefix in Golang - GeeksforGeeks

26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix. It is defined under the strings package so, you have to import strings package in your program for accessing HasPrefix function.
Syntax:
func HasPrefix(str, pre string) bool
Here, str is the original string and pre is a string which represents the prefix. The return type of this function is of the bool type. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to check// the given string starts with the// specified prefixpackage main  import (    "fmt"    "strings")  // Main functionfunc main() {      // Creating and initializing strings    // Using shorthand declaration    s1 := "I am working as a Technical content writer in GeeksforGeeks!"    s2 := "I am currently writing articles on Go language!"      // Checking the given strings starts with the specified prefix    // Using HasPrefix() function    res1 := strings.HasPrefix(s1, "I")    res2 := strings.HasPrefix(s1, "My")    res3 := strings.HasPrefix(s2, "I")    res4 := strings.HasPrefix(s2, "We")    res5 := strings.HasPrefix("GeeksforGeeks", "Welcome")    res6 := strings.HasPrefix("Welcome to GeeksforGeeks", "Welcome")      // Displaying results    fmt.Println("Result 1: ", res1)    fmt.Println("Result 2: ", res2)    fmt.Println("Result 3: ", res3)    fmt.Println("Result 4: ", res4)    fmt.Println("Result 5: ", res5)    fmt.Println("Result 6: ", res6)}
Output:
Result 1:  true
Result 2:  false
Result 3:  true
Result 4:  false
Result 5:  false
Result 6:  true

Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
Interfaces in Golang
How to Trim a String in Golang?
How to Parse JSON in Golang?
Importing Data in Python

When running python programs, we need to use datasets for data analysis. Python has various modules which help us in importing the external data in various file formats to a python program. In this example we will see how to import data of various formats to a python program.
The csv module enables us to read each of the row in the file using a comma as a delimiter. We first open the file in read only mode and then assign the delimiter. Finally use a for loop to read each row from the csv file.
import csv

with open("E:\\customers.csv",'r') as custfile:
rows=csv.reader(custfile,delimiter=',')
for r in rows:
print(r)
Running the above code gives us the following result −
['customerID', 'gender', 'Contract', 'PaperlessBilling', 'Churn']
['7590-VHVEG', 'Female', 'Month-to-month', 'Yes', 'No']
['5575-GNVDE', 'Male', 'One year', 'No', 'No']
['3668-QPYBK', 'Male', 'Month-to-month', 'Yes', 'Yes']
['7795-CFOCW', 'Male', 'One year', 'No', 'No']
......
.......
The pandas library can actually handle most of the file types inclusing csv file. In this program let see how pandas library handles the excel file using the read_excel module. In the below example we read the excel version of the above file and get the same result when we read the file.
import pandas as pd

df = pd.ExcelFile("E:\\customers.xlsx")
data=df.parse("customers")
print(data.head(10))
Running the above code gives us the following result −
  customerID   gender Contract            PaperlessBilling Churn
0 7590-VHVEG Female   Month-to-month         Yes            No
1 5575-GNVDE   Male   One year                No            No
2 3668-QPYBK   Male   Month-to-month         Yes           Yes
3 7795-CFOCW   Male   One year                No            No
4 9237-HQITU Female   Month-to-month        Yes            Yes
5 9305-CDSKC Female   Month-to-month        Yes            Yes
6 1452-KIOVK   Male   Month-to-month        Yes             No
7 6713-OKOMC Female   Month-to-month         No             No
8 7892-POOKP Female   Month-to-month        Yes            Yes
9 6388-TABGU   Male   One year               No             No
We can also connect to database servers using a module called pyodbc. This will help us import data from relational sources using a sql query. Ofcourse we also have to define the connection details to the db before passing on the query.
import pyodbc
sql_conn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=sqldb;")
data_sql = pd.read_sql_query(SQL QUERY’, sql_conn)
data_sql.head()

Depending the SQL query the result will be displayed.
Polygon: Real-Time Stocks, Forex, and Crypto Data. | by Bernard Brenyah | Towards Data Science

You may have heard this quote “Data Is The New Oil” one too many times. Regardless of one’s opinion on this assertion, it is widely recognised that data is crucial to the innovative processes of every industry. The financial industry, in particular, is one industry where having access to quality and updated data is crucial given the highly dynamic nature of this industry. Recently, I had been working on a trading bot which requires real-time data (stocks, forex, and cryptocurrency data) and I happen to have settled on a really good platform called Polygon which delivered all that I needed in a nice, affordable and well-documented service.
The project I was working on required real-time cryptocurrency data over a period some period of time. After googling and asking around for various platforms, I ended up with Polygon. I found the service competitively priced, stable with excellent documentation. As a result of my positive experience with the platform, I decided to share my experience and code via this post for anyone who might be in the same boat.
Polygon offers streaming clients via WebSockets or RESTful APIs for accessing real-time data in most of the popular programming languages Python to Go. They even have a dedicated Python package for a more straight forward access. Since the project required Python, I opted for their Python package.
Enough talking, let us get right to business and start playing with some real-time cryptocurrency data after installing this python package:
pip install polygon-api-client
NB: This post will focus on cryptocurrencies for brevity’s sake but the code will include comments for readers who are interested in real-time stocks/equities, forex data. An API key is needed for access so head over to https://polygon.io/signup to get access to a key.
The goal of the project was to gather some realtime data on some selected cryptocurrencies over a specified period. In the relatively simple script below, I demonstrate how one can interact with live streaming data using the Python client of Polygon.
The script is designed with other types of assets supported by the platform in mind so it should be easy to adjust it for various use cases. The extensive and user-friendly documentation provided by the platform will be more than what one would need for every custom scenario.
In this short post, I have introduced Polygon as a viable and excellent platform for projects or products that require various classes of realtime financial data using their Python client. I recommend readers who are interested in such services to visit their documentation for both WebSockets and RESTful APIs and explore their vast offerings for cryptocurrency/stock/forex data. Until the next post, happy coding!
As always, I look forward to feedback (good or bad)! The code for this post, like with all other posts, is available on this GitHub repository.
How to read csv file with Pandas without header? - GeeksforGeeks

03 Mar, 2021
Prerequisites: Pandas
A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. This article discusses how we can read a csv file without header using pandas. To do this header attribute should be set to None while reading the file.
Syntax:
read_csv(“file name”, header=None)
Import module
Read file
Set header to None
Display data 
Let us first see how data is displayed with headers, to make difference crystal clear.
Data file used:
file.csv
sample.csv
Example1: 
Python3
# importing python packageimport pandas as pd  # read the contents of csv filedataset = pd.read_csv("file.csv")  # display the modified resultdisplay(dataset)
Output:
Now let us see the implementation without headers.
Example 2:
Python3
# importing python packageimport pandas as pd  # read the contents of csv filedataset = pd.read_csv("file.csv", header=None)  # display the modified resultdisplay(dataset)
Output:
Example 3:
Python3
# importing python packageimport pandas as pd  # read the content of csv filedataset = pd.read_csv("sample1.csv", header=None)  # display modified csv filedisplay(dataset)
Output:
Picked
Python pandas-io
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Writing a For Loop to Evaluate a Factorial - JavaScript

We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial using a for loop and returns the factorial.
For example −
factorial(5) = 120,
factorial(6) = 720
Maintain a count and a result variable, keep multiplying the count into result, simultaneously decreasing the count by 1, until it reaches 1
And then finally we return the result.
Following is the code −
const num = 14;
const factorial = num => {
   let res = 1;
   for(let i = num; i > 1; i--){
      res *= i;
   };
   return res;
};
console.log(factorial(num));
This will produce the following output in console −
87178291200
array_sum() function in PHP

The array_sum() function returns the sum of the values in an array. The returned value can be integer or float. It returns 0 if the array is empty.
array_sum(arr)
arr − the specified array
The array_sum() function returns the sum of values. The returned value can be integer or float. It returns 0 if the array is empty.
The following is an example −
 Live Demo
<?php
$arr = array(50, 100, 150, 300);
echo array_sum($arr);
?>
The following is the output −
600
Let us see another example −
 Live Demo
<?php
$arr = array("a"=>29.8,"b"=>66.4);
echo array_sum($arr);
?>
The following is the output −
96.2
What is the difference between = and == operators in Python?

In Python = symbol is defined as assignment operator. It requires one variable on its left and an expression on its right. Value of the expression on right is assigned to variable on left. Expression and name of variable are not interchangeable.
>>> a=10
>>> b=20
>>> c=a+b
>>> a,b,c
(10, 20, 30)
>>> a+b=c
SyntaxError: can't assign to operator
The == symbol is a comparison operator and called equal to operator. It returns true if operands on either side are equal, otherwise it returns false
>>> 10+2 == 10
False
>>> (10+2) == 12
True
>>> 'computer' == 'Computer'
False
>>> 'computer' == "computer"
True
Float parseFloat() method in Java with examples - GeeksforGeeks

26 Oct, 2018
The parseFloat() method in Float Class is a built in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float.
Syntax:
public static float parseFloat(String s)
Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.
Return type: It returns e float value represented by the string argument.
Exception: The function throws two exceptions which are described below:
NullPointerException– when the string parsed is null
NumberFormatException– when the string parsed does not contain a parsable float
Below is the implementation of the above method.
Program 1:
// Java Code to implement// parseFloat() method of Float class  class GFG {      // Driver method    public static void main(String[] args)    {        String str = "100";          // returns the float value        // represented by the string argument        float val = Float.parseFloat(str);          // prints the float value        System.out.println("Value = " + val);    }}
Value = 100.0

Program 2: To show NumberFormatException
// Java Code to implement// parseFloat() method of Float class  class GFG {      // Driver method    public static void main(String[] args)    {          try {            String str = "";              // returns the float value            // represented by the string argument            float val = Float.parseFloat(str);              // prints the float value            System.out.println("Value = " + val);        }          catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Exception: java.lang.NumberFormatException: empty String

Program 3: To show NullPointerException
// Java Code to implement// parseFloat() method of Float class  class GFG {      // Driver method    public static void main(String[] args)    {          try {              String str = null;              // returns the float value            // represented by the string argument            float val = Float.parseFloat(str);              // prints the float value            System.out.println("Value = " + val);        }          catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Exception: java.lang.NullPointerException

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#parseFloat(java.lang.String)
java-basics
Java-Float
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
How to copy from clipboard using tkinter without displaying a window

Let us suppose that in a particular application, we have to copy the content residing in the clipboard. We can access the clipboard using clipboard_get().
After copying the text from the clipboard, it will reside in the cache memory through
which we can debug the program and display the text in the frame, then we can
see the copied text from the clipboard.
First, we will create a window which will store the copied characters or text from the source using the get method. Once the execution is done, then we can hide the window by using the “withdraw” method in tkinter. It helps to get rid of the window.
#Import the tkinter library
from tkinter import *

#Create an instance of tkinter canvas by executing it
win = Tk()
win.geometry("600x200")

#Get the data from the clipboard
cliptext = win.clipboard_get()

#Create the label for the clipboard
lab=Label(win, text = cliptext)
lab.pack()

#Keep Running the window
win.mainloop()
Running the above code snippet will copy the content from the clipboard and display it in a window.
To avoid the window, we can use “withdraw” method,
from tkinter import *
win = Tk()
win.withdraw()
number = win.clipboard_get()
Extract unique values from an array - JavaScript

Suppose we have an array that contains duplicate elements like this −
const arr = [1,1,2,2,3,4,4,5];
We are required to write a JavaScript function that takes in one such array and returns a new array. The array should only contain the elements that only appear once in the original array.
Following is the code −
const arr = [1,1,2,2,3,4,4,5];
const extractUnique = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])){
         continue;
      };
      res.push(arr[i]);
   };
   return res;
};
console.log(extractUnique(arr));
This will produce the following output in console −
[ 3, 5 ]
How to do a sum of previous row value with the current row and display the result in another row with MySQL cross join?

Let us first create a table −
mysql> create table DemoTable(Value int);
Query OK, 0 rows affected (1.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(50);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 50    |
| 20    |
| 30    |
+-------+
3 rows in set (0.00 sec)
Here is the query to do a sum of previous rows in MySQL a sum of previous rows −
mysql> select t.Value,
   (@s := @s + t.Value) as Number
   from DemoTable t cross join
      (select @s := 0) p
   order by t.Value;
This will produce the following output −
+-------+--------+
| Value | Number |
+-------+--------+
| 20    | 20     |
| 30    | 50     |
| 50    | 100    |
+-------+--------+
3 rows in set (0.07 sec)
How to write an image file in internal storage in android?

This example demonstrates How to write an image file in internal storage in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<Button
android:id = "@+id/save"
android:text = "save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a button. When user click on button, It will store data in internal storage.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
   Button save;
   Bitmap bitmap;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Drawable drawable = getResources().getDrawable(R.drawable.mario);
      bitmap = ((BitmapDrawable) drawable).getBitmap();
      save = findViewById(R.id.save);
      save.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            File file = new File(directory, "UniqueFileName" + ".jpg");
            if (!file.exists()) {
               Log.d("path", file.toString());
               FileOutputStream fos = null;
               try {
                  fos = new FileOutputStream(file);
                  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                  fos.flush();
                  fos.close();
               } catch (java.io.IOException e) {
                  e.printStackTrace();
               }
            }
         }
      });
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -
In the above result, click on save button to store image in internal storage as shown below –
Click here to download the project code
remove null value from a String array in Java

Following program creates an array with null values. Convert it a list with not-null values only and then get the array of that list.
import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      String[] array = {"I", null, "love", null, "Java" };
      List<String> values = new ArrayList<String>();
      for(String data: array) {
         if(data != null) { 
            values.add(data);
         }
      }
      String[] target = values.toArray(new String[values.size()]);
      for(String data: target) {
         System.out.println(data + " ");
      }
   }
}
I
love
Java
Foundation - Switch

It is used to switch between on and off state.
The following example demonstrates the use of switch in Foundation −
<!doctype html>
   <head>
      <meta charset = "utf-8" />
      <meta http-equiv = "x-ua-compatible" content = "ie = edge" />
      <meta name = "viewport" content = "width = device-width, initial-scale = 1.0" />

      <title>Switch</title>

      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">

    <!-- Compressed JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>

   </head>

   <body>
      <h2>Switch Example</h2>

      <div class = "switch tiny">
         <input class = "switch-input" id = "switch_tiny" type = "checkbox">
         <label class = "switch-paddle" for = "switch_tiny"></label>
      </div>

      <div class = "switch small">
         <input class = "switch-input" id = "switch_small" type = "checkbox">
         <label class = "switch-paddle" for = "switch_small"></label>
      </div>

      <div class = "switch large">
         <input class = "switch-input" id = "switch_large" type = "checkbox">
         <label class = "switch-paddle" for = "switch_large"></label>
      </div>

      <script>
         $(document).ready(function() {
            $(document).foundation();
         })
      </script>
   </body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code switch.html file.
Save the above given html code switch.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.

    117 Lectures 
     5.5 hours 

 Shakthi Swaroop

    61 Lectures 
     1.5 hours 

 Hans Weemaes

    17 Lectures 
     4 hours 

 Stephen Kahuria

    8 Lectures 
     50 mins

 Zenva

    28 Lectures 
     2 hours 

 Sandra L

    16 Lectures 
     2.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2007 | Question 58 - GeeksforGeeks

28 Jun, 2021
Two processes, P1 and P2, need to access a critical section of code. Consider the following synchronization construct used by the processes:Here, wants1 and wants2 are shared variables, which are initialized to false. Which one of the following statements is TRUE about the above construct?v
  /* P1 */
while (true) {
  wants1 = true;
  while (wants2 == true);
  /* Critical
    Section */
  wants1=false;
}
/* Remainder section */       


/* P2 */
while (true) {
  wants2 = true;
  while (wants1==true);
  /* Critical
    Section */
  wants2 = false;
}
/* Remainder section */
(A) It does not ensure mutual exclusion.(B) It does not ensure bounded waiting.(C) It requires that processes enter the critical section in strict alternation.(D) It does not prevent deadlocks, but ensures mutual exclusion.Answer: (D)Explanation:Bounded waiting :There exists a bound, or limit, on the number of times other processes are allowed to enter their critical sections after a process has made request to enter its critical section and before that request is granted.
mutual exclusion prevents simultaneous access to a shared resource. This concept is used in concurrent programming with a critical section, a piece of code in which processes or threads access a shared resource.
Solution:
Two processes, P1 and P2, need to access a critical section of code. Here, wants1 and wants2 are shared variables, which are initialized to false.Now, when both wants1 and wants2 become true, both process p1 and p2 enter in while loop and waiting for each other to finish. This while loop run indefinitely which leads to deadlock.Now, Assume P1 is in critical section (it means wants1=true, wants2 can be anything, true or false). So this ensures that p2 won’t enter in critical section and vice versa. This satisfies the property of mutual exclusion.Here bounded waiting condition is also satisfied as there is a bound on the number of process which gets access to critical section after a process request access to it.
See question 3 of https://www.geeksforgeeks.org/operating-systems-set-13/
This solution is contributed by Nitika BansalQuiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
Can namespaces be nested in C++? - GeeksforGeeks

29 May, 2017
In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace. In the line “int z = x”, x refers to outer::x. If x would not have been in outer then this x would have referred to x in global namespace.
#include <iostream>  int x = 20;namespace outer {  int x = 10;           namespace inner {    int z = x; // this x refers to outer::x  }}  int main(){  std::cout<<outer::inner::z; //prints 10  getchar();  return 0;}
Output of the above program is 10.
On a side node, unlike C++ namespaces, Java packages are not hierarchical.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
namespaces
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Socket Programming in C/C++
Operator Overloading in C++
Bitwise Operators in C/C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Object Oriented Programming in C++