code-rag-bench/online-tutorials huggingface dataset:
Python – Convert Matrix to Custom Tuple Matrix

10 Jul, 2022
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have application in data domains as Matrix is integral DS that is used. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[4, 5], [7, 3]], add_list = [‘Gfg’, ‘best’] Output : [(‘Gfg’, 4), (‘Gfg’, 5), (‘best’, 7), (‘best’, 3)] Input : test_list = [[4, 5]], add_list = [‘Gfg’] Output : [(‘Gfg’, 4), (‘Gfg’, 5)]
Method #1 : Using loop + zip() The combination of above functionalities can be used to solve this problem. In this, we perform the task of binding custom value to each element of row using zip(). This is brute force way to perform this task. 
Python3
# Python3 code to demonstrate working of# Convert Matrix to Custom Tuple Matrix# Using zip() + loop # initializing liststest_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]] # printing original listprint("The original list is : " + str(test_list)) # initializing List elementsadd_list = ['Gfg', 'is', 'best'] # Convert Matrix to Custom Tuple Matrix# Using zip() + loopres = []for idx, ele in zip(add_list, test_list):  for e in ele:    res.append((idx, e)) # printing resultprint("Matrix after conversion : " + str(res))
  Method #2 : Using list comprehension + zip() This is yet another way in which this task can be performed. In this, we perform a similar task as the above method, just as a shorthand. 
Python3
# Python3 code to demonstrate working of# Convert Matrix to Custom Tuple Matrix# Using list comprehension + zip() # initializing liststest_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]] # printing original listprint("The original list is : " + str(test_list)) # initializing List elementsadd_list = ['Gfg', 'is', 'best'] # Convert Matrix to Custom Tuple Matrix# Using list comprehension + zip()res = [(ele1, ele2) for ele1, sub in zip(add_list, test_list) for ele2 in sub] # printing resultprint("Matrix after conversion : " + str(res))
The Time and Space Complexity is the same for both methods:
Time Complexity: O(n2)
Space Complexity: O(n)
harshmaster07705
Python List-of-Tuples
Python matrix-program
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Continue Statement in C/C++

26 Aug, 2019
Continue is also a loop control statement just like the break statement. continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.As the name suggest the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and next iteration of the loop will begin.Syntax:
continue;

Example:Consider the situation when you need to write a program which prints number from 1 to 10 and but not 6. It is specified that you have to do this using loop and only one loop is allowed to use.Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of iterator with 6. If it is equal to 6 we will use the continue statement to continue to next iteration without printing anything otherwise we will print the value.Below is the implementation of the above idea:
C
C++
// C program to explain the use // of continue statement #include <stdio.h>  int main() {    // loop from 1 to 10     for (int i = 1; i <= 10; i++) {           // If i is equals to 6,         // continue to next iteration         // without printing         if (i == 6)             continue;           else            // otherwise print the value of i             printf("%d ", i);     }       return 0; }
// C++ program to explain the use// of continue statement  #include <iostream>using namespace std;  int main(){    // loop from 1 to 10    for (int i = 1; i <= 10; i++) {          // If i is equals to 6,        // continue to next iteration        // without printing        if (i == 6)            continue;          else            // otherwise print the value of i            cout << i << " ";    }      return 0;}
1 2 3 4 5 7 8 9 10 

The continue statement can be used with any other loop also like while or do while in a similar way as it is used with for loop above.
Exercise Problem:Given a number n, print triangular pattern. We are allowed to use only one loop.
Input: 7
Output:
*
* * 
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Solution : Print the pattern by using one loop | Set 2 (Using Continue Statement)
This article is contributed by Harsh Agarwal. 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.
C Basics
CPP-Basics
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between single-quoted and double-quoted strings in PHP?

10 Apr, 2022
Single or double quotes in PHP programming are used to define a string. But, there are lots of differences between these two. Single-quoted Strings: It is the easiest way to define a string. You can use it when you want the string to be exactly as it is written. All the escape sequences like \r or \n, will be output as specified instead of having any special meaning. Single-quote is usually faster in some cases. The special case is that if you to display a literal single-quote, escape it with a backslash (\) and if you want to display a backslash, you can escape it with another backslash (\\). 
Below program illustrates the Single-quoted Strings: 
Program 1: 
php
<?php // A simple stringecho 'I am a geek. ';echo"\n"; // use of back-slash to display string with apostropheecho 'It\'ll be interesting to know about the string. ';echo"\n"; // to escape the backslash within the stringecho 'A \\ is named as backslash. ';echo"\n"; // The variable will not be evaluated if used directly//within the single-quoted string$string = 'geeks';echo 'This is a portal for $string. ';echo"\n"; // The \n will be displayed as it is without having any//special meaning.echo 'This is a portal for \n geeks. ';?>
Output:
I am a geek. 
It'll be interesting to know about the string. 
A \ is named as backslash. 
This is a portal for $string. 
This is a portal for \n geeks.
Double-quoted strings: By using Double quotes the PHP code is forced to evaluate the whole string. The main difference between double quotes and single quotes is that by using double quotes, you can include variables directly within the string. It interprets the Escape sequences. Each variable will be replaced by its value. 
Below program illustrates the Double-quoted Strings: 
Program 2: 
php
<?php // A simple string.echo "I am a geek."; echo"\n"; // Nothing extra is needed hereecho "It'll be interesting to know about the string."; echo"\n"; // \n is working hereecho "This is a simple string."; echo"\n"; // Variables are included directly$string = 'ABC';echo "The word is $string."; ?>
Output:
I am a geek.
It'll be interesting to know about the string.
This is a simple string.
The word is ABC.
Let us understand the differences in a tabular form -:
Syntax -:
‘string’
Syntax -:
“string”
Example -:
‘GeeksforGeeks’
Example -:
“GeeksforGeeks”
MeghaKakkar
mayank007rawa
PHP-string
Picked
PHP
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Key index in Dictionary

19 Jul, 2019
The concept of dictionary is similar to that of map data structure in C++ language, but with the exception that keys in dictionary has nothing to do with its ordering, i.e it is not sorted unlike C++ in which the keys are sorted internally. This opens up the problem in which we might have to find the exact position of key in the dictionary. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + enumerate()The combination of above functions together can perform this particular task. In this, first the dictionary is converted to a pair tuple and then the first element of tuple being the key is checked for index.
# Python3 code to demonstrate working of# Key index in Dictionary# Using list comprehension + enumerate()  # initializing dictionarytest_dict = {'all' : 1, 'food' : 2, 'good' : 3, 'have' : 4}  # initializing search key stringsearch_key = 'good'  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using list comprehension + enumerate()# Key index in Dictionarytemp = list(test_dict.items()) res = [idx for idx, key in enumerate(temp) if key[0] == search_key]  # printing result print("Index of search key is : " + str(res))
The original dictionary is : {'have': 4, 'all': 1, 'good': 3, 'food': 2}
Index of search key is : [2]

 
Method #2 : Using list() + keys() + index()The combination of above functions can also be used to perform this particular task. In this, the dictionary keys are first converted to list and then found the desired one using the index method.
# Python3 code to demonstrate working of# Key index in Dictionary# Using list() + keys() + index()  # initializing dictionarytest_dict = {'all' : 1, 'food' : 2, 'good' : 3, 'have' : 4}  # initializing search key stringsearch_key = 'good'  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using list() + keys() + index()# Key index in Dictionaryres = list(test_dict.keys()).index(search_key)  # printing result print("Index of search key is : " + str(res))
The original dictionary is : {'food': 2, 'have': 4, 'good': 3, 'all': 1}
Index of search key is : 2

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IntStream iterator() in Java

21 Mar, 2018
IntStream iterator() returns an iterator for the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Syntax :
PrimitiveIterator.OfInt iterator()

Where, PrimitiveIterator.OfInt is an Iterator 
specialized for int values.

Return Value : IntStream iterator() returns the element iterator for this stream.
Example 1 :
// Java code for IntStream iterator()import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(2, 4, 6, 8);          // Using IntStream iterator() to return        // an iterator for elements of the stream        PrimitiveIterator.OfInt answer = stream.iterator();          // Displaying the stream elements        while (answer.hasNext()) {            System.out.println(answer.nextInt());        }    }}
2
4
6
8

Example 2 :
// Java code for IntStream iterator()import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream which includes        // lower bound element but excludes        // upper bound element        IntStream stream = IntStream.range(2, 8);          // Using IntStream iterator() to return        // an iterator for elements of the stream        PrimitiveIterator.OfInt answer = stream.iterator();          // Displaying the stream elements        while (answer.hasNext()) {            System.out.println(answer.nextInt());        }    }}
2
3
4
5
6
7

Java - util package
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
Differences between JDK, JRE and JVM
Initializing HashSet in C#

To initialize a HashSet.
var h = new HashSet<string>(arr1);
Above, we have set an array in the HashSet. The following is the array −
string[] arr1 = {
   "electronics",
   "accessories”,
   "electronics",
};
The following is an example showing how to implement HashSet in C# −
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      string[] arr1 = {
         "electronics",
         "accessories”,
         "electronics",
      };

      Console.WriteLine(string.Join(",", arr1));

      // HashSet
      var h = new HashSet(arr1);
      // eliminates duplicate words
      string[] arr2 = h.ToArray();
      Console.WriteLine(string.Join(",", arr2));
   }
}
Python Design Patterns - Abstract Factory

The abstract factory pattern is also called factory of factories. This design pattern comes under the creational design pattern category. It provides one of the best ways to create an object.
It includes an interface, which is responsible for creating objects related to Factory.
The following program helps in implementing the abstract factory pattern.
class Window:
   __toolkit = ""
   __purpose = ""

   def __init__(self, toolkit, purpose):
      self.__toolkit = toolkit
      self.__purpose = purpose
   
   def getToolkit(self):
      return self.__toolkit
   
   def getType(self):
      return self.__purpose

class GtkToolboxWindow(Window):
   def __init__(self):
      Window.__init__(self, "Gtk", "ToolboxWindow")

class GtkLayersWindow(Window):
   def __init__(self):
      Window.__init__(self, "Gtk", "LayersWindow")

class GtkMainWindow(Window):
   def __init__(self):
      Window.__init__(self, "Gtk", "MainWindow")

class QtToolboxWindow(Window):
   def __init__(self):
      Window.__init__(self, "Qt", "ToolboxWindow")

class QtLayersWindow(Window):
   def __init__(self):
      Window.__init__(self, "Qt", "LayersWindow")

class QtMainWindow(Window):
   def __init__(self):
      Window.__init__(self, "Qt", "MainWindow")

# Abstract factory class
class UIFactory:
   def getToolboxWindow(self): pass
   def getLayersWindow(self): pass
   def getMainWindow(self): pass

class GtkUIFactory(UIFactory):
   def getToolboxWindow(self):
      return GtkToolboxWindow()
   def getLayersWindow(self):
      return GtkLayersWindow()
   def getMainWindow(self):
      return GtkMainWindow()

class QtUIFactory(UIFactory):
   def getToolboxWindow(self):
      return QtToolboxWindow()
   def getLayersWindow(self):
      return QtLayersWindow()
   def getMainWindow(self):
      return QtMainWindow()

if __name__ == "__main__":
   gnome = True
   kde = not gnome
   
   if gnome:
      ui = GtkUIFactory()
   elif kde:
      ui = QtUIFactory()
   
   toolbox = ui.getToolboxWindow()
   layers = ui.getLayersWindow()
   main = ui.getMainWindow()
   
   print "%s:%s" % (toolbox.getToolkit(), toolbox.getType())
   print "%s:%s" % (layers.getToolkit(), layers.getType())
   print "%s:%s" % (main.getToolkit(), main.getType())
The above program generates the following output −
In the above program, the abstract factory creates objects for each window. It calls for each method, which executes the output as expected.

    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
How to subtract seconds from all the date records in a MySQL column?

Let us first create a table −
mysql> create table DemoTable833(ArrivalTime datetime);
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable833 values('2019-01-10 12:40:50');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable833 values('2019-02-16 11:10:30');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable833 values('2018-03-17 10:00:10');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable833;
This will produce the following output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-01-10 12:40:50 |
| 2019-02-16 11:10:30 |
| 2018-03-17 10:00:10 |
+---------------------+
3 rows in set (0.00 sec)
Following is the query to subtract seconds from a MySQL date −
mysql> select ArrivalTime-interval 10 SECOND from DemoTable833;
This will produce the following output −
+--------------------------------+
| ArrivalTime-interval 10 SECOND |
+--------------------------------+
| 2019-01-10 12:40:40            |
| 2019-02-16 11:10:20            |
| 2018-03-17 10:00:00            |
+--------------------------------+
3 rows in set (0.00 sec)
Check if a number is a Krishnamurthy Number or not in C++

Here we will see how to check a number is Krishnamurty number or not. A number is Krishnamurty number, if the sum of the factorial of each digit is the same as the number. For example, if a number is 145, then sum = 1! + 4! + 5! = 1 + 24 + 120 = 145. So this is a Krishnamurty number,
The logic is simple, we have to find the factorial of each number, and find the sum, then if that is the same as a given number, the number is Krishnamurty number. Let us see the code to get a better idea.
 Live Demo
#include <iostream>
#include <cmath>>
using namespace std;
long factorial(int n){
   if(n <= 1){
      return 1;
   }
   return n * factorial(n - 1);
}
bool isKrishnamurty(int number) {
   int temp = number;
   int sum = 0;
   while(number > 0){
      sum += factorial(number % 10);
      number /= 10;
   }
   if(sum == temp){
      return true;
   }
   return false;
}
int main() {
   int n = 145;
   if(isKrishnamurty(n)){
      cout << n << " is Krishnamurty Number";
   } else {
      cout << n << " is not Krishnamurty Number";
   }
}
145 is Krishnamurty Number
unlink() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <unistd.h> 
int unlink(const char *pathname); 


int unlink(const char *pathname); 

unlink() deletes a name from the filesystem. If that name was the
last link to a file and no processes have the file open the file is
deleted and the space it was using is made available for reuse.
If the name was the last link to a file but any processes still have
the file open the file will remain in existence until the last file
descriptor referring to it is closed.
If the name referred to a symbolic link the link is removed. 
If the name referred to a socket, fifo or device the name for it is
removed but processes which have the object open may continue to use
it.
On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.
SVr4, 4.3BSD, POSIX.1-2001. 
Infelicities in the protocol underlying NFS can cause the unexpected
disappearance of files which are still being used.
rm (1)
rm (1)
chmod (2)
chmod (2)
link (2)
link (2)
mknod (2)
mknod (2)
open (2)
open (2)
path_resolution (2)
path_resolution (2)
rename (2)
rename (2)
rmdir (2)
rmdir (2)
unlinkat (2)
unlinkat (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How do I create a random four-digit number in MySQL?

Let us first create a table −
mysql> create table DemoTable717 (
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserPassword int
);
Query OK, 0 rows affected (0.81 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable717(UserPassword) values(1454343);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable717(UserPassword) values(674654);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable717(UserPassword) values(989883);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable717(UserPassword) values(909983);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable717;
This will produce the following output -
+--------+--------------+
| UserId | UserPassword |
+--------+--------------+
| 1      | 1454343      |
| 2      | 674654       |
| 3      | 989883       |
| 4      | 909983       |
+--------+--------------+
4 rows in set (0.00 sec)
Following is the query to create a random 4 digit and set for the “UserPassword” column −
mysql> update DemoTable717
   SET UserPassword=(select floor(0+ RAND() * 10000));
Query OK, 4 rows affected (0.22 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable717;
This will produce the following output -
+--------+--------------+
| UserId | UserPassword |
+--------+--------------+
| 1      | 4319         |
| 2      | 3902         |
| 3      | 6553         |
| 4      | 1060         |
+--------+--------------+
4 rows in set (0.00 sec)
Python Pillow - Environment Setup

This chapter discusses how to install pillow package in your computer.
Installing pillow package is very easy, especially if you’re installing it using pip.
To install pillow using pip, just run the below command in your command prompt −
python -m pip install pip
python -m pip install pillow

In case, if pip and pillow are already installed in your computer, above commands will simply mention the ‘requirement already satisfied’as shown below −

    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
Java this Keyword

❮ Java Keywords

Using this with a class attribute (x):
public class Main {
  int x;

  // Constructor with a parameter
  public Main(int x) {
    this.x = x;
  }

  // Call the constructor
  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println("Value of x = " + myObj.x);
  }
}


Try it Yourself »

The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate 
the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
this can also be used to:
Invoke current class constructor
Invoke current class method
Return the current class object
Pass an argument in the method call
Pass an argument in the constructor call
Read more about objects in our Java Classes/Objects Tutorial.
Read more about constructors in our Java Constructors Tutorial.
Read more about methods in our Java Methods Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Encrypt and Decrypt a string in MySQL?

To encrypt and decrypt in MySQL, use the AES_ENCRYPT() and AES_DECRYPT() in MySQL −
insert into yourTableName values(AES_ENCRYPT(yourValue,yourSecretKey));

select cast(AES_DECRYPT(yourColumnName, yourSecretKey) as char) from
yourTableName;
To understand the above syntax, let us first create a table −
mysql> create table demo63
−> (
−> value blob
−> );
Query OK, 0 rows affected (2.60 sec)
Insert some records into the table with the help of insert command. We are encrypting while inserting −
mysql> insert into demo63 values(AES_ENCRYPT('John','PASS'));
Query OK, 1 row affected (0.18 sec)

mysql> insert into demo63 values(AES_ENCRYPT('David','PASS'));
Query OK, 1 row affected (0.41 sec)

mysql> insert into demo63 values(AES_ENCRYPT('123456','PASS'));
Query OK, 1 row affected (0.41 sec)
Display records from the table using select statement −
mysql> select *from demo63;
This will produce the following output −
+------------------------------------+
| value                              |
+------------------------------------+
| 0x16D8A4F11321D761920783BF96BB8314 |
| 0x0A85099F705F21D27B0129C54C4473AA |
| 0xAB7C6D6068BC100B0F04D1C4EA068AC9 |
+------------------------------------+
3 rows in set (0.00 sec)
Following is the query to decrypt −
mysql> select cast(aes_decrypt(value, 'PASS') AS char) from demo63;
This will produce the following output −
+------------------------------------------+
| cast(aes_decrypt(value, 'PASS') AS char) |
+------------------------------------------+
| John                                     |
| David                                    |
| 123456                                   |
+------------------------------------------+
3 rows in set (0.00 sec)
What is an anonymous array and explain with an example in Java?

An array is a data structure/container/objectthat stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.
The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.
Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.
For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −
System.out.println(myArray[3]);
//25
In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −
int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
Or, you can directly assign values with in flower braces separating them with commas (,) as −
int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};
In addition to the above specified ways you can create an array without specifying any name such arrays are known as anonymous arrays. Since it doesn’t have name to refer you can use it only once in your program. Generally, anonymous arrays are passed as arguments to methods.
You can create an anonymous array by initializing it at the time of creation.
new int[] { 1254, 5452, 5743, 9984}; //int array

new String[] {"Java", "JavaFX", "Hadoop"}; //String array
In the following Java program the arrayToUpperCase() method accepts an array of Strings, converts each String to upper case and prints the results.
To this method we are passing an anonymous array of Strngs as a parameter.
public class AnonymousArray {
   public static void arrayToUpperCase(String [] array) {
      for(int i=0; i< array.length; i++) {
         char[] ch = array[i].toCharArray();
         for(int j=0; j<ch.length; j++){
            ch[j] = Character.toUpperCase(ch[j]);
         }
         System.out.println(new String(ch));
      }
   }
   public static void main(String args[]) {
      arrayToUpperCase(new String[] {"Krishna", "Vishnu", "Dhana", "Rupa", "Raja", "Kavya"});
   }
}
KRISHNA
VISHNU
DHANA
RUPA
RAJA
KAVYA
How to clear the EEPROM with Arduino?

Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data.
In this article, we will see how to clear the EEPROM, i.e., set all its bytes to 0. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from − File → Examples → EEPROM.
We will look at the eeprom_clear example. It is very easy. You essentially use the EEPROM.write() function, and iterate over the length of the EEPROM, and write 0 at each address.
We begin with the inclusion of the library.
#include <EEPROM.h>
Within the Setup, you set pin 13 as output, and connect an LED to it. Then you make the LED glow once we are done. This is optional though. The code snippet of interest is the for loop wherein we iterate over each address in the EEPROM, till we reach the end of the EEPROM, and write 0 to each address.
void setup() {
   // initialize the LED pin as an output.
   pinMode(13, OUTPUT);

   for (int i = 0 ; i < EEPROM.length() ; i++) {
      EEPROM.write(i, 0);
   }

   // turn the LED on when we're done
   digitalWrite(13, HIGH);
}
Nothing happens in the loop.
void loop() {
   /** Empty loop. **/
}
How to sort an HTML table using JavaScript?

To sort an HTML table using JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Sort a HTML Table Alphabetically</title>
<style>
   button {
      padding: 10px;
      margin-bottom: 5px;
      font-size: 16px;
      font-weight: bold;
   }
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   table {
      border-spacing: 0;
      width: 100%;
      border: 1px solid #ddd;
   }
   th, td {
      border-top: 1px solid black;
      text-align: left;
      padding: 16px;
   }
</style>
</head>
<body>
<h1>Sorting table example</h1>
<button onclick="sortTable()">Sort</button>
<table class="filterTable">
<tr>
<th>Name</th>
<th>BirthDay Month</th>
</tr>
<tr>
<td>Ron</td>
<td>January</td>
</tr>
<tr>
<td>Shawn</td>
<td>April</td>
<tr>
<tr>
<td>Caleb</td>
<td>December</td>
</tr>
<tr>
<td>Bruno</td>
<td>February</td>
</tr>
<tr>
<td>Jack</td>
<td>October</td>
</tr>
<tr>
<td>Max</td>
<td>November</td>
</tr>
</table>
<script>
   function sortTable() {
      var filterTable, rows, sorted, i, x, y, sortFlag;
      filterTable = document.querySelector(".filterTable");
      sorted = true;
      while (sorted) {
         sorted = false;
         rows = filterTable.rows;
         for (i = 1; i < rows.length - 1; i++) {
            sortFlag = false;
            x = rows[i].getElementsByTagName("TD")[0];
            y = rows[i + 1].getElementsByTagName("TD")[0];
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
               sortFlag = true;
               break;
            }
         }
         if (sortFlag) {
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            sorted = true;
         }
      }
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the Sort button −
How to make a pair of columns unique in MySQL?

To make a pair of columns unique, use UNIQUE with ALTER TABLE command. Following is the syntax −
alter table yourTableName add unique yourUniqueName(yourColumnName1,yourColumnName2,...N);
Let us first create a table −
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(100),
   StudentLastName varchar(100),
   StudentAge int,
   StudentPhoneNumber varchar(20)
);
Query OK, 0 rows affected (0.81 sec)
Following is the query to make a pair of unique columns in MySQL −
mysql> alter table DemoTable add unique DemoTable_unique_StudentFirstName_StudentPhoneNumber(StudentFirstName,StudentPhoneNumber);
Query OK, 0 rows affected (0.40 sec)
Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber) values('John','Doe',21,'9878567878');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber) values('John','Smith',23,'7654674545');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber)
values('John','Brown',21,'9878567878');
ERROR 1062 (23000): Duplicate entry 'John-9878567878' for key 'DemoTable_unique_StudentFirstName_StudentPhoneNumber'
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+------------------+-----------------+------------+--------------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge | StudentPhoneNumber |
+-----------+------------------+-----------------+------------+--------------------+
|         1 | John             | Doe             | 21         | 9878567878         |
|         2 | John             | Smith           | 23         | 7654674545         |
+-----------+------------------+-----------------+------------+--------------------+
2 rows in set (0.00 sec)
Python 3 - File readlines() Method

The method readlines() reads until EOF using readline() and returns a list containing the lines. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.
An empty string is returned only when EOF is encountered immediately.
Following is the syntax for readlines() method −
fileObject.readlines( sizehint );

sizehint − This is the number of bytes to be read from the file.
This method returns a list containing the lines.
The following example shows the usage of readlines() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python3

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

line = fo.readlines()
print ("Read Line: %s" % (line))

line = fo.readlines(2)
print ("Read Line: %s" % (line))

# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 
   'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line\n']
Read Line: 


    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
How to convert Wrapper value array list into primitive array in Java?

Here, to convert Wrapper value array list into primitive array, we are considering Integer as Wrapper, whereas double as primitive.
At first, declare an Integer array list and add elements to it −
ArrayList < Integer > arrList = new ArrayList < Integer > ();
arrList.add(5);
arrList.add(10);
arrList.add(15);
arrList.add(20);
arrList.add(25);
arrList.add(30);
arrList.add(45);
arrList.add(50);
Now, convert the above Integer array list to primitive array. Firstly, we set the same size for the double array and then assigned each value
final double[] arr = new double[arrList.size()];
int index = 0;
for (final Integer value: arrList) {
   arr[index++] = value;
}
The following is an example to convert an Integer (wrapper) array list into a double array (primitive) −
 Live Demo
import java.util.ArrayList;
public class Demo {
   public static void main(String[] args) {
      ArrayList<Integer>arrList = new ArrayList<Integer>();
      arrList.add(5);
      arrList.add(10);
      arrList.add(15);
      arrList.add(20);
      arrList.add(25);
      arrList.add(30);
      arrList.add(45);
      arrList.add(50);
      final double[] arr = new double[arrList.size()];
      int index = 0;
      for (final Integer value: arrList) {
         arr[index++] = value;
      }
      System.out.println("Elements of double array...");
      for (Double i: arr) {
         System.out.println(i);
      }
   }
}
Elements of double array...
5.0
10.0
15.0
20.0
25.0
30.0
45.0
50.0
How do you get the file size in C#?

The FileInfo class is used to deal with file and its operations in C#.
It provides properties and methods that are used to create, delete and read file. It uses
StreamWriter class to write data to the file. It is a part of System.IO namespace.
The Directory property retrieves an object that represents the parent directory of a file.
The DirectoryName property retrieves the full path of the parent directory of a file.
The Exists property checks for the presence of a file before operating on it.
The IsReadOnly property retrieves or sets a value that specifies whether a file can be
modified.
The Length retrieves the size of a file.
The Name retrieves the name of a file.
class Program{
   public static void Main(){
      var path = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp\Data.csv";
      long length = new System.IO.FileInfo(path).Length;
      System.Console.WriteLine(length);
   }
}
12
class Program{
   public static void Main(){
      var path = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp";
      DirectoryInfo di = new DirectoryInfo(path);
      FileInfo[] fiArr = di.GetFiles();
      Console.WriteLine("The directory {0} contains the following files:", di.Name);
      foreach (FileInfo f in fiArr)
         Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
   }
}
The directory ConsoleApp contains the following files:
The size of ConsoleApp.csproj is 333 bytes.
The size of Data.csv is 12 bytes.
The size of Program.cs is 788 bytes.
How to Fix: Length of values does not match length of index - GeeksforGeeks

22 Nov, 2021

In this article we will fix the error: The length of values does not match the length of the index in Python.
Python3
 

 
 










# importing pandas 
import pandas as pd 
  
sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4,  
                4.6, 5.0, 4.4, 4.9] 
sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4,  
               4.9, 5.1, 5.2, 5.3] 
petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8] 
petal_width = [3.6, 5.6, 5.4, 4.6, 4.4, 5.0, 4.9] 
  
# DataFrame with 2 columns 
df = pd.DataFrame({'sepal_length(cm)': sepal_length, 
                   'sepal_width(cm)': sepal_width}) 
  
df['petal_length(cm)'] = petal_length 
df['petal_width(cm)'] = petal_width 
  
print(df) 






Output:
ValueError: Length of values (7) does not match length of index (10)
The length of the index of the pandas DataFrame(i.e length of the column of present DataFrame) which is 10 in this case is not equal to the length of the new list or NumPy array which is 7 in this case.
pd.Index.size!=len(petal_width)
This error can be fixed by preprocessing the new list or NumPy array that is going to be a column of the DataFrame by using the pandas Series() function which actually converts the list or NumPy array into the size of the DataFrame column length by adding NaN if list or NumPy array has lesser length else if the list or NumPy has greater length then it takes the list or NumPy array with the length of columns of the pandas dataframe.
Syntax For list:
Consider list1 as a python list
df['new_column'] = pd.Series(list1)
Syntax For NumPy array:
Consider numarr as a numpy array
df['new_column'] = pd.Series(numarr)
Python3
 

 
 










# importing pandas 
import pandas as pd 
  
# importing numpy 
import numpy as np 
sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 
                4.6, 5.0, 4.4, 4.9] 
sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 
               4.9, 5.1, 5.2, 5.3] 
petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8] 
  
# numpy array of length 7 
petal_width = np.array([3.6, 5.6, 5.4, 4.6, 4.4,  
                        5.0, 4.9]) 
  
# DataFrame with 2 columns of length 10 
df = pd.DataFrame({'sepal_length(cm)': sepal_length, 
                   'sepal_width(cm)': sepal_width}) 
  
# Adding list to pandas DataFrame 
df['petal_length(cm)'] = pd.Series(petal_length) 
  
# Adding numpy array to pandas DataFrame 
df['petal_width(cm)'] = pd.Series(petal_width) 
  
print(df) 






Output:

Picked


Python How-to-fix


Python

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

22 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.getctime() method in Python is used to get system’s ctime of the specified path. Here ctime refers to the last metadata change for specified path in UNIX while in Windows, it refers to path creation time.This method returns a floating point value which represents the number of seconds since the epoch. This method raise OSError if the file does not exist or is somehow inaccessible.
Note: The epoch represents the point where the time starts. It is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC).
Syntax: os.path.getctime(path)
Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a floating-point value of class ‘float’ that represents the ctime (in seconds) for the specified path.
Code #1: Use of os.path.getctime() method
# Python program to explain os.path.getctime() method     # importing os and time module import osimport time  # Pathpath = '/home/User/Documents/file.txt'  # Get the ctime of last# for the specified pathc_time = os.path.getctime(path)print("ctime since the epoch:", c_time)  # convert the ctime in# seconds since epoch# to local timelocal_time = time.ctime(c_time)print("ctime (Local time):", local_time)
ctime since the epoch: 1558447897.3122742
ctime (Local time): Tue May 21 19:41:37 2019

Code #2: Handling error while using os.path.getctime() method
# Python program to explain os.path.getctime() method     # importing os, time and sys module import osimport sysimport time  # Pathpath = '/home/User/Documents/file2.txt'  # Get the ctime # for the specified pathtry:    c_time = os.path.getctime(path)    print("ctime since the epoch:", c_time)  except OSError:    print("Path '%s' does not exists or is inaccessible" %path)    sys.exit()  # convert ctime in# seconds since epoch# to local timelocal_time = time.ctime(c_time)print("ctime(Local time):", local_time)    # above code will print# path does not exists or is inaccessible'# if the specified path does not# exists or is inaccessible  
Path '/home/User/Documents/file2.txt' does not exists or is inaccessible

Reference: https://docs.python.org/3/library/os.path.html
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to Trim a String in Arduino?

Sometimes, a string can contain leading or trailing whitespaces. Arduino has a trim() function that removes all these leading/trailing whitespaces from the string.
String1.trim()
Where String1 is the string that you need to trim. Please note that this function doesn’t return anything. String1 itself is modified.
The following example illustrates this −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   String string1 = " Hello World! ";
   Serial.println(string1);
   string1.trim();
   Serial.println(string1);
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, string1 was modified in place.
Checking memory_limit in PHP

The ‘memory_limit’ is the maximum amount of server memory that a single PHP script is allowed to use. The value needs to be converted before comparing the threshold of memory.
For example − 64M is converted to 64 * 1024 * 1024. After this, the comparison is done and the result is printed out.
<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
   if ($matches[2] == 'M') {
      $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
   } else if ($matches[2] == 'K') {
      $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
   }
}
$ok = ($memory_limit >= 640 * 1024 * 1024); // at least 64M?
echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';
The output will be the memory limit of that specific environment setup.