code-rag-bench/online-tutorials huggingface dataset:
How to load large Objects in Python Classes efficiently. | Towards Data Science

Thanks to open-sourced machine learning frameworks, everybody can integrate powerful (and large) models into data pipelines. The opportunity to do this creates challenges that most data scientists are not equipped to deal with. This blog post addresses one of these: how do you build your code in a way that integrates state-of-the-art models without overloading the computational system?
Here is a concrete example. Image your job is to build a Python pipeline that processes product reviews. The goal is to detect phony reviews that try to pull down your products’ score. You decide to do this in a multi-step approach:
First, you check whether there are new reviews available.
Second, you check whether their rating is low enough to justify further investigation.
Third, a machine learning pipeline checks the texts that pass both checks to a machine learning pipeline by calculating embeddings and applying a classification model.
This process runs daily for all products. Here is our initial version of the ReviewClassifier class:
As you can see from the output, each instance of the classifier reloads the complicated model. Let’s assume that loading a model takes about one minute each time. If 100 products have suspicious reviews each day, that is already 100 minutes of loading time! And that is on top of everything your pipeline needs to do.
To improve on that — and save 99% of the loading time — we need to move the loading from the instance to the class level. Here is our next version:
That is way better, but we can improve it further. Currently, the classifier loads the model immediately when you import the class:
from review_pipeline import ReviewClassifier# Loaded: A Complicated Model
We don’t want this premature loading. Maybe we don’t need the model at all. It also messes up unit-tests very fast.
To change that, we check whether the model is loaded on the class level when we calculate the embeddings and do it if not. Here is our final version:
Now we have achieved what we set out to do. The model is loaded when it is necessary for the first time and consequently available for further uses.
Once you are aware of this pattern, you will discover many useful applications. For instance, there are situations where a single database export with subsequent local filtering better fits your infrastructure than repeated small queries. The same can be true for large pre-calculations.
Although it is a crafty pattern, some alternatives are better suited for some use cases. If you apply the design above, the class objects will remain in memory, which can lead to problems that are hard to detect. In these cases, it might be preferable to create a local copy (once) and reload the object from the file system for each new class instance.
Let me know in the comments or on Twitter if this post helped you or if you want to add something. I’m also happy to connect on LinkedIn. Thanks for reading!
How Do You Define Bandwidth and Throughput in Wireless Communications?

A wireless communication link is specified or characterized in terms of some performance metrics. We call these performance metrics as 'Quality of Service' (QoS) metrics or parameters. Some of the major QoS parameters include bandwidth, throughput, jitter, latency and bit error rate.
Bandwidth is a popular term used in the context of both networking and communications. In networking, the bandwidth is specified using bps (bits per second), kbps (kilobits per second), Mbps (Megabits per second) and so on.
In communications, bandwidth is measured in the unit kHz (kilo Hertz), MHz (Mega Hertz), GHz (Giga Hertz) and so on. Throughput is also a quality-of-service parameter and is specified in the same units as bandwidth.
Bandwidth refers to a range of frequencies. It is the difference between the highest and lowest frequencies present in the considered frequency range. When the difference between these two frequencies is large, the bandwidth of the system is also large.
Bandwidth refers to a range of frequencies
Throughput refers to the amount of data flowing down a network at any given unit of time. While bandwidth specifies the net achievable link speed, throughput is the actual link speed as seen in real time scenarios.
In practice, throughput is less than the bandwidth. In the best case, throughput is equal o the bandwidth.
Let us understand the concept of bandwidth with an example of box. Suppose you have a 4''x 4'' x 4'' box that can roughly accommodate 12 tennis balls. If you want to accommodate seven more balls to make the count 19, you may have to use a bigger box. A bigger box implies more balls can be accommodated. Balls in this context can be mapped to the subscribers and the box to the bandwidth.
Having a wider bandwidth enables more users/subscribers to access the network at the same time with lesser traffic or congestion than with lower bandwidth.
Box = Bandwidth, Balls = Users/Subscribers
Let us look at another example of door. Let there be a door that lets only two people to get through at any given point of time. When we replace the narrow door with a wider one, more number of people can pass through. This 'pass-through percentage' is termed 'throughput'.
Pass-through percentage = Throughput
At any given point of time, the wider door offers more throughput than the narrower one. The wider door has offered more bandwidth than the narrower one.
Throughput ≤ Bandwidth
Wide door = More bandwidth Narrow door = Less bandwidth
If the bandwidth of the system is 1 Mbps and at 500 kilobits flow down the network per second, we can say that the throughput is 50% of bandwidth.
Explain the concept of pointers in C language

The pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
Pointer saves the memory space.
The execution time of a pointer is faster because it directly accesses to memory location.
The execution time of a pointer is faster because it directly accesses to memory location.
The memory is accessed efficiently with the help of a pointer.
The memory is accessed efficiently with the help of a pointer.
Memory is allocated and deallocated dynamically.
Memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Pointers are used with data structures.
The syntax for the pointer is as follows −
pointer = &variable;
Following is the C program for the pointer −
 Live Demo
#include <stdio.h>
int main(){
   int x=40; //variable declaration
   int *p; //pointer variable declaration
   p=&x; //store address of variable x in pointer p
   printf("address in variable p is:%d\n",p); //accessing the address
   printf("value in variable p is:%d\n",*p); //accessing the value
   return 0;
}
When the above program is executed, it produces the following result −
Address in variable p is:5ff678
Value in variable p is:40
Operator * serves two purposes which are as follows −
Declaration of a pointer.
Declaration of a pointer.
Returns the value of the referenced variable.
Returns the value of the referenced variable.
Operator &  serves only one purpose, which is as follows −
Returns the address of a variable.
Returns the address of a variable.
Display the alternate rows from MySQL table

Theory of Computation
To display alternate records from MYSQL table, suppose we have the following records -
CREATE TABLE IF NOT EXISTS `empdata` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(25) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `empdata` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Anjali', 'anjali@example.com', 878433948),
(2, 'Priska', 'priska@example.com', 493905490),
(3, 'Abhi', 'abhi@example.com', 403022139),
(4, 'Joya', 'joya@example.com', 342345329),
(5, 'Ammy', 'ammy@example.com', 239848342),
(6, 'Lussi', 'lussi@example.com', 490290331);
These are the methods that you can use to get alternate or ODD-EVEN records from a MySQL table -
MySQL MOD() method returns the remainder of a number divided by another number. So for getting alternate rows, we can divide the ID with 2 and displays only those having remainder 1.
SELECT * FROM empdata GROUP BY id having mod(id,2)=1;
Output of the above statement
+----+--------+--------------------+-----------+
| id | name   | email              | phone     |
+----+--------+--------------------+-----------+
|  1 | Anjali | anjali@example.com | 878433948 |
|  3 | Abhi   | abhi@example.com   | 403022139 |
|  5 | Ammy   | ammy@example.com   | 239848342 |
+----+--------+--------------------+-----------+
The above statement returns only ODD rows. If you want to get even rows, write the statement as-
SELECT * FROM empdata GROUP BY id having mod(id,2)=0;
Output of the above statement
+----+--------+--------------------+-----------+
| id | name   | email              | phone     |
+----+--------+--------------------+-----------+
|  2 | Priska | priska@example.com | 493905490 |
|  4 | Joya   | joya@example.com   | 342345329 |
|  6 | Lussi  | lussi@example.com  | 490290331 |
+----+--------+--------------------+-----------+
We can also use the modulus operator instead of mod() method, like- the given statement returns only even rows-
SELECT * FROM empdata
WHERE id IN(SELECT id FROM empdata WHERE id%2 = 0);
Output of the above statement
+----+--------+--------------------+-----------+
| id | name   | email              | phone     |
+----+--------+--------------------+-----------+
|  2 | Priska | priska@example.com | 493905490 |
|  4 | Joya   | joya@example.com   | 342345329 |
|  6 | Lussi  | lussi@example.com  | 490290331 |
+----+--------+--------------------+-----------+
similarly, the following statement returns only odd rows-
SELECT * FROM empdata
WHERE id IN(SELECT id FROM empdata WHERE id%2 = 1);
Output of the above statement
+----+--------+--------------------+-----------+
| id | name   | email              | phone     |
+----+--------+--------------------+-----------+
|  1 | Anjali | anjali@example.com | 878433948 |
|  3 | Abhi   | abhi@example.com   | 403022139 |
|  5 | Ammy   | ammy@example.com   | 239848342 |
Lex program for Decimal to Hexadecimal Conversion - GeeksforGeeks

30 Apr, 2019
Problem: Write a Lex program for Decimal to Hexadecimal conversion.
Explanation:Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Prerequisite: Flex (Fast lexical Analyzer Generator)
Examples:
Input: 12 
Output: C

Input: 116
Output: 74

Input: 55
Output: 37

Input: 212
Output: D4 
Implementation:
/* Lex program for decimal to hexadecimal conversion */  %{    /* Definition section */    #include<stdio.h>    int num, r, digit=0, count, pcount=0, i;    char a[20];%}  DIGIT [0-9]/* Rule Section */%%  {DIGIT}+ { num=atoi(yytext);          while(num!=0)        {              r=num%16;            digit='0'+r;            if(digit>'9')            digit+=7;            a[count++]=digit;            num=num/16;          }          for(i=count-1;i>=pcount;--i)                printf("%c", a[i]);                pcount=count;        }  .|\n    ECHO;         %%  // driver codeint main(){    yylex();    return 0;}      
Output:
Lex program
C Programs
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
C program to find the length of a string
Phases of a Compiler
Code Optimization in Compiler Design
Intermediate Code Generation in Compiler Design
Three address code in Compiler
Construction of LL(1) Parsing Table
C++ Program to Implement Queue

The queue which is implemented as FIFO where insertions are done at one end (rear) and deletions are done from another end (front). The first element that entered is deleted first.
Queue operations are −
EnQueue (int data) − Insertion at rear end
int DeQueue()− Deletion from front end
This is a C++ program to implement queue using array.
Begin
   function Enqueue() to insert elements in queue:
      If queue is completely filled up then print “Overflow”.
      Otherwise insert element at rear.
      Update the value of rear
End
Begin
   function Dequeue() to delete elements from queue:
      If queue is completely empty then print “Underflow”.
      Otherwise insert element from the front.
      Update the value of rear.
End
#include <bits/stdc++.h>
using namespace std;
struct Q {
   int f, r, capacity;
   int* q;
   Q(int c) {
      f = r= 0;
      capacity = c;
      q = new int;
   }
   ~Q() { delete[] q; }
   void Enqueue(int d) {
      if (capacity == r) { //check if queue is empty or not
         printf("\nQueue is full\n");
         return;
      } else {
         q[r] = d; //insert data
         r++; //update rear
      }
      return;
   }
   void Dequeue() {
      if (f == r) {
         printf("\nQueue is empty\n");
         return;
      } else {
         for (int i = 0; i < r - 1; i++) {
            q[i] = q[i + 1];
         }
         r--; //update rear
      }
      return;
   }
   void Display() //display the queue {
      int i;
      if (f == r) {
         printf("\nQueue is Empty\n");
         return;
      }
      for (i = f; i < r; i++) {
         printf(" %d <-- ", q[i]);
      }
      return;
   }
   void Front() {
      if (f == r) {
         printf("\nQueue is Empty\n");
         return;
      }
      printf("\nFront Element is: %d", q[f]); //print front element of queue
      return;
   }
};
int main(void) {
   Q qu(3);
   qu.Display();
   cout<<"after inserting elements"<<endl;
   qu.Enqueue(10);
   qu.Enqueue(20);
   qu.Enqueue(30);
   qu.Display();
   qu.Dequeue();
   qu.Dequeue();
   printf("\n\nafter two node deletion\n\n");
   qu.Display();
   qu.Front();
   return 0;
}
Queue is Empty
10 <-- 20 <-- 30 <--

after two node deletion

30 <--
Front Element is: 30
How I can show JavaScript alert box in the middle of the screen?

To show the JavaScript alert box in the middle, you need to use the custom alert box. Under that, style it accordingly and position it to the center. Use the “top” and “left” CSS properties to achieve this. Set them as 50%, but as you can see a button below, use the property to 40% to align it with the button:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #F3F5F6;
            color: #000000;
            border: 1px solid #aaa;
            position: fixed;
            width: 300px;
            height: 100px;
            left: 40%;
            top: 40%;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #FFFFFF;
            display: inline-block;
            border-radius: 12px;
            border: 4px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 60px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message">This is a warning message.</div><br>
         <button class="yes">OK</button>
      </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>
How can I store JavaScript objects in cookies?

To store JavaScript objects in cookies, use JSON stringify. It is used to convert a JavaScript value to a JSON string.
The following code snippet to learn how to store JavaScript objects in cookies −
(function(){
   var myObject = JSON.parse('{"id":1,"gender":"male"}');
   var e = 'Thu Nov 26 2017 15:44:38'; document.cookie = 'myObj='+ JSON.stringify(myObject) +';expires=' + e;
})()
What is "not in" operator in Python?

In Python 'not in' membership operator evaluates to true if it does not finds a variable in the specified sequence and false otherwise. For example
>>> a = 10
>>> b = 4
>>> l1 = [1,2,3,4,5]
>>> a not in l1
True
>>> b not in l1
False
Since 'a' doesn't belong to l1, a not in b returns True. However, b can be found in l1, hence  b not in l1 returns False
PyQt5 QSpinBox - Blocking Signals - GeeksforGeeks

17 May, 2020
In this article we will see how we can block the signals of the spin box, blocking signals means the connected methods with the spin box will not receive the signals for example when we add action to it when its value changes that action will not work. Signals emitted while being blocked are not buffered.
Note : The destroyed() signal will be emitted even if the signals for the spin box have been blocked
In order to do this we use blockSignals method.
Syntax : spin_box.blockSignals(True)
Argument : It takes bool as argument
Action Performed : It blocks the emitting signals of spin box
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):        # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting prefix to spin        self.spin.setPrefix("Prefix ")          # setting suffix to spin        self.spin.setSuffix(" Suffix")          # adding action to the spin box        self.spin.valueChanged.connect(self.do)          # blocking signals of the spin box        self.spin.blockSignals(True)          # creating a label        self.label = QLabel("Label ", self)          # setting geometry to the label        self.label.setGeometry(100, 200, 300, 30)      # method called by spin box    def do(self):        # setting text to the label        self.label.setText("Action done")    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :Label text didn’t change as signals of spin box are blocked so they can’t call the value changed signal
Python PyQt-SpinBox
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
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
How to import excel file and find a specific column using Pandas? - GeeksforGeeks

05 Sep, 2020
In this article, we will learn how to import an excel file into a data frame and find the specific column. Let’s suppose our excel file looks like this.
Sample_data.xlsx
Excel sheet Link: https://drive.google.com/file/d/1x-S0z-gTo–H8byN12_MWLawlCXfMZkm/view?usp=sharing
Approach :
Import Pandas program
Create a DataFrame
Store Excel data into DataFrame
Check the specific column and display with head() function
Below is the implementation.
Step 1: Import excel file.
Python3
# importing moduleimport pandas as pd    # creating dataframe# importing excel filedf = pd.read_excel('Sample_data.xlsx')  df.head()
Output :
Step 2: Check the specific column and display topmost 5 value with the head()
Python3
df[df["Country"] == 'Canada'].head()
Output :
Another column with the same methods.
Python3
df[df["Year"] == 2013].head()
Output :
Another column with the same methods.
Python3
df[df["Segment"]=='Government'].head()
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
is_selected() element method - Selenium Python - GeeksforGeeks

27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use is_selected method in Selenium. is_selected method is used to check if element is selected or not. It returns a boolean value True or False.It can be used to check if a checkbox or radio button is selected.
element.is_selected()
Example –
<a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a>
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_id("link")
Now one can check if this element is being displayed with
text_length = element.is_selected()
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we check if courses tab is selected in navigation bar at geeksforgeeks.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.practice.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # print valueprint(element.is_selected())
Output-
Terminal Output –
Python-selenium
selenium
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
Node.js fsPromises.readFile() Method - GeeksforGeeks

08 Oct, 2021
The fsPromises.readFile() method is used to read the file. This method read the entire file into buffer. To load the fs module, we use require() method. It Asynchronously reads the entire contents of a file.
Syntax:
fsPromises.readFile( path, options )
Parameters: The method accept two parameters as mentioned above and described below:
path: It holds the name of the file to read or the entire path if stored at other location. It is a string, buffer, URL or a filename.
options: It holds the encoding of file. Its default value is ‘utf8’. It is an object or a string.encoding: It is a String or NULL. Default: nullflag: It is a string that support file system flags. Default: ‘r’.
encoding: It is a String or NULL. Default: null
flag: It is a string that support file system flags. Default: ‘r’.
Return Value: It returns a Promise.
The Promise is resolved with the contents of the file. If no encoding is specified (using options.encoding), the data is returned as a Buffer object. Otherwise, the data will be a string.
If options is a string, then it specifies the encoding.
When the path is a directory, the behavior of fsPromises.readFile() is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory’s contents will be returned.
Below examples illustrate the fsPromises.readFile() method in Node.js:
Create a demo text file like, we have created GFG.txt with the following text:
Greetings from GeeksforGeeks
Filename: index.js
// Node.js program to demonstrate // the fsPromises.readFile() method      // Include fs module var fs = require('fs'); const fsPromises = require('fs').promises;  // Use fsPromises.readFile() method// to read the file fs.promises.readFile("./GFG_Test.txt").then(function(result) {  console.log(""+result);}).catch(function(error) {   console.log(error);})
Step to run this program: Run the following command from the root directory as shown below:
node index.js
Output:
Greetings from GeeksforGeeks
Reference: https://nodejs.org/api/fs.html#fs_fspromises_readfile_path_options
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
p5.js | sphere() function - GeeksforGeeks

22 Apr, 2019
The sphere() function in p5.js is used to draw a sphere with given radius.
Syntax:
sphere( radius )
Parameters: This function accepts single parameter radius which stores the radius of the sphere.
Below programs illustrate the sphere() function in p5.js:
Example 1: This example uses sphere() function to draw the circle.
function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set filled color of sphere    fill('green');         // sphere() function called    sphere(100);}
Output:
Example 2: This example uses sphere() function to draw the circle.
function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set filled color of sphere    fill('yellow');         // Rotate     rotateX(frameCount * 0.01);    rotate(frameCount*0.03);         // sphere() function called    sphere(140);}
Output:Reference: https://p5js.org/reference/#/p5/sphere
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python | Size of string in memory - GeeksforGeeks

07 Jun, 2019
While working with strings, sometimes, we require to get the size of the string, i.e the length of it. But there can be situations in which we require to get the size that the string takes in bytes usually useful in case one is working with files. Let’s discuss certain ways in which this can be performed.
Method #1 : Using len() + encode()
The simplest and initial method that comes to the mind is to convert the string into a byte format and then extract its size.
# Python3 code to demonstrate# getting size of string in bytes# using encode() + len()  # initializing string test_string = "geekforgeeks"  # printing original string print("The original string : " + str(test_string))  # using encode() + len()# getting size of string in bytesres = len(test_string.encode('utf-8'))      # print resultprint("The length of string in bytes : " + str(res))
The original string : geekforgeeks
The length of string in bytes : 12

 
Method #2 : Using sys.getsizeof()
This task can also be performed by one of the system calls, offered by Python as in sys function library, the getsizeof function can get us the size in bytes of desired string.
# Python3 code to demonstrate# getting size of string in bytes# using sys.getsizeof()import sys  # initializing string test_string = "geekforgeeks"  # printing original string print("The original string : " + str(test_string))  # using sys.getsizeof()# getting size of string in bytesres = sys.getsizeof(test_string)      # print resultprint("The length of string in bytes : " + str(res))
The original string : geekforgeeks
The length of string in bytes : 12

Python string-programs
Python
Python Programs
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
Iterate over a list in Python
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
Find sum of the series 1+22+333+4444+...... upto n terms - GeeksforGeeks

25 Mar, 2021
Given a number N. The task is to find the sum of the below series up to N-th term: 
1 + 22 + 333 + 4444 + ...up to n terms
Examples:  
Input: N = 3
Output: 356

Input: N = 10 
Output: 12208504795
 
Approach: 
    
Below is the implementation of the above approach: 
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find the sum// of given series #include <iostream>#include <math.h> using namespace std; // Function to calculate sumint findSum(int n){    // Return sum    return (pow(10, n + 1) * (9 * n - 1) + 10) /                    pow(9, 3) - n * (n + 1) / 18;} // Driver codeint main(){    int n = 3;     cout << findSum(n);         return 0;}
// Java Program to find// Sum of first n termsimport java.util.*; class solution{static int calculateSum(int n){ // Returning the final sumreturn ((int)Math.pow(10, n + 1) * (9 * n - 1) + 10) /                (int)Math.pow(9, 3) - n * (n + 1) / 18;} // Driver codepublic static void main(String ar[]){// no. of terms to find the sumint n=3;System.out.println("Sum= "+ calculateSum(n)); }} //This code is contributed by Surendra_Gangwar
# Python program to find the sum of given series.  # Function to calculate sumdef solve_sum(n):    # Return sum    return (pow(10, n + 1)*(9 * n - 1)+10)/pow(9, 3)-n*(n + 1)/18 # driver coden = 3 print(int(solve_sum(n)))
// C# Program to find// Sum of first n termsusing System;class solution{static int calculateSum(int n){ // Returning the final sumreturn ((int)Math.Pow(10, n + 1) * (9 * n - 1) + 10) /                (int)Math.Pow(9, 3) - n * (n + 1) / 18;} // Driver codepublic static void  Main(){// no. of terms to find the sumint n=3;Console.WriteLine("Sum= "+ calculateSum(n)); }} //This code is contributed by inder_verma.
<?php// PHP program to find the sum// of given series // Function to calculate sumfunction findSum($n){    // Return sum    return (pow(10, $n + 1) *               (9 * $n - 1) + 10) /            pow(9, 3) - $n * ($n + 1) / 18;} // Driver code $n = 3; echo findSum($n); // This code is contributed// by inder_verma.?>
<script>// Javascript Program to find// Sum of first n terms     function calculateSum( n)    {         // Returning the const sum        return (parseInt(Math.pow(10, n + 1)) * (9 * n - 1) + 10) /                parseInt(Math.pow(9, 3)) - n * (n + 1) / 18;     }     // Driver code         // no. of terms to find the sum    let n = 3;    document.write("Sum= " + calculateSum(n)); // This code is contributed by 29AjayKumar </script>
356
 
SURENDRA_GANGWAR
inderDuMCA
29AjayKumar
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Strobogrammatic number - GeeksforGeeks

16 Oct, 2019
For the given length n, find all n-length Strobogrammatic numbers.
Strobogrammatic Number is a number whose numeral is rotationally symmetric so that it appears the same when rotated 180 degrees. In other words, Strobogrammatic Number appears the same right-side up and upside down.
0 after 180° rotation : (0 → 0)1 after 180° rotation : (1 → 1)8 after 180° rotation : (8 → 8)6 after 180° rotation : (6 → 9)9 after 180° rotation : (9 → 6)
Examples :
Input : n = 2
Output : 88  11  96  69

Input : n = 4
Output : 8008 1001 9006 6009 8888 1881 9886 6889 8118 1111
         9116 6119 8968 1961 9966 6969 8698 1691 9696 6699

 
Below is the Python3 implementation :
# Python program to print all# Strobogrammatic number of length n  # strobogrammatic function def strobogrammatic_num(n):          result = numdef(n, n)    return result      # definition functiondef numdef(n, length):          if n == 0: return [""]    if n == 1: return ["1", "0", "8"]          middles = numdef(n - 2, length)    result = []          for middle in middles:        if n != length:                        result.append("0" + middle + "0")          result.append("8" + middle + "8")        result.append("1" + middle + "1")        result.append("9" + middle + "6")        result.append("6" + middle + "9")    return result  # Driver Codeif __name__ == '__main__':          # Print all Strobogrammatic     # number for n = 3    print(strobogrammatic_num(3))
Output :
['818', '111', '916', '619', '808', '101', '906', '609', '888', '181', '986', '689']

 Reference : https://en.wikipedia.org/wiki/Strobogrammatic_number
chaudhary_19
number-digits
number-theory
series
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Print all possible combinations of r elements in a given array of size n
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Program to print prime numbers from 1 to N.
Euclidean algorithms (Basic and Extended)
Python - PyTorch exp() method - GeeksforGeeks

26 May, 2020
PyTorch torch.exp() method returns a new tensor after getting the exponent of the elements of the input tensor.
Syntax: torch.exp(input, out=None)
Arguments
input: This is input tensor.
out: The output tensor.
Return: It returns a Tensor.
# Importing the PyTorch library import torch     # A constant tensor of size na = torch.randn(6)print(a)  # Applying the exp function and # storing the result in 'out'out = torch.exp(a)print(out)
Output:
1.0532
-1.9300
 0.6392
-0.7519
 0.9133
 0.3998
[torch.FloatTensor of size 6]
 2.8667
 0.1451
 1.8949
 0.4715
 2.4925
 1.4915
[torch.FloatTensor of size 6]


Example 2:
# Importing the PyTorch library import torch     # A constant tensor of size na = torch.FloatTensor([1, 4, 6, 3])print(a)  # Applying the exp function and # storing the result in 'out'out = torch.exp(a)print(out)
Output:
 1
 4
 6
 3
[torch.FloatTensor of size 4]
   2.7183
  54.5981
 403.4288
  20.0855
[torch.FloatTensor of size 4]

Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Anonymous Union and Structure in C - GeeksforGeeks

06 Oct, 2021
In C11 standard of C, anonymous Unions and structures were added. Anonymous unions/structures are also known as unnamed unions/structures as they don’t have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions. Definition is just like that of a normal union just without a name or tag. For example, 
// Anonymous union example
union 
{
   char alpha;
   int num;
};
// Anonymous structure example
struct 
{
   char alpha;
   int num;
};
Since there is no variable and no name, we can directly access members. This accessibility works only inside the scope where the anonymous union is defined. Following is a complete working example of anonymous union.
C
// C Program to demonstrate working of anonymous union#include <stdio.h>struct Scope {    // Anonymous union    union {        char alpha;        int num;    };}; int main(){    struct Scope x, y;    x.num = 65;    y.alpha = 'A';     // Note that members of union are accessed directly    printf("y.alpha = %c, x.num = %d", y.alpha, x.num);     return 0;}
Remember that we can only access one member of a union at a time. If another member is assigned the previous member will be wiped out from the union.
x.alpha = A, x.num = 65
C
// C Program to demonstrate working of anonymous struct#include<stdio.h>struct Scope{    // Anonymous structure    struct    {        char alpha;        int num;    };}; int main(){    struct Scope x;    x.num = 65;    x.alpha = 'B';     // Note that members of structure are accessed directly    printf("x.alpha = %c, x.num = %d", x.alpha, x.num);     return 0;}
x.alpha = B, x.num = 65
What about C++? Anonymous Unions and Structures are NOT part of C++ 11 standard, but most of the C++ compilers support them. Since this is a C only feature, the C++ implementations don’t allow to anonymous struct/union to have private or protected members, static members, and functions.  
This article is contributed by Nikita Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Arshad Ali
sritej20
C-Structure & Union
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
rand() and srand() in C/C++
std::string class in C++
fork() in C
Command line arguments in C/C++
Enumeration (or enum) in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
How to use the 'with' keyword in JavaScript?

The with keyword is used as a kind of shorthand for referencing an object's properties or methods.
The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.
The syntax for with object is as follows −
with (object){
   properties used without the object name and dot
}
You can try to learn the following code to learn how to implement with keyword −
Live Demo
<html>
   <head>
      <title>User-defined objects</title>
      <script>
         // Define a function which will work as a method
         function addPrice(amount){
            with(this){
               price = amount;
            }
         }
         function book(title, author){
            this.title = title;
            this.author = author;
            this.price = 0;
            this.addPrice = addPrice; // Assign that method as property.
         }
      </script>
   </head>
   <body>
      <script type="text/javascript">
         var myBook = new book("Python", "Tutorialspoint");
         myBook.addPrice(100);

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
   </body>
</html>
Book title is : Python
Book author is : Tutorialspoint
Book price is : 100
DAX Aggregation - COUNTA function

Counts the number of cells in a column that are not empty. It counts not just the rows that contain numeric values, but also the rows that contain nonblank values, including text, dates, and logical values.
COUNTA (<column>)

column
The column that contains the values to be counted.
Returns a whole number.
When the function does not find any rows to count, the function returns a blank. When there are rows, but none of them meet the specified criteria, then the function returns 0.
= COUNTA (ProductInventory[UsageDate])

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Decimal.Add() Method in C# - GeeksforGeeks

29 Jan, 2019
This method is used to add two specified decimal values.
Syntax: public static decimal Add (decimal a1, decimal a2);
Parameters:a1: This parameter specifies the first value to add.a2: This parameter specifies the second value to add.
Return Value: Decimal sum of a1 & a2.
Exceptions: This method will give OverflowException if the sum of a1 and a2 is less than smallest possible value of Decimal or greater than the largest possible value of Decimal.
Below programs illustrate the use of Decimal.Add(Decimal, Decimal) Method
Example 1:
// C# program to demonstrate the// Decimal.Add(Decimal, Decimal) // Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // Declaring the decimal            // variables            Decimal a1 = .01m;            Decimal a2 = .03m;              // adding the two Decimal value            // using Add() method;            Decimal value = Decimal.Add(a1, a2);              // Display the sum            Console.WriteLine("Decimal Sum : {0}",                                           value);        }          catch (OverflowException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Decimal Sum : 0.04

Example 2: For OverflowException
// C# program to demonstrate the// Decimal.Add(Decimal, Decimal)// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // Declaring the decimal variables            Decimal a1 = 1.01m;            Decimal a2 = Decimal.MaxValue;              // adding the two Decimal value            // using Add() method;            Decimal value = Decimal.Add(a1, a2);              // Display the sum            Console.WriteLine("Decimal Sum : {0}",                                           value);        }          catch (OverflowException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.OverflowException

CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
How to Change DB Schema to DBO in SQL?

30 Dec, 2021
In this article, we will look at two methods for changing the database schema in SQL Server to DBO. 
Schema:
SQL Schema is defined as a logical grouping of database objects. Tables, views, stored procedures, functions, indexes, and triggers are all part of database object. It is a handy tool for segregating database items for various applications, regulating access privileges, and managing database security management.
Now that we have a fundamental understanding of what schema is let’s get started. We have a database called geeks.
Step 1: Use the below SQL statement to switch the database context to geeks:
Query: 
USE geeks;
We have a table named brands (Notice: Here the table prefix is GeekSchema indicating that table is under GeekSchema schema).
Step 2: To verify the contents of the table use the below query
Query: 
SELECT * FROM
[GeekSchema].brands;
Now let’s proceed with changing the table Schema:
Step 1: Right-click on the brands table from the object explorer window and choose Design option:
Step 2: It will opens the table designer window. Wherein we can change table properties. Click on Properties Window
Step 3: Choose the desired Scheme name from the drop down ( dbo in our case)
Step 4: Save the changes by clicking Yes on the confirmation dialogue box. Refresh the tables, we can see the schema of the brands table has been changes from GeekSchema to dbo:
Output:
Step 1: We can also alter the Table schema using SQL Query. By using the below syntax.
Syntax:
ALTER SCHEMA TargetSchema 
TRANSFER SourceSchema.TableName; 
Use below query to alter the Schema for brands table.
Query:
ALTER SCHEMA dbo 
TRANSFER GeekSchema.brands;
Refresh the tables, we can see the schema of the brands table has been changes from GeekSchema to dbo:
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server