Skip to content

Commit

Permalink
Merge branch 'main' into issue#838
Browse files Browse the repository at this point in the history
  • Loading branch information
Sameeratweb authored Oct 31, 2024
2 parents 87eeace + bb472fa commit 4ebcf31
Show file tree
Hide file tree
Showing 203 changed files with 1,825,679 additions and 153 deletions.
49 changes: 49 additions & 0 deletions .github/workflows/auto-label.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Auto Label Issue

on:
issues:
types: [opened, reopened, edited]

jobs:
label_issue:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Label Issue
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const issue = context.payload.issue;
const issueBody = issue.body ? issue.body.toLowerCase() : '';
// Check for participation roles in the issue body
const hasGSSOC = issueBody.includes('gssoc');
const hasHacktoberfest = issueBody.includes('hacktoberfest');
const labelsToAdd = [];
// Add labels based on participation roles
if (hasGSSOC) {
labelsToAdd.push('gssoc-ext');
console.log('gssoc-ext label will be added for GSSOC participant.');
}
if (hasHacktoberfest) {
labelsToAdd.push('hacktoberfest');
console.log('hacktoberfest label will be added for Hacktoberfest participant.');
}
// Add labels if any are present
if (labelsToAdd.length > 0) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: labelsToAdd
});
console.log(`Added labels: ${labelsToAdd.join(', ')}`);
} else {
console.log('No relevant participation role found. Skipping label addition.');
}
72 changes: 72 additions & 0 deletions Advanced_Projects/Telegram_Bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Advanced Telegram Bot Project

This project is a feature-rich Telegram bot built using the `python-telegram-bot` library. The bot provides a variety of interactive commands and functionalities, such as weather updates, motivational quotes, and more.

## Features

- **Basic Commands**: Includes `/start`, `/help`, and `/info` commands to guide users.
- **Weather Updates**: Provides real-time weather information for any city, using an external API.
- **Motivational Quotes**: Offers daily motivational quotes with an option to get more via inline buttons.
- **Interactive Elements**: Inline keyboards for quick interactions, making the bot more engaging.
- **Error Handling**: Comprehensive logging and error handling for smooth operation.

## Setup and Installation

### 1. Install Dependencies

Ensure you have Python 3 installed. Then, install the required libraries:

```bash
pip install -r requirements.txt
```

### 2. Get API Keys

- **Telegram Bot API Key**: Create a bot through [BotFather on Telegram](https://core.telegram.org/bots#botfather) and get the token.
- **Weather API Key**: Sign up on [WeatherAPI](https://www.weatherapi.com/) or [OpenWeatherMap](https://openweathermap.org/) to obtain an API key.

### 3. Configure API Keys

Replace placeholders in `app.py` with your actual API keys:

```python
WEATHER_API_KEY = 'your_weather_api_key'
TELEGRAM_TOKEN = 'your_telegram_bot_token'
```

### 4. Run the Bot

Run the bot using:

```bash
python app.py
```

## Usage

Once the bot is running, you can interact with it on Telegram:

- **/start** - Starts the bot and displays a welcome message.
- **/help** - Lists available commands.
- **/weather `<city_name>`** - Retrieves the current weather for a specified city.
- **/motivate** - Sends a motivational quote with an inline option to get more quotes.

## Example Interactions

- `/start`: "Welcome! Use /help to see available commands."
- `/weather London`: "Weather in London: 18°C, Partly Cloudy"
- `/motivate`: "Stay positive, work hard, make it happen!" with a button for more quotes.

## Project Structure

```
├── app.py # Main bot code
├── README.md # Project documentation
└── requirements.txt # Dependencies
```

## Troubleshooting

- **TypeError**: If you encounter issues with the `Updater` class, ensure you're using `Application` instead (for `python-telegram-bot` v20+).
- **Network/API Errors**: Ensure API keys are correctly configured and active.

64 changes: 64 additions & 0 deletions Advanced_Projects/Telegram_Bot/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import logging
import requests
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes

# Enable logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Constants
WEATHER_API_KEY = 'your_weather_api_key'
TELEGRAM_TOKEN = 'your_telegram_bot_token'

# Start command
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Welcome! Use /help to see available commands.")

# Help command
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
help_text = "/start - Start the bot\n/help - Get help\n/weather - Get current weather\n/motivate - Get daily motivation"
await update.message.reply_text(help_text)

# Weather command with API integration
async def weather(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
city = ' '.join(context.args) if context.args else 'London'
response = requests.get(f"http://api.weatherapi.com/v1/current.json?key={WEATHER_API_KEY}&q={city}")
if response.status_code == 200:
data = response.json()
weather_info = f"Weather in {data['location']['name']}: {data['current']['temp_c']}°C, {data['current']['condition']['text']}"
await update.message.reply_text(weather_info)
else:
await update.message.reply_text("Could not retrieve weather data.")

# Motivation command with inline keyboard
async def motivate(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
quote = "Stay positive, work hard, make it happen!"
keyboard = [[InlineKeyboardButton("Get Another", callback_data='new_motivation')]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(quote, reply_markup=reply_markup)

# Callback for inline button to get new quote
async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
query = update.callback_query
await query.answer()
new_quote = "Believe in yourself and all that you are!"
await query.edit_message_text(text=new_quote)

# Main function to start the bot
def main() -> None:
# Create the Application instance
application = Application.builder().token(TELEGRAM_TOKEN).build()

# Commands
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("weather", weather))
application.add_handler(CommandHandler("motivate", motivate))
application.add_handler(CallbackQueryHandler(button))

# Start the bot
application.run_polling()

if __name__ == '__main__':
main()
2 changes: 2 additions & 0 deletions Advanced_Projects/Telegram_Bot/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
python-telegram-bot
requests
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import List

class Solution:
def maxProfit(self, prices: List[int]) -> int:
# Initialize the minimum price as the price on the first day
min_price = prices[0]
# Initialize max profit as 0 (because we can't make a profit if prices always go down)
max_profit = 0

# Loop through the prices starting from the second day
for i in range(1, len(prices)):
# Calculate the profit if we were to sell on this day
profit_today = prices[i] - min_price
# Update max profit if the profit today is higher
max_profit = max(max_profit, profit_today)
# Update min_price to be the lowest price seen so far
min_price = min(min_price, prices[i])

return max_profit

# Example usage
solution = Solution()

# Example 1
prices1 = [7, 1, 5, 3, 6, 4]
print("Input:", prices1)
print("Max Profit:", solution.maxProfit(prices1)) # Expected output: 5

# Example 2
prices2 = [7, 6, 4, 3, 1]
print("\nInput:", prices2)
print("Max Profit:", solution.maxProfit(prices2)) # Expected output: 0 (no profit possible)
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Best Time To Buy And Sell Stock

## Problem Statement
Given an array `prices` where `prices[i]` represents the price of a given stock on the ith day, you need to maximize your profit by selecting a single day to buy the stock and a different day in the future to sell it.

- The goal is to determine the maximum profit you can achieve from this single transaction.
- If no profit is possible (i.e., prices decrease continuously), return 0.

### Example
1. **Input**: `prices = [7, 1, 5, 3, 6, 4]`
- **Output**: `5`
- **Explanation**: Buy on day 2 (price = 1) and sell on day 5 (price = 6), achieving a maximum profit of `6 - 1 = 5`.

2. **Input**: `prices = [7, 6, 4, 3, 1]`
- **Output**: `0`
- **Explanation**: No profit can be made, as prices are in descending order.

## Solution Approach
The solution involves a single-pass algorithm to find the maximum profit efficiently.

1. **Track Minimum Price**: Keep track of the lowest stock price encountered as you iterate over the array. This is the day to "buy" for maximum profit.
2. **Calculate Maximum Profit**: For each price, calculate the potential profit if you were to sell on that day by subtracting the minimum price seen so far.
3. **Update Maximum Profit**: If the potential profit for the current price is greater than the maximum profit so far, update the maximum profit.

This approach has a time complexity of **O(n)**, as we only traverse the `prices` array once.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
INF = 99

def shortestDist(graph, n, source, target):
dist = [INF] * (n + 1)
path = [-1] * (n + 1)

dist[target] = 0
path[target] = target

for i in range(target - 1, 0, -1):
for j in range(i + 1, n + 1):
if graph[i][j] != INF and dist[i] > graph[i][j] + dist[j]:
dist[i] = graph[i][j] + dist[j]
path[i] = j

if dist[source] == INF:
print(f"There is no path from node {source} to node {target}")
return

print(f"The shortest path distance from node {source} to node {target} is: {dist[source]}")

print("Path:", source, end="")
current = source
while current != target:
current = path[current]
print(f" -> {current}", end="")
print()

def main():
n = int(input("Enter the number of vertices in the graph: "))

graph = [[INF] * (n + 1) for _ in range(n + 1)]

print(f"Enter the adjacency matrix (use {INF} for INF):")
for i in range(1, n + 1):
row = list(map(int, input(f"Row {i}: ").split()))
for j in range(1, n + 1):
graph[i][j] = row[j - 1]

source = int(input("Enter the source node: "))
target = int(input("Enter the target node: "))

shortestDist(graph, n, source, target)

if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
self.random = None

# Function to clone the linked list with random pointers
def clone_linked_list_with_random_pointer(head):
if not head:
return None

# Step 1: Create a dictionary to store the mapping from original to cloned nodes
node_map = {}

# Step 2: First pass to create all nodes (without setting next or random)
curr = head
while curr:
node_map[curr] = ListNode(curr.val) # Map original node to its clone
curr = curr.next

# Step 3: Second pass to set next and random pointers
curr = head
while curr:
node_map[curr].next = node_map.get(curr.next) # Set the next pointer
node_map[curr].random = node_map.get(curr.random) # Set the random pointer
curr = curr.next

# Return the head of the cloned list
return node_map[head]

# Helper function to create a linked list from a list of values and random indices
def create_linked_list(values, random_indices):
if not values:
return None

# Create all nodes
nodes = [ListNode(val) for val in values]

# Set the next pointers
for i in range(len(nodes) - 1):
nodes[i].next = nodes[i + 1]

# Set the random pointers based on random_indices
for i, random_index in enumerate(random_indices):
if random_index != -1: # -1 indicates no random pointer
nodes[i].random = nodes[random_index]

return nodes[0]

# Helper function to print the linked list along with random pointers
def print_linked_list(head):
curr = head
while curr:
random_val = curr.random.val if curr.random else "NULL"
print(f"Node({curr.val}) -> Random({random_val})")
curr = curr.next

# Main function to demonstrate cloning
if __name__ == "__main__":
# Define values and random indices for each node
values = [1, 2, 3, 4, 5]
random_indices = [2, 4, -1, 0, 1] # -1 indicates no random pointer

# Create the linked list with random pointers
original_list = create_linked_list(values, random_indices)

print("Original list with random pointers:")
print_linked_list(original_list)

# Clone the linked list
cloned_list = clone_linked_list_with_random_pointer(original_list)

print("\nCloned list with random pointers:")
print_linked_list(cloned_list)
Loading

0 comments on commit 4ebcf31

Please sign in to comment.