code-rag-bench/online-tutorials huggingface dataset:
Calculate Inverse cosine of a value in R Programming - acos() Function - GeeksforGeeks

01 Jun, 2020
acos() function in R Language is used to calculate the inverse cosine value of the numeric value passed to it as argument.
Syntax: acos(x)
Parameter:x: Numeric value
Example 1:
# R code to calculate inverse cosine of a value  # Assigning values to variables x1 <- -1x2 <- 0.5  # Using acos() Functionacos(x1)acos(x2)
Output:
[1] 3.141593
[1] 1.047198
Example 2:
# R code to calculate inverse cosine of a value  # Assigning values to variablesx1 <- 0.224587x2 <- 0.456732  # Using acos() Functionacos(x1)acos(x2)
Output:
[1] 1.344277
[1] 1.096478
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Printing Output of an R Program
K-Means Clustering in R Programming
Scala Set toArray() method with example - GeeksforGeeks

18 Oct, 2019
The toArray() is utilized to return an array consisting of all the elements of the set.
Method Definition: def toArray: Array[A]
Return Type: It returns an array consisting of all the elements of the set.
Example #1:
// Scala program of toArray() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(1, 2, 3, 4, 7)                   // Applying toArray method         val result = s1.toArray                  // Display output        for (elem <- result)            println(elem)                  } } 
1
2
7
3
4

Example #2:
// Scala program of toArray() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(41, 12, 23, 43, 1, 72)                   // Applying toArray method         val result = s1.toArray                  // Display output        for (elem <- result)            println(elem)                  } } 
1
41
12
72
43
23

Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala ListBuffer
Inheritance in Scala
Scala | Case Class and Case Object
Hello World in Scala
Scala | Traits
Scala | Try-Catch Exceptions
Scala List map() method with example
How to install Scala on Windows?
Comments In Scala
Scala | Option
BinarySearch() method in C#

BinarySearch() works on a sorted list whether its numeric, alphanumeric or strings. It finds you the index of an element.
Let’s say the following is our list.
List<int> list = new List<int>();
list.Add(70);
list.Add(150);
list.Add(220);
list.Add(250);
list.Add(300);
Now to check the index where 250 is placed, use BinarySearch() method.
list.BinarySearch(250);
 Live Demo
using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<int> list = new List<int>();
      list.Add(70);
      list.Add(150);
      list.Add(220);
      list.Add(250);
      list.Add(300);
      int value = list.BinarySearch(250);
      Console.WriteLine("Element 250 at Index: "+value);
   }
}
Element 250 at Index: 3
MySQL - Insert current date/time?

To insert only date value, use curdate() in MySQL. With that, if you want to get the entire datetime, then you can use now() method.
Let us first create a table −
mysql> create table CurDateDemo
   -> (
   -> ArrivalDate datetime
   -> );
Query OK, 0 rows affected (0.74 sec)
Now you can insert only date with the help of curdate() method −
mysql> insert into CurDateDemo values(curdate());
Query OK, 1 row affected (0.15 sec)
Display the inserted date with the help of select statement. The query is as follows −
mysql> select *from CurDateDemo;
Here is the output −
+---------------------+
| ArrivalDate         |
+---------------------+
| 2018-11-23 00:00:00 |
+---------------------+
1 row in set (0.00 sec)
Let us now create a table and display the current datetime −
mysql> create table NowDemo
   -> (
   -> ArrivalDate datetime
   -> );
Query OK, 0 rows affected (0.47 sec)
Insert both date and time with the help of now().
The query to insert record is as follows −
mysql> insert into NowDemo values(now());
Query OK, 1 row affected (0.16 sec)
Let us now check whether the date and time is inserted or not. The query to display records is as follows −
mysql> select *from NowDemo;
The following is the output −
+---------------------+
| ArrivalDate         |
+---------------------+
| 2018-11-23 17:31:26 |
+---------------------+
1 row in set (0.00 sec)
Bootstrap 4 .justify-content-*-start class

Use the justify-content-start class in Bootstrap to justify content in the beginning.
The justify-content-*-start class is used in Bootstrap to justify content in the beginning on different screen sizes like the following on small, medium, and large screen sizes −
You can try to run the following code to implement the justify-content-*-start class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

  <div class="container mt-3">
    <h3>Entertainment</h3>
    <div class="d-flex justify-content-sm-start bg-info mb-5">
      <div class="p-2 bg-danger">Bollywood</div>
      <div class="p-2 bg-secondary">Tollywood</div>
      <div class="p-2 bg-warning">Hollywood</div>
    </div>
    <div class="d-flex justify-content-md-start bg-info mb-5">
      <div class="p-2 bg-secondary">Bollywood</div>
      <div class="p-2 bg-warning">Tollywood</div>
      <div class="p-2 bg-primary">Hollywood</div>
    </div>
    <div class="d-flex justify-content-lg-start bg-info mb-5">
       <div class="p-2 bg-secondary">Bollywood</div>
       <div class="p-2 bg-warning">Tollywood</div>
       <div class="p-2 bg-primary">Hollywood</div>
    </div>
  </div>

</body>
</html>
Finding first non-repeating character JavaScript

We have an array of Numbers/String literals where most of the entries are repeated. Our job is
to write a function that takes in this array and returns the index of first such element which does
not make consecutive appearances.
If there are no such elements in the array, our function should return -1. So now, let's write the
code for this function. We will use a simple loop to iterate over the array and return where we
find non-repeating characters, if we find no such characters, we return -1 −
const arr = ['d', 'd', 'e', 'e', 'e', 'k', 'j', 'j', 'h'];
const firstNonRepeating = arr => {
   let count = 0;
   for(let ind = 0; ind < arr.length-1; ind++){
      if(arr[ind] !== arr[ind+1]){
         if(!count){
            return ind;
         };
         count = 0;
      } else {
         count++;
      }
   };
   return -1;
};
console.log(firstNonRepeating(arr));
The output in the console will be −
5
Difference between @Inject and @Autowired

@Inject and @Autowired both annotations are used for autowiring in your application.
@Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application.
public class InjectionExample {
   @Inject
   private CarBean carbean;
}
public class AutowiredExample {
   @Autowired
   private CarBean carbean;
}
Program to find total unique duration from a list of intervals in Python

Suppose we have a list of intervals where each list represents an interval [start, end] (inclusive). We have to find the total unique duration it covers.
So, if the input is like intervals = [[2, 11],[13, 31],[41, 61]], then the output will be 50, as the total unique covered distance is (11 - 2 + 1) = 10 then (31 - 13 + 1) = 19 and (61 - 41 + 1) = 21, so total is 50.
To solve this, we will follow these steps −
if intervals list is empty, thenreturn 0
return 0
sort the list intervals
[start, end] := intervals[0]
ans := 0
for each start and end (s, e) in intervals, doif s > end, thenans := ans + end - start + 1start := s, end := eotherwise,end := maximum of end, e
if s > end, thenans := ans + end - start + 1start := s, end := e
ans := ans + end - start + 1
start := s, end := e
otherwise,end := maximum of end, e
end := maximum of end, e
ans := ans + end - start + 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, intervals):
      if not intervals:
         return 0
         intervals.sort()
         start, end = intervals[0]
         ans = 0
         for s, e in intervals:
            if s > end:
               ans += end - start + 1
               start = s
               end = e
            else:
               end = max(end, e)
            ans += end - start + 1
         return ans
ob = Solution()
intervals = [[2, 11],[13, 31],[41, 61]]
print(ob.solve(intervals))
[[2, 11],[13, 31],[41, 61]]
50
How to make a phone call using intent in Android using Kotlin?

This example demonstrates how to make a phone call using intent in Android using Kotlin
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"?>
<RelativeLayout 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:padding="8dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <Button
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:onClick="call"
      android:text="Call" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   fun call(view: View) {
      val dialIntent = Intent(Intent.ACTION_DIAL)
      dialIntent.data = Uri.parse("tel:" + "8344814819")
      startActivity(dialIntent)
   }
}
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="com.example.q11">
   <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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
How do I display the indexes of a collection in MongoDB?

In order to display the indexes of a collection, you can use getIndexes(). The syntax is as follows −
db.yourCollectionName.getIndexes();
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599")
}
> db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20});
The following is the output −
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f7c5e2f684a30fbdfd59b")
}
> db.indexDemo.find().pretty();
{
   "_id" : ObjectId("5c8f7c4f2f684a30fbdfd599"),
   "StudentName" : "Larry",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c8f7c552f684a30fbdfd59a"),
   "StudentName" : "Mike",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c8f7c5e2f684a30fbdfd59b"),
   "StudentName" : "Carol",
   "StudentAge" : 20
}
Here is the query to create indexes −
> db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1});
The following is the output:
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 2,
   "numIndexesAfter" : 3,
   "ok" : 1
}
Here is the query to display the indexes of a collection. The collection name is “indexDemo” −
> db.indexDemo.getIndexes();
The following is the output −
[
   {
      "v" : 2,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "test.indexDemo"
   },
   {
      "v" : 2,
      "key" : {
         "StudentName" : -1
      },
      "name" : "StudentName_-1",
      "ns" : "test.indexDemo"
   },
   {
      "v" : 2,
      "key" : {
         "StudentName" : -1,
         "StudentAge" : -1
      },
      "name" : "StudentName_-1_StudentAge_-1",
      "ns" : "test.indexDemo"
   }
]
How to use deleteOne() function in MongoDB?

The deleteOne() function in MongoDB deletes at most one matching document from a collection. Let us first create a collection with documents −
> db.demo363.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2c3d0ada61456dc9369")
}
> db.demo363.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2c7d0ada61456dc936a")
}
> db.demo363.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2cad0ada61456dc936b")
}
> db.demo363.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d2d1d0ada61456dc936c")
}
Display all documents from a collection with the help of find() method −
> db.demo363.find();
This will produce the following output −
{ "_id" : ObjectId("5e57d2c3d0ada61456dc9369"), "Name" : "Chris" }
{ "_id" : ObjectId("5e57d2c7d0ada61456dc936a"), "Name" : "David" }
{ "_id" : ObjectId("5e57d2cad0ada61456dc936b"), "Name" : "Bob" }
{ "_id" : ObjectId("5e57d2d1d0ada61456dc936c"), "Name" : "Chris" }
Following is the query to work with deleteOne() in MongoDB −
> db.demo363.deleteOne({Name:"Chris"});
{ "acknowledged" : true, "deletedCount" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo363.find();
This will produce the following output −
{ "_id" : ObjectId("5e57d2c7d0ada61456dc936a"), "Name" : "David" }
{ "_id" : ObjectId("5e57d2cad0ada61456dc936b"), "Name" : "Bob" }
{ "_id" : ObjectId("5e57d2d1d0ada61456dc936c"), "Name" : "Chris" }
Add a background color to the form input with CSS

To add background color to the form input, use the background-color property.
You can try to run the following code to implement the background color property to form
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         input[type=text] {
            width: 100%;
            padding: 10px 15px;
            margin: 5px 0;
            box-sizing: border-box;
            background-color: gray;
         }
      </style>
   </head>
   <body>
      <p>Fill the below form,</p>
      <form>
         <label for = "subject">Subject</label>
         <input type = "text" id = "subject" name = "sub">
         <label for = "student">Student</label>
         <input type = "text" id = "student" name = "stu">
      </form>
   </body>
</html>
How to bind the spacebar key to a certain method in Tkinter?

Tkinter methods can be bound with the Keys or Mouse to perform certain operations or events in an application. Let us suppose for a particular application, we want to bind the <Space> Key such that it will perform a certain operation. We can bind any key to a particular operation or event by defining the bind(<key>, callback) method.
In this example, we will create rectangles of random width and height by using random Module in Python. So, whenever we will press the Key, it will generate some random shapes on the screen.
#Import the required Libraries
from tkinter import *
import random

#Create an instance of Tkinter frame
win= Tk()

#Crate a canvas
canvas=Canvas(win,width=500,height=250,bg='white')
def draw_shapes(e):
   canvas.delete(ALL)

canvas.create_rectangle(random.randint(5,300), random.randint(1,300), 25, 25, fill='khaki3')
canvas.pack()

#Bind the spacebar Key to a function
win.bind("<space>", draw_shapes)
win.mainloop()
Run the above code to display a window that generates random shapes while pressing the <Space> Key on the Keyboard.
Uploading Large Files to GitHub. 3 ways to avoid getting error messages... | by Eden Au | Towards Data Science

GitHub has a strict file limit of 100MB. If you are just uploading lines of codes, this is not something that you need to worry about. However, if you want to upload a bit of data, or something in binary, this is a limit that you might want to cross. Here are three different ways to overcome the 100MB limit.
Originally published on my blog edenau.github.io.
Create a file .gitignore in the parent directory of the repository, and store all the file directories that you want Git to ignore. Use * for wildcard so that you do not need to add file directories manually each time you create a new large file. Here is an example:
*.nc*.DS_store
These ignored files will be automatically ignored by Git and will not be uploaded to GitHub. No more error messages.
If you have accidentally committed files locally that exceeds 100MB, you would have a hard time trying to push it to GitHub. It cannot be solved by removing the large files and committing again. This is because GitHub keeps track of every commit, not just the latest one. You are technically pushing files in your entire commit record.
While you could technically resolve it by branching, it is by no means straightforward. Fortunately, you can run a repository cleaner and it automatically cleans all the large file commits.
Download BFG Repo-Cleaner bfg.jar and run the following command:
java -jar bfg.jar --strip-blobs-bigger-than 100M <your_repo>
It automatically cleans your commits and produces a new commit with the comment ‘remove large files’. Push it and you are good to go.
You might have noticed that the abovementioned methods both avoid uploading the large files. What if you really want to upload them so that you could gain access to them on another device?
Git Large File Storage lets you store them on a remote server such as GitHub. Download and install git-lfs by placing it into your $PATH. You will then need to run the following command once per local repository:
git lfs install
Large files are selected by:
git lfs track '*.nc'git lfs track '*.csv'
This will create a file named .gitattributes, and voilà! You can perform add and commit operations as normal. Then, you will first need to a) push the files to the LFS, then b) push the pointers to GitHub. Here are the commands:
git lfs push --all origin mastergit push -u origin master
Files on Git LFS are then available on GitHub with the following label.
In order to pull the repository on another device, simply install git-lfs on that device (per local repository).
Thank you for reading! If you are interested in data science, check out the following articles:
towardsdatascience.com
towardsdatascience.com
Originally published on my blog edenau.github.io.
Single dimensional array vs multidimensional array in JavaScript.

Following is the code for single and multidimentsional array in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Single dimensional array vs multidimensional array</h1>
<div class="sample">Single dimensional Array<br /></div>
<div class="result">Multidimensional Array<br /></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to display single and multidimensional array</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let BtnEle = document.querySelector(".Btn");
   let arr = [1, 2, 3, 4, 5];
   let arr1 = [
      [1, 2, 3],
      ["A", "B", "C"],
      [5, "D", 6],
   ];
   BtnEle.addEventListener("click", () => {
      sampleEle.innerHTML += arr + "";
      arr1.forEach((item, index) => {
         resEle.innerHTML += "Index : " + index + " array = " + item + "";
      });
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
clear command in Linux with examples - GeeksforGeeks

26 Aug, 2020
clear is a standard Unix computer operating system command that is used to clear the terminal screen. This command first looks for a terminal type in the environment and after that, it figures out the terminfo database for how to clear the screen. And this command will ignore any command-line parameters that may be present. Also, the clear command doesn’t take any argument and it is almost similar to cls command on a number of other Operating Systems.
Syntax:
$clear
Terminal Before Executing clear command:
Terminal after Executing clear command:
Note:- In order to clear the terminal press [ctrl+l] and for GNOME terminal in ubuntu 18.04 press [shift + ctrl + alt + c]
manav014
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Docker - COPY Instruction
nslookup command in Linux with Examples
Basic Operators in Shell Scripting
How to obtain the highest occurring character in a String using C#?

The highest occurring character in a string is one that occurs most number of times. This can be demonstrated using the following example.
String: apples are red
The highest occurring character in the above string is e as it occurs 3 times, which is more than the occurrence of any other character.
A program that obtains the highest occurring character in a string using C# is given as follows.
 Live Demo
using System;
namespace charCountDemo {
   public class Example {
      public static void Main() {
         String str = "abracadabra";
         int []charCount = new int[256];
         int length = str.Length;
         for (int i = 0; i < length; i++) {
            charCount[str[i]]++;
         }
         int maxCount = -1;
         char character = ' ';
         for (int i = 0; i < length; i++) {
            if (maxCount < charCount[str[i]]) {
               maxCount = charCount[str[i]];
               character = str[i];
            }
         }
         Console.WriteLine("The string is: " + str);
         Console.WriteLine("The highest occurring character in the above string is: " + character);
         Console.WriteLine("Number of times this character occurs: " + maxCount);
      }
   }
}
The output of the above program is as follows.
The string is: abracadabra
The highest occurring character in the above string is: a
Number of times this character occurs: 5
Now, let us understand the above program.
The string str is abracadabra. A new array charCount is created which is of size 256 and shows all the characters in the ASCII table. Then the string str is traversed using a for loop and the value in charCount is incremented corresponding to the character in the string. This can be seen in the following code snippet.
String str = "abracadabra";
int []charCount = new int[256];
int length = str.Length;
for (int i = 0; i < length; i++) {
   charCount[str[i]]++;
}
The integer maxCount stores the maximum count and character is the char value that occurs the maximum times. The values of maxCount and character can be determined using a for loop. This can be seen in the following code snippet.
int maxCount = -1;
char character = ' ';
for (int i = 0; i < length; i++) {
   if (maxCount < charCount[str[i]]) {
      maxCount = charCount[str[i]];
      character = str[i];
   }
}
Finally, the values of str, maxCount and character are displayed. This can be seen in the following code snippet.
Console.WriteLine("The string is: " + str);
Console.WriteLine("The highest occurring character in the above string is: " + character);
Console.WriteLine("Number of times this character occurs: " + maxCount);
What are increment (++) and decrement (--) operators in C#?

To increment a value in C#, you can use the increment operators i.e. Pre-Increment and Post-Increment Operators.
The following is an example −
using System;

class Demo {
   static void Main() {
      int a = 250;
      Console.WriteLine(a);

      a++;
      Console.WriteLine(a);

      ++a;
      Console.WriteLine(a);

      int b = 0;
      b = a++;
      Console.WriteLine(b);
      Console.WriteLine(a);

      b = ++a;
      Console.WriteLine(b);
      Console.WriteLine(a);
   }
}
To decrement a value in C#, you can use the decrement operators i.e. Pre-Decrement and Post-Decrement Operators.
The following is an example −
using System;

class Demo {
   static void Main() {
      int a = 250;
      Console.WriteLine(a);

      a--;
      Console.WriteLine(a);

      --a;
      Console.WriteLine(a);

      int b = 0;
      b = a--;
      Console.WriteLine(b);
      Console.WriteLine(a);

      b = --a;
      Console.WriteLine(b);
      Console.WriteLine(a);
   }
}
Running chrome browser in inconginto Mode in Selenium

We can run Chrome browser Incognito mode with Selenium webdriver. Incognito mode is a safe mode of opening a browser. This can be done with the help of the DesiredCapabilities and ChromeOptions class.
We shall create an object of the ChromeOptions class and apply addArguments method on it. Then pass −−incognito as a parameter to that method. We shall then create an object of the DesiredCapabilities class.
We shall apply setCapability method on the object of the DesiredCapabilities class and pass the ChromeOptions.CAPABILITY and the object of ChromeOptions class as parameters to that method.
Finally, this browser chrome profile shall be fed to the webdriver object.
ChromeOptions o= new ChromeOptions();
o.addArguments("−−incognito");
DesiredCapabilities c = DesiredCapabilities.chrome();
c.setCapability(ChromeOptions.CAPABILITY, o);
WebDriver driver = new ChromeDriver(o);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class BrwIncognt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      // configure options parameter to Chrome driver
      ChromeOptions o= new ChromeOptions();
      // add Incognito parameter
      o.addArguments("--incognito");
      // DesiredCapabilities object
      DesiredCapabilities c = DesiredCapabilities.chrome();
      //set capability to browser
      c.setCapability(ChromeOptions.CAPABILITY, o);
      WebDriver driver = new ChromeDriver(o);
      driver.get("https://www.tutorialspoint.com/index.htm ");
   }
}
How to format date and time in android?

This example demonstrates how do I format date and time in android.
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"?>
<RelativeLayout 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"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAlignment="center"
      android:textSize="16sp"
      android:textStyle="bold|italic"
      android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   String dateTime;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy hh-mm-ss a");
      dateTime = simpleDateFormat.format(calendar.getTime());
      textView.setText(dateTime);
   }
}
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 –
Click here to download the project code.
Cosine similarity: How does it measure the similarity, Maths behind and usage in Python | by Varun | Towards Data Science

What is cosine similarity?
Cosine similarity measures the similarity between two vectors by calculating the cosine of the angle between the two vectors.
Cosine similarity is one of the most widely used and powerful similarity measure in Data Science. It is used in multiple applications such as finding similar documents in NLP, information retrieval, finding similar sequence to a DNA in bioinformatics, detecting plagiarism and may more.
Cosine similarity is calculated as follows,
Why cosine of the angle between A and B gives us the similarity?
If you look at the cosine function, it is 1 at theta = 0 and -1 at theta = 180, that means for two overlapping vectors cosine will be the highest and lowest for two exactly opposite vectors. You can consider 1-cosine as distance.
How to calculate it in Python?
The numerator of the formula is the dot product of the two vectors and denominator is the product of L2 norm of both the vectors. Dot product of two vectors is the sum of element wise multiplication of the vectors and L2 norm is the square root of sum of squares of elements of a vector.
We can either use inbuilt functions in Numpy library to calculate dot product and L2 norm of the vectors and put it in the formula or directly use the cosine_similarity from sklearn.metrics.pairwise. Consider two vectors A and B in 2-D, following code calculates the cosine similarity,
import numpy as npimport matplotlib.pyplot as plt# consider two vectors A and B in 2-DA=np.array([7,3])B=np.array([3,7])ax = plt.axes()ax.arrow(0.0, 0.0, A[0], A[1], head_width=0.4, head_length=0.5)plt.annotate(f"A({A[0]},{A[1]})", xy=(A[0], A[1]),xytext=(A[0]+0.5, A[1]))ax.arrow(0.0, 0.0, B[0], B[1], head_width=0.4, head_length=0.5)plt.annotate(f"B({B[0]},{B[1]})", xy=(B[0], B[1]),xytext=(B[0]+0.5, B[1]))plt.xlim(0,10)plt.ylim(0,10)plt.show()plt.close()# cosine similarity between A and Bcos_sim=np.dot(A,B)/(np.linalg.norm(A)*np.linalg.norm(B))print (f"Cosine Similarity between A and B:{cos_sim}")print (f"Cosine Distance between A and B:{1-cos_sim}")
# using sklearn to calculate cosine similarityfrom sklearn.metrics.pairwise import cosine_similarity,cosine_distancescos_sim=cosine_similarity(A.reshape(1,-1),B.reshape(1,-1))print (f"Cosine Similarity between A and B:{cos_sim}")print (f"Cosine Distance between A and B:{1-cos_sim}")
# using scipy, it calculates 1-cosinefrom scipy.spatial import distancedistance.cosine(A.reshape(1,-1),B.reshape(1,-1))
Proof of the formula
Cosine similarity formula can be proved by using Law of cosines,
Consider two vectors A and B in 2-dimensions, such as,
Using Law of cosines,
You can prove the same for 3-dimensions or any dimensions in general. It follows exactly same steps as above.
Summary
We saw how cosine similarity works, how to use it and why does it work. I hope this article helped in understanding the whole concept behind this powerful metric.
Mode 1—strobed I/O

We call mode 1 as the strobed Input Output or handshake Input Output. We use this mode when the data is supplied by the input device to the microprocessor at irregular interval of time. A port which is functioned to program in mode uses three handshake signals. These handshake signals are provided by Port C. Only port A and B works in mode 1. The pins PC2, PC1, and PC0 provides handshake signals for port B when we configure it for Input port or Output port. Moreover, the pins PC7, PC6, and PC3 provides handshake signals for port A. The point to be noted that PC3 pin is a handshake line for Port A in the input terminal and also performing the output operations. If port A and B both works in mode 1 the remaining two pins of port C are used for performing the simple Input Output operations in mode 0. If either of Port A or B works in mode 1 then the rest 5 pins of port C are completely free.
Example 1: Configure Port A as strobed input port, Port B as strobed output port, and PC7, PC6 as output lines.
The required mode definition control word is shown in the figure below −
It is to be noted that the LS bit is a don't care bit. This is because all the four lines of Port C
lower are used for handshaking purposes some of which will be input pins and some others outputs. The 8255 will automatically configure these handshake pins, and so it is unimportant whether this LS bit is a 0 or a 1.
Bit 3 must be a 0 to indicate that PC7 and PC6 are output lines. In this case it does not mean that
the entire Port C upper is output, as PC5 and PC4 are used for handshaking purposes. The instructions to achieve this requirement assuming the chip select circuit are as follows.
MVI A, B4H ; Treating X as 0
OUT 23H
Design and Analysis Merge Sort

In this chapter, we will discuss merge sort and analyze its complexity.
The problem of sorting a list of numbers lends itself immediately to a divide-and-conquer strategy: split the list into two halves, recursively sort each half, and then merge the two sorted sub-lists.
In this algorithm, the numbers are stored in an array numbers[]. Here, p and q represents the start and end index of a sub-array.
Algorithm: Merge-Sort (numbers[], p, r) 
if p < r then  
q = ⌊(p + r) / 2⌋ 
Merge-Sort (numbers[], p, q) 
    Merge-Sort (numbers[], q + 1, r) 
    Merge (numbers[], p, q, r) 

Function: Merge (numbers[], p, q, r)
n1 = q – p + 1 
n2 = r – q 
declare leftnums[1...n1 + 1] and rightnums[1...n2 + 1] temporary arrays 
for i = 1 to n1 
   leftnums[i] = numbers[p + i - 1] 
for j = 1 to n2 
   rightnums[j] = numbers[q+ j] 
leftnums[n1 + 1] = ∞ 
rightnums[n2 + 1] = ∞ 
i = 1 
j = 1 
for k = p to r 
   if leftnums[i] ≤ rightnums[j] 
      numbers[k] = leftnums[i] 
      i = i + 1 
   else
      numbers[k] = rightnums[j] 
      j = j + 1 

Let us consider, the running time of Merge-Sort as T(n). Hence,
T(n)={cifn⩽12xT(n2)+dxnotherwise where c and d are constants
Therefore, using this recurrence relation,
T(n)=2iT(n2i)+i.d.n
As, i=logn,T(n)=2lognT(n2logn)+logn.d.n
=c.n+d.n.logn
Therefore, T(n)=O(nlogn)
In the following example, we have shown Merge-Sort algorithm step by step. First, every iteration array is divided into two sub-arrays, until the sub-array contains only one element. When these sub-arrays cannot be divided further, then merge operations are performed.

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Monitoring and TroubleShooting using Cloudwatch

Functions created in AWS Lambda are monitored by Amazon CloudWatch. It helps in logging all the requests made to the Lambda function when it is triggered.
Consider that the following code is uploaded in AWS Lambda with function name as lambda and cloudwatch.
exports.handler = (event, context, callback) => {
   // TODO implement
   console.log("Lambda monitoring using amazon cloudwatch");    
   callback(null, 'Hello from Lambda');
};
When the function is tested or triggered, you should see an entry in Cloudwatch. For this purpose,  go to AWS services and click CloudWatch.
Select logs from left side.
When you click Logs, it has the Log Groups of AWS Lambda function created in your account. Select anyAWS Lambda function and check the details. Here, we are referring to Lambda function with name:lambdaandcloudwatch. The logs added to the Lambda function are displayed here as shown below −
Now, let us add S3 trigger to the Lambda function and see the logs details in CloudWatch as shown below −
Let us update AWS Lambda code to display the file uploaded and bucket name as shown in the code given below −
exports.handler = (event, context, callback) => {
   // TODO implement
   console.log("Lambda monitoring using amazon cloudwatch");
   const bucket = event.Records[0].s3.bucket.name;
   const filename = event.Records[0].s3.object.key;
   const message = `File is uploaded in - ${bucket} -> ${filename}`;
   console.log(message);
   callback(null, 'Hello from Lambda');
};
Now, add file in s3storetestlambdaEventbucket as shown −
When the file is uploaded, AWS Lambda functions will get triggered and the console log messages from Lambda code are displayed in CloudWatch as shown below −
If there is any error, CloudWatch gives the error details as shown below −
Note that we have referred to the bucket name wrongly in AWS Lambda code as shown −
exports.handler = (event, context, callback) => {
   // TODO implement
   console.log("Lambda monitoring using amazon cloudwatch");
   const bucket = event.Records[0].bucket.name;
   const filename = event.Records[0].s3.object.key;
   const message = `File is uploaded in - ${bucket} -> ${filename}`;
   console.log(message);
   callback(null, 'Hello from Lambda');
};
The bucket name reference from the event is wrong. Thus, we should see an error displayed in CloudWatch as shown below −
The details of the Lambda function execution can be seen in the metrics. Click Metrics displayed in the left side.
The graph details for the lambda function lambdaandcloudwatch are as shown below −
It gives details such as the duration for which the Lambda function is executed, number of times it is invoked and the errors from the Lambda function.

    35 Lectures 
     7.5 hours 

 Mr. Pradeep Kshetrapal

    30 Lectures 
     3.5 hours 

 Priyanka Choudhary

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    51 Lectures 
     6 hours 

 Manuj Aggarwal

    41 Lectures 
     5 hours 

 AR Shankar

    14 Lectures 
     1 hours 

 Zach Miller
 Print
 Add Notes
 Bookmark this page
java.time.Duration.ofSeconds() Method Example

The java.time.Duration.ofSeconds(long seconds) method obtains a Duration representing a number of seconds and an adjustment in nanoseconds.
Following is the declaration for java.time.Duration.ofSeconds(long seconds) method.
public static Duration ofSeconds(long seconds, long nanoAdjustment)

seconds − the number of seconds, positive or negative.
seconds − the number of seconds, positive or negative.
nanoAdjustment − the nanosecond adjustment to the number of seconds, positive or negative.
nanoAdjustment − the nanosecond adjustment to the number of seconds, positive or negative.
a Duration, not null.
ArithmeticException − if the adjustment causes the seconds to exceed the capacity of Duration.
The following example shows the usage of java.time.Duration.ofSeconds(long seconds, long nanoAdjustment) method.
package com.tutorialspoint;

import java.time.Duration;

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

      Duration duration = Duration.ofSeconds(2);
      Duration duration1 = duration.plus(Duration.ofSeconds(5));
      System.out.println(duration1.toMillis());
   }
}
Let us compile and run the above program, this will produce the following result −
7000

 Print
 Add Notes
 Bookmark this page
How to use function Alias in PowerShell?

Like the Parameter alias, we can also set the function alias name to refer to the function as a different name.
function Test-NewConnection{
   [CmdletBinding()]
   [Alias("TC")]
   param(
      [Parameter(Mandatory=$true)]
      [String]$Server
   )
   Write-Output "Testing $server connection"
}
Now, instead of the Test-NewConnection function name, you can directly use the function alias “TC” as shown below.
PS C:\> Tc -Server "Test1-win2k16"
Testing Test1-win2k16 connection
What is an inline function in C language?

The inline function can be substituted at the place where the function call is happening. Function substitution is always compiler choice.
In an inline function, a function call is replaced by the actual program code.
In an inline function, a function call is replaced by the actual program code.
Most of the Inline functions are used for small computations. They are not suitable for large computing.
Most of the Inline functions are used for small computations. They are not suitable for large computing.
An inline function is similar to a normal function. The only difference is that we place a keyword inline before the function name.
An inline function is similar to a normal function. The only difference is that we place a keyword inline before the function name.
Inline functions are created with the following syntax −
inline function_name (){
   //function definition
}
Following is the C program for inline functions −
#include<stdio.h>
inline int mul(int a, int b) //inline function declaration{
   return(a*b);
}
int main(){
   int c;
   c=mul(2,3);
   printf("Multiplication:%d\n",c);
   return 0;
}
When the above program is executed, it produces the following result −
6
How to get android application version name?

This example demonstrate about How to get android application version name.
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:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken text view to show application version name.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.P)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
      WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      PackageManager pm = getApplicationContext().getPackageManager();
      String pkgName = getApplicationContext().getPackageName();
      PackageInfo pkgInfo = null;
      try {
         pkgInfo = pm.getPackageInfo(pkgName, 0);
      } catch (PackageManager.NameNotFoundException e) {
         e.printStackTrace();
      }
      String ver = pkgInfo.versionName;
      textView.setText("" +ver);
   }
}
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 –
Click here to download the project code