code-rag-bench/online-tutorials huggingface dataset:
How to use classes in other package in Java

You can understand it using an example where a Boss class is defined in payroll package.
package payroll;
public class Boss {
   public void payEmployee(Employee e) {
      e.mailCheck();
   }
}
if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example −
payroll.Employee
The package can be imported using the import keyword and the wildcard (*). For example −
import payroll.*;
The class itself can be imported using the import keyword. For example −
import payroll.Employee;
How can Tensorflow be used to configure the dataset for performance?

The flower dataset can be configured for performance with the help of buffer prefetch, shuffle method, and cache method. Buffered prefetching can be used to ensure that the data can be taken from disk without having I/O become blocking. Dataset.cache() keeps the images in memory after they have been loaded off disk during the first epoch. Dataset.prefetch() will overlap the data preprocessing and model execution while training.
Read More:
What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?
The Keras Sequential API is used, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor.
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.
print("Configuring the dataset for better performance")
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
Code credit: https://www.tensorflow.org/tutorials/images/classification
Configuring the dataset for better performance
Configuring the dataset for better performance
The concept of buffered prefetching can be used so that the data can be taken from disk without having I/O become blocking.
There are two important methods that can be used when loading data.cache() keeps the images in memory after they have been loaded off disk during the first epoch.This will ensure that the dataset doesn't become a bottleneck when the model is being trained.If the dataset is too large to fit into memory, this method can be used to create a performant on-disk cache.prefetch() will overlap the data preprocessing and model execution while training.
cache() keeps the images in memory after they have been loaded off disk during the first epoch.
This will ensure that the dataset doesn't become a bottleneck when the model is being trained.
If the dataset is too large to fit into memory, this method can be used to create a performant on-disk cache.
prefetch() will overlap the data preprocessing and model execution while training.
Cursors in Oracle DBMS

When a SQL statement is executed in Oracle, the temporary context area is created. This area contains all the relevant information relating to the statement and its execution. The cursor is a pointer to this context area and allows the PL/SQL program to control this area.
There are two types of Cursors.
Implicit Cursors
Explicit Cursors
Let us begin with Implicit Cursors −
Whenever an SQL statement is executed, the implicit cursors are automatically created. This happens if there is no explicit cursor for the particular statement. Implicit cursors cannot be controlled by the programmers.
There are many different attributes for Implicit Cursors. Some of them are −
If one or more records were fetched successfully with commands such as INSERT, UPDATE, DELETE etc., then it returns TRUE. Otherwise it returns FALSE.
This is the direct opposite of %FOUND. If one or more records were fetched successfully with commands such as INSERT, UPDATE, DELETE etc., then it returns FALSE. Otherwise it returns TRUE.
This returns the number of rows that are affected by different commands such as INSERT, UPDATE, DELETE etc.
This returns TRUE if the cursor is open and false otherwise. However, for implicit cursors, the value is always FALSE because the cursor is closed immediately after executing its instruction.
While implicit cursors were automatically created, explicit cursors are specifically created by the programmers. There definition is provided in the declaration section of the PL/SQL block.
Creating an explicit cursor has the following steps −
The cursor is declared as follows. Here, the cursor is c_student −
CURSOR c_student IS
Select Stu_ID,Stu_Name from Student;
The cursor is opened as follows −
OPEN c_student;
One row at a time is accessed while fetching the cursor. Fetching the cursor is done as follows −
FETCH c_student INTO
c_stuID, c_stuName;
The allocated memory is released when the cursor is closed. This is done as follows −
CLOSE c_student;
How to change the name of a data frame in R?

To change the name of a data frame, we can set the original name to the new name. Now both of the names can be used. Most of the times the purpose behind changing the name of the data frame is that, the original name does not seem to be a valid name based on the characteristics of the data. For example, if we have normally distributed columns in the data frame then we can name it as normal_distribution. This will help everyone to understand the data belongs to normal distribution.
 Live Demo
set.seed(24)
x<−rnorm(20,1,0.25)
df1<−data.frame(x)
df1
      x
1 0.8635298
2 1.1341463
3 1.1049058
4 0.8540932
5 1.2118650
6 1.0665055
7 1.1111463
8 0.8833762
9 0.7879075
10 1.0005780
11 0.6707730
12 1.1495673
13 0.8094464
14 0.6427274
15 1.0830611
16 0.8827348
17 0.9162533
18 1.3840630
19 1.1524986
20 1.1290839
Changing the name of df1 to Normal_Distribution −
Normal_Distribution<−df1
Normal_Distribution
     x
1 0.8635298
2 1.1341463
3 1.1049058
4 0.8540932
5 1.2118650
6 1.0665055
7 1.1111463
8 0.8833762
9 0.7879075
10 1.0005780
11 0.6707730
12 1.1495673
13 0.8094464
14 0.6427274
15 1.0830611
16 0.8827348
17 0.9162533
18 1.3840630
19 1.1524986
20 1.1290839
 Live Demo
y<−sample(0:5,20,replace=TRUE)
df2<−data.frame(y)
df2
  y
1 4
2 2
3 2
4 3
5 3
6 1
7 1
8 2
9 0
10 4
11 4
12 3
13 5
14 1
15 0
16 0
17 4
18 2
19 2
20 5
Changing the name of df2 to Random_Sample −
Random_Sample<−df2
Random_Sample
  y
1 4
2 2
3 2
4 3
5 3
6 1
7 1
8 2
9 0
10 4
11 4
12 3
13 5
14 1
15 0
16 0
17 4
18 2
19 2
20 5
SQLAlchemy Core - Selecting Rows

In this chapter, we will discuss about the concept of selecting rows in the table object.
The select() method of table object enables us to construct SELECT expression.
s = students.select()
The select object translates to SELECT query by str(s) function as shown below −
'SELECT students.id, students.name, students.lastname FROM students'
We can use this select object as a parameter to execute() method of connection object as shown in the code below −
result = conn.execute(s)
When the above statement is executed, Python shell echoes following equivalent SQL expression −
SELECT students.id, students.name, students.lastname
FROM students
The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method.
row = result.fetchone()
All selected rows in the table can be printed by a for loop as given below −
for row in result:
   print (row)
The complete code to print all rows from students table is shown below −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()

students = Table(
   'students', meta, 
   Column('id', Integer, primary_key = True), 
   Column('name', String), 
   Column('lastname', String), 
)

s = students.select()
conn = engine.connect()
result = conn.execute(s)

for row in result:
   print (row)
The output shown in Python shell is as follows −
(1, 'Ravi', 'Kapoor')
(2, 'Rajiv', 'Khanna')
(3, 'Komal', 'Bhandari')
(4, 'Abdul', 'Sattar')
(5, 'Priya', 'Rajhans')

The WHERE clause of SELECT query can be applied by using Select.where(). For example, if we want to display rows with id >2
s = students.select().where(students.c.id>2)
result = conn.execute(s)

for row in result:
   print (row)
Here c attribute is an alias for column. Following output will be displayed on the shell −
(3, 'Komal', 'Bhandari')
(4, 'Abdul', 'Sattar')
(5, 'Priya', 'Rajhans')

Here, we have to note that select object can also be obtained by select() function in sqlalchemy.sql module. The select() function requires the table object as argument.
from sqlalchemy.sql import select
s = select([users])
result = conn.execute(s)

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Command to show the database currently being used in MongoDB?

The command to show the database currently used in MongoDB is the following −
db;
Let us first check how many databases are present. The query is as follows −
> show dbs;
The following is the output displaying all the databases −
admin 0.000GB
config 0.000GB
local 0.000GB
sample 0.000GB
sampleDemo 0.000GB
studentSearch 0.000GB
test 0.003GB
Now, we have the list of all databases. Let us use the above syntax to check current database. The query is as follows −
> db;
The following is the output −
sample
Look at the above sample output, we are currently using ‘sample’ database. Let us switch the database and verify again the correctness of command db.
The query is as follows to switch database.
> use test;
The following is the output −
switched to db test

Look at the above sample output, we have changed the database from ‘sample’ to ‘test’.
Now let us once again check the current database name. The query is as follows −
> db;
The following is the output −
test
Use the function getName(). The query is as follows −
> db.getName();
The following is the output −
test

You can use the current command to check the current working database −
The query is as follows −
> db.current;
The following is the output −
test.current
Creating 3D Text using React-three-fiber

In this article, we will see how to create a 3D text using react-threefiber. We will first download the font of JSON and then we will add it in our Text Geometry object. We will add orbit control to it which will allow moving the text on the screen and view the 3D text properly. So, let's get started.
First, download important libraries −
npm i --save @react-three/fiber three
This library react-three/fiber will be used to add webGL renderer to the website and to connect threejs and React.
Now install a typeface font JSON and put it inside “src” folder. You can download a font from google fonts and go to https://gero3.github.io/facetype.js/ for converting it into JSON.
Add the following lines of code in App.js −
import React, { useEffect, useRef } from "react";
import { Canvas, useThree ,useLoader } from "@reactthree/fiber";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as THREE from "three";
import Roboto from "./Roboto_Regular.json"
import "./App.css";

const CameraController = () => {
   const { camera, gl } = useThree();
   useEffect(
      () => {
         const controls = new OrbitControls(camera, gl.domElement);
         controls.minDistance = 3;
         controls.maxDistance = 20;
         return () => {
            controls.dispose();
         };
      },
      [camera, gl]
   );
   return null;
};
function Text3d(){
   const font = new THREE.FontLoader().parse(Roboto);
   const textOptions = {
      font,
      size: 5,
      height: 1
   };
   return (
      <mesh>
         <textGeometry attach='geometry' args={['three.js', text Options]} />
         <meshStandardMaterial attach='material' color="hotpink" />
       </mesh>
    )
}
export default function App(){
   return (
      <Canvas>
         <CameraController/>
         <ambientLight />
         <Text3d/>
      </Canvas>
   );
};
We first loaded the JSON font with “Roboto” variable and then inside our function, we parsed it as a font and stored it in “font” const.
Then we set its styles and other aspects in “textOptions”. Next we simply created textGeometry and passed args, and material object is used to apply styles.
It will produce the following output −
Your browser does not support HTML5 video.
How can we return multiple values from a function in C/C++?

In C or C++, we cannot return multiple values from a function directly. In this section, we will see how to use some trick to return more than one value from a function.
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.
In this example, we will see how to define a function that can return quotient and remainder after dividing two numbers from one single function.
#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) {
   *quotient = a / b;
   *remainder = a % b;
}
main() {
   int a = 76, b = 10;
   int q, r;
   div(a, b, &q, &r);
   printf("Quotient is: %d\nRemainder is: %d\n", q, r);
}
Quotient is: 7
Remainder is: 6
Jackson - Tree Model

Tree Model prepares a  in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML.
ObjectMapper provides a pointer to root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String.
//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();	
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
//create tree from JSON
JsonNode rootNode = mapper.readTree(jsonString);
Get each node using relative path to the root node while traversing tree and process the data. Consider the following code snippet traversing the tree provided the root node.
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.textValue());
 
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){

      try {
         ObjectMapper mapper = new ObjectMapper();
         String jsonString = "{\"name\":\"Mahesh Kumar\",  \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
         JsonNode rootNode = mapper.readTree(jsonString);

         JsonNode nameNode = rootNode.path("name");
         System.out.println("Name: "+ nameNode.textValue());

         JsonNode ageNode = rootNode.path("age");
         System.out.println("Age: " + ageNode.intValue());

         JsonNode verifiedNode = rootNode.path("verified");
         System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));

         JsonNode marksNode = rootNode.path("marks");
         Iterator<JsonNode> iterator = marksNode.elements();
         System.out.print("Marks: [ ");

         while (iterator.hasNext()) {
            JsonNode marks = iterator.next();
            System.out.print(marks.intValue() + " "); 
         }

         System.out.println("]");
      }
      catch (JsonParseException e) { e.printStackTrace(); }
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Tree to JSON
Tree to Java Objects
 Print
 Add Notes
 Bookmark this page
Prototype - getWidth() Method

This method finds and returns the computed width of element.
This method returns correct values on elements whose display is set to none either in an inline style rule or in an CSS stylesheet.
Note that the value returned is a number only although it is expressed in pixels.
element.getWidth();

It returns the computed width of an element.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var width = $('rectangle').getWidth();
            alert("Element width is " +  width );
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      
      <div id = "rectangle" 
         style = "font-size: 10px; width: 20em; height 10em">
         <p>This is the paragraph.</p>
      </div>
      <br />
      
      <input type = "button" value = "showResult" onclick = "showResult();"/>
   </body>
</html>
Click the button to see the result.
This is the paragraph.

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
How to search a value inside a JSON file using Jackson in Java?

The com.fasterxml.jackson.databind.node.ObjectNode class can be used to map the JSON object structure in Json content. We can search for a particular value inside the JSON file using the get() method of ObjectNode class, this method used for accessing the value of a specified field of an object node.
public JsonNode get(String fieldName)
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class ObjectNodeTest {
   public static void main(String args[]) throws Exception {
      String jsonString = "{\"Id\":101, \"name\":\"Raja Ramesh\", \"address\":\"Madhapur\"}";
      ObjectMapper mapper = new ObjectMapper();
      ObjectNode node = mapper.readValue(jsonString, ObjectNode.class);
      if(node.has("name")) {
         System.out.println("NAME: " + node.get("name"));
      }
   }
}
NAME: "Raja Ramesh"
Tryit Editor v3.7

Tryit: All list style types
How to check if a string contains only upper case letters in Python?

We can check if a string contains only upper case letters using 2 methods. First is using method isupper(). 
print( 'Hello world'.isupper())
print('HELLO'.isupper())
False
True
You can also use regexes for the same result. For matching only uppercase, we can call the re.match(regex, string) using the regex: "^[A-Z]+$". 
import re
print(bool(re.match('^[A-Z]+$', '123aAbc'))
print(bool(re.match('^[A-Z]+$', 'ABC'))
False
True
Python | Pandas DataFrame.blocks

20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.blocks attribute is synonym for as_blocks() function. It basically convert the frame to a dict of dtype -> Constructor Types that each has a homogeneous dtype.
Syntax: DataFrame.blocks
Parameter : None
Returns : dict
Example #1: Use DataFrame.blocks attribute to return a dictionary containing the data in blocks of separate data types.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],                   'Age':[14, 25, 55, 8, 21]})  # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.blocks attribute to return the block representation of the given dataframe.
# return a dictionaryresult = df.blocks  # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.blocks attribute has successfully returned a dictionary containing the data of the dataframe. Homogeneous columns are places in the same block. Example #2: Use DataFrame.blocks attribute to return a dictionary containing the data in blocks of separate data types.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.blocks attribute to return the block representation of the given dataframe.
# return a dictionaryresult = df.blocks  # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.blocks attribute has successfully returned a dictionary containing the data of the dataframe. Homogeneous columns are places in the same block.
Python pandas-dataFrame
Python pandas-dataFrame-methods
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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Convert a Set to Stream in Java

11 Dec, 2018
Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection.
Below given are some examples to understand the implementation in a better way.
Example 1 : Converting Integer HashSet to Stream of Integers.
// Java code for converting // Set to Streamimport java.util.*;import java.util.stream.Stream;  class GFG {          // Driver code    public static void main(String[] args) {          // Creating an Integer HashSet    Set<Integer> set = new HashSet<>();          // adding elements in set    set.add(2);    set.add(4);    set.add(6);    set.add(8);    set.add(10);    set.add(12);          // converting Set to Stream    Stream<Integer> stream = set.stream();          // displaying elements of Stream using lambda expression    stream.forEach(elem->System.out.print(elem+" "));          }}
Example 2 : Converting HashSet of String to stream.
// Java code for converting // Set to Streamimport java.util.*;import java.util.stream.Stream;  class GFG {          // Driver code    public static void main(String[] args) {          // Creating an String HashSet    Set<String> set = new HashSet<>();          // adding elements in set    set.add("Geeks");    set.add("for");    set.add("GeeksQuiz");    set.add("GeeksforGeeks");          // converting Set to Stream    Stream<String> stream = set.stream();          // displaying elements of Stream    stream.forEach(elem -> System.out.print(elem+" "));          }}
Note : Objects that you insert in HashSet are not guaranteed to be inserted in same order. Objects are inserted based on their hash code.
Convert Stream to Set in Java
Java - util package
Java-Collections
java-hashset
java-set
Java-Set-Programs
java-stream
Java-Stream-programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML DOM createObjectURL() method

14 Jul, 2020
The createObjectURL() method creates a DOMString containing a URL representing the object given in the parameter of the method. The new object URL represents the specified File object or Blob object.
Note: The URL lifetime is tied to the document in which it was created.
Syntax:
const url = URL.createObjectURL(object);
Parameters:
object: A File, image, or any other MediaSource object for which object URL is to be created.
Return value: A DOMString containing an object URL of that object.
Example: In this example, we will create an object URL for the image object using this method.
<!DOCTYPE html><html><head>  <meta charset="utf-8">  <title>URL.createObjectURL example</title></head><body>  <h1>GeeksforGeeks</h1>  <input type="file">  <img>  <p class="p">The URL of this image is : </p></body><script>    var Element = document.querySelector('input');    var img = document.querySelector('img');    Element.addEventListener('change', function() {      var url = URL.createObjectURL(Element.files[0]);      img.src = url;      console.log(url);      var d=document.querySelector(".p");      d.textContent+=url;});</script></html>
Output: we will select an image from local storage and then the URL of that object will be created.
Before Choosing Image:
After Choosing Image:
Checking the created URL in a new tab:
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Checking if a key exists in HTML5 Local Storage

The getitem(key) takes value for one parameter and returns the value associated with the key. The given key is present in the list associated with the object.
if(localStorage.getItem("user")===null) {
   //...
}
But if the key is not present in the list then it passes null value by using the below-given code
You can also follow the below-given procedure −
if("user" in localStorage){
   alert('yes');
} else {
   alert('no');
}
How to Map Ports in Docker? - GeeksforGeeks

22 Jun, 2021
In docker, all the application in the container runs on particular ports when you run a container. If you want to access the particular application with the help of port number you need to map the port number of the container with the port number of the docker host.
In the implementation, we are going to download a Jenkins container from the docker hub and map the Jenkins container port number with the docker host port number.
Sign-up to your docker hub repository.
Sign-up in docker hub
Search for the Jenkins image and use the docker pull command to download the Jenkins image on your local server.
Download Jenkins’s image using the below command:
sudo docker pull jenkins
To see the ports exposed by the Jenkins container type docker inspect command.
docker inspect Container/image
In this step, we run Jenkins and map the port by changing the docker run command by adding the p option which specifies the port mapping.
sudo docker run -p 8080:8080 50000:500000 jenkins
On the left-hand side, it is the Docker host port number and on the right-hand side Docker container number.
These are all the steps required to map the port number of the container to the port number of the docker host. 
rajeev0719singh
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
ML | Underfitting and Overfitting
Clustering in Machine Learning
Getting started with Machine Learning
C program to print a string without any quote (single or double) in the program - GeeksforGeeks

31 Jan, 2022
Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console.
 
The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it.  
C
// C program to print a string without// quote in the program#include <stdio.h>#define get(x) #xint main(){    printf(get(vignesh));    return 0;}
Output:  
vignesh
This article is contributed by Vignesh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or 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. 
germanshephered48
C-Macro & Preprocessor
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Converting Strings to Numbers in C/C++
Substring in C++
rand() and srand() in C/C++
std::string class in C++
Enumeration (or enum) in C
TCP Server-Client implementation in C
Count words in a given string in C++

We are given with a sentence or string containing words that can contain spaces, new line characters and tab characters in between. The task is to calculate the total number of words in a string and print the result.
Input − string str = “welcome to\n tutorials point\t”
Output − Count of words in a string are − 4
Explanation − There are four words in a string i.e. welcome, to, tutorials, point and the rest are spaces(“ ”), next line character(\n) and tab character(\t) present between the words.
Input − string str = “\nhonesty\t is the best policy”
Output − Count of words in a string are − 5
Explanation − There are four words in a string i.e. honesty, is, the, best, policy and the rest are spaces(“ ”), next line character(\n) and tab character(\t) present between the words.
There can be multiple solutions for this. So let’s first look at the simpler approach we had used in the below code −
Create an array of char type for storing the string let’s say, str[]
Create an array of char type for storing the string let’s say, str[]
Declare two temporary variable one is count to count the number of words in a string and temp to perform the flag operations
Declare two temporary variable one is count to count the number of words in a string and temp to perform the flag operations
Start loop While str is not null
Start loop While str is not null
Inside the loop, check IF *str = space OR *str = next line OR *str = tab then set temp to 0
Inside the loop, check IF *str = space OR *str = next line OR *str = tab then set temp to 0
Else If temp = 0 then set temp to 1 and increment the value of count by 1
Else If temp = 0 then set temp to 1 and increment the value of count by 1
Increment the str pointer by 1
Increment the str pointer by 1
Return the value in count
Return the value in count
Print the result
Print the result
 Live Demo
#include
using namespace std;
//count words in a given string
int total_words(char *str){
   int count = 0;
   int temp = 0;
   while (*str){
      if (*str == ' ' || *str == '\n' || *str == '\t'){
         temp = 0;
      }
      else if(temp == 0){
         temp = 1;
         count++;
      }
      ++str;
   }
   return count;
}
int main(){
   char str[] = "welcome to\n tutorials point\t";
   cout<<"Count of words in a string are: "<<total_words(str);
   return 0;
}
If we run the above code it will generate the following output −
Count of words in a string are: 4
StringWriter vs StringReader in C#?

StringReader and StringWriter derive from TextReader and TextWriter
StringWriter is used for writing into a string buffer. It implements a TextWriter for writing information to a string.
For StringWriter −
StringWriter sWriter = new StringWriter();
while(true) {
   myChar = strReader.Read();
   if(myChar == -1) break;

   convertedChar = Convert.ToChar(myChar);
   if(convertedChar == '.') {
      strWriter.Write(".\n\n");

      sReader.Read();
      sReader.Read();
   }else {
      sWriter.Write(convertedChar);
   }
}
}
StringReader to read a string −
StringBuilder sbuilder = new StringBuilder();

// append
sbuilder.AppendLine("Line one characters");
sbuilder.AppendLine("Line two characters");
sbuilder.AppendLine("Line three characters");

// read string
using (StringReader sReader = new StringReader(sbuilder.ToString())) {
   string readString = await sReader.ReadToEndAsync();
   Console.WriteLine(readString);
}
Python Program for Linear Search

In this article, we will learn about the Linear Search and its implementation in Python 3.x. Or earlier.
Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]
If x matches with any of the element, return the index value.
If x doesn’t match with any of elements in arr[] , return -1 or element not found.
Now let’s see the visual representation of the given approach −
 Live Demo
def linearsearch(arr, x):
   for i in range(len(arr)):
      if arr[i] == x:
         return i
      return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))
element found at index 6
The scope of the variables are shown in the figure −
In this article, we learned about the mechanism of linear search in Python3.x. Or earlier.
Check if a String is empty ("") or null in Java

To check if a string is null or empty in Java, use the == operator.
Let’s say we have the following strings.
String myStr1 = "Jack Sparrow";
String myStr2 = "";
Let us check both the strings now whether they are null or empty. Result will be a boolean.
res = (myStr1 == null || myStr1.length() == 0);
res = (myStr2 == null || myStr2.length() == 0);
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String myStr1 = "Jack Sparrow";
      String myStr2 = "";
      boolean res;
      res = (myStr1 == null || myStr1.length() == 0);
      System.out.println("String 1 is null or empty? "+res);
      res = (myStr2 == null || myStr2.length() == 0);
      System.out.println("String 2 is null or empty? "+res);
   }
}
String 1 is null or empty? False
String 2 is null or empty? True
Boss Fight in Python

Suppose we have a binary list called fighters and another list of binary lists called bosses. In fighters list the 1 is representing a fighter. Similarly, in bosses list 1 representing a boss. That fighters can beat a boss’s row if it contains more fighters than bosses. We have to return a new bosses matrix with defeated boss rows removed.
So, if the input is like fighters = [0,1,1]
then the output will be
To solve this, we will follow these steps −
fighter_cnt := sum of all elements of fighters
fighter_cnt := sum of all elements of fighters
result := a new list
result := a new list
for each row in bosses, doif fighter_cnt <= sum of each element in row, theninsert row at the end of result
for each row in bosses, do
if fighter_cnt <= sum of each element in row, theninsert row at the end of result
if fighter_cnt <= sum of each element in row, then
insert row at the end of result
insert row at the end of result
return result
return result
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, fighters, bosses):
      fighter_cnt = sum(fighters)
      result = []
      for row in bosses:
         if fighter_cnt <= sum(row):
            result.append(row)
      return result
ob = Solution()
fighters = [0, 1, 1]
bosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
print(ob.solve(fighters, bosses))
[0, 1, 1], [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
[[0, 1, 1], [1, 1, 1]]
Immutable annotation in Dart Programming

We know that const keyword provides immutability in objects. But what about the cases, where we want the entire class to be immutable in nature.
In such cases, we make use of the immutable annotation that is present inside the meta package of dart library.
import 'pacakge:meta/meta.dart';

@immutable
class User {
   String name;
}
It should be noted that once we declare any class with the immutable notation, all its object and the object properties and methods will be immutable as well.
Consider the example shown below −
 Live Demo
import 'pacakge:meta/meta.dart';

@immutable
class User {
   final String name;
   User(this.name);
   User.withPrint(this.name){
      print('New user added ${this.name}');
   }
}

void main(){
   var u = User.withPrint('Mukul');
   u = {};
   print(u.name);
}
In the above code, we declared the entire class as immutable and hence any object that we instantiate through it will be immutable as well. Inside the main function, we are trying to assign a different value to the variable u, which will give us a compile error.
Error: Overriding not allowed, as 'u' is immutable.
   u = {};
   ^^^^
How to define alternate names to a field using Jackson in Java?

The @JsonAlias annotation can define one or more alternate names for the attributes accepted during the deserialization, setting the JSON data to a Java object. But when serializing, i.e. getting JSON from a Java object, only the actual logical property name is used instead of the alias.
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonAlias
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class ObjectToJsonTest {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      Technology tech = new Technology("Java", "Oracle");
      Employee emp = new Employee(110, "Raja", tech);
      String jsonWriter = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonWriter);
   }
}
// Technology class
class Technology {
   @JsonProperty("skill")
   private String skill;
   @JsonProperty("subSkill")
   @JsonAlias({"sSkill", "mySubSkill"})
   private String subSkill;
   public Technology(){}
   public Technology(String skill, String subSkill) {
      this.skill = skill;
      this.subSkill = subSkill;
   }
   public String getSkill() {
      return skill;
   }
   public void setSkill(String skill) {
      this.skill = skill;
   }
   public String getSubSkill() {
      return subSkill;
   }
   public void setSubSkill(String subSkill) {
      this.subSkill = subSkill;
   }
}
// Employee class
class Employee {
   @JsonProperty("empId")
   private Integer id;
   @JsonProperty("empName")
   @JsonAlias({"ename", "myename"})
   private String name;
   @JsonProperty("empTechnology")
   private Technology tech;
   public Employee(){}
   public Employee(Integer id, String name, Technology tech){
      this.id = id;
      this.name = name;
      this.tech = tech;
   }
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public Technology getTechnology() {
      return tech;
   }
   public void setTechnology(Technology tech) {
      this.tech = tech;
   }
}
{
 "technology" : {
 "skill" : "Java",
 "subSkill" : "Oracle"
 },
 "empId" : 110,
 "empName" : "Raja",
 "empTechnology" : {
 "skill" : "Java",
 "subSkill" : "Oracle"
 }
}
Java program to find if the given number is a leap year?

Finding a year is a leap or not is a bit tricky. We generally assume that if a year number is evenly divisible by 4 is a leap year. But it is not the only case. A year is a leap year if −
1. It is evenly divisible by 100
2. If it is divisible by 100, then it should also be divisible by 400
3. Except this, all other years evenly divisible by 4 are leap years.
1. Take integer variable year
2. Assign a value to the variable
3. Check if the year is divisible by 4 but not 100, DISPLAY "leap year"
4. Check if the year is divisible by 400, DISPLAY "leap year"
5. Otherwise, DISPLAY "not leap year"
import java.util.Scanner;
public class LeapYear {
   public static void main(String[] args){
      int year;
      System.out.println("Enter an Year :: ");
      Scanner sc = new Scanner(System.in);
      year = sc.nextInt();

      if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
         System.out.println("Specified year is a leap year");
      else
         System.out.println("Specified year is not a leap year");
   }
}
Enter an Year ::
2020
Specified year is a leap year
Java Programming questions
31
Enter an Year ::
2017
Specified year is not a leap year
MariaDB - Table Cloning

Some situations require producing an exact copy of an existing table. The CREATE...SELECT statement cannot produce this output because it neglects things like indexes and default values.
The procedure for a duplicating a table is as follows −
Utilize SHOW CREATE TABLE to produce a CREATE TABLE statement that details the entire structure of the source table.
Utilize SHOW CREATE TABLE to produce a CREATE TABLE statement that details the entire structure of the source table.
Edit the statement to give the table a new name, and execute it.
Edit the statement to give the table a new name, and execute it.
Use an INSERT INTO...SELECT statement if you also need the table data copied.
Use an INSERT INTO...SELECT statement if you also need the table data copied.
mysql> INSERT INTO inventory_copy_tbl (
   product_id,product_name,product_manufacturer,ship_date)
   
   SELECT product_id,product_name,product_manufacturer,ship_date,
   FROM inventory_tbl;

Another method for creating a duplicate uses a CREATE TABLE AS statement. The statement copies all columns, column definitions, and populates the copy with the source table's data.
Review its syntax given below −
CREATE TABLE clone_tbl AS
   SELECT columns
   FROM original_tbl
   WHERE conditions];

Review an example of its use below −
CREATE TABLE products_copy_tbl AS
   SELECT *
   FROM products_tbl;

 Print
 Add Notes
 Bookmark this page
Batch Script - XCOPY

This batch command copies files and directories in a more advanced way.
Xcopy [source][destination]

Xcopy c:\lists.txt c:\tp\
The above command will copy the file lists.txt to the tp folder.
 Print
 Add Notes
 Bookmark this page
\textbf - Tex Command

\textbf - Used to produce text-mode material in boldface within a mathematical expression.
{ \textbf #1}
\textbf command is used to produce text-mode material in boldface within a mathematical expression.

\textbf{\alpha in textbf mode }\alpha

\alpha in textbf mode α



\textbf{\alpha in textbf mode }\alpha

\alpha in textbf mode α


\textbf{\alpha in textbf mode }\alpha

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Art module in Python - GeeksforGeeks

12 Nov, 2020
Art package is used to print decorative art’s on the terminal as well as to save in file and a word can be represented by ” | “and can be saved in a file
This module doesn’t come built-in with Python. To install this type the below command in the terminal. 
 pip install art 

Function:
Printing Normal and random arts on terminal and aprint() functionPrinting a word in form of | and tprint() function also saving it in text/pdf file
Printing Normal and random arts on terminal and aprint() function
Printing a word in form of | and tprint() function also saving it in text/pdf file
Printing art on terminal:
Syntax: art ( name of art, number is integer denoting number of arts in string )
Python3
# import modulefrom art import *  # return multiple art as strart__0=art("woman",number=10)  print(art__0)
Output: 
Random generation of arts:
Python3
from art import *  print(art("random"))
Output:
Using aprint() function
Here, you can directly print arts just like the print function you print something 
Python3
from art import *    print("Buttterfly by art :  ",end=" ")  aprint("butterfly")print()
Output:
Now Let’s move towards the capability of python text to art 
Python3
# import modulefrom art import *  # Return ASCII text with block font# If font=None then there is no blockArt = text2art("GFG", font='block', chr_ignore=True)  print(Art)
Output:
tprint() function is same as print() function it prints the text into ASCII format
Python3
# import modulefrom art import *  # random large text to art representation # This art will be random every timetprint("GFG","rnd-xlarge")
Output:
We can save this to a txt file too by using tsave() function. 
Syntax: tsave(“STRING”, OUTPUT FILE NAME OR PATH)
Python3
# import modulefrom art import *  Filename = tsave(    "GEEKSFORGEEKS", filename="Output_in_txt_file_using_tsave().txt")
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Types of Java comments.

Java supports single-line, multi-line comments, and documentation comments. Documentation comments are understood by Javadoc tool and can be used to create HTML based documentation.
/** is known as documentation comments. It is used by Javadoc tool while creating the documentation for the program code.
/* is used for multi-line comments.
// is used for single line comments
Live Demo
/**
   * This is a documentation comment.
   * This is my first Java program.
   * This will print 'Hello World' as the output
   * This is an example of multi-line comments.
*/
public class MyFirstJavaProgram {
   public static void main(String[] args) {
      /* This is an example of multi line comment. */
 
      // This is a single line comment.
      System.out.println("Hello World");
   }
}
How to change the color of X-axis label using ggplot2 in R?

The default color of labels is black but we might want to change that color to something else so that we can get attention of the viewer to the labels if it is needed. To change the color of X-axis label using ggplot2, we can use theme function that has axis.title.x argument which can be used for changing the color of the label values.
Consider the below data frame −
 Live Demo
x<−rnorm(20,5,0.25)
y<−rnorm(20,5,0.004)
df<−data.frame(x,y)
df
      x       y
1 5.030380 4.997751
2 5.240119 4.998680
3 4.544677 4.999195
4 4.858193 4.998952
5 5.071308 5.001092
6 5.512129 4.998037
7 5.236292 5.002558
8 5.081739 5.001903
9 4.940688 5.005155
10 4.437274 5.002876
11 5.472674 4.997229
12 4.813980 5.005284
13 4.859050 4.993907
14 5.353379 4.998850
15 5.537771 4.988465
16 5.302592 4.999421
17 5.486402 4.991891
18 5.121558 5.003857
19 4.908864 5.003393
20 5.137028 5.008340
Loading ggplot2 package and creating a scatterplot −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating the scatterplot with X-axis label in red color −
ggplot(df,aes(x,y))+geom_point()+theme(axis.title.x=element_text(colour="red"))