instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate docstrings for script automation | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | --- +++ @@ -6,6 +6,10 @@ # distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
+"""Facilities for reporting and collecting training statistics across
+multiple processes and devices. The interface is designed to minimize
+sync... | https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/torch_utils/training_stats.py |
Add docstrings following best practices | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | --- +++ @@ -6,6 +6,12 @@ # distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
+"""Facilities for pickling Python code alongside other data.
+
+The pickled code is automatically imported into a separate Python module
+during u... | https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/torch_utils/persistence.py |
Generate helpful docstrings for debugging | import os
import os.path as osp
from argparse import ArgumentParser
from functools import partial
import gradio as gr
import numpy as np
import torch
from PIL import Image
import dnnlib
from gradio_utils import (ImageMask, draw_mask_on_image, draw_points_on_image,
get_latest_points_pair, get... | --- +++ @@ -37,6 +37,11 @@
def clear_state(global_state, target=None):
+ """Clear target history state from global_state
+ If target is not defined, points and mask will be both removed.
+ 1. set global_state['points'] as empty dict
+ 2. set global_state['mask'] as full-one mask.
+ """
if target... | https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/visualizer_drag_gradio.py |
Annotate my code with docstrings | #!/usr/bin/env python3
import subprocess
import os
import re
import csv
import shutil
from datetime import datetime
from pathlib import Path
import argparse
class GemmTuner:
def __init__(self, config_path, model_path, threads=16):
self.config_path = Path(config_path)
self.model_path = model_path
... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+GEMM Configuration Tuning Script
+This script automatically tunes ROW_BLOCK_SIZE, COL_BLOCK_SIZE, and PARALLEL_SIZE
+to find the optimal configuration for maximum throughput (t/s).
+"""
import subprocess
import os
@@ -20,14 +25,17 @@ self.results = []
... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/utils/tune_gemm_config.py |
Improve documentation using docstrings | #!/usr/bin/env python3
from __future__ import annotations
import logging
import argparse
import concurrent.futures
import enum
import faulthandler
import functools
import itertools
import json
import math
import mmap
import os
import re
import signal
import struct
import sys
import textwrap
import time
from abc import... | --- +++ @@ -1000,6 +1000,10 @@
def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]:
+ '''Parallel map, but with backpressure. If the caller doesn't call `next`
+ fast enough, thi... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/utils/convert.py |
Add professional docstrings to my codebase | #!/usr/bin/env python3
import subprocess
import os
import argparse
import re
import csv
from pathlib import Path
from datetime import datetime
class EmbeddingQuantizer:
def __init__(self, input_model, output_dir, quantize_bin="../build/bin/llama-quantize",
bench_bin="../build/bin/llama-bench", ... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Embedding Quantization Script
+This script converts ggml-model-f32.gguf to multiple quantized versions
+with different token embedding types.
+"""
import subprocess
import os
@@ -39,6 +44,16 @@ self.newly_created_files = set() # Track newly created files... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/utils/quantize_embeddings.py |
Write docstrings describing functionality | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import time
from dataclasses import dataclass
from typing import Optional
@dataclass
class PhaseStats:
name: str
... | --- +++ @@ -1,49 +1,57 @@-# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
-#
-# This source code is licensed under the BSD license found in the
-# LICENSE file in the root directory of this source tree.
-
-import time
-from dataclasses import dataclass
-from typing import Optional
-
-
-@dataclas... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/gpu/stats.py |
Add docstrings to improve readability | import os
from logging import getLogger
from pathlib import Path
from typing import (
AbstractSet,
cast,
Collection,
Dict,
Iterator,
List,
Literal,
Sequence,
TypedDict,
Union,
)
import tiktoken
from tiktoken.load import load_tiktoken_bpe
logger = getLogger(__name__)
Role = Li... | --- +++ @@ -1,214 +1,257 @@-import os
-from logging import getLogger
-from pathlib import Path
-from typing import (
- AbstractSet,
- cast,
- Collection,
- Dict,
- Iterator,
- List,
- Literal,
- Sequence,
- TypedDict,
- Union,
-)
-
-import tiktoken
-from tiktoken.load import load_tiktoken_... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/gpu/tokenizer.py |
Add missing documentation to my Python functions | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from torch import nn
from torch... | --- +++ @@ -1,333 +1,366 @@-# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
-#
-# This source code is licensed under the BSD license found in the
-# LICENSE file in the root directory of this source tree.
-
-from dataclasses import dataclass
-from typing import Optional, Tuple, Union
-
-import t... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/gpu/model.py |
Document my Python code with docstrings | #!/usr/bin/env python3
from __future__ import annotations
import logging
import argparse
import concurrent.futures
import enum
import faulthandler
import functools
import itertools
import json
import math
import mmap
import os
import re
import signal
import struct
import sys
import textwrap
import time
from abc import... | --- +++ @@ -1074,6 +1074,10 @@
def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]:
+ '''Parallel map, but with backpressure. If the caller doesn't call `next`
+ fast enough, thi... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/utils/convert-ms-to-gguf-bitnet.py |
Add missing documentation to my Python functions | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import json
import os
import readline # type: ignore # noqa
import sys
import time
from dataclasses import dataclass
fro... | --- +++ @@ -1,354 +1,359 @@-# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
-#
-# This source code is licensed under the BSD license found in the
-# LICENSE file in the root directory of this source tree.
-
-import json
-import os
-import readline # type: ignore # noqa
-import sys
-import time
... | https://raw.githubusercontent.com/microsoft/BitNet/HEAD/gpu/generate.py |
Add professional docstrings to my codebase | ############################## Warning! ##############################
# #
# Onnx Export Not Support All Of Non-Torch Types #
# Include Python Built-in Types!!!!!!!!!!!!!!!!! #
# If You Want TO C... | --- +++ @@ -289,6 +289,20 @@
class SineGen(torch.nn.Module):
+ """Definition of sine generator
+ SineGen(samp_rate, harmonic_num = 0,
+ sine_amp = 0.1, noise_std = 0.003,
+ voiced_threshold = 0,
+ flag_for_pulse=False)
+ samp_rate: sampling rate in Hz
+ harmonic_num: num... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/infer_pack/models_onnx.py |
Add documentation for all methods | ############################## Warning! ##############################
# #
# Onnx Export Not Support All Of Non-Torch Types #
# Include Python Built-in Types!!!!!!!!!!!!!!!!! #
# If You Want TO C... | --- +++ @@ -1,431 +1,459 @@-############################## Warning! ##############################
-# #
-# Onnx Export Not Support All Of Non-Torch Types #
-# Include Python Built-in Types!!!!!!!!!!!!!!!!! #
-# ... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/infer_pack/attentions_onnx.py |
Replace inline comments with docstrings | import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
import logging
logger = logging.getLogger(__name__)
MAX_WAV_VALUE = 32768.0
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression_torc... | --- +++ @@ -1,98 +1,127 @@-import torch
-import torch.utils.data
-from librosa.filters import mel as librosa_mel_fn
-import logging
-
-logger = logging.getLogger(__name__)
-
-MAX_WAV_VALUE = 32768.0
-
-
-def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
- return torch.log(torch.clamp(x, min=clip_val) * C)
... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/train/mel_processing.py |
Fill in missing docstrings in my code | from collections import defaultdict
import torch
import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
import intel_extension_for_pytorch._C as core # pylint: disable=import-error, unused-import
# pylint: disable=protected-access, missing-function-docstring, line-too-long
OptState... | --- +++ @@ -64,6 +64,28 @@
def unscale_(self, optimizer):
+ """
+ Divides ("unscales") the optimizer's gradient tensors by the scale factor.
+ :meth:`unscale_` is optional, serving cases where you need to
+ :ref:`modify or inspect gradients<working-with-unscaled-gradients>`
+ between the backward pas... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/modules/ipex/gradscaler.py |
Add docstrings to incomplete code | import os
import traceback
import logging
logger = logging.getLogger(__name__)
import numpy as np
import torch
import torch.utils.data
from infer.lib.train.mel_processing import spectrogram_torch
from infer.lib.train.utils import load_filepaths_and_text, load_wav_to_torch
class TextAudioLoaderMultiNSFsid(torch.uti... | --- +++ @@ -1,481 +1,517 @@-import os
-import traceback
-import logging
-
-logger = logging.getLogger(__name__)
-
-import numpy as np
-import torch
-import torch.utils.data
-
-from infer.lib.train.mel_processing import spectrogram_torch
-from infer.lib.train.utils import load_filepaths_and_text, load_wav_to_torch
-
-
-... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/train/data_utils.py |
Write docstrings including parameters and return values | import math
import logging
from typing import Optional
logger = logging.getLogger(__name__)
import numpy as np
import torch
from torch import nn
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn import functional as F
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor... | --- +++ @@ -310,6 +310,20 @@
class SineGen(torch.nn.Module):
+ """Definition of sine generator
+ SineGen(samp_rate, harmonic_num = 0,
+ sine_amp = 0.1, noise_std = 0.003,
+ voiced_threshold = 0,
+ flag_for_pulse=False)
+ samp_rate: sampling rate in Hz
+ harmonic_num: num... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/infer_pack/models.py |
Add standardized docstrings across the file | from typing import List, Optional
import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def get_padding(kernel_... | --- +++ @@ -1,166 +1,172 @@-from typing import List, Optional
-import math
-
-import numpy as np
-import torch
-from torch import nn
-from torch.nn import functional as F
-
-
-def init_weights(m, mean=0.0, std=0.01):
- classname = m.__class__.__name__
- if classname.find("Conv") != -1:
- m.weight.data.norm... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/infer_pack/commons.py |
Add docstrings to existing functions | import torch
from torch.types import Number
@torch.no_grad()
def amp_to_db(
x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40
) -> torch.Tensor:
x_db = 20 * torch.log10(x.abs() + eps)
return torch.max(x_db, (x_db.max(-1).values - top_db).unsqueeze(-1))
@torch.no_grad()
def temperature_sigmo... | --- +++ @@ -6,12 +6,38 @@ def amp_to_db(
x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40
) -> torch.Tensor:
+ """
+ Convert the input tensor from amplitude to decibel scale.
+
+ Arguments:
+ x {[torch.Tensor]} -- [Input tensor.]
+
+ Keyword Arguments:
+ eps {[float]} -- [S... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/tools/torchgate/utils.py |
Generate docstrings for this script | import copy
import math
from typing import Optional
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from infer.lib.infer_pack import commons, modules
from infer.lib.infer_pack.modules import LayerNorm
class Encoder(nn.Module):
def __init__(
self,
hidden_... | --- +++ @@ -1,431 +1,459 @@-import copy
-import math
-from typing import Optional
-
-import numpy as np
-import torch
-from torch import nn
-from torch.nn import functional as F
-
-from infer.lib.infer_pack import commons, modules
-from infer.lib.infer_pack.modules import LayerNorm
-
-
-class Encoder(nn.Module):
- d... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/infer_pack/attentions.py |
Add documentation for all methods | from io import BytesIO
import os
from typing import List, Optional, Tuple
import numpy as np
import torch
from infer.lib import jit
try:
# Fix "Torch not compiled with CUDA enabled"
import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
if torch.xpu.is_available():
... | --- +++ @@ -1,622 +1,670 @@-from io import BytesIO
-import os
-from typing import List, Optional, Tuple
-import numpy as np
-import torch
-
-from infer.lib import jit
-
-try:
- # Fix "Torch not compiled with CUDA enabled"
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/rmvpe.py |
Write docstrings for backend logic | import torch
from infer.lib.rmvpe import STFT
from torch.nn.functional import conv1d, conv2d
from typing import Union, Optional
from .utils import linspace, temperature_sigmoid, amp_to_db
class TorchGate(torch.nn.Module):
@torch.no_grad()
def __init__(
self,
sr: int,
nonstationary: bo... | --- +++ @@ -6,6 +6,28 @@
class TorchGate(torch.nn.Module):
+ """
+ A PyTorch module that applies a spectral gate to an input signal.
+
+ Arguments:
+ sr {int} -- Sample rate of the input signal.
+ nonstationary {bool} -- Whether to use non-stationary or stationary masking (default: {False}).
... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/tools/torchgate/torchgate.py |
Improve documentation using docstrings | class F0Predictor(object):
def compute_f0(self, wav, p_len):
pass
def compute_f0_uv(self, wav, p_len):
pass | --- +++ @@ -1,6 +1,16 @@-class F0Predictor(object):
- def compute_f0(self, wav, p_len):
- pass
-
- def compute_f0_uv(self, wav, p_len):
- pass+class F0Predictor(object):
+ def compute_f0(self, wav, p_len):
+ """
+ input: wav:[signal_length]
+ p_len:int
+ ou... | https://raw.githubusercontent.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/HEAD/infer/lib/infer_pack/modules/F0Predictor/F0Predictor.py |
Add docstrings to improve readability | class DLL:
def __init__(self, val: str = None):
self.val = val
self.nxt = None
self.prev = None
class BrowserHistory:
def __init__(self, homepage: str):
self._head = DLL(homepage)
self._curr = self._head
self._back_count = 0
self._forward_count = 0
... | --- +++ @@ -1,4 +1,9 @@ class DLL:
+ """
+ a doubly linked list that holds the current page,
+ next page, and previous page.
+ Used to enforce order in operations.
+ """
def __init__(self, val: str = None):
self.val = val
@@ -7,14 +12,37 @@
class BrowserHistory:
+ """
+ This cla... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/BrowserHistory/backend.py |
Add inline docstrings for readability | from __future__ import print_function
import sys
lines = [] # contains the lines of the file.
tokens = [] # contains all tokens of the source code.
# register eax, ebx,..., ecx
eax = 1
ebx = 0
ecx = 0
edx = 0
# status register
zeroFlag = False
# stack data structure
# push --> append
# pop --> pop
stack = []
# ... | --- +++ @@ -49,6 +49,9 @@
def loadFile(fileName):
+ """
+ loadFile: This function loads the file and reads its lines.
+ """
global lines
fo = open(fileName)
for line in fo:
@@ -57,6 +60,10 @@
def scanner(string):
+ """
+ scanner: This function builds the tokens by the content of th... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Assembler/assembler.py |
Add return value explanations in docstrings |
import random
def get_user_choice():
choice = input("Enter your choice (rock, paper, scissors): ").lower()
if choice in ["rock", "paper", "scissors"]:
return choice
else:
print("Invalid choice! Please enter rock, paper, or scissors.")
return get_user_choice()
def get_computer_ch... | --- +++ @@ -1,8 +1,14 @@+"""
+Triple Round : Rock, Paper, Scissors Game (CLI Version)
+Final round is the Winning Round
+Author: Your Name
+"""
import random
def get_user_choice():
+ """Prompt the user to enter their choice."""
choice = input("Enter your choice (rock, paper, scissors): ").lower()
i... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/BrowserHistory/rock_paper_scissors.py |
Add docstrings to my Python code | # Program make a simple calculator
class Calculator:
def __init__(self):
pass
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multiply(self, num1, num2):
return num1 * num2
def divide(self, num1, num2):
... | --- +++ @@ -6,15 +6,59 @@ pass
def add(self, num1, num2):
+ """
+ This function adds two numbers.
+
+ Examples:
+ >>> add(2, 3)
+ 5
+ >>> add(5, 9)
+ 14
+ >>> add(-1, 2)
+ 1
+ """
return num1 + num2
def subtract(self, n... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Calculator with simple ui.py |
Annotate my code with docstrings | import sqlite3
import json
class AutoComplete:
def __init__(self):
self.conn = sqlite3.connect("autocompleteDB.sqlite3", autocommit=True)
cur = self.conn.cursor()
res = cur.execute("SELECT name FROM sqlite_master WHERE name='WordMap'")
tables_exist = res.fetchone()
if not... | --- +++ @@ -3,8 +3,43 @@
class AutoComplete:
+ """
+ It works by building a `WordMap` that stores words to word-follower-count
+ ----------------------------
+ e.g. To train the following statement:
+
+ It is not enough to just know how tools work and what they worth,
+ we have got to learn how to... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/AutoComplete_App/backend.py |
Create structured documentation for my script | from queue import PriorityQueue
from typing import List, Tuple, Optional, Set
class PuzzleState:
def __init__(
self,
board: List[List[int]],
goal: List[List[int]],
moves: int = 0,
previous: Optional["PuzzleState"] = None,
) -> None:
self.board = board # Curren... | --- +++ @@ -3,6 +3,7 @@
class PuzzleState:
+ """Represents a state in 8-puzzle solving with A* algorithm."""
def __init__(
self,
@@ -17,12 +18,15 @@ self.previous = previous # Previous state in solution path
def __lt__(self, other: "PuzzleState") -> bool:
+ """For PriorityQ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/8_puzzle.py |
Add docstrings that explain inputs and outputs | import os
import random
from functools import namedtuple
"""
Target: BlackJack 21 simulate
- Role
- Dealer: 1
- Insurance: (When dealer Get A(1) face up)
- When dealer got 21
- lost chips
- When dealer doesn't got 21
- win ... | --- +++ @@ -45,6 +45,11 @@ __slots__ = "suit", "rank", "is_face"
def __init__(self, suit, rank, face=True):
+ """
+ :param suit: pattern in the card
+ :param rank: point in the card
+ :param face: show or cover the face(point & pattern on it)
+ """
self.suit = suit... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/BlackJack_game/blackjack_simulate.py |
Write docstrings for this repository |
import sys
def with_files(files):
try:
# Read each file's contents and store them
file_contents = [contents for contents in [open(file).read() for file in files]]
except OSError as err:
# This executes when there's an error (e.g. FileNotFoundError)
exit(print(f"cat: error read... | --- +++ @@ -1,40 +1,65 @@-
-import sys
-
-
-def with_files(files):
- try:
- # Read each file's contents and store them
- file_contents = [contents for contents in [open(file).read() for file in files]]
- except OSError as err:
- # This executes when there's an error (e.g. FileNotFoundError)
-... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Cat/cat.py |
Write docstrings for backend logic |
# def solution(n: int) -> int:
def solution(n: int = 600851475143) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or passive of cast to int.")
if n <= 0:
raise ValueError("Parameter n must be greater or equal to one.")
i = 2
... | --- +++ @@ -1,7 +1,40 @@+"""
+Problem:
+The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor
+of a given number N?
+
+e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
+"""
# def solution(n: int) -> int:
def solution(n: int = 600851475143) -> int:
+ """Returns ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/A solution to project euler problem 3.py |
Help me write clear docstrings | #!/usr/bin/env python3
# Recommended: Python 3.6+
import math
print("Collatz Conjecture (Revised)\n")
def main():
# Get the input
number = input("Enter a number to calculate: ")
try:
number = float(number)
except ValueError:
print("Error: Could not convert to integer.")
pri... | --- +++ @@ -2,6 +2,35 @@
# Recommended: Python 3.6+
+"""
+Collatz Conjecture - Python
+
+The Collatz conjecture, also known as the
+3x + 1 problem, is a mathematical conjecture
+concerning a certain sequence. This sequence
+operates on any input number in such a way
+that the output will always reach 1.
+
+The Coll... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Collatz-Conjecture.py |
Add docstrings that explain purpose and usage | # uno game #
import random
from typing import List
"""
Generate the UNO deck of 108 cards.
Doctest examples:
>>> deck = buildDeck()
>>> len(deck)
108
>>> sum(1 for c in deck if 'Wild' in c)
8
Return: list of card strings (e.g. 'Red 7', 'Wild Draw Four')
"""
def buildDeck() -> List[str]:
deck: List[... | --- +++ @@ -56,6 +56,11 @@
def drawCards(numCards: int) -> List[str]:
+ """
+ Draw a number of cards from the top of the global `unoDeck`.
+
+ Raises ValueError if the deck runs out of cards.
+ """
cardsDrawn: List[str] = []
for x in range(numCards):
try:
@@ -91,6 +96,14 @@
def ca... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/BoardGame-CLI/uno.py |
Add missing documentation to my Python functions | #!/usr/bin/env python3
from collections import namedtuple
from typing import List
class Scheduling:
def __init__(self, jobs: List[int]) -> None:
self.jobs = jobs
def schedule(self, total_jobs: int, deadline: List[int]) -> List[int]:
self.j = [self.jobs[1]]
self.x = 2
while s... | --- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3
+"""
+Author : Mohit Kumar
+Job Sequencing Problem implemented in python
+"""
from collections import namedtuple
from typing import List
@@ -7,9 +11,23 @@
class Scheduling:
def __init__(self, jobs: List[int]) -> None:
+ """
+ Assign jobs as insta... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Job_scheduling.py |
Can you add docstrings to this Python file? | import json
class JsonParser:
def convert_json_to_python(self, par_json_file):
with open(par_json_file) as json_file:
data_dic = json.load(json_file)
return data_dic
def convert_python_to_json(self, par_data_dic, par_json_file=""):
if par_json_file:
with open(... | --- +++ @@ -2,13 +2,29 @@
class JsonParser:
+ """
+ this class to handle anything related to json file [as implementation of facade pattern]
+ """
def convert_json_to_python(self, par_json_file):
+ """
+ this function to convert any json file format to dictionary
+ args: the jso... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/JsonParser.py |
Add docstrings including usage examples | from tkinter import Tk, Canvas
from PIL.Image import open as openImage
from PIL.ImageTk import PhotoImage
class Background(Canvas):
__background = []
__stop = False
def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed=50):
# Verifica se o parâmetro tk_instance é uma i... | --- +++ @@ -5,6 +5,9 @@
class Background(Canvas):
+ """
+ Classe para gerar um plano de fundo animado
+ """
__background = []
__stop = False
@@ -55,12 +58,25 @@ )
def getBackgroundID(self):
+ """
+ Retorna os id's das imagens de background
+ """
retu... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Flappy Bird - created with tkinter/Background.py |
Add documentation for all methods |
class Node:
def __init__(self, val=None, next=None):
self.data = val
self.next = next
class LinkedList:
def __init__(self):
self.head = self.tail = None
self.length = 0
def insert_front(self, data):
node = Node(data, self.head)
if self.head == None:
... | --- +++ @@ -1,3 +1,12 @@+"""Contains Most of the Singly Linked List functions.\n
+'variable_name' = singly_linked_list.LinkedList() to use this an external module.\n
+'variable_name'.insert_front('element') \t,'variable_name'.insert_back('element'),\n
+'variable_name'.pop_front() are some of its functions.\n
+To print ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/LinkedLists all Types/singly_linked_list.py |
Add docstrings including usage examples | def is_square_free(factors):
for i in factors:
if factors.count(i) > 1:
return False
return True
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
... | --- +++ @@ -1,4 +1,8 @@ def is_square_free(factors):
+ """
+ This functions takes a list of prime factors as input.
+ returns True if the factors are square free.
+ """
for i in factors:
if factors.count(i) > 1:
return False
@@ -6,6 +10,9 @@
def prime_factors(n):
+ """
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/MobiusFunction.py |
Create documentation for each function signature | import json
import random
import time
from enum import Enum
from pathlib import Path
from typing import Callable, List
import requests
from colorama import Fore, Style
DEBUG = False
success_code = 200
request_timeout = 1000
data_path = Path(__file__).parent.parent.parent / "Data"
year = 4800566455
class Source(Enum... | --- +++ @@ -16,17 +16,30 @@
class Source(Enum):
+ """Enum that represents switch between local and web word parsing."""
FROM_FILE = 0 # noqa: WPS115
FROM_INTERNET = 1 # noqa: WPS115
def print_wrong(text: str, print_function: Callable[[str], None]) -> None:
+ """
+ Print styled text(red).... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Industrial_developed_hangman/src/hangman/main.py |
Add docstrings including usage examples |
import numpy as np
def get_array(x: np.ndarray, y: np.ndarray) -> None:
if x.shape == y.shape:
np_pow_array = x**y
print("Array of powers without using np.power: ", np_pow_array)
print("Array of powers using np.power: ", np.power(x, y))
else:
print("Error: Shape of the given a... | --- +++ @@ -1,8 +1,47 @@+"""
+NumPy Array Exponentiation
+
+Check if two arrays have the same shape and compute element-wise powers
+with and without np.power.
+
+Example usage:
+>>> import numpy as np
+>>> x = np.array([1, 2])
+>>> y = np.array([3, 4])
+>>> get_array(x, y) # doctest: +ELLIPSIS
+Array of powers withou... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/NumPy Array Exponentiation.py |
Turn comments into proper docstrings |
class Node:
def __init__(self, val=None, next=None, prev=None):
self.data = val
self.next = next
self.prev = prev
class DoublyLinkedList:
def __init__(self):
self.head = self.tail = None
self.length = 0
def insert_front(self, data):
node = Node(data, self... | --- +++ @@ -1,250 +1,261 @@-
-
-class Node:
- def __init__(self, val=None, next=None, prev=None):
- self.data = val
- self.next = next
- self.prev = prev
-
-
-class DoublyLinkedList:
- def __init__(self):
- self.head = self.tail = None
- self.length = 0
-
- def insert_front(s... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/LinkedLists all Types/doubly_linked_list.py |
Document this module using docstrings | import tkinter as tk
from tkinter import messagebox, simpledialog
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import pyperclip
import json
from random import choice, randint, shuffle
# ---------------------------- CONSTANTS ------------------------------- #
FONT_NAME = "Helvetica"
# IMP: this is no... | --- +++ @@ -14,6 +14,7 @@
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def generate_password():
+ """generates a random strong password and copies it to clipboard."""
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Password Manager Using Tkinter/main.py |
Improve my code by adding docstrings | # author: slayking1965 (refactored for Python 3.13.7 with typing & doctests)
import random
import time
from typing import Dict
CHOICES: Dict[str, str] = {"s": "Snake", "w": "Water", "g": "Gun"}
def determine_winner(user: str, computer: str) -> str:
if user == computer:
return "draw"
if user == "s... | --- +++ @@ -1,5 +1,31 @@ # author: slayking1965 (refactored for Python 3.13.7 with typing & doctests)
+"""
+Snake-Water-Gun Game.
+
+Rules:
+- Snake vs Water → Snake drinks water → Snake (computer) wins
+- Gun vs Water → Gun sinks in water → Water (user) wins
+- Snake vs Gun → Gun kills snake → Gun wins
+- Same choic... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Sanke-water-gun game.py |
Generate missing documentation strings | import sqlite3
import json
class SearchEngine:
def __init__(self):
self.conn = sqlite3.connect("searchengine.sqlite3", autocommit=True)
cur = self.conn.cursor()
res = cur.execute("SELECT name FROM sqlite_master WHERE name='IdToDoc'")
tables_exist = res.fetchone()
if not t... | --- +++ @@ -3,8 +3,23 @@
class SearchEngine:
+ """
+ It works by building a reverse index store that maps
+ words to an id. To find the document(s) that contain
+ a certain search term, we then take an intersection
+ of the ids
+ """
def __init__(self):
+ """
+ Returns - None
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Search_Engine/backend.py |
Write proper docstrings for these functions | import sqlite3
import json
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
class QuestionAnswerVirtualAssistant:
def __init__(self):
self.conn = sqlite3.connect("virtualassistant.sqlite3", autocommit=True)
cur = self.conn.cursor()
res = cur.execute("SELECT ... | --- +++ @@ -5,8 +5,26 @@
class QuestionAnswerVirtualAssistant:
+ """
+ Used for automatic question-answering
+
+ It works by building a reverse index store that maps
+ words to an id. To find the indexed questions that contain
+ a certain the words in the user question, we then take an
+ intersect... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/QuestionAnswerVirtualAssistant/backend.py |
Generate NumPy-style docstrings |
import random
from typing import List, Tuple
def get_players(n: int) -> List[str]:
return [input("Enter name of player: ") for _ in range(n)]
def play_turn(player: str) -> int:
target = random.randint(1, 100)
print(f"\n{player}, it's your turn!")
attempts = 0
while True:
guess = int(inp... | --- +++ @@ -1,13 +1,68 @@+"""
+Random Number Guessing Game
+---------------------------
+This is a simple multiplayer game where each player tries to guess a number
+chosen randomly by the computer between 1 and 100. After each guess, the game
+provides feedback whether the guess is higher or lower than the target numb... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/RandomNumberGame.py |
Add docstrings to incomplete code | from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import Scoreboard
from wall import Wall
import colors
# --- CONSTANTS ---
MOVE_DELAY_MS = 100 # Game speed in milliseconds
# --- GAME STATE ---
game_state = "start" # Possible states: "start", "playing", "paused", "game_... | --- +++ @@ -1,184 +1,195 @@-from turtle import Screen, Turtle
-from snake import Snake
-from food import Food
-from scoreboard import Scoreboard
-from wall import Wall
-import colors
-
-# --- CONSTANTS ---
-MOVE_DELAY_MS = 100 # Game speed in milliseconds
-
-# --- GAME STATE ---
-game_state = "start" # Possible state... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Snake Game Using Turtle/main.py |
Generate missing documentation strings |
from turtle import Turtle, Screen
import colors
class Wall:
def __init__(self):
self.screen = Screen()
self.create_wall()
def create_wall(self):
width = self.screen.window_width()
height = self.screen.window_height()
# Calculate coordinates for the border based on scr... | --- +++ @@ -1,42 +1,46 @@-
-from turtle import Turtle, Screen
-import colors
-
-class Wall:
- def __init__(self):
- self.screen = Screen()
- self.create_wall()
-
- def create_wall(self):
- width = self.screen.window_width()
- height = self.screen.window_height()
-
- # Calculate ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Snake Game Using Turtle/wall.py |
Document this script properly | from turtle import Turtle
import colors
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP, DOWN, LEFT, RIGHT = 90, 270, 180, 0
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
def create_snake(self):
for... | --- +++ @@ -1,58 +1,73 @@-from turtle import Turtle
-import colors
-
-STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
-MOVE_DISTANCE = 20
-UP, DOWN, LEFT, RIGHT = 90, 270, 180, 0
-
-class Snake:
- def __init__(self):
- self.segments = []
- self.create_snake()
- self.head = self.segments[0]
-
-... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Snake Game Using Turtle/snake.py |
Write docstrings for algorithm functions |
from turtle import Turtle
import random
import colors
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.shapesize(stretch_len=0.7, stretch_wid=0.7)
self.color(colors.FOOD_COLOR)
self.speed("fastest")
def refresh(s... | --- +++ @@ -1,20 +1,27 @@-
-from turtle import Turtle
-import random
-import colors
-
-class Food(Turtle):
- def __init__(self):
- super().__init__()
- self.shape("circle")
- self.penup()
- self.shapesize(stretch_len=0.7, stretch_wid=0.7)
- self.color(colors.FOOD_COLOR)
- se... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Snake Game Using Turtle/food.py |
Write docstrings that follow conventions | from turtle import Turtle, Screen
import colors
# Constants for styling and alignment
ALIGNMENT = "left"
SCORE_FONT = ("Lucida Sans", 20, "bold")
MESSAGE_FONT = ("Courier", 40, "bold")
INSTRUCTION_FONT = ("Lucida Sans", 16, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
... | --- +++ @@ -1,67 +1,80 @@-from turtle import Turtle, Screen
-import colors
-
-# Constants for styling and alignment
-ALIGNMENT = "left"
-SCORE_FONT = ("Lucida Sans", 20, "bold")
-MESSAGE_FONT = ("Courier", 40, "bold")
-INSTRUCTION_FONT = ("Lucida Sans", 16, "normal")
-
-class Scoreboard(Turtle):
- def __init__(self)... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Snake Game Using Turtle/scoreboard.py |
Document functions with detailed explanations | import tkinter as tk
from tkinter.font import Font
from tkinter import messagebox
from tkinter import filedialog
from ThirdAI import NeuralDBClient as Ndb
class ThirdAIApp:
def __init__(self, root):
# Initialize the main window
self.root = root
self.root.geometry("600x500")
self.r... | --- +++ @@ -6,8 +6,17 @@
class ThirdAIApp:
+ """
+ A GUI application for using the ThirdAI neural database client to train and query data.
+ """
def __init__(self, root):
+ """
+ Initialize the user interface window.
+
+ Args:
+ root (tk.Tk): The main Tkinter window.
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/ThirdAI/Terms and Conditions/TkinterUI.py |
Write documentation strings for class attributes |
import numpy as np
import random
from time import sleep
from typing import List, Tuple
def create_board() -> np.ndarray:
return np.zeros((3, 3), dtype=int)
def possibilities(board: np.ndarray) -> List[Tuple[int, int]]:
return [(i, j) for i in range(3) for j in range(3) if board[i, j] == 0]
def random_pla... | --- +++ @@ -1,3 +1,26 @@+"""
+Tic-Tac-Toe Game using NumPy and random moves.
+
+Two players (1 and 2) randomly take turns until one wins or board is full.
+
+Doctests:
+
+>>> b = create_board()
+>>> all(b.flatten() == 0)
+True
+>>> len(possibilities(b))
+9
+>>> row_win(np.array([[1,1,1],[0,0,0],[0,0,0]]), 1)
+True
+>>>... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Tic-Tac-Toe Games/tic-tac-toe4.py |
Add docstrings including usage examples |
import random
from typing import List, Optional, Tuple
def introduction() -> None:
print("Welcome to Tic Tac Toe!")
print("Player is X, Computer is O.")
print("Board positions 1-9 (bottom-left to top-right).")
def draw_board(board: List[str]) -> None:
print(" | |")
print(f" {board[7]} | ... | --- +++ @@ -1,15 +1,34 @@+"""
+Tic-Tac-Toe Game with Full Type Hints and Doctests.
+
+Two-player game where Player and Computer take turns.
+Player chooses X or O and Computer takes the opposite.
+
+Doctests examples:
+
+>>> is_winner([' ', 'X','X','X',' ',' ',' ',' ',' ',' '], 'X')
+True
+>>> is_space_free([' ', 'X','... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Tic-Tac-Toe Games/tic-tac-toe5.py |
Add docstrings to incomplete code |
from typing import List, Optional, Tuple
import customtkinter as ctk
from tkinter import messagebox
Board = List[List[str]]
def check_winner(board: Board, player: str) -> bool:
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(
board[j][i] == player for j in range(3)
... | --- +++ @@ -1,3 +1,15 @@+"""
+Tic-Tac-Toe with AI (Minimax) using CustomTkinter.
+
+Player = "X", AI = "O". Click a button to play.
+
+>>> check_winner([['X','X','X'],[' ',' ',' '],[' ',' ',' ']], 'X')
+True
+>>> check_winner([['X','O','X'],['O','O','O'],['X',' ',' ']], 'O')
+True
+>>> check_winner([['X','O','X'],['O',... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Tic-Tac-Toe Games/tic-tac-toe3.py |
Add docstrings to existing functions |
import os
import time
from typing import List
# Global Variables
board: List[str] = [" "] * 10 # 1-based indexing
player: int = 1
Win: int = 1
Draw: int = -1
Running: int = 0
Game: int = Running
def draw_board() -> None:
print(f" {board[1]} | {board[2]} | {board[3]}")
print("___|___|___")
print(f" {bo... | --- +++ @@ -1,3 +1,18 @@+"""
+Tic-Tac-Toe Console Game
+
+Two players (X and O) take turns to mark a 3x3 grid until one wins
+or the game ends in a draw.
+
+Doctest Examples:
+
+>>> test_board = [" "] * 10
+>>> check_position(test_board, 1)
+True
+>>> test_board[1] = "X"
+>>> check_position(test_board, 1)
+False
+"""
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Tic-Tac-Toe Games/tic-tac-toe2.py |
Add docstrings for internal functions |
from typing import List, Dict
def print_tic_tac_toe(values: List[str]) -> None:
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print("\t_____|_____|_____")
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[... | --- +++ @@ -1,8 +1,26 @@+"""
+Tic-Tac-Toe Series Game
+
+Two players can play multiple rounds of Tic-Tac-Toe.
+Keeps score across rounds until players quit.
+
+Doctest examples:
+
+>>> check_win({"X": [1, 2, 3], "O": []}, "X")
+True
+>>> check_win({"X": [1, 2], "O": []}, "X")
+False
+>>> check_draw({"X": [1, 2, 3], "O"... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Tic-Tac-Toe Games/tic-tac-toe6.py |
Add professional docstrings to my codebase |
import tkinter as tk
from tkinter import messagebox
def clock_diff(t1: str, t2: str) -> str:
h1, m1, s1 = int(t1[0:2]), int(t1[3:5]), int(t1[6:8])
h2, m2, s2 = int(t2[0:2]), int(t2[3:5]), int(t2[6:8])
sec1 = h1 * 3600 + m1 * 60 + s1
sec2 = h2 * 3600 + m2 * 60 + s2
diff = sec2 - sec1
if diff <... | --- +++ @@ -1,9 +1,24 @@+"""
+Tkinter Clock Difference Calculator.
+
+Compute difference between two times (HH:MM:SS) with midnight wrap-around.
+
+Doctests:
+
+>>> clock_diff("12:00:00", "14:30:15")
+'02:30:15'
+>>> clock_diff("23:50:00", "00:15:30")
+'00:25:30'
+>>> clock_diff("00:00:00", "00:00:00")
+'00:00:00'
+"""... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Timetable_Operations.py |
Add docstrings for internal functions |
from typing import List
Board = List[List[str]]
def print_board(board: Board) -> None:
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board: Board, player: str) -> bool:
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(
... | --- +++ @@ -1,3 +1,17 @@+"""
+Text-based Tic-Tac-Toe (2 players).
+
+>>> check_winner([['X','X','X'],[' ',' ',' '],[' ',' ',' ']], 'X')
+True
+>>> check_winner([['X','O','X'],['O','O','O'],['X',' ',' ']], 'O')
+True
+>>> check_winner([['X','O','X'],['O','X','O'],['O','X','O']], 'X')
+False
+>>> is_full([['X','O','X'],[... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Tic-Tac-Toe Games/tic-tac-toe1.py |
Generate helpful docstrings for debugging |
# function to print triplets with 0 sum
def find_Triplets_with_zero_sum(arr, num):
# bool variable to check if triplet found or not
found = False
# sort array elements
arr.sort()
# Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and bre... | --- +++ @@ -1,7 +1,21 @@+"""
+Author : Mohit Kumar
+
+Python program to find triplets in a given array whose sum is zero
+"""
# function to print triplets with 0 sum
def find_Triplets_with_zero_sum(arr, num):
+ """find triplets in a given array whose sum is zero
+
+ Parameteres :
+ arr : input arra... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Triplets with zero sum/find_Triplets_with_zero_sum.py |
Create docstrings for each class method | from speakListen import hear
from speakListen import speak
""" 1. speakListen.speak(text)
2. speakListen.greet()
3. speakListen.hear()
"""
import wikipedia
import webbrowser
def google_search():
google_search_link = "https://www.google.co.in/search?q="
google_search = "What do you want me to search ... | --- +++ @@ -1,68 +1,70 @@-from speakListen import hear
-from speakListen import speak
-
-
-""" 1. speakListen.speak(text)
- 2. speakListen.greet()
- 3. speakListen.hear()
-"""
-import wikipedia
-import webbrowser
-
-
-def google_search():
- google_search_link = "https://www.google.co.in/search?q="
- google_... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/VoiceAssistant/Project_Basic_struct/websiteWork.py |
Write documentation strings for class attributes | import time
from colorama import Fore
import speech_recognition as sr
import pyttsx3
import datetime
from rich.progress import Progress
python = pyttsx3.init("sapi5") # name of the engine is set as Python
voices = python.getProperty("voices")
# print(voices)
python.setProperty("voice", voices[1].id)
python.setProper... | --- +++ @@ -1,151 +1,182 @@-import time
-from colorama import Fore
-import speech_recognition as sr
-import pyttsx3
-import datetime
-from rich.progress import Progress
-
-
-python = pyttsx3.init("sapi5") # name of the engine is set as Python
-voices = python.getProperty("voices")
-# print(voices)
-python.setProperty(... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/VoiceAssistant/Project_Basic_struct/speakListen.py |
Generate helpful docstrings for debugging | from speakListen import hear
from speakListen import speak
import docx
import fitz
import time
from rich.console import Console # pip3 install Rich
from rich.table import Table
from colorama import Fore
def ms_word():
# TODO : Take location input from the user
try:
speak("Enter the document's locatio... | --- +++ @@ -1,306 +1,347 @@-from speakListen import hear
-from speakListen import speak
-import docx
-import fitz
-import time
-from rich.console import Console # pip3 install Rich
-from rich.table import Table
-from colorama import Fore
-
-
-def ms_word():
- # TODO : Take location input from the user
- try:
- ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/VoiceAssistant/Project_Basic_struct/textRead.py |
Document all public functions with docstrings |
class XORCipher(object):
def __init__(self, key=0):
# private field
self.__key = key
def encrypt(self, content, key):
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key can be any size
... | --- +++ @@ -1,12 +1,40 @@+"""
+author: Christian Bender
+date: 21.12.2017
+class: XORCipher
+
+This class implements the XOR-cipher algorithm and provides
+some useful methods for encrypting and decrypting strings and
+files.
+
+Overview about methods
+
+- encrypt : list of char
+- decrypt : list of char
+- encrypt_str... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/XORcipher/XOR_cipher.py |
Auto-generate documentation strings for this file |
from __future__ import print_function
import wikipedia as wk
from bs4 import BeautifulSoup
def wiki():
word = input("Wikipedia Search : ")
results = wk.search(word)
for i in enumerate(results):
print(i)
try:
key = int(input("Enter the number : "))
except AssertionError:
... | --- +++ @@ -1,3 +1,8 @@+"""
+Created on Sat Jul 15 01:41:31 2017
+
+@author: Albert
+"""
from __future__ import print_function
@@ -6,6 +11,9 @@
def wiki():
+ """
+ Search Anything in wikipedia
+ """
word = input("Wikipedia Search : ")
results = wk.search(word)
@@ -43,6 +51,10 @@
def ra... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/WikipediaModule.py |
Write beginner-friendly docstrings | # This is like making a package.lock file for npm package.
# Yes, I should be making it.
__author__ = "Nitkarsh Chourasia"
__version__ = "0.0.0" # SemVer # Understand more about it
__license__ = "MIT" # Understand more about it
# Want to make it open source but how to do it?
# Program to make a simple calculator
# Wi... | --- +++ @@ -32,45 +32,102 @@ self.take_inputs()
def add(self):
+ """summary: Get the sum of numbers
+
+ Returns:
+ _type_: _description_
+ """
return self.num1 + self.num2
def sub(self):
+ """_summary_: Get the difference of numbers
+
+ Return... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/advanced_calculator.py |
Document my Python code with docstrings | from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import backend
backend.connect_database()
employee_data = None
# Page Constants (for reference)
HOME_PAGE = 0
ADMIN_PAGE = 1
EMPLOYEE_PAGE = 2
ADMIN_MENU_PAGE = 3
ADD_EMPLOYEE_PAGE = 4
UPDATE_EMPLOYEE_PAGE1 = 5
UPDATE_EMPLOYEE_PAGE2 = 6
EMPLOYEE_LIST_PAGE = 7
ADMI... | --- +++ @@ -35,6 +35,7 @@
def create_styled_frame(parent, min_size=None, style=""):
+ """Create a styled QFrame with optional minimum size and custom style."""
frame = QtWidgets.QFrame(parent)
frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
frame.setFrameShadow(QtWidgets.QFrame.Raised)
@@ -47,6 ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/bank_managment_system/QTFrontend.py |
Write clean docstrings for readability | # batch_file_rename.py
# Created: 6th August 2012
# just checking
__author__ = "Craig Richards"
__version__ = "1.0"
import argparse
import os
def batch_rename(work_dir, old_ext, new_ext):
# files = os.listdir(work_dir)
for filename in os.listdir(work_dir):
# Get the file extension
split_fil... | --- +++ @@ -1,71 +1,82 @@-# batch_file_rename.py
-# Created: 6th August 2012
-
-
-# just checking
-__author__ = "Craig Richards"
-__version__ = "1.0"
-
-import argparse
-import os
-
-
-def batch_rename(work_dir, old_ext, new_ext):
- # files = os.listdir(work_dir)
- for filename in os.listdir(work_dir):
- #... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/batch_file_rename.py |
Document functions with clear intent | class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
# self.level = None
def __str__(self):
return str(self.info)
def __del__(self):
del self
class BinarySearchTree:
def __init__(self):
self.root = None
... | --- +++ @@ -1,6 +1,8 @@ class Node:
+ """Class for node of a tree"""
def __init__(self, info):
+ """Initialising a node"""
self.info = info
self.left = None
self.right = None
@@ -14,11 +16,14 @@
class BinarySearchTree:
+ """Class for BST"""
def __init__(self):
+... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/binary_search_tree.py |
Add docstrings for production code |
import sys
## Imported math library to run sin(), cos(), tan() and other such functions in the calculator
from fileinfo import raw_input
def calc(term):
# This part is for reading and converting function expressions.
term = term.lower()
# This part is for reading and converting arithmetic terms.
... | --- +++ @@ -1,3 +1,27 @@+"""
+Written by : Shreyas Daniel - github.com/shreydan
+Description : Uses Pythons eval() function
+ as a way to implement calculator.
+
+Functions available are:
+--------------------------------------------
+ + : addition
+ - : sub... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/calculator.py |
Auto-generate documentation strings for this file |
# Import
# Cartesian Product of Two Lists
def cartesian_product(list1, list2):
for _i in list1:
for _j in list2:
print((_i, _j), end=" ")
# Main
if __name__ == "__main__":
list1 = input().split()
list2 = input().split()
# Convert to ints
list1 = [int(i) for i in list1]
... | --- +++ @@ -1,9 +1,11 @@+"""Cartesian Product of Two Lists."""
# Import
# Cartesian Product of Two Lists
def cartesian_product(list1, list2):
+ """Cartesian Product of Two Lists."""
for _i in list1:
for _j in list2:
print((_i, _j), end=" ")
@@ -18,4 +20,4 @@ list1 = [int(i) fo... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/cartesian_product.py |
Create simple docstrings for beginners | def dual_pivot_quicksort(arr, low, high):
if low < high:
# Partition the array and get the two pivot indices
lp, rp = partition(arr, low, high)
# Recursively sort elements less than pivot1
dual_pivot_quicksort(arr, low, lp - 1)
# Recursively sort elements between pivot1 and p... | --- +++ @@ -1,4 +1,21 @@ def dual_pivot_quicksort(arr, low, high):
+ """
+ Performs Dual-Pivot QuickSort on the input array.
+
+ Dual-Pivot QuickSort is an optimized version of QuickSort that uses
+ two pivot elements to partition the array into three segments in each
+ recursive call. This improves perf... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/Sorting Algorithms/dual_pivot_quicksort.py |
Document this module using docstrings | # Fibonacci tool
# This script only works with Python3!
import time
def getFibonacciIterative(n: int) -> int:
a = 0
b = 1
for _ in range(n):
a, b = b, a + b
return a
def getFibonacciRecursive(n: int) -> int:
a = 0
b = 1
def step(n: int) -> int:
nonlocal a, b
... | --- +++ @@ -5,6 +5,9 @@
def getFibonacciIterative(n: int) -> int:
+ """
+ Calculate the fibonacci number at position n iteratively
+ """
a = 0
b = 1
@@ -16,6 +19,9 @@
def getFibonacciRecursive(n: int) -> int:
+ """
+ Calculate the fibonacci number at position n recursively
+ """
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/fibonacci.py |
Add professional docstrings to my codebase |
import random
# using pygame python GUI
import pygame
# Define Four Colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
# Setting the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
"""
This is a simple B... | --- +++ @@ -1,3 +1,19 @@+"""
+ Pygame base template for opening a window
+
+ Sample Python/Pygame Programs
+ Simpson College Computer Science
+ http://programarcadegames.com/
+ http://simpson.edu/computer-science/
+
+ Explanation video: http://youtu.be/vRB_983kUMc
+
+-------------------------------------------------
+
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/brickout-game/brickout-game.py |
Generate docstrings for each module |
# ALL the combinations of 4 digit combo
def four_digit_combinations():
numbers = []
for code in range(10000):
code = str(code).zfill(4)
print(code)
numbers.append(code)
# Same as above but more pythonic
def one_line_combinations():
numbers = [str(i).zfill(4) for i in range(10000)... | --- +++ @@ -1,15 +1,18 @@-
-
-# ALL the combinations of 4 digit combo
-def four_digit_combinations():
- numbers = []
- for code in range(10000):
- code = str(code).zfill(4)
- print(code)
- numbers.append(code)
-
-
-# Same as above but more pythonic
-def one_line_combinations():
- numbers =... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/four_digit_num_combination.py |
Generate consistent docstrings | import random
class Die:
def __init__(self, sides=6):
self.sides = 6 # Internal default
self.set_sides(sides)
def set_sides(self, num_sides):
if isinstance(num_sides, int) and num_sides >= 4:
if num_sides != self.sides:
print(f"Changing sides from {self.si... | --- +++ @@ -1,12 +1,23 @@ import random
class Die:
+ """
+ A class used to represent a multi-sided die.
+
+ Attributes:
+ sides (int): The number of sides on the die (default is 6).
+ """
def __init__(self, sides=6):
+ """Initializes the die. Defaults to 6 sides if no value is pr... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/dice.py |
Add docstrings to existing functions | from PIL import Image
import os
class image2pdf:
def __init__(self):
self.validFormats = (".jpg", ".jpeg", ".png", ".JPG", ".PNG")
self.pictures = []
self.directory = ""
self.isMergePDF = True
def getUserDir(self):
msg = "\n1. Current directory\n2. Custom directory\n... | --- +++ @@ -11,6 +11,7 @@ self.isMergePDF = True
def getUserDir(self):
+ """Allow user to choose image directory"""
msg = "\n1. Current directory\n2. Custom directory\nEnter a number: "
user_option = int(input(msg))
@@ -40,6 +41,7 @@ return pictures
def selectPic... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/image2pdf/image2pdf.py |
Generate docstrings with examples | # insertion sort
list = [] # declaring list
def input_list():
# taking length and then values of list as input from user
n = int(input("Enter number of elements in the list: ")) # taking value from user
for i in range(n):
temp = int(input("Enter element " + str(i + 1) + ": "))
list.appe... | --- +++ @@ -12,6 +12,16 @@
def insertion_sort(list, n):
+ """
+ sort list in assending order
+
+ INPUT:
+ list=list of values to be sorted
+ n=size of list that contains values to be sorted
+
+ OUTPUT:
+ list of sorted values in assending order
+ """
for i in range(0, n):
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/insertion_sort.py |
Generate docstrings with examples | # -*- coding: utf-8 -*-
import math
import random
class Vector(object):
def __init__(self, components):
self.__components = components
def set(self, components):
if len(components) > 0:
self.__components = components
else:
raise Exception("please give any vec... | --- +++ @@ -1,21 +1,72 @@ # -*- coding: utf-8 -*-
+"""
+Created on Mon Feb 26 14:29:11 2018
+
+@author: Christian Bender
+@license: MIT-license
+
+This module contains some useful classes and functions for dealing
+with linear algebra in python.
+
+Overview:
+
+- class Vector
+- function zeroVector(dimension)
+- functi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/linear-algebra-python/src/lib.py |
Add docstrings that explain inputs and outputs | # Required imports to run this file
import matplotlib.pyplot as plt
import numpy as np
# weighted matrix
def weighted_matrix(point: np.mat, training_data_x: np.mat, bandwidth: float) -> np.mat:
# m is the number of training samples
m, n = np.shape(training_data_x)
# Initializing weights as identity matrix... | --- +++ @@ -1,93 +1,117 @@-# Required imports to run this file
-import matplotlib.pyplot as plt
-import numpy as np
-
-
-# weighted matrix
-def weighted_matrix(point: np.mat, training_data_x: np.mat, bandwidth: float) -> np.mat:
- # m is the number of training samples
- m, n = np.shape(training_data_x)
- # Ini... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/local_weighted_learning/local_weighted_learning.py |
Document all public functions with docstrings | from random import *
from turtle import *
from freegames import path
car = path("car.gif")
tiles = list(range(32)) * 2
state = {"mark": None}
hide = [True] * 64
def square(x, y):
up()
goto(x, y)
down()
color("black", "white")
begin_fill()
for count in range(4):
forward(50)
lef... | --- +++ @@ -9,6 +9,7 @@
def square(x, y):
+ "Draw white square with black outline at (x, y)."
up()
goto(x, y)
down()
@@ -21,14 +22,17 @@
def index(x, y):
+ "Convert (x, y) coordinates to tiles index."
return int((x + 200) // 50 + ((y + 200) // 50) * 8)
def xy(count):
+ "Convert... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/memorygame.py |
Write Python docstrings for this snippet | def main():
try:
lines = int(input("Enter number of lines: "))
if lines < 0:
raise ValueError("Number of lines must be non-negative")
result = pattern(lines)
print(result)
except ValueError as e:
if "invalid literal" in str(e):
print(f"Error: Pleas... | --- +++ @@ -1,4 +1,5 @@ def main():
+ """Main function that gets user input and calls the pattern generation function."""
try:
lines = int(input("Enter number of lines: "))
if lines < 0:
@@ -15,6 +16,35 @@
def pattern(lines: int) -> str:
+ """
+ Generate a pattern of '@' and '$' char... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/new_pattern.py |
Add standardized docstrings across the file | # news_oversimplifier.py
# Python command-line tool that fetches recent news articles based on a search query using NewsAPI and summarizes the article content using extractive summarization. You can also save the summaries to a text file.
# (requires API key in .env file)
import requests
import os
import sys
from dot... | --- +++ @@ -71,10 +71,29 @@
def word_count(text): # pytest in test file
+ """
+ Returns the number of words in the given text.
+
+ args:
+ text (str): Input string to count words from.
+
+ returns:
+ int: Number of words in the string.
+ """
return len(text.split())
def summa... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/news_oversimplifier.py |
Annotate my code with docstrings | from tkinter import *
# To install hupper, use: "pip install hupper"
# On CMD, or Terminal.
import hupper
# Python program to create a simple GUI
# calculator using Tkinter
# Importing everything from tkinter module
# globally declare the expression variable
# Global variables are those variables that can be acces... | --- +++ @@ -17,12 +17,18 @@
def start_reloader():
+ """Adding a live server for tkinter test GUI, which reloads the GUI when the code is changed."""
reloader = hupper.start_reloader("p1.main")
# Function to update expression
# In the text entry box
def press(num):
+ """Function to update expressio... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py |
Create Google-style docstrings for my code | class OneRepMaxCalculator:
def __init__(self):
self.weight_lifted = 0
self.reps_performed = 0
def get_user_input(self):
self.weight_lifted = int(input("Enter the weight you lifted (in kg): "))
self.reps_performed = int(input("Enter the number of reps you performed: "))
def... | --- +++ @@ -1,26 +1,45 @@ class OneRepMaxCalculator:
+ """
+ A class to calculate the one-repetition maximum (1RM) for a weightlifting exercise.
+ """
def __init__(self):
+ """
+ Initializes the OneRepMaxCalculator with default values.
+ """
self.weight_lifted = 0
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator.py |
Write reusable docstrings | #! /usr/bin/env python
#
# GUI module generated by PAGE version 4.10
# In conjunction with Tcl version 8.6
# Jan 30, 2018 02:49:06 PM
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
import tkinter.ttk as ttk
py3 = 1
import ... | --- +++ @@ -22,6 +22,7 @@
def vp_start_gui():
+ """Starting point when module is the main routine."""
global val, w, root
root = Tk()
root.resizable(False, False)
@@ -34,6 +35,7 @@
def create_Notepads_managment(root, *args, **kwargs):
+ """Starting point when module is imported by another p... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/nodepad/notepad.py |
Turn comments into proper docstrings | # Author: Slayking1965
# Email: kingslayer8509@gmail.com
import random
import string
from typing import List
def guess_password_simulation(password: str) -> str:
chars_list: List[str] = list(string.printable)
guess: List[str] = []
attempts = 0
while guess != list(password):
guess = random.c... | --- +++ @@ -1,6 +1,22 @@ # Author: Slayking1965
# Email: kingslayer8509@gmail.com
+"""
+Brute-force password guessing demonstration.
+
+This script simulates guessing a password using random choices from
+printable characters. It is a conceptual demonstration and is **not
+intended for real-world password cracking**... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/password guessing.py |
Add docstrings to make code maintainable |
import random
import sys
import numpy as np
from matplotlib import use as mpluse
mpluse("TkAgg")
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
usage_doc = "Usage of script: script_nama <size_of_canvas:int>"
choice = [0] * 100 + [1] * 10
random.shuffle(choice)
def create_canva... | --- +++ @@ -1,3 +1,32 @@+"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com)
+
+Requirements:
+ - numpy
+ - random
+ - time
+ - matplotlib
+
+Python:
+ - 3.5
+
+Usage:
+ - $python3 game_o_life <canvas_size:int>
+
+Game-Of-Life Rules:
+
+ 1.
+ Any live cell with fewer than two live neig... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/game_of_life/game_o_life.py |
Add professional docstrings to my codebase | #! /usr/bin/env python
#
# Support module generated by PAGE version 4.10
# In conjunction with Tcl version 8.6
# Jan 29, 2018 03:25:00 PM
import sqlite3
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
py3 = 1
# connect with da... | --- +++ @@ -49,6 +49,9 @@
def create_button(p1):
+ """
+ for creating a new database
+ """
global cursor
sql_command = """
@@ -93,10 +96,18 @@
def clear_button(p1):
+ """
+ This function is for the clear button.
+ This will clear the notice-input field
+ """
w.inputNotice.d... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/notepad/notepad_support.py |
Add docstrings to make code maintainable | #!/usr/bin/env python3
from __future__ import annotations
import argparse
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import re
import sys
SUPPORTED_EXTS = {".jpg", ".jpeg", ".png", ".heic", ".webp", ".tif", ".tiff"}
# EXIF support is optional (w\ Pillow)
try:
from PI... | --- +++ @@ -1,4 +1,20 @@ #!/usr/bin/env python3
+"""
+Author: Ivan Costa Neto
+Date: 13-01-26
+
+Auto-rename photos by timestamp, so you can organize those vacation trip photos!!
+
+Name format: YYYY-MM-DD_HH-MM-SS[_NN].ext
+
+Uses EXIF DateTimeOriginal when available (best for JPEG),
+otherwise falls back to file modi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/photo_timestamp_renamer.py |
Improve my code by adding docstrings | # -*- coding: utf-8 -*-
def pi(maxK=70, prec=1008, disp=1007):
from decimal import Decimal as Dec, getcontext as gc
gc().prec = prec
K, M, L, X, S = 6, 1, 13591409, 1, 13591409
for k in range(1, maxK + 1):
M = Dec((K**3 - (K << 4)) * M / k**3)
L += 545140134
X *= -262537412640... | --- +++ @@ -1,7 +1,51 @@ # -*- coding: utf-8 -*-
+"""
+Created on Thu Oct 5 16:44:23 2017
+
+@author: Christian Bender
+
+This python library contains some useful functions to deal with
+prime numbers and whole numbers.
+
+Overview:
+
+isPrime(number)
+sieveEr(N)
+getPrimeNumbers(N)
+primeFactorization(number)
+greate... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/primelib/primelib.py |
Add structured docstrings to improve clarity |
import random
article = ["the", "a", "one", "some", "any"]
noun = ["boy", "girl", "dog", "town", "car"]
verb = ["drove", "jumped", "ran", "walked", "skipped"]
preposition = ["to", "from", "over", "under", "on"]
def random_int():
return random.randint(0, 4)
def random_sentence():
return (
"{} {} {}... | --- +++ @@ -1,3 +1,9 @@+"""Generates Random Sentences
+Creates a sentence by selecting a word at randowm from each of the lists in
+the following order: 'article', 'nounce', 'verb', 'preposition',
+'article' and 'noun'.
+The second part produce a short story consisting of several of
+these sentences -- Random Note Writ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/random-sentences.py |
Add well-formatted docstrings | import requests
import xlwt
from xlwt import Workbook
BASE_URL = 'https://remoteok.com/api'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
REQUEST_HEADER = {
'User-Agent': USER_AGENT,
'Accept-Language': 'en-US, en;q=0.5',
}
def ge... | --- +++ @@ -10,6 +10,7 @@ }
def get_job_postings():
+ """Fetch job postings from RemoteOK API."""
try:
res = requests.get(BASE_URL, headers=REQUEST_HEADER)
res.raise_for_status()
@@ -20,6 +21,7 @@ return []
def save_jobs_to_excel(jobs, filename='remoteok_jobs.xls'):
+ """Save ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/remoteok_jobs_scraper/remoteok_jobs.py |
Provide clean and structured docstrings |
import random
def get_user_choice():
choice = input("Enter your choice (rock, paper, scissors): ").lower()
if choice in ["rock", "paper", "scissors"]:
return choice
else:
print("Invalid choice! Please enter rock, paper, or scissors.")
return get_user_choice()
def get_computer_ch... | --- +++ @@ -1,8 +1,13 @@+"""
+Rock, Paper, Scissors Game
+Author: DEVANSH-GAJJAR
+"""
import random
def get_user_choice():
+ """Prompt the user to enter their choice."""
choice = input("Enter your choice (rock, paper, scissors): ").lower()
if choice in ["rock", "paper", "scissors"]:
return... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/rock_paper_scissors.py |
Add docstrings including usage examples |
def score(source_data: list, weights: list, *args) -> list:
# getting data
data_lists = []
for item in source_data:
for i, val in enumerate(item):
try:
data_lists[i].append(float(val))
except IndexError:
data_lists.append([])
... | --- +++ @@ -1,6 +1,48 @@+"""
+developed by: markmelnic
+original repo: https://github.com/markmelnic/Scoring-Algorithm
+ pypi: https://pypi.org/project/scalg/
+Analyse data using a range based percentual proximity algorithm
+and calculate the linear maximum likelihood estimation.
+The basic principle is that al... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/scalg.py |
Write reusable docstrings |
def add(x: float, y: float) -> float:
return x + y
def subtract(x: float, y: float) -> float:
return x - y
def multiply(x: float, y: float) -> float:
return x * y
def divide(x: float, y: float) -> float:
return x / y
def calculator() -> None:
print("Select operation.")
print("1.Add\n2.... | --- +++ @@ -1,22 +1,42 @@+"""
+Simple Calculator Module.
+
+Provides basic operations: add, subtract, multiply, divide.
+
+Example usage:
+>>> add(2, 3)
+5
+>>> subtract(10, 4)
+6
+>>> multiply(3, 4)
+12
+>>> divide(8, 2)
+4.0
+"""
def add(x: float, y: float) -> float:
+ """Return the sum of x and y."""
re... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/simple_calculator.py |
Add docstrings following best practices |
def selection_sort(arr: list) -> list:
"""TC : O(n^2)
SC : O(1)"""
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
def bubble_sort(arr: list) -> list:
n = len(arr)
flag = True
... | --- +++ @@ -1,122 +1,169 @@-
-
-def selection_sort(arr: list) -> list:
-
- """TC : O(n^2)
- SC : O(1)"""
-
- n = len(arr)
- for i in range(n):
- for j in range(i + 1, n):
- if arr[i] > arr[j]:
- arr[i], arr[j] = arr[j], arr[i]
- return arr
-
-
-def bubble_sort(arr: list) ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/sorting_algos.py |
Insert docstrings into my code | import os
import argparse
def generate_unique_name(directory: str, name: str) -> str:
base_name, extension = os.path.splitext(name)
index = 1
while os.path.exists(os.path.join(directory, f"{base_name}_{index}{extension}")):
index += 1
return f"{base_name}_{index}{extension}"
def rename_files... | --- +++ @@ -3,6 +3,21 @@
def generate_unique_name(directory: str, name: str) -> str:
+ """
+ Generate a unique name for a file or folder in the specified directory.
+
+ Parameters:
+ ----------
+ directory : str
+ The path to the directory.
+ name : str
+ The name of the file or fold... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/snake_case_renamer_depth_one.py |
Improve documentation using docstrings | #!/usr/bin/env python3
import os
import shutil
import argparse
import time
from datetime import datetime
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".svg"],
"Documents": [".pdf", ".doc", ".docx", ".txt", ".ppt", ".pptx", ".xls", ".xlsx"],
"Videos": [".mp4", ".mkv", ".... | --- +++ @@ -1,4 +1,22 @@ #!/usr/bin/env python3
+"""
+Smart File Organizer
+
+A utility script to organize files in a specified directory into categorized
+subfolders based on file types.
+
+Example categories include: Images, Documents, Videos, Audios, Archives, Scripts, Others.
+
+Usage:
+ python smart_file_organi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/smart_file_organizer.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.