Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|># of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Obtained from https://github.com/gavinandresen/bitcointools/
"""Encode/decode base58 in the same way that Bitcoin does
The original code has been ported to run on Python 2.x and Python 3.x.
However, the implementation is still a broken one. DO NOT USE.
"""
from __future__ import absolute_import
b = builtins.b
<|code_end|>
with the help of current file imports:
from mom import _compat
from mom import builtins
and context from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
, which may contain function names, class names, or code. Output only the next line. | ZERO_BYTE = _compat.ZERO_BYTE |
Predict the next line after this snippet: <|code_start|># Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Obtained from https://github.com/gavinandresen/bitcointools/
"""Encode/decode base58 in the same way that Bitcoin does
The original code has been ported to run on Python 2.x and Python 3.x.
However, the implementation is still a broken one. DO NOT USE.
"""
from __future__ import absolute_import
<|code_end|>
using the current file's imports:
from mom import _compat
from mom import builtins
and any relevant context from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
. Output only the next line. | b = builtins.b |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://goo.gl/9qEXu
# Public domain.
"""Generates a prime sieve."""
from __future__ import division
try:
# TODO(yesudeep): numpy import disabled temporarily until we can convert
# the generated list to Python native. Rename "nump" to "numpy" when ready.
def make_prime_sieve(max_n): # def _numpy_primesfrom2to(max_n):
"""Input n>=6, Returns a array of primes, 2 <= p < n"""
sieve = np.ones(max_n // 3 + (max_n % 6 == 2), dtype=np.bool)
sieve[0] = False
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from mom import _compat
import nump as np
and context:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
which might include code, classes, or functions. Output only the next line. | for i in _compat.range(int(max_n ** 0.5) // 3 + 1): |
Predict the next line for this snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""":synopsis: Routines used by ASCII-based base converters.
:module: mom.codec._base
.. autofunction:: base_encode
.. autofunction:: base_decode
.. autofunction:: base_to_uint
.. autofunction:: uint_to_base256
"""
from __future__ import absolute_import
# pylint: disable-msg=R0801
try: # pragma: no cover
psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
<|code_end|>
with the help of current file imports:
import psyco
from mom import _compat
from mom import builtins
from mom.codec import integer
and context from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/codec/integer.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def bytes_to_uint(raw_bytes):
# def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False):
, which may contain function names, class names, or code. Output only the next line. | ZERO_BYTE = _compat.ZERO_BYTE |
Here is a snippet: <|code_start|># pylint: disable-msg=R0801
try: # pragma: no cover
psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
ZERO_BYTE = _compat.ZERO_BYTE
EMPTY_BYTE = _compat.EMPTY_BYTE
def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True):
"""
Encodes raw bytes given a base.
:param raw_bytes:
Raw bytes to encode.
:param base:
Unsigned integer base.
:param base_bytes:
The ASCII bytes used in the encoded string. "Character set" or "alphabet".
:param base_zero:
"""
<|code_end|>
. Write the next line using the current file imports:
import psyco
from mom import _compat
from mom import builtins
from mom.codec import integer
and context from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/codec/integer.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def bytes_to_uint(raw_bytes):
# def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False):
, which may include functions, classes, or code. Output only the next line. | if not builtins.is_bytes(raw_bytes): |
Continue the code snippet: <|code_start|> psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
ZERO_BYTE = _compat.ZERO_BYTE
EMPTY_BYTE = _compat.EMPTY_BYTE
def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True):
"""
Encodes raw bytes given a base.
:param raw_bytes:
Raw bytes to encode.
:param base:
Unsigned integer base.
:param base_bytes:
The ASCII bytes used in the encoded string. "Character set" or "alphabet".
:param base_zero:
"""
if not builtins.is_bytes(raw_bytes):
raise TypeError("data must be raw bytes: got %r" %
type(raw_bytes).__name__)
<|code_end|>
. Use current file imports:
import psyco
from mom import _compat
from mom import builtins
from mom.codec import integer
and context (classes, functions, or code) from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/codec/integer.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def bytes_to_uint(raw_bytes):
# def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False):
. Output only the next line. | number = integer.bytes_to_uint(raw_bytes) |
Using the snippet: <|code_start|>
psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
# Follows ASCII order.
ASCII62_BYTES = (string.DIGITS +
string.ASCII_UPPERCASE +
string.ASCII_LOWERCASE).encode("ascii")
# Therefore, b"0" represents b"\0".
ASCII62_ORDS = dict((x, i) for i, x in enumerate(ASCII62_BYTES))
# Really, I don't understand why people use the non-ASCII order,
# but if you really like it that much, go ahead. Be my guest. Here
# is what you will need:
#
# Does not follow ASCII order.
ALT62_BYTES = (string.DIGITS +
string.ASCII_LOWERCASE +
string.ASCII_UPPERCASE).encode("ascii")
# Therefore, b"0" represents b"\0".
ALT62_ORDS = dict((x, i) for i, x in enumerate(ALT62_BYTES))
<|code_end|>
, determine the next line of code. You have imports:
import psyco
from mom import _compat
from mom import builtins
from mom import string
from mom.codec import _base
and context (class names, function names, or code) available:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/string.py
# ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
# ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE
# DIGITS = "0123456789"
# PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"""
# PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\
# ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c"""
# WHITESPACE = "\t\n\x0b\x0c\r "
#
# Path: mom/codec/_base.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True):
# def base_decode(encoded, base, base_ords, base_zero, powers):
# def base_to_uint(encoded,
# base,
# ord_lookup_table,
# powers):
# def uint_to_base256(number, encoded, base_zero):
. Output only the next line. | if _compat.HAVE_PYTHON3: |
Given the following code snippet before the placeholder: <|code_start|> psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
# Follows ASCII order.
ASCII62_BYTES = (string.DIGITS +
string.ASCII_UPPERCASE +
string.ASCII_LOWERCASE).encode("ascii")
# Therefore, b"0" represents b"\0".
ASCII62_ORDS = dict((x, i) for i, x in enumerate(ASCII62_BYTES))
# Really, I don't understand why people use the non-ASCII order,
# but if you really like it that much, go ahead. Be my guest. Here
# is what you will need:
#
# Does not follow ASCII order.
ALT62_BYTES = (string.DIGITS +
string.ASCII_LOWERCASE +
string.ASCII_UPPERCASE).encode("ascii")
# Therefore, b"0" represents b"\0".
ALT62_ORDS = dict((x, i) for i, x in enumerate(ALT62_BYTES))
if _compat.HAVE_PYTHON3:
<|code_end|>
, predict the next line using imports from the current file:
import psyco
from mom import _compat
from mom import builtins
from mom import string
from mom.codec import _base
and context including class names, function names, and sometimes code from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/string.py
# ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
# ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE
# DIGITS = "0123456789"
# PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"""
# PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\
# ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c"""
# WHITESPACE = "\t\n\x0b\x0c\r "
#
# Path: mom/codec/_base.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True):
# def base_decode(encoded, base, base_ords, base_zero, powers):
# def base_to_uint(encoded,
# base,
# ord_lookup_table,
# powers):
# def uint_to_base256(number, encoded, base_zero):
. Output only the next line. | ASCII62_BYTES = tuple(builtins.byte(x) for x in ASCII62_BYTES) |
Given snippet: <|code_start|>* Shorter URLs also implies that fewer bytes are transferred in HTTP responses.
* Bandwidth consumption is reduced by a noticeably large factor.
* Multiple versions of assets (if required).
Essentially, URLs shortened using base-58 or base-62 encoding can result
in a faster Web-browsing experience for end-users.
Functions
---------
.. autofunction:: b62encode
.. autofunction:: b62decode
"""
from __future__ import absolute_import
from __future__ import division
# pylint: disable-msg=R0801
try: # pragma: no cover
psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
# Follows ASCII order.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import psyco
from mom import _compat
from mom import builtins
from mom import string
from mom.codec import _base
and context:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/string.py
# ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
# ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE
# DIGITS = "0123456789"
# PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"""
# PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\
# ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c"""
# WHITESPACE = "\t\n\x0b\x0c\r "
#
# Path: mom/codec/_base.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True):
# def base_decode(encoded, base, base_ords, base_zero, powers):
# def base_to_uint(encoded,
# base,
# ord_lookup_table,
# powers):
# def uint_to_base256(number, encoded, base_zero):
which might include code, classes, or functions. Output only the next line. | ASCII62_BYTES = (string.DIGITS + |
Here is a snippet: <|code_start|>if _compat.HAVE_PYTHON3:
ASCII62_BYTES = tuple(builtins.byte(x) for x in ASCII62_BYTES)
ALT62_BYTES = tuple(builtins.byte(x) for x in ALT62_BYTES)
# If you're going to make people type stuff longer than this length
# I don't know what to tell you. Beyond this length powers
# are computed, so be careful if you care about computation speed.
# I think this is a VERY generous range. Decoding bytes fewer than 512
# will use this pre-computed lookup table, and hence, be faster.
POW_62 = tuple(62 ** power for power in range(512))
def b62encode(raw_bytes,
base_bytes=ASCII62_BYTES,
_padding=True):
"""
Base62 encodes a sequence of raw bytes. Zero-byte sequences are
preserved by default.
:param raw_bytes:
Raw bytes to encode.
:param base_bytes:
(Internal) The character set to use. Defaults to ``ASCII62_BYTES``
that uses natural ASCII order.
:param _padding:
(Internal) ``True`` (default) to include prefixed zero-byte sequence
padding converted to appropriate representation.
:returns:
Base-62 encoded bytes.
"""
<|code_end|>
. Write the next line using the current file imports:
import psyco
from mom import _compat
from mom import builtins
from mom import string
from mom.codec import _base
and context from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/string.py
# ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
# ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE
# DIGITS = "0123456789"
# PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"""
# PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\
# ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c"""
# WHITESPACE = "\t\n\x0b\x0c\r "
#
# Path: mom/codec/_base.py
# ZERO_BYTE = _compat.ZERO_BYTE
# EMPTY_BYTE = _compat.EMPTY_BYTE
# def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True):
# def base_decode(encoded, base, base_ords, base_zero, powers):
# def base_to_uint(encoded,
# base,
# ord_lookup_table,
# powers):
# def uint_to_base256(number, encoded, base_zero):
, which may include functions, classes, or code. Output only the next line. | return _base.base_encode(raw_bytes, 62, base_bytes, base_bytes[0], _padding) |
Using the snippet: <|code_start|>#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google Inc. 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
try:
except ImportError:
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
class Test_AttributeDict(unittest2.TestCase):
def test_behavior(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest2
import queue as Queue
import Queue
import threading
from mom import collections
and context (class names, function names, or code) available:
# Path: mom/collections.py
# class SetQueue(queue.Queue):
# class AttributeDict(dict):
# def _init(self, maxsize):
# def _put(self, item):
# def _get(self):
# def __init__(self, *args, **kw):
# def __repr__(self):
# def __delattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
. Output only the next line. | d = collections.AttributeDict(something="foobar", another_thing="haha") |
Here is a snippet: <|code_start|>
# TODO: Keep these functions around.
def bytearray_to_long(byte_array):
"""
Converts a byte array to long.
:param byte_array:
The byte array.
:returns:
Long.
"""
total = 0
multiplier = 1
for count in range(len(byte_array) - 1, -1, -1):
byte_val = byte_array[count]
total += multiplier * byte_val
multiplier *= 256
return total
def long_to_bytearray(num):
"""
Converts a long into a byte array.
:param num:
Long value
:returns:
Long.
"""
<|code_end|>
. Write the next line using the current file imports:
from array import array
from mom import builtins
and context from other files:
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
, which may include functions, classes, or code. Output only the next line. | bytes_count = builtins.integer_byte_length(num) |
Here is a snippet: <|code_start|> "truthy",
"union",
"unique",
"without",
]
# Higher-order functions that generate other functions.
def compose(function, *functions):
"""Composes a sequence of functions such that::
compose(g, f, s) -> g(f(s()))
:param functions:
An iterable of functions.
:returns:
A composition function.
"""
def _composition(a_func, b_func):
"""Composition."""
def _wrap(*args, **kwargs):
"""Wrapper."""
return a_func(b_func(*args, **kwargs))
return _wrap
<|code_end|>
. Write the next line using the current file imports:
import collections
import functools
import itertools
from itertools import ifilter as _ifilter
from itertools import ifilterfalse as _ifilterfalse
from itertools import imap as map
from mom import builtins
from mom.itertools import chain
from mom.itertools import starmap
and context from other files:
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/itertools.py
# class chain(object):
# """An iterator which yields elements from the given `iterables` until each
# iterable is exhausted.
#
# .. versionadded:: 0.2
# """
#
# @classmethod
# def from_iterable(cls, iterable):
# """Alternative constructor which takes an `iterable` yielding iterators,
# this can be used to chain an infinite number of iterators.
# """
# rv = object.__new__(cls)
# rv._init(iterable)
# return rv
#
# def __init__(self, *iterables):
# self._init(iterables)
#
# def _init(self, iterables):
# self.iterables = iter(iterables)
# self.current_iterable = iter([])
#
# def __iter__(self):
# return self
#
# def next(self):
# try:
# return self.current_iterable.next()
# except StopIteration:
# self.current_iterable = iter(self.iterables.next())
# return self.current_iterable.next()
#
# Path: mom/itertools.py
# def starmap(function, iterable):
# """Make an iterator that computes the function using arguments obtained from
# the iterable. Used instead of :func:`itertools.imap` when an argument
# parameters are already grouped in tuples from a single iterable (the data
# has been "pre-zipped"). The difference between :func:`itertools.imap` and
# :func:`starmap` parallels the distinction between ``function(a, b)`` and
# ``function(*c)``.
#
# .. note:: Software and documentation for this function are taken from
# CPython, :ref:`license details <psf-license>`.
# """
# for args in iterable:
# yield function(*args)
, which may include functions, classes, or code. Output only the next line. | return builtins.reduce(_composition, functions, function) |
Based on the snippet: <|code_start|>
def ichunks(iterable, size, *args, **kwargs):
"""Splits an iterable into iterators for chunks each of specified size.
:param iterable:
The iterable to split. Must be an ordered sequence to guarantee order.
:param size:
Chunk size.
:param padding:
If a pad value is specified appropriate multiples of it will be
appended to the end of the iterator if the size is not an integral
multiple of the length of the iterable:
map(tuple, ichunks("aaabccd", 3, "-"))
-> [("a", "a", "a"), ("b", "c", "c"), ("d", "-", "-")]
map(tuple, ichunks("aaabccd", 3, None))
-> [("a", "a", "a"), ("b", "c", "c"), ("d", None, None)]
If no padding is specified, nothing will be appended if the
chunk size is not an integral multiple of the length of the
iterable. That is, the last chunk will have chunk size less than
the specified chunk size. :yields: Generator of chunk iterators.
"""
length = len(iterable)
if args or kwargs:
padding = kwargs["padding"] if kwargs else args[0]
for i in builtins.range(0, length, size):
yield itertools.islice(
<|code_end|>
, predict the immediate next line with the help of imports:
import collections
import functools
import itertools
from itertools import ifilter as _ifilter
from itertools import ifilterfalse as _ifilterfalse
from itertools import imap as map
from mom import builtins
from mom.itertools import chain
from mom.itertools import starmap
and context (classes, functions, sometimes code) from other files:
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/itertools.py
# class chain(object):
# """An iterator which yields elements from the given `iterables` until each
# iterable is exhausted.
#
# .. versionadded:: 0.2
# """
#
# @classmethod
# def from_iterable(cls, iterable):
# """Alternative constructor which takes an `iterable` yielding iterators,
# this can be used to chain an infinite number of iterators.
# """
# rv = object.__new__(cls)
# rv._init(iterable)
# return rv
#
# def __init__(self, *iterables):
# self._init(iterables)
#
# def _init(self, iterables):
# self.iterables = iter(iterables)
# self.current_iterable = iter([])
#
# def __iter__(self):
# return self
#
# def next(self):
# try:
# return self.current_iterable.next()
# except StopIteration:
# self.current_iterable = iter(self.iterables.next())
# return self.current_iterable.next()
#
# Path: mom/itertools.py
# def starmap(function, iterable):
# """Make an iterator that computes the function using arguments obtained from
# the iterable. Used instead of :func:`itertools.imap` when an argument
# parameters are already grouped in tuples from a single iterable (the data
# has been "pre-zipped"). The difference between :func:`itertools.imap` and
# :func:`starmap` parallels the distinction between ``function(a, b)`` and
# ``function(*c)``.
#
# .. note:: Software and documentation for this function are taken from
# CPython, :ref:`license details <psf-license>`.
# """
# for args in iterable:
# yield function(*args)
. Output only the next line. | chain(iterable, |
Based on the snippet: <|code_start|> one dictionary the predicate is true and for those of the other it is false.
:param predicate:
Function of the format::
f(key, value) -> bool
:param dictionary:
Dictionary.
:returns:
Tuple (selected_dict, rejected_dict)
"""
def _pred(tup):
"""Apply arguments to predicate."""
return predicate(*tup)
pairs_a, pairs_b = partition(_pred, dictionary.items())
return dict(pairs_a), dict(pairs_b)
def map_dict(transform, dictionary):
"""Maps over a dictionary of key, value pairs.
:param transform:
Function that accepts two arguments ``key, value``
and returns a ``(new key, new value)`` pair.
:returns:
New dictionary of ``new key=new value`` pairs.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import collections
import functools
import itertools
from itertools import ifilter as _ifilter
from itertools import ifilterfalse as _ifilterfalse
from itertools import imap as map
from mom import builtins
from mom.itertools import chain
from mom.itertools import starmap
and context (classes, functions, sometimes code) from other files:
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
#
# Path: mom/itertools.py
# class chain(object):
# """An iterator which yields elements from the given `iterables` until each
# iterable is exhausted.
#
# .. versionadded:: 0.2
# """
#
# @classmethod
# def from_iterable(cls, iterable):
# """Alternative constructor which takes an `iterable` yielding iterators,
# this can be used to chain an infinite number of iterators.
# """
# rv = object.__new__(cls)
# rv._init(iterable)
# return rv
#
# def __init__(self, *iterables):
# self._init(iterables)
#
# def _init(self, iterables):
# self.iterables = iter(iterables)
# self.current_iterable = iter([])
#
# def __iter__(self):
# return self
#
# def next(self):
# try:
# return self.current_iterable.next()
# except StopIteration:
# self.current_iterable = iter(self.iterables.next())
# return self.current_iterable.next()
#
# Path: mom/itertools.py
# def starmap(function, iterable):
# """Make an iterator that computes the function using arguments obtained from
# the iterable. Used instead of :func:`itertools.imap` when an argument
# parameters are already grouped in tuples from a single iterable (the data
# has been "pre-zipped"). The difference between :func:`itertools.imap` and
# :func:`starmap` parallels the distinction between ``function(a, b)`` and
# ``function(*c)``.
#
# .. note:: Software and documentation for this function are taken from
# CPython, :ref:`license details <psf-license>`.
# """
# for args in iterable:
# yield function(*args)
. Output only the next line. | return dict(starmap(transform or (lambda k, v: (k, v)), |
Using the snippet: <|code_start|>.. autofunction:: uint_to_bytes
"""
# This module contains only the implementations that were bench-marked
# to be the fastest. See _alt_integer.py for alternative but slower
# implementations.
from __future__ import absolute_import
from __future__ import division
# pylint: disable-msg=R0801
try: # pragma: no cover
psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
__all__ = [
"bytes_to_uint",
"uint_to_bytes",
]
<|code_end|>
, determine the next line of code. You have imports:
import psyco
import binascii
import struct
from mom import _compat
from mom import builtins
and context (class names, function names, or code) available:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
. Output only the next line. | ZERO_BYTE = _compat.ZERO_BYTE |
Predict the next line for this snippet: <|code_start|> psyco.full()
except ImportError: # pragma: no cover
psyco = None
# pylint: enable-msg=R0801
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
__all__ = [
"bytes_to_uint",
"uint_to_bytes",
]
ZERO_BYTE = _compat.ZERO_BYTE
EMPTY_BYTE = _compat.EMPTY_BYTE
def bytes_to_uint(raw_bytes):
"""
Converts a series of bytes into an unsigned integer.
:param raw_bytes:
Raw bytes (base-256 representation).
:returns:
Unsigned integer.
"""
<|code_end|>
with the help of current file imports:
import psyco
import binascii
import struct
from mom import _compat
from mom import builtins
and context from other files:
# Path: mom/_compat.py
# INT_MAX = sys.maxsize
# INT_MAX = sys.maxint
# INT64_MAX = (1 << 63) - 1
# INT32_MAX = (1 << 31) - 1
# INT16_MAX = (1 << 15) - 1
# UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L
# UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1)
# UINT32_MAX = 0xffffffff # ((1 << 32) - 1)
# UINT16_MAX = 0xffff # ((1 << 16) - 1)
# UINT8_MAX = 0xff
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# MACHINE_WORD_SIZE = 32
# UINT_MAX = UINT32_MAX
# MACHINE_WORD_SIZE = 64
# UINT_MAX = UINT64_MAX
# LONG_TYPE = long
# LONG_TYPE = int
# INT_TYPE = long
# INTEGER_TYPES = (int, long)
# INT_TYPE = int
# INTEGER_TYPES = (int,)
# BYTES_TYPE = bytes
# BYTES_TYPE = str
# UNICODE_TYPE = unicode
# BASESTRING_TYPE = basestring
# HAVE_PYTHON3 = False
# UNICODE_TYPE = str
# BASESTRING_TYPE = (str, bytes)
# HAVE_PYTHON3 = True
# ZERO_BYTE = byte_literal("\x00")
# EMPTY_BYTE = byte_literal("")
# EQUAL_BYTE = byte_literal("=")
# PLUS_BYTE = byte_literal("+")
# HYPHEN_BYTE = byte_literal("-")
# FORWARD_SLASH_BYTE = byte_literal("/")
# UNDERSCORE_BYTE = byte_literal("_")
# DIGIT_ZERO_BYTE = byte_literal("0")
# HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00")
# def byte_ord(byte_):
# def byte_ord(byte_):
# def byte_literal(literal):
# def byte_literal(literal):
# def dict_each(func, iterable):
# def dict_each(func, iterable):
# def next(iterator, default=throw):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(count):
# def generate_random_bytes(_):
# def get_word_alignment(num, force_arch=64,
# _machine_word_size=MACHINE_WORD_SIZE):
# class Throw(object):
#
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
, which may contain function names, class names, or code. Output only the next line. | if not builtins.is_bytes(raw_bytes): |
Next line prediction: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""":synopsis: Library compatibility.
:module: mom.codec._json_compat
"""
from __future__ import absolute_import
try:
# Built-in JSON library.
assert hasattr(json, "loads") and hasattr(json, "dumps")
def json_loads(value):
"""Wrapper to decode JSON."""
return json.loads(value)
def json_dumps(value):
"""Wrapper to encode JSON."""
return json.dumps(value)
except (AssertionError, ImportError):
try:
# Try to use the simplejson library.
def json_loads(value):
"""Wrapper to decode JSON."""
<|code_end|>
. Use current file imports:
(from mom.codec import text
from django.utils import simplejson as json
import json
import simplejson as json)
and context including class names, function names, or small code snippets from other files:
# Path: mom/codec/text.py
# def utf8_encode(unicode_text):
# def utf8_decode(utf8_encoded_bytes):
# def utf8_encode_if_unicode(obj):
# def utf8_decode_if_bytes(obj):
# def to_unicode_if_bytes(obj, encoding="utf-8"):
# def bytes_to_unicode(raw_bytes, encoding="utf-8"):
# def utf8_encode_recursive(obj):
# def bytes_to_unicode_recursive(obj, encoding="utf-8"):
# def utf8_decode_recursive(obj):
# def ascii_encode(obj):
# def latin1_encode(obj):
. Output only the next line. | return json.loads(text.utf8_decode(value)) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google Inc. 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
__author__ = "yesudeep@google.com (Yesudeep Mangalapilly)"
UNICODE_STRING = "\u00ae"
UNICODE_STRING2 = "深入 Python"
<|code_end|>
. Use current file imports:
from mom.builtins import b
and context (classes, functions, or code) from other files:
# Path: mom/builtins.py
# def byte(number):
# def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE):
# def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE):
# def bin(number, prefix="0b"):
# def hex(number, prefix="0x"):
# def is_sequence(obj):
# def is_unicode(obj):
# def is_bytes(obj):
# def is_bytes_or_unicode(obj):
# def is_integer(obj):
# def integer_byte_length(number):
# def integer_byte_size(number):
# def integer_bit_length(number):
# def integer_bit_size(number):
# def integer_bit_count(number):
# def is_even(num):
# def is_odd(num):
# def is_positive(num):
# def is_negative(num):
. Output only the next line. | FOO = b("foo") |
Using the snippet: <|code_start|> return
# strip off status
status = ll[0]
# strip of rest into a dict of name: [values,...,]
d = {a: [float(y) for y in b.split(',')] for a, b in [x.split(':') for x in ll[1:]]}
self.log.debug('Comms: got status:{} - rest: {}'.format(status, d))
self.app.main_window.update_status(status, d)
# schedule next report
self.timer = async_main_loop.call_later(self.report_rate, self._get_reports)
def handle_probe(self, s):
# [PRB:1.000,80.137,10.000:0]
ll = s[5:-1].split(':')
c = ll[0].split(',')
st = ll[1]
self.app.main_window.async_display("Probe: {} - X: {}, Y: {}, Z: {}".format(st, c[0], c[1], c[2]))
self.app.last_probe = {'X': float(c[0]), 'Y': float(c[1]), 'Z': float(c[2]), 'status': st == '1'}
def handle_alarm(self, s):
''' handle case where smoothie sends us !! or an error of some sort '''
self.log.warning('Comms: alarm message: {}'.format(s))
if self.file_streamer:
# pause any streaming immediately, (let operator decide to abort or not)
self._stream_pause(True, False)
if self.app.notify_email:
<|code_end|>
, determine the next line of code. You have imports:
import threading
import asyncio
import aiofiles
import logging
import functools
import sys
import re
import os
import traceback
import serial.tools.list_ports
import subprocess
import socket
import time
import libs.serial_asyncio.serial_asyncio
import datetime
from notify import Notify
and context (class names, function names, or code) available:
# Path: notify.py
# class Notify():
# """Send an Email to notify user"""
# def send(self, msg):
# self.logger = logging.getLogger()
# self.msg = msg
# threading.Thread(target=self._send).start()
#
# def _send(self):
# try:
# config = configparser.ConfigParser()
# config.read('notify.ini')
# # load user defined email settings
# user = config.get('authentication', 'user', fallback=None)
# password = config.get('authentication', 'password', fallback=None)
# server = config.get('authentication', 'server', fallback=None)
# port = config.getint('authentication', 'port', fallback=465)
# to_addr = config.get('header', 'to_address', fallback=None)
# subject = config.get('header', 'subject', fallback='Smoopi notification')
#
# except Exception as err:
# self.logger.error('Notify: notify.ini file errors: {}'.format(err))
# return False
#
# if user is None:
# self.logger.error('Notify: no user specified')
# return False
# if password is None:
# self.logger.error('Notify: no password specified')
# return False
# if server is None:
# self.logger.error('Notify: no server specified')
# return False
# if to_addr is None:
# self.logger.error('Notify: no to address specified')
# return False
#
# body = '{}\n'.format(self.msg)
#
# email_text = """\
# From: %s
# To: %s
# Subject: %s
#
# %s
# """ % (user, to_addr, subject, body)
#
# try:
# server = smtplib.SMTP_SSL(server, port)
# server.ehlo()
# server.login(user, password)
# server.sendmail(user, to_addr, email_text)
# server.close()
# return True
#
# except Exception as ex:
# self.logger.error('Notify: Failed to send email: {}'.format(ex))
# return False
. Output only the next line. | notify = Notify() |
Based on the snippet: <|code_start|> self.toggle_buttons[name] = (lon, loff, cmd_on, cmd_off, tbtn, poll)
tbtn.bind(on_press=partial(self._handle_toggle, name))
tbtn.ud = True
self.add_widget(tbtn)
elif section.startswith('script '):
name = config.get(section, 'name', fallback=None)
script = config.get(section, 'exec', fallback=None)
args = config.get(section, 'args', fallback=None)
io = config.getboolean(section, 'io', fallback=False)
self.debug = config.getboolean(section, 'debug', fallback=False)
btn = Factory.MacroButton()
btn.text = name
btn.background_color = (1, 1, 0, 1)
btn.bind(on_press=partial(self.exec_script, script, io, args))
btn.ud = True
self.add_widget(btn)
# add simple macro buttons (with optional prompts)
for (key, v) in config.items('macro buttons'):
btn = Factory.MacroButton()
btn.text = key
btn.bind(on_press=partial(self.send, v))
btn.ud = True
self.add_widget(btn)
except Exception as err:
Logger.warning('MacrosWidget: WARNING - exception parsing config file: {}'.format(err))
def new_macro(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import kivy
import configparser
import subprocess
import threading
import select
import re
import os
from kivy.app import App
from kivy.logger import Logger
from kivy.uix.stacklayout import StackLayout
from kivy.config import ConfigParser
from kivy.clock import Clock, mainthread
from kivy.factory import Factory
from multi_input_box import MultiInputBox
from functools import partial
and context (classes, functions, sometimes code) from other files:
# Path: multi_input_box.py
# class MultiInputBox(Popup):
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def __init__(self, **kwargs):
# self.window = Window
# super(MultiInputBox, self).__init__(**kwargs)
# self.content = self.ids["content"]
# self.contentButtons = self.ids["contentButtons"]
# self.wl = []
#
# def _dismiss(self):
# self.dismiss()
#
# def open(self):
# super(MultiInputBox, self).open()
#
# def _ok(self):
# if self.optionCallBack is not None:
# opts = {}
# for x in self.wl:
# opts[x[0]] = x[1].text
# self.optionCallBack(opts)
# self.dismiss()
#
# def on_open(self):
# if self.wl:
# self.wl[0][1].focus = True
#
# def setOptions(self, options, callBack):
# self.optionCallBack = callBack
# self.contentButtons.clear_widgets()
# self.wl = []
# for name in options:
# self.contentButtons.add_widget(Label(text=name, size_hint_y=None, height='30dp', halign='right'))
# tw = TextInput(multiline=False, write_tab=False, use_bubble=False, use_handles=False)
# self.contentButtons.add_widget(tw)
# self.wl.append((name, tw))
. Output only the next line. | o = MultiInputBox(title='Add Macro') |
Using the snippet: <|code_start|>''')
class ConfigV2Editor(Screen):
jsondata = []
current_section = None
config = None
configdata = []
msp = None
def _add_line(self, line):
ll = line.lstrip().rstrip()
if not ll.startswith("#") and ll != "":
if ll == "ok":
# finished
try:
self.config.read_string('\n'.join(self.configdata))
except Exception as e:
Logger.error("ConfigV2Editor: Error parsing the config file: {}".format(e))
self.app.main_window.async_display("Error parsing config file, see log")
self.close()
return
self.configdata = []
self._build()
else:
self.configdata.append(ll)
def new_entry(self):
<|code_end|>
, determine the next line of code. You have imports:
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock, mainthread
from kivy.config import ConfigParser
from kivy.uix.settings import SettingsWithNoMenu
from kivy.uix.label import Label
from kivy.logger import Logger
from kivy.uix.screenmanager import ScreenManager, Screen
from multi_input_box import MultiInputBox
import json
import configparser
import threading
and context (class names, function names, or code) available:
# Path: multi_input_box.py
# class MultiInputBox(Popup):
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def __init__(self, **kwargs):
# self.window = Window
# super(MultiInputBox, self).__init__(**kwargs)
# self.content = self.ids["content"]
# self.contentButtons = self.ids["contentButtons"]
# self.wl = []
#
# def _dismiss(self):
# self.dismiss()
#
# def open(self):
# super(MultiInputBox, self).open()
#
# def _ok(self):
# if self.optionCallBack is not None:
# opts = {}
# for x in self.wl:
# opts[x[0]] = x[1].text
# self.optionCallBack(opts)
# self.dismiss()
#
# def on_open(self):
# if self.wl:
# self.wl[0][1].focus = True
#
# def setOptions(self, options, callBack):
# self.optionCallBack = callBack
# self.contentButtons.clear_widgets()
# self.wl = []
# for name in options:
# self.contentButtons.add_widget(Label(text=name, size_hint_y=None, height='30dp', halign='right'))
# tw = TextInput(multiline=False, write_tab=False, use_bubble=False, use_handles=False)
# self.contentButtons.add_widget(tw)
# self.wl.append((name, tw))
. Output only the next line. | o = MultiInputBox(title='Add new entry') |
Given the following code snippet before the placeholder: <|code_start|>
def open(self, start_dir="", title="", cb=None):
self.cb = cb
self.title = title
self.start_dir = start_dir
threading.Thread(target=self._open_dialog).start()
def _open_dialog(self):
path = None
try:
if self.use_wx:
path = self._wx_get_path()
elif self.use_zenity:
os.unsetenv('WINDOWID') # needed so dialog pops up infront of my window
path = self._run_command(['zenity', '--title', self.title, '--file-selection', '--filename', self.start_dir + '/', '--file-filter', 'GCode files | *.g *.gcode *.nc *.gc *.ngc'])
elif self.use_kdialog:
path = self._run_command(['kdialog', '--title', self.title, '--getopenfilename', self.start_dir, 'GCode Files (*.g *.gcode *.nc *.gc *.ngc)'])
else:
self.failed = True
except Exception:
self.failed = True
self._loaded(path)
@mainthread
def _loaded(self, path):
if self.failed:
<|code_end|>
, predict the next line using imports from the current file:
import wx
import threading
import os.path
import subprocess as sp
import time
from kivy.clock import mainthread
from message_box import MessageBox
and context including class names, function names, and sometimes code from other files:
# Path: message_box.py
# class MessageBox(Popup):
# text = StringProperty('')
# cb = ObjectProperty()
#
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def ok(self):
# if self.cb:
# self.cb(True)
# self.dismiss()
#
# def cancel(self):
# if self.cb:
# self.cb(False)
# self.dismiss()
. Output only the next line. | mb = MessageBox(text='File Chooser {} failed - try a different one'.format(NativeFileChooser.type_name)) |
Continue the code snippet: <|code_start|>
class ConfigEditor(Screen):
@mainthread
def _add_line(self, line):
if not line.lstrip().startswith("#"):
t = line.split()
if len(t) >= 2:
self.rv.data.append({'k': t[0], 'v': t[1]})
elif t[0] == 'ok':
# add dummy lines at end so we can edit the last few lines without keyboard covering them
for i in range(10):
self.rv.data.append({'k': '', 'v': ''})
self.app.comms.redirect_incoming(None)
def open(self):
self.rv.data = []
self.manager.current = 'config_editor'
self.app = App.get_running_app()
# get config, parse and populate
self.app.comms.redirect_incoming(self._add_line)
# issue command
self.app.comms.write('cat /sd/config\n')
self.app.comms.write('\n') # get an ok to indicate end of cat
def insert(self, value):
self.rv.data.insert(0, {'k': value, 'v': ''})
def new_switch(self):
<|code_end|>
. Use current file imports:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import mainthread
from multi_input_box import MultiInputBox
and context (classes, functions, or code) from other files:
# Path: multi_input_box.py
# class MultiInputBox(Popup):
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def __init__(self, **kwargs):
# self.window = Window
# super(MultiInputBox, self).__init__(**kwargs)
# self.content = self.ids["content"]
# self.contentButtons = self.ids["contentButtons"]
# self.wl = []
#
# def _dismiss(self):
# self.dismiss()
#
# def open(self):
# super(MultiInputBox, self).open()
#
# def _ok(self):
# if self.optionCallBack is not None:
# opts = {}
# for x in self.wl:
# opts[x[0]] = x[1].text
# self.optionCallBack(opts)
# self.dismiss()
#
# def on_open(self):
# if self.wl:
# self.wl[0][1].focus = True
#
# def setOptions(self, options, callBack):
# self.optionCallBack = callBack
# self.contentButtons.clear_widgets()
# self.wl = []
# for name in options:
# self.contentButtons.add_widget(Label(text=name, size_hint_y=None, height='30dp', halign='right'))
# tw = TextInput(multiline=False, write_tab=False, use_bubble=False, use_handles=False)
# self.contentButtons.add_widget(tw)
# self.wl.append((name, tw))
. Output only the next line. | o = MultiInputBox(title='Add Switch') |
Given snippet: <|code_start|> too_many = BooleanProperty(False)
def __init__(self, comms=None, is_standalone=False, **kwargs):
super(GcodeViewerScreen, self).__init__(**kwargs)
self.app = App.get_running_app()
self.last_file_pos = None
self.canv = InstructionGroup()
self.bind(pos=self._redraw, size=self._redraw)
self.tx = 0
self.ty = 0
self.scale = 1.0
self.comms = comms
self.twod_mode = self.app.is_cnc
self.rval = 0.0
self.max_vectors = -1
if not is_standalone:
self.slice_size = self.app.config.get('Viewer', 'slice')
self.above_layer = -self.slice_size
self.max_vectors = self.app.config.getint('Viewer', 'vectors')
def loading(self):
self.valid = False
self.li = Image(source='img/image-loading.gif')
self.add_widget(self.li)
self.ids.surface.canvas.remove(self.canv)
# give loading image a chance to display
Clock.schedule_once(self._load_file)
def _loaded(self, ok):
if not ok:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from kivy.uix.scatter import Scatter
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.logger import Logger, LOG_LEVELS
from kivy.graphics import Color, Line, Scale, Translate, PopMatrix, PushMatrix, Rectangle
from kivy.graphics import InstructionGroup
from kivy.properties import NumericProperty, BooleanProperty, ListProperty, ObjectProperty
from kivy.graphics.transformation import Matrix
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.clock import Clock, mainthread
from kivy.core.text import Label as CoreLabel
from message_box import MessageBox
from input_box import InputBox
import logging
import sys
import re
import math
import time
import traceback
and context:
# Path: message_box.py
# class MessageBox(Popup):
# text = StringProperty('')
# cb = ObjectProperty()
#
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def ok(self):
# if self.cb:
# self.cb(True)
# self.dismiss()
#
# def cancel(self):
# if self.cb:
# self.cb(False)
# self.dismiss()
#
# Path: input_box.py
# class InputBox(Popup):
# text = StringProperty('')
# value = StringProperty('')
# cb = ObjectProperty()
#
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def __init__(self, **kwargs):
# self.window = Window
# super(InputBox, self).__init__(**kwargs)
# self.content = self.ids["content"]
#
# def on_open(self):
# self.ids.input.focus = True
#
# def ok(self):
# if self.cb:
# s = self.ids.input.text
# self.cb(s)
# self.dismiss()
#
# def cancel(self):
# if self.cb:
# self.cb(None)
# self.dismiss()
which might include code, classes, or functions. Output only the next line. | mb = MessageBox(text='File not found: {} or Parse error'.format(self.app.gcode_file)) |
Predict the next line after this snippet: <|code_start|> def next_layer(self):
if self.twod_mode:
self.above_layer -= self.slice_size
self.below_layer -= self.slice_size
self.loading()
def prev_layer(self):
if self.twod_mode:
self.above_layer += self.slice_size
self.below_layer += self.slice_size
self.loading()
else:
if len(self.layers) > 2:
self.layers.pop()
self.layers.pop()
self.loading()
def _set_slice(self, val):
if val:
try:
self.slice_size = float(val)
self.above_layer = -self.slice_size
self.below_layer = 0.0
self.loading()
except Exception as e:
pass
def set_slice(self):
<|code_end|>
using the current file's imports:
from kivy.uix.scatter import Scatter
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.logger import Logger, LOG_LEVELS
from kivy.graphics import Color, Line, Scale, Translate, PopMatrix, PushMatrix, Rectangle
from kivy.graphics import InstructionGroup
from kivy.properties import NumericProperty, BooleanProperty, ListProperty, ObjectProperty
from kivy.graphics.transformation import Matrix
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.clock import Clock, mainthread
from kivy.core.text import Label as CoreLabel
from message_box import MessageBox
from input_box import InputBox
import logging
import sys
import re
import math
import time
import traceback
and any relevant context from other files:
# Path: message_box.py
# class MessageBox(Popup):
# text = StringProperty('')
# cb = ObjectProperty()
#
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def ok(self):
# if self.cb:
# self.cb(True)
# self.dismiss()
#
# def cancel(self):
# if self.cb:
# self.cb(False)
# self.dismiss()
#
# Path: input_box.py
# class InputBox(Popup):
# text = StringProperty('')
# value = StringProperty('')
# cb = ObjectProperty()
#
# ok_text = StringProperty('OK')
# cancel_text = StringProperty('Cancel')
#
# def __init__(self, **kwargs):
# self.window = Window
# super(InputBox, self).__init__(**kwargs)
# self.content = self.ids["content"]
#
# def on_open(self):
# self.ids.input.focus = True
#
# def ok(self):
# if self.cb:
# s = self.ids.input.text
# self.cb(s)
# self.dismiss()
#
# def cancel(self):
# if self.cb:
# self.cb(None)
# self.dismiss()
. Output only the next line. | o = InputBox(title='Set Slice', text='enter size in mm of slice to view', cb=self._set_slice) |
Using the snippet: <|code_start|>
"""
name = 'Data'
version = 7
msg = None
api = None
showlist = None
infocache = dict()
queue = list()
config = dict()
meta = {'lastget': 0, 'lastsend': 0, 'version': '', 'apiversion': '',
'altnames': {}, 'library': {}, 'library_cache': {}, }
autosend_timer = None
signals = {
'show_synced': None,
'sync_complete': None,
'queue_changed': None,
}
def __init__(self, messenger, config, account, mediatype):
"""Checks if the config is correct and creates an API object."""
self.msg = messenger
self.config = config
self.msg.info(self.name, "Initializing...")
# Get filenames
userfolder = "%s.%s" % (account['username'], account['api'])
<|code_end|>
, determine the next line of code. You have imports:
import os.path
import sys
import threading
import time
from trackma import utils
and context (class names, function names, or code) available:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | self.userconfig_file = utils.to_data_path(userfolder, 'user.json') |
Predict the next line after this snippet: <|code_start|>
class AccountManager:
"""
This is the account manager.
It provides a generic way for the user interface to query for the
available registered accounts, and add or delete accounts.
This class returns an Account Dictionary used by
the :class:`Engine` to start.
"""
accounts = {'default': None, 'next': 1, 'accounts': dict()}
def __init__(self):
<|code_end|>
using the current file's imports:
import pickle
from trackma import utils
and any relevant context from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | utils.make_dir(utils.to_config_path()) |
Continue the code snippet: <|code_start|># This file is part of Trackma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
NOT_RUNNING = 0
ACTIVE = 1
CLAIMED = 2
PLAYING = 3
PAUSED = 4
IDLE = 5
<|code_end|>
. Use current file imports:
import ntpath
import time
import urllib.parse
import urllib.request
import xml.dom.minidom as xdmd
import trackma.utils as utils
from trackma.tracker import tracker
and context (classes, functions, or code) from other files:
# Path: trackma/tracker/tracker.py
# class TrackerBase(object):
# def __init__(self, messenger, tracker_list, config, watch_dirs, redirections=None):
# def set_message_handler(self, message_handler):
# def disable(self):
# def update_list(self, tracker_list):
# def connect_signal(self, signal, callback):
# def observe(self, config, watch_dirs):
# def get_status(self):
# def _emit_signal(self, signal, *args):
# def _update_show(self, state, show_tuple):
# def action(): return self._emit_signal('update', show, episode)
# def action(): return self._emit_signal('unrecognised', show, episode)
# def _ignore_current(self):
# def _update_state(self, state):
# def pause_timer(self):
# def resume_timer(self):
# def update_show_if_needed(self, state, show_tuple):
# def _get_playing_show(self, filename):
. Output only the next line. | class PlexTracker(tracker.TrackerBase): |
Given snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#import http.client
#http.client.HTTPConnection.debuglevel = 1
class libkitsu(lib):
"""
API class to communicate with Kitsu
Should inherit a base library interface.
Website: https://kitsu.io/
API documentation:
Designed by:
"""
name = 'libkitsu'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import time
import urllib.parse
import urllib.request
import json
import gzip
import socket
from trackma.lib.lib import lib
from trackma import utils
and context:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
which might include code, classes, or functions. Output only the next line. | user_agent = 'Trackma/{}'.format(utils.VERSION) |
Given the following code snippet before the placeholder: <|code_start|> msg = None
logged_in = False
api_info = {'name': 'Anilist', 'shortname': 'anilist',
'version': '2.1', 'merge': False}
mediatypes = dict()
mediatypes['anime'] = {
'has_progress': True,
'can_add': True,
'can_delete': True,
'can_score': True,
'can_status': True,
'can_update': True,
'can_play': True,
'can_date': True,
'date_next_ep': True,
'statuses_start': ['CURRENT', 'REPEATING'],
'statuses_finish': ['COMPLETED'],
'statuses_library': ['CURRENT', 'REPEATING', 'PAUSED', 'PLANNING'],
'statuses': ['CURRENT', 'COMPLETED', 'REPEATING', 'PAUSED', 'DROPPED', 'PLANNING'],
'statuses_dict': {
'CURRENT': 'Watching',
'COMPLETED': 'Completed',
'REPEATING': 'Rewatching',
'PAUSED': 'Paused',
'DROPPED': 'Dropped',
'PLANNING': 'Plan to Watch'
},
'score_max': 100,
'score_step': 1,
<|code_end|>
, predict the next line using imports from the current file:
import json
import urllib.parse
import urllib.request
import socket
import time
import datetime
from trackma.lib.lib import lib
from trackma import utils
and context including class names, function names, and sometimes code from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | 'search_methods': [utils.SearchMethod.KW, utils.SearchMethod.SEASON], |
Next line prediction: <|code_start|> def _reconnect(self):
if not self._enabled:
try:
self._rpc = Client(self._client_id)
self._rpc.start()
self._enabled = True
except self._errors:
self._enabled = False
rpc = DiscordRPC(daemon=True)
def init(engine):
"""
Initialize this hook.
"""
rpc.start()
rpc.present(engine)
def tracker_state(engine, status):
"""
Update status in thread.
"""
if status["state"] == 1:
show = status["show"][0]
title = show["titles"][0]
episode = status["show"][-1]
<|code_end|>
. Use current file imports:
(import time
import os
from threading import Thread
from asyncio import (
new_event_loop as new_loop,
set_event_loop as set_loop)
from pypresence.client import Client
from pypresence.exceptions import InvalidID, InvalidPipe
from trackma.utils import estimate_aired_episodes)
and context including class names, function names, or small code snippets from other files:
# Path: trackma/utils.py
# def estimate_aired_episodes(show):
# """ Estimate how many episodes have passed since airing """
#
# if show['status'] == Status.FINISHED:
# return show['total']
# elif show['status'] == Status.NOTYET:
# return 0
# # It's airing, so we make an estimate based on available information
# elif show['status'] == Status.AIRING:
# if 'next_ep_number' in show: # Do we have the upcoming episode number?
# return show['next_ep_number']-1
# elif show['start_date']: # Do we know when it started? Let's just assume 1 episode = 1 week
# days = (datetime.datetime.now() - show['start_date']).days
# if days <= 0:
# return 0
#
# eps = days // 7 + 1
# if show['total'] and eps > show['total']:
# return show['total']
# return eps
# return 0
. Output only the next line. | total = show["total"] or estimate_aired_episodes( |
Given the code snippet: <|code_start|> 'can_update': False,
'can_play': False,
'statuses': [0, 1, 2, 3],
'statuses_dict': {0: 'High', 1: 'Medium', 2: 'Low', 3: 'Blacklist'},
'score_max': 10,
'score_step': 0.1,
'statuses_start': [],
'statuses_finish': [],
}
def __init__(self, messenger, account, userconfig):
"""Initializes the useragent through credentials."""
super(libvndb, self).__init__(messenger, account, userconfig)
self.hostname = "api.vndb.org"
self.tls = 19535
self.tcp = 19534
self.username = account['username']
self.password = account['password']
self.logged_in = False
def _connect(self):
"""Create TCP socket and connect"""
self.context = ssl.create_default_context()
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s = self.context.wrap_socket(s, server_hostname=self.hostname)
self.s.connect((self.hostname, self.tls))
except socket.error:
<|code_end|>
, generate the next line using the imports in this file:
import socket
import json
import datetime
import ssl
from trackma.lib.lib import lib
from trackma import utils
and context (functions, classes, or occasionally code) from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | raise utils.APIError("Connection error.") |
Continue the code snippet: <|code_start|> 'can_status': True,
'can_update': True,
'can_play': False,
'statuses_start': ['watching', 'rewatching'],
'statuses_finish': ['completed'],
'statuses': ['watching', 'completed', 'on_hold', 'rewatching', 'dropped', 'planned'],
'statuses_dict': {
'watching': 'Reading',
'completed': 'Completed',
'on_hold': 'On-Hold',
'rewatching': 'Re-reading',
'dropped': 'Dropped',
'planned': 'Plan to Read'
},
'score_max': 10,
'score_step': 1,
}
default_mediatype = 'anime'
# Supported signals for the data handler
signals = {'show_info_changed': None, }
url = "https://shikimori.org"
auth_url = "https://shikimori.org/oauth/token"
api_url = "https://shikimori.org/api"
client_id = "Jfu9MKkUKPG4fOC95A6uwUVLHy3pwMo3jJB7YLSp7Ro"
client_secret = "y7YmQx8n1l7eBRugUSiB7NfNJxaNBMvwppfxJLormXU"
status_translate = {
<|code_end|>
. Use current file imports:
import json
import urllib.parse
import urllib.request
import socket
import time
from trackma.lib.lib import lib
from trackma import utils
and context (classes, functions, or code) from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | 'ongoing': utils.Status.AIRING, |
Given the following code snippet before the placeholder: <|code_start|># This file is part of Trackma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# TODO: Add gui stuff for this
NOT_RUNNING = 0
ACTIVE = 1
CLAIMED = 2
PLAYING = 3
PAUSED = 4
IDLE = 5
<|code_end|>
, predict the next line using imports from the current file:
import time
import os
import requests
from trackma.tracker import tracker
and context including class names, function names, and sometimes code from other files:
# Path: trackma/tracker/tracker.py
# class TrackerBase(object):
# def __init__(self, messenger, tracker_list, config, watch_dirs, redirections=None):
# def set_message_handler(self, message_handler):
# def disable(self):
# def update_list(self, tracker_list):
# def connect_signal(self, signal, callback):
# def observe(self, config, watch_dirs):
# def get_status(self):
# def _emit_signal(self, signal, *args):
# def _update_show(self, state, show_tuple):
# def action(): return self._emit_signal('update', show, episode)
# def action(): return self._emit_signal('unrecognised', show, episode)
# def _ignore_current(self):
# def _update_state(self, state):
# def pause_timer(self):
# def resume_timer(self):
# def update_show_if_needed(self, state, show_tuple):
# def _get_playing_show(self, filename):
. Output only the next line. | class JellyfinTracker(tracker.TrackerBase): |
Continue the code snippet: <|code_start|># This file is part of Trackma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
NOT_RUNNING = 0
IDLE = 1
ACTIVE = 2
AUTH_REQUIRED = 3
PLAYING = 4
PAUSED = 5
<|code_end|>
. Use current file imports:
import time
import json
import base64
import urllib.request
import trackma.utils as utils
from trackma.tracker import tracker
and context (classes, functions, or code) from other files:
# Path: trackma/tracker/tracker.py
# class TrackerBase(object):
# def __init__(self, messenger, tracker_list, config, watch_dirs, redirections=None):
# def set_message_handler(self, message_handler):
# def disable(self):
# def update_list(self, tracker_list):
# def connect_signal(self, signal, callback):
# def observe(self, config, watch_dirs):
# def get_status(self):
# def _emit_signal(self, signal, *args):
# def _update_show(self, state, show_tuple):
# def action(): return self._emit_signal('update', show, episode)
# def action(): return self._emit_signal('unrecognised', show, episode)
# def _ignore_current(self):
# def _update_state(self, state):
# def pause_timer(self):
# def resume_timer(self):
# def update_show_if_needed(self, state, show_tuple):
# def _get_playing_show(self, filename):
. Output only the next line. | class KodiTracker(tracker.TrackerBase): |
Given the following code snippet before the placeholder: <|code_start|> def process_IN_MOVED_TO(self, event):
if not event.mask & pyinotify.IN_ISDIR: # pylint: disable=no-member
self.parent._emit_signal(
'detected', event.path, event.name)
def process_IN_MOVED_FROM(self, event):
if not event.mask & pyinotify.IN_ISDIR: # pylint: disable=no-member
self.parent._emit_signal('removed', event.path, event.name)
def process_IN_DELETE(self, event):
if not event.mask & pyinotify.IN_ISDIR: # pylint: disable=no-member
self.parent._emit_signal('removed', event.path, event.name)
handler = EventHandler(parent=self)
notifier = pyinotify.Notifier(wm, handler)
for path in watch_dirs:
self.msg.debug(self.name, 'Watching directory {}'.format(path))
wm.add_watch(path, mask, rec=True, auto_add=True)
try:
# notifier.loop()
timeout = None
while self.active:
if notifier.check_events(timeout):
# Check again to avoid notifying while inactive
if not self.active:
return
notifier.read_events()
notifier.process_events()
<|code_end|>
, predict the next line using imports from the current file:
import pyinotify
from trackma.tracker import inotifyBase
from trackma import utils
and context including class names, function names, and sometimes code from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | if self.last_state == utils.Tracker.NOVIDEO or self.last_updated: |
Using the snippet: <|code_start|># This file is part of Trackma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
class MPRISTracker(tracker.TrackerBase):
name = 'Tracker (MPRIS)'
mpris_base = 'org.mpris.MediaPlayer2'
def is_active_player(self, sender):
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import urllib.parse
from pydbus import SessionBus
from gi.repository import GLib
from trackma.tracker import tracker
from trackma import utils
and context (class names, function names, or code) available:
# Path: trackma/tracker/tracker.py
# class TrackerBase(object):
# def __init__(self, messenger, tracker_list, config, watch_dirs, redirections=None):
# def set_message_handler(self, message_handler):
# def disable(self):
# def update_list(self, tracker_list):
# def connect_signal(self, signal, callback):
# def observe(self, config, watch_dirs):
# def get_status(self):
# def _emit_signal(self, signal, *args):
# def _update_show(self, state, show_tuple):
# def action(): return self._emit_signal('update', show, episode)
# def action(): return self._emit_signal('unrecognised', show, episode)
# def _ignore_current(self):
# def _update_state(self, state):
# def pause_timer(self):
# def resume_timer(self):
# def update_show_if_needed(self, state, show_tuple):
# def _get_playing_show(self, filename):
#
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | return not self.active_player or self.active_player == sender or self.last_state != utils.Tracker.PLAYING |
Given the following code snippet before the placeholder: <|code_start|>
try:
for event in i.event_gen():
if not self.active:
return
if event is not None:
# With inotifyx impl., only the event type was used,
# such that it only served to poll lsof when an
# open or close event was received.
(header, types, path, filename) = event
if 'IN_ISDIR' not in types:
# If the file is gone, we remove from library
if ('IN_MOVED_FROM' in types
or 'IN_DELETE' in types):
self._emit_signal('removed', str(
path, 'utf-8'), str(filename, 'utf-8'))
# Otherwise we attempt to add it to library
# Would check for IN_MOVED_TO or IN_CREATE but no need
else:
self._emit_signal('detected', str(
path, 'utf-8'), str(filename, 'utf-8'))
if 'IN_OPEN' in types:
self._proc_open(str(path, 'utf-8'),
str(filename, 'utf-8'))
elif ('IN_CLOSE_NOWRITE' in types
or 'IN_CLOSE_WRITE' in types):
self._proc_close(
str(path, 'utf-8'), str(filename, 'utf-8'))
<|code_end|>
, predict the next line using imports from the current file:
import inotify.adapters
import inotify.constants
from trackma.tracker import inotifyBase
from trackma import utils
and context including class names, function names, and sometimes code from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | elif self.last_state != utils.Tracker.NOVIDEO and not self.last_updated: |
Here is a snippet: <|code_start|> self.colors = colors
self.decimals = decimals
self.set_sort_column_id(1, Gtk.SortType.ASCENDING)
@staticmethod
def format_date(date):
if date:
try:
return date.strftime('%Y-%m-%d')
except ValueError:
return '?'
else:
return '-'
@classmethod
def __columns__(cls):
return (k for i, k in cls.__cols)
@classmethod
def column(cls, key):
try:
return cls.__cols.index(next(i for i in cls.__cols if i[0] == key))
except ValueError:
return None
def _get_color(self, show, eps):
if show.get('queued'):
return self.colors['is_queued']
elif eps and max(eps) > show['my_progress']:
return self.colors['new_episode']
<|code_end|>
. Write the next line using the current file imports:
from gi.repository import Gtk, Gdk, Pango, GObject
from trackma import utils
and context from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
, which may include functions, classes, or code. Output only the next line. | elif show['status'] == utils.Status.AIRING: |
Using the snippet: <|code_start|> cancel_btn = QPushButton('Cancel')
cancel_btn.clicked.connect(self.cancel)
add_btn = QPushButton('Add')
add_btn.clicked.connect(self.add)
self.edit_btns = QComboBox()
self.edit_btns.blockSignals(True)
self.edit_btns.addItem('Edit...')
self.edit_btns.addItem('Update')
self.edit_btns.addItem('Delete')
self.edit_btns.addItem('Purge')
self.edit_btns.setItemData(
1, 'Change the local password/PIN for this account', QtCore.Qt.ToolTipRole)
self.edit_btns.setItemData(
2, 'Remove this account from Trackma', QtCore.Qt.ToolTipRole)
self.edit_btns.setItemData(
3, 'Clear local DB for this account', QtCore.Qt.ToolTipRole)
self.edit_btns.setCurrentIndex(0)
self.edit_btns.blockSignals(False)
self.edit_btns.activated.connect(self.s_edit)
select_btn = QPushButton('Select')
select_btn.clicked.connect(self.select)
select_btn.setDefault(True)
bottom_layout.addWidget(self.remember_chk)
bottom_layout.addWidget(cancel_btn)
bottom_layout.addWidget(add_btn)
bottom_layout.addWidget(self.edit_btns)
bottom_layout.addWidget(select_btn)
# Get icons
self.icons = dict()
<|code_end|>
, determine the next line of code. You have imports:
from trackma import utils
from PyQt5.QtWidgets import (
QDialog, QTableWidgetItem, QVBoxLayout, QHBoxLayout, QTableWidget,
QAbstractItemView, QCheckBox, QPushButton, QComboBox, QHeaderView,
QMessageBox, QFormLayout, QLabel, QLineEdit, QDialogButtonBox)
from PyQt5 import QtCore, QtGui
and context (class names, function names, or code) available:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | for libname, lib in utils.available_libs.items(): |
Predict the next line for this snippet: <|code_start|> name = 'libmal'
msg = None
logged_in = False
api_info = {'name': 'MyAnimeList', 'shortname': 'mal',
'version': 3, 'merge': False}
mediatypes = dict()
mediatypes['anime'] = {
'has_progress': True,
'can_add': True,
'can_delete': True,
'can_score': True,
'can_status': True,
'can_update': True,
'can_play': True,
'can_date': True,
'date_next_ep': True,
'statuses_start': ['watching'],
'statuses_finish': ['completed'],
'statuses_library': ['watching', 'on_hold', 'plan_to_watch'],
'statuses': ['watching', 'completed', 'on_hold', 'dropped', 'plan_to_watch'],
'statuses_dict': {
'watching': 'Watching',
'completed': 'Completed',
'on_hold': 'On hold',
'dropped': 'Dropped',
'plan_to_watch': 'Plan to Watch'
},
'score_max': 10,
'score_step': 1,
<|code_end|>
with the help of current file imports:
import json
import urllib.parse
import urllib.request
import socket
import time
import datetime
from trackma.lib.lib import lib
from trackma import utils
and context from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
, which may contain function names, class names, or code. Output only the next line. | 'search_methods': [utils.SearchMethod.KW, utils.SearchMethod.SEASON], |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
try:
LONG_DESCRIPTION = open("README.md").read()
except IOError:
LONG_DESCRIPTION = __doc__
NAME = "Trackma"
REQUIREMENTS = []
EXTRA_REQUIREMENTS = {
'curses': ['urwid'],
'GTK': ['pygobject'],
'Qt': [],
}
setup(
name=NAME,
<|code_end|>
, predict the immediate next line with the help of imports:
from setuptools import setup, find_packages
from trackma import utils
and context (classes, functions, sometimes code) from other files:
# Path: trackma/utils.py
# VERSION = '0.8.4'
# DATADIR = os.path.dirname(__file__) + '/data'
# PASSWD = auto()
# OAUTH = auto()
# OAUTH_PKCE = auto()
# UNKNOWN = 'Unknown'
# ONGOING = 'Ongoing'
# FINISHED = 'Finished'
# NOTYET = 'Not yet started'
# CANCELLED = 'Cancelled'
# OTHER = 'Other'
# AIRING = ONGOING
# RELEASING = ONGOING
# PUBLISHING = ONGOING
# CURRENTLY_AIRING = ONGOING
# FINISHED_AIRING = FINISHED
# NOT_YET_AIRED = NOTYET
# NOT_YET_RELEASED = NOTYET
# NOT_YET_PUBLISHED = NOTYET
# UNKNOWN = "Unknown"
# OTHER = "Other"
# TV = "TV"
# MOVIE = "Movie"
# OVA = "OVA"
# SPECIAL = "Special"
# MANGA = "Manga"
# NOVEL = "Novel"
# ONE_SHOT = "One Shot"
# SP = SPECIAL
# MUSIC = OTHER
# ONA = OVA
# NOVIDEO = auto()
# PLAYING = auto()
# UNRECOGNIZED = auto()
# NOT_FOUND = auto()
# IGNORED = auto()
# WINTER = 'Winter'
# SPRING = 'Spring'
# SUMMER = 'Summer'
# FALL = 'Fall'
# KEYWORD = auto()
# SEASON = auto()
# KW = KEYWORD
# HOME = os.path.expanduser("~")
# EXTENSIONS = ('.mkv', '.mp4', '.avi', '.ts')
# class Login(Enum):
# class BaseEnum(Enum):
# class Status(BaseEnum):
# class Type(BaseEnum):
# class Tracker(Enum):
# class Season(Enum):
# class SearchMethod(Enum):
# class TrackmaError(Exception):
# class EngineError(TrackmaError):
# class DataError(TrackmaError):
# class APIError(TrackmaError):
# class AccountError(TrackmaError):
# class TrackmaFatal(Exception):
# class EngineFatal(TrackmaFatal):
# class DataFatal(TrackmaFatal):
# class APIFatal(TrackmaFatal):
# def find(cls, name):
# def from_int(cls, index):
# def __int__(self):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __str__(self):
# def oauth_generate_pkce() -> str:
# def parse_config(filename, default):
# def save_config(config_dict, filename):
# def load_data(filename):
# def save_data(data, filename):
# def log_error(msg):
# def expand_path(path):
# def expand_paths(paths):
# def is_media(filename):
# def regex_find_videos(subdirectory=''):
# def regex_rename_files(pattern, source_dir, dest_dir):
# def list_library(path):
# def make_dir(path):
# def dir_exists(dirname):
# def file_exists(filename):
# def file_older_than(filename, mtime):
# def try_files(filenames):
# def sync_file(fname, sync_url):
# def copy_file(src, dest):
# def to_config_path(*paths):
# def to_data_path(*paths):
# def to_cache_path(*paths):
# def change_permissions(filename, mode):
# def estimate_aired_episodes(show):
# def guess_show(show_title, tracker_list):
# def redirect_show(show_tuple, redirections, tracker_list):
# def spawn_process(arg_list):
# def get_terminal_size(fd=1):
# def show():
. Output only the next line. | version=utils.VERSION, |
Predict the next line after this snippet: <|code_start|>
def description_i18n(self):
"""Return the translated description."""
if self.description:
return mark_safe(gettext(self.description.replace('\r\n', '\n')))
return ''
def mitigation_i18n(self):
"""Return translated mitigation."""
if self.mitigation:
return mark_safe(gettext(self.mitigation.replace('\r\n', '\n')))
return ''
class Meta:
ordering = ['-date']
def handler_security_saved(sender, **kwargs):
"""Write file _i18n_security.py with security issues to translate."""
# pylint: disable=unused-argument
strings = []
for security in Security.objects.filter(visible=1).order_by('-date'):
fields = (
security.cwe_text,
security.scope,
security.issue,
security.description,
security.mitigation,
)
strings.extend([field for field in fields if field])
<|code_end|>
using the current file's imports:
from django.db import models
from django.db.models.signals import post_save
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_noop
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
from weechat.common.tracker import commits_links, tracker_links
and any relevant context from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
. Output only the next line. | i18n_autogen('doc', 'security', strings) |
Given the code snippet: <|code_start|> class Meta:
ordering = ['priority']
class Security(models.Model):
"""A security vulnerability in WeeChat."""
visible = models.BooleanField(default=True)
date = models.DateTimeField()
wsa = models.CharField(max_length=64)
cve = models.CharField(max_length=64, blank=True)
cwe_id = models.IntegerField(default=0)
cwe_text = models.CharField(max_length=64)
cvss_vector = models.CharField(max_length=64)
cvss_score = models.DecimalField(max_digits=3, decimal_places=1)
tracker = models.CharField(max_length=64, blank=True)
affected = models.CharField(max_length=64, blank=True)
fixed = models.CharField(max_length=32, blank=True)
release_date = models.DateField(blank=True, null=True)
commits = models.CharField(max_length=1024, blank=True)
scope = models.CharField(max_length=64)
issue = models.TextField()
description = models.TextField()
mitigation = models.TextField(blank=True)
credit = models.TextField(blank=True)
def __str__(self):
return f'{self.wsa}: [{self.scope}] {self.issue} ({self.release_date})'
def date_l10n(self):
"""Return the date formatted with localized date format."""
<|code_end|>
, generate the next line using the imports in this file:
from django.db import models
from django.db.models.signals import post_save
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_noop
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
from weechat.common.tracker import commits_links, tracker_links
and context (functions, classes, or occasionally code) from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
. Output only the next line. | return localdate(self.date) |
Continue the code snippet: <|code_start|> """Return translated severity based on CVSS score."""
text = dict(SECURITY_SEVERITIES).get(self.severity_index(), '')
return gettext(text) if text else ''
def score_bar(self):
"""Return HTML code with score bar."""
return mark_safe(get_score_bar(self.cvss_score))
def affected_html(self):
"""Return list of affected versions, as HTML."""
list_affected = []
for version in self.affected.split(','):
if '-' in version:
version1, version2 = version.split('-', 1)
list_affected.append(f'{version1} → {version2}')
else:
list_affected.append(version)
return mark_safe(', '.join(list_affected))
def fixed_html(self):
"""Return fixed version, as HTML."""
return mark_safe(f'<span class="text-success fw-bold">'
f'{self.fixed}</span>')
def release_date_l10n(self):
"""Return the release date formatted with localized date format."""
return localdate(self.release_date)
def url_commits(self):
"""Return URL(s) with links to commits, as HTML."""
<|code_end|>
. Use current file imports:
from django.db import models
from django.db.models.signals import post_save
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_noop
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
from weechat.common.tracker import commits_links, tracker_links
and context (classes, functions, or code) from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
. Output only the next line. | return commits_links(self.commits) |
Here is a snippet: <|code_start|>
def cve_links(self):
"""Return URLs for the CVE."""
if not self.cve:
return {}
return {
name: url % {'cve': self.cve}
for name, url in URL_CVE.items()
}
def cwe_i18n(self):
"""Return the translated vulnerability type."""
if self.cwe_text:
return gettext(self.cwe_text)
return ''
def url_cwe(self):
"""Return URL to CWE detail."""
if self.cwe_id > 0:
return URL_CWE % {'cwe': self.cwe_id}
return ''
def url_cvss_vector(self):
"""Return URL to CVSS vector detail."""
if self.cvss_vector:
return URL_CVSS_VECTOR % {'vector': self.cvss_vector}
return ''
def url_tracker(self):
"""Return URL with links to tracker items."""
<|code_end|>
. Write the next line using the current file imports:
from django.db import models
from django.db.models.signals import post_save
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_noop
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
from weechat.common.tracker import commits_links, tracker_links
and context from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
, which may include functions, classes, or code. Output only the next line. | return mark_safe(tracker_links(self.tracker)) |
Predict the next line after this snippet: <|code_start|>#
# This file is part of WeeChat.org.
#
# WeeChat.org is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# WeeChat.org is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Views for "about" menu."""
def screenshots(request, app='weechat', filename=''):
"""
Page with one screenshot (if filename given),
or all screenshots as thumbnails.
"""
if filename:
try:
<|code_end|>
using the current file's imports:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and any relevant context from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | screenshot = Screenshot.objects.get(app=app, filename=filename) |
Continue the code snippet: <|code_start|> 'app': app,
'filename': filename,
'screenshot': screenshot,
},
)
screenshot_list = Screenshot.objects.filter(app=app).order_by('priority')
return render(
request,
'about/screenshots.html',
{
'app': app,
'screenshot_list': screenshot_list,
},
)
def history(request):
"""Page with WeeChat history, including key dates."""
release_list = (Release.objects.all().exclude(version='devel')
.order_by('-date'))
releases = []
for release in release_list:
name = f'weechat-{release.version}.png'
if os.path.exists(media_path_join('images', 'story', name)):
releases.append((release.version, release.date))
return render(
request,
'about/history.html',
{
'releases': releases,
<|code_end|>
. Use current file imports:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and context (classes, functions, or code) from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | 'keydate_list': Keydate.objects.all().order_by('date'), |
Here is a snippet: <|code_start|> 'keydate_list': Keydate.objects.all().order_by('date'),
},
)
def about(request, extra_info=False):
"""About WeeChat.org."""
context = {}
if extra_info:
context.update({
'extra_info': {
'django': django_version,
'python': python_version,
},
})
return render(request, 'about/weechat.org.html', context)
def donate(request, sort_key='date', view_key=''):
"""Page with link for donation and list of sponsors."""
sort_key_top = 'top10'
sort_key_top_count = 10
sort_count = 0
if sort_key.startswith('top'):
sort_key_top = sort_key
sort_count = max(int(sort_key[3:]), 1)
sort_key_top_count = sort_count
sort_key = 'top'
if sort_key == 'type':
<|code_end|>
. Write the next line using the current file imports:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and context from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may include functions, classes, or code. Output only the next line. | sponsor_list = (Sponsor.objects.values('sponsortype') |
Given the following code snippet before the placeholder: <|code_start|> """About WeeChat.org."""
context = {}
if extra_info:
context.update({
'extra_info': {
'django': django_version,
'python': python_version,
},
})
return render(request, 'about/weechat.org.html', context)
def donate(request, sort_key='date', view_key=''):
"""Page with link for donation and list of sponsors."""
sort_key_top = 'top10'
sort_key_top_count = 10
sort_count = 0
if sort_key.startswith('top'):
sort_key_top = sort_key
sort_count = max(int(sort_key[3:]), 1)
sort_key_top_count = sort_count
sort_key = 'top'
if sort_key == 'type':
sponsor_list = (Sponsor.objects.values('sponsortype')
.annotate(amount=Sum('amount'))
.order_by('-amount'))
total = sum(sponsor['amount'] for sponsor in sponsor_list)
for sponsor in sponsor_list:
sponsor['sponsortype_i18n'] = gettext(
<|code_end|>
, predict the next line using imports from the current file:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and context including class names, function names, and sometimes code from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | dict(SPONSOR_TYPE_CHOICES)[sponsor['sponsortype']]) |
Continue the code snippet: <|code_start|> if extra_info:
context.update({
'extra_info': {
'django': django_version,
'python': python_version,
},
})
return render(request, 'about/weechat.org.html', context)
def donate(request, sort_key='date', view_key=''):
"""Page with link for donation and list of sponsors."""
sort_key_top = 'top10'
sort_key_top_count = 10
sort_count = 0
if sort_key.startswith('top'):
sort_key_top = sort_key
sort_count = max(int(sort_key[3:]), 1)
sort_key_top_count = sort_count
sort_key = 'top'
if sort_key == 'type':
sponsor_list = (Sponsor.objects.values('sponsortype')
.annotate(amount=Sum('amount'))
.order_by('-amount'))
total = sum(sponsor['amount'] for sponsor in sponsor_list)
for sponsor in sponsor_list:
sponsor['sponsortype_i18n'] = gettext(
dict(SPONSOR_TYPE_CHOICES)[sponsor['sponsortype']])
sponsor['sponsortype_svg'] = \
<|code_end|>
. Use current file imports:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and context (classes, functions, or code) from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | SPONSOR_TYPE_SVG[sponsor['sponsortype']] |
Continue the code snippet: <|code_start|> screenshot = Screenshot.objects.get(app=app, filename=filename)
except ObjectDoesNotExist:
screenshot = None
return render(
request,
'about/screenshots.html',
{
'app': app,
'filename': filename,
'screenshot': screenshot,
},
)
screenshot_list = Screenshot.objects.filter(app=app).order_by('priority')
return render(
request,
'about/screenshots.html',
{
'app': app,
'screenshot_list': screenshot_list,
},
)
def history(request):
"""Page with WeeChat history, including key dates."""
release_list = (Release.objects.all().exclude(version='devel')
.order_by('-date'))
releases = []
for release in release_list:
name = f'weechat-{release.version}.png'
<|code_end|>
. Use current file imports:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and context (classes, functions, or code) from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | if os.path.exists(media_path_join('images', 'story', name)): |
Predict the next line after this snippet: <|code_start|> Page with one screenshot (if filename given),
or all screenshots as thumbnails.
"""
if filename:
try:
screenshot = Screenshot.objects.get(app=app, filename=filename)
except ObjectDoesNotExist:
screenshot = None
return render(
request,
'about/screenshots.html',
{
'app': app,
'filename': filename,
'screenshot': screenshot,
},
)
screenshot_list = Screenshot.objects.filter(app=app).order_by('priority')
return render(
request,
'about/screenshots.html',
{
'app': app,
'screenshot_list': screenshot_list,
},
)
def history(request):
"""Page with WeeChat history, including key dates."""
<|code_end|>
using the current file's imports:
import os
from sys import version as python_version
from django import __version__ as django_version
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum
from django.shortcuts import render
from django.utils.translation import gettext
from weechat.about.models import (
Screenshot,
Keydate,
Sponsor,
SPONSOR_TYPE_CHOICES,
SPONSOR_TYPE_SVG,
)
from weechat.common.path import media_path_join
from weechat.download.models import Release
and any relevant context from other files:
# Path: weechat/about/models.py
# class Screenshot(models.Model):
# """A WeeChat screenshot."""
# app = models.CharField(max_length=256)
# filename = models.CharField(max_length=256)
# comment = models.TextField(blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# return f'{self.app}: {self.filename} ({self.priority})'
#
# class Meta:
# """Meta class for ScreenShot."""
# ordering = ['priority']
#
# class Keydate(models.Model):
# """A WeeChat key date."""
# date = models.DateField()
# version = models.TextField(max_length=32)
# text = models.TextField()
#
# def __str__(self):
# str_version = f'{self.version}: ' if self.version else ''
# return f'{self.date} - {str_version}{self.text}'
#
# def text_i18n(self):
# """Return translated key date."""
# return gettext(self.text.replace('\r\n', '\n'))
#
# class Meta:
# """Meta class for KeyDate."""
# ordering = ['-date']
#
# class Sponsor(models.Model):
# """A WeeChat sponsor."""
# sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
# name = models.CharField(max_length=64)
# date = models.DateField()
# site = models.CharField(max_length=512, blank=True)
# amount = models.DecimalField(max_digits=10, decimal_places=2)
# number = models.IntegerField(default=1)
# comment = models.CharField(max_length=1024, blank=True)
#
# def __str__(self):
# str_num = f' (#{self.number})' if self.number > 1 else ''
# return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
# f'{self.date}, {self.amount:.2f} €')
#
# def date_l10n(self):
# """Return the sponsor date formatted with localized date format."""
# return localdate(self.date)
#
# def sponsortype_i18n(self):
# """Return the translated sponsor type."""
# return gettext(dict(SPONSOR_TYPE_CHOICES)[self.sponsortype])
#
# def sponsortype_svg(self):
# """Return the name of SVG for the sponsor type."""
# return SPONSOR_TYPE_SVG[self.sponsortype]
#
# SPONSOR_TYPE_CHOICES = (
# (0,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Individual')),
# (1,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Association')),
# (2,
# # Translators: context: Individual / Association / Company
# gettext_lazy('Company')),
# )
#
# SPONSOR_TYPE_SVG = {
# 0: 'person',
# 1: 'persons',
# 2: 'briefcase',
# }
#
# Path: weechat/common/path.py
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | release_list = (Release.objects.all().exclude(version='devel') |
Given the code snippet: <|code_start|> class Meta:
"""Meta class for ScreenShot."""
ordering = ['priority']
class Keydate(models.Model):
"""A WeeChat key date."""
date = models.DateField()
version = models.TextField(max_length=32)
text = models.TextField()
def __str__(self):
str_version = f'{self.version}: ' if self.version else ''
return f'{self.date} - {str_version}{self.text}'
def text_i18n(self):
"""Return translated key date."""
return gettext(self.text.replace('\r\n', '\n'))
class Meta:
"""Meta class for KeyDate."""
ordering = ['-date']
def handler_keydate_saved(sender, **kwargs):
"""Write file _i18n_keydates.py with key dates to translate."""
# pylint: disable=unused-argument
strings = []
for keydate in Keydate.objects.order_by('-date'):
strings.append(keydate.text)
<|code_end|>
, generate the next line using the imports in this file:
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import gettext, gettext_lazy
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
and context (functions, classes, or occasionally code) from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
. Output only the next line. | i18n_autogen('about', 'keydates', strings) |
Next line prediction: <|code_start|>
def handler_keydate_saved(sender, **kwargs):
"""Write file _i18n_keydates.py with key dates to translate."""
# pylint: disable=unused-argument
strings = []
for keydate in Keydate.objects.order_by('-date'):
strings.append(keydate.text)
i18n_autogen('about', 'keydates', strings)
post_save.connect(handler_keydate_saved, sender=Keydate)
class Sponsor(models.Model):
"""A WeeChat sponsor."""
sponsortype = models.IntegerField(choices=SPONSOR_TYPE_CHOICES, default=0)
name = models.CharField(max_length=64)
date = models.DateField()
site = models.CharField(max_length=512, blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
number = models.IntegerField(default=1)
comment = models.CharField(max_length=1024, blank=True)
def __str__(self):
str_num = f' (#{self.number})' if self.number > 1 else ''
return (f'{self.name}{str_num}, {self.sponsortype_i18n()}, '
f'{self.date}, {self.amount:.2f} €')
def date_l10n(self):
"""Return the sponsor date formatted with localized date format."""
<|code_end|>
. Use current file imports:
(from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import gettext, gettext_lazy
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate)
and context including class names, function names, or small code snippets from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
. Output only the next line. | return localdate(self.date) |
Based on the snippet: <|code_start|> def file_exists(self):
"""Check if script exists (on disk)."""
return os.path.isfile(self.filename())
def checksum(self, hash_func):
"""Return script checksum using the hash function (from hashlib)."""
try:
with open(self.filename(), 'rb') as _file:
return hash_func(_file.read()).hexdigest()
except: # noqa: E722 pylint: disable=bare-except
return ''
def get_md5sum(self):
"""
Return the script MD5 (if known), or compute it with the file
if it is not set in database.
"""
return self.md5sum or self.checksum(hashlib.md5)
def get_sha512sum(self):
"""
Return the script SHA512 (if known), or compute it with the file
if it is not set in database.
"""
return self.sha512sum or self.checksum(hashlib.sha512)
class Meta:
ordering = ['-added']
<|code_end|>
, predict the immediate next line with the help of imports:
import gzip
import hashlib
import json
import os
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils import translation
from django.utils.safestring import mark_safe
from django.utils.translation import gettext
from weechat.common.decorators import disable_for_loaddata
from weechat.common.i18n import i18n_autogen
from weechat.common.path import files_path_join
and context (classes, functions, sometimes code) from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
. Output only the next line. | @disable_for_loaddata |
Next line prediction: <|code_start|> json_script[field] = value_i18n[field]
xml += ' </plugin>\n'
json_data.append(json_script)
xml += '</plugins>\n'
# create scripts.xml
filename = files_path_join('scripts.xml')
with open(filename, 'w', encoding='utf-8') as _file:
_file.write(xml)
# create scripts.xml.gz
with open(filename, 'rb') as _f_in:
_f_out = gzip.open(filename + '.gz', 'wb')
_f_out.writelines(_f_in)
_f_out.close()
# create scripts.json
filename = files_path_join('scripts.json')
with open(filename, 'w', encoding='utf-8') as _file:
_file.write(json.dumps(json_data, indent=2, ensure_ascii=False,
separators=(',', ': ')))
# json.dump(json_data, _file)
# create scripts.json.gz
with open(filename, 'rb') as _f_in:
_f_out = gzip.open(filename + '.gz', 'wb')
_f_out.writelines(_f_in)
_f_out.close()
# create _i18n_scripts.py
<|code_end|>
. Use current file imports:
(import gzip
import hashlib
import json
import os
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils import translation
from django.utils.safestring import mark_safe
from django.utils.translation import gettext
from weechat.common.decorators import disable_for_loaddata
from weechat.common.i18n import i18n_autogen
from weechat.common.path import files_path_join)
and context including class names, function names, or small code snippets from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
. Output only the next line. | i18n_autogen('scripts', 'scripts', strings) |
Given snippet: <|code_start|> return gettext(self.desc_en.encode('utf-8'))
return gettext(self.desc_en)
def disabled_i18n(self):
"""Return the translated disabled reason."""
if not isinstance(self.disabled, str):
# python 2.x
return gettext(self.disabled.encode('utf-8'))
return gettext(self.disabled)
def version_weechat(self):
"""Return the WeeChat supported versions in a string."""
vmin = self.min_weechat or '0.3.0'
return f'{vmin}+'
def version_weechat_html(self):
"""Return the WeeChat supported versions in a string for HTML."""
vmin = self.min_weechat or '0.3.0'
return f'≥ {vmin}'
def build_url(self):
"""Return URL to the script."""
return f'/files/{self.path()}/{self.name_with_extension()}'
def build_url_repo(self):
"""Return URL to the script in repository."""
return f'{REPOSITORY}/{self.language}/{self.name_with_extension()}'
def filename(self):
"""Return script filename (on disk)."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import gzip
import hashlib
import json
import os
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils import translation
from django.utils.safestring import mark_safe
from django.utils.translation import gettext
from weechat.common.decorators import disable_for_loaddata
from weechat.common.i18n import i18n_autogen
from weechat.common.path import files_path_join
and context:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
which might include code, classes, or functions. Output only the next line. | return files_path_join(self.path(), |
Continue the code snippet: <|code_start|>
class WeechatFeed(Feed):
"""A WeeChat feed."""
def get_object(self, request, *args, **kwargs):
# pylint: disable=attribute-defined-outside-init
self.request = request
def item_link(self, item):
"""Return link to item by using the domain sent in the request."""
return (f'{self.request.scheme}://{self.request.get_host()}/news/'
f'{item.id}')
def item_pubdate(self, info):
"""Return idem date."""
# pylint: disable=no-self-use
return info.date
class LatestNewsFeed(WeechatFeed):
"""Feed with latest news."""
title = 'WeeChat news'
description = title
link = '/news/'
def items(self):
"""Return items with date in the past."""
# pylint: disable=no-self-use
<|code_end|>
. Use current file imports:
from datetime import datetime
from django.contrib.syndication.views import Feed
from weechat.news.models import Info
and context (classes, functions, or code) from other files:
# Path: weechat/news/models.py
# class Info(models.Model):
# """A WeeChat info."""
# visible = models.BooleanField(default=False)
# date = models.DateTimeField()
# title = models.CharField(max_length=64)
# author = models.CharField(max_length=256)
# mail = models.EmailField(max_length=256)
# text = models.TextField(blank=True)
#
# def __str__(self):
# return f'{self.title} ({self.date})'
#
# def date_l10n(self):
# """Return the info date formatted with localized date format."""
# return localdate(self.date)
#
# def title_i18n(self):
# """Return translated title."""
# match = PATTERN_TITLE_VERSION.match(self.title)
# if match:
# # if the title is "Version x.y.z", translate only "Version"
# return f'{gettext(match.group(1))} {match.group(2)}'
# return gettext(self.title)
#
# def text_i18n(self):
# """Return translated text."""
# if self.text:
# return gettext(self.text.replace('\r\n', '\n'))
# return ''
#
# def date_title_url(self):
# """Return date+title to include in URL."""
# text_url = re.sub(' +', '-',
# re.sub('[^ a-zA-Z0-9.]', ' ', self.title).strip())
# return (f'{self.date.year:0>4}{self.date.month:0>2}{self.date.day:0>2}'
# f'-{text_url}')
. Output only the next line. | return (Info.objects.filter(visible=1) |
Based on the snippet: <|code_start|> self.fields['theme'].choices = get_theme_choices()
def clean_themefile(self):
"""Check if theme file is valid."""
_file = self.cleaned_data['themefile']
if _file.size > 512*1024:
raise forms.ValidationError(gettext('Theme file too big.'))
content = _file.read()
if isinstance(content, bytes):
content = content.decode('utf-8')
props = Theme.get_props(content)
if 'name' not in props or 'weechat' not in props:
raise forms.ValidationError(gettext('Invalid theme file.'))
theme = Theme.objects.get(id=self.cleaned_data['theme'])
if not theme:
raise forms.ValidationError(gettext('Internal error.'))
if props['name'] != theme.name:
raise forms.ValidationError(
gettext('Invalid name: different from theme.'))
release_stable = Release.objects.get(version='stable')
release_devel = Release.objects.get(version='devel')
if props['weechat'] not in (release_stable.description,
re.sub('-.*', '',
release_devel.description)):
raise forms.ValidationError(
gettext('Invalid WeeChat version, too old!'))
_file.seek(0)
return _file
<|code_end|>
, predict the immediate next line with the help of imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (classes, functions, sometimes code) from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | @disable_for_loaddata |
Using the snippet: <|code_start|># the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# WeeChat.org is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Models for "themes" menu."""
MAX_LENGTH_NAME = 64
MAX_LENGTH_VERSION = 32
MAX_LENGTH_MD5SUM = 32
MAX_LENGTH_SHA512SUM = 128
MAX_LENGTH_DESC = 1024
MAX_LENGTH_COMMENT = 1024
MAX_LENGTH_AUTHOR = 256
MAX_LENGTH_MAIL = 256
class Theme(models.Model):
"""A WeeChat theme."""
visible = models.BooleanField(default=False)
<|code_end|>
, determine the next line of code. You have imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (class names, function names, or code) available:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | name = models.CharField(max_length=MAX_LENGTH_NAME) |
Continue the code snippet: <|code_start|> if not re.search('^[A-Za-z0-9_]+$', shortname):
raise forms.ValidationError(
gettext('Invalid name inside theme file.'))
release_stable = Release.objects.get(version='stable')
release_devel = Release.objects.get(version='devel')
if props['weechat'] not in (release_stable.description,
re.sub('-.*', '',
release_devel.description)):
raise forms.ValidationError(
gettext('Invalid WeeChat version, too old!'))
_file.seek(0)
return _file
def get_theme_choices():
"""Get list of themes for update form."""
try:
theme_list = Theme.objects.filter(visible=1).order_by('name')
theme_choices = []
theme_choices.append(('', gettext('Choose…')))
for theme in theme_list:
theme_choices.append((theme.id, f'{theme.name} ({theme.version})'))
return theme_choices
except: # noqa: E722 pylint: disable=bare-except
return []
class ThemeFormUpdate(Form):
"""Form to update a theme."""
required_css_class = 'required'
<|code_end|>
. Use current file imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (classes, functions, or code) from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | theme = ChoiceField( |
Given the code snippet: <|code_start|>
def get_sha512sum(self):
"""
Return the theme SHA512 (if known), or compute it with the file
if it is not set in database.
"""
return self.sha512sum or self.checksum(hashlib.sha512)
class Meta:
ordering = ['-added']
class ThemeFormAdd(Form):
"""Form to add a theme."""
required_css_class = 'required'
themefile = FileField(
label=gettext_lazy('File'),
help_text=gettext_lazy('The theme.'),
widget=forms.FileInput(attrs={'autofocus': True}),
)
description = CharField(
required=False,
max_length=MAX_LENGTH_DESC,
label=gettext_lazy('Description'),
)
author = CharField(
max_length=MAX_LENGTH_AUTHOR,
label=gettext_lazy('Your name or nick'),
help_text=gettext_lazy('Used for themes page.'),
)
<|code_end|>
, generate the next line using the imports in this file:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (functions, classes, or occasionally code) from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | mail = EmailField( |
Using the snippet: <|code_start|>
def checksum(self, hash_func):
"""Return theme checksum using the hash function (from hashlib)."""
try:
with open(self.filename(), 'rb') as _file:
return hash_func(_file.read()).hexdigest()
except: # noqa: E722 pylint: disable=bare-except
return ''
def get_md5sum(self):
"""
Return the theme MD5 (if known), or compute it with the file
if it is not set in database.
"""
return self.md5sum or self.checksum(hashlib.md5)
def get_sha512sum(self):
"""
Return the theme SHA512 (if known), or compute it with the file
if it is not set in database.
"""
return self.sha512sum or self.checksum(hashlib.sha512)
class Meta:
ordering = ['-added']
class ThemeFormAdd(Form):
"""Form to add a theme."""
required_css_class = 'required'
<|code_end|>
, determine the next line of code. You have imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (class names, function names, or code) available:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | themefile = FileField( |
Here is a snippet: <|code_start|> """Form to add a theme."""
required_css_class = 'required'
themefile = FileField(
label=gettext_lazy('File'),
help_text=gettext_lazy('The theme.'),
widget=forms.FileInput(attrs={'autofocus': True}),
)
description = CharField(
required=False,
max_length=MAX_LENGTH_DESC,
label=gettext_lazy('Description'),
)
author = CharField(
max_length=MAX_LENGTH_AUTHOR,
label=gettext_lazy('Your name or nick'),
help_text=gettext_lazy('Used for themes page.'),
)
mail = EmailField(
max_length=MAX_LENGTH_MAIL,
label=gettext_lazy('Your e-mail'),
help_text=gettext_lazy('No spam, never displayed.'),
widget=Html5EmailInput(),
)
comment = CharField(
required=False,
max_length=1024,
label=gettext_lazy('Comments'),
help_text=gettext_lazy('Not displayed.'),
widget=forms.Textarea(attrs={'rows': '3'}),
)
<|code_end|>
. Write the next line using the current file imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may include functions, classes, or code. Output only the next line. | test = TestField( |
Here is a snippet: <|code_start|> if it is not set in database.
"""
return self.sha512sum or self.checksum(hashlib.sha512)
class Meta:
ordering = ['-added']
class ThemeFormAdd(Form):
"""Form to add a theme."""
required_css_class = 'required'
themefile = FileField(
label=gettext_lazy('File'),
help_text=gettext_lazy('The theme.'),
widget=forms.FileInput(attrs={'autofocus': True}),
)
description = CharField(
required=False,
max_length=MAX_LENGTH_DESC,
label=gettext_lazy('Description'),
)
author = CharField(
max_length=MAX_LENGTH_AUTHOR,
label=gettext_lazy('Your name or nick'),
help_text=gettext_lazy('Used for themes page.'),
)
mail = EmailField(
max_length=MAX_LENGTH_MAIL,
label=gettext_lazy('Your e-mail'),
help_text=gettext_lazy('No spam, never displayed.'),
<|code_end|>
. Write the next line using the current file imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may include functions, classes, or code. Output only the next line. | widget=Html5EmailInput(), |
Using the snippet: <|code_start|> if match:
props[match.group(1)] = match.group(2)
return props
def checksum(self, hash_func):
"""Return theme checksum using the hash function (from hashlib)."""
try:
with open(self.filename(), 'rb') as _file:
return hash_func(_file.read()).hexdigest()
except: # noqa: E722 pylint: disable=bare-except
return ''
def get_md5sum(self):
"""
Return the theme MD5 (if known), or compute it with the file
if it is not set in database.
"""
return self.md5sum or self.checksum(hashlib.md5)
def get_sha512sum(self):
"""
Return the theme SHA512 (if known), or compute it with the file
if it is not set in database.
"""
return self.sha512sum or self.checksum(hashlib.sha512)
class Meta:
ordering = ['-added']
<|code_end|>
, determine the next line of code. You have imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (class names, function names, or code) available:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | class ThemeFormAdd(Form): |
Given the code snippet: <|code_start|> name = models.CharField(max_length=MAX_LENGTH_NAME)
version = models.CharField(max_length=MAX_LENGTH_VERSION)
md5sum = models.CharField(max_length=MAX_LENGTH_MD5SUM, blank=True)
sha512sum = models.CharField(max_length=MAX_LENGTH_SHA512SUM, blank=True)
desc = models.CharField(max_length=MAX_LENGTH_DESC, blank=True)
comment = models.CharField(max_length=MAX_LENGTH_COMMENT, blank=True)
author = models.CharField(max_length=MAX_LENGTH_AUTHOR)
mail = models.CharField(max_length=MAX_LENGTH_MAIL)
added = models.DateTimeField()
updated = models.DateTimeField(null=True)
def __str__(self):
return f'{self.name} - {self.author} ({self.version}, {self.added})'
def short_name(self):
"""Return short name (without extension)."""
pos = self.name.find('.')
if pos > 0:
return self.name[0:pos]
return self.name
def path(self):
"""Return path to theme (for URL)."""
pending = ''
if not self.visible:
pending = '/pending'
return f'themes{pending}'
def html_preview(self):
"""Return HTML with theme preview."""
<|code_end|>
, generate the next line using the imports in this file:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (functions, classes, or occasionally code) from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | filename = files_path_join('themes', 'html', |
Based on the snippet: <|code_start|> max_length=64,
label=gettext_lazy('Are you a spammer?'),
help_text=gettext_lazy('Enter "no" if you are not a spammer.'),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label_suffix = ''
def clean_themefile(self):
"""Check if theme file is valid."""
_file = self.cleaned_data['themefile']
if _file.size > 512*1024:
raise forms.ValidationError(gettext('Theme file too big.'))
content = _file.read()
if isinstance(content, bytes):
content = content.decode('utf-8')
props = Theme.get_props(content)
if 'name' not in props or 'weechat' not in props:
raise forms.ValidationError(gettext('Invalid theme file.'))
themes = Theme.objects.filter(name=props['name'])
if themes:
raise forms.ValidationError(gettext('This name already exists.'))
if not props['name'].endswith('.theme'):
raise forms.ValidationError(
gettext('Invalid name inside theme file.'))
shortname = props['name'][0:-6]
if not re.search('^[A-Za-z0-9_]+$', shortname):
raise forms.ValidationError(
gettext('Invalid name inside theme file.'))
<|code_end|>
, predict the immediate next line with the help of imports:
import gzip
import hashlib
import json
import os
import re
import tarfile
from collections import OrderedDict
from io import open
from xml.sax.saxutils import escape
from django import forms
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy
from weechat.common.decorators import disable_for_loaddata
from weechat.common.forms import (
CharField,
ChoiceField,
EmailField,
FileField,
TestField,
Html5EmailInput,
Form,
)
from weechat.common.path import files_path_join
from weechat.download.models import Release
and context (classes, functions, sometimes code) from other files:
# Path: weechat/common/decorators.py
# def disable_for_loaddata(signal_handler):
# """
# Decorator that turns off signal handlers when loading fixture data.
# """
# @wraps(signal_handler)
# def wrapper(*args, **kwargs):
# if kwargs.get('raw'):
# return
# signal_handler(*args, **kwargs)
# return wrapper
#
# Path: weechat/common/forms.py
# class CharField(forms.CharField):
# """Char field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class ChoiceField(forms.ChoiceField):
# """Choice field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class EmailField(forms.EmailField):
# """E-mail field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class FileField(forms.FileField):
# """File field in new script form."""
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class TestField(forms.CharField):
# """Anti-spam field in forms."""
#
# def clean(self, value):
# if not value:
# raise forms.ValidationError(gettext('This field is required.'))
# if value.lower() != 'no':
# raise forms.ValidationError(gettext('This field is required.'))
# return value
#
# def get_bound_field(self, form, field_name):
# return BootstrapBoundField(form, self, field_name)
#
# class Html5EmailInput(forms.widgets.Input):
# """E-mail field (with HTML5 validator)."""
# input_type = 'email'
#
# class Form(forms.Form):
# """Form with "as_div" method."""
#
# def as_div(self):
# "Return this form rendered as HTML <div>s."
# return self._html_output(
# normal_row=('<div%(html_class_attr)s class="form-group row">'
# '%(label)s'
# '<div class="col-12 col-md-9 col-lg-10">'
# '%(field)s%(help_text)s'
# '</div>'
# '</div>'),
# error_row='%s',
# row_ender='</p>',
# help_text_html=' <span class="helptext">%s</span>',
# errors_on_separate_row=True)
#
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | release_stable = Release.objects.get(version='stable') |
Next line prediction: <|code_start|> class Meta:
ordering = ['priority']
class Package(models.Model):
"""A WeeChat package."""
version = models.ForeignKey(Release, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
filename = models.CharField(max_length=512, blank=True)
sha1sum = models.CharField(max_length=128, blank=True)
sha512sum = models.CharField(max_length=128, blank=True)
display_time = models.BooleanField(default=False)
directory = models.CharField(max_length=256, blank=True)
url = models.CharField(max_length=512, blank=True)
text = models.CharField(max_length=512, blank=True)
def __str__(self):
if self.filename != '':
string = self.filename
elif self.directory != '':
string = self.directory
elif self.url != '':
string = self.url
else:
string = self.text
return f'{self.version.version}-{self.type.type}, {string}'
def fullname(self):
"""Return the path for package."""
if self.filename:
<|code_end|>
. Use current file imports:
(from datetime import datetime
from hashlib import sha1, sha512
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from weechat.common.path import files_path_join
from weechat.common.templatetags.localdate import localdate
from weechat.common.utils import version_to_tuple
import os
import pytz)
and context including class names, function names, or small code snippets from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/utils.py
# def version_to_tuple(version):
# """Convert version to a tuple of integers."""
# return tuple(map(int, version.split('.')))
. Output only the next line. | return files_path_join(self.type.directory, self.filename) |
Here is a snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Models for "download" menu."""
class Release(models.Model):
"""A WeeChat release."""
version = models.CharField(max_length=64, primary_key=True)
description = models.CharField(max_length=64, blank=True)
date = models.DateField(blank=True, null=True)
security_issues_fixed = models.IntegerField(default=0)
securityfix = models.CharField(max_length=256, blank=True)
def __str__(self):
security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
if self.security_issues_fixed > 0 else '')
fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
if self.securityfix else '')
return f'{self.version} ({self.date}){security_fix}{fixed_in}'
def date_l10n(self):
"""Return the release date formatted with localized date format."""
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from hashlib import sha1, sha512
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from weechat.common.path import files_path_join
from weechat.common.templatetags.localdate import localdate
from weechat.common.utils import version_to_tuple
import os
import pytz
and context from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/utils.py
# def version_to_tuple(version):
# """Convert version to a tuple of integers."""
# return tuple(map(int, version.split('.')))
, which may include functions, classes, or code. Output only the next line. | return localdate(self.date) |
Given the following code snippet before the placeholder: <|code_start|>
class Release(models.Model):
"""A WeeChat release."""
version = models.CharField(max_length=64, primary_key=True)
description = models.CharField(max_length=64, blank=True)
date = models.DateField(blank=True, null=True)
security_issues_fixed = models.IntegerField(default=0)
securityfix = models.CharField(max_length=256, blank=True)
def __str__(self):
security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
if self.security_issues_fixed > 0 else '')
fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
if self.securityfix else '')
return f'{self.version} ({self.date}){security_fix}{fixed_in}'
def date_l10n(self):
"""Return the release date formatted with localized date format."""
return localdate(self.date)
def security_fixed_versions(self):
"""Return the list of versions fixing security issues."""
return self.securityfix.split(',')
@property
def is_released(self):
"""Return True if the version is released."""
stable_version = Release.objects.get(version='stable').description
<|code_end|>
, predict the next line using imports from the current file:
from datetime import datetime
from hashlib import sha1, sha512
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from weechat.common.path import files_path_join
from weechat.common.templatetags.localdate import localdate
from weechat.common.utils import version_to_tuple
import os
import pytz
and context including class names, function names, and sometimes code from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/common/utils.py
# def version_to_tuple(version):
# """Convert version to a tuple of integers."""
# return tuple(map(int, version.split('.')))
. Output only the next line. | stable_version_tuple = version_to_tuple(stable_version) |
Given the following code snippet before the placeholder: <|code_start|> if len(self.description) < 100
else f'{self.description[0:100]}…')
version = (f'({self.version.version})' if self.visible
else self.version.version)
tracker = self.tracker if self.tracker else '-'
return (f'{version}, {tracker}, {self.status}%, {self.component}: '
f'{desc} ({self.priority})')
def version_date(self):
"""Return the date of version.
It is prefixed with "≈ " if the date is in the future.
"""
try:
if self.version.date > date.today():
return mark_safe(f'≈ {localdate(self.version.date)}')
return localdate(self.version.date)
except: # noqa: E722 pylint: disable=bare-except
return ''
def url_tracker(self):
"""Return the tracker URL using keyword(s) in string."""
return tracker_links(self.tracker) or '-'
def status_remaining(self):
"""Return the remaining status as % (100 - status)."""
return 100 - self.status
def url_commits(self):
"""Return the URL for commit(s), as HTML."""
<|code_end|>
, predict the next line using imports from the current file:
from datetime import date
from django.db import models
from django.utils.safestring import mark_safe
from weechat.common.tracker import commits_links, tracker_links
from weechat.common.templatetags.localdate import localdate
from weechat.download.models import Release
and context including class names, function names, and sometimes code from other files:
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | return commits_links(self.commits) |
Here is a snippet: <|code_start|> status = models.IntegerField(default=0)
commits = models.CharField(max_length=1024, blank=True)
component = models.CharField(max_length=64, default='core')
description = models.CharField(max_length=512)
priority = models.IntegerField(default=0)
def __str__(self):
desc = (self.description
if len(self.description) < 100
else f'{self.description[0:100]}…')
version = (f'({self.version.version})' if self.visible
else self.version.version)
tracker = self.tracker if self.tracker else '-'
return (f'{version}, {tracker}, {self.status}%, {self.component}: '
f'{desc} ({self.priority})')
def version_date(self):
"""Return the date of version.
It is prefixed with "≈ " if the date is in the future.
"""
try:
if self.version.date > date.today():
return mark_safe(f'≈ {localdate(self.version.date)}')
return localdate(self.version.date)
except: # noqa: E722 pylint: disable=bare-except
return ''
def url_tracker(self):
"""Return the tracker URL using keyword(s) in string."""
<|code_end|>
. Write the next line using the current file imports:
from datetime import date
from django.db import models
from django.utils.safestring import mark_safe
from weechat.common.tracker import commits_links, tracker_links
from weechat.common.templatetags.localdate import localdate
from weechat.download.models import Release
and context from other files:
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may include functions, classes, or code. Output only the next line. | return tracker_links(self.tracker) or '-' |
Predict the next line for this snippet: <|code_start|>
class Task(models.Model):
"""A task (a new feature or bug to fix)."""
visible = models.BooleanField(default=True)
version = models.ForeignKey(Release, on_delete=models.CASCADE)
tracker = models.CharField(max_length=64, blank=True)
spec = models.CharField(max_length=512, blank=True)
status = models.IntegerField(default=0)
commits = models.CharField(max_length=1024, blank=True)
component = models.CharField(max_length=64, default='core')
description = models.CharField(max_length=512)
priority = models.IntegerField(default=0)
def __str__(self):
desc = (self.description
if len(self.description) < 100
else f'{self.description[0:100]}…')
version = (f'({self.version.version})' if self.visible
else self.version.version)
tracker = self.tracker if self.tracker else '-'
return (f'{version}, {tracker}, {self.status}%, {self.component}: '
f'{desc} ({self.priority})')
def version_date(self):
"""Return the date of version.
It is prefixed with "≈ " if the date is in the future.
"""
try:
if self.version.date > date.today():
<|code_end|>
with the help of current file imports:
from datetime import date
from django.db import models
from django.utils.safestring import mark_safe
from weechat.common.tracker import commits_links, tracker_links
from weechat.common.templatetags.localdate import localdate
from weechat.download.models import Release
and context from other files:
# Path: weechat/common/tracker.py
# def commits_links(commits):
# """Replace commits or branches by GitHub URLs."""
# if not commits:
# return ''
#
# # read SVG with git commit/branch
# filename = project_path_join('templates', 'svg', 'git-commit.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_commit = _file.read().strip()
# filename = project_path_join('templates', 'svg', 'git-branch.html')
# with open(filename, 'r', encoding='utf-8') as _file:
# svg_branch = _file.read().strip()
#
# images = []
# for commit in commits.split(','):
# objtype = 'commit'
# link = svg_commit
# if commit.startswith('commit/'):
# commit = commit[7:]
# if commit.startswith('tree/'):
# objtype = 'tree'
# commit = commit[5:]
# link = svg_branch
# repo, commit_id = split_commit(commit)
# images.append(f'<a href="https://github.com/{repo}/{objtype}/'
# f'{commit_id}" target="_blank" rel="noopener">'
# f'{link}</a>')
# return mark_safe(' '.join(images))
#
# def tracker_links(tracker):
# """Replace tracker items by URLs.
#
# Replace GitHub tracker item(s) (for example: "closes #123")
# and savannah tracker item(s) (for example: "bug #12345")
# by URL(s) to this/these item(s).
# """
# if not tracker:
# return ''
# items = [_replace_link(item) for item in tracker.split(',')]
# return mark_safe('<br>'.join(items))
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may contain function names, class names, or code. Output only the next line. | return mark_safe(f'≈ {localdate(self.version.date)}') |
Predict the next line after this snippet: <|code_start|> if strings:
content += [
'',
'from django.utils.translation import gettext_noop',
'',
'',
f'def __i18n_{app}_{name}():',
f' """Translations for {app}/{name}."""',
]
done = set()
for string in sorted(strings):
if isinstance(string, tuple):
# if type is tuple of 2 strings: use the second as note for
# translators
(message, translators) = (string[0], string[1])
else:
# single string (no note for translators)
(message, translators) = (string, None)
# add string if not already done
if message not in done:
if translators:
content.append(f' # Translators: {translators}')
message = (message
.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\r\n', '\\n'))
content.append(f' gettext_noop("{message}")')
done.add(message)
content.append('')
# write file
<|code_end|>
using the current file's imports:
from io import open
from weechat.common.path import project_path_join
and any relevant context from other files:
# Path: weechat/common/path.py
# def project_path_join(*args):
# """Join multiple paths after settings.BASE_DIR."""
# return __path_join(settings.BASE_DIR, *args)
. Output only the next line. | filename = project_path_join(app, f'_i18n_{name}.py') |
Based on the snippet: <|code_start|> return ''
items = [_replace_link(item) for item in tracker.split(',')]
return mark_safe('<br>'.join(items))
def split_commit(commit):
"""
Return repository and commit id with a commit name, with one of these
formats:
org/repo@commit
repo@commit
commit
Default repository is weechat/weechat.
"""
if '@' not in commit:
return ('weechat/weechat', commit)
repo, commit_id = commit.split('@', 1)
if '/' not in repo:
repo = f'weechat/{repo}'
return (repo, commit_id)
def commits_links(commits):
"""Replace commits or branches by GitHub URLs."""
if not commits:
return ''
# read SVG with git commit/branch
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from django.utils.safestring import mark_safe
from weechat.common.path import project_path_join
and context (classes, functions, sometimes code) from other files:
# Path: weechat/common/path.py
# def project_path_join(*args):
# """Join multiple paths after settings.BASE_DIR."""
# return __path_join(settings.BASE_DIR, *args)
. Output only the next line. | filename = project_path_join('templates', 'svg', 'git-commit.html') |
Continue the code snippet: <|code_start|> return f'{gettext(match.group(1))} {match.group(2)}'
return gettext(self.title)
def text_i18n(self):
"""Return translated text."""
if self.text:
return gettext(self.text.replace('\r\n', '\n'))
return ''
def date_title_url(self):
"""Return date+title to include in URL."""
text_url = re.sub(' +', '-',
re.sub('[^ a-zA-Z0-9.]', ' ', self.title).strip())
return (f'{self.date.year:0>4}{self.date.month:0>2}{self.date.day:0>2}'
f'-{text_url}')
def handler_info_saved(sender, **kwargs):
"""Write file _i18n_info.py with infos to translate."""
# pylint: disable=unused-argument
strings = []
for info in Info.objects.filter(visible=1).order_by('-date'):
match = PATTERN_TITLE_VERSION.match(info.title)
if match:
# if the title is "Version x.y.z", translate only "Version"
strings.append(match.group(1))
else:
strings.append(info.title)
if info.text:
strings.append(info.text)
<|code_end|>
. Use current file imports:
import re
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import gettext
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
and context (classes, functions, or code) from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
. Output only the next line. | i18n_autogen('news', 'info', strings) |
Here is a snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Models for news."""
PATTERN_TITLE_VERSION = re.compile('(Version) ([0-9.a-z-]*)$')
class Info(models.Model):
"""A WeeChat info."""
visible = models.BooleanField(default=False)
date = models.DateTimeField()
title = models.CharField(max_length=64)
author = models.CharField(max_length=256)
mail = models.EmailField(max_length=256)
text = models.TextField(blank=True)
def __str__(self):
return f'{self.title} ({self.date})'
def date_l10n(self):
"""Return the info date formatted with localized date format."""
<|code_end|>
. Write the next line using the current file imports:
import re
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import gettext
from weechat.common.i18n import i18n_autogen
from weechat.common.templatetags.localdate import localdate
and context from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/templatetags/localdate.py
# @register.filter()
# def localdate(value, fmt='date'):
# """
# Format date with localized date/time format.
# If fmt == "date", the localized date format is used.
# If fmt == "datetime", the localized date/fime format is used.
# Another fmt it is used as-is.
# """
# if fmt == 'date':
# fmt = gettext(settings.DATE_FORMAT)
# elif fmt == 'datetime':
# fmt = gettext(settings.DATETIME_FORMAT)
# date_iso = value.isoformat()
# date_fmt = dateformat.format(value, fmt)
# return mark_safe(f'<time datetime="{date_iso}">{date_fmt}</time>')
, which may include functions, classes, or code. Output only the next line. | return localdate(self.date) |
Here is a snippet: <|code_start|># the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# WeeChat.org is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Views for news."""
def home(request, max_info=None, max_event=None):
"""Homepage."""
now = datetime.now()
info_list = (Info.objects.all().filter(visible=1).filter(date__lte=now)
.order_by('-date'))
if max_info:
info_list = info_list[:max_info]
event_list = (Info.objects.all().filter(visible=1).filter(date__gt=now)
.order_by('date'))
if max_event:
event_list = event_list[:max_event]
try:
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from weechat.download.models import Release
from weechat.news.models import Info
and context from other files:
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
#
# Path: weechat/news/models.py
# class Info(models.Model):
# """A WeeChat info."""
# visible = models.BooleanField(default=False)
# date = models.DateTimeField()
# title = models.CharField(max_length=64)
# author = models.CharField(max_length=256)
# mail = models.EmailField(max_length=256)
# text = models.TextField(blank=True)
#
# def __str__(self):
# return f'{self.title} ({self.date})'
#
# def date_l10n(self):
# """Return the info date formatted with localized date format."""
# return localdate(self.date)
#
# def title_i18n(self):
# """Return translated title."""
# match = PATTERN_TITLE_VERSION.match(self.title)
# if match:
# # if the title is "Version x.y.z", translate only "Version"
# return f'{gettext(match.group(1))} {match.group(2)}'
# return gettext(self.title)
#
# def text_i18n(self):
# """Return translated text."""
# if self.text:
# return gettext(self.text.replace('\r\n', '\n'))
# return ''
#
# def date_title_url(self):
# """Return date+title to include in URL."""
# text_url = re.sub(' +', '-',
# re.sub('[^ a-zA-Z0-9.]', ' ', self.title).strip())
# return (f'{self.date.year:0>4}{self.date.month:0>2}{self.date.day:0>2}'
# f'-{text_url}')
, which may include functions, classes, or code. Output only the next line. | stable_version = Release.objects.get(version='stable').description |
Predict the next line for this snippet: <|code_start|># along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""URLs for "about" menu."""
# pylint: disable=invalid-name, no-value-for-parameter
URL_ABOUT_EXTRA = getattr(settings, 'URL_ABOUT_EXTRA', 'extra')
urlpatterns = [
path('', TemplateView.as_view(template_name='about/features.html'),
name='about'),
path('features/',
TemplateView.as_view(template_name='about/features.html'),
name='about_features'),
path('interfaces/',
TemplateView.as_view(template_name='about/interfaces.html'),
name='about_interfaces'),
path('screenshots/', view_screenshots, name='about_screenshots'),
re_path(r'^screenshots/(?P<app>weechat|relay)/$', view_screenshots,
name='about_screenshots_app'),
re_path(r'^screenshots/(?P<app>weechat|relay)/'
r'(?P<filename>[a-zA-Z0-9_\-.]*)/$',
view_screenshots, name='about_screenshot'),
path('screenshots/<str:filename>/', view_screenshots),
path('history/', view_history, name='about_history'),
path('support/', TemplateView.as_view(template_name='about/support.html'),
name='about_support'),
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.urls import path, re_path
from django.views.generic.base import TemplateView
from weechat.about.views import (
screenshots as view_screenshots,
history as view_history,
about as view_about,
)
and context from other files:
# Path: weechat/about/views.py
# def screenshots(request, app='weechat', filename=''):
# """
# Page with one screenshot (if filename given),
# or all screenshots as thumbnails.
# """
# if filename:
# try:
# screenshot = Screenshot.objects.get(app=app, filename=filename)
# except ObjectDoesNotExist:
# screenshot = None
# return render(
# request,
# 'about/screenshots.html',
# {
# 'app': app,
# 'filename': filename,
# 'screenshot': screenshot,
# },
# )
# screenshot_list = Screenshot.objects.filter(app=app).order_by('priority')
# return render(
# request,
# 'about/screenshots.html',
# {
# 'app': app,
# 'screenshot_list': screenshot_list,
# },
# )
#
# def history(request):
# """Page with WeeChat history, including key dates."""
# release_list = (Release.objects.all().exclude(version='devel')
# .order_by('-date'))
# releases = []
# for release in release_list:
# name = f'weechat-{release.version}.png'
# if os.path.exists(media_path_join('images', 'story', name)):
# releases.append((release.version, release.date))
# return render(
# request,
# 'about/history.html',
# {
# 'releases': releases,
# 'keydate_list': Keydate.objects.all().order_by('date'),
# },
# )
#
# def about(request, extra_info=False):
# """About WeeChat.org."""
# context = {}
# if extra_info:
# context.update({
# 'extra_info': {
# 'django': django_version,
# 'python': python_version,
# },
# })
# return render(request, 'about/weechat.org.html', context)
, which may contain function names, class names, or code. Output only the next line. | path('weechat.org/', view_about, name='about_weechat.org'), |
Next line prediction: <|code_start|> Return the URL to use with apt for binary packages, for example:
"deb [signed-by=/usr/share/keyrings/weechat-archive-keyring.gpg]
https://weechat.org/debian sid main".
"""
return (f'deb [signed-by=/usr/share/keyrings/weechat-archive-'
f'keyring.gpg] {self.url} {self.version.codename} main')
def apt_url_src(self):
"""
Return the URL to use with apt for sources packages, for example:
"deb-src [signed-by=/usr/share/keyrings/weechat-archive-
keyring.gpg] https://weechat.org/debian sid main".
"""
return (
f'deb-src [signed-by=/usr/share/keyrings/weechat-'
f'archive-keyring.gpg] {self.url} {self.version.codename} main'
)
class Meta:
"""Sort Repos by priority."""
ordering = ['priority']
def handler_repo_saved(sender, **kwargs):
"""Handler called when a Repo is saved."""
# pylint: disable=unused-argument
strings = []
for repo in Repo.objects.order_by('priority'):
if repo.message:
strings.append(repo.message)
<|code_end|>
. Use current file imports:
(from django.db import models
from django.db.models.signals import post_save
from weechat.common.i18n import i18n_autogen
from weechat.common.path import repo_path_join)
and context including class names, function names, or small code snippets from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/path.py
# def repo_path_join(*args):
# """Join multiple paths after settings.REPO_DIR."""
# return __path_join(settings.REPO_DIR, *args)
. Output only the next line. | i18n_autogen('debian', 'repo', strings) |
Next line prediction: <|code_start|> """The nick and name of person building packages in this repository."""
nick = models.CharField(max_length=64, primary_key=True)
name = models.CharField(max_length=128)
def __str__(self):
return f'{self.name} ({self.nick})'
class Repo(models.Model):
"""A Debian repository."""
visible = models.BooleanField(default=True)
active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
version = models.ForeignKey(Version, on_delete=models.CASCADE)
url = models.CharField(max_length=512)
arch = models.CharField(max_length=128)
builder = models.ForeignKey(Builder, on_delete=models.CASCADE)
# in hours, 0 = unknown frequency (next build date is not displayed)
build_frequency = models.IntegerField(default=24)
message = models.CharField(max_length=1024, blank=True)
priority = models.IntegerField(default=0)
def __str__(self):
visible = 'visible' if self.visible else 'hidden'
active = 'active' if self.active else 'discontinued'
return (f'{self.name} {self.version}, {visible}, {active} '
f'({self.arch}) ({self.priority})')
def path_packages_gz(self, arch):
"""Return path/name to the Packages.gz file of repository."""
<|code_end|>
. Use current file imports:
(from django.db import models
from django.db.models.signals import post_save
from weechat.common.i18n import i18n_autogen
from weechat.common.path import repo_path_join)
and context including class names, function names, or small code snippets from other files:
# Path: weechat/common/i18n.py
# def i18n_autogen(app, name, strings):
# """Create a file '_i18n_xxx.py' with strings to translate."""
# # build content of file
# content = [
# '# This file is auto-generated after changes in database, '
# 'DO NOT EDIT!',
# '',
# f'"""Translations for {app}/{name}."""',
# '',
# '# flake8: noqa',
# '# pylint: disable=line-too-long,too-many-statements',
# ]
# if strings:
# content += [
# '',
# 'from django.utils.translation import gettext_noop',
# '',
# '',
# f'def __i18n_{app}_{name}():',
# f' """Translations for {app}/{name}."""',
# ]
# done = set()
# for string in sorted(strings):
# if isinstance(string, tuple):
# # if type is tuple of 2 strings: use the second as note for
# # translators
# (message, translators) = (string[0], string[1])
# else:
# # single string (no note for translators)
# (message, translators) = (string, None)
# # add string if not already done
# if message not in done:
# if translators:
# content.append(f' # Translators: {translators}')
# message = (message
# .replace('\\', '\\\\')
# .replace('"', '\\"')
# .replace('\r\n', '\\n'))
# content.append(f' gettext_noop("{message}")')
# done.add(message)
# content.append('')
# # write file
# filename = project_path_join(app, f'_i18n_{name}.py')
# with open(filename, 'w', encoding='utf-8') as _file:
# data = '\n'.join(content)
# if hasattr(data, 'decode') and isinstance(data, str):
# data = data.decode('utf-8')
# _file.write(data)
#
# Path: weechat/common/path.py
# def repo_path_join(*args):
# """Join multiple paths after settings.REPO_DIR."""
# return __path_join(settings.REPO_DIR, *args)
. Output only the next line. | return repo_path_join(self.name, 'dists', |
Predict the next line for this snippet: <|code_start|>
def get_repository_packages(repository):
"""Get list of packages for a repository."""
# pylint: disable=too-many-locals
timezone = pytz.timezone(settings.TIME_ZONE)
now = datetime.now(tz=timezone)
repopkgs = []
for arch in repository.arch.split(','):
build = {
'id': f'{repository.name}_{repository.version.version}',
'repo': repository,
'arch': arch,
'date': None,
'files': [],
}
filename = repository.path_packages_gz(arch)
build['date'] = os.stat(filename).st_mtime
with gzip.open(filename, 'rb') as _file:
pkg = {}
for line in _file.readlines():
line = line.strip().decode('utf-8')
if len(line) == 0:
if pkg:
pkg['repoarch'] = (f'{repository.name}_'
f'{repository.version.codename}')
pkg['repo'] = repository
pkg['distro'] = repository.name
pkg['arch'] = arch
<|code_end|>
with the help of current file imports:
from datetime import datetime, timedelta
from django.conf import settings
from django.shortcuts import render
from weechat.common.path import repo_path_join
from weechat.debian.models import Repo
import gzip
import os
import re
import pytz
and context from other files:
# Path: weechat/common/path.py
# def repo_path_join(*args):
# """Join multiple paths after settings.REPO_DIR."""
# return __path_join(settings.REPO_DIR, *args)
#
# Path: weechat/debian/models.py
# class Repo(models.Model):
# """A Debian repository."""
# visible = models.BooleanField(default=True)
# active = models.BooleanField(default=True)
# name = models.CharField(max_length=64)
# version = models.ForeignKey(Version, on_delete=models.CASCADE)
# url = models.CharField(max_length=512)
# arch = models.CharField(max_length=128)
# builder = models.ForeignKey(Builder, on_delete=models.CASCADE)
# # in hours, 0 = unknown frequency (next build date is not displayed)
# build_frequency = models.IntegerField(default=24)
# message = models.CharField(max_length=1024, blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# visible = 'visible' if self.visible else 'hidden'
# active = 'active' if self.active else 'discontinued'
# return (f'{self.name} {self.version}, {visible}, {active} '
# f'({self.arch}) ({self.priority})')
#
# def path_packages_gz(self, arch):
# """Return path/name to the Packages.gz file of repository."""
# return repo_path_join(self.name, 'dists',
# self.version.codename, 'main',
# f'binary-{arch}', 'Packages.gz')
#
# def apt_url(self):
# """
# Return the URL to use with apt for binary packages, for example:
# "deb [signed-by=/usr/share/keyrings/weechat-archive-keyring.gpg]
# https://weechat.org/debian sid main".
# """
# return (f'deb [signed-by=/usr/share/keyrings/weechat-archive-'
# f'keyring.gpg] {self.url} {self.version.codename} main')
#
# def apt_url_src(self):
# """
# Return the URL to use with apt for sources packages, for example:
# "deb-src [signed-by=/usr/share/keyrings/weechat-archive-
# keyring.gpg] https://weechat.org/debian sid main".
# """
# return (
# f'deb-src [signed-by=/usr/share/keyrings/weechat-'
# f'archive-keyring.gpg] {self.url} {self.version.codename} main'
# )
#
# class Meta:
# """Sort Repos by priority."""
# ordering = ['priority']
, which may contain function names, class names, or code. Output only the next line. | pkgfilename = repo_path_join(repository.name, |
Using the snippet: <|code_start|> pkg['size'] = fstat.st_size
date_time = datetime.fromtimestamp(fstat.st_mtime,
tz=timezone)
pkg['builddatetime'] = date_time
add_hours = repository.build_frequency
if repository.active and add_hours > 0:
nextbuilddatetime = (date_time +
timedelta(hours=add_hours))
if nextbuilddatetime > now:
pkg['nextbuilddatetime'] = nextbuilddatetime
pkg['basename'] = os.path.basename(pkg['Filename'])
pkg['anchor'] = (f'{repository.name}_'
f'{repository.version.codename}_'
f'{pkg["Version"]}_{arch}')
if 'Source' not in pkg:
pkg['Source'] = pkg['Package']
pkg['version_type'] = ('dev'
if 'dev' in pkg['Version']
else 'stable')
repopkgs.append(pkg)
pkg = {}
match = re.match('^([^ ]+): (.*)$', line)
if match:
pkg[match.group(1)] = match.group(2)
return repopkgs
def repos(request, active='active', files=''):
"""Page with debian repositories."""
if active == 'active':
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime, timedelta
from django.conf import settings
from django.shortcuts import render
from weechat.common.path import repo_path_join
from weechat.debian.models import Repo
import gzip
import os
import re
import pytz
and context (class names, function names, or code) available:
# Path: weechat/common/path.py
# def repo_path_join(*args):
# """Join multiple paths after settings.REPO_DIR."""
# return __path_join(settings.REPO_DIR, *args)
#
# Path: weechat/debian/models.py
# class Repo(models.Model):
# """A Debian repository."""
# visible = models.BooleanField(default=True)
# active = models.BooleanField(default=True)
# name = models.CharField(max_length=64)
# version = models.ForeignKey(Version, on_delete=models.CASCADE)
# url = models.CharField(max_length=512)
# arch = models.CharField(max_length=128)
# builder = models.ForeignKey(Builder, on_delete=models.CASCADE)
# # in hours, 0 = unknown frequency (next build date is not displayed)
# build_frequency = models.IntegerField(default=24)
# message = models.CharField(max_length=1024, blank=True)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# visible = 'visible' if self.visible else 'hidden'
# active = 'active' if self.active else 'discontinued'
# return (f'{self.name} {self.version}, {visible}, {active} '
# f'({self.arch}) ({self.priority})')
#
# def path_packages_gz(self, arch):
# """Return path/name to the Packages.gz file of repository."""
# return repo_path_join(self.name, 'dists',
# self.version.codename, 'main',
# f'binary-{arch}', 'Packages.gz')
#
# def apt_url(self):
# """
# Return the URL to use with apt for binary packages, for example:
# "deb [signed-by=/usr/share/keyrings/weechat-archive-keyring.gpg]
# https://weechat.org/debian sid main".
# """
# return (f'deb [signed-by=/usr/share/keyrings/weechat-archive-'
# f'keyring.gpg] {self.url} {self.version.codename} main')
#
# def apt_url_src(self):
# """
# Return the URL to use with apt for sources packages, for example:
# "deb-src [signed-by=/usr/share/keyrings/weechat-archive-
# keyring.gpg] https://weechat.org/debian sid main".
# """
# return (
# f'deb-src [signed-by=/usr/share/keyrings/weechat-'
# f'archive-keyring.gpg] {self.url} {self.version.codename} main'
# )
#
# class Meta:
# """Sort Repos by priority."""
# ordering = ['priority']
. Output only the next line. | repositories = (Repo.objects.all().filter(active=1).filter(visible=1) |
Predict the next line for this snippet: <|code_start|># This file is part of WeeChat.org.
#
# WeeChat.org is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# WeeChat.org is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""URLs for "download" menu."""
# pylint: disable=invalid-name, no-value-for-parameter
urlpatterns = [
path('', view_packages, name='download'),
path('debian/', view_repos, kwargs={'active': 'active'},
name='download_debian'),
re_path(r'^debian/(?P<active>(active|all))/$', view_repos,
name='download_debian_active'),
re_path(r'^debian/(?P<active>(active|all))/(?P<files>[a-zA-Z0-9.]*)/$',
view_repos),
<|code_end|>
with the help of current file imports:
from django.urls import path, re_path
from weechat.debian.views import repos as view_repos
from weechat.download.views import (
packages as view_packages,
package_checksums as view_package_checksums,
release as view_release,
)
and context from other files:
# Path: weechat/debian/views.py
# def repos(request, active='active', files=''):
# """Page with debian repositories."""
# if active == 'active':
# repositories = (Repo.objects.all().filter(active=1).filter(visible=1)
# .order_by('priority'))
# else:
# repositories = (Repo.objects.all().filter(visible=1)
# .order_by('priority'))
# debpkgs = []
# errors = []
# for repository in repositories:
# try:
# repo_packages = get_repository_packages(repository)
# debpkgs.extend(sorted(repo_packages,
# key=lambda p: p['builddatetime'],
# reverse=True))
# except: # noqa: E722 pylint: disable=bare-except
# errors.append(f'{repository.name} {repository.version}')
# return render(
# request,
# 'download/debian.html',
# {
# 'debpkgs': debpkgs,
# 'active': active,
# 'allfiles': files == 'files',
# 'repositories': repositories,
# 'errors': errors,
# },
# )
#
# Path: weechat/download/views.py
# def packages(request, version='stable'):
# """Page with packages for a version (stable, devel, all, old, or x.y.z)."""
# package_list = None
# release_progress = None
# try:
# if version == 'stable':
# stable_desc = Release.objects.get(version='stable').description
# package_list = (Package.objects.all().filter(version=stable_desc)
# .order_by('type__priority'))
# elif version == 'devel':
# package_list = (Package.objects.all().filter(version='devel')
# .order_by('type__priority'))
# elif version == 'all':
# package_list = (Package.objects.all().exclude(version='devel')
# .order_by('-version__date', 'type__priority'))
# elif version == 'old':
# stable_desc = Release.objects.get(version='stable').description
# package_list = (Package.objects.all().exclude(version='devel')
# .exclude(version=stable_desc)
# .order_by('-version__date', 'type__priority'))
# else:
# package_list = (Package.objects.filter(version=version)
# .order_by('type__priority'))
# release_progress = get_release_progress()
# except ObjectDoesNotExist:
# package_list = None
# release_progress = None
# return render(
# request,
# 'download/packages.html',
# {
# 'version': version,
# 'package_list': package_list,
# 'release_progress': release_progress,
# },
# )
#
# def package_checksums(request, version, checksum_type):
# """Page with checksums of packages in a version."""
# package_list = (Package.objects.filter(version=version)
# .order_by('type__priority'))
# checksums = []
# for package in package_list:
# checksum = package.checksum()
# if checksum:
# checksums.append(f'{checksum} {package.filename}')
# response = HttpResponse('\n'.join(checksums), content_type='text/plain')
# response['Content-disposition'] = (f'inline; filename=weechat-'
# f'{version}-{checksum_type}.txt')
# return response
#
# def release(request):
# """Page with release in progress."""
# return render(
# request,
# 'download/release.html',
# {
# 'release_progress': get_release_progress(),
# },
# )
, which may contain function names, class names, or code. Output only the next line. | path('release/', view_release, name='download_release'), |
Here is a snippet: <|code_start|> else:
# already released versions
task_list = (Task.objects.all().filter(visible=1)
.filter(version__lte=Release.objects.get(
version='stable').description)
.order_by('-version__date', 'priority'))
except ObjectDoesNotExist:
task_list = None
return render(
request,
'dev/roadmap.html',
{
'task_list': task_list,
'versions': versions,
},
)
def stats_repo(request, stats='weechat'):
"""Page with statistics about source code (git repositories)."""
repository = ''
sloc = ''
sloc_lang = ''
svg_list = ['authors', 'tickets_author', 'files_type', 'commits_year',
'commits_year_month', 'commits_day', 'commits_day_max',
'commits_day_week', 'commits_hour_day', 'commits_hour_week']
git_commits = ['?', '?', '?', '?']
scripts_downloads = None
try:
<|code_end|>
. Write the next line using the current file imports:
import re
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import gettext, gettext_lazy
from weechat.common.path import files_path_join, media_path_join
from weechat.common.templatetags.version import version_as_int
from weechat.dev.models import Task
from weechat.download.models import Release
and context from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/common/templatetags/version.py
# @register.filter()
# def version_as_int(version):
# """
# Return a string with number of version, for example: 0.4.1 gives:
# 262400 (0x00040100).
# """
# try:
# items = version.split('.', 3)
# value = [0, 0, 0, 0]
# for i in range(0, 4):
# if i < len(items):
# value[i] = int(re.sub('[^0-9].*', '', items[i]))
# if value[i] < 0:
# value[i] = 0
# elif value[i] > 0xFF:
# value[i] = 0xFF
# return (value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]
# except: # noqa: E722 pylint: disable=bare-except
# return 0
#
# Path: weechat/dev/models.py
# class Task(models.Model):
# """A task (a new feature or bug to fix)."""
# visible = models.BooleanField(default=True)
# version = models.ForeignKey(Release, on_delete=models.CASCADE)
# tracker = models.CharField(max_length=64, blank=True)
# spec = models.CharField(max_length=512, blank=True)
# status = models.IntegerField(default=0)
# commits = models.CharField(max_length=1024, blank=True)
# component = models.CharField(max_length=64, default='core')
# description = models.CharField(max_length=512)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# desc = (self.description
# if len(self.description) < 100
# else f'{self.description[0:100]}…')
# version = (f'({self.version.version})' if self.visible
# else self.version.version)
# tracker = self.tracker if self.tracker else '-'
# return (f'{version}, {tracker}, {self.status}%, {self.component}: '
# f'{desc} ({self.priority})')
#
# def version_date(self):
# """Return the date of version.
#
# It is prefixed with "≈ " if the date is in the future.
# """
# try:
# if self.version.date > date.today():
# return mark_safe(f'≈ {localdate(self.version.date)}')
# return localdate(self.version.date)
# except: # noqa: E722 pylint: disable=bare-except
# return ''
#
# def url_tracker(self):
# """Return the tracker URL using keyword(s) in string."""
# return tracker_links(self.tracker) or '-'
#
# def status_remaining(self):
# """Return the remaining status as % (100 - status)."""
# return 100 - self.status
#
# def url_commits(self):
# """Return the URL for commit(s), as HTML."""
# return commits_links(self.commits)
#
# class Meta:
# ordering = ['-version__date', 'priority']
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may include functions, classes, or code. Output only the next line. | with open(files_path_join('stats', f'git_{stats}_commits.txt'), |
Here is a snippet: <|code_start|> pass
elif stats == 'qweechat':
repository = ('https://github.com/weechat/qweechat')
sloc_lang = 'Python'
elif stats == 'weechat.org':
repository = ('https://github.com/weechat/weechat.org')
return render(
request,
'dev/stats.html',
{
'stats': stats,
'repository': repository,
'sloc': sloc,
'sloc_lang': sloc_lang,
'git_commits_last_week': git_commits[0],
'git_commits_last_month': git_commits[1],
'git_commits_last_year': git_commits[2],
'git_commits_total': git_commits[3],
'scripts_downloads': scripts_downloads,
'svg_list': svg_list,
},
)
def get_info(name, version):
"""Get an info."""
# pylint: disable=too-many-branches,too-many-return-statements
if name == 'stable':
return version['stable'].description
if name == 'stable_number':
<|code_end|>
. Write the next line using the current file imports:
import re
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import gettext, gettext_lazy
from weechat.common.path import files_path_join, media_path_join
from weechat.common.templatetags.version import version_as_int
from weechat.dev.models import Task
from weechat.download.models import Release
and context from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/common/templatetags/version.py
# @register.filter()
# def version_as_int(version):
# """
# Return a string with number of version, for example: 0.4.1 gives:
# 262400 (0x00040100).
# """
# try:
# items = version.split('.', 3)
# value = [0, 0, 0, 0]
# for i in range(0, 4):
# if i < len(items):
# value[i] = int(re.sub('[^0-9].*', '', items[i]))
# if value[i] < 0:
# value[i] = 0
# elif value[i] > 0xFF:
# value[i] = 0xFF
# return (value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]
# except: # noqa: E722 pylint: disable=bare-except
# return 0
#
# Path: weechat/dev/models.py
# class Task(models.Model):
# """A task (a new feature or bug to fix)."""
# visible = models.BooleanField(default=True)
# version = models.ForeignKey(Release, on_delete=models.CASCADE)
# tracker = models.CharField(max_length=64, blank=True)
# spec = models.CharField(max_length=512, blank=True)
# status = models.IntegerField(default=0)
# commits = models.CharField(max_length=1024, blank=True)
# component = models.CharField(max_length=64, default='core')
# description = models.CharField(max_length=512)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# desc = (self.description
# if len(self.description) < 100
# else f'{self.description[0:100]}…')
# version = (f'({self.version.version})' if self.visible
# else self.version.version)
# tracker = self.tracker if self.tracker else '-'
# return (f'{version}, {tracker}, {self.status}%, {self.component}: '
# f'{desc} ({self.priority})')
#
# def version_date(self):
# """Return the date of version.
#
# It is prefixed with "≈ " if the date is in the future.
# """
# try:
# if self.version.date > date.today():
# return mark_safe(f'≈ {localdate(self.version.date)}')
# return localdate(self.version.date)
# except: # noqa: E722 pylint: disable=bare-except
# return ''
#
# def url_tracker(self):
# """Return the tracker URL using keyword(s) in string."""
# return tracker_links(self.tracker) or '-'
#
# def status_remaining(self):
# """Return the remaining status as % (100 - status)."""
# return 100 - self.status
#
# def url_commits(self):
# """Return the URL for commit(s), as HTML."""
# return commits_links(self.commits)
#
# class Meta:
# ordering = ['-version__date', 'priority']
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
, which may include functions, classes, or code. Output only the next line. | return version_as_int(version['stable'].description) |
Given the code snippet: <|code_start|> 'debian_repository_signing_fingerprint',
gettext_lazy('Debian/Ubuntu repository signing key fingerprint '
'(format: PGP fingerprint).'),
),
(
'debian_repository_signing_key',
gettext_lazy('Debian/Ubuntu repository signing key '
'(format: PGP public key).'),
),
(
'all',
gettext_lazy('All non-binary infos '
'(one info by line, format: "info:value").'),
),
)
BINARY_INFO_KEYS = ('release_signing_key', 'debian_repository_signing_key')
PGP_KEYS = {
'release_signing': 'A9AB5AB778FA5C3522FD0378F82F4B16DEC408F8',
'debian_repository_signing': '11E9DE8848F2B65222AA75B8D1820DB22A11534E'
}
def roadmap(request, versions='future'):
"""Page with roadmap for future or all versions."""
task_list = None
try:
if versions == 'future':
# future versions
<|code_end|>
, generate the next line using the imports in this file:
import re
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import gettext, gettext_lazy
from weechat.common.path import files_path_join, media_path_join
from weechat.common.templatetags.version import version_as_int
from weechat.dev.models import Task
from weechat.download.models import Release
and context (functions, classes, or occasionally code) from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/common/templatetags/version.py
# @register.filter()
# def version_as_int(version):
# """
# Return a string with number of version, for example: 0.4.1 gives:
# 262400 (0x00040100).
# """
# try:
# items = version.split('.', 3)
# value = [0, 0, 0, 0]
# for i in range(0, 4):
# if i < len(items):
# value[i] = int(re.sub('[^0-9].*', '', items[i]))
# if value[i] < 0:
# value[i] = 0
# elif value[i] > 0xFF:
# value[i] = 0xFF
# return (value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]
# except: # noqa: E722 pylint: disable=bare-except
# return 0
#
# Path: weechat/dev/models.py
# class Task(models.Model):
# """A task (a new feature or bug to fix)."""
# visible = models.BooleanField(default=True)
# version = models.ForeignKey(Release, on_delete=models.CASCADE)
# tracker = models.CharField(max_length=64, blank=True)
# spec = models.CharField(max_length=512, blank=True)
# status = models.IntegerField(default=0)
# commits = models.CharField(max_length=1024, blank=True)
# component = models.CharField(max_length=64, default='core')
# description = models.CharField(max_length=512)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# desc = (self.description
# if len(self.description) < 100
# else f'{self.description[0:100]}…')
# version = (f'({self.version.version})' if self.visible
# else self.version.version)
# tracker = self.tracker if self.tracker else '-'
# return (f'{version}, {tracker}, {self.status}%, {self.component}: '
# f'{desc} ({self.priority})')
#
# def version_date(self):
# """Return the date of version.
#
# It is prefixed with "≈ " if the date is in the future.
# """
# try:
# if self.version.date > date.today():
# return mark_safe(f'≈ {localdate(self.version.date)}')
# return localdate(self.version.date)
# except: # noqa: E722 pylint: disable=bare-except
# return ''
#
# def url_tracker(self):
# """Return the tracker URL using keyword(s) in string."""
# return tracker_links(self.tracker) or '-'
#
# def status_remaining(self):
# """Return the remaining status as % (100 - status)."""
# return 100 - self.status
#
# def url_commits(self):
# """Return the URL for commit(s), as HTML."""
# return commits_links(self.commits)
#
# class Meta:
# ordering = ['-version__date', 'priority']
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | task_list = (Task.objects.all().filter(visible=1) |
Based on the snippet: <|code_start|> gettext_lazy('Debian/Ubuntu repository signing key fingerprint '
'(format: PGP fingerprint).'),
),
(
'debian_repository_signing_key',
gettext_lazy('Debian/Ubuntu repository signing key '
'(format: PGP public key).'),
),
(
'all',
gettext_lazy('All non-binary infos '
'(one info by line, format: "info:value").'),
),
)
BINARY_INFO_KEYS = ('release_signing_key', 'debian_repository_signing_key')
PGP_KEYS = {
'release_signing': 'A9AB5AB778FA5C3522FD0378F82F4B16DEC408F8',
'debian_repository_signing': '11E9DE8848F2B65222AA75B8D1820DB22A11534E'
}
def roadmap(request, versions='future'):
"""Page with roadmap for future or all versions."""
task_list = None
try:
if versions == 'future':
# future versions
task_list = (Task.objects.all().filter(visible=1)
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import gettext, gettext_lazy
from weechat.common.path import files_path_join, media_path_join
from weechat.common.templatetags.version import version_as_int
from weechat.dev.models import Task
from weechat.download.models import Release
and context (classes, functions, sometimes code) from other files:
# Path: weechat/common/path.py
# def files_path_join(*args):
# """Join multiple paths after settings.FILES_ROOT."""
# return __path_join(settings.FILES_ROOT, *args)
#
# def media_path_join(*args):
# """Join multiple paths after settings.MEDIA_ROOT."""
# return __path_join(settings.MEDIA_ROOT, *args)
#
# Path: weechat/common/templatetags/version.py
# @register.filter()
# def version_as_int(version):
# """
# Return a string with number of version, for example: 0.4.1 gives:
# 262400 (0x00040100).
# """
# try:
# items = version.split('.', 3)
# value = [0, 0, 0, 0]
# for i in range(0, 4):
# if i < len(items):
# value[i] = int(re.sub('[^0-9].*', '', items[i]))
# if value[i] < 0:
# value[i] = 0
# elif value[i] > 0xFF:
# value[i] = 0xFF
# return (value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]
# except: # noqa: E722 pylint: disable=bare-except
# return 0
#
# Path: weechat/dev/models.py
# class Task(models.Model):
# """A task (a new feature or bug to fix)."""
# visible = models.BooleanField(default=True)
# version = models.ForeignKey(Release, on_delete=models.CASCADE)
# tracker = models.CharField(max_length=64, blank=True)
# spec = models.CharField(max_length=512, blank=True)
# status = models.IntegerField(default=0)
# commits = models.CharField(max_length=1024, blank=True)
# component = models.CharField(max_length=64, default='core')
# description = models.CharField(max_length=512)
# priority = models.IntegerField(default=0)
#
# def __str__(self):
# desc = (self.description
# if len(self.description) < 100
# else f'{self.description[0:100]}…')
# version = (f'({self.version.version})' if self.visible
# else self.version.version)
# tracker = self.tracker if self.tracker else '-'
# return (f'{version}, {tracker}, {self.status}%, {self.component}: '
# f'{desc} ({self.priority})')
#
# def version_date(self):
# """Return the date of version.
#
# It is prefixed with "≈ " if the date is in the future.
# """
# try:
# if self.version.date > date.today():
# return mark_safe(f'≈ {localdate(self.version.date)}')
# return localdate(self.version.date)
# except: # noqa: E722 pylint: disable=bare-except
# return ''
#
# def url_tracker(self):
# """Return the tracker URL using keyword(s) in string."""
# return tracker_links(self.tracker) or '-'
#
# def status_remaining(self):
# """Return the remaining status as % (100 - status)."""
# return 100 - self.status
#
# def url_commits(self):
# """Return the URL for commit(s), as HTML."""
# return commits_links(self.commits)
#
# class Meta:
# ordering = ['-version__date', 'priority']
#
# Path: weechat/download/models.py
# class Release(models.Model):
# """A WeeChat release."""
# version = models.CharField(max_length=64, primary_key=True)
# description = models.CharField(max_length=64, blank=True)
# date = models.DateField(blank=True, null=True)
# security_issues_fixed = models.IntegerField(default=0)
# securityfix = models.CharField(max_length=256, blank=True)
#
# def __str__(self):
# security_fix = (f', {self.security_issues_fixed} SECURITY FIX'
# if self.security_issues_fixed > 0 else '')
# fixed_in = (f', fix in: {", ".join(self.securityfix.split(","))}'
# if self.securityfix else '')
# return f'{self.version} ({self.date}){security_fix}{fixed_in}'
#
# def date_l10n(self):
# """Return the release date formatted with localized date format."""
# return localdate(self.date)
#
# def security_fixed_versions(self):
# """Return the list of versions fixing security issues."""
# return self.securityfix.split(',')
#
# @property
# def is_released(self):
# """Return True if the version is released."""
# stable_version = Release.objects.get(version='stable').description
# stable_version_tuple = version_to_tuple(stable_version)
# return version_to_tuple(self.version) <= stable_version_tuple
#
# class Meta:
# ordering = ['-date']
. Output only the next line. | .filter(version__gt=Release.objects.get( |
Predict the next line after this snippet: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
using the current file's imports:
import random
from estrategias.jogadores import Jogador
from random import choice
and any relevant context from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Given snippet: <|code_start|>#-*- coding:utf-8 -*-
u"""
Created on 21/01/14
by fccoelho
license: GPL V3 or Later
"""
__docformat__ = 'restructuredtext en'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .jogadores import Jogador
and context:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
which might include code, classes, or functions. Output only the next line. | class MeuJogador(Jogador): |
Continue the code snippet: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
. Use current file imports:
import random
from .jogadores import Jogador
from random import choice
and context (classes, functions, or code) from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Given the code snippet: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
, generate the next line using the imports in this file:
import random
from .jogadores import Jogador
from random import choice
and context (functions, classes, or occasionally code) from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Predict the next line for this snippet: <|code_start|>#-*- coding:utf-8 -*-
u"""
Created on 21/01/14
by fccoelho
license: GPL V3 or Later
"""
__docformat__ = 'restructuredtext en'
<|code_end|>
with the help of current file imports:
from .jogadores import Jogador
import random
and context from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
, which may contain function names, class names, or code. Output only the next line. | class MeuJogador(Jogador): |
Next line prediction: <|code_start|>#-*- coding:utf-8 -*-
u"""
Created on 21/01/14
by fccoelho
license: GPL V3 or Later
"""
__docformat__ = 'restructuredtext en'
<|code_end|>
. Use current file imports:
(from .jogadores import Jogador
import random)
and context including class names, function names, or small code snippets from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Based on the snippet: <|code_start|>os.chdir('..')
simulador.R = StringIO()
class TesteSimulador(unittest.TestCase):
def setUp(self):
self.torneio = simulador.Torneio()
def testa_instanciacao_dos_jogadores(self):
self.torneio.inicializa_jogadores()
for i in self.torneio.jogadores.values():
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import os
import simulador
from estrategias.jogadores import Jogador
from io import StringIO
and context (classes, functions, sometimes code) from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | self.assertIsInstance(i, Jogador) |
Given the following code snippet before the placeholder: <|code_start|>#-*- coding:utf-8 -*-
u"""
Created on 21/01/14
by fccoelho
license: GPL V3 or Later
"""
__docformat__ = 'restructuredtext en'
<|code_end|>
, predict the next line using imports from the current file:
from .jogadores import Jogador
import random
and context including class names, function names, and sometimes code from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Predict the next line for this snippet: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
with the help of current file imports:
from estrategias.jogadores import Jogador
and context from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
, which may contain function names, class names, or code. Output only the next line. | class MeuJogador(Jogador): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.