code-rag-bench/online-tutorials huggingface dataset:
How to prevent modification of object in JavaScript ?.

ECMAScript 5 has introduced several methods to prevent modification of object. Those preventive measures ensures that no one, accidentally or otherwise change functionality of object.
In this level, one cannot add any new properties or methods but can access existing properties or methods. Here there is an ability to delete the respective object. Object.preventExtensions() is the method used to accomplish this task. It prevents any new properties from ever being added to the object.
Live Demo
<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.preventExtensions(object1);
   delete object1.prop1 // value got deleted
   try {
      Object.defineProperty(object1, 'prop2', {
      value: 2
   });
   } catch (err) {
   document.write(err);
   }
   document.write("</br>");
   document.write(object1.prop1);
</script>
</body>
</html>
TypeError: Cannot define property prop2, object is not extensible
undefined // deleted so undefined
It is same as preventing extensions, in addition it doesn't allow to delete existing properties or methods. To accomplish this task Object.seal() method is used.
Live Demo
<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.seal(object1);
   object1.prop1 = 2;                 // value got changed
   delete object1.prop1;
   try {
      Object.defineProperty(object1, 'prop2', {
      value: 2
   });
   } catch (err) {
      document.write(err);
   }
   document.write("</br>");
   document.write(object1.prop1); // it gives value as 2 because of seal.
</script>
</body>
</html>
TypeError: Cannot define property prop2, object is not extensible
2  // because of seal the value can't be deleated but got updated
In addition to seal's functionality, freeze doesn't allow even to access the existing properties. To freeze an object we use Object.freeze() method. It can also make an object immutable.
Live Demo
<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.freeze(object1);
   object1.prop1 = 2;          //  value got updated
   delete object1.prop1;        // value got deleted
   try {
      Object.defineProperty(object1, 'prop2', {
      value: 2
   });
   } catch (err) {
      document.write(err);
   }
   document.write("</br>");
   document.write(object1.prop1);  // it gives 1 as output despite value updated to 2
</script>
</body>
</html>
TypeError: Cannot define property prop2, object is not extensible
1 // because of freeze the value won't get delete and won't get update.
How can I get the list of files in a directory using C/C++?

Standard C++ doesn't provide a way to do this. You could use the system command to initialize the ls command as follows −
#include<iostream>
int main () {
   char command[50] = "ls -l";
   system(command);
   return 0;
}
This will give the output −
-rwxrwxrwx 1 root root  9728 Feb 25 20:51 a.out
-rwxrwxrwx 1 root root   131 Feb 25 20:44 hello.cpp
-rwxrwxrwx 1 root root   243 Sep  7 13:09 hello.py
-rwxrwxrwx 1 root root 33198 Jan  7 11:42 hello.o
drwxrwxrwx 0 root root   512 Oct  1 21:40 hydeout
-rwxrwxrwx 1 root root    42 Oct 21 11:29 my_file.txt
-rwxrwxrwx 1 root root   527 Oct 21 11:29 watch.py
If you're on windows, you can use dir instead of ls to display the list.
You can use the direct package(https://github.com/tronkko/dirent) to use a much more flexible API. You can use it as follows to get a list of files −
#include <iostream>
#include <dirent.h>
#include <sys/types.h>

using namespace std;
void list_dir(const char *path) {
   struct dirent *entry;
   DIR *dir = opendir(path);
   
   if (dir == NULL) {
      return;
   }
   while ((entry = readdir(dir)) != NULL) {
   cout << entry->d_name << endl;
   }
   closedir(dir);
}
int main() {
   list_dir("/home/username/Documents");
}
This will give the output −
a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py
Tryit Editor v3.7

CSS Text Effects
Tryit: The word-break property
Sorting a VARCHAR column as FLOAT using the CAST operator isn’t working in MySQL ?

If your cast does not work, then you can use yourColumnName*1 with ORDER BY clause.
Using yourColumnName*1. The syntax is as follows:
SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY yourColumnName*1 DESC;
You can also use CAST() operator. The syntax is as follows:
SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY CAST(yourColumnName as DECIMAL(8,2)) DESC;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table VarcharColumnAsFloatDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Amount varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.01 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3446.23');
Query OK, 1 row affected (0.10 sec)
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('2464.46');
Query OK, 1 row affected (0.16 sec)
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.78');
Query OK, 1 row affected (0.13 sec)
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6464.98');
Query OK, 1 row affected (0.44 sec)
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('645.90');
Query OK, 1 row affected (0.19 sec)
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.99');
Query OK, 1 row affected (0.23 sec)
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3745.76');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from VarcharColumnAsFloatDemo;
The following is the output:
+----+---------+
| Id | Amount  |
+----+---------+
|  1 | 3446.23 |
|  2 | 2464.46 |
|  3 | 6465.78 |
|  4 | 6464.98 |
|  5 | 645.90  |
|  6 | 6465.99 |
|  7 | 3745.76 |
+----+---------+
7 rows in set (0.00 sec)
Here is the query to sort varchar as float using cast operator:
mysql> select Id,Amount from VarcharColumnAsFloatDemo order by cast(Amount as DECIMAL(8,2)) DESC;
The following is the output:
+----+---------+
| Id | Amount  |
+----+---------+
|  6 | 6465.99 |
|  3 | 6465.78 |
|  4 | 6464.98 |
|  7 | 3745.76 |
|  1 | 3446.23 |
|  2 | 2464.46 |
|  5 | 645.90  |
+----+---------+
7 rows in set (0.00 sec)
The second approach is as follows using yourColumnName*1:
mysql> select Id,Amount from VarcharColumnAsFloatDemo order by Amount*1 desc;
The following is the output:
+----+---------+
| Id | Amount  |
+----+---------+
|  6 | 6465.99 |
|  3 | 6465.78 |
|  4 | 6464.98 |
|  7 | 3745.76 |
|  1 | 3446.23 |
|  2 | 2464.46 |
|  5 | 645.90  |
+----+---------+
7 rows in set (0.00 sec)
Can we cast a double value to a byte in java?

Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects).
Converting one primitive data type into another is known as type casting. There are two types of casting −
Widening− Converting a lower datatype to a higher datatype is known as widening. It is done implicitly.
Narrowing− Converting a higher datatype to a lower datatype is known as narrowing. You need to do it explicitly using the cast operator (“( )”).
Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.
 Live Demo
import java.util.Scanner;
public class CastingExample {
   public static void main(String args[]){
      //Reading a double value form user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a double value: ");
      double d = sc.nextDouble();
      //Converting the double value to byte
      byte by = (byte) d;
      //Printing the result
      System.out.println("byte value: "+by);
   }
}
Enter a double value:
102.365
byte value: 102
How to handle the error “Text strings must be rendered within a <Text> component” in ReactNative?

While developing your app you can come across the error as stated above. Here is the
code that gives the error −
import React from "react";
import { Image , Text, View, StyleSheet } from "react-native";
export default class App extends React.Component {
   render() {
      return (
         <View style={styles.container}>
            <Image
               style={styles.stretch}
               source={{
                  uri:
               'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png ',
               }}
            />
         </View>
      );
   }
}
const styles = StyleSheet.create({
   container: {
      paddingTop: 50,
      paddingLeft: 50,
   },
   stretch: {
      width: 200,
      height: 200,
      resizeMode: 'stretch',
   },
});
The error displayed on the screen is as follows −
The error comes for the following reasons. Make sure you avoid those mistakes while
coding in your app.
The first cause for the error is because of bad indentation. It is very necessary that each
component is indented properly. The child elements are indented properly inside the
parent component.
The second case is because of spaces left at the end of each component. Remove the
spaces from the end of the screen and compile again. It will work fine. Please be careful
when copy pasting the code from another source. You will encounter this error mostly in
those cases.
Let us now correct the code and check the output again.
import React from "react";
import { Image , Text, View, StyleSheet } from "react-native";
export default class App extends React.Component {
   render() {
      return (
         <View style={styles.container}>
            <Image style={styles.stretch} source={{uri:
               'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png
         '}} />
         </View>
      );
   }
}
const styles = StyleSheet.create({
   container: {
      paddingTop: 50,
      paddingLeft: 50,
   },
   stretch: {
      width: 200,
      height: 200,
      resizeMode: 'stretch',
   }
});
How to check if a Python variable exists? - GeeksforGeeks

29 Dec, 2020
Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function.
To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table.
Example:Examples: Checking local variable existence
def func():      # defining local variable    a_variable = 0      # using locals() function     # for checking existence in symbol table    is_local_var = "a_variable" in locals()      # printing result    print(is_local_var)  # driver codefunc()
Output:
True

To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table.
Example:
Examples: Checking global variable existence
def func():      # defining variable    a_variable = 0      # using globals() function check     # if global variable exist    is_global_var = "a_variable" in globals()      # printing result    print(is_global_var)  # driver codefunc()
Output:
False

Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
PyQt5 – Set minimum window size | setMinimumWidth and setMinimumHeight method - GeeksforGeeks

26 Mar, 2020
When we create a window, by default the window size is resizable although, we can use setMinimumSize() method to set the minimum size of the window. But what if we want to set minimum length only for width or height only, in order to do so we use setMinimumWidth() method to set minimum width and setMinimumHeight() method to set minimum height. When we use these method other length will be variable i.e there will be no minimum length to it, it can shrinks as much it can.
Syntax :
self.setMinimumWidth(width)
self.setMinimumHeight(height)

Argument : Both takes integer as argument.
Action performed.setMinimumWidth() sets the minimum width.setMinimumHeight() sets the minimum height.
Code for setting minimum width :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          width = 200        height = 200          # setting the minimum width        self.setMinimumWidth(width)          # creating a label widget        self.label_1 = QLabel("Minimum width", self)          # moving position        self.label_1.move(0, 0)          # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # resizing label        self.label_1.resize(120, 80)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
 Code for setting minimum width :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          width = 200        height = 200          # setting the minimum width        self.setMinimumHeight(height)          # creating a label widget        self.label_1 = QLabel("Minimum height", self)          # moving position        self.label_1.move(0, 0)          # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # resizing label        self.label_1.resize(120, 80)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How do I get the parent directory in Python?

In Python 3.4+ you can use the pathlib module to get the parent directory.
from pathlib import Path
print(Path('/home/username').parent)
This will give the output:
/home
In older versions, you can call the os.path.join on your path and '..'(represents parent directory) and then find its absolute path using os.path.abspath.
import os
print(os.path.abspath(os.path.join('/home/username', '..')))
This will give the output:
/home
Difference between Thread and Runnable in Java

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of the Thread class. This subclass should override the run method of the Thread class. An instance of the subclass can then be allocated and started.
The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.
Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
class RunnableExample implements Runnable{
   public void run(){
      System.out.println("Thread is running for Runnable Implementation");
   }
   public static void main(String args[]){
      RunnableExample runnable=new RunnableExample();
      Thread t1 =new Thread(runnable);
      t1.start();
   }
}
class ThreadExample extends Thread{
   public void run(){
      System.out.println("Thread is running");
   }
   public static void main(String args[]){
      ThreadExample t1=new ThreadExample ();
      t1.start();
   }
}
A new plot theme for Matplotlib — Gadfly | by Jonny Brooks-Bartlett | Towards Data Science

I’ve made a plotting theme for Matplotlib that’s inspired by the default plotting theme used in Gadfly for the Julia programming language. Typically I’d just write the code in Julia, which is what I’ve done for many of my previous blog posts. However, since upgrading to Julia v1.0, I’ve been unable to import Gadfly, which means no more pretty Gadfly plots. So I said to myself “Jonny, it’s time to just create the theme yourself”. And I did!
(If you want to find out how to use this theme then skip to the last section)
When plotting using the Seaborn, the default aesthetics change a little. I haven’t worked out how to change this exactly but I’m not too fussed about it. For example, boxplots are very different (see below)
When plotting withsns.lmplot the legend is plotted outside of the axes and does not have a border (below). It also draw the left and bottom spines by default too.
This theme isn’t installed in the set of themes that come with matplotlib. Therefore, if you want to use the theme you have a few options. I’ll list a couple of the options here but you can learn about all of the ways by reading the matplotlib documentation on Customizing Matplotlib with style sheets and rcParams.
Copy the matplotlibrc style sheet contents at the end of this blog post and save it in the same directory as the script from which you want to do your plotting. Save it under the name matplotlibrc . Then it should just work.
Again, copy the matplotlibrc style sheet contents at the end of this blog post but this time save as in mpl_configdir/stylelib as <style-name>.mplstyle. You can find out where mpl_configdir is with matplotlib.get_configdir(). I had to create the stylelib directory because it wasn’t already in the mpl_configdir directory.
Once you’ve saved the file in the right directory you can then set the theme with
import matplotlib.pyplot as pltplt.style.use(<style-name>)
So I saved the file as gadfly.mplstyle and I can set the theme with plt.style.use('gadfly')
Python | Pandas Series.dt.date - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.date attribute return a numpy array of python datetime.date objects.
Syntax: Series.dt.date
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.date attribute to return the date property of the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',               '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.date attribute to return the date property of the underlying data of the given Series object.
# return the dateresult = sr.dt.date  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.date attribute has successfully accessed and returned the date property of the underlying data in the given series object. Example #2 : Use Series.dt.date attribute to return the date property of the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                        periods = 5, freq = 'H'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.date attribute to return the date property of the underlying data of the given Series object.
# return the dateresult = sr.dt.date  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.date attribute has successfully accessed and returned the date property of the underlying data in the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
sum() function in Python
MongoDB - $slice Modifier - GeeksforGeeks

10 May, 2020
MongoDB provides different types of array update operators to update the values of the array fields in the documents and $slice modifier is one of them. This modifier is used to limit the number of array items during a $push operation.
Syntax:
{
  $push: {
     <field>: {
       $each: [ <value1>, <value2>, ... ],
       $slice: <number>
     }
  }
}
If the value of number is zero, then this modifier will update the array field to an empty array.
If the value of number is negative, then this modifier will update the array field to contain only the last number items.
If the value of number is positive, then this modifier will update the array field to contain only the first number items.
$slice modifier must appear with $each modifier in the $push operator. You are allowed to pass an empty array in the $each modifier which help $slice modifier to show its effect. If you use the $slice modifier without $each modifier, then you will get an error.
The order in which the modifiers appear in $push operation is immaterial.
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs.
In this example, we are adding new items in the language field and then use $slice modifier to trim the array to the last four items.
db.contributor.update({name: "Suman"},                      {$push: {language: { $each: ["SQL", "JS++"],                        $slice: -4}}})
In this example, we are adding new items in the language field and then use $slice modifier to trim the array to the first five items.
db.contributor.update({name: "Rohit"},                       {$push: {language: { $each: ["R Language", "JS++"],                       $slice: 5}}})
In this example, we are updating the array of the language field by triming the array to the last three items.
db.contributor.update({name: "Rohit"},                      {$push: {language: { $each: [],                         $slice: -3}}})
In this example, we are using the $slice modifier with other modifiers like $each and $sort with $push operator.
db.contributor.update({name: "Rohit"},                      {$push: { language: { $each: ["C++", "Kotlin"],                        $sort: 1, $slice: 4}}})
Here,
The $each modifier is used to add multiple documents to the language array.
The $sort modifier is used to sort all the items of the modified language array in ascending.
The $slice modifier is used to keep only the first four sorted items of the language array.
MongoDB
MongoDB-modifier
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB - Update() Method
MongoDB Cursor
MongoDB updateMany() Method - db.Collection.updateMany()
Python | Numpy matrix.std() - GeeksforGeeks

20 May, 2019
With the help of matrix.std() method, we are able to find the standard deviation a matrix by using the same method.
Syntax : matrix.std()Return : Return standard deviation of a matrix
Example #1 :In this example we are able to find the standard deviation of a matrix by using matrix.std() method.
# import the important module in pythonimport numpy as np             # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]')             # applying matrix.std() methodgeek = gfg.std()   print(geek)
4.18330013267

Example #2 :
# import the important module in pythonimport numpy as np             # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')             # applying matrix.std() methodgeek = gfg.std()   print(geek)
3.3993463424

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
HTML | <option> label Attribute - GeeksforGeeks

07 Aug, 2019
The HTML option label Attribute is used to specify the text value which represents the shorted label for option. The shortest version will be displayed in the drop-down list.
Syntax:
<option label="text">
Attribute Values: It contains single value text which specify the shorter version for an option.
Below example illustrates the use of label attribute for an option element.Example:
<!DOCTYPE html> <html>   <head>     <title>        HTML option label attribute    </title>           <style>         body {             text-align:center;         }         h1 {             color:green;         }     </style> </head>   <body>     <h1>GeeksforGeeks</h1>           <h2>HTML option label Attribute</h2>           <select>         <option>Choose an option</option>         <option label="HTML">HTML Language</option>         <option label="JAVA">JAVA Programming</option>         <option label="C++">C++ Programming</option>         <option label="PHP">PHP Programming</option>         <option label="PERL">PERL Programming</option>     </select> </body>   </html>             
Output:
Supported Browsers: The browsers supported by HTML <option> label attribute are listed below:
Google Chrome
Internet Explorer 8.0
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Pandas.set_option() function in Python - GeeksforGeeks

28 Jul, 2020
Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to set the value of a specified option.
Syntax : pandas.set_option(pat, value)
Parameters :
pat : Regexp which should match a single option.
value : New value of option.
Returns : NoneRaises : OptionError if no such option exists
Example 1 : Changing the number of rows to be displayed using display.max_rows.
# importing the moduleimport pandas as pd  # creating the DataFramedata = {"Number" : [0, 1, 2, 3, 4,                     5, 6, 7, 8, 9],        "Alphabet" : ['A', 'B', 'C', 'D', 'E',                       'F', 'G', 'H', 'I', 'J']}df = pd.DataFrame(data)  print("Initial max_rows value : " +       str(pd.options.display.max_rows))  # displaying the DataFramedisplay(df)  # changing the max_rows valuepd.set_option("display.max_rows", 5)  print("max_rows value after the change : " +       str(pd.options.display.max_rows))  # displaying the DataFramedisplay(df)
Output :
Example 2 : Changing the number of columns to be displayed using display.max_columns.
# importing the moduleimport pandas as pd  # creating the DataFramedata = {"Number" : 1,        "Name" : ["ABC"],        "Subject" : ["Computer"],        "Field" : ["BDA"],        "Marks" : 70}df = pd.DataFrame(data)  print("Initial max_columns value : " +       str(pd.options.display.max_columns))  # displaying the DataFramedisplay(df)  # changing the max_columns valuepd.set_option("display.max_columns", 3)  print("max_columns value after the change : " +       str(pd.options.display.max_columns))  # displaying the DataFramedisplay(df)
Output :
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Implementing Non-contiguous Memory Management Techniques - GeeksforGeeks

14 Apr, 2020
Memory Management Techniques are basic techniques that are used in managing the memory in operating system. Memory Management Techniques are basically classified into two categories:
(i) Contiguous
(ii) Non-contiguous 
We have already discussed the implementation of contiguous in the article Implementation of Contiguous Memory Management Techniques. Here we will discuss the implementation of non-contiguous memory management techniques.
Non-contiguous Memory Management Techniques:In this technique, memory is allotted in a non-continuous way to the processes. It has five types:
Paging:Paging is a non-contiguous memory management technique that permits the physical address space of a process to be non–contiguous. Whenever the process is created paging will be applied on the process and page table will be created. Paging is related with respect to every process and every process will have its own page table.
There is no external fragmentation in the paging. The internal fragmentation exists in the last page and internal fragmentation in paging is considered as P/2 where P is the page size.
Multilevel Paging:Multilevel Paging is a non-contiguous memory management technique which contains two or more levels of page tables in a hierarchical manner.In the multilevel paging when the paging is applied on the page tables, the last page is called the first level page table. In multilevel paging, when the paging is applied on the page tables then all the page table will be stored in main memory.
Inverted Paging:To avoid the overhead of maintaining page table process, the concept of Inverted Paging is implemented. In the inverted paging only one page table will be maintained for all the processes. The memory required to maintain the page tables of the processes will be less but searching time for corresponding page of a process will be more.
Segmentation:Segmentation is a non-contiguous memory management technique in which the memory is divided into segments. Each process is allotted a segment. There are two types of segmentation:
(i) Simple
(ii) Virtual 
Segmented Paging:To avoid the overhead of bringing large size segment into memory the concept of segmented paging is implemented. IN the segmented paging, paging will be applied on the segment and instead of bringing the entire segment into memory, the pages of segment will be brought into memory. The number of entries in the page table of segment is same as the number of pages on the segment.
Page size of segment is same as frame size of physical address space.
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Introduction of Process Synchronization
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Introduction of Deadlock in Operating System
Program for Round Robin scheduling | Set 1
Python Program to Compute Life Path Number - GeeksforGeeks

24 Jan, 2021
Given a String of date of format YYYYMMDD, our task is to compute the life path number.  Life Path Number is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions.
Examples:
Input : test_str = “19970314”
Output : 7
Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 3 = 3 [ month ] ; 1 + 4 = 5 [ day ]. 5 + 3 + 8 = 16 ; 1 + 6 = 7.
Input : test_str = “19970104”
Output : 4
Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 1 = 1 [ month ] ; 0 + 4 = 4 [ day ]. 4 + 1 + 8 = 13 ; 1 + 3 = 4.
Method 1: Using loop
The logic behind computing this is getting a summation of each digit and perform %10 at each step. This way result curlers to single digit if it goes to double-digit. 
Python3
# Python3 code to demonstrate working of# Life Path Number# Using loop  # initializing stringtest_str = "19970314"  # printing original stringprint("The original string is : " + str(test_str))  res = 0for num in test_str:    res += int(num)          # modulation in case of 2 digit number    if res > 9:        res = res % 10 + res // 10  # printing resultprint("Life Path Number  : " + str(res))
Output:
The original string is : 19970314
Life Path Number  : 7
Method 2: Using recursion
Similar way as above, the difference being the recursive function is used for repeated modulation in case of digit count greater than 1.
Python3
# Python3 code to demonstrate working of# Life Path Number# Using recursion  # initializing stringtest_str = "19970314"  # printing original stringprint("The original string is : " + str(test_str))  # recursion function definitiondef lpn(num): return num if num < 10 else lpn(num // 10 + num % 10)  # recursive function initial callres = lpn(int(test_str))  # printing resultprint("Life Path Number  : " + str(res))
Output:
The original string is : 19970314
Life Path Number  : 7
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
wxPython - Change Button Label Font - GeeksforGeeks

06 Jan, 2022
In this article we are going to learn that how can we change the font of the label text present on the button present in the frame. We need to follow some steps as follows: 
Step 1: Create a wx.Font object. Step 2: Add different attributes of font in parameters like: family, style etc. Step 3: Set font by using SetFont() function. 
 
Syntax: wx.Button.SetFont(self, font)Parameters:  
 
Code Example:  
Python3
import wx  class Example(wx.Frame):     def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)        self.InitUI()     def InitUI(self):        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)        self.pnl = wx.Panel(self)        # wx.Font object initialization        font = wx.Font(12, wx.FONTFAMILY_MODERN, 0, 90, underline = False,     faceName ="")                 # CREATE BUTTON AT POINT (20, 20)        self.st = wx.Button(self.pnl, id = 1, label ="Button", pos =(20, 20),                                size = wx.DefaultSize,  name ="button")        # SET FONT FOR LABEL        self.st.SetFont(font)        self.SetSize((350, 250))        self.SetTitle('wx.Button')        self.Centre() def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()  if __name__ == '__main__':    main()
Output Window:  
 
gulshankumarar231
Python wxPython-Button
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to apply multiple CSS properties using jQuery?

Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call.
Here is the syntax for the method −
selector.css( {key1:val1, key2:val2....keyN:valN})
Here you can pass key as property and val as its value as described above.
You can try to run the following code to learn how to apply multiple CSS properties using jQuery:
Live Demo
<html>
   <head>
      <title>jQuery CSS</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {
            $("li").eq(2).css({"color":"red", "background-color":"green"});
         });
      </script>
   </head>
   <body>
      <div>
         <ul>
            <li>list item 1</li>
            <li>list item 2</li>
            <li>list item 3</li>
            <li>list item 4</li>
            <li>list item 5</li>
            <li>list item 6</li>
         </ul>
      </div>    
   </body>
</html>
How can I select an element by tag name using jQuery?

Using jQuery selector, you can select an element by tag name. The jQuery element selector selects elements.
Try to run the following code to learn how to select an element by tag name using jQuery −
Live Demo
<html>

   <head>
      <title>jQuery Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {
            $("div").css("background-color", "yellow");
         });
      </script>
   </head>
   
   <body>

      <div class = "big" id = "div1">
         <p>This is first division of the DOM.</p>
      </div>

      <div class = "medium" id = "div2">
         <p>This is second division of the DOM.</p>
      </div>

      <div class = "small" id = "div3">
         <p>This is third division of the DOM</p>
      </div>

   </body>
   
</html>
Fix MySQL Database Error #1064?

The Database Error #1064 may occur due to incorrect syntax. For example, let’s say we are creating the below table −
mysql> create table DemoTable
   (
      UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
      UserName varchar(100),
      UserAge int,
      UserAddress varchar(200),
      UserCountryName varchar(100) ,
      isMarried boolean,
   );
This will produce the following output i.e. error −
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 10
To get rid of the above error, you need to remove last comma(,). The query is as follows to remove the error −
mysql> create table DemoTable
   (
      UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
      UserName varchar(100),
      UserAge int,
      UserAddress varchar(200),
      UserCountryName varchar(100),
      isMarried boolean
   );
Query OK, 0 rows affected (1.04 sec)
PHP | utf8_encode() Function - GeeksforGeeks

30 Sep, 2019
The utf8_encode() function is an inbuilt function in PHP which is used to encode an ISO-8859-1 string to UTF-8. Unicode has been developed to describe all possible characters of all languages and includes a lot of symbols with one unique number for each symbol/character. UTF-8 has been used to transfer the Unicode character from one computer to another. It is not always possible to transfer a Unicode character to another computer reliably.
Syntax:
string utf8_encode( string $string )
Parameters: This function accepts single parameter $string which is required. It specifies the ISO-8859-1 string which need to be encoded.
Return Value: This function returns a string representing the encoded string on success or False on failure.
Note: This function is available for PHP 4.0.0 and newer version.
Example 1:
<?php  // String to encode$string_to_encode = "\x63";  // Encoding stringecho utf8_encode($string_to_encode);  ?>
Output:
c

Example 2:
<?php  // Creating an array of 256 elements$text = array(    "\x20", "\x21", "\x22", "\x23", "\x24", "\x25",    "\x26", "\x27", "\x28", "\x29", "\x2a", "\x2b",    "\x2c", "\x2d", "\x2e", "\x2f", "\x30", "\x31",     "\x32", "\x33", "\x34", "\x35", "\x36", "\x37", );  // Encoding all charactersforeach( $text as $index ) {    echo utf8_encode($index) . " "; }  ?>
Output:
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7
Reference: https://www.php.net/manual/en/function.utf8-encode.php
PHP-function
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Python | os.truncate() method - GeeksforGeeks

25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.truncate() method truncates the file corresponding to path so that it is at most length bytes in size. This function can support file descriptor too.
Syntax: os.truncate(path, length)
Parameters:path: This parameter is the path or file descriptor of the file that is to be truncated.length: This is the length of the file upto which file is to be truncated.
Return Value: This method does not returns any value.
Example #1 :
Using os.truncate() method to truncate a file using it’s path.
# Python program to explain os.truncate() method         # importing os module import os     # path path = 'C:/Users/Rajnish/Desktop/testfile.txt'  # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR|os.O_CREAT)  # String to be writtens = 'GeeksforGeeks - A Computer Science portal'  # Convert the string to bytes line = str.encode(s)  # Write the bytestring to the file # associated with the file # descriptor fd os.write(fd, line)  # Using os.truncate() method# Using path as parameteros.truncate(path, 10)  # Seek the file from beginning# using os.lseek() methodos.lseek(fd, 0, 0)  # Read the files = os.read(fd, 15)  # Print stringprint(s)  # Close the file descriptor os.close(fd)
b'GeeksforGe'

Example #2 :Using os.truncate() method to truncate a file using a file descriptor
# Python program to explain os.truncate() method         # importing os module import os     # path path = 'C:/Users/Rajnish/Desktop/testfile.txt'  # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR|os.O_CREAT)  # String to be writtens = 'GeeksforGeeks'  # Convert the string to bytes line = str.encode(s)  # Write the bytestring to the file # associated with the file # descriptor fd os.write(fd, line)  # Using os.truncate() method# Using fd as parameteros.truncate(fd, 4)  # Seek the file from beginning# using os.lseek() methodos.lseek(fd, 0, 0)  # Read the files = os.read(fd, 15)  # Print stringprint(s)  # Close the file descriptor os.close(fd)
b'Geek'

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to save a histogram plot in Python?

To save a histogram plot in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create data points "k" for the histogram.
Plot the histogram using hist() method.
To save the histogram, use plt.savefig('image_name').
To display the figure, use show() method.
import matplotlib.pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Data points for the histogram
k = [1, 3, 2, 5, 4, 7, 5, 1, 0, 4, 1]

# Plot the histogram
plt.hist(k)

# Save the histogram
plt.savefig('hist.png')

# Display the plot
plt.show()
It will save the following plot as 'hist.png' in the project directory.
How to Create a Correlation Matrix using Pandas?

08 Oct, 2021
Correlation is a statistical technique that shows how two variables are related. Pandas dataframe.corr() method is used for creating the correlation matrix. It is used to find the pairwise correlation of all columns in the dataframe. Any na values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored.To create correlation matrix using pandas, these steps should be taken:  
Obtain the data.Create the DataFrame using Pandas.Create correlation matrix using Pandas
Obtain the data.
Create the DataFrame using Pandas.
Create correlation matrix using Pandas
Example 1:  
Python3
# import pandasimport pandas as pd # obtaining the datadata = {'A': [45, 37, 42],        'B': [38, 31, 26],        'C': [10, 15, 17]        }# creation of DataFramedf = pd.DataFrame(data) # creation of correlation matrixcorrM = df.corr() corrM
Output: 
 
Values at the diagonal shows the correlation of a variable with itself, hence diagonal shows the correlation 1.
Example 2:  
Python3
import pandas as pd data = {'A': [45, 37, 42, 50],        'B': [38, 31, 26, 90],        'C': [10, 15, 17, 100],        'D': [60, 99, 23, 56],        'E': [76, 98, 78, 90]        } df = pd.DataFrame(data) corrM = df.corr()corrM
Output:  
Example 3:  
Python3
import pandas as pd # Integer and string values can# never be correlated.data = {'A': [45, 37, 42, 50],        'B': ['R', 'O', 'M', 'Y'],        } df = pd.DataFrame(data) corrM = df.corr()corrM
Output:  
Example 4:  
Python3
import pandas as pd data = {'A': [45, 37, 42, 50],        'B': ['R', 'O', 'M', 'Y'],        'C': [56, 67, 68, 60],                       } df = pd.DataFrame(data) corrM = df.corr()corrM
Output:  
 
sagar0719kumar
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.