code-rag-bench/online-tutorials huggingface dataset:
Python 3 -File close() Method

The method close() closes the opened file. A closed file cannot be read or written any more. Any operation, which requires that the file be opened will raise a ValueError after the file has been closed. Calling close() more than once is allowed.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
Following is the syntax for close() method −
fileObject.close()

NA
This method does not return any value.
The following example shows the usage of close() method.
#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)

# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file:  foo.txt


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
inheritance(is-a) v/s composition (has-a) relationship in Java

IS-A is a way of saying − This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. 
public class Animal {
}
public class Mammal extends Animal {
}
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}
Now, if we consider the IS-A relationship, we can say −
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Live Demo
class Animal {
} class Mammal extends Animal {
} class Reptile extends Animal {
} public class Dog extends Mammal {
   public static void main(String args[]) {
      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();
      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
    }
}
This will produce the following result −
true
true
true
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Let's  look into an example −
public class Vehicle{ }
public class Speed{ }
public class Van extends Vehicle {
   private Speed sp;  
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.
In an Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
Unity - Rigidbodies and Physics

The main issue with the collisions in the last chapter was with the code. We will now modify the values of the GameObject’s position directly. We are simply adding a value to the position, if the player is pressing a key. We need a way to make the player move in such a way that it reacts properly to boundaries and other GameObjects.
To do so, we need to understand what rigidbodies are. Rigidbodies are components that allow a GameObject to react to real-time physics. This includes reactions to forces and gravity, mass, drag and momentum.
You can attach a Rigidbody to your GameObject by simply clicking on Add Component and typing in Rigidbody2D in the search field.
Clicking on Rigidbody2D will attach the component to your GameObject. Now that it is attached, you will notice that many new fields have opened up.
With the default settings, the GameObject will fall vertically down due to gravity. To avoid this, set the Gravity Scale to 0.
Now, playing the game will not show any visible difference, because the GameObject does not have anything to do with its physics component yet.
To solve our problem, let us open our code again, and rewrite it.
public class Movement : MonoBehaviour {
   public float speed;
   public Rigidbody2D body;
   // Update is called once per frame
   void Update() {
      float h = Input.GetAxisRaw(“Horizontal”);
      float v = Input.GetAxisRaw(“Vertical”);
      body.velocity = new Vector2(h * speed, v * speed);
   }
}
We can see that we create a reference to a Rigidbody2D in the declarations, and our update code works on that reference instead of the Object’s transform. This means that the Rigidbody has now been given the responsibility of moving.
You may expect the body reference to throw NullReferenceException, since we have not assigned anything to it. If you compile and run the game as is, you will get the following error on the bottom left of the editor
To fix this, let us consider the component created by the script. Remember that public properties create their own fields in Unity, as we did with the speed variable.
Adjust the speed to a higher value, around 5, and play the game.
Your collisions will now work correctly!

    119 Lectures 
     23.5 hours 

 Raja Biswas

    58 Lectures 
     10 hours 

 Three Millennials

    16 Lectures 
     1 hours 

 Peter Jepson

    23 Lectures 
     2.5 hours 

 Zenva

    21 Lectures 
     2 hours 

 Zenva

    43 Lectures 
     9.5 hours 

 Raja Biswas
 Print
 Add Notes
 Bookmark this page
Python Deep Learning - Environment

In this chapter, we will learn about the environment set up for Python Deep Learning. We have to install the following software for making deep learning algorithms.
Python 2.7+
Scipy with Numpy
Matplotlib
Theano
Keras
TensorFlow
It is strongly recommend that Python, NumPy, SciPy, and Matplotlib are installed through the Anaconda distribution. It comes with all of those packages.
We need to ensure that the different types of software are installed properly.
Let us go to our command line program and type in the following command −
$ python
Python 3.6.3 |Anaconda custom (32-bit)| (default, Oct 13 2017, 14:21:34)
[GCC 7.2.0] on linux

Next, we can import the required libraries and print their versions −
import numpy
print numpy.__version__

1.14.2

Before we begin with the installation of the packages − Theano, TensorFlow and Keras, we need to confirm if the pip is installed. The package management system in Anaconda is called the pip.
To confirm the installation of pip, type the following in the command line −
$ pip

Once the installation of pip is confirmed, we can install TensorFlow and Keras by executing the following command −
$pip install theano
$pip install tensorflow
$pip install keras
Confirm the installation of Theano by executing the following line of code −
$python –c “import theano: print (theano.__version__)”
1.0.1

Confirm the installation of Tensorflow by executing the following line of code −
$python –c “import tensorflow: print tensorflow.__version__”

1.7.0

Confirm the installation of Keras by executing the following line of code −
$python –c “import keras: print keras.__version__”
Using TensorFlow backend

2.1.5


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
New ways to Assign values to Variables in C++ 17 ?

In C++ 17, there are introduced two new ways by which a programmer can assign values to a variable or declared them. In this update, elser then the classical way of assigning values to a variable the following two ways to initialise values.
Initially the assignment operator ‘=’ is used for assignment and declaration of a variable. assignment of a variable using = looks like,
datatype variable_name = value;
Example,
int val = 243;
In uniform initialisation of variables we do not use the ‘=’ operator. the value is enclosed inside a pair of curly braces ' {} '. Value inside the pair of curly braces is passed to the variable.
data_type variable_name{ value};
 Live Demo
#include <iostream>
using namespace std;
int main() {
   cout<<"Declaring Values using uniform initialization \n";
   int val1{ 367 };
   cout << "val1 = " <<val1<<endl;
   int val2 = { 897 };
   cout << "val2 = " << val2<<endl;
   return 0;
}
Declaring Values using uniform initialization
val1 = 367
val2 = 897
another method to assign values to a variable. in constructor initialisation of variables, we use a pair of parentheses instead of the = operator. the value of variable is enclosed inside a pair of parentheses ( ).
data_type variable_name(values);
 Live Demo
#include <iostream>
using namespace std;
int main() {
   cout<<"Declaring Values using constructor initialization \n";
   int val1( 367 );
   cout << "val1 = " <<val1<<endl;
   int val2 = ( 897 );
   cout << "val2 = " << val2<<endl;
   return 0;
}
Declaring Values using constructor initialization
val1 = 367
val2 = 897
How can I split an array of Numbers to individual digits in JavaScript?

We have an array of Number literals, and we are required to write a function, say splitDigit() that
takes in this array and returns an array of Numbers where the numbers greater than 10 are splitted into single digits.
For example −
//if the input is:
const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]
//then the output should be:
const output = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1,
0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ];
So, let’s write the code for this function, we will use the Array.prototype.reduce() method to split
the numbers.
const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]
const splitNum = (n, res = []) => {
   if(n){
      return splitNum(Math.floor(n/10), [n % 10].concat(res));
   };
   return res;
};
const splitDigit = (arr) => {
   return arr.reduce((acc, val) => acc.concat(splitNum(val)), []);
};
console.log(splitDigit(arr));
The output in the console will be −
[
   9, 4, 9, 5, 9, 6, 9, 7, 9,
   8, 9, 9, 1, 0, 0, 1, 0, 1,
   1, 0, 2, 1, 0, 3, 1, 0, 4,
   1, 0, 5, 1, 0, 6
]
How to remove all trailing whitespace of string in Python?

We can use the method rstrip() which returns a copy of the string in which all specified chars have been stripped from the end of the string. The default char to be trimmed is whitespace. For example:
>>> '   Hello   '.rstrip()
'   Hello'
>>> 'Ninja Turtles the movie     '.rstrip()
'Ninja Turtles the movie'
Working with hex numbers in MySQL?

In order to work with hex, use the CONV() function to convert between bases. The syntax is as follows −
SET anyVariableName = CONV(yourHexValue,16,10);
To understand the above syntax, let us create a stored procedure. The query to create a stored procedure is as follows −
mysql> DELIMITER //
mysql> CREATE PROCEDURE SP_HEX_TO_DEC( HEXVALUE VARCHAR(10) )
   -> BEGIN
   -> DECLARE Decimalvalue INTEGER;
   -> SET Decimalvalue = CONV(HEXVALUE,16,10);
   -> select Decimalvalue;
   -> END;
   -> //
Query OK, 0 rows affected (0.19 sec)
mysql> DELIMITER ;
The above stored procedure converts the hexadecimal to decimal. As we know the A represents 10 in decimal, we will pass A as the parameter. Call the stored procedure using CALL command.
The syntax is as follows −
CALL yourStoredProcedureName;
Call the above stored procedure using CALL command. The query is as follows −
mysql> call SP_HEX_TO_DEC('A');
The following is the output displaying the decimal value calculated using the stored procedure created above −
+--------------+
| Decimalvalue |
+--------------+
| 10           |
+--------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
Check with select statement directly.
mysql> select conv('AB',16,10) as DecimalResult;
The following is the output −
+---------------+
| DecimalResult |
+---------------+
| 171           |
+---------------+
1 row in set (0.00 sec)
Let us now see the procedure to convert hex to decimal. Remember this rule −
A and B represented as 10 and 11 respectively in hexadecimal.
To convert it into decimal rule is as follows:
N .........+value3 *162 +value2 *161 + value1 * 160
= 10 * 161 + 11 * 160
= 160+11
= 171.
Java Interface methods - GeeksforGeeks

07 Jun, 2020
There is a rule that every member of interface is only and only public whether you define or not. So when we define the method of the interface in a class implementing the interface, we have to give it public access as child class can’t assign the weaker access to the methods.As defined, every method present inside interface is always public and abstract whether we are declaring or not. Hence inside interface the following methods declarations are equal.
void methodOne();
public Void methodOne();
abstract Void methodOne();
public abstract Void methodOne();

public : To make this method available for every implementation class.abstract : Implementation class is responsible to provide implementation.Also, We can’t use the following modifiers for interface methods.
Private
protected
final
static
synchronized
native
strictfp
// A Simple Java program to demonstrate that// interface methods must be public in // implementing classinterface A{    void fun();}  class B implements A{     // If we change public to anything else,    // we get compiler error    public void fun()    {        System.out.println("fun()");    }}  class C{    public static void main(String[] args)    {        B b = new B();        b.fun();    }}
Output:
fun()
If we change fun() to anything other than public in class B, we get compiler error “attempting to assign weaker access privileges; was public”
This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
gauravmoney26
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
Check If the Rune is a Decimal Digit or not in Golang - GeeksforGeeks

27 Sep, 2019
Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a decimal digit or not with the help of IsDigit() function. This function returns true if the given rune is a decimal digit, or return false if the given rune is a non-decimal digit. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program.
Syntax:
func IsDigit(r rune) bool
The return type of this function is boolean. Let us discuss this concept with the help of given examples:
Example 1:
// Go program to illustrate how to// check the given rune is a// decimal digit or notpackage main  import (    "fmt"    "unicode")  // Main functionfunc main() {      // Creating rune    rune_1 := 'g'    rune_2 := 'e'    rune_3 := '1'    rune_4 := '4'    rune_5 := 'S'      // Checking the given rune is     // a decimal digit or not    // Using IsDigit() function    res_1 := unicode.IsDigit(rune_1)    res_2 := unicode.IsDigit(rune_2)    res_3 := unicode.IsDigit(rune_3)    res_4 := unicode.IsDigit(rune_4)    res_5 := unicode.IsDigit(rune_5)      // Displaying results    fmt.Println(res_1)    fmt.Println(res_2)    fmt.Println(res_3)    fmt.Println(res_4)    fmt.Println(res_5)  }
Output:
false
false
true
true
false

Example 2:
// Go program to illustrate how to check// the given rune is a decimal digit or notpackage main  import (    "fmt"    "unicode")  // Main functionfunc main() {      // Creating a slice of rune    val := []rune{'g', 'E', '3', 'K', '1'}      // Checking each element of the given    // slice of the rune is a decimal    // digit or not    // Using  IsDigit() function    for i := 0; i < len(val); i++ {          if unicode.IsDigit(val[i]) == true {              fmt.Println("It is a decimal digit")                      } else {                      fmt.Println("It is not a decimal digit")        }    }}
Output:
It is not a decimal digit
It is not a decimal digit
It is a decimal digit
It is not a decimal digit
It is a decimal digit

Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Loops in Go Language
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Class and Object in Golang
jQuery | multiple classes Selector - GeeksforGeeks

08 Sep, 2021
The .class selector in jquery is used to select multiple classes.
Syntax:
$(".class1, .class2, .class3, ...")
Parameter:
class: This parameter is required to specify the class of the elements to be selected.
Example-1:
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>       <script>        $(document).ready(function() {         $(".geeks, .for, .GeeksforGeeks").css(              "background-color", "green");        });    </script></head>  <body>    <center>        <h1 class="geeks">          Welcome to GeeksforGeeks      </h1>                <p>Geeks1</p>        <p class="for">Geeks2</p>        <p>Geeks3</p>        <p class="GeeksforGeeks">          Geeks3      </p>    </center></body>  </html>
Output:
Example-2:
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>    <script>        $(document).ready(function() {            $(".c1, .c2").css(              "background-color", "green");        });    </script></head>  <body>    <center>        <h1 class="geeks">          Welcome to GeeksforGeeks      </h1>                <p class="c1">Geeks1</p>        <p class="for">Geeks2</p>        <p class="c2">Geeks3</p>        <p class=           "GeeksforGeeks">          Geeks3      </p>    </center></body>  </html>
Output:
Supported Browsers:
Google Chrome 90.0+
Internet Explorer 9.0
Firefox 3.6
Safari 4.0
Opera 10.5
ysachin2314
jQuery-Selectors
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to plot a histogram using Matplotlib in Python with a list of data?

To plot a histogram using Matplotlib, we can follow the steps given below −
Make a list of numbers and assign it to a variable x.
Make a list of numbers and assign it to a variable x.
Use the plt.hist() method to plot a histogram.
Use the plt.hist() method to plot a histogram.
Compute and draw the histogram of *x*.
Compute and draw the histogram of *x*.
We can pass n-Dimensional arrays in the hist argument also.
We can pass n-Dimensional arrays in the hist argument also.
To show the plotted figure, use the plt.show() method.
To show the plotted figure, use the plt.show() method.
from matplotlib import pyplot as plt

x = [300, 400, 500, 2000, 10]

plt.hist(x, 10)

plt.show()
GDB - Installation

Before you go for installation, check if you already have gdb installed on your Unix system by issuing the following command −
$gdb -help 

If GDB is installed, then it will display all the available options within your GDB. If GDB is not installed, then proceed for a fresh installation.
You can install GDB on your system by following the simple steps discussed below.
Step 1 − Make sure you have the prerequisites for installing gdb −
An ANSI-compliant C compiler (gcc is recommended − note that gdb can debug codes generated by other compilers)
An ANSI-compliant C compiler (gcc is recommended − note that gdb can debug codes generated by other compilers)
115 MB of free disk space is required on the partition on which you're going to build gdb.
115 MB of free disk space is required on the partition on which you're going to build gdb.
20 MB of free disk space is required on the partition on which you're going to install gdb.
20 MB of free disk space is required on the partition on which you're going to install gdb.
Step 2 − Use the following command to install gdb on linux machine.
$ sudo apt-get install libc6-dbg gdb valgrind 

Step 3 − Now use the following command to find the help information.
$gdb -help 

You now have gdb installed on your system and it is ready to use.
 Print
 Add Notes
 Bookmark this page
JavaScript program to take in a binary number as a string and returns its numerical equivalent in base 10

We are required to write a JavaScript function that takes in a binary number as a string and
returns its numerical equivalent in base 10. Therefore, let’s write the code for the function.
This one is quite simple, we iterate over the string using a for loop and for each passing bit, we
double the number with adding the current bit value to it like this −
const binaryToDecimal = binaryStr => {
   let num = 0;
   for(let i = 0; i < binaryStr.length; i++){
      num *= 2;
      num += Number(binaryStr[i]);
   };
   return num;
};
console.log(binaryToDecimal('1101'));
console.log(binaryToDecimal('1101000'));
console.log(binaryToDecimal('10101'));
The output in the console will be −
13
104
21
What is Context on Android?

it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application). In the below program you will see that we have created a textView dynamically and passed context. This context is used to get the information about the environment.
This example demonstrates how do I display context in an android textView.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/linearLayout"
   android:orientation="vertical"
   android:padding="16sp"
   tools:context=".MainActivity">
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LinearLayout linearLayout = findViewById(R.id.linearLayout);
      TextView textViewContext = new TextView(getApplicationContext());
      textViewContext.setTextSize(30);
      textViewContext.setText("Application Context");
      textViewContext.setTextColor(Color.RED);
      TextView textViewActivityContext = new TextView(this);
      textViewActivityContext.setTextSize(30);
      textViewActivityContext.setText("Activity Context");
      linearLayout.addView(textViewContext);
      linearLayout.addView(textViewActivityContext);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Generation of triangular wave using DAC interface

We write an 8085 assembly language program for the generation of triangular waveform using the Digital to Analog Converter (DAC) interface. The display of the waveform is seen on the CRO.
Let us consider a problem solution in this domain. The problem states that: To get unipolar output, J1 is shorted to J2 on the interface. To display the waveform on a CRO, connect pin 1 of connector P1 to CRO signal pin, and pin 2 of connector P1 to CRO ground pin.
; FILE NAME DAC_TO_TRIANG.ASM
ORG C100H
X DW 00FFH ; the fall of rise and time I proportional directly to the value.

ORG C000H
PA EQU D8H
PB EQU D9H
PC EQU DAH
CTRL EQU DBH

MVI A, 88H
OUT CTRL ; Purpose to configure 8255 ports
; The next 7 instructions will generate rising portion of the triangular waveform.
; And it is done by sending to DAC through Port A values from 00H to FFH,
; in steps of 01. Also the increment will be done after a small time delay here.

LOOP: MVI A, 00H
ASCEND: OUT PA
PUSH PSW
CALL DELAY

POP PSW
INR A
JNZ ASCEND

DCR A ; Now A contents will be FFH

DESCEND: OUT PA
PUSH PSW

CALL DELAY

POP PSW
DCR A
CPI FFH
JNZ DESCEND

JMP LOOP
; These Subroutines are used only for the generation of delay
; which is proportional to all the contents of word located at X.

DELAY: LHLD X
AGAIN: DCX H
MOV A, H
ORA L
JNZ AGAIN
RET
How to Write/create a JSON file using Java?

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document −
{
   "book": [
      {
         "id": "01",
         "language": "Java",
         "edition": "third",
         "author": "Herbert Schildt"
      },
      {
         "id": "07",
         "language": "C++",
         "edition": "second",
         "author": "E.Balagurusamy"
      }
   ]
}
The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program.
Following is the maven dependency for the JSON-simple library −
<dependencies>
   <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
   </dependency>
</dependencies>
Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag)
To create a JSON document using a Java program −
Instantiate the JSONObject class of the json-simple library.
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
Insert the required key-value pairs using the put() method of the JSONObject class.
jsonObject.put("key", "value");
Write the created JSON object into a file using the FileWriter class as −
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
Following Java program creates a JSON object and writes it into a file named output.json.
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
   public static void main(String args[]) {
      //Creating a JSONObject object
      JSONObject jsonObject = new JSONObject();
      //Inserting key-value pairs into the json object
      jsonObject.put("ID", "1");
      jsonObject.put("First_Name", "Shikhar");
      jsonObject.put("Last_Name", "Dhawan");
      jsonObject.put("Date_Of_Birth", "1981-12-05");
      jsonObject.put("Place_Of_Birth", "Delhi");
      jsonObject.put("Country", "India");
      try {
         FileWriter file = new FileWriter("E:/output.json");
         file.write(jsonObject.toJSONString());
         file.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      System.out.println("JSON file created: "+jsonObject);
   }
}
JSON file created: {
"First_Name":"Shikhar",
"Place_Of_Birth":"Delhi",
"Last_Name":"Dhawan",
"Country":"India",
"ID":"1",
"Date_Of_Birth":
"1981-12-05"}
If you observe the contents of the JSON file you can see the created data as −
How to make an HTTP POST request on iOS App using Swift?

To make an http request in iOS we’ll make use of DataTask and sessions. We’ll create configuration, sessions, url, request, and dataTask objects. Let’s see the steps that we’ll go through.
First of all we need to create a session object, which default configuration.
First of all we need to create a session object, which default configuration.
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”POST” type.
Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”POST” type.
let url = URL(string: URLString)
//let url = NSURL(string: urlString as String)
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now.
Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now.
let dataTask = session.dataTask(with: url!) { data,response,error in
   guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
   else {
      print("error: not a valid http response")
      return
   }
   switch (httpResponse.statusCode) {
      case 200: //success response.
         break
      case 400:
         break
      default:
         break
   }
}
dataTask.resume()
Now we can embed this in a function and use in our code.
Now we can embed this in a function and use in our code.
func hitAPI(_for URLString:String) {
   let configuration = URLSessionConfiguration.default
   let session = URLSession(configuration: configuration)
   let url = URL(string: URLString)
   //let url = NSURL(string: urlString as String)
   var request : URLRequest = URLRequest(url: url!)
   request.httpMethod = "POST"
   request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   request.addValue("application/json", forHTTPHeaderField: "Accept")
   let dataTask = session.dataTask(with: url!) {
      data,response,error in
      // 1: Check HTTP Response for successful GET request
      guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
      else {
         print("error: not a valid http response")
         return
      }
      switch (httpResponse.statusCode) {
         case 200:
            //success response.
            break
         case 400:
            break
         default:
            break
      }
   }
   dataTask.resume()
}
Note: You may need to allow Transport Security exceptions in your info.plist file to access some APIs.
There is no output shown with this example as an API is required to post some data.
Difference between require() and require_once() in PHP - GeeksforGeeks

21 Oct, 2021
PHP require() Function: The require() function in PHP is mostly used to include the code/data of one PHP file to another file. During this process, if there are any kind of errors then this require() function will display a warning along with a fatal error which will immediately stop the execution of the script. 
In order to use this require() function, we will first need to create two PHP files.  Include one PHP file into another one by using the include() function. The two PHP files are combined into one HTML file. This require() function will not see whether the code is included in the specified file before, rather it will include the code as many times the require() function is used.
Example:
HTML
<html>  <body>    <h1>Welcome to geeks for geeks!</h1>    <p>Myself, Gaurav Gandal</p>      <p>Thank you</p>      <?php require 'requiregfg.php'; ?></body>  </html>
 
requiregfg.php
<?php      echo "<p>visit Again-" . date("Y")         . " geeks for geeks.com</p>";  ?>
Output:
PHP require_once() Function: The require_once() function in PHP is used to include one PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is already included in a specified file then it will not include that code again if we use the require_once() function. It means that this function will add a file into another only once. 
In case this function does not locate a specified file then it will produce a fatal error and will immediately stop the execution.
Example:
PHP
<?php    require_once('demo.php');    require_once('demo.php');?>
The following code is used in the above PHP code.
demo.php
<?php    echo "Hello from Geeks for Geeks";?>
Output:
Difference between require() and require_once():
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
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?
Class and Instance Attributes in Python

20 Apr, 2020
Class attributes
Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility.
# Write Python code hereclass sampleclass:    count = 0     # class attribute      def increase(self):        sampleclass.count += 1  # Calling increase() on an objects1 = sampleclass()s1.increase()        print(s1.count)  # Calling increase on one more# objects2 = sampleclass()s2.increase()print(s2.count)  print(sampleclass.count)
Output:
1              
2                           
2
Instance Attributes
Unlike class attributes, instance attributes are not shared by objects. Every object has its own copy of the instance attribute (In case of class attributes all object refer to single copy).
To list the attributes of an instance/object, we have two functions:-1. vars()– This function displays the attribute of an instance in the form of an dictionary.2. dir()– This function displays more attributes than vars function,as it is not limited to instance. It displays the class attributes as well. It also displays the attributes of its ancestor classes.
# Python program to demonstrate# instance attributes.class emp:    def __init__(self):        self.name = 'xyz'        self.salary = 4000      def show(self):        print(self.name)        print(self.salary)  e1 = emp()print("Dictionary form :", vars(e1))print(dir(e1))
Output :
Dictionary form :{'salary': 4000, 'name': 'xyz'}
['__doc__', '__init__', '__module__', 'name', 'salary', 'show']
This article is contributed by Harsh Valecha. 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.
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.setworldcoordinates() function in Python

25 Aug, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to set up a user-defined coordinate system. This performs a reset. If mode ‘world’ is already active, all drawings are redrawn according to the new coordinates. 
Note: In user-defined coordinate systems angles may appear distorted.
Syntax : turtle.setworldcoordinates(llx, lly, urx, ury) 
Parameters:
llx: a number, x-coordinate of lower left corner of canvas
lly: a number, y-coordinate of lower left corner of canvas
urx: a number, x-coordinate of upper right corner of canvas
ury: a number, y-coordinate of upper right corner of canvas
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle # make screen object and# set screen mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-20, -20, 20, 20) # loop for some motionfor i in range(20):    turtle.forward(1+1*i)    turtle.right(90)
Output:
Part A
 Example 2:
Python3
# importing packageimport turtle # make screen object and# set screen mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-40, -40, 40, 40) # loop for some motionfor i in range(20):    turtle.forward(1+1*i)    turtle.right(90)
Output :
In the  above two examples, the code are the same and only the difference of world coordinates differ the output as shown below :
Example  3 :
Python3
# importing packageimport turtle # make screen object and# set mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-50, -50, 50, 50) # do some motionfor i in range(16):    turtle.forward(1+1*i)    turtle.right(90) # set world coordinatesturtle.setworldcoordinates(-40, -40, 40, 40) # do some motionfor i in range(16):    turtle.forward(1+1*(i+16))    turtle.right(90) # set world coordinatesturtle.setworldcoordinates(-30, -30, 30, 30) # do some motionfor i in range(16):    turtle.forward(1+1*(i+32))    turtle.right(90)
Output :
Here, we can see that the all previous drawing is set to new world coordinates ( drawing enlarges ).
sumitgumber28
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Bash program to check if the Number is a Palindrome

14 Jan, 2019
Given a number num, find whether the given number is palindrome or not using Bash Scripting.
Examples:
Input : 
666
Output :
Number is palindrome

Input :
45667
Output :
Number is NOT palindrome

ApproachTo find the given number is palindrome just check if the number is same from beginning and the end. Reverse the number to check if the number reversed is equal to the original number or not, if yes than echo Number is palindrome otherwise echo Number is NOT palindrome .
num=545   # Storing the remainders=0   # Store number in reverse # orderrev=""   # Store original number # in another variabletemp=$num   while [ $num -gt 0 ]do    # Get Remainder    s=$(( $num % 10 ))            # Get next digit    num=$(( $num / 10 ))           # Store previous number and    # current digit in reverse     rev=$( echo ${rev}${s} ) done   if [ $temp -eq $rev ];then    echo "Number is palindrome"else    echo "Number is NOT palindrome"fi
Output:
Number is palindrome

AnmolAgarwal
palindrome
Shell Script
Linux-Unix
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Puzzle 19 | (Poison and Rat)

12 Aug, 2021
There are 1000 wine bottles. One of the bottles contains poisoned wine. A rat dies after one hour of drinking the poisoned wine. How many minimum rats are needed to figure out which bottle contains poison in hour. 
Solution: We need to figure out in hour. We need 10 rats to figure out the poisoned bottle. The result is based on binary number system. We get 10 using ⌈ Log21000 ⌉. 
The idea is to number bottles from 1 to 1000 and write their corresponding binary numbers on the bottle. Each rat is assigned a position in the binary numbers written on bottles. Let us take an example. Rat 1 represents first bit in every bottle, rat 2 represents second bit and so on. If rat numbers 2, 4 and 6 die, then bottle number 42 (Binary 0000101010) is poisoned. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above  
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Xw5LR6WRTz4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
priyameena1408
Mathematical
Puzzles
Mathematical
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
QlikView - Dashboard

A Dashboard is a powerful feature to display values from many fields simultaneously. QlikeView's feature of data association in memory can display the dynamic values in all the sheet objects.
Let us consider the following input data, which represents the sales figure of different product lines and product categories.
Product_Line,Product_category,Value
Sporting Goods,Outdoor Recreation,5642
Food, Beverages & Tobacco,2514
Apparel & Accessories,Clothing,2365
Apparel & Accessories,Costumes & Accessories,4487
Sporting Goods,Athletics,812
Health & Beauty,Personal Care,6912
Arts & Entertainment,Hobbies & Creative Arts,5201
Arts & Entertainment,Paintings,8451
Arts & Entertainment,Musical Instruments,1245
Hardware,Tool Accessories,456
Home & Garden,Bathroom Accessories,241
Food,Drinks,1247
Home & Garden,Lawn & Garden,5462
Office Supplies,Presentation Supplies,577
Hardware,Blocks,548
Baby & Toddler,Diapering,1247
Baby & Toddler,Toys,257
Home & Garden,Pipes,1241
Office Supplies,Display Board,2177

The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory.
LOAD Product_Line, 
     Product_category, 
     Value
FROM
[C:\Qlikview\data\product_sales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
We choose the fields from the above input data as matrices to be displayed in the dashboard. For this, we follow the steps in the menu Layout → Select Fields.
In the next screen, choose the available fields to be displayed in the dashboard. Click "OK".
The following screen appears displaying all the fields
NNow we add a chart to the dashboard by right-clicking anywhere in the sheet and choosing New Sheet Object → Chart.
Let us choose the chart type as a bar chart to display the sales values for various product Lines.
Let us select the Product Line as the Chart Dimension.
The expression to display the sales value for the Product Line dimension is written in the expression editor.
Given below is the dashboard displayed after finishing the above steps.
The values in the above Dashboard can be selected for filtering specific products and the chart changes accordingly. In addition, the associated values are highlighted.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
Create Word Cloud using Python

In this problem, there is a file with some texts. We have to create Word Clouds from those texts and one masking image. The program will store the word cloud image as png format.
To implement this problem, we need to use some libraries of python. The libraries are matplotlib, wordcloud, numpy, tkinter and PIL.
To install these libraries, we need to follow these commands −
$ sudo pip3 install matplotlib
$ sudo pip3 install wordcloud
$ sudo apt-get install python3-tk

After adding these libraries, we can write the python code to perform the task.
Step 1: Read the data from the file and store it into ‘dataset’. 
Step 2: Create pixel array from the mask image. 
Step 3: Create the word cloud from the dataset. Set the background color, mask, and stop-words. 
Step 4: Store the final image into the disk. 

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.
Another input is the mask image (cloud.png). The final Result is on the right side.
import matplotlib.pyplot as pPlot
from wordcloud import WordCloud, STOPWORDS
import numpy as npy
from PIL import Image
dataset = open("sampleWords.txt", "r").read()
defcreate_word_cloud(string):
   maskArray = npy.array(Image.open("cloud.png"))
   cloud = WordCloud(background_color = "white", max_words = 200, mask = maskArray, stopwords = set(STOPWORDS))
   cloud.generate(string)
   cloud.to_file("wordCloud.png")
dataset = dataset.lower()
create_word_cloud(dataset)