code-rag-bench/online-tutorials huggingface dataset:
How to get service information with the WMI method using PowerShell?

You can also use the WMI method to get the services information instead of standard command Get-Service.
To get the service information on the server, you need to use WMI class Win32_Service.
Get-WmiObject -Class Win32_Service
ExitCode  : 0
Name      : Browser
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

ExitCode  : 0
Name      : BTAGService
ProcessId : 1468
StartMode : Manual
State     : Running
Status    : OK

ExitCode  : 0
Name      : BthAvctpSvc
ProcessId : 1460
StartMode : Manual
State     : Running
Status    : OK

ExitCode  : 0
Name      : bthserv
ProcessId : 1480
StartMode : Manual
State     : Running
Status    : OK
You can filter the specific output with Select-Object.
Get-WmiObject win32_Service | Select-Object Name, State, Startmode

Name                                                   State   Startmode
----                                                   -----   ---------
AdobeARMservice                                        Running Auto
AdobeFlashPlayerUpdateSvc                              Stopped Manual
AJRouter                                               Stopped Manual
ALG                                                    Stopped Manual
AppIDSvc                                               Stopped Manual
Appinfo                                                Running Manual
AppMgmt                                                Stopped Manual
AppReadiness                                           Stopped Manual
AppVClient                                             Stopped Disabled
AppXSvc                                                Stopped Manual
AssignedAccessManagerSvc                               Stopped Manual
AudioEndpointBuilder                                   Running Auto
Audiosrv                                               Running Auto
autotimesvc                                            Stopped Manual
AVP20.0                                                Running Auto
AxInstSV                                               Stopped Manual
BDESVC                                                 Stopped Manual
BFE                                                    Running Auto
BITS                                                   Running Auto
Bluetooth Device Monitor                               Running Auto
Bluetooth OBEX Service                                 Running Auto
To get the services on a remote computer(s) using WMI.
Get-WmiObject win32_Service –ComputerName Win7,Test-PC | Select-
Object Name, State, Startmode
K Nearest Neighbours — Introduction to Machine Learning Algorithms | by Rohith Gandhi | Towards Data Science

The reason we find that much importance is given to classification algorithms and not much is given to regression algorithms is because a lot of problems faced during our diurnal routine belongs to the classification task. For example, we would like to know whether a tumour is malignant or benign, we like to know whether the product we sold was received positively or negatively by the consumers, etc. K nearest neighbours is another classification algorithm and it is very simple one too. If you are following this article after K means algorithm, don’t get confused as these both belong to different domains of learning. K means is a clustering/unsupervised algorithm whereas K nearest neighbours is a classification/supervised learning algorithm.
In K means algorithm, for each test data point, we would be looking at the K nearest training data points and take the most frequently occurring classes and assign that class to the test data. Therefore, K represents the number of training data points lying in proximity to the test data point which we are going to use to find the class.
1. Load the training and test data 2. Choose the value of K 3. For each point in test data:       - find the Euclidean distance to all training data points       - store the Euclidean distances in a list and sort it        - choose the first k points        - assign a class to the test point based on the majority of      classes present in the chosen points4. End 
We will be using the Iris dataset to illustrate the KNN algorithm. The Iris dataset has four features, we will only be using two(Sepal Length, Petal Length) of them. This helps us to better visualize the data points.
We load the Iris dataset and obtain the target values and store it in an array. We drop the target values and the two features that we won’t need from the data frame.
From plotting the data points based on the two features, we obtain a scatter plot as shown below.
We convert the classes which is present in string types into integer types. We shuffle and split the data into training and testing data, 90% of data is used for training while the remaining 10% is used for testing.
We use Scikit-learn library to implement our KNN algorithm. We take a range of values of K, from 1 to 20 and plot the accuracy of our KNN model based on the different values of K.
You can see that we are able to achieve 100% accuracy at K = 3 and the accuracy remains the same for greater values of K. Now that we have implemented the algorithm using the Scikit-learn library, let’s try to implement the KNN algorithm without Scikit-learn. This would provide us with a better intuitive understanding of how the algorithm works.
We implement the algorithm based on the pseudocode mentioned above. We use the value of K = 3. The accuracy of the model is again 100%.
K nearest neighbours is a simple classification algorithm with a wide array of applications. Knowing how it works definitely helps :)
jQuery Mobile - Touch Swipe Event

Fires when the user horizontally drag more than 30px over an element using id of the page to specify an event and on() method attaches the event handlers.
Following example describes the use of swipe event in jQuery Mobile Framework.
<!DOCTYPE html>
   <head>
      <title>Swipe Event</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
      <script src = "https://code.jquery.com/jquery-1.11.3.min.js"></script>
      <script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
      
      <script>
         $(document).on("pagecreate","#page1",function() {
            $("p").on("swipe",function() {
               $("span").text("swipe event occurred!!!");
            });
         });
      </script>
   </head>
   
   <body>
      <div data-role = "page" id = "page1">
         <div data-role = "header">
            <h2>Header</h2>
         </div>

         <div data-role = "main" class = "ui-content">
            <p>It will display the text when you swipe here.</p>
            <span style = "color:orange"></span>
         </div>

         <div data-role = "footer">
            <h2>Footer</h2>
         </div>
      
      </div>
   </body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above html code as jqm_touch_swipe_event.html file in your server root folder.
Save the above html code as jqm_touch_swipe_event.html file in your server root folder.
Open this HTML file as http://localhost/jqm_touch_swipe_event.html and the following output will be displayed.
Open this HTML file as http://localhost/jqm_touch_swipe_event.html and the following output will be displayed.
It will display the text when you swipe here.

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Python program to find hash from a given tuple

Suppose we have a tuple. There are few numbers are present. We have to find the hash value of this tuple by using hash() function. This is a built-in function. The hash() function can work on some datatypes like int, float, string, tuples etc, but some types like lists are not hashable. As
lists are mutable in nature, we cannot hash it. This hash value is used to map other values when we use dictionary.
So, if the input is like t = (2,4,5,6,7,8), then the output will be -1970127882925375109
To solve this, we will follow these steps −
take the tuple as input
take the tuple as input
call hash function and pass the tuple into it hash(tuple)
call hash function and pass the tuple into it hash(tuple)
Let us see the following implementation to get better understanding
def solve(t):
   return hash(t)

t = (2,4,5,6,7,8)
print(solve(t))
(2,4,5,6,7,8)
-6569923111468529526
JSTL - Core <c:url> Tag

The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically performs URL rewriting when necessary. The var attribute specifies the variable that will contain the formatted URL.
The JSTL url tag is just an alternative method of writing the call to the response.encodeURL() method. The only real advantage the url tag provides is proper URL encoding, including any parameters specified by children param tag.
The <c:url> tag has the following attributes −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
   <head>
      <title><c:url> Tag Example</title>
   </head>

   <body>
      <a href = "<c:url value = "/jsp/index.htm"/>">TEST</a>
   </body>
</html>
This will produce the following result −
TEST


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
A comma operator question in C/C++ ?

Comma Operator in C/C++ programming language has two contexts −
As a Separator −
As a Separator −
As an operator − The comma operator { , } is a binary operator that discards the first expression (after evaluation) and then use the value of the second expression. This operator has the least precedence.
As an operator − The comma operator { , } is a binary operator that discards the first expression (after evaluation) and then use the value of the second expression. This operator has the least precedence.
Consider the following codes and guess the output −
 Live Demo
#include <stdio.h>
int main(void) {
   char ch = 'a', 'b', 'c';
   printf("%c", ch);
   return 0;
}
It gives an error because the works as a separator.
prog.c: In function ‘main’:
prog.c:5:20: error: expected identifier or ‘(’ before 'b'
char ch = 'a', 'b', 'c';
^~~
 Live Demo
#include <stdio.h>
int main(void) {
   char ch;
   ch = 'a','b','c';
   printf("%c", ch);
   return 0;
}
It gives a as output as it works because the ‘,’ works as operator but it precedence is below assignment operator hence the output is a.
a
 Live Demo
#include <stdio.h>
int f1() {
   return 43;
}
int f2() {
   return 123 ;
}
int main(void) {
   int a;
   a = (f1() , f2());
   printf("%d", a);
   return 0;
}
It gives 123 as output as the ‘, ’ works as operator and being in braces it works and evaluates the second expression and gives output.
123
Neo4j - Foreach Clause

The FOREACH clause is used to update data within a list whether components of a path, or result of aggregation.
Following is the syntax of the FOREACH clause.
MATCH p = (start node)-[*]->(end node) 
WHERE start.node = "node_name" AND end.node = "node_name" 
FOREACH (n IN nodes(p)| SET n.marked = TRUE) 

Before proceeding with the example, create a path p in Neo4j database as shown below.
CREATE p = (Dhawan {name:"Shikar Dhawan"})-[:TOPSCORRER_OF]->(Ind{name: 
   "India"})-[:WINNER_OF]->(CT2013{name: "Champions Trophy 2013"}) 
RETURN p 
Following is a sample Cypher Query which adds a property to all the nodes along the path using the FOREACH clause.
MATCH p = (Dhawan)-[*]->(CT2013) 
   WHERE Dhawan.name = "Shikar Dhawan" AND CT2013.name = "Champions Trophy 2013" 
FOREACH (n IN nodes(p)| SET n.marked = TRUE)
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
To verify the creation of the node, type and execute the following query in the dollar prompt.
MATCH (n) RETURN n 

This query returns all the nodes in the database (we will discuss this query in detail in the coming chapters).
On executing, this query shows the created node as shown in the following screenshot.
 Print
 Add Notes
 Bookmark this page
Show flex items horizontally in Bootstrap

To show flex items horizontally, use the flex-row class.
Add it to <div> class −
<div class="d-flex flex-row bg-primary mb-3">
Now add flex items accordingly −
<div class="d-flex flex-row bg-primary mb-3">
  <div class="p-2 bg-info">TCS</div>
  <div class="p-2 bg-secondary">Wipro</div>
  <div class="p-2 bg-danger">Accenture</div>
  <div class="p-2 bg-warning">Gartner</div>
</div>
Here is the complete example to implement the flex items horizontally −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

  <div class="container mt-3">
    <h2>Companies</h2>
    <div class="d-flex flex-row bg-primary mb-3">
      <div class="p-2 bg-info">TCS</div>
      <div class="p-2 bg-secondary">Wipro</div>
      <div class="p-2 bg-danger">Accenture</div>
      <div class="p-2 bg-warning">Gartner</div>
    </div>
  </div>

</body>
</html>
How to convert a JSON object to an enum using Jackson in Java?

A JSONObject can parse the text from String to produce a Map kind of an object. An Enum can be used to define a collection of constants, when we need a predefined list of values which do not represent some kind of numeric or textual data then we can use an enum. We can convert a JSON object to an enum using the readValue() method of ObjectMapper class.
In the below example, we can convert/deserialize a JSON object to Java enum using the Jackson library.
import com.fasterxml.jackson.databind.*;
public class JSONToEnumTest {
   public static void main(String arg[]) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      Employee emp = mapper.readValue("{\"jobType\":\"CONTRACT\"}", Employee.class);
      System.out.println(emp.getJobType());
   }
   public static class Employee {
      private JobType jobType;
      public JobType getJobType() {
         return jobType;
      }
      public void setJobType(JobType jobType) {
         this.jobType = jobType;
      }
   }
   public enum JobType {
      PERMANENT,
      CONTRACT,
   }
}
CONTRACT
How can we stop a thread in Java?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java.This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method. The stop() method is deprecated in Java due to thread-safety issues.
@Deprecated
public final void stop()
import static java.lang.Thread.currentThread;
public class ThreadStopTest {
   public static void main(String args[]) throws InterruptedException {
      UserThread userThread = new UserThread();
      Thread thread = new Thread(userThread, "T1");
      thread.start();
      System.out.println(currentThread().getName() + " is stopping user thread");
      userThread.stop();
      Thread.sleep(2000);
      System.out.println(currentThread().getName() + " is finished now");
   }
}
class UserThread implements Runnable {
   private volatile boolean exit = false;
   public void run() {
      while(!exit) {
         System.out.println("The user thread is running");
      }
      System.out.println("The user thread is now stopped");
   }
   public void stop() {
      exit = true;
   }
}
main is stopping user thread
The user thread is running
The user thread is now stopped
main is finished now
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider a token ring network with a length of 2 km having 10 stations including a monitoring station. The propagation speed of the signal is 2 × 108 m/s and the token transmission time is ignored. If each station is allowed to hold the token for 2 μsec, the minimum time for which the monitoring station should wait (in μsec)before assuming that the token is lost is _______.(A) 28 to 30(B) 20 to 22(C) 0 to 2(D) 31 to 33Answer: (A)Explanation:
Length = 2 km
Propagation Speed v = 2*10^8 m/s
Token Holding Time = 2 micro sec

Waiting time
= length/speed + (#stations - 1)*(token holding time) to 
  length/speed + (#stations)*(token holding time)
= 28 to 30

Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2004 | Question 3
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2011 | Question 65
MySQL Tryit Editor v1.0

SELECT CONCAT_WS("-", "SQL", "Tutorial", "is", "fun!") AS ConcatenatedString;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
C library function - difftime()

The C library function double difftime(time_t time1, time_t time2) returns the difference of seconds between time1 and time2 i.e. (time1 - time2). The two times are specified in calendar time, which represents the time elapsed since the Epoch (00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)).
Following is the declaration for difftime() function.
double difftime(time_t time1, time_t time2)
time1 − This is the time_t object for end time.
time1 − This is the time_t object for end time.
time2 − This is the time_t object for start time.
time2 − This is the time_t object for start time.
This function returns the difference of two times (time1 - time2) as a double value.
The following example shows the usage of difftime() function.
#include <stdio.h>
#include <time.h>

int main () {
   time_t start_t, end_t;
   double diff_t;

   printf("Starting of the program...\n");
   time(&start_t);

   printf("Sleeping for 5 seconds...\n");
   sleep(5);

   time(&end_t);
   diff_t = difftime(end_t, start_t);

   printf("Execution time = %f\n", diff_t);
   printf("Exiting of the program...\n");

   return(0);
}
Let us compile and run the above program that will produce the following result −
Starting of the program...
Sleeping for 5 seconds...
Execution time = 5.000000
Exiting of the program...


    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
How to get the web page contents from a WebView in Android?

This example demonstrates how do I get the web page contents from a webView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <WebView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/webView"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      WebView webView = findViewById(R.id.webView);
      webView.loadUrl("http://www.tutorialspoint.com");
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.INTERNET"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
final keyword in Java

final is a non-access modifier for Java elements. The final modifier is used for finalizing the implementations of classes, methods, and variables.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object.
However, the data within the object can be changed. So, the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
public class Test {
   final int value = 10;
   // The following are examples of declaring constants:
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";
   public void changeValue() {
      value = 12; // will give an error
   }
}
A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.
The main intention of making a method final would be that the content of the method should not be changed by any outsider.
You declare methods using the final modifier in the class declaration, as in the following
public class Test {
   public final void changeName() {
      // body of method
   }
}
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.
public final class Test {
   // body of class
}
C# | Check if a Stack contains an element - GeeksforGeeks

01 Feb, 2019
Stack represents a last-in, first out collection of object.Stack<T>.Contains(Object) Method is used to check whether an element is in the Stack<T> or not.
Syntax:
public virtual bool Contains(object obj);

Return Value: The function returns True if the element exists in the Stack<T> and returns False if the element doesn’t exist in the Stack.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to Check if a Stack// contains an elementusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack of strings        Stack<string> myStack = new Stack<string>();          // Inserting the elements into the Stack        myStack.Push("Geeks");        myStack.Push("Geeks Classes");        myStack.Push("Noida");        myStack.Push("Data Structures");        myStack.Push("GeeksforGeeks");          // Checking whether the element is        // present in the Stack or not        // The function returns True if the        // element is present in the Stack, else        // returns False        Console.WriteLine(myStack.Contains("GeeksforGeeks"));    }}
True

Example 2:
// C# code to Check if a Stack// contains an elementusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack of Integers        Stack<int> myStack = new Stack<int>();          // Inserting the elements into the Stack        myStack.Push(5);        myStack.Push(10);        myStack.Push(15);        myStack.Push(20);        myStack.Push(25);          // Checking whether the element is        // present in the Stack or not        // The function returns True if the        // element is present in the Stack, else        // returns False        Console.WriteLine(myStack.Contains(7));    }}
False

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.contains?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-Namespace
CSharp-Generic-Stack
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
Changing the Frequency (Precision) of Time Data in Pandas | by Allison Stafford | Towards Data Science

Today we’re going to take Washington State Ferry wait announcements (tweets with to-the-minute timestamps) and convert them into a full hour-by-hour data set. I saw some other suggestions floating around the Stack Overflow, but pandas resample() seems to be an elegant tool for my task.
So far, I have the tweets describing the wait time, the timestamp of those announcements, and the extracted wait time:
I want to expand this information so there is a record for each hour the ferry operated with the number of hours of wait for that time. In this case, the wait time alerts persist until the update that there is no longer an extended wait.
After adjusting the time zone and adding a start-of-day wait reset, all I needed to get the result above was
df = df.resample('1H').ffill()
Let’s take a look at each of these parts:
First, DataFrame.resample() changes the frequency of time series data. See the full documentation here. So you can convert data pertaining to time periods to whatever your desired level. It works on DatetimeIndex fields or any datetime-like column with the argument on='col_name'.
Second, we indicate what strategy we want to use for the non-time data. In this case, ffill() is perfect — it forward fills all data points from the last known value. Alternatively, you can use a variety of strategies, including sum, min, max, mean, median, first, last, std, bfill (backward fill), etc.
In a few lines of code, I was able to get what I need:
You can find the full code on this GitHub repo. For more on datetime data with pandas, check out their time series/date user guide. Happy coding!
C++ Program to print current Day, Date and Time

Current day, date and time are all calendar dates that are printed on screen. In c++, the ctime library contains all the methods and variables related to date and time.
You can also check current date and time details using the ctime library which contains methods to display time. The following methods are used to display details of date and time −
time() − The time() method is used to find the current time. The return time of the time() method is time_t. time_t is the data type that can store time.
localtime() − To convert the time_t type variables to a variable that can hold both date and time. The localtime() function converts time_t to a structure that can hold both date and time. It accepts the time() function as argument.
The data returned by localtime() method cannot be directly printed to the output screen. So, the asctime() method will return the date in the following form −
day month date hh:mm:ss year
Now, let’s put all these methods together into a program. This program uses methods of ctime and defines a time_t this variable is used to hold the current date and time using the time() method. The data from this variable is passed to the localtime() method whose returned data is passed to the asctime() method which returns user representable form and displays it.
 Live Demo
#include<iostream>
#include<ctime>
using namespace std;
int main(){
   time_t timetoday;
   time (&timetoday);
   cout << "Calendar date and time as per todays is : "<< asctime(localtime(&timetoday));
   return 0;
}
Calendar date and time as per today is : Mon Sep 9 18:56:33 2019
ostream::seekp(pos) method in C++ with Examples - GeeksforGeeks

13 Jul, 2021
The seekp(pos) method of ostream in C++ is used to set the position of the pointer in the output sequence with the specified position. This method takes the new position to be set and returns this ostream instance with the position set to the specified new position.Syntax:  
ostream& seekp(streampos pos);
Parameter: This method takes the new position to be set as the parameter.Return Value: This method returns this ostream instance with the position set to the specified new position.Exceptions: If the operation sets an internal state flag (except eofbit) that was registered with member exceptions, the function throws an exception of member type failure.Below examples demonstrate the use of seekp() method in C++:Example 1: To show the use of seekp() with Binary file  
Take the input from the user about the serial number of the record to be displayed
Pass n to the function then open the file in reading mode
Place the write pointer at the starting of record by seekp((n-1)*Sizeof (object))
Write the record to the file and then close it
Open the file read the data and then close the file
 
CPP
// C++ program to show the use of// ostream::seekp() method using binary file #include <bits/stdc++.h>using namespace std; class student {    int rno;    char name[20]; public:    void getdata()    {       name = "geek" rno = 11;    }     void putdata()    {        cout << rno << endl             << name << endl;    }     // accepts the serial number    // of record to be displayed    void DisplayRecordAtPosition(int);}; void student::DisplayRecordAtPosition(int n){     ofstream ofs;     // opening the file in writing mode    ofs.open("he.dat", ios::out | ios::binary);     // displays the size of the object    // sizeof object is 22    // char[20]+int = 1*20 + 2 = 22    cout << "size of record: "         << sizeof(*this) << endl;     // Using seekp() method to change position    ofs.seekp((n - 1) * sizeof(student));     // Writing in the new position  ofs.write(char*)this, sizeof(student));   // Closing the output stream  ofs.close();   ifstream ifs;  ifs.open("he.dat", ios::in | ios::binary);  ifs.seekg((n - 1) * sizeof(student);  ifs.read((char*)this, sizeof(student)) ";  putdata();  ifs.close();} // Driver codeint main(){    student s;    int pos = 1;     s.getdata();     cout << "record no " << pos         << " (position int file "         << pos - 1 << ")\n";    s.DisplayRecordAtPosition(pos);     return 0;}
Output:  
size of record: 24
record no 1 (position int file 0)
rno: 1
name: geek
 
karthikmuthuraj
ruhelaa48
sagar0719kumar
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
std::string class in C++
new and delete operators in C++ for dynamic memory
NumPy Array Reshaping

Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of elements in each dimension.
Convert the following 1-D array with 12 elements into a 2-D array.
The outermost dimension will have 4 arrays, each with 3 elements:
Convert the following 1-D array with 12 elements into a 3-D array.
The outermost dimension will have 2 arrays that contains 3 arrays, each 
  with 2 elements:
Yes, as long as the elements required for reshaping are equal in both shapes.
We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it 
into a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.
Try converting 1D array with 8 elements to a 2D array with 3 elements in each dimension (will raise an error):
Check if the returned array is a copy or a view:
The example above returns the original array, so it is a view.
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the 
dimensions in the reshape method.
Pass -1 as the value, and NumPy will 
calculate this number for you.
Convert 1D array with 8 elements to 3D array with 2x2 elements:
Note: We can not pass -1 to more than one dimension.
Flattening array means converting a multidimensional array into a 1D array.
We can use reshape(-1) to do this.
Convert the array into a 1D array:
Note: There are a lot of functions for changing the shapes of arrays in numpy flatten, ravel and also for rearranging the elements rot90, flip, fliplr, flipud etc. These fall under Intermediate to Advanced section of numpy.
Use the correct NumPy method to change the shape of an array from 1-D to 2-D.
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.(4, 3)

Start the Exercise
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.
MySQL select distinct dates from datetime column in a table?

You need to use DISTINCT keyword to select distinct dates from datetime column in a table.
For an example, let us create a table
mysql> create table PostMesssageDemo
   - > (
   - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > UserMessage varchar(100),
   - > UserPost datetime
   - > );
Query OK, 0 rows affected (0.60 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer',now());
Query OK, 1 row affected (0.17 sec)
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer',date_add(now(),interval 3 month));
Query OK, 1 row affected (0.16 sec)
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer',now());
Query OK, 1 row affected (0.12 sec)
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer','2019-03-31 17:30:34');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from PostMesssageDemo;
The following is the output
+--------+--------------------+---------------------+
| UserId | UserMessage        | UserPost            |
+--------+--------------------+---------------------+
|      1 | Software Developer | 2019-02-15 18:07:27 |
|      2 | Software Developer | 2019-05-15 18:09:18 |
|      3 | Software Developer | 2019-02-15 18:09:31 |
|      4 | Software Developer | 2019-03-31 17:30:34 |
+--------+--------------------+---------------------+
4 rows in set (0.00 sec)
The following is the query to get distinct dates
mysql> select distinct year(UserPost),month(UserPost) from PostMesssageDemo;
Here is the output
+----------------+-----------------+
| year(UserPost) | month(UserPost) |
+----------------+-----------------+
|           2019 |               2 |
|           2019 |               5 |
|           2019 |               3 |
+----------------+-----------------+
3 rows in set (0.00 sec)
AtomicInteger get() method in Java with examples - GeeksforGeeks

31 Jan, 2019
The java.util.concurrent.atomic.AtomicInteger.get() is an inbuilt method in java which returns the current value which is of date-type int.
Syntax:
public final int get()

Parameters: The function does not accepts any parameter.
Return value: The function returns the current value
Program below demonstrates the function:
Program 1:
// Java Program to demonstrates// the get() function  import java.util.concurrent.atomic.AtomicInteger;  public class GFG {    public static void main(String args[])    {          // Initially value as 0        AtomicInteger val            = new AtomicInteger(0);          val.addAndGet(7);          // Prints the updated value        System.out.println("Previous value: "                           + val);          // Gets the current value        int res = val.get();          System.out.println("current value: "                           + res);    }}
Previous value: 7
current value: 7

Program 2:
// Java Program to demonstrates// the get() function  import java.util.concurrent.atomic.AtomicInteger;  public class GFG {    public static void main(String args[])    {          // Initially value as 18        AtomicInteger val = new AtomicInteger(18);          val.addAndGet(7);          // Prints the updated value        System.out.println("Previous value: " + val);          // Gets the current value        int res = val.get();          System.out.println("current value: " + res);    }}
Previous value: 25
current value: 25

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#get–
Java - util package
Java-AtomicInteger
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Calling a Python function from MATLAB - GeeksforGeeks

20 Oct, 2021
We can call the Python functions and objects directly from MATLAB. To call Python functions from MATLAB, need to install a supported version of  Python. MATLAB supports versions 2.7, 3.6, and 3.7
MATLAB  loads Python when you type py.command.
py.modulename.functionname
Below examples shows how to call a user defined Python function from MATLAB.
Example 1 :
Call Python function to print Hello. First of all, we will make a Python module named print.py containing the function. 
Python3
# Python Module - print.py  def printHello():    return "Hello"
Now, open a new file in MATLAB Editor. Verify whether the current folder pointed to the Python search path. Use below code to add the current folder to Python search path.
MATLAB
if count(py.sys.path, '') == 0  insert(py.sys.path, int32(0), '');end
Call the Python function to print Hello.
MATLAB
py.print.printHello();
Output :  
Hello
 
Example 2 : Call Python function to get the sum of two numbers.
First of all, we will create a Python module names add.py containing the function. 
Python3
# Python Module - add.py  def addgivenNumbers( num1, num2):    sum = num1 + num2    return sum
Call Python function to get the sum of two given numbers
MATLAB
py.add.addgivenNumbers(int32(2), int32(3));
Output :  
5
 
saurabh1990aror
MATLAB
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to filter array elements in MongoDB?

You can use $setIntersection operator along with aggregate framework to filter array elements in MongoDB. Let us first create a collection with documents −
> db.filterArrayElementsDemo.insertOne( { "Scores": [10,45,67,78,90,98,99,92] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2d582b64f4b851c3a13c8")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.filterArrayElementsDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"),
   "Scores" : [
      10,
      45,
      67,
      78,
      90,
      98,
      99,
      92
   ]
}
Following is the query to filter array elements −
> db.filterArrayElementsDemo.aggregate([
...    { $match : {
...          _id: ObjectId("5cd2d582b64f4b851c3a13c8")
...    }},
...    { $project: {
...       Scores: {
...          $setIntersection: ['$Scores', [10,98,99]]
...       }
...    }}
... ]);
This will produce the following output −
{ "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores" : [ 10, 98, 99 ] }
Bootstrap navbar-static-top class

To create a navbar that scrolls with the page, add the .navbar-static-top class. This class does not require adding the padding to the <body>.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <nav class = "navbar navbar-default navbar-static-top" role = "navigation">
         <div class = "navbar-header">
            <a class = "navbar-brand" href = "#">Car Accessories</a>
         </div>
         <div>
            <ul class = "nav navbar-nav">
               <li class = "active"><a href = "#">Car Cover</a></li>
               <li><a href = "#">Car Mobile Holder</a></li>
               <li><a href = "#">Car Mobile Charger</a></li>
            </ul>
         </div>
      </nav>
   </body>
</html>
How to extract numbers from a string in Python?

If you only want positive integers, you can split and search for numbers as follows:
>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
For all other cases, using a regular expression would be the best choice. Also when extracting values, it'll be best to convert them to ints from string. For example:
>>> import re
>>> [float(s) for s in re.findall(r'-?\d+\.?\d*', 'he33.45llo -42 I\'m a 32 string 30')]
[33.45, -42.0, 32.0, 30.0]
Tryit Editor v3.7

Tryit: HTML table - invisible columns
Differences between Difference between getc(), getchar(), getch() and getche() functions

All of these functions are used to get character from input and each function returns an integer signifying the status code as well.
Following are the important differences between getc(), getchar(), getch() and getche() functions.
getc() can read characters from any stream. Returns EOF on failure.
Syntax
int getc(FILE *stream);
getchar() can read characters from standard input only.
Syntax
int getchar();
getch() can read characters from standard input but it does not use any buffer and returns immidately without waiting for enter key pressed.
Syntax
int getch();
getche() behaves similar to getch() as it can read characters from standard input and it does not use any buffer and returns immidately without waiting for enter key pressed. Only differnce is that it prints the character as well.
Syntax
int getch();
#include <stdio.h>
#include <conio.h>
int main() {
   printf("%c", getc(stdin));
   printf("%c", getchar());
   printf("%c", getch());
   printf("%c", getche());
   return 0;
}
A
B
C
D
EE
Fixed Point in Python

Suppose we have an array A of unique integers sorted in ascending order, we have to return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. So if the array is like [-10,-5,0,3,7], then the output will be 3, as A[3] = 3 the output will be 3.
To solve this, we will follow these steps −
For i in range 0 to length of Aif i = A[i], then return i
if i = A[i], then return i
return -1
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def fixedPoint(self, A):
      for i in range(len(A)):
         if i == A[i]:
            return i
      return -1
ob1 = Solution()
print(ob1.fixedPoint([-10,-5,0,3,7]))
[-10,-5,0,3,7]
3
Mobile Angular UI - Dropdowns

To work with dropdowns in mobile angular ui, you need to make use of class .dropdown-menu.
Here is an example that displays dropdown.
We will add the changes in src/home/home.html.
<div class="list-group text-center">
   <div class="list-group-item list-group-item-home">
      <h1>{{msg}}</h1>
   </div>
   <div class="list-group-item list-group-item-home">
      <div class="btn-group">
         <a ui-turn-on='testDropdown' class='btn'>
            <i class="fa fa-caret-down" aria-hidden="true"></i>Tutorials
         </a>
         <ul
            class="dropdown-menu"
            ui-outer-click="Ui.turnOff('testDropdown')"
            ui-outer-click-if="Ui.active('testDropdown')"
            role="menu"
            ui-show="testDropdown"
            ui-state="testDropdown"
            ui-turn-off="testDropdown">
            <li><a>PHP</a></li>
            <li><a>JAVA</a></li>
            <li><a>MYSQL</a></li>
            <li class="divider"></li>
            <li><a>PYTHON</a></li>
         </ul>
      </div>
   </div>
</div>
We are having a list of Tutorials shown in the dropdown. The output on the screen is as follows −

    28 Lectures 
     3 hours 

 Asif Hussain

    19 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    30 Lectures 
     3.5 hours 

 Abhilash Nelson

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    62 Lectures 
     4.5 hours 

 Senol Atac

    22 Lectures 
     3 hours 

 Sandip Bhattacharya
 Print
 Add Notes
 Bookmark this page