instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings for better understanding
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the ChatJoinRequestHandler class.""" from telegram import Update from telegram._utils.defaultvalue import DEFAULT_TRUE @@ ...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/chatjoinrequesthandler.py
Annotate my code with docstrings
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the ShippingQueryHandler class.""" from telegram import Update from telegram.ext._handlers.basehandler import BaseHandler ...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/shippingqueryhandler.py
Generate docstrings for this script
from __future__ import print_function, division """This file contains class definitions for: Hist: represents a histogram (map from values to integer frequencies). Pmf: represents a probability mass function (map from values to probs). _DictWrapper: private parent class for Hist and Pmf. Cdf: represents a discret...
--- +++ @@ -1,3 +1,9 @@+"""This file contains code for use with "Think Stats" and +"Think Bayes", both by Allen B. Downey, available from greenteapress.com + +Copyright 2014 Allen B. Downey +License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html +""" from __future__ import print_function, division @@ -40,37 +46,7...
https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/HEAD/scipy/thinkstats2.py
Provide docstrings following PEP 257
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np import warnings from keras.layers import merge, Input from keras.layers import Dense, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D, AveragePooling2D from keras.layers import BatchNormalization f...
--- +++ @@ -1,4 +1,12 @@ # -*- coding: utf-8 -*- +'''ResNet50 model for Keras. + +# Reference: + +- [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) + +Adapted from code contributed by BigMoyan. +''' from __future__ import print_function import numpy as np @@ -22,6 +30,15 @@ def ...
https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/HEAD/deep-learning/keras-tutorial/deep_learning_models/resnet50.py
Create simple docstrings for beginners
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np import warnings from keras.models import Model from keras.layers import Flatten, Dense, Input from keras.layers import Convolution2D, MaxPooling2D from keras.preprocessing import image from keras.utils.layer_utils import convert_all_kern...
--- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*- +'''VGG16 model for Keras. + +# Reference: + +- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556) + +''' from __future__ import print_function import numpy as np @@ -22,6 +29,29 @@ def VGG16(include_top=True, weig...
https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/HEAD/deep-learning/keras-tutorial/deep_learning_models/vgg16.py
Write docstrings for utility functions
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the PreCheckoutQueryHandler class.""" import re from re import Pattern @@ -31,6 +32,43 @@ class PreCheckoutQueryHandle...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/precheckoutqueryhandler.py
Create docstrings for each class method
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the PaidMediaPurchased class.""" from telegram import Update from telegram._utils.defaultvalue import DEFAULT_TRUE @@ -26,6...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/paidmediapurchasedhandler.py
Generate consistent documentation across files
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains a class that holds the parameters of a request to the Bot API.""" import json from typing import Any, final @@ -28,6 +29...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/request/_requestdata.py
Generate NumPy-style docstrings
from __future__ import print_function import math import matplotlib import matplotlib.pyplot as pyplot import numpy as np import pandas import warnings # customize some matplotlib attributes #matplotlib.rc('figure', figsize=(4, 3)) #matplotlib.rc('font', size=14.0) #matplotlib.rc('axes', labelsize=22.0, titlesize=...
--- +++ @@ -1,3 +1,9 @@+"""This file contains code for use with "Think Stats", +by Allen B. Downey, available from greenteapress.com + +Copyright 2014 Allen B. Downey +License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html +""" from __future__ import print_function @@ -24,6 +30,13 @@ class _Brewer(object): + ...
https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/HEAD/scipy/thinkplot.py
Add docstrings for production code
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the PollAnswerHandler class.""" from telegram import Update from telegram.ext._handlers.basehandler import BaseHandler @...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/pollanswerhandler.py
Create structured documentation for my script
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the PollHandler class.""" from telegram import Update from telegram.ext._handlers.basehandler import BaseHandler @@ -23,8 ...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/pollhandler.py
Add docstrings following best practices
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the PrefixHandler class.""" import itertools from typing import TYPE_CHECKING, Any, TypeVar @@ -34,6 +35,90 @@ class P...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_handlers/prefixhandler.py
Add docstrings to clarify complex logic
import torch import torch.distributed as dist # ==================== # All-To-All # ==================== def _all_to_all( input_: torch.Tensor, world_size: int, group: dist.ProcessGroup, scatter_dim: int, gather_dim: int, ): input_list = [t.contiguous() for t in torch.tensor_split(input_, worl...
--- +++ @@ -19,6 +19,14 @@ class _AllToAll(torch.autograd.Function): + """All-to-all communication. + + Args: + input_: input matrix + process_group: communication group + scatter_dim: scatter dimension + gather_dim: gather dimension + """ @staticmethod def forward(c...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/acceleration/communications.py
Auto-generate documentation strings for this file
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
--- +++ @@ -16,6 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. +"""This module contains the BasePersistence class.""" from abc import ABC, abstractmethod from typing import Generic, NamedTuple, NoReturn @@ -26,...
https://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/HEAD/src/telegram/ext/_basepersistence.py
Add docstrings to meet PEP guidelines
# Copyright 2024 Vchitect/Latte # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -32,6 +32,10 @@ def crop(clip, i, j, h, w): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W) + """ if len(clip.size()) != 4: raise ValueError("clip should be a 4D tensor") return clip[..., i : i + h, j : j + w] @@ -53,6 +57,18 @@ d...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/datasets/video_transforms.py
Add docstrings that explain inputs and outputs
from collections import OrderedDict, defaultdict from typing import Iterator import numpy as np import torch import torch.distributed as dist from torch.utils.data import Dataset, DistributedSampler from opensora.utils.logger import log_message from opensora.utils.misc import format_numel_str from .aspect import get...
--- +++ @@ -208,6 +208,13 @@ self._cached_num_total_batch = 0 def group_by_bucket(self) -> dict: + """ + Group the dataset samples into buckets. + This method will set `self._cached_bucket_sample_dict` to the bucket sample dict. + + Returns: + dict: a dictionary wit...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/datasets/sampler.py
Add documentation for all methods
import threading from typing import Dict, List, Optional import torch class PinMemoryCache: force_dtype: Optional[torch.dtype] = None min_cache_numel: int = 0 pre_alloc_numels: List[int] = [] def __init__(self): self.cache: Dict[int, torch.Tensor] = {} self.output_to_cache: Dict[int,...
--- +++ @@ -24,6 +24,14 @@ self.cache[id(cache_tensor)] = cache_tensor def get(self, tensor: torch.Tensor) -> torch.Tensor: + """Receive a cpu tensor and return the corresponding pinned tensor. Note that this only manage memory allocation, doesn't copy content. + + Args: + ...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/datasets/pin_memory_cache.py
Improve documentation using docstrings
import math import os import random import re from typing import Any import numpy as np import pandas as pd import requests import torch import torch.distributed as dist import torchvision import torchvision.transforms as transforms from PIL import Image from torchvision.datasets.folder import IMG_EXTENSIONS, pil_load...
--- +++ @@ -209,6 +209,10 @@ verbose=True, crf=23, ): + """ + Args: + x (Tensor): shape [C, T, H, W] + """ assert x.ndim == 4 if not force_video and x.shape[1] == 1: # T = 1: save as image @@ -231,6 +235,10 @@ def center_crop_arr(pil_image, image_size): + """ + Center cr...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/datasets/utils.py
Add docstrings for better understanding
from __future__ import print_function from collections import defaultdict import numpy as np import sys import thinkstats2 def ReadFemPreg(dct_file='2002FemPreg.dct', dat_file='2002FemPreg.dat.gz'): dct = thinkstats2.ReadStataDct(dct_file) df = dct.ReadFixedWidth(dat_file, compression='gzip...
--- +++ @@ -1,3 +1,9 @@+"""This file contains code for use with "Think Stats", +by Allen B. Downey, available from greenteapress.com + +Copyright 2010 Allen B. Downey +License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html +""" from __future__ import print_function @@ -10,6 +16,13 @@ def ReadFemPreg(dct_file='2...
https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/HEAD/scipy/nsfg.py
Document this module using docstrings
class TypeUtil: @classmethod def is_iterable(cls, obj): try: iter(obj) return True except TypeError: return False @classmethod def convert_to_list(cls, obj): if not isinstance(obj, list) and cls.is_iterable(obj): obj = list(obj) ...
--- +++ @@ -2,6 +2,12 @@ @classmethod def is_iterable(cls, obj): + """Determines if obj is iterable. + + Useful when writing functions that can accept multiple types of + input (list, tuple, ndarray, iterator). Pairs well with + convert_to_list. + """ try: ...
https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/HEAD/python-data/type_util.py
Provide clean and structured docstrings
import torch from einops import rearrange from flash_attn import flash_attn_func as flash_attn_func_v2 from liger_kernel.ops.rope import LigerRopeFunction from torch import Tensor from typing import Tuple try: from flash_attn_interface import flash_attn_func as flash_attn_func_v3 SUPPORT_FA3 = True except: ...
--- +++ @@ -66,6 +66,16 @@ def rearrange_tensor(tensor): + """ + Rearranges the last dimension (D) of the input tensor based on the specified mapping: + 2d -> d, 2d+1 -> D/2 + d. + + Args: + tensor (torch.Tensor): Input tensor of shape [B, H, L, D], where D is even. + + Returns: + torch...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/mmdit/math.py
Add docstrings that explain logic
from typing import List, Optional, Union import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from colossalai.device.device_mesh import DeviceMesh from colossalai.shardformer.layer._operation import ( gather_forward_split_backward, reduce_forward, split_forwar...
--- +++ @@ -27,6 +27,19 @@ def shard_channelwise( tensor: torch.Tensor, group_or_device_mesh: Union[ProcessGroup, DeviceMesh] = None ) -> torch.Tensor: + """ + Shard the second dim of the given tensor. + + Args: + tensor (torch.Tensor): The tensor to be sharded. + group_or_device_mesh (Unio...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/vae/tensor_parallel.py
Add return value explanations in docstrings
from functools import partial from typing import Dict, List, Optional, Tuple, Union import torch import torch.distributed as dist import torch.nn as nn from colossalai.shardformer.layer import (FusedLinear1D_Col, FusedLinear1D_Row, Linear1D_Col, Linear1D_Row) from colossalai.s...
--- +++ @@ -37,6 +37,15 @@ class _SplitForwardGatherBackwardVarLen(torch.autograd.Function): + """ + Split the input and keep only the corresponding chuck to the rank. + + Args: + input_ (`torch.Tensor`): input matrix. + dim (int): the dimension to perform split and gather + process_gr...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/mmdit/distributed.py
Generate docstrings for each module
# Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law...
--- +++ @@ -162,6 +162,13 @@ cond: Tensor = None, guidance: Tensor | None = None, ): + """ + obtain the processed: + img: projected noisy img latent, + txt: text context (from t5), + vec: clip encoded vector, + pe: the positional embeddings...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/mmdit/model.py
Generate docstrings with parameter types
# Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law...
--- +++ @@ -67,6 +67,14 @@ @torch.compile(mode="max-autotune-no-cudagraphs", dynamic=True) def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0): + """ + Create sinusoidal timestep embeddings. + :param t: a 1-D Tensor of N indices, one per batch element. + ...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/mmdit/layers.py
Add docstrings for internal functions
import os import torch.nn as nn from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint def weights_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn...
--- +++ @@ -27,6 +27,7 @@ class NLayerDiscriminator3D(nn.Module): + """Defines a 3D PatchGAN discriminator as in Pix2Pix but for 3D inputs.""" def __init__( self, @@ -37,6 +38,15 @@ conv_cls="conv3d", dropout=0.30, ): + """ + Construct a 3D PatchGAN discriminat...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/vae/discriminator.py
Add docstrings to incomplete code
#!/usr/bin/env python import argparse import datetime import importlib import os import subprocess import sys from tempfile import NamedTemporaryFile import spaces import torch import gradio as gr MODEL_TYPES = ["v1.3"] WATERMARK_PATH = "./assets/images/watermark/watermark.png" CONFIG_MAP = { "v1.3": "configs/o...
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python +""" +This script runs a Gradio App for the Open-Sora model. + +Usage: + python demo.py <config-path> +""" import argparse import datetime @@ -32,6 +38,9 @@ # Prepare Runtime Environment # ============================ def install_dependencies(enable_optimization=F...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/gradio/app.py
Help me document legacy Python code
# Modified from HunyuanVideo # # Copyright 2024 HunyuanVideo # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from typing import Optional, Tuple import numpy as np import torch import torch.nn as nn from diffus...
--- +++ @@ -26,11 +26,21 @@ @dataclass class DecoderOutput(BaseOutput): + r""" + Output of decoding method. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): + The decoded output sample from the last layer of the model. + """ sample: t...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/hunyuan_vae/vae.py
Create simple docstrings for beginners
import torch from colossalai.nn.lr_scheduler import CosineAnnealingWarmupLR from colossalai.nn.optimizer import HybridAdam from torch.optim.lr_scheduler import _LRScheduler def create_optimizer( model: torch.nn.Module, optimizer_config: dict, ) -> torch.optim.Optimizer: optimizer_name = optimizer_config.p...
--- +++ @@ -8,6 +8,16 @@ model: torch.nn.Module, optimizer_config: dict, ) -> torch.optim.Optimizer: + """ + Create an optimizer. + + Args: + model (torch.nn.Module): The model to be optimized. + optimizer_config (dict): The configuration of the optimizer. + + Returns: + torch...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/optimizer.py
Add documentation for all methods
import logging import os import torch.distributed as dist def is_distributed() -> bool: return os.environ.get("WORLD_SIZE", None) is not None def is_main_process() -> bool: return not is_distributed() or dist.get_rank() == 0 def get_world_size() -> int: if is_distributed(): return dist.get_wo...
--- +++ @@ -5,14 +5,32 @@ def is_distributed() -> bool: + """ + Check if the code is running in a distributed setting. + + Returns: + bool: True if running in a distributed setting, False otherwise + """ return os.environ.get("WORLD_SIZE", None) is not None def is_main_process() -> bool...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/logger.py
Document this module using docstrings
import os import time from collections import OrderedDict from collections.abc import Sequence from contextlib import nullcontext import numpy as np import psutil import torch import torch.distributed as dist import torch.nn as nn from colossalai.cluster.dist_coordinator import DistCoordinator from torch.utils.tensorb...
--- +++ @@ -18,6 +18,15 @@ def create_tensorboard_writer(exp_dir: str) -> SummaryWriter: + """ + Create a tensorboard writer. + + Args: + exp_dir (str): The directory to save tensorboard logs. + + Returns: + SummaryWriter: The tensorboard writer. + """ tensorboard_dir = f"{exp_dir}...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/misc.py
Add docstrings to improve collaboration
import copy import os import re from enum import Enum import torch from torch import nn from opensora.datasets import save_sample from opensora.datasets.aspect import get_image_size from opensora.datasets.utils import read_from_path, rescale_image_by_path from opensora.utils.logger import log_message from opensora.ut...
--- +++ @@ -19,6 +19,16 @@ def create_tmp_csv(save_dir: str, prompt: str, ref: str = None, create=True) -> str: + """ + Create a temporary CSV file with the prompt text. + + Args: + save_dir (str): The directory where the CSV file will be saved. + prompt (str): The prompt text. + + Returns...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/inference.py
Help me comply with documentation standards
from typing import List, Optional, Tuple import torch import torch.distributed as dist from colossalai.shardformer.layer._operation import gather_forward_split_backward, split_forward_gather_backward from colossalai.shardformer.layer.attn import RingComm, _rescale_out_lse from colossalai.shardformer.layer.utils import...
--- +++ @@ -88,6 +88,21 @@ softmax_scale: Optional[float] = None, attn_mask: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: + """Ring attention forward + + Args: + ctx (_type_): self + q (torch.Tensor): shape [B, S/P, N, D] + k...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/hunyuan_vae/distributed.py
Write docstrings describing functionality
# Modified from diffusers==0.29.2 and HunyuanVideo # # Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org...
--- +++ @@ -61,6 +61,10 @@ class CausalConv3d(nn.Module): + """ + Implements a causal 3D convolution layer where each position only depends on previous timesteps and current spatial locations. + This maintains temporal causality in video generation tasks. + """ def __init__( self, @@ -92...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/hunyuan_vae/unet_causal_3d_blocks.py
Add docstrings to clarify complex logic
# Modified from diffusers==0.29.2 and HunyuanVideo # # Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/...
--- +++ @@ -82,6 +82,12 @@ class AutoencoderKLCausal3D(ModelMixin, ConfigMixin, FromOriginalVAEMixin): + r""" + A VAE model with KL loss for encoding images/videos into latents and decoding latent representations into images/videos. + + This model inherits from [`ModelMixin`]. Check the superclass document...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/hunyuan_vae/autoencoder_kl_causal_3d.py
Add docstrings for utility scripts
import random import warnings from collections import OrderedDict from datetime import timedelta import torch import torch.distributed as dist import torch.nn.functional as F from colossalai.booster.plugin import HybridParallelPlugin, LowLevelZeroPlugin from colossalai.cluster import DistCoordinator from colossalai.ut...
--- +++ @@ -54,6 +54,12 @@ def setup_device() -> tuple[torch.device, DistCoordinator]: + """ + Setup the device and the distributed coordinator. + + Returns: + tuple[torch.device, DistCoordinator]: The device and the distributed coordinator. + """ assert torch.cuda.is_available(), "Training ...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/train.py
Write docstrings describing each step
import math import os import random from abc import ABC, abstractmethod from dataclasses import dataclass, replace import torch from einops import rearrange, repeat from mmengine.config import Config from peft import PeftModel from torch import Tensor, nn from opensora.datasets.aspect import get_image_size from opens...
--- +++ @@ -80,6 +80,15 @@ def sanitize_sampling_option(sampling_option: SamplingOption) -> SamplingOption: + """ + Sanitize the sampling options. + + Args: + sampling_option (SamplingOption): The sampling options. + + Returns: + SamplingOption: The sanitized sampling options. + """ ...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/sampling.py
Add docstrings to existing functions
import colossalai import torch import torch.distributed as dist from colossalai.booster import Booster from colossalai.cluster import DistCoordinator from opensora.acceleration.parallel_states import ( get_sequence_parallel_group, get_tensor_parallel_group, set_sequence_parallel_group, ) from opensora.mode...
--- +++ @@ -18,6 +18,12 @@ def set_group_size(plugin_config: dict): + """ + Set the group size for tensor parallelism and sequence parallelism. + + Args: + plugin_config (dict): Plugin configuration. + """ tp_size = int(plugin_config.get("tp_size", 1)) sp_size = int(plugin_config.get("s...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/cai.py
Help me document legacy Python code
import functools import json import operator import os import re import shutil from glob import glob from typing import Dict, Optional import torch import torch.distributed as dist import torch.nn as nn from colossalai.booster import Booster from colossalai.checkpoint_io import GeneralCheckpointIO from colossalai.util...
--- +++ @@ -31,6 +31,16 @@ def load_from_hf_hub(repo_path: str, cache_dir: str = None) -> str: + """ + Loads a checkpoint from the Hugging Face Hub. + + Args: + repo_path (str): The path to the checkpoint on the Hugging Face Hub. + cache_dir (str): The directory to cache the downloaded checkp...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/ckpt.py
Add clean documentation to messy code
from typing import List from setuptools import find_packages, setup def fetch_requirements(paths) -> List[str]: if not isinstance(paths, list): paths = [paths] requirements = [] for path in paths: with open(path, "r") as fd: requirements += [r.strip() for r in fd.readlines()] ...
--- +++ @@ -4,6 +4,15 @@ def fetch_requirements(paths) -> List[str]: + """ + This function reads the requirements file. + + Args: + path (str): the path to the requirements file. + + Returns: + The lines in the requirements file. + """ if not isinstance(paths, list): paths...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/setup.py
Generate missing documentation strings
import math import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn NUMEL_LIMIT = 2**30 def ceil_to_divisible(n: int, dividend: int) -> int: return math.ceil(dividend / (dividend // n)) def chunked_avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, cou...
--- +++ @@ -115,6 +115,7 @@ parameters, deterministic=False, ): + """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models""" self.parameters = parameters self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) self.logvar = t...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/models/vae/utils.py
Write proper docstrings for these functions
import argparse import ast import json import os from datetime import datetime import torch from mmengine.config import Config from .logger import is_distributed, is_main_process def parse_args() -> tuple[str, argparse.Namespace]: parser = argparse.ArgumentParser() parser.add_argument("config", type=str, he...
--- +++ @@ -11,6 +11,12 @@ def parse_args() -> tuple[str, argparse.Namespace]: + """ + This function parses the command line arguments. + + Returns: + tuple[str, argparse.Namespace]: The path to the configuration file and the command line arguments. + """ parser = argparse.ArgumentParser() ...
https://raw.githubusercontent.com/hpcaitech/Open-Sora/HEAD/opensora/utils/config.py
Annotate my code with docstrings
from sqlalchemy.ext.indexable import index_property from sqlalchemy.ext.mutable import Mutable from sqlalchemy.types import TypeDecorator from sqlalchemy_utils import EncryptedType from redash.utils import json_dumps, json_loads from redash.utils.configuration import ConfigurationContainer from .base import db clas...
--- +++ @@ -48,6 +48,7 @@ class MutableDict(Mutable, dict): @classmethod def coerce(cls, key, value): + "Convert plain dictionaries to MutableDict." if not isinstance(value, MutableDict): if isinstance(value, dict): @@ -59,11 +60,13 @@ return value def __setit...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/models/types.py
Add verbose docstrings with examples
import json import click from flask import current_app from flask.cli import FlaskGroup, run_command, with_appcontext from rq import Connection from redash import __version__, create_app, rq_redis_connection, settings from redash.cli import ( data_sources, database, groups, organization, queries, ...
--- +++ @@ -32,6 +32,7 @@ @click.group(cls=FlaskGroup, create_app=create) def manager(): + """Management script for Redash""" manager.add_command(database.manager, "database") @@ -46,6 +47,7 @@ @manager.command() def version(): + """Displays Redash version.""" print(__version__) @@ -57,6 +59,7...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/cli/__init__.py
Document this module using docstrings
import unicodedata from urllib.parse import quote import regex from flask import make_response, request from flask_login import current_user from flask_restful import abort from redash import models, settings from redash.handlers.base import BaseResource, get_object_or_404, record_event from redash.models.parameteriz...
--- +++ @@ -143,6 +143,18 @@ class QueryResultListResource(BaseResource): @require_permission("execute_query") def post(self): + """ + Execute a query (or retrieve recent results). + + :qparam string query: The query text to execute + :qparam number query_id: The query object to up...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/handlers/query_results.py
Generate docstrings for each module
import functools from flask_sqlalchemy import BaseQuery, SQLAlchemy from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import object_session from sqlalchemy.pool import NullPool from sqlalchemy_searchable import SearchQueryMixin, make_searchable, vectorizer from redash import settings from redash.uti...
--- +++ @@ -43,6 +43,9 @@ class SearchBaseQuery(BaseQuery, SearchQueryMixin): + """ + The SQA query class to use when full text search is wanted. + """ @vectorizer(db.Integer) @@ -69,6 +72,9 @@ class GFKBase: + """ + Compatibility with 'generic foreign key' approach Peewee used. + """ ...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/models/base.py
Help me write clear docstrings
from sys import exit import click from click.types import convert_type from flask.cli import AppGroup from sqlalchemy.orm.exc import NoResultFound from redash import models from redash.query_runner import ( get_configuration_schema_for_query_runner_type, query_runners, ) from redash.utils import json_loads fr...
--- +++ @@ -24,6 +24,7 @@ help="The organization the user belongs to (leave blank for " "all organizations).", ) def list_command(organization=None): + """List currently configured data sources.""" if organization: org = models.Organization.get_by_slug(organization) data_sources = models...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/cli/data_sources.py
Write Python docstrings for this snippet
import sqlparse from flask import jsonify, request, url_for from flask_login import login_required from flask_restful import abort from funcy import partial from sqlalchemy.orm.exc import StaleDataError from redash import models, settings from redash.authentication.org_resolving import current_org from redash.handlers...
--- +++ @@ -54,6 +54,12 @@ @routes.route(org_scoped_rule("/api/queries/format"), methods=["POST"]) @login_required def format_sql_query(org_slug=None): + """ + Formats an SQL query using the Python ``sqlparse`` formatter. + + :<json string query: The SQL text to format + :>json string query: Formatted SQL...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/handlers/queries.py
Write docstrings for utility functions
import calendar import datetime import logging import numbers import re import time import pytz from sqlalchemy import UniqueConstraint, and_, cast, distinct, func, or_ from sqlalchemy.dialects.postgresql import ARRAY, DOUBLE_PRECISION, JSONB from sqlalchemy.event import listens_for from sqlalchemy.ext.hybrid import h...
--- +++ @@ -836,10 +836,12 @@ @hybrid_property def lowercase_name(self): + "Optional property useful for sorting purposes." return self.name.lower() @lowercase_name.expression def lowercase_name(cls): + "The SQLAlchemy expression for the property above." return fun...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/models/__init__.py
Write docstrings for data processing functions
import json from sys import exit from click import BOOL, argument, option, prompt from flask.cli import AppGroup from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound from redash import models from redash.handlers.users import invite_user manager = AppGroup(help="Users management com...
--- +++ @@ -36,6 +36,9 @@ help="the organization the user belongs to, (leave blank for " "'default').", ) def grant_admin(email, organization="default"): + """ + Grant admin access to user EMAIL. + """ try: org = models.Organization.get_by_slug(organization) admin_group = org.admin...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/cli/users.py
Add docstrings to make code maintainable
from flask import request from redash import models from redash.handlers.base import BaseResource from redash.permissions import ( require_access, require_object_modify_permission, require_permission, view_only, ) from redash.serializers import serialize_widget class WidgetListResource(BaseResource):...
--- +++ @@ -14,6 +14,17 @@ class WidgetListResource(BaseResource): @require_permission("edit_dashboard") def post(self): + """ + Add a widget to a dashboard. + + :<json number dashboard_id: The ID for the dashboard being added to + :<json visualization_id: The ID of the visualizati...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/handlers/widgets.py
Generate docstrings with examples
from __future__ import with_statement from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig import logging # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config ...
--- +++ @@ -30,6 +30,17 @@ def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Cal...
https://raw.githubusercontent.com/getredash/redash/HEAD/migrations/env.py
Add missing documentation to my Python functions
from flask import request, url_for from flask_restful import abort from funcy import partial, project from sqlalchemy.orm.exc import StaleDataError from redash import models from redash.handlers.base import ( BaseResource, filter_by_tags, get_object_or_404, paginate, ) from redash.handlers.base import ...
--- +++ @@ -36,6 +36,17 @@ class DashboardListResource(BaseResource): @require_permission("list_dashboards") def get(self): + """ + Lists all accessible dashboards. + + :qparam number page_size: Number of queries to return per page + :qparam number page: Page number to retrieve + ...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/handlers/dashboards.py
Document all endpoints with docstrings
import hashlib import itertools import logging import time from functools import reduce from operator import or_ from flask import current_app, request_started, url_for from flask_login import AnonymousUserMixin, UserMixin, current_user from passlib.apps import custom_app_context as pwd_context from sqlalchemy.dialect...
--- +++ @@ -26,6 +26,12 @@ def sync_last_active_at(): + """ + Update User model with the active_at timestamp from Redis. We first fetch + all the user_ids to update, and then fetch the timestamp to minimize the + time between fetching the value and updating the DB. This is because there + might be a ...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/models/users.py
Document this script properly
import csv import logging import uuid from redash.query_runner import ( TYPE_DATE, TYPE_DATETIME, TYPE_FLOAT, TYPE_INTEGER, TYPE_STRING, BaseQueryRunner, InterruptException, JobTimeoutException, register, ) from redash.utils import json_loads logger = logging.getLogger(__name__) t...
--- +++ @@ -41,6 +41,11 @@ def resolve_redash_type(type_in_atsd): + """ + Retrieve corresponding redash type + :param type_in_atsd: `str` + :return: redash type constant + """ if isinstance(type_in_atsd, dict): type_in_redash = types_map.get(type_in_atsd["base"]) else: @@ -49,6 +54...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/axibase_tsd.py
Add missing documentation to my Python functions
import datetime import logging from urllib.parse import urljoin import yaml from funcy import compact, project from redash.query_runner import ( TYPE_BOOLEAN, TYPE_DATETIME, TYPE_FLOAT, TYPE_INTEGER, TYPE_STRING, BaseHTTPQueryRunner, register, ) class QueryParseError(Exception): pass...
--- +++ @@ -198,6 +198,7 @@ return parse_json(results, fields), error def _get_all_results(self, url, method, result_path, pagination, **request_options): + """Get all results from a paginated endpoint.""" base_url = self.configuration.get("base_url") url = urljoin(base_url, url)...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/json_ds.py
Create Google-style docstrings for my code
import logging from collections import defaultdict from contextlib import ExitStack from functools import wraps import sqlparse from dateutil import parser from rq.timeouts import JobTimeoutException from sshtunnel import open_tunnel from redash import settings, utils from redash.utils.requests_session import ( U...
--- +++ @@ -139,6 +139,12 @@ @property def host(self): + """Returns this query runner's configured host. + This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source. + + `BaseQueryRunner`'s naïve implementation supports query runner impl...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/__init__.py
Add structured docstrings to improve clarity
import json import logging from os import environ from redash.query_runner import BaseQueryRunner from . import register try: from cmem.cmempy.dp.proxy.graph import get_graphs_list from cmem.cmempy.queries import ( # noqa: F401 QUERY_STRING, QueryCatalog, SparqlQuery, ) ena...
--- +++ @@ -1,3 +1,8 @@+"""Provide the query runner for eccenca Corporate Memory. + +seeAlso: https://documentation.eccenca.com/ +seeAlso: https://eccenca.com/ +""" import json import logging @@ -23,6 +28,7 @@ class CorporateMemoryQueryRunner(BaseQueryRunner): + """Use eccenca Corporate Memory as redash data...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/corporate_memory.py
Write docstrings for data processing functions
import logging import os from base64 import b64decode from tempfile import NamedTemporaryFile from typing import Any, Dict, Optional, Tuple, Type, TypeVar from redash.query_runner import ( TYPE_BOOLEAN, TYPE_DATETIME, TYPE_FLOAT, TYPE_INTEGER, TYPE_STRING, BaseQueryRunner, register, ) try:...
--- +++ @@ -37,10 +37,17 @@ class InfluxDBv2(BaseQueryRunner): + """ + Query runner for influxdb version 2. + """ should_annotate_query = False def _get_influx_kwargs(self) -> Dict: + """ + Determines additional arguments for influxdb client connection. + :return: An obje...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/influx_db_v2.py
Create documentation for each function signature
import datetime import importlib import logging import sys from RestrictedPython import compile_restricted from RestrictedPython.Guards import ( guarded_iter_unpack_sequence, guarded_unpack_sequence, safe_builtins, ) from RestrictedPython.transformer import IOPERATOR_TO_STR from redash import models from ...
--- +++ @@ -39,6 +39,7 @@ class CustomPrint: + """CustomPrint redirect "print" calls to be sent as "log" on the result object.""" def __init__(self): self.enabled = True @@ -151,6 +152,10 @@ @staticmethod def custom_write(obj): + """ + Custom hooks which controls the way ...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/python.py
Add docstrings to improve code quality
import os from urllib.parse import urlparse, urlunparse def fix_assets_path(path): fullpath = os.path.join(os.path.dirname(__file__), "../", path) return fullpath def array_from_string(s): array = s.split(",") if "" in array: array.remove("") return array def set_from_string(s): r...
--- +++ @@ -20,6 +20,7 @@ def parse_boolean(s): + """Takes a string and returns the equivalent as a boolean value.""" s = s.strip().lower() if s in ("yes", "true", "on", "1"): return True @@ -44,6 +45,7 @@ def add_decode_responses_to_redis_url(url): + """Make sure that the Redis URL inc...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/settings/helpers.py
Add professional docstrings to my codebase
import logging import time from rq.timeouts import JobTimeoutException from redash import models, redis_connection, settings, statsd_client from redash.models.parameterized_query import ( InvalidParameterError, QueryDetachedFromDataSourceError, ) from redash.monitor import rq_job_ids from redash.query_runner ...
--- +++ @@ -118,6 +118,13 @@ def cleanup_query_results(): + """ + Job to cleanup unused query results -- such that no query links to them anymore, and older than + settings.QUERY_RESULTS_CLEANUP_MAX_AGE (a week by default, so it's less likely to be open in someone's browser and be used). + + Each time t...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/tasks/queries/maintenance.py
Add docstrings for production code
import json try: import pydgraph enabled = True except ImportError: enabled = False from redash.query_runner import BaseQueryRunner, register def reduce_item(reduced_item, key, value): # Reduction Condition 1 if isinstance(value, list): for i, sub_item in enumerate(value): r...
--- +++ @@ -11,6 +11,7 @@ def reduce_item(reduced_item, key, value): + """From https://github.com/vinay20045/json-to-csv""" # Reduction Condition 1 if isinstance(value, list): for i, sub_item in enumerate(value): @@ -113,6 +114,9 @@ return data, error def get_schema(self, get_st...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/dgraph.py
Add docstrings including usage examples
import json import logging from os import environ from redash.query_runner import BaseQueryRunner from . import register try: import requests from cmem.cmempy.queries import SparqlQuery from rdflib.plugins.sparql import prepareQuery # noqa enabled = True except ImportError: enabled = False lo...
--- +++ @@ -1,3 +1,7 @@+"""Provide the query runner for SPARQL Endpoints. + +seeAlso: https://www.w3.org/TR/rdf-sparql-query/ +""" import json import logging @@ -20,6 +24,7 @@ class SPARQLEndpointQueryRunner(BaseQueryRunner): + """Use SPARQL Endpoint as redash data source""" # These environment keys a...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/sparql_endpoint.py
Generate docstrings for this script
import errno import os import signal import sys from rq import Queue as BaseQueue from rq.job import Job as BaseJob from rq.job import JobStatus from rq.timeouts import HorseMonitorTimeoutException from rq.utils import utcnow from rq.worker import ( HerokuWorker, # HerokuWorker implements graceful shutdown on SIG...
--- +++ @@ -35,6 +35,9 @@ class StatsdRecordingQueue(BaseQueue): + """ + RQ Queue Mixin that overrides `enqueue_call` to increment metrics via Statsd + """ def enqueue_job(self, *args, **kwargs): job = super().enqueue_job(*args, **kwargs) @@ -51,6 +54,9 @@ class StatsdRecordingWorker(Ba...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/tasks/worker.py
Write docstrings for algorithm functions
import logging import os from redash.models.users import ApiUser, User from redash.query_runner import ( TYPE_BOOLEAN, TYPE_DATE, TYPE_DATETIME, TYPE_FLOAT, TYPE_INTEGER, TYPE_STRING, BaseQueryRunner, InterruptException, JobTimeoutException, register, ) from redash.settings impo...
--- +++ @@ -30,6 +30,7 @@ def _convert_row_types(value): + """Convert NamedRowTuple instances to dicts so ROW fields are serialized with their names.""" if isinstance(value, NamedRowTuple): names = value.__annotations__.get("names", []) return { @@ -163,6 +164,7 @@ return catalogs ...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/query_runner/trino.py
Add minimal docstrings for each function
import binascii import codecs import csv import datetime import decimal import hashlib import io import json import math import os import random import re import sys import uuid import pystache import pytz import sqlparse from flask import current_app from funcy import select_values from sqlalchemy.orm.query import Qu...
--- +++ @@ -30,6 +30,11 @@ def utcnow(): + """Return datetime.now value with timezone specified. + + Without the timezone data, when the timestamp stored to the database it gets the current timezone of the server, + which leads to errors in calculations. + """ return datetime.datetime.now(pytz.utc)...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/utils/__init__.py
Add docstrings to my Python code
from collections import defaultdict # Replace this method with your own implementation in case you want to limit the time limit on certain queries or users. def query_time_limit(is_scheduled, user_id, org_id): from redash import settings if is_scheduled: return settings.SCHEDULED_QUERY_TIME_LIMIT ...
--- +++ @@ -12,6 +12,16 @@ def periodic_jobs(): + """Schedule any custom periodic jobs here. For example: + + from time import timedelta + from somewhere import some_job, some_other_job + + return [ + {"func": some_job, "interval": timedelta(hours=1)}, + {"func": some_other_job, "interval"...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/settings/dynamic_settings.py
Create docstrings for each class method
# Copyright (c) 2012, Konsta Vesterinen # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions a...
--- +++ @@ -49,6 +49,16 @@ def query_labels(query): + """ + Return all labels for given SQLAlchemy query object. + Example:: + query = session.query( + Category, + db.func.count(Article.id).label('articles') + ) + query_labels(query) # ['articles'] + :param qu...
https://raw.githubusercontent.com/getredash/redash/HEAD/redash/utils/query_order.py
Include argument descriptions in docstrings
from __future__ import annotations from reflex.components.component import Component from reflex.components.datadisplay.logo import svg_logo from reflex.components.el import a, button, div, h2, hr, p, pre, svg from reflex.event import EventHandler, set_clipboard from reflex.state import FrontendEventExceptionState fr...
--- +++ @@ -1,3 +1,4 @@+"""A React Error Boundary component that catches unhandled frontend exceptions.""" from __future__ import annotations @@ -14,6 +15,15 @@ def on_error_spec( error: ObjectVar[dict[str, str]], info: ObjectVar[dict[str, str]] ) -> tuple[Var[str], Var[str]]: + """The spec for the on_err...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/base/error_boundary.py
Provide clean and structured docstrings
from __future__ import annotations from reflex.components.base.bare import Bare from reflex.components.el import elements from reflex.components.el.elements.metadata import Meta as Meta # for compatibility from reflex.vars.base import Var class Title(elements.Title): def render(self) -> dict: # Make s...
--- +++ @@ -1,3 +1,4 @@+"""Display the title of the current page.""" from __future__ import annotations @@ -8,8 +9,17 @@ class Title(elements.Title): + """A component that displays the title of the current page.""" def render(self) -> dict: + """Render the title component. + + Raises: +...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/base/meta.py
Add docstrings that explain purpose and usage
from reflex.components.component import Component class Fragment(Component): library = "react" tag = "Fragment" fragment = Fragment.create
--- +++ @@ -1,11 +1,13 @@+"""React fragments to enable bare returns of component trees from functions.""" from reflex.components.component import Component class Fragment(Component): + """A React fragment to return multiple components from a function without wrapping it in a container.""" library = "r...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/base/fragment.py
Add docstrings with type hints explained
from __future__ import annotations from reflex import constants from reflex.components.base.fragment import Fragment from reflex.components.component import Component from reflex.components.core.cond import cond from reflex.components.el.elements.typography import Div from reflex.components.lucide.icon import Icon fr...
--- +++ @@ -1,3 +1,4 @@+"""Banner components.""" from __future__ import annotations @@ -53,9 +54,15 @@ class WebsocketTargetURL(Var): + """A component that renders the websocket target URL.""" @classmethod def create(cls) -> Var: + """Create a websocket target URL component. + + Re...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/banner.py
Document classes and their methods
from __future__ import annotations from typing import TypeVar breakpoints_values = ["30em", "48em", "62em", "80em", "96em"] breakpoint_names = ["xs", "sm", "md", "lg", "xl"] def set_breakpoints(values: tuple[str, str, str, str, str]): breakpoints_values.clear() breakpoints_values.extend(values) K = TypeV...
--- +++ @@ -1,3 +1,4 @@+"""Breakpoints utility.""" from __future__ import annotations @@ -8,6 +9,11 @@ def set_breakpoints(values: tuple[str, str, str, str, str]): + """Overwrite default breakpoint values. + + Args: + values: CSS values in order defining the breakpoints of responsive layouts + ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/breakpoints.py
Add docstrings to clarify complex logic
from __future__ import annotations import contextlib import copy import dataclasses import enum import functools import inspect import typing from abc import ABC, ABCMeta, abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from dataclasses import _MISSING_TYPE, MISSING from fun...
--- +++ @@ -1,3 +1,4 @@+"""Base component definitions.""" from __future__ import annotations @@ -69,6 +70,7 @@ class ComponentField(BaseField[FIELD_TYPE]): + """A field for a component.""" def __init__( self, @@ -77,10 +79,23 @@ is_javascript: bool | None = None, annotated_t...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/component.py
Add docstrings to existing functions
from __future__ import annotations from reflex.components import el as elements from reflex.components.core.helmet import helmet from reflex.utils import console class Script(elements.Script): @classmethod def create( cls, *children, **props, ): async_ = props.pop("async...
--- +++ @@ -1,3 +1,4 @@+"""Wrapper for the script element. Uses the Helmet component to manage the head.""" from __future__ import annotations @@ -7,6 +8,7 @@ class Script(elements.Script): + """Wrapper for the script element.""" @classmethod def create( @@ -14,6 +16,18 @@ *children, ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/base/script.py
Document all endpoints with docstrings
from __future__ import annotations from typing import Any, overload from reflex.components.base.fragment import Fragment from reflex.components.component import BaseComponent, Component from reflex.components.tags import CondTag, Tag from reflex.constants import Dirs from reflex.style import LIGHT_COLOR_MODE, resolv...
--- +++ @@ -1,3 +1,4 @@+"""Create a list of components from an iterable.""" from __future__ import annotations @@ -20,6 +21,7 @@ class Cond(Component): + """Render one of two components based on a condition.""" # The cond to determine which component to render. cond: Var[Any] @@ -31,6 +33,16 @@ ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/cond.py
Expand my code with proper documentation strings
from reflex.components.component import ComponentNamespace from reflex.components.core.colors import color from reflex.components.core.cond import color_mode_cond from reflex.components.core.responsive import desktop_only from reflex.components.el.elements.inline import A from reflex.components.el.elements.media impor...
--- +++ @@ -1,3 +1,4 @@+"""Components for displaying the Reflex sticky logo.""" from reflex.components.component import ComponentNamespace from reflex.components.core.colors import color @@ -10,9 +11,15 @@ class StickyLogo(Svg): + """A simple Reflex logo SVG with only the letter R.""" @classmethod ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/sticky.py
Generate consistent documentation across files
from __future__ import annotations import dataclasses from reflex.components.el.elements.typography import Div from reflex.constants.compiler import MemoizationDisposition, MemoizationMode from reflex.utils.imports import ImportDict from reflex.vars.base import Var, get_unique_variable_name class AutoScroll(Div): ...
--- +++ @@ -1,3 +1,4 @@+"""A component that automatically scrolls to the bottom when new content is added.""" from __future__ import annotations @@ -10,6 +11,7 @@ class AutoScroll(Div): + """A div that automatically scrolls to the bottom when new content is added.""" _memoization_mode = MemoizationMo...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/auto_scroll.py
Improve documentation using docstrings
from reflex.components.el.elements.typography import Div from reflex.vars.base import Var class Html(Div): # The HTML to render. dangerouslySetInnerHTML: Var[dict[str, str]] # noqa: N815 @classmethod def create(cls, *children, **props): # If children are not provided, throw an error. ...
--- +++ @@ -1,15 +1,33 @@+"""A html component.""" from reflex.components.el.elements.typography import Div from reflex.vars.base import Var class Html(Div): + """Render the html. + + Returns: + The code to render the html component. + """ # The HTML to render. dangerouslySetInnerHTM...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/html.py
Auto-generate documentation strings for this file
from __future__ import annotations from collections.abc import Sequence from reflex.components.base.fragment import Fragment from reflex.components.tags.tag import Tag from reflex.constants.compiler import Hooks from reflex.event import EventChain, EventHandler, passthrough_event_spec from reflex.utils.format import...
--- +++ @@ -1,3 +1,4 @@+"""Global on_paste handling for Reflex app.""" from __future__ import annotations @@ -14,6 +15,7 @@ class Clipboard(Fragment): + """Clipboard component.""" # The element ids to attach the event listener to. Defaults to all child components or the document. targets: Var[Se...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/clipboard.py
Create docstrings for all classes and functions
from __future__ import annotations from typing import Any from reflex.components.component import Component from reflex.constants import EventTriggers from reflex.event import EventHandler, no_args_event_spec from reflex.vars import VarData from reflex.vars.base import Var DEFAULT_DEBOUNCE_TIMEOUT = 300 class Deb...
--- +++ @@ -1,3 +1,4 @@+"""Wrapper around react-debounce-input.""" from __future__ import annotations @@ -13,6 +14,12 @@ class DebounceInput(Component): + """The DebounceInput component is used to buffer input events on the client side. + + It is intended to wrap various form controls and should be used ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/debounce.py
Add minimal docstrings for each function
import dataclasses @dataclasses.dataclass class AppMixin: def _init_mixin(self):
--- +++ @@ -1,8 +1,14 @@+"""Default mixin for all app mixins.""" import dataclasses @dataclasses.dataclass class AppMixin: + """Define the base class for all app mixins.""" - def _init_mixin(self):+ def _init_mixin(self): + """Initialize the mixin. + + Any App mixin can override this m...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/app_mixins/mixin.py
Generate docstrings for exported functions
from __future__ import annotations from collections.abc import Callable, Sequence from pathlib import Path from typing import Any, ClassVar from reflex.app import UploadFile from reflex.components.base.fragment import Fragment from reflex.components.component import ( Component, ComponentNamespace, Memoi...
--- +++ @@ -1,3 +1,4 @@+"""A file upload component.""" from __future__ import annotations @@ -56,6 +57,17 @@ def upload_file(id_: str | Var[str] = DEFAULT_UPLOAD_ID) -> Var: + """Get the file upload drop trigger. + + This var is passed to the dropzone component to update the file list when a + drop oc...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/upload.py
Fill in missing docstrings in my code
from __future__ import annotations import asyncio import concurrent.futures import contextlib import copy import dataclasses import functools import inspect import json import operator import sys import time import traceback import urllib.parse from collections.abc import ( AsyncGenerator, AsyncIterator, ...
--- +++ @@ -1,3 +1,4 @@+"""The main Reflex app.""" from __future__ import annotations @@ -134,10 +135,25 @@ def default_frontend_exception_handler(exception: Exception) -> None: + """Default frontend exception handler function. + + Args: + exception: The exception. + + """ console.error(f"...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/app.py
Generate docstrings for script automation
from __future__ import annotations import asyncio import contextlib import dataclasses import functools import inspect import time from collections.abc import Callable, Coroutine from starlette.applications import Starlette from reflex.utils import console from reflex.utils.exceptions import InvalidLifespanTaskType...
--- +++ @@ -1,3 +1,4 @@+"""Mixin that allow tasks to run during the whole app lifespan.""" from __future__ import annotations @@ -19,6 +20,7 @@ @dataclasses.dataclass class LifespanMixin(AppMixin): + """A Mixin that allow tasks to run during the whole app lifespan.""" # Lifespan tasks that are planned...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/app_mixins/lifespan.py
Add structured docstrings to improve clarity
from __future__ import annotations import dataclasses from typing import ClassVar, Literal from reflex.components.component import Component, ComponentNamespace, field from reflex.components.core.cond import color_mode_cond from reflex.components.lucide.icon import Icon from reflex.components.markdown.markdown impor...
--- +++ @@ -1,3 +1,4 @@+"""A code component.""" from __future__ import annotations @@ -301,6 +302,14 @@ def construct_theme_var(theme: str) -> Var[Theme]: + """Construct a theme var. + + Args: + theme: The theme to construct. + + Returns: + The constructed theme var. + """ return...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/datadisplay/code.py
Document functions with detailed explanations
import inspect from pathlib import Path from reflex import constants from reflex.environment import EnvironmentVariables def remove_stale_external_asset_symlinks(): external_dir = ( Path.cwd() / constants.Dirs.APP_ASSETS / constants.Dirs.EXTERNAL_APP_ASSETS ) if not external_dir.exists(): ...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for adding assets to the app.""" import inspect from pathlib import Path @@ -7,6 +8,13 @@ def remove_stale_external_asset_symlinks(): + """Remove broken symlinks and empty directories in assets/external/. + + When a Python module directory that uses rx.asset(sha...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/assets.py
Turn comments into proper docstrings
from reflex.components.el.elements.base import BaseHTML from reflex.vars.base import Var class RawLink(BaseHTML): tag = "link" # The href. href: Var[str] # The type of link. rel: Var[str] class ScriptTag(BaseHTML): tag = "script" # The type of script represented. type_: Var[str...
--- +++ @@ -1,9 +1,11 @@+"""Display the title of the current page.""" from reflex.components.el.elements.base import BaseHTML from reflex.vars.base import Var class RawLink(BaseHTML): + """A component that displays the title of the current page.""" tag = "link" @@ -15,6 +17,7 @@ class ScriptTag...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/base/link.py
Create docstrings for API functions
from typing import TYPE_CHECKING, Union from reflex import constants from reflex.utils import imports from reflex.utils.exceptions import DynamicComponentMissingLibraryError from reflex.utils.format import format_library_name from reflex.utils.serializers import serializer from reflex.vars import Var, get_unique_vari...
--- +++ @@ -1,3 +1,4 @@+"""Components that are dynamically generated on the backend.""" from typing import TYPE_CHECKING, Union @@ -14,6 +15,14 @@ def get_cdn_url(lib: str) -> str: + """Get the CDN URL for a library. + + Args: + lib: The library to get the CDN URL for. + + Returns: + The...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/dynamic.py
Add docstrings for better understanding
from __future__ import annotations from typing import Any, cast import reflex as rx from reflex.components.base.fragment import Fragment from reflex.components.component import StatefulComponent, field from reflex.constants.compiler import Hooks from reflex.event import key_event, no_args_event_spec from reflex.vars...
--- +++ @@ -1,3 +1,4 @@+"""Window event listener component for Reflex.""" from __future__ import annotations @@ -13,22 +14,46 @@ def _on_resize_spec() -> tuple[Var[int], Var[int]]: + """Args spec for the on_resize event trigger. + + Returns: + A tuple containing window width and height variables. ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/core/window_events.py
Add docstrings with type hints explained
from reflex.vars.base import Var from .base import BaseHTML class Details(BaseHTML): tag = "details" # Indicates whether the details will be visible (expanded) to the user open: Var[bool] class Dialog(BaseHTML): tag = "dialog" # Indicates whether the dialog is active and can be interacted ...
--- +++ @@ -1,3 +1,4 @@+"""Other classes.""" from reflex.vars.base import Var @@ -5,6 +6,7 @@ class Details(BaseHTML): + """Display the details element.""" tag = "details" @@ -13,6 +15,7 @@ class Dialog(BaseHTML): + """Display the dialog element.""" tag = "dialog" @@ -21,26 +24,43 @...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/el/elements/other.py
Generate docstrings for exported functions
from __future__ import annotations import dataclasses import inspect from reflex.event import Event from reflex.middleware import HydrateMiddleware, Middleware from reflex.state import BaseState, StateUpdate from .mixin import AppMixin @dataclasses.dataclass class MiddlewareMixin(AppMixin): # Middleware to a...
--- +++ @@ -1,3 +1,4 @@+"""Middleware Mixin that allow to add middleware to the app.""" from __future__ import annotations @@ -13,6 +14,7 @@ @dataclasses.dataclass class MiddlewareMixin(AppMixin): + """Middleware Mixin that allow to add middleware to the app.""" # Middleware to add to the app. Users s...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/app_mixins/middleware.py
Generate consistent documentation across files
from typing import ClassVar from reflex.components.component import Component class Element(Component): _is_tag_in_global_scope: ClassVar[bool] = True def __eq__(self, other: object): return isinstance(other, Element) and self.tag == other.tag
--- +++ @@ -1,3 +1,4 @@+"""Base class definition for raw HTML elements.""" from typing import ClassVar @@ -5,8 +6,17 @@ class Element(Component): + """The base class for all raw HTML elements.""" _is_tag_in_global_scope: ClassVar[bool] = True def __eq__(self, other: object): - return is...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/el/element.py
Add docstrings that explain logic
from __future__ import annotations import json from collections.abc import Iterable, Mapping from typing import TYPE_CHECKING, Any, Literal from reflex import constants from reflex.constants import Hooks from reflex.constants.state import CAMEL_CASE_MEMO_MARKER from reflex.utils.format import format_state_name, json...
--- +++ @@ -1,3 +1,4 @@+"""Templates to use in the reflex compiler.""" from __future__ import annotations @@ -19,6 +20,14 @@ def _sort_hooks( hooks: dict[str, VarData | None], ) -> tuple[list[str], list[str], list[str]]: + """Sort the hooks by their position. + + Args: + hooks: The hooks to sort...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/compiler/templates.py
Add well-formatted docstrings
from __future__ import annotations from collections.abc import Callable from dataclasses import _MISSING_TYPE, MISSING from typing import Annotated, Any, Generic, TypeVar, get_origin from reflex.utils import types from reflex.utils.compat import annotations_from_namespace FIELD_TYPE = TypeVar("FIELD_TYPE") class ...
--- +++ @@ -1,3 +1,4 @@+"""Shared field infrastructure for components and props.""" from __future__ import annotations @@ -12,6 +13,7 @@ class BaseField(Generic[FIELD_TYPE]): + """Base field class used by internal metadata classes.""" def __init__( self, @@ -19,6 +21,13 @@ default_fa...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/field.py
Write docstrings describing functionality
from typing import ClassVar, Literal from reflex.vars.base import Var from .base import BaseHTML class Blockquote(BaseHTML): tag = "blockquote" # Define the title of a work. cite: Var[str] class Dd(BaseHTML): tag = "dd" class Div(BaseHTML): tag = "div" class Dl(BaseHTML): tag = "...
--- +++ @@ -1,3 +1,4 @@+"""Typography classes.""" from typing import ClassVar, Literal @@ -7,6 +8,7 @@ class Blockquote(BaseHTML): + """Display the blockquote element.""" tag = "blockquote" @@ -15,46 +17,55 @@ class Dd(BaseHTML): + """Display the dd element.""" tag = "dd" class D...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/el/elements/typography.py
Write docstrings for algorithm functions
from __future__ import annotations from collections.abc import Sequence from typing import Any from reflex.components.component import NoSSRComponent from reflex.components.tags import Tag from reflex.utils import types from reflex.utils.imports import ImportDict from reflex.utils.serializers import serialize from r...
--- +++ @@ -1,3 +1,4 @@+"""Table components.""" from __future__ import annotations @@ -13,6 +14,7 @@ class Gridjs(NoSSRComponent): + """A component that wraps a nivo bar component.""" library = "gridjs-react@6.1.1" @@ -20,6 +22,7 @@ class DataTable(Gridjs): + """A data table component.""" ...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/gridjs/datatable.py
Add docstrings including usage examples
from __future__ import annotations import sys from collections.abc import Callable, Iterable, Sequence from inspect import getmodule from pathlib import Path from typing import TYPE_CHECKING, Any from reflex import constants from reflex.compiler import templates, utils from reflex.components.base.fragment import Fra...
--- +++ @@ -1,3 +1,4 @@+"""Compiler for the reflex apps.""" from __future__ import annotations @@ -42,6 +43,14 @@ def _compile_document_root(root: Component) -> str: + """Compile the document root. + + Args: + root: The document root to compile. + + Returns: + The compiled document root....
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/compiler/compiler.py
Create docstrings for reusable components
import dataclasses from datetime import date, datetime, time, timedelta from reflex.components.component import NoSSRComponent from reflex.event import EventHandler, passthrough_event_spec from reflex.utils.imports import ImportDict from reflex.vars.base import LiteralVar, Var @dataclasses.dataclass(frozen=True) cl...
--- +++ @@ -1,3 +1,4 @@+"""Moment component for humanized date rendering.""" import dataclasses from datetime import date, datetime, time, timedelta @@ -10,6 +11,7 @@ @dataclasses.dataclass(frozen=True) class MomentDelta: + """A delta used for add/subtract prop in Moment.""" years: int | None = datacla...
https://raw.githubusercontent.com/reflex-dev/reflex/HEAD/reflex/components/moment/moment.py