code-rag-bench/online-tutorials huggingface dataset:
How to implement CANDIDATE key in any MySQL table?

Each relation may have one or more candidate key. One of these candidate keys is called Primary Key. Each candidate key qualifies for Primary Key. Therefore, candidates for Primary Key is called Candidate Key. To implement candidate key in MySQL, set more than one column as unique key. These keys would qualify for candidate key as in the below syntax −
alter table yourTableName add unique key anyName(yourColumnName1,yourColumnName2);
Let us first create a −
mysql> create table DemoTable1400
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(40),
   -> Age int
   -> );
Query OK, 0 rows affected (0.50 sec)
Following is the query to implement CANDIDATE key in any MySQL −
mysql> alter table DemoTable1400 add unique key name_age_unique(Name,Age);
Query OK, 0 rows affected (0.67 sec)
Records: 0  Duplicates: 0  Warnings: 0
Insert some records in the table using insert −
mysql> insert into DemoTable1400(Name,Age) values('Chris',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1400(Name,Age) values('Chris',23);
ERROR 1062 (23000): Duplicate entry 'Chris-23' for key 'name_age_unique'
mysql> insert into DemoTable1400(Name,Age) values('David',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1400(Name,Age) values('Chris',24);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select −
mysql> select * from DemoTable1400;
This will produce the following output −
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Chris |   23 |
|  4 | Chris |   24 |
|  3 | David |   23 |
+----+-------+------+
3 rows in set (0.00 sec)
JavaScript Separate objects based on properties

Suppose, we have an object like this −
const obj = {
   0: { "time": 1, "day": 1, },
   1: { "time": 2, "day": 1, },
   2: { "time": 3, "day": 1, },
   3: { "time": 1, "day": 2, },
   4: { "time": 2, "day": 2, },
   5: { "time": 3, "day": 2, }
};
We are required to write a JavaScript function that takes one such object and groups all the key value pairs in separate sub objects that have the same value for the day key.
The output for the above object should be −
const output = { '1':
{ '1': { time: 1, day: 1 },
'2': { time: 2, day: 1 },
'3': { time: 3, day: 1 } },
'2':
{ '1': { time: 1, day: 2 },
'2': { time: 2, day: 2 },
'3': { time: 3, day: 2 } }
}
The code for this will be −
const obj = {
   0: { "time": 1, "day": 1, },
   1: { "time": 2, "day": 1, },
   2: { "time": 3, "day": 1, },
   3: { "time": 1, "day": 2, },
   4: { "time": 2, "day": 2, },
   5: { "time": 3, "day": 2, }
};
const groupObject = obj => {
   let res = {};
   res = Object.values(obj).reduce((acc, val) => {
      if(acc[val['day']] === undefined){
         acc[val['day']] ={};
      };
      acc[val['day']][val['time']] = val;
      return acc;
   },{});
   return res;
};
console.log(groupObject(obj));
The output in the console −
{
   '1': {
      '1': { time: 1, day: 1 },
      '2': { time: 2, day: 1 },
      '3': { time: 3, day: 1 }
   },
   '2': {
      '1': { time: 1, day: 2 },
      '2': { time: 2, day: 2 },
      '3': { time: 3, day: 2 }
   }
}
Print number with commas as 1000 separators in Python

Many times the numbers with three or more digits need to be represented suitably using comma. This is a requirement mainly in the accounting industry as well as in the finance domain. In this article we'll see how Python program can be used to insert a comma at a suitable place. We are aiming to insert comma as a thousand separator.
The format function in python can be used with below settings to achieve this requirement.
(f"{num:,d}")
: is the format specifier
D is the thousand separator
 Live Demo
print(f'{1445:,d}')
print(f'{140045:,d}')
Running the above code gives us the following result −
1,445
140,045
With floats we have to specify with a slightly different format as shown below. The digits beyond two places after the decimal get ignored.
 Live Demo
print("{:,.2f}".format(3435.242563))
Running the above code gives us the following result −
3,435.24
Getting the URL of the current page using Selenium WebDriver.

We can obtain the URL of the current page with Selenium webdriver. This is achieved with the help of getCurrentUrl() method. It fetches the URL of the opened application. This method accepts no parameters and strings the URL in the form of String.
Syntax −
String strUrl = driver.getCurrentUrl();
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class CurrentUrl{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // get current URL and print
      String strUrl = driver.getCurrentUrl();
      System.out.println("Current Url is:"+ strUrl);
      driver.quit();
   }
}
Rotating axes label text in 3D Matplotlib

To rotate axes label text in 3D matplotlib, we can use set_zlabel() method with rotation in the method's argument.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add a subplot to the current axis with projection="3d".
Add a subplot to the current axis with projection="3d".
Initialize a variable, angle, for an angle.
Initialize a variable, angle, for an angle.
Set Z-axis label using set_zlabel() method with a rotation.
Set Z-axis label using set_zlabel() method with a rotation.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
angle = 45
ax.set_zlabel('Z-Axis', rotation=angle)
plt.show()
When to use @JsonValue annotation using Jackson in Java?


The @JsonValue annotation is useful at the method level. We can use this annotation to generate a JSON string from java object. If we want to print a serialized object then override the toString() method. But using @JsonValue annotation, we can define a way in which java object is serialized.
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonValue
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JsonValueAnnotationTest {
   public static void main(String args[]) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(new Student());
      System.out.println(jsonString);
   }
}
// Student class
class Student {
   @JsonProperty
   private int studentId = 115;
   @JsonProperty
   private String studentName = "Sai Adithya";
   @JsonValue
   public String toJson() {
      return this.studentName + "," + this.studentId + "," + this.toString();
   }
   @Override
   public String toString() {
      return "Student[" +
            "studentId = " + studentId +
      ", studentName = " + studentName +
      ']';
   }
}
"Sai Adithya,115,Student[studentId = 115, studentName = Sai Adithya]"
How to check if a time series is stationary in R?

To check if a time series is stationary, we can use Dickey-Fuller test using adf.test function of tseries package. For example, if we have a time series object say TimeData then to check whether this time series is stationary or not we can use the command adf.test(TimeData).
 Live Demo
x1<-ts(rpois(240,5),frequency=12)
x1
   Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1  3   7   7   1   1   6   5   4   8   5   2   3
2  5   0   3   4   4   3   2   4   6   5   5   4
3  5   8   6   2   3   9   5   4   7   4   4   7
4  2   5   4   5   7   9   9   2   3   2   7   7
5  3   5   3   3   8   2   2   3   5   4   3   7
6  6   6   5   4   6   6   5   6   4   2   7   5
7  5   2   3   7   3   7   7   3   7   4   5   6
8  2   5   6   4   6   5   6   3   5   4   9   3
9  4   4   3   7   8   5   1   7   3   5   4   7
10 4   4   7   9   6   6   8   4   4   4   3   3
11 5   2   5   1   2   6   2   2   5   4   3   6
12 4   7   9   2   8   5   6   3   3   5   4   2
13 7  12   2   3   7   3   1   7   6   8   6   4
14 4   4   6  10   8   9   4   2   7   3   6   9
15 5   5   6  11   2   2   6   5   8  10   6   9
16 5   4   2   3   5  14   4   5   3   9   7  11
17 4   5   6   6   4  10   5   6   3   7   7   3
18 8   7   4   9   4   6   1   2   2   7   5   8
19 8   6   5   2   3   8   8   4   5   3   3   8
20 3   4   4   2   4   2   8   3   5   6   4   4
Loading tseries package and testing for stationarity of x1 −
library(tseries)
adf.test(x1)
Augmented Dickey-Fuller Test
data: x1
Dickey-Fuller = -5.3203, Lag order = 6, p-value = 0.01
alternative hypothesis: stationary
Warning message:
In adf.test(x1) : p-value smaller than printed p-value
 Live Demo
x2<-ts(rnorm(80),frequency=4)
x2
       Qtr1           Qtr2       Qtr3        Qtr4
1   0.60770751  1.51860885   0.42749703   0.68703506
2   0.42218841  0.32858411   0.17599648   0.87994947
3  -1.33761406  0.31770494  -0.47925768   0.97272742
4  -0.37615238 -0.22445651   0.84534205   1.62197957
5  -0.89668820  1.73200007  -0.08857733   1.00659180
6   0.43669956 -1.73037915  -0.20687863  -1.00296218
7   0.63507344 -1.19167403   0.10682158  -0.35904410
8  -0.23533581  1.73153525   0.30313272   0.79616948
9   0.14177702  1.05396871   0.10664840   1.00615408
10 -0.75120735  1.40710169   1.03382332  0.84761125
11 -0.09219708 -2.90114437   0.86964912   0.75207072
12 -1.98357706  0.92872611  -0.59287936   1.10598932
13 -0.24146436 -0.44565952  -0.63415612  -0.28752626
14 -1.98998974 -0.53391601   1.14723658  -1.17779097
15 -0.55899287  0.91836259   0.17393828   2.37323800
16 -0.73209001  0.18996601  -0.60507321   1.48610650
17 -1.38941874 -0.12928990   0.66282081   0.76798462
18  0.27651434  0.36685046   1.35956161  -1.53075985
19 -2.67204336  0.21251039  -1.75949873  -0.33758449
20  1.20913418  0.68987712   2.28974722   1.37072301
Testing for stationarity of x2 −
adf.test(x2)
Augmented Dickey-Fuller Test
data: x2
Dickey-Fuller = -3.6685, Lag order = 4, p-value = 0.03288
alternative hypothesis: stationary
Implement If else in stored procedure in MySQL?

To implement if-else, the syntax is as follows −
if yourCondition then
     yourStatement1;
    else
    yourStatement2;
    end if ;
To understand the above concept for if-else in a stored procedure, let us create a stored procedure −
mysql> delimiter //
mysql> create procedure If_else_stored_demo(value int)
     begin
     if value > 1000 then
     select "your value is greater than 1000";
     else
     select "your value is less than or equal to 1000";
     end if ;
     end
     //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
Now you can call the stored procedure using call command −
mysql> call If_else_stored_demo(500);
This will produce the following output −
+------------------------------------------+
| your value is less than or equal to 1000 |
+------------------------------------------+
| your value is less than or equal to 1000 |
+------------------------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Converting an unsigned 32 bit decimal to corresponding ipv4 address in JavaScript

Consider the following ipv4 address −
128.32.10.1
If we convert it to binary, the equivalent will be −
10000000.00100000.00001010.00000001
And further if we convert this binary to unsigned 32 bit decimal, the decimal will be −
2149583361
Hence, we can say that the ipv4 equivalent of 2149583361 is 128.32.10.1
We are required to write a JavaScript function that takes in a 32-bit unsigned integer and returns its equivalent ipv4 address.
Following is the code −
 Live Demo
const num = 2149583361;
const int32ToIp = (num) => {
   return (num >>> 24 & 0xFF) + '.' +
   (num >>> 16 & 0xFF) + '.' +
   (num >>> 8 & 0xFF) + '.' +
   (num & 0xFF);
};
console.log(int32ToIp(num));
Following is the console output −
128.32.10.1
Delete array element in given index range [L – R] in C++ Program

In this tutorial, we are going to learn how to delete elements from the given range. Let's see the steps to solve the problem.
Initialize the array and range to delete the elements from.
Initialize the array and range to delete the elements from.
Initialize a new index variable.
Initialize a new index variable.
Iterate over the array.If the current index is not in the given range, then update the element in the array with a new index variableIncrement the new index.
Iterate over the array.
If the current index is not in the given range, then update the element in the array with a new index variable
If the current index is not in the given range, then update the element in the array with a new index variable
Increment the new index.
Increment the new index.
Return the new index.
Return the new index.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int deleteElementsInRange(int arr[], int n, int l, int r) {
   int i, newIndex = 0;
   for (i = 0; i < n; i++) {
      // adding updating element if it is not in the given range
      if (i <= l || i >= r) {
         arr[newIndex] = arr[i];
         newIndex++;
      }
   }
   // returing the updated index
   return newIndex;
}
int main() {
   int n = 9, l = 1, r = 6;
   int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   int updatedArrayLength = deleteElementsInRange(arr, n, l, r);
   for (int i = 0; i < updatedArrayLength; i++) {
      cout << arr[i] << " ";
   }
   cout << endl;
   return 0;
}
If you execute the above program, then you will get the following result.
1 2 7 8 9
If you have any queries in the tutorial, mention them in the comment section.
Magnetic Ink Character Recognition using Python - GeeksforGeeks

29 Dec, 2020
Magnetic Ink Character Recognition or MICR which is generally used in a bank. This is a 9 digit code to identify the location of the bank branch. MICR code is a code printed on cheques using MICR (Magnetic Ink Character Recognition technology). This enables identification of the cheques and which in turns means faster processing. In this article, we are going to write a python script to validate the MICR code and extract information.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4

requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests

Approach:
Import module
Merge MICR Code into URL
Make requests instance and pass into URL
Pass the requests into a Beautifulsoup() function
traverse the information MICR code into soup object
Implementation:
Python3
# import moduleimport requestsfrom bs4 import BeautifulSoup  # link for extract html data# Making a GET requestdef getdata(url):    r = requests.get(url)    return r.text    # input by geek# MICR codeMicr = "800002012"  # urlurl = "https://micr.bankifsccode.com/"+Micr    # pass the url# into getdata functionhtmldata = getdata(url)soup = BeautifulSoup(htmldata, 'html.parser')  # traverse the bank informationdata = []for i in (soup.find_all("div", class_="text6")):    data.append((i.get_text()))  # Validate the# dataif len(data) == 0:    print("Not Valid MICR Code")else:    print("Found")    print(data)
Output:
Found
['MICR Code:- 800002012, STATE BANK OF INDIA, DIGHA']

Python web-scraping-exercises
python-utility
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
How to plot with different scales in Matplotlib?

To plot with different scales in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create t, data1 and data2 data points using numpy
Create a figure and a set of subplots, ax1.
Initialize a color variable.
Set x and y labels of axis 1.
Plot t and data1 using plot() method.
Set label colors using tick_params() method.
Create a twin Axes sharing the X-axis, ax2.
Perform steps 4, 6, 7 with a different dataset on axis 2.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)
fig, ax1 = plt.subplots()
color = 'red'

ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()

color = 'blue'
ax2.set_ylabel('sin', color=color)
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

plt.show()
Java program to find maximum of three numbers

The maximum among three numbers can be found using an if else statement. A program that demonstrates this is given as follows.
 Live Demo
public class Example {
   public static void main(String args[]) {
      int num1 = 15;
      int num2 = -5;
      int num3 = 7;
      if (num1 >= num2 && num1 >= num3)
         System.out.println( num1 + " is the maximum number.");
      else if (num2 >= num1 && num2 >= num3)
         System.out.println( num2 + " is the maximum number.");
      else
         System.out.println( num3 + " is the maximum number.");
   }
}
15 is the maximum number.
Now let us understand the above program.
First, the three numbers are defined. If num1 is greater than num2 and num3, then it is the maximum number. If num2 is greater than num1 and num3, it is the maximum number. Otherwise, num3 is the maximum number. The code snippet that demonstrates this is given as follows.
int num1 = 15;
int num2 = -5;
int num3 = 7;
if (num1 >= num2 && num1 >= num3)
System.out.println( num1 + " is the maximum number.");
else if (num2 >= num1 && num2 >= num3)
System.out.println( num2 + " is the maximum number.");
else
System.out.println( num3 + " is the maximum number.");
How to make horizontal scrollable in a bootstrap row? - GeeksforGeeks

04 Oct, 2019
Here is the task to make horizontally scrollable in a bootstrap row.It can be done by the following approach:
Approach:
Making all the div element in inline using display: inline-block; property
Adding the scroll bar to all the div element using overflow-x: auto; property.
white-space: nowrap; property is used make all div in a single line.
Example :
<!DOCTYPE html><html lang="en">  <head>    <title>How to make horizontal       scrollable in a bootstrap row?</title>      <meta charset="utf-8">    <meta name="viewport"           content="width=device-width, initial-scale=1">      <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">    <style>        /* The heart of the matter */                  .horizontal-scrollable > .row {            overflow-x: auto;            white-space: nowrap;        }                  .horizontal-scrollable > .row > .col-xs-4 {            display: inline-block;            float: none;        }        /* Decorations */                  .col-xs-4 {            color: white;            font-size: 24px;            padding-bottom: 20px;            padding-top: 18px;        }                  .col-xs-4:nth-child(2n+1) {            background: green;        }                  .col-xs-4:nth-child(2n+2) {            background: black;        }    </style></head>  <body>    <center>        <div class="container">              <h1 style="text-align:center;color:green;">             GeeksforGeeks         </h1>            <h3>            To make horizontal scrollable in a bootstrap row?        </h3>            <div class="container horizontal-scrollable">                <div class="row text-center">                    <div class="col-xs-4">1</div>                    <div class="col-xs-4">2</div>                    <div class="col-xs-4">3</div>                    <div class="col-xs-4">4</div>                    <div class="col-xs-4">5</div>                    <div class="col-xs-4">6</div>                    <div class="col-xs-4">7</div>                </div>            </div>        </div>    </center></body>  </html>
Output:
Akanksha_Rai
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
Difference between Bootstrap 4 and Bootstrap 5
How to Use Bootstrap with React?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Differences between abstract class and interface in Java

In Java, abstraction is achieved using Abstract classes and interfaces. Both contains abstract methods which a child class or implementing class has to implement. Following are the important differences between abstract class and an interface.
public class JavaTester {
   public static void main(String args[]) {
      Animal tiger = new Tiger();
      tiger.eat();
      Cat lion = new Lion();
      lion.eat();
   }
}
interface Animal {
   public void eat();
}
class Tiger implements Animal {
   public void eat(){
      System.out.println("Tiger eats");
   }
}
abstract class Cat {
   abstract public void eat();
}
class Lion extends Cat{
   public void eat(){
      System.out.println("Lion eats");
   }
}
Tiger eats
Lion eats
Neo4j CQL - IN Operator

Like SQL, Neo4j CQL has provided an IN operator to give a collection of values to CQL Commands.
IN[<Collection-of-values>]
Syntax Description
Let us examine this with an example.
This example demonstrates how to use IN operator to retrieve Employee node details.
Step 1 - Open Neo4j Data Browser
Step 2 - Type the below command at dollar prompt in Data Browser.
MATCH (e:Employee) 
RETURN e.id,e.name,e.sal,e.deptno
Step 3 - Click on Execute button and observe the results.
We can observe that this query returns 4 rows.
Step 4 - Type the below command and click on Execute button.
MATCH (e:Employee) 
WHERE e.id IN [123,124]
RETURN e.id,e.name,e.sal,e.deptno
This query returns only two rows whose ids are matched specified in the IN operator.
 Print
 Add Notes
 Bookmark this page
Output of C++ programs | Set 44 - GeeksforGeeks

04 Sep, 2017
Output In C++Q.1 What is the output of below program?
#include <iostream>using namespace std;int main(){    int x = 0;    x = printf("Hello World");    printf(" %d", x);    return 0;}
Optiona) Hello World 10b) Hello World 11c) Hello World 12d) Hello World 0
ans :- b
Explanation : printf() returns count of characters successfully written on screen. In this program, printf() writes 10 character + 1 space total 11 so x is 11.
Q.2 What is the output of below program assuming that a character takes 1 byte and a pointer takes 8 bytes.
#include <iostream>#include <bits/stdc++.h>using namespace std;int main(){    char a[] = "Hello World";    char* p = a;    printf("%d %d %d", sizeof(a), sizeof(p), strlen(a));    return 0;}
Optiona) 12 10 8b) 12 4 10c) 12 8 10d) 12 8 11
ans :- d
Explanation :sizeof(a) : Character array size is 12 because in Hello World there are : 10 characters 1 space and 1 NULL.sizeof(p) : 8 is pointer size of a pointer. Note that all pointer types take same size on a particular compiler.strlen(a) : 11 is string length because length function not contain NULL character.
Q.3 What is the output of below program?
#include <iostream>using namespace std;int main(){    printf("%d", 'C' > 'A');    return 0;}
Optiona) 1b) 0c) 67d) Error
ans :- a
Explanation : This code compares ASCII values of A and C and return 1 because ASCII value of C greater than that of A.
Q.4 What is the output of below program?
#include <iostream>using namespace std;int main(){    for (int i = 1; i <= 10; i++) {        int k = i & (i << 1);        if (k)            printf("%d, ", i);    }}
Optiona) 1, 2, 4, 5, 8, 9b) 3, 6, 7c) 0d) None of these
Ans :b
Explanation : This program basically prints all numbers (smaller than or equal to 10) that don’t have consecutive 1’s in binary representation. Please refer this article for details.
This article is contributed by Gyayak Jain . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Output of Python Program | Set 1
Output of Java Program | Set 2
Output of Java program | Set 28
Concatenation of arrays in Julia - cat(), vcat(), hcat() and hvcat() Methods - GeeksforGeeks

01 Apr, 2020
The cat() is an inbuilt function in julia which is used to concatenate the given input arrays along the specified dimensions in the iterable dims.
Syntax: cat(A...; dims=dims)
Parameters:
A: Specified arrays.
A: Specified dimensions.
Returns: It returns the concatenated array.
Example:
# Julia program to illustrate # the use of cat() method   # Getting the concatenated arraya = [1, 2, 3, 4]b = [5, 10, 15, 20]cat(a, b, dims =(2, 2))
Output:
The vcat() is an inbuilt function in julia which is used to concatenate the given arrays along dimension 1.
Syntax: vcat(A...)
Parameters:
A: Specified arrays.
Returns: It returns the concatenated array.
Example:
# Julia program to illustrate # the use of vcat() method   # Getting the concatenated arraya = [5 10 15 20]b = [2 4 6 8; 1 3 5 7]vcat(a, b)
Output:
The hcat() is an inbuilt function in julia which is used to concatenate the given arrays along dimension 2.
Syntax: hcat(A...)
Parameters:
A: Specified arrays.
Returns: It returns the concatenated array.
Example:
# Julia program to illustrate # the use of hcat() method   # Getting the concatenated arraya = [5; 10; 15; 20; 25]b = [1 2; 3 4; 5 6; 7 8; 9 10]hcat(a, b)
Output:
The hvcat() is an inbuilt function in julia which is used to concatenate the given arrays horizontally and vertically in one call. The first parameter specifies the number of arguments to concatenate in each block row.
Syntax:hvcat(rows::Tuple{Vararg{Int}}, values...)
Parameters:
rows: Specified block row.
values: Specified values.
Returns: It returns the concatenated array.
Example:
# Julia program to illustrate # the use of hvcat() method   # Getting the concatenated arraya, b, c, d = 5, 10, 15, 20[a b; c d]hvcat((2, 2), a, b, c, d)
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Working with CSV Files in Julia
Printing Struct Variables in Golang - GeeksforGeeks

01 Mar, 2020
Suppose, we need to print the structure with its fields corresponding value. We can do this with the help of package fmt which implements formatted I/O with functions analogous to C’s printf and scanf. Let’s first try if we just print the structure, what will happen.
package main   import ("fmt")   // Fields: structure to be printedtype Fields struct {    Name     string    NickName string    Age      int}   func main() {      // Initialising the struct with values    var f = Fields{    Name:     "Abc",    NickName: "abc",    Age:      19,    }      // printing the structure    fmt.Println(f)}
Output:
{Abc abc 19}

There are two ways to print Struct Variables in Golang. The first way is to use Printf function of package fmt with special tags in the arguments the printing format arguments. Some of those arguments are as below:
%v the value in a default format
%+v the plus flag adds field names
%#v a Go-syntax representation of the value

package main  import (    "fmt")  // Fields: structure to be printedtype Fields struct {    Name     string    NickName string    Age      int}  func main() {      // initializing the     // struct with values    var f = Fields{        Name:     "Abc",        NickName: "abc",        Age:      19,    }          // printing the structure    fmt.Printf("%v\n", f)    fmt.Printf("%+v\n", f)    fmt.Printf("%#v\n", f)}
Output:
{Abc abc 19}
{Name:Abc NickName:abc Age:19}
main.Fields{Name:"Abc", NickName:"abc", Age:19}

Printf with #v includes main.Fields that is the structure’s name. It includes “main” to distinguish the structure present in different packages.
Second possible way is to use function Marshal of package encoding/json.
Syntax :
func Marshal(v interface{}) ([]byte, error)

package main  import (    "encoding/json"    "fmt")  // Fields: structure to be printedtype Fields struct {    Name     string    NickName string    Age      int}  func main() {      // initialising the struct    // with values    var f = Fields{        Name:     "Abc",        NickName: "abc",        Age:      19,    }          // Marshalling the structure    // For now ignoring error    // but you should handle    // the error in above function    jsonF, _ := json.Marshal(f)      // typecasting byte array to string    fmt.Println(string(jsonF))  }
Output:
{"Name":"Abc", "NickName":"abc", "Age":19}

Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
Python PIL Attributes | Image.width Method - GeeksforGeeks

27 Sep, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
The Image class have the width attributes.
Image.width Image width, in pixels. Attribute defines the various property of an object, element or file.
Syntax: PIL.Image.width
Parameters:image– image used of different extension.
Returns: width of the image
Image Used:
     # importing Image module from PIL package from PIL import Image   # opening a  image im = Image.open(r"C:\Users\System-Pc\Desktop\flower1.jpg")   # width attributeim1 = im.widthprint(im1)
Output:
225

Another Example: take another image with .png extension.
Image Used:
     # importing Image module from PIL package from PIL import Image   # opening a  image im = Image.open(r"C:\Users\System-Pc\Desktop\python.png")   # width attributeim1 = im.widthprint(im1)
Output:
220

nidhi_biet
Python-pil
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Check whether a value is logical or not in R Programming - is.logical() Function - GeeksforGeeks

16 Jun, 2020
is.logical() function in R Language is used to check whether a value is logical or not.
Syntax: is.logical(x)
Parameters:x: Value to be checked
Example 1:
# R Program to test whether# a value is logical or not  # Calling is.logical() functionis.logical(0)is.logical(!5)is.logical(T)is.logical(FALSE)
Output:
[1] FALSE
[1] TRUE
[1] TRUE
[1] TRUE

Example 2:
# R Program to test whether# a value is logical or not  # Creating vectorx1 <- c(1, 2, 3, 4)x2 <- c(T, F, TRUE, FALSE, ! 2)x3 <- c(1, T, F)  # Calling is.logical() functionis.logical(x1)is.logical(x2)is.logical(x3)
Output:
[1] FALSE
[1] TRUE
[1] FALSE

R Math-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
numpy.ndarray.nbytes() method | Python - GeeksforGeeks

26 Mar, 2020
numpy.ndarray.nbytes() function return total bytes consumed by the elements of the array.
Syntax : numpy.ndarray.nbytes(arr)
Parameters :arr : [array_like] Input array.
Return : [int] Total bytes consumed by the elements of the array.
Code #1 :
# Python program explaining# numpy.ndarray.nbytes() function  # importing numpy as geek import numpy as geek  arr = geek.zeros((1, 2, 3), dtype = geek.complex128)  gfg = arr.nbytes  print (gfg)
Output :
96


 Code #2 :
# Python program explaining# numpy.ndarray.nbytes() function  # importing numpy as geek import numpy as geek  arr = geek.random.rand(10000, 50)  gfg = arr.nbytes  print (gfg)
Output :
4000000


Python numpy-ndarray
Python-numpy
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()
Why does a nested loop perform much faster than the flattened one? - GeeksforGeeks

22 Jul, 2021
Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.  
In this article, we will see why does a nested loop performs better than the flattened one. But first, let’s see what is a nested loop and what is a flattened loop.
Nested loops are the logical structure in computer programming and coding. In which one loop statement is inside another loop statement.
Syntax:
for [iter_1] in [sequence_1]:
    for [iter_2] in [sequence_2]:
          
          # statements of inner loop
          statements(iter_2)

    # statements of outer loop
    statements(iter_1)  
Loops have the ability to iterate over the items of any sequence, such as a list or a string.
Syntax:
for [iter] in sequence:
     statements(s)
When we run our python script, the operating system we are running on will assign a Process ID for it. It can be interrupted by system calls and its priority can be changed over time. But the system is not likely to take resources away from a process when we change memory address or values. When we run flat for loop it is assigning much fewer variables than a nested loop. So we can say that a nested loop utilizes resources more than a flat loop if they are available. 
Example:
Python3
# import moduleimport time  # flattened loopdef loop(n):    for i in range(n**3):        pass    # nested loopdef nested(n):        for i in range(n):        for j in range(n):            for k in range(n):                pass  for i in range(10, 100, 10):    start = time.time()    loop(i)    print('For flattened loop:',time.time() - start)          start = time.time()    nested(i)    print('For nested loop:',time.time() - start)    print()
Output:
For flattened loop: 2.7894973754882812e-05
For nested loop: 4.9114227294921875e-05

For flattened loop: 0.0002155303955078125
For nested loop: 0.00024271011352539062

For flattened loop: 0.0007171630859375
For nested loop: 0.0007529258728027344

For flattened loop: 0.0016894340515136719
For nested loop: 0.0012614727020263672

For flattened loop: 0.0029077529907226562
For nested loop: 0.0022766590118408203

For flattened loop: 0.004510402679443359
For nested loop: 0.003597736358642578

For flattened loop: 0.007539272308349609
For nested loop: 0.0057599544525146484

For flattened loop: 0.01167440414428711
For nested loop: 0.008468151092529297

For flattened loop: 0.016645431518554688
For nested loop: 0.01381683349609375
We can see that the time taken by the nested loop decreases for the increasing value of n.
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
3D Contour Plotting in Python using Matplotlib - GeeksforGeeks

21 Apr, 2020
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let’s look at a 3d contour diagram of a 3d cosine function. The code is attached for reference.
Example 1:
from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib import cmimport math  x = [i for i in range(0, 200, 100)]y = [i for i in range(0, 200, 100)]  X, Y = np.meshgrid(x, y)Z = []for i in x:    t = []    for j in y:        t.append(math.cos(math.sqrt(i*2+j*2)))    Z.append(t)  fig = plt.figure()ax = plt.axes(projection='3d')ax.contour3D(X, Y, Z, 50, cmap=cm.cool)ax.set_xlabel('a')ax.set_ylabel('b')ax.set_zlabel('c')ax.set_title('3D contour for cosine')plt.show()
Output:
Example 2: Let’s look at another 3d diagram for better understanding of the concept. This time, of a 3d tan function.
from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib import cmimport math  x = [i for i in range(0, 200, 100)]y = [i for i in range(0, 200, 100)]  X, Y = np.meshgrid(x, y)Z = []for i in x:    t = []    for j in y:        t.append(math.tan(math.sqrt(i*2+j*2)))    Z.append(t)  fig = plt.figure()ax = plt.axes(projection='3d')ax.contour3D(X, Y, Z, 50, cmap=cm.cool)ax.set_xlabel('a')ax.set_ylabel('b')ax.set_zlabel('c')ax.set_title('3D contour for tan')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Querying internal array size in MongoDB?

You can use the $size operator for internal array size in MongoDB. The syntax is as follows:
db.internalArraySizeDemo.aggregate(
   [
      {
         $group: {
            _id:yourObjectIdValue,
            anyFieldName: {$first: {$size: "$yourArrayName" }}
         }
      }
   ]
);
To understand the above syntax, let us create a collection with some documents. The query to
create a collection with documents are as follows:
>db.internalArraySizeDemo.insertOne({"EmployeeName":"Mike","EmployeeTechnology":["Jav
a Web Development","Python Web Development"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6eff586fd07954a48906b2")
}
> db.internalArraySizeDemo.insertOne({"EmployeeName":"Sam","EmployeeTechnology":["C
with Graphics","Game Development with C++ Language","MatLab"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6effcd6fd07954a48906b3")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.internalArraySizeDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6eff586fd07954a48906b2"),
   "EmployeeName" : "Mike",
   "EmployeeTechnology" : [
      "Java Web Development",
      "Python Web Development"
   ]
}
{
   "_id" : ObjectId("5c6effcd6fd07954a48906b3"),
   "EmployeeName" : "Sam",
   "EmployeeTechnology" : [
      "C with Graphics",
      "Game Development with C++ Language",
      "MatLab"
   ]
}
Here is the query to get the internal array size with the help of $size operator:
> db.internalArraySizeDemo.aggregate(
...    [
...       {
...          $group: {
...             _id:ObjectId("5c6eff586fd07954a48906b2"),
...             EmployeeTechnology_count: {$first: {$size: "$EmployeeTechnology" }}
...          }
...       }
...    ]
... );
The following is the output:
{ "_id" : ObjectId("5c6eff586fd07954a48906b2"), "EmployeeTechnology_count" : 2 }
strip - Unix, Linux Command

strip modifies the files named in its argument,
rather than writing modified copies under different names.





          -w -K !foo -K fo*



would cause strip to only keep symbols that start with the letters
fo, but to discard the symbol foo.



The intention is that this option will be used in conjunction with
--add-gnu-debuglink to create a two part executable.  One a
stripped binary which will occupy less space in RAM and in a
distribution and the second a debugging information file which is only
needed if debugging abilities are required.  The suggested procedure
to create these files is as follows:



Note - the choice of .dbg as an extension for the debug info
file is arbitrary.  Also the --only-keep-debug step is
optional.  You could instead do this:



ie the file pointed to by the --add-gnu-debuglink can be the
full executable.  It does not have to be a file created by the
--only-keep-debug switch.



Note - this switch is only intended for use on fully linked files.  It
does not make sense to use it on object files where the debugging
information may be incomplete.  Besides the gnu_debuglink feature
currently only supports the presence of one filename containing
debugging information, not multiple filenames on a one-per-object-file
basis.



Options in file are separated by whitespace.  A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes.  Any character (including a
backslash) may be included by prefixing the character to be included
with a backslash.  The file may itself contain additional
@file options; any such options will be processed recursively.


Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts.  A copy of the license is included in the
section entitled GNU Free Documentation License.











Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to display only hour and minutes in MySQL?

To display only hour and minutes, use DATE_FORMAT() and set format specifiers as in the below syntax −
select date_format(yourColumnName,'%H:%i') as anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable1527
   -> (
   -> ArrivalDatetime datetime
   -> );
Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1527 values('2019-01-10 12:34:45');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1527 values('2018-12-12 11:00:34');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1527 values('2019-03-21 04:55:56');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1527;
This will produce the following output −
+---------------------+
| ArrivalDatetime     |
+---------------------+
| 2019-01-10 12:34:45 |
| 2018-12-12 11:00:34 |
| 2019-03-21 04:55:56 |
+---------------------+
3 rows in set (0.00 sec)
Following is the query to display only hour and minutes −
mysql> select date_format(ArrivalDatetime,'%H:%i') as HourAndMinutes from DemoTable1527;
This will produce the following output −
+----------------+
| HourAndMinutes |
+----------------+
| 12:34          |
| 11:00          |
| 04:55          |
+----------------+
3 rows in set (0.00 sec)
Adding MySQL to Windows Path

Environment variables can be set at the command prompt. This is done to affect the current invocation of the command processor, or to permanently set to affect the future invocations. To set a variable permanently, it can be set in a startup file or with the help of the interface provided by the system for the same purpose. The documentation of the command interpreter needs to be consulted for specific details.
To specify a value for an environment variable, the syntax relevant for the command processor needs to be used.
The command to set environment variables can be executed at the command prompt which will take effect immediately, but the settings will last as long as the user is logged in. Once they log out, the changes are lost.
If the MySQL programs are installed in /usr/local/mysql/bin and the user wishes to make it easy to invoke these programs, the value of the PATH environment variable can be set to include that directory.
Before trying to add MySQL to Windows path, ensure that MySQL has been installed properly.
Below are the steps to add MySQL to path −
Step1 − Locate the mysql.exe file. We found in the following location −
C:\Program Files\MySQL\MySQL Server 8.0\bin
Step 2 − Press Start and type “Environment Variables”. Click −
Step 3 − Under ‘Advanced’, click on ‘Environment Variables’ −
Step 4 − Locate the ‘System variables’ and double-click on “Path”:
Step 5 − Click on “New” −
Add the same path and click OK −
C:\Program Files\MySQL\MySQL Server 8.0\bin
The new PATH value should be available to any new command shell the user opens now. This will allow the user to invoke any MySQL executable program by typing its name at the DOS prompt from any directory on the system.