instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write documentation strings for class attributes
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -31,6 +31,19 @@ class FileSystemMediaProvider(MediaProvider): + """A simple media provider that writes to the filesystem. + + It is assumed that an external HTTP server will take care of serving the + media objects once written. + + `media_fs_root` is the root directory on the filesystem to w...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/providers/media/filesystem.py
Auto-generate documentation strings for this file
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -45,6 +45,10 @@ def safe_xml_str(s, use_encoding="utf-8"): + '''Replace invalid-in-XML unicode control characters with '\uFFFD'. + Also, coerces result to unicode + + ''' illegal_xml = re.compile(u'[\x00-\x08\x0b\x0c\x0e-\x1F\uD800-\uDFFF\uFFFE\uFFFF]') if not isinstance(s, unico...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/providers/search/common.py
Write docstrings describing functionality
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -30,8 +30,12 @@ from r2.lib.utils import constant_time_compare class CloudFlareCdnProvider(CdnProvider): + """A provider for reddit's configuration of CloudFlare. + + """ def _do_content_purge(self, url): + """Does the purge of the content from CloudFlare.""" data = {...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/providers/cdn/cloudflare.py
Document this module using docstrings
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,7 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +"""Utilities for interfacing with the WebSocket server Sutro.""" import datetime import json @@ -36...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/websockets.py
Add verbose docstrings with examples
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -164,6 +164,8 @@ pass def author_spammer(self, things, spam): + """incr/decr the 'spammer' field for the author of every + passed thing""" by_aid = {} for thing in things: if (hasattr(thing, 'author_id') @@ -239,6 +241,16 @@ def create_awar...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/admintools.py
Expand my code with proper documentation strings
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -35,6 +35,13 @@ def connect_to_zookeeper(hostlist, credentials): + """Create a connection to the ZooKeeper ensemble. + + If authentication credentials are provided (as a two-tuple: username, + password), we will ensure that they are provided to the server whenever we + establish a connection....
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/zookeeper.py
Create Google-style docstrings for my code
import datetime import dateutil import json import pytz import time from boto.s3.connection import S3Connection from boto.sqs.connection import SQSConnection from pylons import app_globals as g from r2.lib.s3_helpers import parse_s3_path from r2.lib.sitemaps.store import store_sitemaps_in_s3 from r2.lib.sitemaps.data...
--- +++ @@ -23,6 +23,7 @@ def watcher(): + """Poll for new sitemap data and process it as necessary.""" while True: _process_message() @@ -84,6 +85,7 @@ def _create_test_message(): + """A dev only function that drops a new message on the sqs queue.""" sqs = SQSConnection() sqs_q ...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/sitemaps/watcher.py
Document this module using docstrings
import datetime from pycassa.batch import Mutator from pycassa.system_manager import ASCII_TYPE from pylons import app_globals as g import pytz from r2.lib.contrib.ipaddress import ip_address from r2.lib.db import tdb_cassandra __all__ = ["IPsByAccount", "AccountsByIP"] CONNECTION_POOL = g.cassandra_pools['main']...
--- +++ @@ -41,6 +41,28 @@ column_finish=None, column_count=100, column_reversed=True): + """Get the last accessed times of an account by IP address. + + Returns a list of dicts of the last accessed times of an account by + IP address, most recent first. + + ...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/ip.py
Create simple docstrings for beginners
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,9 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +"""Module for request signing. + +""" import hmac import hashlib import re @@ -57,6 +60,8 @@ cla...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/signing.py
Fill in missing docstrings in my code
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -121,6 +121,7 @@ @classmethod def get(cls, date): + """Gets the goal for a date, or the nearest previous goal.""" try: colkey = cls._colkey(date) col = cls._cf.get( @@ -433,6 +434,11 @@ def append_random_bottlecap_phrase(message): + """Appends a ran...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/gold.py
Document classes and their methods
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -21,6 +21,47 @@ ############################################################################### +"""Create exhaustive sitemaps for Reddit. + +This module exists to make fairly exhaustive sitemaps as defined by the +sitemap protocol (http://www.sitemaps.org/protocol.html) + +We currently support two types...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/sitemaps/generate.py
Improve documentation using docstrings
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -482,6 +482,12 @@ element_name=None, context=None, site_name=None): + """Add utm query parameters to reddit.com links to track navigation. + + context => ?utm_medium (listing page, post listing on hybrid page) + site_nam...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/link.py
Add docstrings to incomplete code
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -20,6 +20,11 @@ # Inc. All Rights Reserved. ############################################################################### +""" +Module for maintaining long or commonly used translatable strings, +removing the need to pollute the code with lots of extra _ and +ungettext calls. +""" from pylons import ...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/strings.py
Add docstrings for utility scripts
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -113,6 +113,7 @@ _connection_pool = 'main' class WikiRevision(tdb_cassandra.UuidThing, Printable): + """ Contains content (markdown), author of the edit, page the edit belongs to, and datetime of the edit """ _use_db = True _connection_pool = 'main' @@ -209,6 +210,8 @@ class Wik...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/wiki.py
Add docstrings for utility scripts
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -78,6 +78,7 @@ @classmethod def create(self, subreddit, short_name, description, kind=None, created_utc=None): + """Create a rule and append to the end of the priority list.""" try: priority = len(list(self._cf.get(subreddit._id36))) except tdb_cass...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/rules.py
Add docstrings for utility scripts
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -71,11 +71,13 @@ @classmethod def _mutation_context(cls, link): + """Return a lock for use during read-modify-write operations""" key = 'comment_lock_' + str(link._id) return g.make_lock("comment_tree", key) @classmethod def prepare_new_storage(cls, link): + ...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/comment_tree.py
Include argument descriptions in docstrings
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,42 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +"""A delayed execution system. + +The ``trylater`` module provides tools for performing an action at a...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/trylater.py
Add docstrings to my Python code
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -54,6 +54,7 @@ class FlairTemplate(tdb_cassandra.Thing): + """A template for some flair.""" _defaults = dict(text='', css_class='', text_editable=False, @@ -81,6 +82,17 @@ return tdb_cassandra.Thing._commit(self, *a, **kw) def covers(self...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/flair.py
Improve my code by adding docstrings
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -41,6 +41,7 @@ class Token(tdb_cassandra.Thing): + """A unique randomly-generated token used for authentication.""" _extra_schema_creation_args = dict( key_validation_class=ASCII_TYPE, @@ -325,6 +326,14 @@ @classmethod def merge_scopes(cls, scopes): + """Return a by-s...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/token.py
Fill in missing docstrings in my code
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,18 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +""" +These models represent the traffic statistics stored for subreddits and +promoted links. They ar...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/traffic.py
Add docstrings that explain logic
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -37,6 +37,11 @@ from r2.lib import utils class TimingStatBuffer: + """Dictionary of keys to cumulative time+count values. + + This provides thread-safe accumulation of pairs of values. Iterating over + instances of this class yields (key, (total_time, count)) tuples. + """ Timing = coll...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/stats.py
Document functions with clear intent
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -131,6 +131,7 @@ @classmethod def get_reports(cls, wrapped, max_user_reasons=20): + """Get two lists of mod and user reports on the item.""" if (wrapped.reported > 0 and (wrapped.can_ban or getattr(wrapped, "promoted", None) and c.user_is_sponsor)...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/report.py
Add docstrings to meet PEP guidelines
#!/usr/bin/env python # The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public #...
--- +++ @@ -47,6 +47,11 @@ def generate_static_name(name, base=None): + """Generate a unique filename. + + Unique filenames are generated by base 64 encoding the first 64 bits of + the SHA1 hash. This hash string is added to the filename before the extension. + """ if base: path = os.p...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/static.py
Auto-generate documentation strings for this file
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -87,6 +87,7 @@ @classmethod def serialize_direction(cls, direction): + """Convert the DIRECTIONS enum to values used when storing.""" if direction not in cls.DIRECTIONS: raise ValueError("Invalid vote direction: %s" % direction) @@ -94,6 +95,7 @@ @classmethod ...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/vote.py
Add docstrings including usage examples
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,7 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +"""Converts msgtime for users to inbox_count, for inbox count tracking.""" import sys @@ -31,6 +32...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/scripts/migrate/backfill/msgtime_to_inbox_count.py
Add docstrings including usage examples
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,10 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +"""Fill in the num_gildings for users + +This is used to determine which gilding trophy level they sho...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/scripts/migrate/backfill/num_gildings.py
Help me comply with documentation standards
#!/usr/bin/python # The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # Lic...
--- +++ @@ -20,6 +20,21 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +""" +This is a tiny Flask app used for a couple of self-serve ad tracking +mechanisms. The URLs it pro...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/scripts/tracker.py
Add docstrings to incomplete code
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -31,6 +31,7 @@ def register_detector(cls): + """Collector of all the reddit detectors.""" detectorshub.register(cls()) return cls @@ -85,6 +86,7 @@ class RedditBrowser(RedditDetectorBase, Browser): + """Base class for all reddit specific browsers.""" # is_app denotes a client t...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/lib/utils/reddit_agent_parser.py
Document functions with detailed explanations
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -46,6 +46,16 @@ class AccountSRPrefs(object): + """Class for managing user recommendation preferences. + + Builds a user profile on-the-fly based on the user's subscriptions, + multireddits, and recent interactions with the recommender UI. + + Likes are used to generate recommendations, disli...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/recommend.py
Add docstrings for utility scripts
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -35,6 +35,15 @@ class ModAction(tdb_cassandra.UuidThing): + """ + Columns: + sr_id - Subreddit id36 + mod_id - Account id36 of moderator + action - specific name of action, must be in ModAction.actions + target_fullname - optional fullname of the target of the action + details - subc...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/modaction.py
Add docstrings to incomplete code
# -*- coding: utf-8 -*- # Author: Steven J. Bethard <steven.bethard@gmail.com>. # flake8: noqa __version__ = '1.2.1' __all__ = [ 'ArgumentParser', 'ArgumentError', 'ArgumentTypeError', 'FileType', 'HelpFormatter', 'ArgumentDefaultsHelpFormatter', 'RawDescriptionHelpFormatter', 'RawTextH...
--- +++ @@ -1,6 +1,66 @@ # -*- coding: utf-8 -*- # Author: Steven J. Bethard <steven.bethard@gmail.com>. # flake8: noqa +"""Command-line parsing library + +This module is an optparse-inspired command-line parsing library that: + + - handles both optional and positional arguments + - produces highly informative ...
https://raw.githubusercontent.com/wting/autojump/HEAD/bin/autojump_argparse.py
Add docstrings to my Python code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function import os import shutil import sys from codecs import open from collections import namedtuple from tempfile import NamedTemporaryFile from time import time from autojump_utils import create_dir from autojump_utils import is_osx from ...
--- +++ @@ -30,6 +30,11 @@ def dictify(entries): + """ + Converts a list of entries into a dictionary where + key = path + value = weight + """ result = {} for entry in entries: result[entry.path] = entry.weight @@ -37,6 +42,7 @@ def entriefy(data): + """Converts a d...
https://raw.githubusercontent.com/wting/autojump/HEAD/bin/autojump_data.py
Generate docstrings for each module
#!/usr/bin/env python2.7 from Queue import Queue import argparse import logging import multiprocessing import os import re import string import subprocess import sys import threading def parse_size(s): def mult(multiplier): return int(s[:-1])*multiplier if all(x in string.digits for x in s): ...
--- +++ @@ -30,6 +30,9 @@ class JobInputter(threading.Thread): + """ + Takes input originally from stdin through iq and sends it to the job + """ def __init__(self, job_name, popen, iq): self.job_name = job_name self.popen = popen @@ -59,6 +62,9 @@ class JobOutputter(threading.Th...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/scripts/hashdist.py
Write proper docstrings for these functions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re from difflib import SequenceMatcher from autojump_utils import is_python3 from autojump_utils import last if is_python3(): # pragma: no cover ifilter = filter imap = map os.getcwdu = os.getcwd else: from itertools import ifilter ...
--- +++ @@ -18,6 +18,24 @@ def match_anywhere(needles, haystack, ignore_case=False): + """ + Matches needles anywhere in the path as long as they're in the same (but + not necessary consecutive) order. + + For example: + needles = ['foo', 'baz'] + regex needle = r'.*foo.*baz.*' + ha...
https://raw.githubusercontent.com/wting/autojump/HEAD/bin/autojump_match.py
Add docstrings that explain inputs and outputs
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -19,6 +19,18 @@ # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### +""" +This module provides a Cassandra-backed lockless query cache. Rather than +doing complicated que...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/query_cache.py
Add standardized docstrings across the file
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, ...
--- +++ @@ -187,6 +187,12 @@ @classmethod def get_all(cls): + """ + Return collections in this order: + 1. SFW/NSFW + 2. Spotlighted + 3. Alphabetical + """ all_collections = CollectionStorage.get_all() sorted_collections = sorted(all_collections, k...
https://raw.githubusercontent.com/reddit-archive/reddit/HEAD/r2/r2/models/promo.py
Generate consistent docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function import errno import os import platform import re import shutil import sys import unicodedata from itertools import islice if sys.version_info[0] == 3: imap = map os.getcwdu = os.getcwd else: from itertools import imap d...
--- +++ @@ -19,6 +19,7 @@ def create_dir(path): + """Creates a directory atomically.""" try: os.makedirs(path) except OSError as exception: @@ -27,6 +28,7 @@ def encode_local(string): + """Converts string into user's preferred encoding.""" if is_python3(): return string ...
https://raw.githubusercontent.com/wting/autojump/HEAD/bin/autojump_utils.py
Auto-generate documentation strings for this file
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function import os import platform import shutil import sys sys.path.append('bin') from autojump_argparse import ArgumentParser # noqa SUPPORTED_SHELLS = ('bash', 'zsh', 'fish', 'tcsh') def cp(src, dest, dryrun=False): print('copying ...
--- +++ @@ -30,6 +30,7 @@ def modify_autojump_sh(etc_dir, share_dir, dryrun=False): + """Append custom installation path to autojump.sh""" custom_install = '\ \n# check custom install \ \nif [ -s %s/autojump.${shell} ]; then \ @@ -41,6 +42,7 @@ def modify_autojump_lua(clink_dir, bin_di...
https://raw.githubusercontent.com/wting/autojump/HEAD/install.py
Write beginner-friendly docstrings
from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件 from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型 from crawlers.bilibili.web.web_crawler import BilibiliWebCrawler # 导入哔哩哔哩web爬虫 router = APIRouter() BilibiliWebCrawler = BilibiliWebCrawler() # ...
--- +++ @@ -1,336 +1,697 @@-from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件 -from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型 - -from crawlers.bilibili.web.web_crawler import BilibiliWebCrawler # 导入哔哩哔哩web爬虫 - - -router = APIRouter() -BilibiliWeb...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/app/api/endpoints/bilibili_web.py
Write documentation strings for class attributes
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -87,6 +87,10 @@ @classmethod def gen_real_msToken(cls) -> str: + """ + 生成真实的msToken,当出现错误时返回虚假的值 + (Generate a real msToken and return a false value when an error occurs) + """ payload = json.dumps( { @@ -148,10 +152,15 @@ @classmethod ...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/douyin/web/utils.py
Document helper functions with docstrings
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -1,418 +1,435 @@-# ============================================================================== -# Copyright (C) 2021 Evil0ctal -# -# This file is part of the Douyin_TikTok_Download_API project. -# -# This project is licensed under the Apache License 2.0 (the "License"); -# you may not use this file except...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/bilibili/web/web_crawler.py
Add docstrings to my Python code
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -59,6 +59,10 @@ ) def md5_str_to_array(self, md5_str): + """ + 将字符串使用md5哈希算法转换为整数数组。 + Convert a string to an array of integers using the md5 hashing algorithm. + """ if isinstance(md5_str, str) and len(md5_str) > 32: return [ord(char) for char...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/douyin/web/xbogus.py
Add docstrings to existing functions
import time from typing import List from pydantic import BaseModel # API基础请求模型/Base Request Model class BaseRequestModel(BaseModel): iid: int = 7318518857994389254 device_id: int = 7318517321748022790 channel: str = "googleplay" app_name: str = "musical_ly" version_code: str = "300904" device...
--- +++ @@ -6,6 +6,9 @@ # API基础请求模型/Base Request Model class BaseRequestModel(BaseModel): + """ + Base Request Model for TikTok API + """ iid: int = 7318518857994389254 device_id: int = 7318517321748022790 channel: str = "googleplay" @@ -18,4 +21,7 @@ # Feed视频详情请求模型/Feed Video Detail Reques...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/tiktok/app/models.py
Write docstrings describing each step
from typing import List from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件 from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型 from crawlers.douyin.web.web_crawler import DouyinWebCrawler # 导入抖音Web爬虫 router = APIRouter() DouyinWebCrawler = DouyinWe...
--- +++ @@ -14,6 +14,26 @@ @router.get("/fetch_one_video", response_model=ResponseModel, summary="获取单个作品数据/Get single video data") async def fetch_one_video(request: Request, aweme_id: str = Query(example="7372484719365098803", description="作品id/Video id")): + """ + # [中文] + ### 用途:...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/app/api/endpoints/douyin_web.py
Write clean docstrings for readability
import os import re import json import yaml import httpx import asyncio from typing import Union from pathlib import Path from crawlers.utils.logger import logger from crawlers.douyin.web.xbogus import XBogus as XB from crawlers.utils.utils import ( gen_random_str, get_timestamp, extract_valid_urls, s...
--- +++ @@ -46,6 +46,10 @@ @classmethod def gen_real_msToken(cls) -> str: + """ + 生成真实的msToken,当出现错误时返回虚假的值 + (Generate a real msToken and return a false value when an error occurs) + """ payload = json.dumps( { @@ -105,10 +109,14 @@ @classmethod ...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/tiktok/web/utils.py
Write clean docstrings for readability
import asyncio from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件 from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型 # 爬虫/Crawler from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合爬虫 HybridCrawler = HybridCrawler() # 实例化混合爬虫 router ...
--- +++ @@ -17,6 +17,26 @@ async def hybrid_parsing_single_video(request: Request, url: str = Query(example="https://v.douyin.com/L4FJNR3/"), minimal: bool = Query(default=False)): + """ + # [中文] + ### 用途: + - 该接口用于解析抖音/TikTok单一视频...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/app/api/endpoints/hybrid_parsing.py
Add clean documentation to messy code
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -66,12 +66,31 @@ def gen_random_str(randomlength: int) -> str: + """ + 根据传入长度产生随机字符串 (Generate a random string based on the given length) + + Args: + randomlength (int): 需要生成的随机字符串的长度 (The length of the random string to be generated) + + Returns: + str: 生成的随机字符串 (The generated r...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/utils/utils.py
Create docstrings for API functions
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -51,6 +51,10 @@ super().__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): + """ + 重写默认的类实例化方法。当尝试创建类的一个新实例时,此方法将被调用。 + 如果已经有一个与参数匹配的实例存在,则返回该实例;否则创建一个新实例。 + """ key = (cls, args, frozenset(kwargs.items())) with cls._lock: i...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/utils/logger.py
Add docstrings that explain logic
from typing import List from fastapi import APIRouter, Query, Body, Request, HTTPException # 导入FastAPI组件 from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型 from crawlers.tiktok.web.web_crawler import TikTokWebCrawler # 导入TikTokWebCrawler类 router = APIRouter() TikTokWebCrawler ...
--- +++ @@ -16,6 +16,26 @@ summary="获取单个作品数据/Get single video data") async def fetch_one_video(request: Request, itemId: str = Query(example="7339393672959757570", description="作品id/Video id")): + """ + # [中文] + ### 用途: + - 获取单个作品数据 + ### 参数: + - itemId: 作品id ...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/app/api/endpoints/tiktok_web.py
Add docstrings to clarify complex logic
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -349,6 +349,13 @@ return await WebCastIdFetcher.get_all_webcast_id(urls) async def update_cookie(self, cookie: str): + """ + 更新指定服务的Cookie + + Args: + service: 服务名称 (如: douyin_web) + cookie: 新的Cookie值 + """ global config ...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/douyin/web/web_crawler.py
Generate docstrings with parameter types
from random import choice from random import randint from random import random from re import compile from time import time from urllib.parse import urlencode from urllib.parse import quote from gmssl import sm3, func __all__ = ["ABogus", ] class ABogus: __filter = compile(r'%([0-9A-F]{2})') __arguments = [...
--- +++ @@ -1,3 +1,19 @@+""" +Original Author: +This file is from https://github.com/JoeanAmier/TikTokDownloader +And is licensed under the GNU General Public License v3.0 +If you use this code, please keep this license and the original author information. + +Modified by: +And this file is now a part of the https://git...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/douyin/web/abogus.py
Write proper docstrings for these functions
# ============================================================================== # Copyright (C) 2021 Evil0ctal # # This file is part of the Douyin_TikTok_Download_API project. # # This project is licensed under the Apache License 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
--- +++ @@ -54,6 +54,9 @@ class BaseCrawler: + """ + 基础爬虫客户端 (Base crawler client) + """ def __init__( self, @@ -99,17 +102,49 @@ ) async def fetch_response(self, endpoint: str) -> Response: + """获取数据 (Get data) + + Args: + endpoint (str): 接口地址 (E...
https://raw.githubusercontent.com/Evil0ctal/Douyin_TikTok_Download_API/HEAD/crawlers/base_crawler.py
Create Google-style docstrings for my code
import math import random from time import time SIZE = 9 GAMES = 200 KOMI = 7.5 EMPTY, WHITE, BLACK = 0, 1, 2 SHOW = {EMPTY: '.', WHITE: 'o', BLACK: 'x'} PASS = -1 MAXMOVES = SIZE * SIZE * 3 TIMESTAMP = 0 MOVES = 0 def to_pos(x, y): return y * SIZE + x def to_xy(pos): y, x = divmod(pos, SIZE) return x,...
--- +++ @@ -1,3 +1,6 @@+""" +Go board game +""" import math import random from time import time @@ -322,6 +325,7 @@ self.parent = None def play(self, board): + """ uct tree search """ color = board.color node = self path = [node] @@ -344,6 +348,7 @@ self.updat...
https://raw.githubusercontent.com/exaloop/codon/HEAD/bench/codon/go.py
Generate consistent docstrings
# https://stackoverflow.com/questions/73473074/speed-up-set-partition-generation-by-skipping-ones-with-subsets-smaller-or-large import sys import time def conforms(candidate, minsize, forgive): deficit = 0 for p in candidate: need = minsize - len(p) if need > 0: deficit += need ...
--- +++ @@ -3,6 +3,10 @@ import time def conforms(candidate, minsize, forgive): + """ + Check if partition `candidate` is at most `forgive` additions from making + all its elements conform to having minimum size `minsize` + """ deficit = 0 for p in candidate: need = minsize - len(p) @@...
https://raw.githubusercontent.com/exaloop/codon/HEAD/bench/codon/set_partition.py
Add minimal docstrings for each function
import math import random import sys import time DEFAULT_THICKNESS = 1.0 DEFAULT_WIDTH = 2048 #256 DEFAULT_HEIGHT = 2048 #256 DEFAULT_ITERATIONS = 1000000 #5000 DEFAULT_RNG_SEED = 1234 class GVector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def Ma...
--- +++ @@ -1,3 +1,8 @@+"""create chaosgame-like fractals +Copyright (C) 2005 Carl Friedrich Bolz + +adapted by @arshajii for Codon +""" import math import random @@ -56,8 +61,12 @@ class Spline(object): + """Class for representing B-Splines and NURBS of arbitrary degree""" def __init__(self, points, ...
https://raw.githubusercontent.com/exaloop/codon/HEAD/bench/codon/chaos.py
Create docstrings for each class method
# Generates API reference for Codon standard library # See CI workflow for usage import itertools import os import os.path import sys import collections import json from pathlib import Path # 1. Set up paths and load JSON json_path = os.path.abspath(sys.argv[1]) out_path = os.path.abspath(sys.argv[2]) roots = [os.pa...
--- +++ @@ -62,6 +62,7 @@ print(f" - Done with directory tree") def parse_docstr(s, level=0): + """Parse docstr s and indent it with level spaces""" s = s.split("\n") while s and s[0] == "": s = s[1:] @@ -75,6 +76,7 @@ return "\n".join((" " * level) + l for l in lines) def parse_type(a...
https://raw.githubusercontent.com/exaloop/codon/HEAD/scripts/docgen.py
Write docstrings that follow conventions
import os from baselines import logger from baselines.common.vec_env import VecEnvWrapper from gym.wrappers.monitoring import video_recorder class VecVideoRecorder(VecEnvWrapper): def __init__(self, venv, directory, record_video_trigger, video_length=200): VecEnvWrapper.__init__(self, venv) self...
--- +++ @@ -5,8 +5,21 @@ class VecVideoRecorder(VecEnvWrapper): + """ + Wrap VecEnv to record rendered image as mp4 video. + """ def __init__(self, venv, directory, record_video_trigger, video_length=200): + """ + # Arguments + venv: VecEnv to wrap + directory: Wh...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/vec_env/vec_video_recorder.py
Write proper docstrings for these functions
import numpy as np import tensorflow as tf from baselines.common import tf_util as U from baselines.common.tests.test_with_mpi import with_mpi from baselines import logger try: from mpi4py import MPI except ImportError: MPI = None class MpiAdamOptimizer(tf.train.AdamOptimizer): def __init__(self, comm, gra...
--- +++ @@ -9,6 +9,7 @@ MPI = None class MpiAdamOptimizer(tf.train.AdamOptimizer): + """Adam optimizer that averages gradients across mpi processes.""" def __init__(self, comm, grad_clip=None, mpi_rank_weight=1, **kwargs): self.comm = comm self.grad_clip = grad_clip @@ -50,6 +51,16 @@ ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/mpi_adam_optimizer.py
Write reusable docstrings
import tensorflow as tf import numpy as np import baselines.common.tf_util as U from baselines.a2c.utils import fc from tensorflow.python.ops import math_ops class Pd(object): def flatparam(self): raise NotImplementedError def mode(self): raise NotImplementedError def neglogp(self, x): ...
--- +++ @@ -5,6 +5,9 @@ from tensorflow.python.ops import math_ops class Pd(object): + """ + A particular probability distribution + """ def flatparam(self): raise NotImplementedError def mode(self): @@ -29,6 +32,9 @@ return self.__class__(self.flatparam()[idx]) class PdType(ob...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/distributions.py
Add docstrings to my Python code
from collections import OrderedDict import gym import numpy as np def copy_obs_dict(obs): return {k: np.copy(v) for k, v in obs.items()} def dict_to_obs(obs_dict): if set(obs_dict.keys()) == {None}: return obs_dict[None] return obs_dict def obs_space_info(obs_space): if isinstance(obs_sp...
--- +++ @@ -1,3 +1,6 @@+""" +Helpers for dealing with vectorized environments. +""" from collections import OrderedDict @@ -6,16 +9,32 @@ def copy_obs_dict(obs): + """ + Deep-copy an observation dict. + """ return {k: np.copy(v) for k, v in obs.items()} def dict_to_obs(obs_dict): + """ + ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/vec_env/util.py
Turn comments into proper docstrings
import numpy as np import scipy.signal def discount(x, gamma): assert x.ndim >= 1 return scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1] def explained_variance(ypred,y): assert y.ndim == 1 and ypred.ndim == 1 vary = np.var(y) return np.nan if vary==0 else 1 - np.var(y-ypred)/vary def ...
--- +++ @@ -3,10 +3,36 @@ def discount(x, gamma): + """ + computes discounted sums along 0th dimension of x. + + inputs + ------ + x: ndarray + gamma: float + + outputs + ------- + y: ndarray with same shape as x, satisfying + + y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + g...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/math_util.py
Add docstrings to make code maintainable
import numpy as np def make_sample_her_transitions(replay_strategy, replay_k, reward_fun): if replay_strategy == 'future': future_p = 1 - (1. / (1 + replay_k)) else: # 'replay_strategy' == 'none' future_p = 0 def _sample_her_transitions(episode_batch, batch_size_in_transitions): ...
--- +++ @@ -2,12 +2,23 @@ def make_sample_her_transitions(replay_strategy, replay_k, reward_fun): + """Creates a sample function that can be used for HER experience replay. + + Args: + replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none', + regular DDPG experien...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/her/her_sampler.py
Add docstrings with type hints explained
import gym import numpy as np import os import pickle import random import tempfile import zipfile def zipsame(*seqs): L = len(seqs[0]) assert all(len(seq) == L for seq in seqs[1:]) return zip(*seqs) class EzPickle(object): def __init__(self, *args, **kwargs): self._ezpickle_args = args ...
--- +++ @@ -14,6 +14,24 @@ class EzPickle(object): + """Objects that are pickled and unpickled via their constructor + arguments. + + Example usage: + + class Dog(Animal, EzPickle): + def __init__(self, furcolor, tailkind="bushy"): + Animal.__init__() + EzPic...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/misc_util.py
Add docstrings for production code
import time import functools import numpy as np import tensorflow as tf from baselines import logger from baselines.common import set_global_seeds from baselines.common.policies import build_policy from baselines.common.tf_util import get_session, save_variables, load_variables from baselines.common.vec_env.vec_frame_...
--- +++ @@ -23,6 +23,16 @@ return seq_to_batch(vars[:-1], flat) def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma): + """ + Calculates q_retrace targets + + :param R: Rewards + :param D: Dones + :param q_i: Q values for actions taken + :param v: V values + :param rho_i: Importance weig...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/acer/acer.py
Create docstrings for each class method
import operator class SegmentTree(object): def __init__(self, capacity, operation, neutral_element): assert capacity > 0 and capacity & (capacity - 1) == 0, "capacity must be positive and a power of 2." self._capacity = capacity self._value = [neutral_element for _ in range(2 * capacity)] ...
--- +++ @@ -3,6 +3,31 @@ class SegmentTree(object): def __init__(self, capacity, operation, neutral_element): + """Build a Segment Tree data structure. + + https://en.wikipedia.org/wiki/Segment_tree + + Can be used as regular array, but with two + important differences: + + ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/segment_tree.py
Document helper functions with docstrings
import numpy as np import random from baselines.common.segment_tree import SumSegmentTree, MinSegmentTree class ReplayBuffer(object): def __init__(self, size): self._storage = [] self._maxsize = size self._next_idx = 0 def __len__(self): return len(self._storage) def add...
--- +++ @@ -6,6 +6,14 @@ class ReplayBuffer(object): def __init__(self, size): + """Create Replay buffer. + + Parameters + ---------- + size: int + Max number of transitions to store in the buffer. When the buffer + overflows the old memories are dropped. + ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/deepq/replay_buffer.py
Write proper docstrings for these functions
import numpy as np import tensorflow as tf # pylint: ignore-module import copy import os import functools import collections import multiprocessing def switch(condition, then_expression, else_expression): x_shape = copy.copy(then_expression.get_shape()) x = tf.cond(tf.cast(condition, 'bool'), ...
--- +++ @@ -7,6 +7,15 @@ import multiprocessing def switch(condition, then_expression, else_expression): + """Switches between two operations depending on a scalar value (int or bool). + Note that both `then_expression` and `else_expression` + should be symbolic tensors of the *same shape*. + + # Argumen...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/tf_util.py
Add minimal docstrings for each function
import time import functools import tensorflow as tf from baselines import logger from baselines.common import set_global_seeds, explained_variance from baselines.common import tf_util from baselines.common.policies import build_policy from baselines.a2c.utils import Scheduler, find_trainable_variables from baselin...
--- +++ @@ -18,6 +18,18 @@ class Model(object): + """ + We use this class to : + __init__: + - Creates the step_model + - Creates the train_model + + train(): + - Make the training part (feedforward and retropropagation of gradients) + + save/load(): + - Save l...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/a2c/a2c.py
Add docstrings that explain purpose and usage
import numpy as np import os os.environ.setdefault('PATH', '') from collections import deque import gym from gym import spaces import cv2 cv2.ocl.setUseOpenCL(False) from .wrappers import TimeLimit class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): gym.Wrapper.__init__(self, env) ...
--- +++ @@ -11,6 +11,9 @@ class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): + """Sample initial states by taking random number of no-ops on reset. + No-op is assumed to be action 0. + """ gym.Wrapper.__init__(self, env) self.noop_max = noop_max ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/atari_wrappers.py
Add docstrings to meet PEP guidelines
import os import tempfile import tensorflow as tf import zipfile import cloudpickle import numpy as np import baselines.common.tf_util as U from baselines.common.tf_util import load_variables, save_variables from baselines import logger from baselines.common.schedules import LinearSchedule from baselines.common impor...
--- +++ @@ -53,6 +53,7 @@ return self._act([observation], **kwargs), None, None, None def save_act(self, path=None): + """Save model to a pickle located at `path`""" if path is None: path = os.path.join(logger.get_dir(), "model.pkl") @@ -75,6 +76,19 @@ def load_act(path...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/deepq/deepq.py
Write docstrings that follow conventions
import tensorflow as tf import numpy as np import re # flake8: noqa F403, F405 from baselines.acktr.kfac_utils import * from functools import reduce KFAC_OPS = ['MatMul', 'Conv2D', 'BiasAdd'] KFAC_DEBUG = False class KfacOptimizer(): # note that KfacOptimizer will be truly synchronous (and thus deterministic) ...
--- +++ @@ -438,6 +438,8 @@ return statsUpdates def apply_stats(self, statsUpdates): + """ compute stats and update/apply the new stats to the running average + """ def updateAccumStats(): if self._full_stats_init: @@ -534,6 +536,7 @@ return self.stats_eigen ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/acktr/kfac.py
Add docstrings with type hints explained
import matplotlib.pyplot as plt import os.path as osp import json import os import numpy as np import pandas from collections import defaultdict, namedtuple from baselines.bench import monitor from baselines.logger import read_json, read_csv def smooth(y, radius, mode='two_sided', valid_only=False): assert mode in...
--- +++ @@ -9,6 +9,17 @@ from baselines.logger import read_json, read_csv def smooth(y, radius, mode='two_sided', valid_only=False): + ''' + Smooth signal y, where radius is determines the size of the window + + mode='twosided': + average over the window [max(index - radius, 0), min(index + radius, l...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/plot_util.py
Generate consistent documentation across files
import numpy as np import tensorflow as tf from baselines.a2c import utils from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch from baselines.common.mpi_running_mean_std import RunningMeanStd mapping = {} def register(name): def _thunk(func): mapping[name] = func retur...
--- +++ @@ -13,6 +13,9 @@ return _thunk def nature_cnn(unscaled_images, **conv_kwargs): + """ + CNN from Nature paper. + """ scaled_images = tf.cast(unscaled_images, tf.float32) / 255. activ = tf.nn.relu h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2), @@ ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/models.py
Generate docstrings with examples
from baselines.common.input import observation_input from baselines.common.tf_util import adjust_shape # ================================================================ # Placeholders # ================================================================ class TfInput(object): def __init__(self, name="(unnamed)"): ...
--- +++ @@ -8,17 +8,26 @@ class TfInput(object): def __init__(self, name="(unnamed)"): + """Generalized Tensorflow placeholder. The main differences are: + - possibly uses multiple placeholders internally and returns multiple values + - can apply light postprocessing to the value fee...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/deepq/utils.py
Improve my code by adding docstrings
import numpy as np from .vec_env import VecEnv from .util import copy_obs_dict, dict_to_obs, obs_space_info class DummyVecEnv(VecEnv): def __init__(self, env_fns): self.envs = [fn() for fn in env_fns] env = self.envs[0] VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_s...
--- +++ @@ -3,7 +3,18 @@ from .util import copy_obs_dict, dict_to_obs, obs_space_info class DummyVecEnv(VecEnv): + """ + VecEnv that does runs multiple environments sequentially, that is, + the step and reset commands are send to one environment at a time. + Useful when debugging and when num_env == 1 (i...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/vec_env/dummy_vec_env.py
Create docstrings for API functions
import tensorflow as tf from baselines.common import tf_util from baselines.a2c.utils import fc from baselines.common.distributions import make_pdtype from baselines.common.input import observation_placeholder, encode_observation from baselines.common.tf_util import adjust_shape from baselines.common.mpi_running_mean_s...
--- +++ @@ -11,8 +11,27 @@ class PolicyWithValue(object): + """ + Encapsulates fields and methods for RL policy and value function estimation with shared parameters + """ def __init__(self, env, observations, latent, estimate_q=False, vf_latent=None, sess=None, **tensors): + """ + Para...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/policies.py
Fully document this Python code with docstrings
import os try: from mpi4py import MPI except ImportError: MPI = None import gym from gym.wrappers import FlattenObservation, FilterObservation from baselines import logger from baselines.bench import Monitor from baselines.common import set_global_seeds from baselines.common.atari_wrappers import make_atari, ...
--- +++ @@ -1,3 +1,6 @@+""" +Helpers for scripts like run_atari.py. +""" import os try: @@ -25,6 +28,9 @@ gamestate=None, initializer=None, force_dummy=False): + """ + Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo. + """ wrapper_kwa...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/cmd_util.py
Document functions with clear intent
import multiprocessing as mp import numpy as np from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars def worker(remote, parent_remote, env_fn_wrappers): def step_env(env, action): ob, reward, done, info = env.step(action) if done: ob = env.reset() return ob, rew...
--- +++ @@ -37,7 +37,18 @@ class SubprocVecEnv(VecEnv): + """ + VecEnv that runs multiple environments in parallel in subproceses and communicates with them via pipes. + Recommended to use when num_envs > 1 and step() can be a bottleneck. + """ def __init__(self, env_fns, spaces=None, context='spaw...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/vec_env/subproc_vec_env.py
Help me write clear docstrings
import contextlib import os from abc import ABC, abstractmethod from baselines.common.tile_images import tile_images class AlreadySteppingError(Exception): def __init__(self): msg = 'already running an async step' Exception.__init__(self, msg) class NotSteppingError(Exception): def __init_...
--- +++ @@ -5,6 +5,10 @@ from baselines.common.tile_images import tile_images class AlreadySteppingError(Exception): + """ + Raised when an asynchronous step is running while + step_async() is called again. + """ def __init__(self): msg = 'already running an async step' @@ -12,6 +16,10 @@...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/vec_env/vec_env.py
Add docstrings to make code maintainable
import multiprocessing as mp import numpy as np from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars import ctypes from baselines import logger from .util import dict_to_obs, obs_space_info, obs_to_dict _NP_TO_CT = {np.float32: ctypes.c_float, np.int32: ctypes.c_int32, np.int...
--- +++ @@ -1,3 +1,6 @@+""" +An interface for asynchronous vectorized environments. +""" import multiprocessing as mp import numpy as np @@ -15,8 +18,15 @@ class ShmemVecEnv(VecEnv): + """ + Optimized version of SubprocVecEnv that uses shared variables to communicate observations. + """ def __in...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/vec_env/shmem_vec_env.py
Add clean documentation to messy code
import tensorflow as tf import baselines.common.tf_util as U def scope_vars(scope, trainable_only=False): return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.GLOBAL_VARIABLES, scope=scope if isinstance(scope, str) else scope.name ) def scope_name():...
--- +++ @@ -1,8 +1,117 @@+"""Deep Q learning graph + +The functions in this file can are used to create the following functions: + +======= act ======== + + Function to chose an action given an observation + + Parameters + ---------- + observation: object + Observation that can be feed into the outpu...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/deepq/build_graph.py
Generate docstrings for script automation
from collections import deque import cv2 cv2.ocl.setUseOpenCL(False) from .atari_wrappers import WarpFrame, ClipRewardEnv, FrameStack, ScaledFloatFrame from .wrappers import TimeLimit import numpy as np import gym class StochasticFrameSkip(gym.Wrapper): def __init__(self, env, n, stickprob): gym.Wrapper._...
--- +++ @@ -47,6 +47,9 @@ class PartialFrameStack(gym.Wrapper): def __init__(self, env, k, channel=1): + """ + Stack one channel (channel keyword) from previous frames + """ gym.Wrapper.__init__(self, env) shp = env.observation_space.shape self.channel = channel @@...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/retro_wrappers.py
Add docstrings to existing functions
import numpy as np import tensorflow as tf from gym.spaces import Discrete, Box, MultiDiscrete def observation_placeholder(ob_space, batch_size=None, name='Ob'): assert isinstance(ob_space, Discrete) or isinstance(ob_space, Box) or isinstance(ob_space, MultiDiscrete), \ 'Can only deal with Discrete and Bo...
--- +++ @@ -3,6 +3,23 @@ from gym.spaces import Discrete, Box, MultiDiscrete def observation_placeholder(ob_space, batch_size=None, name='Ob'): + ''' + Create placeholder to feed observations into of the size appropriate to the observation space + + Parameters: + ---------- + + ob_space: gym.Space ...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/input.py
Add docstrings explaining edge cases
class Schedule(object): def value(self, t): raise NotImplementedError() class ConstantSchedule(object): def __init__(self, value): self._v = value def value(self, t): return self._v def linear_interpolation(l, r, alpha): return l + alpha * (r - l) class PiecewiseSchedule...
--- +++ @@ -1,15 +1,33 @@+"""This file is used for specifying various schedules that evolve over +time throughout the execution of the algorithm, such as: + - learning rate for the optimizer + - exploration epsilon for the epsilon greedy exploration strategy + - beta parameter for beta parameter in prioritized replay +...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/schedules.py
Create docstrings for each class method
from collections import OrderedDict import numpy as np import tensorflow as tf from tensorflow.contrib.staging import StagingArea from baselines import logger from baselines.her.util import ( import_function, store_args, flatten_grads, transitions_in_episode_batch, convert_episode_to_batch_major) from baselines.h...
--- +++ @@ -26,6 +26,42 @@ rollout_batch_size, subtract_goals, relative_goals, clip_pos_returns, clip_return, bc_loss, q_filter, num_demo, demo_batch_size, prm_loss_weight, aux_loss_weight, sample_transitions, gamma, reuse=False, **kwargs): + """Implementation...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/her/ddpg.py
Generate consistent docstrings
import tensorflow as tf import numpy as np from baselines.common.mpi_running_mean_std import RunningMeanStd from baselines.common import tf_util as U def logsigmoid(a): return -tf.nn.softplus(-a) """ Reference: https://github.com/openai/imitation/blob/99fbccf3e060b6e6c739bdf209758620fcdefd3c/policyopt/thutil.py#...
--- +++ @@ -1,3 +1,7 @@+''' +Reference: https://github.com/openai/imitation +I follow the architecture from the official repository +''' import tensorflow as tf import numpy as np @@ -5,6 +9,7 @@ from baselines.common import tf_util as U def logsigmoid(a): + '''Equivalent to tf.log(tf.sigmoid(a))''' retu...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/gail/adversary.py
Help me write clear docstrings
from collections import defaultdict import os, numpy as np import platform import shutil import subprocess import warnings import sys try: from mpi4py import MPI except ImportError: MPI = None def sync_from_root(sess, variables, comm=None): if comm is None: comm = MPI.COMM_WORLD import tensorflow as ...
--- +++ @@ -13,6 +13,12 @@ def sync_from_root(sess, variables, comm=None): + """ + Send the root node's parameters to every worker. + Arguments: + sess: the TensorFlow session. + variables: all parameter variables including optimizer's + """ if comm is None: comm = MPI.COMM_WORLD imp...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/common/mpi_util.py
Please document this code using docstrings
import os import subprocess import sys import importlib import inspect import functools import tensorflow as tf import numpy as np from baselines.common import tf_util as U def store_args(method): argspec = inspect.getfullargspec(method) defaults = {} if argspec.defaults is not None: defaults = ...
--- +++ @@ -12,6 +12,8 @@ def store_args(method): + """Stores provided method args as instance attributes. + """ argspec = inspect.getfullargspec(method) defaults = {} if argspec.defaults is not None: @@ -37,6 +39,8 @@ def import_function(spec): + """Import a function identified by a str...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/her/util.py
Add docstrings that explain logic
import os import sys import shutil import os.path as osp import json import time import datetime import tempfile from collections import defaultdict from contextlib import contextmanager DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 class KVWriter(object): def writekvs(self, kvs): raise NotImpl...
--- +++ @@ -137,6 +137,9 @@ class TensorBoardOutputFormat(KVWriter): + """ + Dumps key/value pairs into TensorBoard's numeric format. + """ def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir @@ -188,16 +191,30 @@ # ================================================...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/logger.py
Generate docstrings with parameter types
from collections import deque import numpy as np import pickle from baselines.her.util import convert_episode_to_batch_major, store_args class RolloutWorker: @store_args def __init__(self, venv, policy, dims, logger, T, rollout_batch_size=1, exploit=False, use_target_net=False, compute_Q=F...
--- +++ @@ -12,6 +12,23 @@ def __init__(self, venv, policy, dims, logger, T, rollout_batch_size=1, exploit=False, use_target_net=False, compute_Q=False, noise_eps=0, random_eps=0, history_len=100, render=False, monitor=False, **kwargs): + """Rollout worker generates experi...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/her/rollout.py
Write documentation strings for class attributes
import numpy as np from baselines.common.runners import AbstractEnvRunner class Runner(AbstractEnvRunner): def __init__(self, *, env, model, nsteps, gamma, lam): super().__init__(env=env, model=model, nsteps=nsteps) # Lambda used in GAE (General Advantage Estimation) self.lam = lam ...
--- +++ @@ -2,6 +2,14 @@ from baselines.common.runners import AbstractEnvRunner class Runner(AbstractEnvRunner): + """ + We use this object to make a mini batch of experiences + __init__: + - Initialize the runner + + run(): + - Make a mini batch + """ def __init__(self, *, env, model, nste...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/ppo2/runner.py
Add detailed docstrings explaining each function
import threading import numpy as np class ReplayBuffer: def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions): self.buffer_shapes = buffer_shapes self.size = size_in_transitions // T self.T = T self.sample_transitions = sample_transitions # self.bu...
--- +++ @@ -5,6 +5,15 @@ class ReplayBuffer: def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions): + """Creates a replay buffer. + + Args: + buffer_shapes (dict of ints): the shape for all buffers that are used in the replay + buffer + s...
https://raw.githubusercontent.com/openai/baselines/HEAD/baselines/her/replay_buffer.py
Add docstrings that explain purpose and usage
# Copyright 2019 Ram Rachum and collaborators. # This program is distributed under the MIT license. import abc import os import inspect import sys import datetime as datetime_module PY3 = (sys.version_info[0] == 3) PY2 = not PY3 if hasattr(abc, 'ABC'): ABC = abc.ABC else: class ABC(object): __metacla...
--- +++ @@ -1,5 +1,6 @@ # Copyright 2019 Ram Rachum and collaborators. # This program is distributed under the MIT license. +'''Python 2/3 compatibility''' import abc import os @@ -14,6 +15,9 @@ ABC = abc.ABC else: class ABC(object): + """Helper class that provides a standard way to create an ABC ...
https://raw.githubusercontent.com/cool-RR/PySnooper/HEAD/pysnooper/pycompat.py
Add verbose docstrings with examples
import zmq import numpy as np import msgpack import msgpack_numpy as m m.patch() from afy.utils import log def check_connection(socket, timeout=1000): old_rcvtimeo = socket.RCVTIMEO socket.RCVTIMEO = timeout try: data = msgpack.packb(([], {})) socket.send_data('hello', data) attr...
--- +++ @@ -27,8 +27,28 @@ class SerializingSocket(zmq.Socket): + """Numpy array serialization methods. + + Based on https://github.com/jeffbass/imagezmq/blob/master/imagezmq/imagezmq.py#L291 + + Used for sending / receiving OpenCV images, which are Numpy arrays. + Also used for sending / receiving jpg ...
https://raw.githubusercontent.com/alievk/avatarify-python/HEAD/afy/networking.py
Generate docstrings with examples
import random import time from functools import wraps from typing import Callable, List, Optional from weclone.utils.log import logger def retry_on_http_error( max_retries: int = 3, base_delay: float = 1.0, max_delay: float = 60.0, backoff_factor: float = 2.0, jitter: bool = True, retry_on_st...
--- +++ @@ -15,6 +15,18 @@ retry_on_status: Optional[List[int]] = None, retry_on_exceptions: Optional[List[type]] = None, ): + """ + HTTP请求重试装饰器,专门处理429状态码和其他网络错误 + + Args: + max_retries: 最大重试次数 + base_delay: 基础延迟时间(秒) + max_delay: 最大延迟时间(秒) + backoff_factor: 退避因子,每次重试延迟时间...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/utils/retry.py
Write docstrings that follow conventions
import functools import os import sys from pathlib import Path from typing import cast import click import pyjson5 from rich.console import Console from rich.panel import Panel from rich.text import Text from weclone.utils.config import load_config from weclone.utils.config_models import CliArgs from weclone.utils.lo...
--- +++ @@ -23,6 +23,10 @@ def clear_argv(func): + """ + Decorator: Clear sys.argv before calling the decorated function, keeping only the script name. Restore original sys.argv after calling. + Used to prevent arguments from being parsed by Hugging Face HfArgumentParser causing ValueError. + """ ...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/cli.py
Write docstrings for this repository
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import List from .models import ChatMessage @dataclass class ConversationStrategy(ABC): is_single_chat: bool @abstractmethod def is_same_conversation(self, history_msg: List[ChatMessage], current_msg: ChatMessage) -> bool...
--- +++ @@ -7,16 +7,19 @@ @dataclass class ConversationStrategy(ABC): + """Abstract base class for conversation strategies""" is_single_chat: bool @abstractmethod def is_same_conversation(self, history_msg: List[ChatMessage], current_msg: ChatMessage) -> bool: + """Determine if two messa...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/data/strategies.py
Improve documentation using docstrings
import json import os from abc import ABC, abstractmethod from dataclasses import dataclass from typing import List, cast import pandas as pd from langchain_core.prompts import PromptTemplate from tqdm import tqdm from weclone.core.inference.online_infer import OnlineLLM from weclone.data.models import QaPair, QaPair...
--- +++ @@ -17,14 +17,21 @@ @dataclass class CleaningStrategy(ABC): + """Abstract base class for data cleaning strategies, but provides common cleaning methods""" make_dataset_config: WCMakeDatasetConfig @abstractmethod def judge(self, data: List[QaPair]) -> None: + """ + Scoring ...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/data/clean/strategies.py
Add detailed documentation for each class
import csv import json import os import shutil import sys from datetime import datetime from typing import Dict, List from pandas import Timestamp from weclone.data.models import ChatMessage from weclone.utils.config_models import DataModality, WCMakeDatasetConfig from weclone.utils.log import logger class Telegram...
--- +++ @@ -14,6 +14,7 @@ class TelegramChatParser: + """Telegram chat parser that converts JSON format to data conforming to ChatMessage structure""" def __init__(self, config: WCMakeDatasetConfig): self.config = config @@ -35,6 +36,14 @@ } def get_message_type_and_content(self, m...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/data/chat_parsers/telegram_parser.py
Add docstrings that explain purpose and usage
from enum import Enum from typing import TYPE_CHECKING, List, Optional from loguru import logger from pydantic import BaseModel, Field, model_validator if TYPE_CHECKING: pass class StrEnum(str, Enum): def __str__(self) -> str: return self.value @classmethod def _missing_(cls, value): ...
--- +++ @@ -9,6 +9,11 @@ class StrEnum(str, Enum): + """ + Pydantic-friendly string enum base class + Supports direct string comparison, e.g.: `if platform == PlatformType.CHAT` + Also supports string literal comparison, e.g.: `if platform == "chat"` + """ def __str__(self) -> str: re...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/utils/config_models.py