code-rag-bench/online-tutorials huggingface dataset:
SQL Query to Display First 50% Records from Employee Table

13 Apr, 2021
Here, we are going to see how to display the first 50% of records from an Employee Table in MS SQL server’s databases.
For the purpose of the demonstration, we will be creating an Employee table in a database called “geeks“.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE Employee(
ID INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(30) NOT NULL,
PHONE INT(10) NOT NULL UNIQUE,
EMAIL VARCHAR(30) NOT NULL UNIQUE,
DATE_OF_JOINING DATE);
You can view the table description using the below command:
 EXEC SP_COLUMNS Employee;
Use the below statement to add data to the Employee table:
INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)
VALUES
('Yogesh Vaishnav', 0000000001, 'yogesh@mail.com', '2019-10-03'),
('Vishal Vishwakarma', 0000000002, 'chicha@mail.com', '2019-11-07'),
('Ajit Yadav', 0000000003, 'ppa@mail.com', '2019-12-12'),
('Ashish Yadav', 0000000004, 'baba@mail.com', '2019-12-25'),
('Tanvi Thakur', 0000000005, 'tanvi@mail.com', '2020-01-20'),
('Sam', 0000000006, 'sam@mail.com', '2020-03-03'),
('Ron', 0000000007, 'ron@mail.com', '2020-05-16'),
('Sara', 0000000008, 'sara@mail.com', '2020-07-01'),
('Zara', 0000000009, 'zara@mail.com', '2020-08-20'),
('Yoji', 0000000010, 'yoji@mail.com', '2020-03-10');
To verify the contents of the table use the below statement:
SELECT * FROM Employee;
Now let’s retrieve the first 50% of the records from the Employee Table.
In MS SQL we can directly retrieve the first 50% of the records with the help of top and percent clauses. A simple syntax for the same is given below:
Syntax :
Select top N percent * from <table_name>; /*Gives the top N percent records from a database table*/
Example :
select top 50 percent * from Employee;
Output : 
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
Python – Itertools.dropwhile()

19 Feb, 2020
Itertools is a Python module that provide various functions that work on iterators to produce complex iterators. It makes the code faster, memory efficient and thus we see a better performance. This module is either used by themselves or in combination to form iterator algebra.
Note: For more information, refer to Python Itertools
The dropwhile() function of Python returns an iterator only after the func. in argument returns false for the first time.
Syntax:
dropwhile(func, seq):
Example 1:
# Python code to demonstrate the working of   # dropwhile()     # Function to be passed# as an argumentdef is_positive(n):    return n > 0   value_list =[5, 6, -8, -4, 2]result = list(itertools.dropwhile(is_positive, value_list))    print(result) 
Output:
[-8, -4, 2]
Example 2:
# Python code to demonstrate the working of   # dropwhile()         import itertools         # initializing list   li = [2, 4, 5, 7, 8]        # using dropwhile() to start displaying after condition is false  print ("The values after condition returns false : ", end ="")  print (list(itertools.dropwhile(lambda x : x % 2 == 0, li))) 
Output:
The values after condition returns false : [5, 7, 8]
Python-itertools
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Python PIL | ImageDraw.Draw.line()

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.line() Draws a line between the coordinates in the xy list.
Syntax: PIL.ImageDraw.Draw.line(xy, fill=None, width=0)
Parameters:xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like [x, y, x, y, ...].fill – Color to use for the line.width –The line width, in pixels. Note that line joins are not handled well, so wide polylines will not look good.
Returns: An Image object in ellipse shape.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create line imageimg1 = ImageDraw.Draw(img)  img1.line(shape, fill ="none", width = 0)img.show()
Another Example: Here we use different colour for filling.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create line imageimg1 = ImageDraw.Draw(img)  img1.line(shape, fill ="red", width = 0)img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Predefined Identifier __func__ in C

Identifier is the name given to an entity in programming to identify it in the program.
Generally, identifiers are created by the programmer for efficient working but there are some predefined identifiers that are inbuilt in programming. For example, cout, cin, etc.
Here, we will see one of these predefined identifiers of C programming language which is __func__.
The formal definition of __func__ is  −
“The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration
static const char __func__[] = “function-name”;
appeared, where function-name is the name of the lexically-enclosing function.”
C program The __func__ is a compiler-generated identifier that is created to identify the function using function name.
Let’s see a few code examples to make the concept more clear,
 Live Demo
#include <stdio.h>
void function1 (void){
   printf ("%s\n", __func__);
}
void function2 (void){
   printf ("%s\n", __func__);
   function1 ();
}
int main (){
   function2 ();
   return 0;
}
function2
function1
Explanation − Here, we have used the __func__ method to return the names of the functions that are called. The identifier returns the name of the function in which it is invoked. Both the print statements called for the __func__ for its own method reference.
This identified works on even the main method. Example,
 Live Demo
#include <stdio.h>
int main (){
   printf ("%s\n", __func__);
   return 0;
}
main
But this cannot be overwritten i.e. __func__ is reserved for function names only. Using it to store anything else will return error.
Let’s see
 Live Demo
#include <stdio.h>
int __func__ = 123;
int main (){
   printf ("%s\n", __func__);
   return 0;
}
error
There are other similar functions too in C programming language which do similar work of identification. Some are
__File__ − return the name of the current file.
__LINE__ − returns the number of current line.
Lets see a code to show the implementation
 Live Demo
#include <stdio.h>
void function1(){
   printf("The function: %s is in line: %d of the file :%s\n", __func__,__LINE__,__FILE__);
}
int main(){
   function1();
   return 0;
}
The function: function1 is in line: 3 of the file :main.c
Explanation − these are some general functions that might be useful as we have gathered information regard filename, line of code and function that is currently invoked using the __func__,__LINE__,__FILE__ identifiers.
Create empty border with BorderFactory class in Java?

To create empty border, use the createEmptyBorder() method. Let us first create a label component −
JLabel label = new JLabel("Label with empty border!");
Now, create empty border with BorderFactory class −
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
The following is an example to create empty border −
package my;
import javax.swing.BorderFactory;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      label = new JLabel("Label with empty border!");
      label.setFont(new Font("Verdana", Font.PLAIN, 16));
      label.setVerticalAlignment(JLabel.BOTTOM);
      label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
      frame.add(label);
      frame.setSize(550,350);
      frame.setVisible(true);
   }
}
How to get the memory address of an object in Python

23 Aug, 2021
In Python, everything is an object, from variables to lists and dictionaries everything is treated as objects. In this article, we are going to get the memory address of an object in Python. 
We can get an address using the id() function. id() function gives the address of the particular object.
Syntax:
id(object)
where the object is the data variables.
Example: Python program to get the address of different objects
Python3
# get id of lista = [1, 2, 3, 4, 5]print(id(a))  # get id of a variablea = 12print(id(a))  # get id of tuplea = (1, 2, 3, 4, 5)print(id(a))  # get id of a dictionarya = {'a': 1, 'b': 2}print(id(a))
Output:
140234866534752
94264748411744
140234904267376
140234866093264
ctypes is a foreign function library for Python. It provides C compatible data types and allows calling functions in DLLs or shared libraries.
Syntax:
addressof(c_int(object))
where object is the data variables
Example: Python program to get the memory address of  a variable
Python3
# import addressof and c_int modules # from ctypes modulefrom ctypes import c_int, addressof  # get memory address of variablea = 44print(addressof(c_int(a)))
Output:
140234866278064
It is also possible to get memory addresses in hexadecimal format. Here we will call the hex(address) function, to convert the memory address to hexadecimal representation.
Syntax:
hex(id(object))
where,
hex() is the memory hexadecimal representation to the address
id is used to get the memory of the object
object is the data
Example: Python program to get the memory address in hexadecimal representation.
Python3
# get id of list in hexadecimal representationa = [1, 2, 3, 4, 5]print(hex(id(a)))  # get id of a variable in hexadecimal # representationa = 12print(hex(id(a)))  # get id of tuple in hexadecimal # representationa = (1, 2, 3, 4, 5)print(hex(id(a)))  # get id of a dictionary in hexadecimal # representationa = {'a': 1, 'b': 2}print(hex(id(a)))
Output:
0x7fba9b0ae8c0
0x5572da858b60
0x7fba9f3c4a10
0x7fba9b05b8c0
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples

02 Dec, 2020
Every command in Linux starts a process at the time of its execution, which automatically gets terminated upon exiting the terminal. Suppose, you are executing programs over SSH and if the connection drops, the session will be terminated, all the executed processes will stop, and you may face a huge accidental crisis. In such cases, running commands in the background can be very helpful to the user and this is where nohup command comes into the picture. nohup (No Hang Up) is a command in Linux systems that runs the process even after logging out from the shell/terminal. 
Usually, every process in Linux systems is sent a SIGHUP (Signal Hang UP) which is responsible for terminating the process after closing/exiting the terminal. Nohup command prevents the process from receiving this signal upon closing or exiting the terminal/shell. Once a job is started or executed using the nohup command, stdin will not be available to the user and nohup.out file is used as the default file for stdout and stderr. If the output of the nohup command is redirected to some other file, nohup.out file is not generated. 
Syntax:
nohup command [command-argument ...]
1. Checking the version of Nohup:
The version of nohup command can be checked by using the following command.
$ nohup --version
Output:
2. To run a command in the foreground:
Runs the command in the foreground and redirects the command output to the nohup.out file if any redirecting filename is not mentioned.
$ nohup bash geekfile.sh
Output:
To redirect the output to the output.txt file:
$ nohup bash geekfile.sh > output.txt
Output:
3. To run a command in the background (with ‘&’): 
To run the command in the background, the ‘&’ symbol is appended at the end of the command. After executing, it doesn’t return to the shell command prompt after running the command in the background. It can be brought back to the foreground with the fg command.
$ nohup bash geekfile.sh &
fg
Output:
Note: The number within square brackets represents the job id and the number next to it is the process id.
4. To run multiple commands in the background:
nohup command can be used to run multiple commands in the background.
$ nohup bash -c 'commands'
Example:
$ nohup bash -c 'cal && ls'
Output:
Here, the output will be by default stored in nohup.out. To redirect it, type:
$ nohup bash -c 'commands' > filename.txt
Example:
$ nohup bash -c 'cal && ls' > output.txt
Output:
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Tail command in Linux with examples
Conditional Statements | Shell Script
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
Introduction to Linux Operating System
MySQL | MD5 Function

08 Nov, 2019
The MySQL MD5 function is used to return an MD5 128-bit checksum representation of a string. The MD5 message-digest algorithm is a widely used hash function producing a 128-bit hash value. The value returned by the MD5 function is a binary string of 32 hexadecimal digits, or NULL if the argument was NULL.
The return value can also be used as a hash key. The MD5 function accepts one parameter which is the string to be encrypted.
Syntax:
MD5( plain_string )
Parameters Used:
plain_string – It is used to specify the plain text string that is to be encrypted.
Return Value:The MD5 function in MySQL returns a binary string of 32 hexadecimal digits.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing MD5 function on a string.
SELECT 
MD5('xyz'); 
Output:
d16fb36f0911f878998c136191af705e 
Example-2: Implementing MD5 function on a string with a combination of characters and integer values.
SELECT 
MD5('xyz123'); 
Output:
j89hj65l0355k878998c136191kl906w 
Example-3: Implementing MD5 function on a bigger string.
SELECT 
MD5('geeksforgeeks'); 
Output:
a6eb56f80be8a120436d6f1c9b8d87ca 
Example-4: Implementing MD5 function on a NULL string.
SELECT 
MD5('NULL'); 
Output:
NULL 
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
java.time.LocalDate.toEpochDay() Method Example

The java.time.LocalDate.toEpochDay() method converts this date to the Epoch Day.
Following is the declaration for java.time.LocalDate.toEpochDay() method.
public long toEpochDay()

the Epoch Day equivalent to this date.
The following example shows the usage of java.time.LocalDate.toEpochDay() method.
package com.tutorialspoint;

import java.time.LocalDate;

public class LocalDateDemo {
   public static void main(String[] args) {
	  
      LocalDate date = LocalDate.now();
      System.out.println(date.toEpochDay());  
   }
}
Let us compile and run the above program, this will produce the following result −
17512

 Print
 Add Notes
 Bookmark this page
How can we define a Python function at runtime?

We can define a python function and execute it at runtime by importing the types module and using its function types.FunctionType() as follows
This code works at the python prompt as shown. First we import the types module. Then we run the command dynf=...; then we call the function dynf() to get the output as shown
>>> import types
>>> dynf = types.FunctionType(compile('print "Really Works"', 'dyn.py', 'exec'), {})
>>> dynf()
Really Works
Calling virtual functions inside constructors in C++

Virtual functions calling from a constructor or destructor is dangerous and should be avoided whenever possible as the virtual function we call is called from the Base class and not from the derived class.
The reason is that in C++ Super-classes are constructed before derived classes. So, in the following example, as B must be instantiated, before D is instantiated. When B's constructor is called, it's not D yet, so the virtual function table still has the entry for B's copy of s().
 Live Demo
#include<iostream>
using namespace std;
class B {
   public: B() {
      s();
   }
   virtual void s() {
      cout << "Base" << endl;
   }
};

class D: public B {
   public: D() : B() {}
   virtual void s() {
      cout << "Derived" <<endl;
   }
};

int main() {
   D de;
}
Base
What is a Multidimensional array in Java?

In Java, a multi-dimensional array is nothing but an array of arrays.
2D array − A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns −
Int[][] myArray = {{10, 20, 30}, {11, 21, 31}, {12, 22, 32} }
In short, a two-dimensional array contains one-dimensional arrays of elements. It is represented by two indices where the first index denotes the position of the array and the second index represents the position of the element within that particular array −
Java Examples - Append String to a File

How to append a string in an existing file ?
This example shows how to append a string in an existing file using filewriter method.
import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
      try {
         BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
         out.write("aString1\n");
         out.close();
         out = new BufferedWriter(new FileWriter("filename",true));
         out.write("aString2");
         out.close();
         BufferedReader in = new BufferedReader(new FileReader("filename"));
         String str;
         
         while ((str = in.readLine()) != null) {
            System.out.println(str);
         }
      }
      in.close();
      catch (IOException e) {
         System.out.println("exception occoured"+ e);
      }
   }
}
The above code sample will produce the following result.
aString1
aString2

The following is an example of append a string in an existing file in java
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileExample {
   public static void main( String[] args ) { 
      try { 
         String data = " Tutorials Point is a best website in the world";
         File f1 = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         if(!f1.exists()) {
            f1.createNewFile();
         } 
         FileWriter fileWritter = new FileWriter(f1.getName(),true);
         BufferedWriter bw = new BufferedWriter(fileWritter);
         bw.write(data);
         bw.close();
         System.out.println("Done");
      } catch(IOException e){
         e.printStackTrace();
      }
   }
}
The above code sample will produce the following result.
Done

 Print
 Add Notes
 Bookmark this page
How to remove rows in an R data frame using row names?

There are a lot of ways to subset an R data frame and sometimes we need to do it by removing rows. In general, the rows are removed by using the row index number but we can do the same by using row names as well. This can be done by storing the row names that should be removed in a vector and then removing through subsetting with single square brackets as shown in the below examples.
Consider the below data frame:
> x<-rnorm(20,1,0.04)
> y<-rnorm(20,100,4)
> row.names(df)<-LETTERS[1:20]
> df
      x        y
A 0.9454799 96.62077
B 0.9642909 101.54903
C 1.0294169 97.17593
D 0.9877072 98.98962
E 1.0182932 92.32761
F 1.0351041 103.04182
G 0.9613700 90.65195
H 1.0240703 99.63975
I 0.9424871 97.11730
J 0.9876748 108.07684
K 1.0652311 102.14823
L 1.0196251 93.51378
M 0.9752639 100.57394
N 0.9890722 101.37151
O 0.9873279 100.37910
P 0.9564027 96.94806
Q 0.9456446 103.40934
R 0.9617322 94.89198
S 0.9956141 86.43256
T 1.0253881 101.52844
Making vector of row names that needs to be removed:
> row_names_df_to_remove<-c("A","B","C","D","E")
Removing the specified row names:
> df[!(row.names(df) %in% row_names_df_to_remove),]
       x         y
F 1.0351041 103.04182
G 0.9613700 90.65195
H 1.0240703 99.63975
I 0.9424871 97.11730
J 0.9876748 108.07684
K 1.0652311 102.14823
L 1.0196251 93.51378
M 0.9752639 100.57394
N 0.9890722 101.37151
O 0.9873279 100.37910
P 0.9564027 96.94806
Q 0.9456446 103.40934
R 0.9617322 94.89198
S 0.9956141 86.43256
T 1.0253881 101.52844
Let’s have a look at another example:
Live Demo
> set.seed(3247)
> x1<-rpois(20,1)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1
x1 x2
1 3 5
2 1 8
3 3 3
4 0 6
5 2 2
6 1 6
7 0 1
8 2 2
9 1 3
10 0 4
11 3 1
12 0 4
13 0 5
14 1 4
15 1 3
16 1 7
17 2 3
18 0 0
19 1 3
20 0 5
> row.names.df1<-c(1:5)
> df1[!(row.names(df1) %in% row.names.df1),]
x1 x2
6 1 6
7 0 1
8 2 2
9 1 3
10 0 4
11 3 1
12 0 4
13 0 5
14 1 4
15 1 3
16 1 7
17 2 3
18 0 0
19 1 3
20 0 5
C Program for Find the largest prime factor of a number?

Prime Factor− In number theory, the prime factors of a positive integer are the prime numbers that divide that integer exactly. The process of finding these numbers is called integer factorization, or prime factorization.
Example− Prime factors of 288 are: 288 = 2 x 2 x 2 x 2 x 2 x 3 x 3
Input: n = 124
Output: 31 is the largest prime factor!
You will find all the prime factors of a number and find the largest of them. The prime factors 124 = 2 x 2 x 31. and 31 is the largest of them.
#include <stdio.h>
int main() {
   long int n;
   n=3453;
   long int div=2, ans = 0, maxFact;
   while(n!=0) {
      if(n % div !=0)
         div = div + 1;
      else {
         maxFact = n;
         n = n / div;
         if(n == 1) {
            printf("%d is the largest prime factor !",maxFact);
            ans = 1;
            break;
         }
      }
   }
   return 0;
}
1151 is the largest prime factor !
Difference between readonly and const keyword in C#

readonly keyword is used to define a variable which can be assigned once after declaration either during declaration or in constructor. const keyword is used to define a constant to be used in the program. Following is the valid usage of a readonly and const keywords in C#.
 Live Demo
using System.IO;
using System;

public class Program {
   public const int VALUE = 10;
   public readonly int value1;

   Program(int value){
      value1 = value;
   }
   public static void Main() {
      Console.WriteLine(VALUE);
      Program p1 = new Program(11);
      Console.WriteLine(p1.value1);
   }
}
10
11
Following are some of the important differences between readonly and const keywords.
What is the difference between cin and cout streams in c++?

cin is an object of the input stream and is used to take input from input streams like files, console, etc. cout is an object of the output stream that is used to show output. Basically, cin is an input statement while cout is an output statement.
They also use different operators. cin uses the insertion operator( >> ) while cout uses the extraction operator( << ).
For example, if you want to read an int value in a variable my_int(using cin) and then print it to the screen(using cout), you'd write −
#include<iostream>
int main() {
   int my_int;
   std::cin >> my_int;
   std::cout << my_int;
   return 0;
}
Then save this program to hello.cpp file. Finally, navigate to the saved location of this file in the terminal/cmd and compile it using −
$ g++ hello.cpp
Run it using −
$ ./a.out
If you give it the input: 15, this will give the output −
15
PHP | strval() Function

31 Jul, 2021
The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted.
Syntax:
strval( $variable ) 
Parameter: This function accepts a single parameter $variable. This parameter represents the value which we want to convert to string
Return value: This function returns a string. This string is generated by typecasting the value of the variable passed to it as a parameter.
Below programs illustrate the strval() function.
Program 1:
<?php  $var_name = 32.360;  // prints the value of above variable // as a stringecho strval($var_name);  ?>
Output:
32.36

Program 2:
<?php  class geeksforgeeks{    public function __toString()    {           // returns the class name         return __CLASS__;    }}  // prints the name of above class as// a stringecho strval(new geeksforgeeks);  ?>
Output:
geeksforgeeks

Program 3:
<?php// Program to illustrate the strval() function// when an array is passed as parameter  // Input array$arr = array(1,2,3,4,5);  // This will print only the type of value// being converted i.e. 'Array'echo strval($arr);  ?>
Reference:http://php.net/manual/en/function.strval.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
nidhi_biet
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to Upload Image into Database and Display it using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Python | Split CamelCase string to individual strings

25 Jun, 2022
Given a string in a camel-case, write a Python program to split each word in the camel case string into individual strings.
Examples:
Input : "GeeksForGeeks"
Output : ['Geeks', 'For', 'Geeks']

Input : "ThisIsInCamelCase"
Output : ['This', 'Is', 'In', 'Camel', 'Case']
Method #1: Naive Approach A naive or brute-force approach to split CamelCase string into individual strings is to use for loop. First, use an empty list ‘words’ and append the first letter of ‘str’ to it. Now using a for loop, check if the current letter is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string. 
Python3
# Python3 program Split camel case# string to individual strings def camel_case_split(str):    words = [[str[0]]]     for c in str[1:]:        if words[-1][-1].islower() and c.isupper():            words.append(list(c))        else:            words[-1].append(c)     return [''.join(word) for word in words]     # Driver codestr = "GeeksForGeeks"print(camel_case_split(str))
['Geeks', 'For', 'Geeks']
Method #2: Using enumerate and zip() In this method, we first use Python enumerate to find indices, where the new string begins and save them in ‘start_idx’. Finally using ‘start_idx’ we return each individual string using Python zip. 
Python3
# Python3 program Split camel case# string to individual strings import re def camel_case_split(str):         start_idx = [i for i, e in enumerate(str)                 if e.isupper()] + [len(str)]     start_idx = [0] + start_idx    return [str[x: y] for x, y in zip(start_idx, start_idx[1:])]          # Driver codestr = "GeeksForGeeks"print(camel_case_split(str))
['', 'Geeks', 'For', 'Geeks']
Method #3: Using Python regex 
Python3
# Python3 program Split camel case# string to individual stringsimport re def camel_case_split(str):     return re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', str)     # Driver codestr = "GeeksForGeeks"print(camel_case_split(str))
['Geeks', 'For', 'Geeks']
Method #4 : Using isupper(),split(),remove() methods.
Python3
# Python3 program Split camel case# string to individual strings   s="ThisIsInCamelCase"new_string=""for i in s:    if(i.isupper()):        new_string+="*"+i    else:        new_string+=ix=new_string.split("*")x.remove('')print(x)
['This', 'Is', 'In', 'Camel', 'Case']
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arithmetic Micro-operations in Registers

19 Jul, 2021
We can perform arithmetic operations on the numeric data which is stored inside the registers. 
Example : 
R3 <- R1 + R2
The value in register R1 is added to the value in the register R2 and then the sum is transferred into register R3. Similarly, other arithmetic micro-operations are performed on the registers. 
Addition – In addition micro-operation, the value in register R1 is added to the value in the register R2 and then the sum is transferred into register R3. 
Subtraction – In subtraction micro-operation, the contents of register R2 are subtracted from contents of the register R1, and then the result is transferred into R3. 
There is another way of doing the subtraction. In this, 2’s complement of R2 is added to R1, which is equivalent to R1 – R2, and then the result is transferred into register R3. 
Increment – In Increment micro-operation, the value inside the R1 register is increased by 1. 
Decrement – In Decrement micro-operation, the value inside the R1 register is decreased by 1.  
1’s Complement – In this micro-operation, the complement of the value inside the register R1 is taken. 
2’s Complement – In this micro-operation, the complement of the value inside the register R2 is taken and then 1 is added to the value and then the final result is transferred into the register R2. This process is also called Negation. It is equivalent to -R2.  
 
 
sooda367
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
VBScript InStr Function

The InStr Function returns the first occurrence of one string within another string. The search happens from left to right.
InStr([start,]string1,string2[,compare])

Start, an Optional Parameter. Specifies the starting position for the search. The search begins at the first position from left to right.
Start, an Optional Parameter. Specifies the starting position for the search. The search begins at the first position from left to right.
String1, a Required Parameter. String to be searched.
String1, a Required Parameter. String to be searched.
String2, a Required Parameter. String against which String1 is searched.
String2, a Required Parameter. String against which String1 is searched.
Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below mentioned values −

0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison


Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below mentioned values −
0 = vbBinaryCompare - Performs Binary Comparison(Default)
0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison
1 = vbTextCompare - Performs Text Comparison
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "Microsoft VBScript"
         document.write("Line 1 : " & InStr(1,var,"s") & "<br />")
         document.write("Line 2 : " & InStr(7,var,"s") & "<br />")
         document.write("Line 3 : " & InStr(1,var,"f",1) & "<br />")
         document.write("Line 4 : " & InStr(1,var,"t",0) & "<br />")
         document.write("Line 5 : " & InStr(1,var,"i") & "<br />")
         document.write("Line 6 : " & InStr(7,var,"i") & "<br />")
         document.write("Line 7 : " & InStr(var,"VB"))
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : 6
Line 2 : 0
Line 3 : 8
Line 4 : 9
Line 5 : 2
Line 6 : 16
Line 7 : 11
PREVIOUSYEAR function

Returns a table that contains a column of all dates from the previous year, given the last date in the dates column, in the current context.
PREVIOUSYEAR (<dates>, [<year_end_date>]) 

dates
A column that contains dates.
year_end_date
Optional.
A literal string with a date that defines the year-end date.
If omitted, the default is December 31.
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
The year_end_date parameter is a string literal of a date, in the locale where the workbook was created. The year portion of the date is ignored.
Previous Year Sales:= CALCULATE ( 
   SUM (Sales [Sales Amount]),PREVIOUSYEAR (Sales [Date])
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Python - Convert String List to Key-Value List dictionary - GeeksforGeeks

02 Sep, 2020
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list.
Input : test_list = [“gfg is best for geeks”, “CS is best subject”]Output : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘geeks’], ‘CS’: [‘is’, ‘best’, ‘subject’]}Explanation : 1st elements are paired with respective rest of words as list.
Input : test_list = [“gfg is best for geeks”]Output : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘geeks’]}Explanation : 1st elements are paired with respective rest of words as list.
Method #1 : Using split() + loop
In this, we iterate for each string, and then perform split of string using split(), assign 1st element as key and pack other elements into list, using * operator and create key-value list pair.
Python3
# Python3 code to demonstrate working of # Convert String List to Key-Value List dictionary# Using split() + loop  # initializing listtest_list = ["gfg is best for geeks", "I love gfg", "CS is best subject"]  # printing stringprint("The original list : " + str(test_list))    res = dict()for sub in test_list:          # split() for key     # packing value list    key, *val = sub.split()    res[key] = val  # printing results print("The key values List dictionary : " + str(res))
The original list : ['gfg is best for geeks', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'geeks'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

Method #2 : Using split() + dictionary comprehension
This is similar way to solve this problem. In this, dictionary comprehension is used to solve this problem.
Python3
# Python3 code to demonstrate working of # Convert String List to Key-Value List dictionary# Using split() + dictionary comprehension  # initializing listtest_list = ["gfg is best for geeks", "I love gfg", "CS is best subject"]  # printing stringprint("The original list : " + str(test_list))  # using dictionary comprehension to solve this problemres = {sub[0] : sub[1:] for sub in (ele.split() for ele in test_list)}  # printing results print("The key values List dictionary : " + str(res))
The original list : ['gfg is best for geeks', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'geeks'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Unix / Linux Shell - The until Loop

The while loop is perfect for a situation where you need to execute a set of commands while some condition is true. Sometimes you need to execute a set of commands until a condition is true.
until command
do
   Statement(s) to be executed until command is true
done

Here the Shell command is evaluated. If the resulting value is false, given statement(s) are executed. If the command is true then no statement will be executed and the program jumps to the next line after the done statement.
Here is a simple example that uses the until loop to display the numbers zero to nine −
#!/bin/sh

a=0

until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9


    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
Tryit Editor v3.7

HTML Input types
Tryit: dates with no time zone
Find the position of an element in a Java TreeMap - GeeksforGeeks

27 Dec, 2019
Given an element N and a TreeMap, the task is to find the position of this element in the given TreeMap in Java.
Examples:
Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 20Output: 2
Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 5Output: -1
Approach:
There is no direct method to find out the position of the key in a TreeMap.
However, we can use TreeMap headMap() method.
The method returns the portion of the treemap whose keys are strictly less than that of the key_point.
Hence, if the key exists in the TreeMap, then the size() of its headMap is equal to the position of the key in the TreeMap.
Below is the implementation of the above approach:
// Java code to find the position// of an element in a Java TreeMap  import java.util.*;  public class Tree_Map_Demo {      // Function to return the position of    // the specified element in the given TreeMap    public static <K, V> int findPosition(K N, TreeMap<K, V> tree_map)    {        int pos = -1;          // Check if the given key        // is present or not        if (tree_map.containsKey(N)) {              // If present, find the position            // using the size of headMap()              pos = tree_map.headMap(N).size();        }          return pos;    }      // Function to print the result    public static <K, V> void printResult(K N, TreeMap<K, V> tree_map)    {          // Get the position        int pos = findPosition(N, tree_map);          // Print the result        if (pos >= 0) {              System.out.println(N + " found at "                               + "position = " + pos);        }        else {              System.out.println(N + " not found. "                               + "Hence position = "                               + pos);        }    }      // Driver code    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<Integer, String> tree_map            = new TreeMap<Integer, String>();          // Mapping string values to int keys        tree_map.put(10, "Geeks");        tree_map.put(15, "4");        tree_map.put(20, "Geeks");        tree_map.put(25, "Welcomes");        tree_map.put(30, "You");          // Displaying the TreeMap        System.out.println("TreeMap: " + tree_map);          // Element of which position is to be found        int N1 = 20, N2 = 5;          // Get the position        printResult(N1, tree_map);        printResult(N2, tree_map);    }}
TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
20 found at position = 2
5 not found. Hence position = -1

java-TreeMap
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java
C library function - ctime()

The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer.
The returned string has the following format: Www Mmm dd hh:mm:ss yyyy,  where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year.
Following is the declaration for ctime() function.
char *ctime(const time_t *timer)
timer − This is the pointer to a time_t object that contains a calendar time.
timer − This is the pointer to a time_t object that contains a calendar time.
This function returns a C string containing the date and time information in a human-readable format.
The following example shows the usage of ctime() function.
#include <stdio.h>
#include <time.h>

int main () {
   time_t curtime;

   time(&curtime);

   printf("Current time = %s", ctime(&curtime));

   return(0);
}
Let us compile and run the above program that will produce the following result −
Current time = Mon Aug 13 08:23:14 2012


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Python | Get all tuple keys from dictionary

18 Oct, 2019
Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get all the tuple key elements, we need to perform certain functionalities to achieve this. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionIn this method, we just iterate through the each dictionary item and get it’s key’s elements into a list.
# Python3 code to demonstrate working of# Get all tuple keys from dictionary# Using list comprehension  # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}  # printing original dictprint("The original dict is : " + str(test_dict))  # Get all tuple keys from dictionary# Using list comprehensionres = [ele for key in test_dict for ele in key]  # printing resultprint("The dictionary tuple key elements are : " + str(res))
The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The dictionary tuple key elements are : [5, 6, 9, 10, 1, 2, 8]

 
Method #2 : Using chain.from_iterable()This task can be performed in more compact form, using one word instead of one-line by using from_iterable(), which internally accesses the tuple elements and stores in list.
# Python3 code to demonstrate working of# Get all tuple keys from dictionary# Using chain.from_iterable()from itertools import chain  # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}  # printing original dictprint("The original dict is : " + str(test_dict))  # Get all tuple keys from dictionary# Using chain.from_iterable()res = list(chain.from_iterable(test_dict))  # printing resultprint("The dictionary tuple key elements are : " + str(res))
The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The dictionary tuple key elements are : [5, 6, 9, 10, 1, 2, 8]

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Java Guava | Chars.concat() method with Examples

31 Jan, 2019
The concat() method of Chars Class in the Guava library is used to concatenate the values of many arrays into a single array. These char arrays to be concatenated are specified as parameters to this method.
For example: concat(new char[] {a, b}, new char[] {}, new char[] {c}returns the array {a, b, c}.
Syntax:
public static char[] concat(char[]... arrays)

Parameter: This method accepts arrays as parameter which is the char arrays to be concatenated by this method.
Return Value: This method returns a single char array which contains all the specified char array values in its original order.
Below programs illustrate the use of concat() method:
Example 1:
// Java code to show implementation of// Guava's Chars.concat() method  import com.google.common.primitives.Chars;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating 2 Character arrays        char[] arr1 = { 'H', 'E', 'L', 'L', 'O' };        char[] arr2 = { 'G', 'E', 'E', 'K', 'S' };          // Using Chars.concat() method to combine        // elements from both arrays into a single array        char[] res = Chars.concat(arr1, arr2);          // Displaying the single combined array        System.out.println(Arrays.toString(res));    }}
[H, E, L, L, O, G, E, E, K, S]

Example 2:
// Java code to show implementation of// Guava's Chars.concat() method  import com.google.common.primitives.Chars;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating 4 Character arrays        char[] arr1 = { '1', '2', '3' };        char[] arr2 = { '4', '5' };        char[] arr3 = { '6', '7', '8' };        char[] arr4 = { '9', '0' };          // Using Chars.concat() method to combine        // elements from both arrays into a single array        char[] res = Chars.concat(arr1, arr2, arr3, arr4);          // Displaying the single combined array        System.out.println(Arrays.toString(res));    }}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Reference: https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#concat(char[]...)
Guava-Chars
Guava-Functions
Java-Functions
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.