code-rag-bench/online-tutorials huggingface dataset:
JavaScript Date setHours() Method

Javascript date setHours() method sets the hours for a specified date according to local time.
Its syntax is as follows −
Date.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])

Note − Parameters in the bracket are always optional.
hoursValue − An integer between 0 and 23, representing the hour.
hoursValue − An integer between 0 and 23, representing the hour.
minutesValue − An integer between 0 and 59, representing the minutes.
minutesValue − An integer between 0 and 59, representing the minutes.
secondsValue − An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue.
secondsValue − An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue.
msValue − A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.
msValue − A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the values returned from the getUTCMinutes, getUTCSeconds, and getMilliseconds methods are used.
Try the following example.
<html>
   <head>
      <title>JavaScript setHours Method</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         var dt = new Date( "Aug 28, 2008 23:30:00" );
         dt.setHours( 02 );
         document.write( dt ); 
      </script>
   </body>
</html>
Thu Aug 28 2008 02:30:00 GMT+0530 (India Standard Time) 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
What are Backslash character constants in C language?

A backslash ( \ ) that allows a visual representation of some nongraphic characters introduces an escape.
One of the common escape constants is the newline character ( \n ).
The backslash characters are as follows −
Following is the C program for the backslash character constants −
 Live Demo
#include<stdio.h>
#define PI 3.14
float area;
void main(){
   double r;
   r=1.0;
   area = PI * r * r;
   printf("Area is %d \n", area); // /n is used to enter the next statement in newline
}
Area is 1492442840
How do we access elements from the two-dimensional array in C#?

A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns.
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array.
int x = a[1,1];
Console.WriteLine(x);
Let us see an example that shows how to access elements from two-dimensional array.
 Live Demo
using System;
namespace Demo {
   class MyArray {
      static void Main(string[] args) {
         /* an array with 5 rows and 2 columns*/
         int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
         int i, j;
         /* output each array element's value */
         for (i = 0; i < 5; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         int x = a[1,1];
         Console.WriteLine(x);
         Console.ReadKey();
      }
   }
}
a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
a[3,0] = 3
a[3,1] = 6
a[4,0] = 4
a[4,1] = 8
2
Unix / Linux - Shell String Operators Example

The following string operators are supported by Bourne Shell.
Assume variable a holds "abc" and variable b holds "efg" then −
Here is an example which uses all the string operators −
#!/bin/sh

a="abc"
b="efg"

if [ $a = $b ]
then
   echo "$a = $b : a is equal to b"
else
   echo "$a = $b: a is not equal to b"
fi

if [ $a != $b ]
then
   echo "$a != $b : a is not equal to b"
else
   echo "$a != $b: a is equal to b"
fi

if [ -z $a ]
then
   echo "-z $a : string length is zero"
else
   echo "-z $a : string length is not zero"
fi

if [ -n $a ]
then
   echo "-n $a : string length is not zero"
else
   echo "-n $a : string length is zero"
fi

if [ $a ]
then
   echo "$a : string is not empty"
else
   echo "$a : string is empty"
fi
The above script will generate the following result −
abc = efg: a is not equal to b
abc != efg : a is not equal to b
-z abc : string length is not zero
-n abc : string length is not zero
abc : string is not empty

The following points need to be considered while using the operator −
There must be spaces between the operators and the expressions. For example, 2+2 is not correct. It should be written as 2 + 2.
There must be spaces between the operators and the expressions. For example, 2+2 is not correct. It should be written as 2 + 2.
if...then...else...fi statement is a decision-making statement which has been explained in the next chapter.
if...then...else...fi statement is a decision-making statement which has been explained in the next chapter.

    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
awk - Unix, Linux Command

awk - Finds and Replaces text, database sort/validate/index
awk command searches files for text containing a pattern. When a line or text matches, awk performs a specific action on that line/text. The Program statement tells awk what operation to do; Program statement consists of a series of "rules" where each rule specifies one pattern to search for, and one action to perform when a particular pattern is found. A regular expression enclosed in slashes (/) is an awk pattern to match every input record whose text belongs to that set.
To return the second item($2) from each line of the output from an ls - l listing.
$ ls -l | awk '{print $2}'
13
3
17
7


To return the second item($2) from each line of the output from an ls - l listing.
$ ls -l | awk '{print $2}'
13
3
17
7

To print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each line in sample.txt.
First create a sample.txt file
Sample Line 1
Sample Line 2
Sample Line 3

$ awk '{print NR "- " $1 }' sample.txt
1 - Sample
2 - Sample
3 - Sample


To print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each line in sample.txt.
First create a sample.txt file
Sample Line 1
Sample Line 2
Sample Line 3

$ awk '{print NR "- " $1 }' sample.txt
1 - Sample
2 - Sample
3 - Sample

To print the first item ($1) and then the second last item $(NF-1) from each line in sample.txt.
$ awk '{print $1, $(NF-1) }' sample.txt
Sample Line
Sample Line
Sample Line


To print the first item ($1) and then the second last item $(NF-1) from each line in sample.txt.
$ awk '{print $1, $(NF-1) }' sample.txt
Sample Line
Sample Line
Sample Line

To print non-empty line from a file.
$ awk 'NF > 0' sample.txt


To print non-empty line from a file.
$ awk 'NF > 0' sample.txt

To print the length of the longest input line.
$ awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt
13


To print the length of the longest input line.
$ awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt
13

To print seven random numbers from zero to 100, inclusive.
$  awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24
29
85
15
59
19
81


To print seven random numbers from zero to 100, inclusive.
$  awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24
29
85
15
59
19
81

To count the lines in a file
$ awk 'END { print NR }' sample.txt
3


To count the lines in a file
$ awk 'END { print NR }' sample.txt
3


    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
PHP Object Inheritance

Inheritance is an important principle of object oriented programming methodology. Using this principle, relation between two classes can be defined. PHP supports inheritance in its object model.
PHP uses extends keyword to establish relationship between two classes.
class B extends A
where A is the base class (also called parent called) and B is called a subclass or child class. Child class inherits public and protected methods of parent class. Child class may redefine or override any of inherited methods. If not, inherited methods will retain their functionality as defined in parent class, when used with object of child class.
Definition of parent class must precede child class definition. In this case, definition of A class should appear before definition of class B in the script.
<?php
class A{
   //properties, constants and methods of class A
}
class B extends A{
   //public and protected methods inherited
}
?>
If autoloading is enabled, definition of parent class is obtained by loading the class script.
Following code shows that child class inherits public and protected members of parent class
 Live Demo
<?php
class parentclass{
   public function publicmethod(){
      echo "This is public method of parent class\n" ;
   }
   protected function protectedmethod(){
      echo "This is protected method of parent class\n" ;
   }
   private function privatemethod(){
      echo "This is private method of parent class\n" ;
   }
}
class childclass extends parentclass{
   public function childmethod(){
      $this->protectedmethod();
      //$this->privatemethod(); //this will produce error
   }
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?>
This will produce following result. −
This is public method of parent class
This is protected method of parent class
PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context 'childclass'
If a method inherited from parent class is redefined in child class, new definition overrides earlier functionality. In following example, publicmethod is defined again in child class
 Live Demo
<?php
class parentclass{
public function publicmethod(){
   echo "This is public method of parent class\n" ;
}
protected function protectedmethod(){
   echo "This is protected method of parent class\n" ;
}
private function privatemethod(){
   echo "This is private method of parent class\n" ;
}
}
class childclass extends parentclass{
   public function publicmethod(){
      echo "public method of parent class is overridden in child class\n" ;
   }
}
$obj=new childclass();
$obj->publicmethod();
?>
This will produce following result. −
public method of parent class is overridden in child class
PHP doesn't support multiple inheritance. Hence a class can not extend two or more classes. However, it supports heirarchical inheritance as follows:
 Live Demo
<?php
class A{
   function test(){
      echo "method in A class";
   }
}
class B extends A{
   //
}
class C extends B{
   //
}
$obj=new C();
$obj->test();
?>
This will show following result
method in A class
Python | Extract specific keys from dictionary - GeeksforGeeks

25 Mar, 2022
We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container. Let’s discuss certain ways in which this can be performed. Method #1 : Using dictionary comprehension + items() This problem can be performed by reconstruction using the keys extracted through items function that wish to be filtered and dictionary function makes the desired dictionary. 
Python3
# Python3 code to demonstrate# Extracting specific keys from dictionary# Using dictionary comprehension + items() # initializing dictionarytest_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4} # printing original listprint("The original dictionary : " + str(test_dict)) # Using dictionary comprehension + items()# Extracting specific keys from dictionaryres = {key: test_dict[key] for key in test_dict.keys()                               & {'akshat', 'nikhil'}} # print resultprint("The filtered dictionary is : " + str(res))
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
  Method #2 : Using dict() The dict function can be used to perform this task by converting the logic performed using list comprehension into a dictionary. 
Python3
C++
# Python3 code to demonstrate# Extracting specific keys from dictionary# Using dict() # initializing dictionarytest_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4} # printing original listprint("The original dictionary : " + str(test_dict)) # Using dict()# Extracting specific keys from dictionaryres = dict((k, test_dict[k]) for k in ['nikhil', 'akshat']                                        if k in test_dict) # print resultprint("The filtered dictionary is : " + str(res))
#include <iostream>using namespace std; int main() {     cout<<"GFG!";    return 0;}
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
rkbhola5
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to print without newline in Python?
W3.CSS Templates

We have created some responsive W3.CSS website templates for you to use.
You are free to modify, save, share, and use them in all your projects.
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.
How can we implement a JSON array using Streaming API in Java?

The JsonGenerator interface can be used to write the JSON data to an output source in a streaming way. We can create or implement a JSON array using the writeStartArray() method of JsonGenerator, this method writes the JSON name/start array character pair within the current object context. The writeStartObject() method writes the JSON start object character, and valid only in an array context and the writeEnd() method writes the end of the current context.
JsonGenerator writeStartArray(String name)
import java.io.*;
import javax.json.*;
import javax.json.stream.*;
public class JsonGeneratorTest {
   public static void main(String[] args) throws Exception {
      StringWriter writer = new StringWriter();
      JsonGenerator jsonGen = Json.createGenerator(writer);
      jsonGen.writeStartObject()
             .write("name", "Adithya")
             .write("designation", "Python Developer")
             .write("company", "TutorialsPoint")
             .writeStartArray("personal details")
             .writeStartObject()
             .write("email", "adithya@gmail.com")
             .writeEnd()
             .writeStartObject()
             .write("contact", "9959927000")
             .writeEnd()  // end of object
             .writeEnd()  // end of an array
             .writeEnd(); // end of main object
      jsonGen.close();
      System.out.println(writer.toString());
   }
}
{"name":"Adithya","designation":"Python Developer","company":"TutorialsPoint","personal details":[{"email":"adithya@gmail.com"},{"contact":"9959927000"}]}
MariaDB - Temporary Tables

Some operations can benefit from temporary tables due to speed or disposable data. The life of a temporary table ends at the termination of a session whether you employ them from the command prompt, with a PHP script, or through a client program. It also does not appear in the system in a typical fashion. The SHOW TABLES command will not reveal a list containing temporary tables.
The TEMPORARY keyword within a CREATE TABLE statement spawns a temporary table. Review an example given below −
mysql>CREATE TEMPORARY TABLE order (
   item_name VARCHAR(50) NOT NULL
   , price DECIMAL(7,2) NOT NULL DEFAULT 0.00
   , quantity INT UNSIGNED NOT NULL DEFAULT 0
);

In creating a temporary table, you can clone existing tables, meaning all their general characteristics, with the LIKE clause. The CREATE TABLE statement used to spawn the temporary table will not commit transactions as a result of the TEMPORARY keyword.
Though temporary tables stand apart from non-temporary and drop at the end of a session, they may have certain conflicts −
They sometimes conflict with ghost temporary tables from expired sessions.
They sometimes conflict with ghost temporary tables from expired sessions.
They sometimes conflict with shadow names of non-temporary tables.
They sometimes conflict with shadow names of non-temporary tables.
Note − Temporary tables are permitted to have the same name as an existing non-temporary table because MariaDB views it as a difference reference.
MariaDB requires granting privileges to users for creating temporary tables. Utilize a GRANT statement to give this privilege to non-admin users.
GRANT CREATE TEMPORARY TABLES ON orders TO 'machine122'@'localhost';

Though temporary tables are essentially removed at the end of sessions, you have the option to delete them. Dropping a temporary table requires the use of the TEMPORARY keyword, and best practices suggest dropping temporary tables before any non-temporary.
mysql> DROP TABLE order;

 Print
 Add Notes
 Bookmark this page
How to sum time in MySQL by converting into seconds?

To convert time to seconds, use the TIME_TO_SEC() method. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> ArrivalTime time
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('04:10:00');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('05:20:50');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('06:40:10');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-------------+
| ArrivalTime |
+-------------+
| 04:10:00    |
| 05:20:50    |
| 06:40:10    |
+-------------+
3 rows in set (0.00 sec)
Following is the query to calculate the sum of time in MySQL −
mysql> select SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) from DemoTable;
+-------------------------------------------------+
| SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) |
+-------------------------------------------------+
| 16:11:00                                        |
+-------------------------------------------------+
1 row in set (0.00 sec)
Python - Append items at beginning of dictionary - GeeksforGeeks

01 Aug, 2020
Given a dictionary, append another dictionary at beginning of it.
Input : test_dict = {“Gfg” : 5, “is” : 3, “best” : 10}, updict = {“pre1” : 4}Output : {‘pre1’: 4, ‘Gfg’: 5, ‘is’: 3, ‘best’: 10}Explanation : New dictionary updated at front of dictionary.
Input : test_dict = {“Gfg” : 5}, updict = {“pre1” : 4}Output : {‘pre1’: 4, ‘Gfg’: 5}Explanation : New dictionary updated at front of dictionary, “pre1” : 4.
Method #1 : Using update()
This is one of the ways in which this task can be performed. In this, we use update function to update old dictionary after the new one so that new dictionary is appended at beginning.
Python3
# Python3 code to demonstrate working of # Append items at beginning of dictionary # Using update()  # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 3, "best" : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing update dictionaryupdict = {"pre1" : 4, "pre2" : 8}  # update() on new dictionary to get desired orderupdict.update(test_dict)  # printing result print("The required dictionary : " + str(updict)) 
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}

Method #2 : Using ** operator
This is yet another way in which this task can be performed. In this, we perform packing and unpacking of items into custom made dictionary using ** operator.
Python3
# Python3 code to demonstrate working of # Append items at beginning of dictionary # Using ** operator  # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 3, "best" : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing update dictionaryupdict = {"pre1" : 4, "pre2" : 8}  # ** operator for packing and unpacking items in orderres = {**updict, **test_dict}  # printing result print("The required dictionary : " + str(res)) 
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}

Python dictionary-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python - Clearing a tuple - GeeksforGeeks

11 Jun, 2021
Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Let’s discuss certain ways in which this task can be performed.Method #1 : Using list() + clear() + tuple() The combination of above 3 functions can be used to perform this task. In this, we interconvert the tuple to list, clear it and again convert to tuple using tuple(). 
Python3
# Python3 code to demonstrate# Clearing a tuple# using list() + tuple() + clear() # initializing tupletest_tup = (1, 5, 3, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tup)) # Clearing a tuple# using list() + tuple() + clear()temp = list(test_tup)temp.clear()test_tup = tuple(temp) # print resultprint("The tuple after clearing values : " + str(test_tup))
The original tuple : (1, 5, 3, 6, 8)
The tuple after clearing values : ()
 
 Method #2 : Reinitialization using tuple() Another straight forward way to perform this task is to reinitialize tuple using tuple() which will return empty tuple. 
Python3
# Python3 code to demonstrate# Clearing a tuple# using Reinitialization + tuple() # initializing tupletest_tup = (1, 5, 3, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tup)) # Clearing a tuple# using Reinitialization + tuple()test_tup = tuple() # print resultprint("The tuple after clearing values : " + str(test_tup))
The original tuple : (1, 5, 3, 6, 8)
The tuple after clearing values : ()
 
adnanirshad158
Python tuple-programs
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python Program to Create a Lap Timer - GeeksforGeeks

24 May, 2020
In this article, we will make a simple timer to calculate lap-time intervals using Python.
time:  This module provides various time-related functions. It is a part of Python’s standard library and does not require installation.
Approach:The user needs to press ENTER to complete each lap. The timer keeps counting till CTRL+C is pressed. For each lap we calculate the lap time by subtracting the current time from the total time at the end of the previous lap. The time() function of the time module, returns the current epoch time in milliseconds.
Below is the implementation: 
# importing librariesimport time    # Timer startsstarttime=time.time()lasttime=starttimelapnum=1  print("Press ENTER to count laps.\nPress CTRL+C to stop")  try:     while True:                        # Input for the ENTER key press          input()            # The current lap-time          laptime=round((time.time() - lasttime), 2)            # Total time elapsed           # since the timer started          totaltime=round((time.time() - starttime), 2)            # Printing the lap number,          # lap-time and total time          print("Lap No. "+str(lapnum))           print("Total Time: "+str(totaltime))          print("Lap Time: "+str(laptime))                      print("*"*20)            # Updating the previous total time          # and lap number          lasttime=time.time()          lapnum+=1  # Stopping when CTRL+C is pressedexcept KeyboardInterrupt:     print("Done")
Output:
ENTER to count laps.
Press CTRL+C to stop

Lap No. 1
Total Time: 1.09
Lap Time: 1.09
********************

Lap No. 2
Total Time: 2.66
Lap Time: 1.41
********************

Lap No. 3
Total Time: 5.06
Lap Time: 2.23
********************

Lap No. 4
Total Time: 5.63
Lap Time: 0.4
********************
Done

Python time-module
Python
Python Programs
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
PHP append one array to another - GeeksforGeeks

03 Nov, 2018
Given two array arr1 and arr2 and the task is to append one array to another array.
Examples:
Input : arr1 = [ 1, 2 ]
        arr2 = [ 3, 4 ]

Output : arr1 = [ 1, 2, 3, 4 ]

Input : arr1 = [ "Geeks", "g4g" ]
        arr2 = [ "GeeksforGeeks" ]

Output : arr1 = [ "Geeks", "g4g", "GeeksforGeeks" ]

Using array_merge function: This function returns a new array after merging the two arrays.
Example:
<?php$arr1 = array("Geeks", "g4g");$arr2 = array("GeeksforGeeks", "Computer science portal");  // Get the merged array in the first array itself.$arr1 = array_merge($arr1, $arr2);   echo "arr1 Contents:";  // Use for each loop to print all the array elements.foreach ($arr1 as $value) {    echo $value . "\n";}?>
Output:
arr1 Contents:
Geeks
g4g
GeeksforGeeks
Computer science portal
Using array_push Method: This method pushes the second array element in the first array in-place.
Example:
<?php$arr1 = array(1, 2);$arr2 = array(3, 4);  // arr2 elements are being pushed in the arr1.array_push($arr1 , ...$arr2);   echo "arr1 = ";  // Use for each loop to print all the array elements.foreach ($arr1 as $value) {echo $value . ' ';}?>
Output:
arr1 = 1 2 3 4
Note: Another way to do it is by ‘ + ‘ but it gives fatal warning in the newer versions, hence it is not recommended.
PHP-array
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
multimap::count() in C++ STL - GeeksforGeeks

18 Nov, 2020
The multimap::count is a built-in function in C++ STL which returns the number of times a key is present in the multimap container.
Syntax:
multimap_name.count(key)

Parameters: The function accepts one mandatory parameter key which specifies the key whose count in multimap container is to be returned.
Return Value: The function returns the number of times a key is present in the multimap container.
// C++ function for illustration// multimap::count() function#include <bits/stdc++.h>using namespace std;  int main(){      // initialize container    multimap<int, int> mp;      // insert elements in random order    mp.insert({ 2, 30 });    mp.insert({ 1, 40 });    mp.insert({ 2, 60 });    mp.insert({ 2, 20 });    mp.insert({ 1, 50 });    mp.insert({ 4, 50 });      // count the number of times    // 1 is there in the multimap    cout << "1 exists " << mp.count(1)          << " times in the multimap\n";      // count the number of times    // 2 is there in the multimap    cout << "2 exists " << mp.count(2)          << " times in the multimap\n";      return 0;}
1 exists 2 times in the multimap
2 exists 3 times in the multimap

arorakashish0911
CPP-Functions
cpp-multimap
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Polymorphism in C++
Python - List Words Frequency in String - GeeksforGeeks

08 Jun, 2021
Given a List of Words, Map frequency of each to occurrence in String.
Input : test_str = ‘geeksforgeeks is best for geeks and best for CS’, count_list = [‘best’, ‘geeksforgeeks’, ‘computer’] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input : test_str = ‘geeksforgeeks is best for geeks and best for CS’, count_list = [‘better’, ‘gfg’, ‘computer’] Output : [0, 0, 0] Explanation : No word from list present in string.  
Method #1 : Using defaultdict() + loop + list comprehension
In this, we compute words frequency using loop + defaultdict() and then use list comprehension to get all the counts corresponding to list of words.
Python3
# Python3 code to demonstrate working of# Divide String into Equal K chunks# Using list comprehensionfrom collections import defaultdict # initializing stringstest_str = 'geeksforgeeks is best for geeks and best for CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing count_listcount_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and'] # computing frequencyres = defaultdict(int)for sub in test_str.split():    res[sub] += 1     # assigning to list wordsres = [res[sub] for sub in count_list] # printing resultprint("The list words frequency : " + str(res))
The original string is : geeksforgeeks is best for geeks and best for CS
The list words frequency : [2, 1, 0, 0, 2, 1]
Method #2 : Using Counter() + list comprehension
In this, Counter() is used to perform task of computing frequency, post that, list comprehension is used to assign frequency to list words.
Python3
# Python3 code to demonstrate working of# Divide String into Equal K chunks# Using list comprehensionfrom collections import Counter # initializing stringstest_str = 'geeksforgeeks is best for geeks and best for CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing count_listcount_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and'] # computing frequency using Counter()res = Counter(test_str.split())     # assigning to list wordsres = [res[sub] for sub in count_list] # printing resultprint("The list words frequency : " + str(res))
The original string is : geeksforgeeks is best for geeks and best for CS
The list words frequency : [2, 1, 0, 0, 2, 1]
simranarora5sos
Python string-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
HTTP headers | Alt-Svc - GeeksforGeeks

10 May, 2020
The HTTP headers Alt-Svc header is a response-type header it has been used to advertise alternative service. Which services can be defined by a protocol/host/port combination.
Syntax:
Alt-Svc: clear
Alt-Svc: <protocol-id>=<alt-authority>; ma=<max-age>; persist=1
Directives: This header accept five directives as mentioned above and described below:
clear: This directive define that all alternative services for that origin to be invalidated.
<protocol-id>: This directive is the ALPN protocol identifier.
<alt-authority>: This directive defines an alternative authority which consists of an optional host override, a colon, and a mandatory port number.
ma=<max-age>: It holds the number that defines seconds for which the alternative service is considered fresh if it is omitted then the default value will be 86400. It is an optional directive.
persist=1: This directive holds the alternative service which cleared on network configuration changes. Use of the persist=1 ensures that the entry is not deleted through such changes.
Example:
Alt-Svc: h2=":425"; ma=2585900; persist=1
Alt-Svc: h2=":425"; ma=2585900; persist=1
Alt-Svc: h2=":485"; ma=592000; 

Alt-Svc: h2=":485"; ma=592000; 

To check this Alt-Svc in action go to Inspect Element -> Network check the request header for Alt-Svc like below, Alt-Svc is highlighted you can see.



Supported Browsers: The browsers compatible with HTTP headers Alt-Svc are listed below:

Google Chrome

Internet Explorer

Firefox

Safari

Opera


HTTP-headers


Picked


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
                            
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React

How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ?
Introduction to Chempy in Python - GeeksforGeeks

19 Aug, 2021
ChemPy is a python package designed mainly to solve problems in analytical, physical and inorganic Chemistry. It is a free, open-source Python toolkit for chemistry, chemical engineering, and materials science applications.
ChemPy includes classes for representing substances, reactions, and systems of reactions. It also includes well-established formulae from physical chemistry, as well as analytic solutions to some differential equations commonly encountered in chemical kinetics.
Its intended audience is primarily researchers and engineers who need to perform modeling work. But since the intermediate representations of, e.g., ODE systems and systems of non-linear equations are available symbolically, ChemPy may also be used in an educational setting.
Installation: ChemPy can be installed by running the following script in the Command Prompt / Terminal:
pip install chempy
Here are some examples of the application of the ChemPy module : Example 1 : Printing a list of elements with their mass.  
Python3
# importing the modulefrom chempy.util import periodic # number of elements to be fetchedn = 10 # displaying the informationprint("Atomic No.\tName\t\tSymbol\t\tMass") # fetching the information for# the first 10 elementsfor i in range(1, n + 1):     # displaying the atomic number    print(i, end = "\t\t")     # displaying the name    if len(periodic.names[i]) > 7:        print(periodic.names[i], end = "\t")    else:        print(periodic.names[i], end = "\t\t")     # displaying the symbol    print(periodic.symbols[i], end = "\t\t")     # displaying the mass    print(periodic.relative_atomic_masses[i])
Output :  
Atomic No.    Name        Symbol        Mass
1        Helium        He        4.002602
2        Lithium        Li        6.94
3        Beryllium    Be        9.0121831
4        Boron        B        10.81
5        Carbon        C        12.011
6        Nitrogen    N        14.007
7        Oxygen        O        15.999
8        Fluorine    F        18.998403163
9        Neon        Ne        20.1797
10        Sodium        Na        22.98976928
Example 2 : Let us see how to represent chemical reactions in ChemPy. Consider the formation of water. In the reaction, 2 H2 molecules combine with an O2 molecule to form 2 H2 molecules. In ChemPy the reaction will be created using the Reaction() function of the chempy.chemistry module. 
Python3
# importing the modulefrom chempy import chemistry # creating the reactionreaction = chemistry.Reaction({'H2': 2, 'O2': 1},                              {'H2O': 2}) # displaying the reactionprint(reaction) # displaying the reaction orderprint(reaction.order())
Output :  
2 H2 + O2 -> 2 H2O
3
 
gulshankumarar231
python-modules
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
Python | Difference in keys of two dictionaries - GeeksforGeeks

12 Feb, 2019
Given two dictionaries dic1 and dic2 which may contain same-keys, find the difference of keys in given dictionaries.
Code #1 : Using set to find keys that are missing.
# Python code to find the difference in# keys in two dictionary  # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}dict2= {'key1':'Geeks', 'key2:':'Portal'}  diff = set(dict2) - set(dict1)  # Printing difference in# keys in two dictionaryprint(diff)
{'key2:'}

 Code #2 : Finding keys in dict2 which are not in dict1.
# Python code to find difference in keys in two dictionary  # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks',        'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }}  for key in dict2.keys():    if not key in dict1:          # Printing difference in        # keys in two dictionary        print(key)
key4
key3

 Code #3: Finding keys in dict1 which are not in dict2.
# Python code to find difference in keys in two dictionary  # Initialising dictionary dict1= {'key1':'Geeks', 'key12':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks',        'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }}          for key in dict1.keys():    if not key in dict2:          # Printing difference in        # keys in two dictionary        print(key)
key12

 Code #4 : Finding the same keys in two dictionaries.
# Python code to find difference in keys in two dictionary  # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks',        'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }}          print(set(dict1.keys()).intersection(dict2.keys()))
{'key2', 'key1'}

Python dictionary-programs
python-dict
Python
Python Programs
python-dict
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to remove white spaces from a string using jQuery ? - GeeksforGeeks

22 Mar, 2021

In this article, we will see how to remove the white spaces from string using jQuery. To remove the white spaces, we will use trim() method. The trim() method is used to remove the white spaces from the beginning and end of a string.
Syntax:
jQuery.trim( str )
Parameters: This method accepts a single parameter string that is to be trimmed.
In this case, we write string containing white spaces in <pre> tag and then apply trim() method to remove all white spaces from starting and ending position. After removing the white spaces we use html() method to display the trimmed string.
Example:
HTML
 

 
 










<!DOCTYpe html> 
<html> 
  
<head> 
    <title> 
        How to remove white space from 
        a string using jQuery? 
    </title> 
  
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
  
    <script> 
        $(document).ready(function () { 
            $("h1").css("color", "green"); 
            $("button").click(function () { 
                $(".str").html("String without whitespaces"); 
                var str = $(".string").text(); 
                var trimStr = $.trim(str); 
                $(".res-string").html(trimStr); 
            }) 
        }); 
    </script> 
</head> 
  
<body> 
    <h1>GeeksforGeeks</h1> 
  
    <h3> 
        How to remove white space from 
        a string using jQuery? 
    </h3> 
  
    <h4>String containing white spaces</h4> 
    <pre class="string">    GeeksforGeeks       </pre> 
  
    <button>Trim String</button> 
  
    <h4 class="str"></h4> 
    <pre class="res-string"></pre> 
</body> 
  
</html>






Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

HTML-Questions


HTML-Tags


jQuery-Methods


jQuery-Questions


HTML


JQuery


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
Pointers, smart pointers and shared pointers in C++

Pointers are used to store the address of variable.
Type *pointer;
Type *pointer;
Pointer = variable name;
pointers are used to store address of variable.
pointers can have a null value assigned.
pointer can be referenced by pass by reference.
a pointer has its own memory address and size on the stack.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   // A normal integer variable
   int a = 7;
   // A pointer variable that holds address of a.
   int *p = &a;
   // Value stored is value of variable "a"
   cout<<"Value of Variable : "<<*p<<endl;
   // It will print the address of the variable "a"
   cout<<"Address of Variable : "<<p<<endl;
   // reassign the value.
   *p = 6;
   cout<<"Value of the variable is now: "<<*p<<endl;
   return 0;
}
Value of Variable : 7
Address of Variable : 0x6ffe34
Value of the variable is now: 6
Smart pointer is an abstract data type by using which we can make a normal pointer in such way that it can be used as memory management like file handling, network sockets etc., also it can do many things like automatic destruction, reference counting etc.
Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator. auto_ptr, shared_ptr, unique_ptr and weak_ptr are the forms of smart pointer can be implemented by C++ libraries.
 Live Demo
#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
   T *p; // Actual pointer
   public:
      // Constructor
      Smartpointer(T *ptr = NULL) {
         p = ptr;
      }
   // Destructor
   ~Smartpointer() {
      delete(p);
   }
   // Overloading dereferencing operator
   T & operator * () {
      return *p;
   }
   // Overloding arrow operator so that members of T can be accessed
   // like a pointer
   T * operator -> () {
      return p;
   }
};
int main() {
   Smartpointer<int> p(new int());
   *p = 26;
   cout << "Value is: "<<*p;
   return 0;
}
Value is: 26
shared_ptr is one of the form of smart pointer can be implemented by C++ libraries. It is a container of raw pointer and a reference counting (a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources) ownership structure of its contained pointer in cooperation with all copies of the shared_ptr.
An object which is referenced by the contained raw pointer will be destroyed only when the all copy is detroyed of shared_ptr.
 Live Demo
#include<iostream>
#include<memory>
using namespace std;
int main() {
   shared_ptr<int> ptr(new int(7));
   shared_ptr<int> ptr1(new int(6));
   cout << ptr << endl;
   cout << ptr1 << endl;
   // Returns the number of shared_ptr objects
   // referring to the same managed object.
   cout << ptr.use_count() << endl;
   cout << ptr1.use_count() << endl;
   // Relinquishes ownership of ptr on the object
   // and pointer becomes NULL
   ptr.reset();
   cout << ptr.get() << endl;
   cout << ptr1.use_count() << endl;
   cout << ptr1.get() << endl;
   return 0;
}
0xe80900
0xe80940
1
1
0
1
0xe80940