Official OWASP NIE Student Chapter's Hacktoberfest Open Source Repository
import pandas as pd

class WhatsAppChat:
    def __init__(self, filename):
        # Initialize the object by reading in the chat file, and counting word frequency and next words
        self.titles = self.read_chat_file(filename)
        self.word_freq_dict = self.count_word_frequency()
        self.next_words_dict = self.find_next_words()

    def read_chat_file(self, filename):
        """Reads in a WhatsApp chat text file and returns a list of titles."""
        chat_df = pd.read_fwf(filename, header=None)
        # Extract the chat titles from the DataFrame and return them as a list
        titles = [title for title in chat_df[2]]
        return titles

    def count_word_frequency(self):
        """Counts the frequency of each word in a list of titles."""
        word_freq_dict = {}
        for title in self.titles:
            # Split each title into words and count their frequency
            for word in str(title).split():
                if len(word) > 1:
                    if word in word_freq_dict.keys():
                        word_freq_dict[word] += 1
                    else:
                        word_freq_dict[word] = 1
        # Sort the word frequency dictionary by value in descending order and return it
        sorted_word_freq_dict = dict(sorted(word_freq_dict.items(),
                                             key=lambda x: -1*int(x[1])))
        return sorted_word_freq_dict

    def find_next_words(self):
        """Finds the most common next word for each word in a list of titles."""
        next_words_dict = {}
        for title in self.titles:
            # Split each title into words and count the frequency of each next word for each word
            words = str(title).split()
            for i in range(len(words)):
                if i != len(words) - 1:
                    current_word = words[i]
                    next_word = words[i+1].replace("\n", "")
                    if current_word in next_words_dict:
                        if next_word in next_words_dict[current_word]:
                            next_words_dict[current_word][next_word] += 1
                        else:
                            next_words_dict[current_word][next_word] = 1
                    else:
                        next_words_dict[current_word] = {next_word: 1}
        # Return the dictionary of next words
        return next_words_dict


class NextWordPredictor:
    def __init__(self, chat, num_predictions=1):
        # Initialize the object with a WhatsAppChat object and the number of predictions to make
        self.chat = chat
        self.num_predictions = num_predictions

    def predict_next_word(self, current_word):
        """Predicts the next word given a current word and a dictionary of next words."""
        if current_word in self.chat.next_words_dict:
            # Get the dictionary of next words for the current word and sort it by frequency
            next_word_freq_dict = self.chat.next_words_dict[current_word]
            sorted_next_words = sorted(next_word_freq_dict.items(),
                                        key=lambda x: x[1],
                                        reverse=True)
            # Get the top num_predictions words and return them
            next_words = [word[0] for word in sorted_next_words[:self.num_predictions]]
            return next_words
        else:
            # If the current word is not in the dictionary of next words, return None
            return None

# Create a WhatsAppChat object and a NextWordPredictor object, and print the predictions

# export the whatsapp chat and use the txt file
chat = WhatsAppChat('Chats.txt')

# example for finding 3 next words for the word "Good"
predictor = NextWordPredictor(chat, num_predictions=3)
print(predictor.predict_next_word("Good"))

Data Analysis/Next_Word_Predictor.py
owasp-nie/open-source-hacktoberfest
import pandas as pd

# Read a CSV file
data = pd.read_csv('data.csv')

# Display basic statistics
print("Summary Statistics:")
print(data.describe())

# Plot a histogram
data['column_name'].hist()
plt.title('Histogram of Column')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()

Data Analysis/analyze-csv.py
owasp-nie/open-source-hacktoberfest
# Title: 1926. Nearest Exit from Entrance in Maze
# Difficulty: Medium
# Problem: https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/description/

## Using sets and queues

class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        rows, cols = len(maze), len(maze[0])
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        queue = deque([(entrance[0], entrance[1], 0)])  # Store (row, col, steps)
        visited = set()
        visited.add(tuple(entrance))  # Mark entrance as visited
        
        while queue:
            row, col, steps = queue.popleft()
            
            # Check if we have reached a valid exit point (excluding the entrance)
            if (row != entrance[0] or col != entrance[1]) and (row == 0 or row == rows - 1 or col == 0 or col == cols - 1):
                return steps
            
            for dr, dc in directions:
                r, c = row + dr, col + dc
                
                # Check if the next cell is within bounds and not a wall, and if it's not visited
                if 0 <= r < rows and 0 <= c < cols and maze[r][c] == '.' and (r, c) not in visited:
                    queue.append((r, c, steps + 1))
                    visited.add((r, c))

Data Structures & Algorithms/Nearest_Exit.py
owasp-nie/open-source-hacktoberfest
# Title: 199. Binary Tree Right Side View
# Difficulty: Medium
# Problem: https://leetcode.com/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=leetcode-75


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        self.level = 0
        self.res = []
        self.dfs(root, 1)
        
        return self.res
    # Implement depth-first search
    def dfs(self, node: Optional[TreeNode], curr_level: int) -> None:
        if node:
            if curr_level > self.level:
                self.res.append(node.val)
                self.level += 1
            if node.right:
                self.dfs(node.right, curr_level + 1)
            if node.left:
                self.dfs(node.left, curr_level + 1)

Data Structures & Algorithms/Right_View_in_Binary_Tree.py
owasp-nie/open-source-hacktoberfest
def binary_search(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1  # Element not found

# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 5
result = binary_search(arr, target)
if result != -1:
    print(f"Element found at index {result}")
else:
    print("Element not found")

Data Structures & Algorithms/binary-search.py
owasp-nie/open-source-hacktoberfest
import random

def play_game():
    target_number = random.randint(1, 100)
    attempts = 0

    while True:
        guess = int(input("Guess the number (1-100): "))
        attempts += 1

        if guess == target_number:
            print(f"Congratulations! You guessed the number in {attempts} attempts.")
            break
        elif guess < target_number:
            print("Higher! Try again.")
        else:
            print("Lower! Try again.")

if __name__ == "__main__":
    play_game()

Game Development/higher-lower.py
owasp-nie/open-source-hacktoberfest
import numpy as np
from sklearn.linear_model import LinearRegression

# Sample data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])

# Create a linear regression model
model = LinearRegression()

# Fit the model to the data
model.fit(X, y)

# Predict using the model
prediction = model.predict([[6]])
print("Predicted value:", prediction[0])

Machine Learning/simple-linear-regression.py
owasp-nie/open-source-hacktoberfest
# password strength checker
import re
import random

class PasswordStrengthChecker:
    def __init__(self, password):
        self.password = password

    def check_password_strength(self):
        score = 0

        # Check length of password
        if len(self.password) < 8:
            return "Very Weak"
        elif len(self.password) >= 8 and len(self.password) <= 10:
            score += 1
        elif len(self.password) > 10:
            score += 2

        # Check for uppercase letters
        if re.search(r'[A-Z]', self.password):
            score += 1

        # Check for lowercase letters
        if re.search(r'[a-z]', self.password):
            score += 1

        # Check for numbers
        if re.search(r'\d', self.password):
            score += 1

        # Check for special characters
        if re.search(r'[^A-Za-z0-9]', self.password):
            score += 2

        # Return password strength based on score
        if score == 0:
            return "Very Weak"
        elif score == 1:
            return "Weak"
        elif score == 2:
            return "Medium"
        elif score == 3:
            return "Strong"
        else:
            return "Very Strong"

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = PasswordStrengthChecker(password)
        self.password_history = [password]

    def change_password(self, new_password):
        """
        This function changes the user's password and adds the old password to
        the password history.
        """
        old_password = self.password.password
        self.password_history.append(old_password)
        self.password = PasswordStrengthChecker(new_password)

    def reset_password(self):
        """
        This function generates a new random password for the user and adds it to
        the password history.
        """
        new_password = self.generate_random_password()
        self.password_history.append(self.password.password)
        self.password = PasswordStrengthChecker(new_password)
        return new_password

    def generate_random_password(self):
        """
        This function generates a random password of length 10 with at least one
        uppercase letter, one lowercase letter, one number, and one special
        character.
        """
        chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()'
        password = ''.join(random.choice(chars) for i in range(10))
        while not (re.search(r'[A-Z]', password) and re.search(r'[a-z]', password) and re.search(r'\d', password) and re.search(r'[^A-Za-z0-9]', password)):
            password = ''.join(random.choice(chars) for i in range(10))
        return password

    def login(self, password):
        """
        This function checks if the password is valid for the user and returns True
        if it is, or False if it is not.
        """
        if self.password.password != password:
            print("Incorrect password.")
            return False
        else:
            print("Welcome back, {}!".format(self.username))
            return True

# example usage
# create a new user with a password
user1 = User("johndoe", "MyPassword1!")

# check the strength of the password
print(user1.password.check_password_strength())  # prints "Medium"

# attempt to login with the wrong password
user1.login("WrongPassword1!")  # prints "Incorrect password." and returns False

# attempt to login with the correct password
user1.login("MyPassword1!")  # prints "Welcome back, johndoe!" and returns True

# change the user's password
user1.change_password("NewPassword123!")

# check the strength of the new password
print(user1.password.check_password_strength())  # prints "Strong"

# reset the user's password
new_password = user1.reset_password()

# check the strength of the new password
print(user1.password.check_password_strength())  # prints "Very Strong"

Miscellaneous/Password_Manager.py
owasp-nie/open-source-hacktoberfest
import random
import string

def generate_random_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

if __name__ == "__main__":
    password = generate_random_password()
    print("Generated Password:", password)

Miscellaneous/random-password-generator.py
owasp-nie/open-source-hacktoberfest
"""
Django settings for django_hello_world project.

Generated by 'django-admin startproject' using Django 4.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-6$bn%r9^6!3p*d68iich((&_4au*!@pu0&k#a)$)1k)_5+uv_0'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello_world',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'django_hello_world.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_hello_world.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Web Development/Django Hello World/django_hello_world/settings.py
owasp-nie/open-source-hacktoberfest
"""
URL configuration for django_hello_world project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('hello_world.urls')),
]

Web Development/Django Hello World/django_hello_world/urls.py
owasp-nie/open-source-hacktoberfest
from django.shortcuts import render

def home(request):
    return render(request, 'hello_world/hello-world.html')

Web Development/Django Hello World/hello_world/views.py
owasp-nie/open-source-hacktoberfest