Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>#!/usr/bin/env python
"""
AES Block Cipher.
Performs single block cipher decipher operations on a 16 element list of integers.
These integers represent 8 bit bytes in a 128 bit block.
The result of cipher or decipher operations is the transformed 16 element list of integers.
Algorithm per NIST FIPS-197 http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
Copyright (c) 2010, Adam Newman http://www.caller9.com/
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php
"""
__all__ = "AESCipher",
class AESCipher:
__slots__ = "_Nr", "_Nrr", "_f16","_l16"
def __init__(self,expanded_key):
self._Nr=[expanded_key[i:i+16] for i in range(16,len(expanded_key)-16,16)]
self._Nrr=self._Nr[::-1]
self._f16=expanded_key[:16]
self._l16=expanded_key[-16:]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .aes_tables import sbox,i_sbox,galI,galNI
and context:
# Path: aespython/aes_tables.py
which might include code, classes, or functions. Output only the next line. | def cipher_block(z,s0,s=sbox,g0=galNI[0],g1=galNI[1]): |
Next line prediction: <|code_start|>AES Block Cipher.
Performs single block cipher decipher operations on a 16 element list of integers.
These integers represent 8 bit bytes in a 128 bit block.
The result of cipher or decipher operations is the transformed 16 element list of integers.
Algorithm per NIST FIPS-197 http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
Copyright (c) 2010, Adam Newman http://www.caller9.com/
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php
"""
__all__ = "AESCipher",
class AESCipher:
__slots__ = "_Nr", "_Nrr", "_f16","_l16"
def __init__(self,expanded_key):
self._Nr=[expanded_key[i:i+16] for i in range(16,len(expanded_key)-16,16)]
self._Nrr=self._Nr[::-1]
self._f16=expanded_key[:16]
self._l16=expanded_key[-16:]
def cipher_block(z,s0,s=sbox,g0=galNI[0],g1=galNI[1]):
s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,sa,sb,sc,sd,se,sf=s0
r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,ra,rb,rc,rd,re,rf=z._f16
s0^=r0;s1^=r1;s2^=r2;s3^=r3;s4^=r4;s5^=r5;s6^=r6;s7^=r7;s8^=r8;s9^=r9;sa^=ra;sb^=rb;sc^=rc;sd^=rd;se^=re;sf^=rf
for r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,ra,rb,rc,rd,re,rf in z._Nr:
s0=s[s0];s4=s[s4];s8=s[s8];sc=s[sc]
s1,s2,s3,s5,s6,s7,s9,sa,sb,sd,se,sf=s[s5],s[sa],s[sf],s[s9],s[se],s[s3],s[sd],s[s2],s[s7],s[s1],s[s6],s[sb]
s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,sa,sb,sc,sd,se,sf=g0[s0]^g1[s1]^s2^s3^r0,s0^g0[s1]^g1[s2]^s3^r1,s0^s1^g0[s2]^g1[s3]^r2,g1[s0]^s1^s2^g0[s3]^r3,g0[s4]^g1[s5]^s6^s7^r4,s4^g0[s5]^g1[s6]^s7^r5,s4^s5^g0[s6]^g1[s7]^r6,g1[s4]^s5^s6^g0[s7]^r7,g0[s8]^g1[s9]^sa^sb^r8,s8^g0[s9]^g1[sa]^sb^r9,s8^s9^g0[sa]^g1[sb]^ra,g1[s8]^s9^sa^g0[sb]^rb,g0[sc]^g1[sd]^se^sf^rc,sc^g0[sd]^g1[se]^sf^rd,sc^sd^g0[se]^g1[sf]^re,g1[sc]^sd^se^g0[sf]^rf
r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,ra,rb,rc,rd,re,rf=z._l16
return s[s0]^r0,s[s5]^r1,s[sa]^r2,s[sf]^r3,s[s4]^r4,s[s9]^r5,s[se]^r6,s[s3]^r7,s[s8]^r8,s[sd]^r9,s[s2]^ra,s[s7]^rb,s[sc]^rc,s[s1]^rd,s[s6]^re,s[sb]^rf
<|code_end|>
. Use current file imports:
(from .aes_tables import sbox,i_sbox,galI,galNI)
and context including class names, function names, or small code snippets from other files:
# Path: aespython/aes_tables.py
. Output only the next line. | def decipher_block(z,s0,s=i_sbox,g0=galI[0],g1=galI[1],g2=galI[2],g3=galI[3]): |
Given snippet: <|code_start|>AES Block Cipher.
Performs single block cipher decipher operations on a 16 element list of integers.
These integers represent 8 bit bytes in a 128 bit block.
The result of cipher or decipher operations is the transformed 16 element list of integers.
Algorithm per NIST FIPS-197 http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
Copyright (c) 2010, Adam Newman http://www.caller9.com/
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php
"""
__all__ = "AESCipher",
class AESCipher:
__slots__ = "_Nr", "_Nrr", "_f16","_l16"
def __init__(self,expanded_key):
self._Nr=[expanded_key[i:i+16] for i in range(16,len(expanded_key)-16,16)]
self._Nrr=self._Nr[::-1]
self._f16=expanded_key[:16]
self._l16=expanded_key[-16:]
def cipher_block(z,s0,s=sbox,g0=galNI[0],g1=galNI[1]):
s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,sa,sb,sc,sd,se,sf=s0
r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,ra,rb,rc,rd,re,rf=z._f16
s0^=r0;s1^=r1;s2^=r2;s3^=r3;s4^=r4;s5^=r5;s6^=r6;s7^=r7;s8^=r8;s9^=r9;sa^=ra;sb^=rb;sc^=rc;sd^=rd;se^=re;sf^=rf
for r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,ra,rb,rc,rd,re,rf in z._Nr:
s0=s[s0];s4=s[s4];s8=s[s8];sc=s[sc]
s1,s2,s3,s5,s6,s7,s9,sa,sb,sd,se,sf=s[s5],s[sa],s[sf],s[s9],s[se],s[s3],s[sd],s[s2],s[s7],s[s1],s[s6],s[sb]
s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,sa,sb,sc,sd,se,sf=g0[s0]^g1[s1]^s2^s3^r0,s0^g0[s1]^g1[s2]^s3^r1,s0^s1^g0[s2]^g1[s3]^r2,g1[s0]^s1^s2^g0[s3]^r3,g0[s4]^g1[s5]^s6^s7^r4,s4^g0[s5]^g1[s6]^s7^r5,s4^s5^g0[s6]^g1[s7]^r6,g1[s4]^s5^s6^g0[s7]^r7,g0[s8]^g1[s9]^sa^sb^r8,s8^g0[s9]^g1[sa]^sb^r9,s8^s9^g0[sa]^g1[sb]^ra,g1[s8]^s9^sa^g0[sb]^rb,g0[sc]^g1[sd]^se^sf^rc,sc^g0[sd]^g1[se]^sf^rd,sc^sd^g0[se]^g1[sf]^re,g1[sc]^sd^se^g0[sf]^rf
r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,ra,rb,rc,rd,re,rf=z._l16
return s[s0]^r0,s[s5]^r1,s[sa]^r2,s[sf]^r3,s[s4]^r4,s[s9]^r5,s[se]^r6,s[s3]^r7,s[s8]^r8,s[sd]^r9,s[s2]^ra,s[s7]^rb,s[sc]^rc,s[s1]^rd,s[s6]^re,s[sb]^rf
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .aes_tables import sbox,i_sbox,galI,galNI
and context:
# Path: aespython/aes_tables.py
which might include code, classes, or functions. Output only the next line. | def decipher_block(z,s0,s=i_sbox,g0=galI[0],g1=galI[1],g2=galI[2],g3=galI[3]): |
Next line prediction: <|code_start|>#!/usr/bin/env python
"""
AES Block Cipher.
Performs single block cipher decipher operations on a 16 element list of integers.
These integers represent 8 bit bytes in a 128 bit block.
The result of cipher or decipher operations is the transformed 16 element list of integers.
Algorithm per NIST FIPS-197 http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
Copyright (c) 2010, Adam Newman http://www.caller9.com/
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php
"""
__all__ = "AESCipher",
class AESCipher:
__slots__ = "_Nr", "_Nrr", "_f16","_l16"
def __init__(self,expanded_key):
self._Nr=[expanded_key[i:i+16] for i in range(16,len(expanded_key)-16,16)]
self._Nrr=self._Nr[::-1]
self._f16=expanded_key[:16]
self._l16=expanded_key[-16:]
<|code_end|>
. Use current file imports:
(from .aes_tables import sbox,i_sbox,galI,galNI)
and context including class names, function names, or small code snippets from other files:
# Path: aespython/aes_tables.py
. Output only the next line. | def cipher_block(z,s0,s=sbox,g0=galNI[0],g1=galNI[1]): |
Given the following code snippet before the placeholder: <|code_start|># modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version
# 2 of the License, or (at your option) any later version.
#
# btcrecover 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/
# If you find this program helpful, please consider a small
# donation to the developer at the following Bitcoin address:
#
# 3Au8ZodNHPei7MQiSVAWb7NB2yqsb48GW4
#
# Thank You!
from __future__ import print_function
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--datadir", metavar="DIRECTORY", help="the Bitcoin data directory (default: auto)")
parser.add_argument("--update", action="store_true", help="update an existing address database")
parser.add_argument("--force", action="store_true", help="overwrite any existing address database")
parser.add_argument("--no-pause", action="store_true", default=len(sys.argv)>1, help="never pause before exiting (default: auto)")
parser.add_argument("--no-progress",action="store_true", default=not sys.stdout.isatty(), help="disable the progress bar (shows cur. blockfile instead)")
<|code_end|>
, predict the next line using imports from the current file:
from btcrecover import addressset
from os import path
import argparse, sys, atexit
import argcomplete
and context including class names, function names, and sometimes code from other files:
# Path: btcrecover/addressset.py
# def bytes_to_int(bytes_rep):
# def __init__(self, table_len, bytes_per_addr = 8, max_load = 0.75):
# def __getstate__(self):
# def __setstate__(self, state):
# def __len__(self):
# def __contains__(self, address):
# def add(self, address):
# def _find(self, addr_to_find):
# def __iter__(self):
# def __reversed__(self):
# def _remove_nonheader_attribs(attrs):
# def _header(self):
# def tofile(self, dbfile):
# def fromfile(cls, dbfile, mmap_access = mmap.ACCESS_READ, preload = True):
# def close(self, flush = True):
# def __del__(self):
# def varint(data, offset):
# def create_address_db(dbfilename, blockdir, update = False, progress_bar = True):
# class AddressSet(object):
# VERSION = 1
# MAGIC = b"seedrecover address database\r\n" # file magic
# HEADER_LEN = 65536
. Output only the next line. | parser.add_argument("--version", "-v", action="version", version="%(prog)s " + addressset.__version__)
|
Here is a snippet: <|code_start|>Copyright (c) 2010, Adam Newman http://www.caller9.com
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php
"""
__all__ = "expandKey",
_expanded_key_length={16:176,24:208,32:240}
def expandKey(new_key):
"""Expand the encryption key per AES key schedule specifications
http://en.wikipedia.org/wiki/Rijndael_key_schedule#Key_schedule_description"""
_n=len(new_key)
if _n not in (16,24,32):
raise RuntimeError('expand(): key size is invalid')
rcon_iter=1
_nn16=_n!=16
_n32=_n==32
n0=new_key[-4]
n1=new_key[-3]
n2=new_key[-2]
n3=new_key[-1]
_n0=-_n
_n1=1-_n
_n2=2-_n
_n3=3-_n
_n=_expanded_key_length[_n]-_n
nex=new_key.extend
while 1:
#Copy last 4 bytes of extended key, apply core, increment rcon_iter,
#core Append the list of elements 1-3 and list comprised of element 0 (circular rotate left)
#core For each element of this new list, put the result of sbox into output array.
#xor with 4 bytes n bytes from end of extended key
#First byte of output array is XORed with rcon(iter)
<|code_end|>
. Write the next line using the current file imports:
from .aes_tables import sbox,rcon
and context from other files:
# Path: aespython/aes_tables.py
, which may include functions, classes, or code. Output only the next line. | nx=n0,n1,n2,n3=(sbox[n1]^rcon[rcon_iter]^new_key[_n0], |
Based on the snippet: <|code_start|>Copyright (c) 2010, Adam Newman http://www.caller9.com
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php
"""
__all__ = "expandKey",
_expanded_key_length={16:176,24:208,32:240}
def expandKey(new_key):
"""Expand the encryption key per AES key schedule specifications
http://en.wikipedia.org/wiki/Rijndael_key_schedule#Key_schedule_description"""
_n=len(new_key)
if _n not in (16,24,32):
raise RuntimeError('expand(): key size is invalid')
rcon_iter=1
_nn16=_n!=16
_n32=_n==32
n0=new_key[-4]
n1=new_key[-3]
n2=new_key[-2]
n3=new_key[-1]
_n0=-_n
_n1=1-_n
_n2=2-_n
_n3=3-_n
_n=_expanded_key_length[_n]-_n
nex=new_key.extend
while 1:
#Copy last 4 bytes of extended key, apply core, increment rcon_iter,
#core Append the list of elements 1-3 and list comprised of element 0 (circular rotate left)
#core For each element of this new list, put the result of sbox into output array.
#xor with 4 bytes n bytes from end of extended key
#First byte of output array is XORed with rcon(iter)
<|code_end|>
, predict the immediate next line with the help of imports:
from .aes_tables import sbox,rcon
and context (classes, functions, sometimes code) from other files:
# Path: aespython/aes_tables.py
. Output only the next line. | nx=n0,n1,n2,n3=(sbox[n1]^rcon[rcon_iter]^new_key[_n0], |
Given the code snippet: <|code_start|>
NoneType = type(None)
T = TypeVar("T")
V = TypeVar("V")
class UnstructureStrategy(Enum):
"""`attrs` classes unstructuring strategies."""
AS_DICT = "asdict"
AS_TUPLE = "astuple"
def _subclass(typ):
"""a shortcut"""
return lambda cls: issubclass(cls, typ)
def is_attrs_union(typ):
<|code_end|>
, generate the next line using the imports in this file:
from collections import Counter
from collections.abc import MutableSet as AbcMutableSet
from dataclasses import Field
from enum import Enum
from functools import lru_cache
from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union
from attr import Attribute
from attr import has as attrs_has
from attr import resolve_types
from cattrs.errors import IterableValidationError, StructureHandlerNotFoundError
from ._compat import (
FrozenSetSubscriptable,
Mapping,
MutableMapping,
MutableSequence,
MutableSet,
Sequence,
Set,
fields,
get_origin,
has,
has_with_generic,
is_annotated,
is_bare,
is_counter,
is_frozenset,
is_generic,
is_generic_attrs,
is_hetero_tuple,
is_literal,
is_mapping,
is_mutable_set,
is_protocol,
is_sequence,
is_tuple,
is_union_type,
)
from .disambiguators import create_uniq_field_dis_func
from .dispatch import MultiStrategyDispatch
from .gen import (
AttributeOverride,
make_dict_structure_fn,
make_dict_unstructure_fn,
make_hetero_tuple_unstructure_fn,
make_iterable_unstructure_fn,
make_mapping_structure_fn,
make_mapping_unstructure_fn,
)
and context (functions, classes, or occasionally code) from other files:
# Path: src/cattr/_compat.py
# def get_args(cl):
# def get_origin(cl):
# def has(cls):
# def has_with_generic(cls):
# def fields(type):
# def adapted_fields(cl) -> List[Attribute]:
# def is_hetero_tuple(type: Any) -> bool:
# def is_protocol(type: Any) -> bool:
# def is_annotated(_):
# def is_tuple(type):
# def is_union_type(obj):
# def is_sequence(type: Any) -> bool:
# def is_mutable_set(type):
# def is_frozenset(type):
# def is_mapping(type):
# def is_bare(type):
# def is_counter(type):
# def is_literal(type) -> bool:
# def is_literal(_) -> bool:
# def is_generic(obj):
# def copy_with(type, args):
# def is_literal(type) -> bool:
# def is_literal(_) -> bool:
# def is_annotated(type) -> bool:
# def is_tuple(type):
# def is_union_type(obj):
# def is_union_type(obj):
# def is_sequence(type: Any) -> bool:
# def is_mutable_set(type):
# def is_frozenset(type):
# def is_bare(type):
# def is_mapping(type):
# def is_counter(type):
# def is_generic(obj):
# def copy_with(type, args):
# def is_generic_attrs(type):
#
# Path: src/cattr/dispatch.py
# class MultiStrategyDispatch:
# """
# MultiStrategyDispatch uses a combination of exact-match dispatch,
# singledispatch, and FunctionDispatch.
# """
#
# __slots__ = (
# "_direct_dispatch",
# "_function_dispatch",
# "_single_dispatch",
# "_generators",
# "dispatch",
# )
#
# def __init__(self, fallback_func):
# self._direct_dispatch = {}
# self._function_dispatch = FunctionDispatch()
# self._function_dispatch.register(lambda _: True, fallback_func)
# self._single_dispatch = singledispatch(_DispatchNotFound)
# self.dispatch = lru_cache(maxsize=None)(self._dispatch)
#
# def _dispatch(self, cl):
# try:
# dispatch = self._single_dispatch.dispatch(cl)
# if dispatch is not _DispatchNotFound:
# return dispatch
# except Exception:
# pass
#
# direct_dispatch = self._direct_dispatch.get(cl)
# if direct_dispatch is not None:
# return direct_dispatch
#
# return self._function_dispatch.dispatch(cl)
#
# def register_cls_list(self, cls_and_handler, direct: bool = False):
# """Register a class to direct or singledispatch."""
# for cls, handler in cls_and_handler:
# if direct:
# self._direct_dispatch[cls] = handler
# else:
# self._single_dispatch.register(cls, handler)
# self.clear_direct()
# self.dispatch.cache_clear()
#
# def register_func_list(
# self,
# func_and_handler: List[
# Union[
# Tuple[Callable[[Any], bool], Any],
# Tuple[Callable[[Any], bool], Any, bool],
# ]
# ],
# ):
# """register a function to determine if the handle
# should be used for the type
# """
# for tup in func_and_handler:
# if len(tup) == 2:
# func, handler = tup
# self._function_dispatch.register(func, handler)
# else:
# func, handler, is_gen = tup
# self._function_dispatch.register(func, handler, is_generator=is_gen)
# self.clear_direct()
# self.dispatch.cache_clear()
#
# def clear_direct(self):
# """Clear the direct dispatch."""
# self._direct_dispatch.clear()
#
# def clear_cache(self):
# """Clear all caches."""
# self._direct_dispatch.clear()
# self.dispatch.cache_clear()
#
# Path: src/cattr/gen.py
. Output only the next line. | return is_union_type(typ) and all(has(get_origin(e) or e) for e in typ.__args__) |
Using the snippet: <|code_start|>
NoneType = type(None)
T = TypeVar("T")
V = TypeVar("V")
class UnstructureStrategy(Enum):
"""`attrs` classes unstructuring strategies."""
AS_DICT = "asdict"
AS_TUPLE = "astuple"
def _subclass(typ):
"""a shortcut"""
return lambda cls: issubclass(cls, typ)
def is_attrs_union(typ):
<|code_end|>
, determine the next line of code. You have imports:
from collections import Counter
from collections.abc import MutableSet as AbcMutableSet
from dataclasses import Field
from enum import Enum
from functools import lru_cache
from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union
from attr import Attribute
from attr import has as attrs_has
from attr import resolve_types
from cattrs.errors import IterableValidationError, StructureHandlerNotFoundError
from ._compat import (
FrozenSetSubscriptable,
Mapping,
MutableMapping,
MutableSequence,
MutableSet,
Sequence,
Set,
fields,
get_origin,
has,
has_with_generic,
is_annotated,
is_bare,
is_counter,
is_frozenset,
is_generic,
is_generic_attrs,
is_hetero_tuple,
is_literal,
is_mapping,
is_mutable_set,
is_protocol,
is_sequence,
is_tuple,
is_union_type,
)
from .disambiguators import create_uniq_field_dis_func
from .dispatch import MultiStrategyDispatch
from .gen import (
AttributeOverride,
make_dict_structure_fn,
make_dict_unstructure_fn,
make_hetero_tuple_unstructure_fn,
make_iterable_unstructure_fn,
make_mapping_structure_fn,
make_mapping_unstructure_fn,
)
and context (class names, function names, or code) available:
# Path: src/cattr/_compat.py
# def get_args(cl):
# def get_origin(cl):
# def has(cls):
# def has_with_generic(cls):
# def fields(type):
# def adapted_fields(cl) -> List[Attribute]:
# def is_hetero_tuple(type: Any) -> bool:
# def is_protocol(type: Any) -> bool:
# def is_annotated(_):
# def is_tuple(type):
# def is_union_type(obj):
# def is_sequence(type: Any) -> bool:
# def is_mutable_set(type):
# def is_frozenset(type):
# def is_mapping(type):
# def is_bare(type):
# def is_counter(type):
# def is_literal(type) -> bool:
# def is_literal(_) -> bool:
# def is_generic(obj):
# def copy_with(type, args):
# def is_literal(type) -> bool:
# def is_literal(_) -> bool:
# def is_annotated(type) -> bool:
# def is_tuple(type):
# def is_union_type(obj):
# def is_union_type(obj):
# def is_sequence(type: Any) -> bool:
# def is_mutable_set(type):
# def is_frozenset(type):
# def is_bare(type):
# def is_mapping(type):
# def is_counter(type):
# def is_generic(obj):
# def copy_with(type, args):
# def is_generic_attrs(type):
#
# Path: src/cattr/dispatch.py
# class MultiStrategyDispatch:
# """
# MultiStrategyDispatch uses a combination of exact-match dispatch,
# singledispatch, and FunctionDispatch.
# """
#
# __slots__ = (
# "_direct_dispatch",
# "_function_dispatch",
# "_single_dispatch",
# "_generators",
# "dispatch",
# )
#
# def __init__(self, fallback_func):
# self._direct_dispatch = {}
# self._function_dispatch = FunctionDispatch()
# self._function_dispatch.register(lambda _: True, fallback_func)
# self._single_dispatch = singledispatch(_DispatchNotFound)
# self.dispatch = lru_cache(maxsize=None)(self._dispatch)
#
# def _dispatch(self, cl):
# try:
# dispatch = self._single_dispatch.dispatch(cl)
# if dispatch is not _DispatchNotFound:
# return dispatch
# except Exception:
# pass
#
# direct_dispatch = self._direct_dispatch.get(cl)
# if direct_dispatch is not None:
# return direct_dispatch
#
# return self._function_dispatch.dispatch(cl)
#
# def register_cls_list(self, cls_and_handler, direct: bool = False):
# """Register a class to direct or singledispatch."""
# for cls, handler in cls_and_handler:
# if direct:
# self._direct_dispatch[cls] = handler
# else:
# self._single_dispatch.register(cls, handler)
# self.clear_direct()
# self.dispatch.cache_clear()
#
# def register_func_list(
# self,
# func_and_handler: List[
# Union[
# Tuple[Callable[[Any], bool], Any],
# Tuple[Callable[[Any], bool], Any, bool],
# ]
# ],
# ):
# """register a function to determine if the handle
# should be used for the type
# """
# for tup in func_and_handler:
# if len(tup) == 2:
# func, handler = tup
# self._function_dispatch.register(func, handler)
# else:
# func, handler, is_gen = tup
# self._function_dispatch.register(func, handler, is_generator=is_gen)
# self.clear_direct()
# self.dispatch.cache_clear()
#
# def clear_direct(self):
# """Clear the direct dispatch."""
# self._direct_dispatch.clear()
#
# def clear_cache(self):
# """Clear all caches."""
# self._direct_dispatch.clear()
# self.dispatch.cache_clear()
#
# Path: src/cattr/gen.py
. Output only the next line. | return is_union_type(typ) and all(has(get_origin(e) or e) for e in typ.__args__) |
Given the code snippet: <|code_start|>
NoneType = type(None)
T = TypeVar("T")
V = TypeVar("V")
class UnstructureStrategy(Enum):
"""`attrs` classes unstructuring strategies."""
AS_DICT = "asdict"
AS_TUPLE = "astuple"
def _subclass(typ):
"""a shortcut"""
return lambda cls: issubclass(cls, typ)
def is_attrs_union(typ):
<|code_end|>
, generate the next line using the imports in this file:
from collections import Counter
from collections.abc import MutableSet as AbcMutableSet
from dataclasses import Field
from enum import Enum
from functools import lru_cache
from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union
from attr import Attribute
from attr import has as attrs_has
from attr import resolve_types
from cattrs.errors import IterableValidationError, StructureHandlerNotFoundError
from ._compat import (
FrozenSetSubscriptable,
Mapping,
MutableMapping,
MutableSequence,
MutableSet,
Sequence,
Set,
fields,
get_origin,
has,
has_with_generic,
is_annotated,
is_bare,
is_counter,
is_frozenset,
is_generic,
is_generic_attrs,
is_hetero_tuple,
is_literal,
is_mapping,
is_mutable_set,
is_protocol,
is_sequence,
is_tuple,
is_union_type,
)
from .disambiguators import create_uniq_field_dis_func
from .dispatch import MultiStrategyDispatch
from .gen import (
AttributeOverride,
make_dict_structure_fn,
make_dict_unstructure_fn,
make_hetero_tuple_unstructure_fn,
make_iterable_unstructure_fn,
make_mapping_structure_fn,
make_mapping_unstructure_fn,
)
and context (functions, classes, or occasionally code) from other files:
# Path: src/cattr/_compat.py
# def get_args(cl):
# def get_origin(cl):
# def has(cls):
# def has_with_generic(cls):
# def fields(type):
# def adapted_fields(cl) -> List[Attribute]:
# def is_hetero_tuple(type: Any) -> bool:
# def is_protocol(type: Any) -> bool:
# def is_annotated(_):
# def is_tuple(type):
# def is_union_type(obj):
# def is_sequence(type: Any) -> bool:
# def is_mutable_set(type):
# def is_frozenset(type):
# def is_mapping(type):
# def is_bare(type):
# def is_counter(type):
# def is_literal(type) -> bool:
# def is_literal(_) -> bool:
# def is_generic(obj):
# def copy_with(type, args):
# def is_literal(type) -> bool:
# def is_literal(_) -> bool:
# def is_annotated(type) -> bool:
# def is_tuple(type):
# def is_union_type(obj):
# def is_union_type(obj):
# def is_sequence(type: Any) -> bool:
# def is_mutable_set(type):
# def is_frozenset(type):
# def is_bare(type):
# def is_mapping(type):
# def is_counter(type):
# def is_generic(obj):
# def copy_with(type, args):
# def is_generic_attrs(type):
#
# Path: src/cattr/dispatch.py
# class MultiStrategyDispatch:
# """
# MultiStrategyDispatch uses a combination of exact-match dispatch,
# singledispatch, and FunctionDispatch.
# """
#
# __slots__ = (
# "_direct_dispatch",
# "_function_dispatch",
# "_single_dispatch",
# "_generators",
# "dispatch",
# )
#
# def __init__(self, fallback_func):
# self._direct_dispatch = {}
# self._function_dispatch = FunctionDispatch()
# self._function_dispatch.register(lambda _: True, fallback_func)
# self._single_dispatch = singledispatch(_DispatchNotFound)
# self.dispatch = lru_cache(maxsize=None)(self._dispatch)
#
# def _dispatch(self, cl):
# try:
# dispatch = self._single_dispatch.dispatch(cl)
# if dispatch is not _DispatchNotFound:
# return dispatch
# except Exception:
# pass
#
# direct_dispatch = self._direct_dispatch.get(cl)
# if direct_dispatch is not None:
# return direct_dispatch
#
# return self._function_dispatch.dispatch(cl)
#
# def register_cls_list(self, cls_and_handler, direct: bool = False):
# """Register a class to direct or singledispatch."""
# for cls, handler in cls_and_handler:
# if direct:
# self._direct_dispatch[cls] = handler
# else:
# self._single_dispatch.register(cls, handler)
# self.clear_direct()
# self.dispatch.cache_clear()
#
# def register_func_list(
# self,
# func_and_handler: List[
# Union[
# Tuple[Callable[[Any], bool], Any],
# Tuple[Callable[[Any], bool], Any, bool],
# ]
# ],
# ):
# """register a function to determine if the handle
# should be used for the type
# """
# for tup in func_and_handler:
# if len(tup) == 2:
# func, handler = tup
# self._function_dispatch.register(func, handler)
# else:
# func, handler, is_gen = tup
# self._function_dispatch.register(func, handler, is_generator=is_gen)
# self.clear_direct()
# self.dispatch.cache_clear()
#
# def clear_direct(self):
# """Clear the direct dispatch."""
# self._direct_dispatch.clear()
#
# def clear_cache(self):
# """Clear all caches."""
# self._direct_dispatch.clear()
# self.dispatch.cache_clear()
#
# Path: src/cattr/gen.py
. Output only the next line. | return is_union_type(typ) and all(has(get_origin(e) or e) for e in typ.__args__) |
Here is a snippet: <|code_start|>
T = TypeVar("T")
T2 = TypeVar("T2")
def test_deep_copy():
"""Test the deep copying of generic parameters."""
mapping = {T.__name__: int}
assert deep_copy_with(Optional[T], mapping) == Optional[int]
assert (
deep_copy_with(List_origin[Optional[T]], mapping) == List_origin[Optional[int]]
)
mapping = {T.__name__: int, T2.__name__: str}
assert (
<|code_end|>
. Write the next line using the current file imports:
from typing import Dict, Generic, List, Optional, TypeVar, Union
from attr import asdict, attrs, define
from cattr._compat import Protocol, is_py39_plus
from cattr._generics import deep_copy_with
from cattrs import Converter, GenConverter
from cattrs.errors import StructureHandlerNotFoundError
from ._compat import Dict_origin, List_origin
import pytest
and context from other files:
# Path: tests/_compat.py
# def change_type_param(cl, new_params):
# def change_type_param(cl, new_params):
, which may include functions, classes, or code. Output only the next line. | deep_copy_with(Dict_origin[T2, List_origin[Optional[T]]], mapping) |
Here is a snippet: <|code_start|>
T = TypeVar("T")
T2 = TypeVar("T2")
def test_deep_copy():
"""Test the deep copying of generic parameters."""
mapping = {T.__name__: int}
assert deep_copy_with(Optional[T], mapping) == Optional[int]
assert (
<|code_end|>
. Write the next line using the current file imports:
from typing import Dict, Generic, List, Optional, TypeVar, Union
from attr import asdict, attrs, define
from cattr._compat import Protocol, is_py39_plus
from cattr._generics import deep_copy_with
from cattrs import Converter, GenConverter
from cattrs.errors import StructureHandlerNotFoundError
from ._compat import Dict_origin, List_origin
import pytest
and context from other files:
# Path: tests/_compat.py
# def change_type_param(cl, new_params):
# def change_type_param(cl, new_params):
, which may include functions, classes, or code. Output only the next line. | deep_copy_with(List_origin[Optional[T]], mapping) == List_origin[Optional[int]] |
Predict the next line after this snippet: <|code_start|>
def deep_copy_with(t, mapping: Mapping[str, Any]):
args = get_args(t)
rest = ()
if is_annotated(t) and args:
# If we're dealing with `Annotated`, we only map the first type parameter
rest = tuple(args[1:])
args = (args[0],)
new_args = (
tuple(
mapping[a.__name__]
if hasattr(a, "__name__") and a.__name__ in mapping
else (deep_copy_with(a, mapping) if is_generic(a) else a)
for a in args
)
+ rest
)
<|code_end|>
using the current file's imports:
from typing import Any, Mapping
from ._compat import copy_with, get_args, is_annotated, is_generic
and any relevant context from other files:
# Path: src/cattr/_compat.py
# def copy_with(type, args):
# """Replace a generic type's arguments."""
# return type.copy_with(args)
#
# def get_args(cl):
# return cl.__args__
#
# def is_annotated(_):
# return False
#
# def is_generic(obj):
# return isinstance(obj, _GenericAlias)
. Output only the next line. | return copy_with(t, new_args) if new_args != args else t |
Given the code snippet: <|code_start|>
def deep_copy_with(t, mapping: Mapping[str, Any]):
args = get_args(t)
rest = ()
<|code_end|>
, generate the next line using the imports in this file:
from typing import Any, Mapping
from ._compat import copy_with, get_args, is_annotated, is_generic
and context (functions, classes, or occasionally code) from other files:
# Path: src/cattr/_compat.py
# def copy_with(type, args):
# """Replace a generic type's arguments."""
# return type.copy_with(args)
#
# def get_args(cl):
# return cl.__args__
#
# def is_annotated(_):
# return False
#
# def is_generic(obj):
# return isinstance(obj, _GenericAlias)
. Output only the next line. | if is_annotated(t) and args: |
Based on the snippet: <|code_start|>
def deep_copy_with(t, mapping: Mapping[str, Any]):
args = get_args(t)
rest = ()
if is_annotated(t) and args:
# If we're dealing with `Annotated`, we only map the first type parameter
rest = tuple(args[1:])
args = (args[0],)
new_args = (
tuple(
mapping[a.__name__]
if hasattr(a, "__name__") and a.__name__ in mapping
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import Any, Mapping
from ._compat import copy_with, get_args, is_annotated, is_generic
and context (classes, functions, sometimes code) from other files:
# Path: src/cattr/_compat.py
# def copy_with(type, args):
# """Replace a generic type's arguments."""
# return type.copy_with(args)
#
# def get_args(cl):
# return cl.__args__
#
# def is_annotated(_):
# return False
#
# def is_generic(obj):
# return isinstance(obj, _GenericAlias)
. Output only the next line. | else (deep_copy_with(a, mapping) if is_generic(a) else a) |
Given the code snippet: <|code_start|> """
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
_handler_pairs: list = attr.ib(factory=list)
def register(self, can_handle: Callable[[Any], bool], func, is_generator=False):
self._handler_pairs.insert(0, (can_handle, func, is_generator))
def dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
for can_handle, handler, is_generator in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
ch = can_handle(typ)
except Exception:
continue
if ch:
if is_generator:
return handler(typ)
else:
return handler
<|code_end|>
, generate the next line using the imports in this file:
from functools import lru_cache, singledispatch
from typing import Any, Callable, List, Tuple, Union
from .errors import StructureHandlerNotFoundError
import attr
and context (functions, classes, or occasionally code) from other files:
# Path: src/cattr/errors.py
. Output only the next line. | raise StructureHandlerNotFoundError( |
Based on the 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.
from __future__ import with_statement
class DataFileWriter(object):
"""Object to write parsed test data file objects back to disk."""
def __init__(self, **options):
"""
:param `**options`: A :class:`.WritingContext` is created based
on these.
"""
self._options = options
def write(self, datafile):
"""Writes given `datafile` using `**options`.
:param datafile: The parsed test data object to be written
:type datafile: :py:class:`~robot.parsing.model.TestCaseFile`,
:py:class:`~robot.parsing.model.ResourceFile`,
:py:class:`~robot.parsing.model.TestDataDirectory`
"""
with WritingContext(datafile, **self._options) as ctx:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from robot.errors import DataError
from .filewriters import FileWriter
and context (classes, functions, sometimes code) from other files:
# Path: lib/robot/writer/filewriters.py
# def FileWriter(context):
# """Creates and returns a FileWriter object.
#
# :param context: Type of returned FileWriter is determined based on
# `context.format`. `context` is also passed to created writer.
# :type context: :py:class:`WritingContext`
# """
# if context.format == context.html_format:
# return HtmlFileWriter(context)
# if context.format == context.tsv_format:
# return TsvFileWriter(context)
# if context.pipe_separated:
# return PipeSeparatedTxtWriter(context)
# return SpaceSeparatedTxtWriter(context)
. Output only the next line. | FileWriter(ctx).write(datafile) |
Given snippet: <|code_start|> if not found:
raise error
if len(found) == 1:
return found[0]
self._raise_multiple_matching_keywords_found(name, found)
def _get_embedded_arg_handlers(self, name):
found = []
for template in self.embedded_arg_handlers:
try:
found.append(EmbeddedArgs(name, template))
except TypeError:
pass
return found
def _raise_multiple_matching_keywords_found(self, name, found):
names = utils.seq2str([f.orig_name for f in found])
if self.name is None:
where = "Test case file"
else:
where = "Resource file '%s'" % self.name
raise DataError("%s contains multiple keywords matching name '%s'\n"
"Found: %s" % (where, name, names))
class UserKeywordHandler(object):
type = 'user'
def __init__(self, keyword, libname):
self.name = keyword.name
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
from robot.common import BaseLibrary, UserErrorHandler
from robot.errors import DataError, ExecutionFailed, UserKeywordExecutionFailed
from robot.variables import is_list_var, VariableSplitter
from robot.output import LOGGER
from robot import utils
from .keywords import Keywords
from .fixture import Teardown
from .timeouts import KeywordTimeout
from .arguments import UserKeywordArguments
and context:
# Path: lib/robot/running/keywords.py
# class Keywords(object):
#
# def __init__(self, steps, template=None):
# self._keywords = []
# self._templated = bool(template)
# if self._templated:
# steps = [s.apply_template(template) for s in steps]
# for s in steps:
# self._add_step(s, template)
#
# def _add_step(self, step, template):
# if step.is_comment():
# return
# if step.is_for_loop():
# keyword = ForLoop(step, template)
# else:
# keyword = Keyword(step.keyword, step.args, step.assign)
# self.add_keyword(keyword)
#
# def add_keyword(self, keyword):
# self._keywords.append(keyword)
#
# def run(self, context):
# errors = []
# for kw in self._keywords:
# try:
# kw.run(context)
# except ExecutionFailed, err:
# errors.extend(err.get_errors())
# if not err.can_continue(context.teardown, self._templated,
# context.dry_run):
# break
# if errors:
# raise ExecutionFailures(errors)
#
# def __nonzero__(self):
# return bool(self._keywords)
#
# def __iter__(self):
# return iter(self._keywords)
which might include code, classes, or functions. Output only the next line. | self.keywords = Keywords(keyword.steps) |
Given the following code snippet before the placeholder: <|code_start|>
def _import_default_libraries(self):
for name in self._default_libraries:
self.import_library(name)
def _handle_imports(self, import_settings):
for item in import_settings:
try:
if not item.name:
raise DataError('%s setting requires a name' % item.type)
self._import(item)
except DataError, err:
item.report_invalid_syntax(unicode(err))
def _import(self, import_setting):
action = {'Library': self._import_library,
'Resource': self._import_resource,
'Variables': self._import_variables}[import_setting.type]
action(import_setting, self.variables.current)
def import_resource(self, name, overwrite=True):
self._import_resource(Resource(None, name), overwrite=overwrite)
def _import_resource(self, import_setting, variables=None, overwrite=False):
path = self._resolve_name(import_setting, variables)
if overwrite or path not in self._imported_resource_files:
resource = IMPORTER.import_resource(path)
self.variables.set_from_variable_table(resource.variable_table,
overwrite)
self._imported_resource_files[path] \
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import copy
from robot import utils
from robot.errors import DataError
from robot.variables import GLOBAL_VARIABLES, is_scalar_var
from robot.common import UserErrorHandler
from robot.output import LOGGER
from robot.parsing.settings import Library, Variables, Resource
from .userkeyword import UserLibrary
from .importer import Importer, ImportCache
from .runkwregister import RUN_KW_REGISTER
from .handlers import _XTimesHandler
from .context import EXECUTION_CONTEXTS
and context including class names, function names, and sometimes code from other files:
# Path: lib/robot/running/userkeyword.py
# class UserLibrary(BaseLibrary):
# supports_named_arguments = True # this attribute is for libdoc
#
# def __init__(self, user_keywords, path=None):
# self.name = self._get_name_for_resource_file(path)
# self.handlers = utils.NormalizedDict(ignore=['_'])
# self.embedded_arg_handlers = []
# for kw in user_keywords:
# try:
# handler = EmbeddedArgsTemplate(kw, self.name)
# except DataError, err:
# LOGGER.error("Creating user keyword '%s' failed: %s"
# % (kw.name, unicode(err)))
# continue
# except TypeError:
# handler = UserKeywordHandler(kw, self.name)
# else:
# self.embedded_arg_handlers.append(handler)
# if handler.name in self.handlers:
# error = "Keyword '%s' defined multiple times." % handler.name
# handler = UserErrorHandler(handler.name, error)
# self.handlers[handler.name] = handler
#
# def _get_name_for_resource_file(self, path):
# if path is None:
# return None
# return os.path.splitext(os.path.basename(path))[0]
#
# def has_handler(self, name):
# if BaseLibrary.has_handler(self, name):
# return True
# for template in self.embedded_arg_handlers:
# try:
# EmbeddedArgs(name, template)
# except TypeError:
# pass
# else:
# return True
# return False
#
# def get_handler(self, name):
# try:
# return BaseLibrary.get_handler(self, name)
# except DataError, error:
# found = self._get_embedded_arg_handlers(name)
# if not found:
# raise error
# if len(found) == 1:
# return found[0]
# self._raise_multiple_matching_keywords_found(name, found)
#
# def _get_embedded_arg_handlers(self, name):
# found = []
# for template in self.embedded_arg_handlers:
# try:
# found.append(EmbeddedArgs(name, template))
# except TypeError:
# pass
# return found
#
# def _raise_multiple_matching_keywords_found(self, name, found):
# names = utils.seq2str([f.orig_name for f in found])
# if self.name is None:
# where = "Test case file"
# else:
# where = "Resource file '%s'" % self.name
# raise DataError("%s contains multiple keywords matching name '%s'\n"
# "Found: %s" % (where, name, names))
#
# Path: lib/robot/running/runkwregister.py
# RUN_KW_REGISTER = _RunKeywordRegister()
#
# Path: lib/robot/running/handlers.py
# class _XTimesHandler(_RunKeywordHandler):
#
# def __init__(self, handler, name):
# _RunKeywordHandler.__init__(self, handler.library, handler.name,
# handler._handler_method)
# self.name = name
# self._doc = "*DEPRECATED* Replace X times syntax with 'Repeat Keyword'."
#
# def run(self, context, args):
# resolved_times = context.namespace.variables.replace_string(self.name)
# _RunnableHandler.run(self, context, [resolved_times] + args)
#
# @property
# def longname(self):
# return self.name
#
# Path: lib/robot/running/context.py
# EXECUTION_CONTEXTS = ExecutionContexts()
. Output only the next line. | = UserLibrary(resource.keyword_table.keywords, resource.source) |
Given the following code snippet before the placeholder: <|code_start|> return found[0]
self._raise_multiple_keywords_found(name, found)
def _get_handler_from_library_keywords(self, name):
found = [lib.get_handler(name) for lib in self._testlibs.values()
if lib.has_handler(name)]
if not found:
return None
if len(found) > 1:
found = self._get_handler_based_on_library_search_order(found)
if len(found) == 2:
found = self._filter_stdlib_handler(found[0], found[1])
if len(found) == 1:
return found[0]
self._raise_multiple_keywords_found(name, found)
def _get_handler_based_on_library_search_order(self, handlers):
for libname in self.library_search_order:
for handler in handlers:
if utils.eq(libname, handler.libname):
return [handler]
return handlers
def _filter_stdlib_handler(self, handler1, handler2):
if handler1.library.orig_name in STDLIB_NAMES:
standard, external = handler1, handler2
elif handler2.library.orig_name in STDLIB_NAMES:
standard, external = handler2, handler1
else:
return [handler1, handler2]
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import copy
from robot import utils
from robot.errors import DataError
from robot.variables import GLOBAL_VARIABLES, is_scalar_var
from robot.common import UserErrorHandler
from robot.output import LOGGER
from robot.parsing.settings import Library, Variables, Resource
from .userkeyword import UserLibrary
from .importer import Importer, ImportCache
from .runkwregister import RUN_KW_REGISTER
from .handlers import _XTimesHandler
from .context import EXECUTION_CONTEXTS
and context including class names, function names, and sometimes code from other files:
# Path: lib/robot/running/userkeyword.py
# class UserLibrary(BaseLibrary):
# supports_named_arguments = True # this attribute is for libdoc
#
# def __init__(self, user_keywords, path=None):
# self.name = self._get_name_for_resource_file(path)
# self.handlers = utils.NormalizedDict(ignore=['_'])
# self.embedded_arg_handlers = []
# for kw in user_keywords:
# try:
# handler = EmbeddedArgsTemplate(kw, self.name)
# except DataError, err:
# LOGGER.error("Creating user keyword '%s' failed: %s"
# % (kw.name, unicode(err)))
# continue
# except TypeError:
# handler = UserKeywordHandler(kw, self.name)
# else:
# self.embedded_arg_handlers.append(handler)
# if handler.name in self.handlers:
# error = "Keyword '%s' defined multiple times." % handler.name
# handler = UserErrorHandler(handler.name, error)
# self.handlers[handler.name] = handler
#
# def _get_name_for_resource_file(self, path):
# if path is None:
# return None
# return os.path.splitext(os.path.basename(path))[0]
#
# def has_handler(self, name):
# if BaseLibrary.has_handler(self, name):
# return True
# for template in self.embedded_arg_handlers:
# try:
# EmbeddedArgs(name, template)
# except TypeError:
# pass
# else:
# return True
# return False
#
# def get_handler(self, name):
# try:
# return BaseLibrary.get_handler(self, name)
# except DataError, error:
# found = self._get_embedded_arg_handlers(name)
# if not found:
# raise error
# if len(found) == 1:
# return found[0]
# self._raise_multiple_matching_keywords_found(name, found)
#
# def _get_embedded_arg_handlers(self, name):
# found = []
# for template in self.embedded_arg_handlers:
# try:
# found.append(EmbeddedArgs(name, template))
# except TypeError:
# pass
# return found
#
# def _raise_multiple_matching_keywords_found(self, name, found):
# names = utils.seq2str([f.orig_name for f in found])
# if self.name is None:
# where = "Test case file"
# else:
# where = "Resource file '%s'" % self.name
# raise DataError("%s contains multiple keywords matching name '%s'\n"
# "Found: %s" % (where, name, names))
#
# Path: lib/robot/running/runkwregister.py
# RUN_KW_REGISTER = _RunKeywordRegister()
#
# Path: lib/robot/running/handlers.py
# class _XTimesHandler(_RunKeywordHandler):
#
# def __init__(self, handler, name):
# _RunKeywordHandler.__init__(self, handler.library, handler.name,
# handler._handler_method)
# self.name = name
# self._doc = "*DEPRECATED* Replace X times syntax with 'Repeat Keyword'."
#
# def run(self, context, args):
# resolved_times = context.namespace.variables.replace_string(self.name)
# _RunnableHandler.run(self, context, [resolved_times] + args)
#
# @property
# def longname(self):
# return self.name
#
# Path: lib/robot/running/context.py
# EXECUTION_CONTEXTS = ExecutionContexts()
. Output only the next line. | if not RUN_KW_REGISTER.is_run_keyword(external.library.orig_name, external.name): |
Based on the snippet: <|code_start|> if handler is None:
raise DataError("No keyword with name '%s' found." % name)
except DataError, err:
handler = UserErrorHandler(name, unicode(err))
self._replace_variables_from_user_handlers(handler)
return handler
def _replace_variables_from_user_handlers(self, handler):
if hasattr(handler, 'replace_variables'):
handler.replace_variables(self.variables)
def _get_handler(self, name):
handler = None
if not name:
raise DataError('Keyword name cannot be empty.')
if not isinstance(name, basestring):
raise DataError('Keyword name must be a string.')
if '.' in name:
handler = self._get_explicit_handler(name)
if not handler:
handler = self._get_implicit_handler(name)
if not handler:
handler = self._get_bdd_style_handler(name)
if not handler:
handler = self._get_x_times_handler(name)
return handler
def _get_x_times_handler(self, name):
if not self._is_old_x_times_syntax(name):
return None
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import copy
from robot import utils
from robot.errors import DataError
from robot.variables import GLOBAL_VARIABLES, is_scalar_var
from robot.common import UserErrorHandler
from robot.output import LOGGER
from robot.parsing.settings import Library, Variables, Resource
from .userkeyword import UserLibrary
from .importer import Importer, ImportCache
from .runkwregister import RUN_KW_REGISTER
from .handlers import _XTimesHandler
from .context import EXECUTION_CONTEXTS
and context (classes, functions, sometimes code) from other files:
# Path: lib/robot/running/userkeyword.py
# class UserLibrary(BaseLibrary):
# supports_named_arguments = True # this attribute is for libdoc
#
# def __init__(self, user_keywords, path=None):
# self.name = self._get_name_for_resource_file(path)
# self.handlers = utils.NormalizedDict(ignore=['_'])
# self.embedded_arg_handlers = []
# for kw in user_keywords:
# try:
# handler = EmbeddedArgsTemplate(kw, self.name)
# except DataError, err:
# LOGGER.error("Creating user keyword '%s' failed: %s"
# % (kw.name, unicode(err)))
# continue
# except TypeError:
# handler = UserKeywordHandler(kw, self.name)
# else:
# self.embedded_arg_handlers.append(handler)
# if handler.name in self.handlers:
# error = "Keyword '%s' defined multiple times." % handler.name
# handler = UserErrorHandler(handler.name, error)
# self.handlers[handler.name] = handler
#
# def _get_name_for_resource_file(self, path):
# if path is None:
# return None
# return os.path.splitext(os.path.basename(path))[0]
#
# def has_handler(self, name):
# if BaseLibrary.has_handler(self, name):
# return True
# for template in self.embedded_arg_handlers:
# try:
# EmbeddedArgs(name, template)
# except TypeError:
# pass
# else:
# return True
# return False
#
# def get_handler(self, name):
# try:
# return BaseLibrary.get_handler(self, name)
# except DataError, error:
# found = self._get_embedded_arg_handlers(name)
# if not found:
# raise error
# if len(found) == 1:
# return found[0]
# self._raise_multiple_matching_keywords_found(name, found)
#
# def _get_embedded_arg_handlers(self, name):
# found = []
# for template in self.embedded_arg_handlers:
# try:
# found.append(EmbeddedArgs(name, template))
# except TypeError:
# pass
# return found
#
# def _raise_multiple_matching_keywords_found(self, name, found):
# names = utils.seq2str([f.orig_name for f in found])
# if self.name is None:
# where = "Test case file"
# else:
# where = "Resource file '%s'" % self.name
# raise DataError("%s contains multiple keywords matching name '%s'\n"
# "Found: %s" % (where, name, names))
#
# Path: lib/robot/running/runkwregister.py
# RUN_KW_REGISTER = _RunKeywordRegister()
#
# Path: lib/robot/running/handlers.py
# class _XTimesHandler(_RunKeywordHandler):
#
# def __init__(self, handler, name):
# _RunKeywordHandler.__init__(self, handler.library, handler.name,
# handler._handler_method)
# self.name = name
# self._doc = "*DEPRECATED* Replace X times syntax with 'Repeat Keyword'."
#
# def run(self, context, args):
# resolved_times = context.namespace.variables.replace_string(self.name)
# _RunnableHandler.run(self, context, [resolved_times] + args)
#
# @property
# def longname(self):
# return self.name
#
# Path: lib/robot/running/context.py
# EXECUTION_CONTEXTS = ExecutionContexts()
. Output only the next line. | return _XTimesHandler(self._get_handler('Repeat Keyword'), name) |
Continue the code snippet: <|code_start|> except DataError, error:
pass
errors.append("Replacing variables from setting '%s' failed: %s"
% (name, error))
return utils.unescape(item)
def __getitem__(self, name):
return self.current[name]
def __setitem__(self, name, value):
self.current[name] = value
def end_suite(self):
self._suite = self._test = self.current = None
def start_test(self, test):
self._test = self.current = self._suite.copy()
def end_test(self):
self.current = self._suite
def start_uk(self, handler):
self._uk_handlers.append(self.current)
self.current = self.current.copy()
def end_uk(self):
self.current = self._uk_handlers.pop()
def set_global(self, name, value):
GLOBAL_VARIABLES.__setitem__(name, value)
<|code_end|>
. Use current file imports:
import os
import sys
import copy
from robot import utils
from robot.errors import DataError
from robot.variables import GLOBAL_VARIABLES, is_scalar_var
from robot.common import UserErrorHandler
from robot.output import LOGGER
from robot.parsing.settings import Library, Variables, Resource
from .userkeyword import UserLibrary
from .importer import Importer, ImportCache
from .runkwregister import RUN_KW_REGISTER
from .handlers import _XTimesHandler
from .context import EXECUTION_CONTEXTS
and context (classes, functions, or code) from other files:
# Path: lib/robot/running/userkeyword.py
# class UserLibrary(BaseLibrary):
# supports_named_arguments = True # this attribute is for libdoc
#
# def __init__(self, user_keywords, path=None):
# self.name = self._get_name_for_resource_file(path)
# self.handlers = utils.NormalizedDict(ignore=['_'])
# self.embedded_arg_handlers = []
# for kw in user_keywords:
# try:
# handler = EmbeddedArgsTemplate(kw, self.name)
# except DataError, err:
# LOGGER.error("Creating user keyword '%s' failed: %s"
# % (kw.name, unicode(err)))
# continue
# except TypeError:
# handler = UserKeywordHandler(kw, self.name)
# else:
# self.embedded_arg_handlers.append(handler)
# if handler.name in self.handlers:
# error = "Keyword '%s' defined multiple times." % handler.name
# handler = UserErrorHandler(handler.name, error)
# self.handlers[handler.name] = handler
#
# def _get_name_for_resource_file(self, path):
# if path is None:
# return None
# return os.path.splitext(os.path.basename(path))[0]
#
# def has_handler(self, name):
# if BaseLibrary.has_handler(self, name):
# return True
# for template in self.embedded_arg_handlers:
# try:
# EmbeddedArgs(name, template)
# except TypeError:
# pass
# else:
# return True
# return False
#
# def get_handler(self, name):
# try:
# return BaseLibrary.get_handler(self, name)
# except DataError, error:
# found = self._get_embedded_arg_handlers(name)
# if not found:
# raise error
# if len(found) == 1:
# return found[0]
# self._raise_multiple_matching_keywords_found(name, found)
#
# def _get_embedded_arg_handlers(self, name):
# found = []
# for template in self.embedded_arg_handlers:
# try:
# found.append(EmbeddedArgs(name, template))
# except TypeError:
# pass
# return found
#
# def _raise_multiple_matching_keywords_found(self, name, found):
# names = utils.seq2str([f.orig_name for f in found])
# if self.name is None:
# where = "Test case file"
# else:
# where = "Resource file '%s'" % self.name
# raise DataError("%s contains multiple keywords matching name '%s'\n"
# "Found: %s" % (where, name, names))
#
# Path: lib/robot/running/runkwregister.py
# RUN_KW_REGISTER = _RunKeywordRegister()
#
# Path: lib/robot/running/handlers.py
# class _XTimesHandler(_RunKeywordHandler):
#
# def __init__(self, handler, name):
# _RunKeywordHandler.__init__(self, handler.library, handler.name,
# handler._handler_method)
# self.name = name
# self._doc = "*DEPRECATED* Replace X times syntax with 'Repeat Keyword'."
#
# def run(self, context, args):
# resolved_times = context.namespace.variables.replace_string(self.name)
# _RunnableHandler.run(self, context, [resolved_times] + args)
#
# @property
# def longname(self):
# return self.name
#
# Path: lib/robot/running/context.py
# EXECUTION_CONTEXTS = ExecutionContexts()
. Output only the next line. | for ns in EXECUTION_CONTEXTS.namespaces: |
Predict the next line after this snippet: <|code_start|># Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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.
class Setting(object):
def __init__(self, setting_name, parent=None, comment=None):
self.setting_name = setting_name
self.parent = parent
self._set_initial_value()
self._set_comment(comment)
def _set_initial_value(self):
self.value = []
def _set_comment(self, comment):
<|code_end|>
using the current file's imports:
from .comments import Comment
and any relevant context from other files:
# Path: lib/robot/parsing/comments.py
# class Comment(object):
#
# def __init__(self, comment_data):
# if isinstance(comment_data, basestring):
# comment_data = [comment_data] if comment_data else []
# self._comment = comment_data or []
#
# def __len__(self):
# return len(self._comment)
#
# def as_list(self):
# if self._not_commented():
# self._comment[0] = '# ' + self._comment[0]
# return self._comment
#
# def _not_commented(self):
# return self._comment and self._comment[0] and self._comment[0][0] != '#'
. Output only the next line. | self.comment = Comment(comment) |
Predict the next line after this snippet: <|code_start|>
class Populator(object):
"""Explicit interface for all populators."""
def add(self, row):
raise NotImplementedError
def populate(self):
raise NotImplementedError
class NullPopulator(Populator):
def add(self, row):
pass
def populate(self):
pass
def __nonzero__(self):
return False
class _TablePopulator(Populator):
def __init__(self, table):
self._table = table
self._populator = NullPopulator()
<|code_end|>
using the current file's imports:
import re
from .comments import CommentCache, Comments
from .settings import Documentation, MetadataList
and any relevant context from other files:
# Path: lib/robot/parsing/comments.py
# class CommentCache(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, comment):
# self._comments.append(comment)
#
# def consume_with(self, function):
# map(function, self._comments)
# self.__init__()
#
# class Comments(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, row):
# if row.comments:
# self._comments.extend(c.strip() for c in row.comments if c.strip())
#
# @property
# def value(self):
# return self._comments
#
# Path: lib/robot/parsing/settings.py
# class Documentation(Setting):
#
# def _set_initial_value(self):
# self.value = ''
#
# def _populate(self, value):
# self.value = self._concat_string_with_value(self.value, value)
#
# def _string_value(self, value):
# return value if isinstance(value, basestring) else ''.join(value)
#
# def _data_as_list(self):
# return [self.setting_name, self.value]
#
# class MetadataList(_DataList):
#
# def populate(self, name, value, comment):
# self._add(Metadata(self._parent, name, value, comment, joined=True))
. Output only the next line. | self._comment_cache = CommentCache() |
Next line prediction: <|code_start|> return NullPopulator()
if setter.im_class is Documentation:
return DocumentationPopulator(setter)
return SettingPopulator(setter)
if row.starts_for_loop():
return ForLoopPopulator(self._test_or_uk.add_for_loop)
return StepPopulator(self._test_or_uk.add_step)
def _continues(self, row):
return row.is_continuing() and self._populator or \
(isinstance(self._populator, ForLoopPopulator) and row.is_indented())
def _setting_setter(self, row):
setting_name = row.test_or_user_keyword_setting_name()
return self._test_or_uk.get_setter(setting_name)
class TestCasePopulator(_TestCaseUserKeywordPopulator):
_item_type = 'test case'
class UserKeywordPopulator(_TestCaseUserKeywordPopulator):
_item_type = 'keyword'
class _PropertyPopulator(Populator):
def __init__(self, setter):
self._setter = setter
self._value = []
<|code_end|>
. Use current file imports:
(import re
from .comments import CommentCache, Comments
from .settings import Documentation, MetadataList)
and context including class names, function names, or small code snippets from other files:
# Path: lib/robot/parsing/comments.py
# class CommentCache(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, comment):
# self._comments.append(comment)
#
# def consume_with(self, function):
# map(function, self._comments)
# self.__init__()
#
# class Comments(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, row):
# if row.comments:
# self._comments.extend(c.strip() for c in row.comments if c.strip())
#
# @property
# def value(self):
# return self._comments
#
# Path: lib/robot/parsing/settings.py
# class Documentation(Setting):
#
# def _set_initial_value(self):
# self.value = ''
#
# def _populate(self, value):
# self.value = self._concat_string_with_value(self.value, value)
#
# def _string_value(self, value):
# return value if isinstance(value, basestring) else ''.join(value)
#
# def _data_as_list(self):
# return [self.setting_name, self.value]
#
# class MetadataList(_DataList):
#
# def populate(self, name, value, comment):
# self._add(Metadata(self._parent, name, value, comment, joined=True))
. Output only the next line. | self._comments = Comments() |
Given the code snippet: <|code_start|> else:
self._populator.populate()
self._populator = self._get_populator(row)
self._consume_standalone_comments()
self._populator.add(row)
def _is_continuing(self, row):
return row.is_continuing() and self._populator
def _get_populator(self, row):
raise NotImplementedError
def _consume_comments(self):
self._comment_cache.consume_with(self._populator.add)
def _consume_standalone_comments(self):
self._consume_comments()
def populate(self):
self._consume_comments()
self._populator.populate()
class SettingTablePopulator(_TablePopulator):
def _get_populator(self, row):
row.handle_old_style_metadata()
setter = self._table.get_setter(row.head)
if not setter:
return NullPopulator()
<|code_end|>
, generate the next line using the imports in this file:
import re
from .comments import CommentCache, Comments
from .settings import Documentation, MetadataList
and context (functions, classes, or occasionally code) from other files:
# Path: lib/robot/parsing/comments.py
# class CommentCache(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, comment):
# self._comments.append(comment)
#
# def consume_with(self, function):
# map(function, self._comments)
# self.__init__()
#
# class Comments(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, row):
# if row.comments:
# self._comments.extend(c.strip() for c in row.comments if c.strip())
#
# @property
# def value(self):
# return self._comments
#
# Path: lib/robot/parsing/settings.py
# class Documentation(Setting):
#
# def _set_initial_value(self):
# self.value = ''
#
# def _populate(self, value):
# self.value = self._concat_string_with_value(self.value, value)
#
# def _string_value(self, value):
# return value if isinstance(value, basestring) else ''.join(value)
#
# def _data_as_list(self):
# return [self.setting_name, self.value]
#
# class MetadataList(_DataList):
#
# def populate(self, name, value, comment):
# self._add(Metadata(self._parent, name, value, comment, joined=True))
. Output only the next line. | if setter.im_class is Documentation: |
Given the code snippet: <|code_start|> self._populator = self._get_populator(row)
self._consume_standalone_comments()
self._populator.add(row)
def _is_continuing(self, row):
return row.is_continuing() and self._populator
def _get_populator(self, row):
raise NotImplementedError
def _consume_comments(self):
self._comment_cache.consume_with(self._populator.add)
def _consume_standalone_comments(self):
self._consume_comments()
def populate(self):
self._consume_comments()
self._populator.populate()
class SettingTablePopulator(_TablePopulator):
def _get_populator(self, row):
row.handle_old_style_metadata()
setter = self._table.get_setter(row.head)
if not setter:
return NullPopulator()
if setter.im_class is Documentation:
return DocumentationPopulator(setter)
<|code_end|>
, generate the next line using the imports in this file:
import re
from .comments import CommentCache, Comments
from .settings import Documentation, MetadataList
and context (functions, classes, or occasionally code) from other files:
# Path: lib/robot/parsing/comments.py
# class CommentCache(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, comment):
# self._comments.append(comment)
#
# def consume_with(self, function):
# map(function, self._comments)
# self.__init__()
#
# class Comments(object):
#
# def __init__(self):
# self._comments = []
#
# def add(self, row):
# if row.comments:
# self._comments.extend(c.strip() for c in row.comments if c.strip())
#
# @property
# def value(self):
# return self._comments
#
# Path: lib/robot/parsing/settings.py
# class Documentation(Setting):
#
# def _set_initial_value(self):
# self.value = ''
#
# def _populate(self, value):
# self.value = self._concat_string_with_value(self.value, value)
#
# def _string_value(self, value):
# return value if isinstance(value, basestring) else ''.join(value)
#
# def _data_as_list(self):
# return [self.setting_name, self.value]
#
# class MetadataList(_DataList):
#
# def populate(self, name, value, comment):
# self._add(Metadata(self._parent, name, value, comment, joined=True))
. Output only the next line. | if setter.im_class is MetadataList: |
Using the snippet: <|code_start|>
class _RunKeywordHandler(_PythonHandler):
def __init__(self, library, handler_name, handler_method):
_PythonHandler.__init__(self, library, handler_name, handler_method)
self._handler_method = handler_method
def _run_with_signal_monitoring(self, runner, context):
# With run keyword variants, only the keyword to be run can fail
# and therefore monitoring should not raise exception yet.
return runner()
def _parse_arguments(self, handler_method):
arg_index = self._get_args_to_process()
return RunKeywordArguments(handler_method, self.longname, arg_index)
def _get_args_to_process(self):
return RUN_KW_REGISTER.get_args_to_process(self.library.orig_name,
self.name)
def _get_timeout(self, namespace):
return None
def _dry_run(self, context, args):
_RunnableHandler._dry_run(self, context, args)
keywords = self._get_runnable_dry_run_keywords(context, args)
keywords.run(context)
def _get_runnable_dry_run_keywords(self, context, args):
<|code_end|>
, determine the next line of code. You have imports:
from robot import utils
from robot.errors import DataError
from robot.variables import is_list_var
from .arguments import (PythonKeywordArguments, JavaKeywordArguments,
DynamicKeywordArguments, RunKeywordArguments,
PythonInitArguments, JavaInitArguments)
from .keywords import Keywords, Keyword
from .outputcapture import OutputCapturer
from .runkwregister import RUN_KW_REGISTER
from .signalhandler import STOP_SIGNAL_MONITOR
from org.python.core import PyReflectedFunction, PyReflectedConstructor
and context (class names, function names, or code) available:
# Path: lib/robot/running/keywords.py
# class Keywords(object):
#
# def __init__(self, steps, template=None):
# self._keywords = []
# self._templated = bool(template)
# if self._templated:
# steps = [s.apply_template(template) for s in steps]
# for s in steps:
# self._add_step(s, template)
#
# def _add_step(self, step, template):
# if step.is_comment():
# return
# if step.is_for_loop():
# keyword = ForLoop(step, template)
# else:
# keyword = Keyword(step.keyword, step.args, step.assign)
# self.add_keyword(keyword)
#
# def add_keyword(self, keyword):
# self._keywords.append(keyword)
#
# def run(self, context):
# errors = []
# for kw in self._keywords:
# try:
# kw.run(context)
# except ExecutionFailed, err:
# errors.extend(err.get_errors())
# if not err.can_continue(context.teardown, self._templated,
# context.dry_run):
# break
# if errors:
# raise ExecutionFailures(errors)
#
# def __nonzero__(self):
# return bool(self._keywords)
#
# def __iter__(self):
# return iter(self._keywords)
#
# class Keyword(BaseKeyword):
#
# def __init__(self, name, args, assign=None, type='kw'):
# BaseKeyword.__init__(self, name, args, type=type)
# self.assign = assign or []
# self.handler_name = name
#
# def run(self, context):
# handler = self._start(context)
# try:
# return_value = self._run(handler, context)
# except ExecutionFailed, err:
# self.status = 'FAIL' if not err.exit_for_loop else 'PASS'
# self._end(context, error=err)
# raise
# else:
# if not (context.dry_run and handler.type == 'library'):
# self.status = 'PASS'
# self._end(context, return_value)
# return return_value
#
# def _start(self, context):
# handler = context.get_handler(self.handler_name)
# handler.init_keyword(context.get_current_vars())
# self.name = self._get_name(handler.longname)
# self.doc = handler.shortdoc
# self.timeout = getattr(handler, 'timeout', '')
# self.starttime = get_timestamp()
# context.start_keyword(self)
# if self.doc.startswith('*DEPRECATED*'):
# msg = self.doc.replace('*DEPRECATED*', '', 1).strip()
# name = self.name.split('} = ', 1)[-1] # Remove possible variable
# context.warn("Keyword '%s' is deprecated. %s" % (name, msg))
# return handler
#
# def _get_name(self, handler_longname):
# if not self.assign:
# return handler_longname
# return '%s = %s' % (', '.join(a.rstrip('= ') for a in self.assign),
# handler_longname)
#
# def _run(self, handler, context):
# try:
# return handler.run(context, self.args[:])
# except ExecutionFailed:
# raise
# except:
# self._report_failure(context)
#
# def _end(self, context, return_value=None, error=None):
# self.endtime = get_timestamp()
# self.elapsedtime = get_elapsed_time(self.starttime, self.endtime)
# if error and self.type == 'teardown':
# self.message = unicode(error)
# try:
# if not error or error.can_continue(context.teardown):
# self._set_variables(context, return_value, error)
# finally:
# context.end_keyword(self)
#
# def _set_variables(self, context, return_value, error):
# if error:
# return_value = error.return_value
# try:
# VariableAssigner(self.assign).assign(context, return_value)
# except DataError, err:
# self.status = 'FAIL'
# msg = unicode(err)
# context.output.fail(msg)
# raise ExecutionFailed(msg, syntax=True)
#
# def _report_failure(self, context):
# failure = HandlerExecutionFailed()
# if not failure.exit_for_loop:
# context.output.fail(failure.full_message)
# if failure.traceback:
# context.output.debug(failure.traceback)
# raise failure
#
# Path: lib/robot/running/runkwregister.py
# RUN_KW_REGISTER = _RunKeywordRegister()
. Output only the next line. | keywords = Keywords([]) |
Predict the next line after this snippet: <|code_start|>#
# 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 with_statement
if utils.is_jython:
def _is_java_init(init):
return isinstance(init, PyReflectedConstructor)
def _is_java_method(method):
return hasattr(method, 'im_func') \
and isinstance(method.im_func, PyReflectedFunction)
else:
_is_java_init = _is_java_method = lambda item: False
def Handler(library, name, method):
<|code_end|>
using the current file's imports:
from robot import utils
from robot.errors import DataError
from robot.variables import is_list_var
from .arguments import (PythonKeywordArguments, JavaKeywordArguments,
DynamicKeywordArguments, RunKeywordArguments,
PythonInitArguments, JavaInitArguments)
from .keywords import Keywords, Keyword
from .outputcapture import OutputCapturer
from .runkwregister import RUN_KW_REGISTER
from .signalhandler import STOP_SIGNAL_MONITOR
from org.python.core import PyReflectedFunction, PyReflectedConstructor
and any relevant context from other files:
# Path: lib/robot/running/keywords.py
# class Keywords(object):
#
# def __init__(self, steps, template=None):
# self._keywords = []
# self._templated = bool(template)
# if self._templated:
# steps = [s.apply_template(template) for s in steps]
# for s in steps:
# self._add_step(s, template)
#
# def _add_step(self, step, template):
# if step.is_comment():
# return
# if step.is_for_loop():
# keyword = ForLoop(step, template)
# else:
# keyword = Keyword(step.keyword, step.args, step.assign)
# self.add_keyword(keyword)
#
# def add_keyword(self, keyword):
# self._keywords.append(keyword)
#
# def run(self, context):
# errors = []
# for kw in self._keywords:
# try:
# kw.run(context)
# except ExecutionFailed, err:
# errors.extend(err.get_errors())
# if not err.can_continue(context.teardown, self._templated,
# context.dry_run):
# break
# if errors:
# raise ExecutionFailures(errors)
#
# def __nonzero__(self):
# return bool(self._keywords)
#
# def __iter__(self):
# return iter(self._keywords)
#
# class Keyword(BaseKeyword):
#
# def __init__(self, name, args, assign=None, type='kw'):
# BaseKeyword.__init__(self, name, args, type=type)
# self.assign = assign or []
# self.handler_name = name
#
# def run(self, context):
# handler = self._start(context)
# try:
# return_value = self._run(handler, context)
# except ExecutionFailed, err:
# self.status = 'FAIL' if not err.exit_for_loop else 'PASS'
# self._end(context, error=err)
# raise
# else:
# if not (context.dry_run and handler.type == 'library'):
# self.status = 'PASS'
# self._end(context, return_value)
# return return_value
#
# def _start(self, context):
# handler = context.get_handler(self.handler_name)
# handler.init_keyword(context.get_current_vars())
# self.name = self._get_name(handler.longname)
# self.doc = handler.shortdoc
# self.timeout = getattr(handler, 'timeout', '')
# self.starttime = get_timestamp()
# context.start_keyword(self)
# if self.doc.startswith('*DEPRECATED*'):
# msg = self.doc.replace('*DEPRECATED*', '', 1).strip()
# name = self.name.split('} = ', 1)[-1] # Remove possible variable
# context.warn("Keyword '%s' is deprecated. %s" % (name, msg))
# return handler
#
# def _get_name(self, handler_longname):
# if not self.assign:
# return handler_longname
# return '%s = %s' % (', '.join(a.rstrip('= ') for a in self.assign),
# handler_longname)
#
# def _run(self, handler, context):
# try:
# return handler.run(context, self.args[:])
# except ExecutionFailed:
# raise
# except:
# self._report_failure(context)
#
# def _end(self, context, return_value=None, error=None):
# self.endtime = get_timestamp()
# self.elapsedtime = get_elapsed_time(self.starttime, self.endtime)
# if error and self.type == 'teardown':
# self.message = unicode(error)
# try:
# if not error or error.can_continue(context.teardown):
# self._set_variables(context, return_value, error)
# finally:
# context.end_keyword(self)
#
# def _set_variables(self, context, return_value, error):
# if error:
# return_value = error.return_value
# try:
# VariableAssigner(self.assign).assign(context, return_value)
# except DataError, err:
# self.status = 'FAIL'
# msg = unicode(err)
# context.output.fail(msg)
# raise ExecutionFailed(msg, syntax=True)
#
# def _report_failure(self, context):
# failure = HandlerExecutionFailed()
# if not failure.exit_for_loop:
# context.output.fail(failure.full_message)
# if failure.traceback:
# context.output.debug(failure.traceback)
# raise failure
#
# Path: lib/robot/running/runkwregister.py
# RUN_KW_REGISTER = _RunKeywordRegister()
. Output only the next line. | if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name): |
Given the following code snippet before the placeholder: <|code_start|>
def _cached_download_helper(cache_obj_name, dl_func, reset=False):
"""Helper function for downloads.
Takes care of checking if the file is already cached.
Only calls the actual download function when no cached version exists.
"""
cache_dir = cfg.PATHS['dl_cache_dir']
cache_ro = cfg.PARAMS['dl_cache_readonly']
# A lot of logic below could be simplified but it's also not too important
wd = cfg.PATHS.get('working_dir')
if wd:
# this is for real runs
fb_cache_dir = os.path.join(wd, 'cache')
check_fb_dir = False
else:
# Nothing have been set up yet, this is bad - find a place to write
# This should happen on read-only cluster only but still
wd = os.environ.get('OGGM_WORKDIR')
if wd is not None and os.path.isdir(wd):
fb_cache_dir = os.path.join(wd, 'cache')
else:
fb_cache_dir = os.path.join(cfg.CACHE_DIR, 'cache')
check_fb_dir = True
if not cache_dir:
# Defaults to working directory: it must be set!
if not cfg.PATHS['working_dir']:
<|code_end|>
, predict the next line using imports from the current file:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context including class names, function names, and sometimes code from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
. Output only the next line. | raise InvalidParamsError("Need a valid PATHS['working_dir']!") |
Continue the code snippet: <|code_start|> if wd is not None and os.path.isdir(wd):
fb_cache_dir = os.path.join(wd, 'cache')
else:
fb_cache_dir = os.path.join(cfg.CACHE_DIR, 'cache')
check_fb_dir = True
if not cache_dir:
# Defaults to working directory: it must be set!
if not cfg.PATHS['working_dir']:
raise InvalidParamsError("Need a valid PATHS['working_dir']!")
cache_dir = fb_cache_dir
cache_ro = False
fb_path = os.path.join(fb_cache_dir, cache_obj_name)
if not reset and os.path.isfile(fb_path):
return fb_path
cache_path = os.path.join(cache_dir, cache_obj_name)
if not reset and os.path.isfile(cache_path):
return cache_path
if cache_ro:
if check_fb_dir:
# Add a manual check that we are caching sample data download
if 'oggm-sample-data' not in fb_path:
raise InvalidParamsError('Attempting to download something '
'with invalid global settings.')
cache_path = fb_path
if not cfg.PARAMS['has_internet']:
<|code_end|>
. Use current file imports:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context (classes, functions, or code) from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
. Output only the next line. | raise NoInternetException("Download required, but " |
Next line prediction: <|code_start|> list of known static files.
Uses _cached_download_helper to perform the actual download.
"""
path = _cached_download_helper(cache_obj_name, dl_func, reset)
try:
dl_verify = cfg.PARAMS['dl_verify']
except KeyError:
dl_verify = True
if dl_verify and path and cache_obj_name not in cfg.DL_VERIFIED:
cache_section, cache_path = cache_obj_name.split('/', 1)
data = get_dl_verify_data(cache_section)
if cache_path not in data.index:
logger.info('No known hash for %s' % cache_obj_name)
cfg.DL_VERIFIED[cache_obj_name] = True
else:
# compute the hash
sha256 = hashlib.sha256()
with open(path, 'rb') as f:
for b in iter(lambda: f.read(0xFFFF), b''):
sha256.update(b)
sha256 = sha256.digest()
size = os.path.getsize(path)
# check
data = data.loc[cache_path]
if data['size'] != size or bytes(data['sha256']) != sha256:
err = '%s failed to verify!\nis: %s %s\nexpected: %s %s' % (
path, size, sha256.hex(), data[0], data[1].hex())
<|code_end|>
. Use current file imports:
(import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist)
and context including class names, function names, or small code snippets from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
. Output only the next line. | raise DownloadVerificationFailedException(msg=err, path=path) |
Based on the snippet: <|code_start|> """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._sock = None
@property
def sock(self):
"""Return the socket."""
return self._sock
@sock.setter
def sock(self, value):
"""When modifying the socket, ensure that it is ssl wrapped."""
if value is not None and not isinstance(value, ssl.SSLSocket):
value = self.context.wrap_socket(value)
self._sock = value
def url_exists(url):
"""Checks if a given a URL exists or not."""
request = requests.get(url)
return request.status_code < 400
def _ftps_retrieve(url, path, reporthook, auth=None, timeout=None):
""" Wrapper around ftplib to download from FTPS server
"""
if not auth:
<|code_end|>
, predict the immediate next line with the help of imports:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context (classes, functions, sometimes code) from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
. Output only the next line. | raise DownloadCredentialsMissingException('No authentication ' |
Based on the snippet: <|code_start|> else:
# compute the hash
sha256 = hashlib.sha256()
with open(path, 'rb') as f:
for b in iter(lambda: f.read(0xFFFF), b''):
sha256.update(b)
sha256 = sha256.digest()
size = os.path.getsize(path)
# check
data = data.loc[cache_path]
if data['size'] != size or bytes(data['sha256']) != sha256:
err = '%s failed to verify!\nis: %s %s\nexpected: %s %s' % (
path, size, sha256.hex(), data[0], data[1].hex())
raise DownloadVerificationFailedException(msg=err, path=path)
logger.info('%s verified successfully.' % path)
cfg.DL_VERIFIED[cache_obj_name] = True
return path
def _requests_urlretrieve(url, path, reporthook, auth=None, timeout=None):
"""Implements the required features of urlretrieve on top of requests
"""
chunk_size = 128 * 1024
chunk_count = 0
with requests.get(url, stream=True, auth=auth, timeout=timeout) as r:
if r.status_code != 200:
<|code_end|>
, predict the immediate next line with the help of imports:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context (classes, functions, sometimes code) from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
. Output only the next line. | raise HttpDownloadError(r.status_code, url) |
Given snippet: <|code_start|>
def _requests_urlretrieve(url, path, reporthook, auth=None, timeout=None):
"""Implements the required features of urlretrieve on top of requests
"""
chunk_size = 128 * 1024
chunk_count = 0
with requests.get(url, stream=True, auth=auth, timeout=timeout) as r:
if r.status_code != 200:
raise HttpDownloadError(r.status_code, url)
r.raise_for_status()
size = r.headers.get('content-length') or -1
size = int(size)
if reporthook:
reporthook(chunk_count, chunk_size, size)
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if not chunk:
continue
f.write(chunk)
chunk_count += 1
if reporthook:
reporthook(chunk_count, chunk_size, size)
if chunk_count * chunk_size < size:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
which might include code, classes, or functions. Output only the next line. | raise HttpContentTooShortError() |
Given snippet: <|code_start|>def rema_zone(lon_ex, lat_ex):
"""Returns a list of REMA-DEM zones covering the desired extent.
"""
gdf = gpd.read_file(get_demo_file('REMA_Tile_Index_Rel1.1.shp'))
p = _extent_to_polygon(lon_ex, lat_ex, to_crs=gdf.crs)
gdf = gdf.loc[gdf.intersects(p)]
return gdf.tile.values if len(gdf) > 0 else []
def alaska_dem_zone(lon_ex, lat_ex):
"""Returns a list of Alaska-DEM zones covering the desired extent.
"""
gdf = gpd.read_file(get_demo_file('Alaska_albers_V3_tiles.shp'))
p = _extent_to_polygon(lon_ex, lat_ex, to_crs=gdf.crs)
gdf = gdf.loc[gdf.intersects(p)]
return gdf.tile.values if len(gdf) > 0 else []
def copdem_zone(lon_ex, lat_ex, source):
"""Returns a list of Copernicus DEM tarfile and tilename tuples
"""
# because we use both meters and arc secs in our filenames...
if source[-2:] == '90':
asec = '30'
elif source[-2:] == '30':
asec = '10'
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
which might include code, classes, or functions. Output only the next line. | raise InvalidDEMError('COPDEM Version not valid.') |
Given the code snippet: <|code_start|>
# Decide if Implicit or Explicit FTPS is used based on the port in url
if upar.port == 990:
ftps = ImplicitFTPTLS()
elif upar.port == 21:
ftps = ftplib.FTP_TLS()
try:
# establish ssl connection
ftps.connect(host=upar.hostname, port=upar.port, timeout=timeout)
ftps.login(user=auth[0], passwd=auth[1])
ftps.prot_p()
logger.info('Established connection %s' % upar.hostname)
# meta for progress bar size
count = 0
total = ftps.size(upar.path)
bs = 12*1024
def _ftps_progress(data):
outfile.write(data)
nonlocal count
count += 1
reporthook(count, count*bs, total)
with open(path, 'wb') as outfile:
ftps.retrbinary('RETR ' + upar.path, _ftps_progress, blocksize=bs)
except (ftplib.error_perm, socket.timeout, socket.gaierror) as err:
<|code_end|>
, generate the next line using the imports in this file:
import glob
import os
import gzip
import bz2
import hashlib
import shutil
import zipfile
import sys
import math
import logging
import time
import fnmatch
import urllib.request
import urllib.error
import socket
import multiprocessing
import ftplib
import ssl
import tarfile
import pandas as pd
import numpy as np
import shapely.geometry as shpg
import requests
import geopandas as gpd
import salem
import rasterio
import oggm.cfg as cfg
from functools import partial, wraps
from urllib.parse import urlparse
from netrc import netrc
from salem import wgs84
from rasterio.merge import merge as merge_tool
from rasterio.tools.merge import merge as merge_tool
from oggm.exceptions import (InvalidParamsError, NoInternetException,
DownloadVerificationFailedException,
DownloadCredentialsMissingException,
HttpDownloadError, HttpContentTooShortError,
InvalidDEMError, FTPSDownloadError)
from progressbar import DataTransferBar, UnknownLength
from oggm.utils import robust_tar_extract
from oggm.utils import tolist
from oggm.utils import tolist
and context (functions, classes, or occasionally code) from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
#
# class NoInternetException(Exception):
# pass
#
# class DownloadVerificationFailedException(Exception):
# def __init__(self, msg=None, path=None):
# self.msg = msg
# self.path = path
#
# class DownloadCredentialsMissingException(Exception):
# pass
#
# class HttpDownloadError(Exception):
# def __init__(self, code, url):
# self.code = code
# self.url = url
#
# class HttpContentTooShortError(Exception):
# pass
#
# class InvalidDEMError(RuntimeError):
# pass
#
# class FTPSDownloadError(Exception):
# def __init__(self, orgerr):
# self.orgerr = orgerr
. Output only the next line. | raise FTPSDownloadError(err) |
Predict the next line after this snippet: <|code_start|> help='Run OGGM in mpi mode')
args, unkn = parser.parse_known_args()
if not args.mpi:
return
OGGM_MPI_COMM = MPI.COMM_WORLD
OGGM_MPI_SIZE = OGGM_MPI_COMM.Get_size() - 1
rank = OGGM_MPI_COMM.Get_rank()
if OGGM_MPI_SIZE <= 0:
_imprint("Error: MPI world size is too small, at least one worker "
"process is required.")
sys.exit(1)
if rank != OGGM_MPI_ROOT:
_mpi_slave()
sys.exit(0)
if OGGM_MPI_SIZE < 2:
_imprint("Warning: MPI world size is small, this is pointless and "
"has no benefit.")
atexit.register(_shutdown_slaves)
_imprint("MPI initialized with a worker count of %s" % OGGM_MPI_SIZE)
def mpi_master_spin_tasks(task, gdirs):
comm = OGGM_MPI_COMM
<|code_end|>
using the current file's imports:
from mpi4py import MPI
from oggm import cfg
import atexit
import argparse
import sys
and any relevant context from other files:
# Path: oggm/cfg.py
# CACHE_DIR = os.path.join(os.path.expanduser('~'), '.oggm')
# CONFIG_FILE = os.path.join(os.path.expanduser('~'), '.oggm_config')
# CONFIG_MODIFIED = False
# DL_VERIFIED = dict()
# DEM_SOURCE_TABLE = dict()
# DATA = dict()
# FLOAT_EPS = np.finfo(float).eps
# CONFIG_MODIFIED = True
# CONFIG_MODIFIED = True
# IS_INITIALIZED = False
# PARAMS = ParamsLoggingDict()
# PATHS = PathOrderedDict()
# BASENAMES = DocumentedDict()
# LRUHANDLERS = ResettingOrderedDict()
# SEC_IN_YEAR = 365*24*3600
# SEC_IN_DAY = 24*3600
# SEC_IN_HOUR = 3600
# SEC_IN_MONTH = 2628000
# DAYS_IN_MONTH = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
# G = 9.80665 # gravity
# GAUSSIAN_KERNEL = dict()
# IS_INITIALIZED = True
# IS_INITIALIZED = cfg_dict['IS_INITIALIZED']
# PARAMS = cfg_dict['PARAMS']
# PATHS = cfg_dict['PATHS']
# LRUHANDLERS = cfg_dict['LRUHANDLERS']
# DATA = cfg_dict['DATA']
# DL_VERIFIED = cfg_dict['DL_VERIFIED']
# DEM_SOURCE_TABLE = cfg_dict['DEM_SOURCE_TABLE']
# BASENAMES = DocumentedDict()
# DL_VERIFIED = new_dict
# DEM_SOURCE_TABLE = new_dict
# DATA = new_dict
# DL_VERIFIED = dict(DL_VERIFIED)
# DEM_SOURCE_TABLE = dict(DEM_SOURCE_TABLE)
# DATA = dict(DATA)
# class DocumentedDict(dict):
# class ResettingOrderedDict(OrderedDict):
# class PathOrderedDict(ResettingOrderedDict):
# class ParamsLoggingDict(ResettingOrderedDict):
# def __init__(self):
# def _set_key(self, key, value, docstr=''):
# def __setitem__(self, key, value):
# def info_str(self, key):
# def doc_str(self, key):
# def __setitem__(self, key, value):
# def __setitem__(self, key, value):
# def __setitem__(self, key, value):
# def _log_param_change(self, key, value):
# def set_logging_config(logging_level='INFO', future=False):
# def workflow(self, message, *args, **kws):
# def initialize_minimal(file=None, logging_level='INFO', params=None,
# future=False):
# def initialize(file=None, logging_level='INFO', params=None, future=False):
# def oggm_static_paths():
# def get_lru_handler(tmpdir=None, maxsize=None, ending='.tif'):
# def set_intersects_db(path_or_gdf=None):
# def reset_working_dir():
# def pack_config():
# def unpack_config(cfg_dict):
# def set_manager(manager):
# def add_to_basenames(basename, filename, docstr=''):
. Output only the next line. | cfg_store = cfg.pack_config() |
Given the following code snippet before the placeholder: <|code_start|> except BaseException:
raise ValueError('DocumentedDict accepts only tuple of len 2')
def info_str(self, key):
"""Info string for the documentation."""
return ' {}'.format(self[key]) + '\n' + ' ' + self._doc[key]
def doc_str(self, key):
"""Info string for the documentation."""
return ' {}'.format(self[key]) + '\n' + ' ' + \
self._doc[key]
class ResettingOrderedDict(OrderedDict):
"""OrderedDict wrapper that resets our multiprocessing on set"""
def __setitem__(self, key, value):
global CONFIG_MODIFIED
OrderedDict.__setitem__(self, key, value)
CONFIG_MODIFIED = True
class PathOrderedDict(ResettingOrderedDict):
"""Quick "magic" to be sure that paths are expanded correctly."""
def __setitem__(self, key, value):
# Overrides the original dic to expand the path
try:
value = os.path.expanduser(value)
except AttributeError:
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
import shutil
import sys
import glob
import warnings
import numpy as np
import pandas as pd
import geopandas as gpd
import salem
import multiprocessing
import multiprocessing
from collections import OrderedDict
from distutils.util import strtobool
from scipy.signal.windows import gaussian
from scipy.signal import gaussian
from configobj import ConfigObj, ConfigObjError
from oggm.exceptions import InvalidParamsError
from oggm.utils import download_oggm_files, get_demo_file
from oggm.utils import get_dl_verify_data
from oggm.utils import LRUFileCache
and context including class names, function names, and sometimes code from other files:
# Path: oggm/exceptions.py
# class InvalidParamsError(ValueError):
# pass
. Output only the next line. | raise InvalidParamsError('The value you are trying to set does ' |
Using the snippet: <|code_start|>
@background(queue=settings.INBOX_EMAIL_NOTIFICATION_QUEUE)
def send_email_notification(message_id, base_site_url):
message_template = 'inbox/message_notification_email.html'
message = Message.objects.select_related('thread').get(pk=message_id)
thread = message.thread
sender = message.sent_by
recipient = inbox_service.get_recipient(thread=thread, sender=sender)
subject, sender_name, url_path = _get_email_context(
thread=thread, message=message, recipient=recipient)
context = {
'recipient': recipient.username,
'sender': sender_name,
'message': message.text,
'url': urljoin(base_site_url, url_path)
}
m = render_to_string(template_name=message_template, context=context)
<|code_end|>
, determine the next line of code. You have imports:
from urllib.parse import urljoin
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import reverse
from background_task import background
from della.email_service import send_email
from .models import Message
from . import inbox_service
and context (class names, function names, or code) available:
# Path: della/email_service/core.py
# def send_email(subject, message, recipient_list):
# send_mail(
# subject=subject,
# message=message,
# html_message=message.replace('\n', '<br />'),
# from_email=settings.SENDER_EMAIL,
# recipient_list=recipient_list,
# )
#
# Path: della/inbox/models.py
# class Message(TimeStampMixin):
# text = models.TextField()
#
# sent_by = models.ForeignKey(User, on_delete=models.CASCADE)
# thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name='messages')
. Output only the next line. | send_email(subject=subject, message=m, recipient_list=[recipient.email]) |
Here is a snippet: <|code_start|>
@background(queue=settings.INBOX_EMAIL_NOTIFICATION_QUEUE)
def send_email_notification(message_id, base_site_url):
message_template = 'inbox/message_notification_email.html'
<|code_end|>
. Write the next line using the current file imports:
from urllib.parse import urljoin
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import reverse
from background_task import background
from della.email_service import send_email
from .models import Message
from . import inbox_service
and context from other files:
# Path: della/email_service/core.py
# def send_email(subject, message, recipient_list):
# send_mail(
# subject=subject,
# message=message,
# html_message=message.replace('\n', '<br />'),
# from_email=settings.SENDER_EMAIL,
# recipient_list=recipient_list,
# )
#
# Path: della/inbox/models.py
# class Message(TimeStampMixin):
# text = models.TextField()
#
# sent_by = models.ForeignKey(User, on_delete=models.CASCADE)
# thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name='messages')
, which may include functions, classes, or code. Output only the next line. | message = Message.objects.select_related('thread').get(pk=message_id) |
Given snippet: <|code_start|>
app_name = 'inbox'
urlpatterns = [
re_path(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
name='thread-detail'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.urls import path, re_path
from .views import (MessageCreateView, ThreadDetailView, ThreadListView,
SantaThreadDetailView, SanteeThreadDetailView)
and context:
# Path: della/inbox/views.py
# class MessageCreateView(CreateView):
# model = Message
# form_class = MessageCreateForm
# success_url = '/'
#
# def post(self, request, pk, *args, **kwargs):
# if not request.is_ajax():
# raise Http404('Haxxeru?')
# self.thread = self._validate_and_get_thread(thread_id=pk)
# if not self.thread:
# raise Http404('Haxxeru?')
# return super().post(request, pk, *args, **kwargs)
#
# def form_valid(self, form):
# message = form.save(commit=False)
# message.sent_by = self.request.user
# message.thread = self.thread
# super().form_valid(form)
# response = self._get_response()
# base_site_url = self.request.build_absolute_uri('/')
# tasks.send_email_notification(
# message_id=self.object.id, base_site_url=base_site_url)
# return JsonResponse(response)
#
# def _validate_and_get_thread(self, thread_id):
# user = self.request.user
# return Thread.objects.filter(
# Q(pk=thread_id) & Q(
# Q(participant_1=user) | Q(participant_2=user))).first()
#
# def _get_response(self):
# timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT')
# data = {
# 'text': self.object.text,
# 'signature': "{} | {}".format(self.object.sent_by.username,
# timestamp),
# }
# return {'status': True, 'data': data}
#
# class ThreadDetailView(BaseThreadDetailView):
# """
# To render (non-sneaky) message thread between two users
# """
#
# def get_object(self):
# user = self.request.user
# recipient_name = self.kwargs.get('recipient')
# recipient = get_object_or_404(User, username=recipient_name)
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=recipient)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2)
# thread.recipient = recipient_name
# return thread
#
# class ThreadListView(ListView):
# model = Thread
#
# def get_queryset(self):
# user = self.request.user
# return Thread.objects.prefetch_related('messages').filter(
# Q(participant_1=user) | Q(participant_2=user)).annotate(
# last_message_time=Max('messages__created_on')).order_by(
# '-last_message_time')
#
# def get_context_data(self, **kwargs):
# sender = self.request.user
# context = super().get_context_data(**kwargs)
# object_list = []
# sneaky_list = []
# for obj in context['object_list']:
# try:
# obj.latest_message = obj.messages.latest('created_on')
# except Message.DoesNotExist:
# continue
# if obj.is_sneaky:
# sneaky_list.append(self._get_sneaky_context(thread=obj))
# else:
# obj.recipient = inbox_service.get_recipient(
# thread=obj, sender=sender)
# object_list.append(obj)
# context['object_list'] = object_list
# context['sneaky_list'] = sneaky_list
# return context
#
# def _get_sneaky_context(self, thread):
# if thread.santa == self.request.user:
# thread.title = 'Santee Messages'
# thread.url = reverse('inbox:santee-detail')
# else:
# thread.title = 'Santa Messages'
# thread.url = reverse('inbox:santa-detail')
# return thread
#
# class SantaThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user and his santa
# """
#
# template_name = 'inbox/thread_detail_sneaky.html'
#
# def get_object(self):
# user = self.request.user
# try:
# # user.santa is a UserProfile
# self.santa = user.santa.user
# except user.userprofile.DoesNotExist:
# raise Http404("You don't have a Santa. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=self.santa)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=self.santa)
# thread.recipient = 'Santa'
# return thread
#
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# for message in context['thread_messages']:
# if message.sent_by == self.santa:
# message.sent_by.username = 'Santa'
# return context
#
# class SanteeThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user (santa) and his santee
# """
#
# def get_object(self):
# user = self.request.user
# santee = user.userprofile.santee
# if not santee:
# raise Http404("You don't have a Santee. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=santee)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=user)
# thread.recipient = "{} (Santee)".format(santee.username)
# return thread
which might include code, classes, or functions. Output only the next line. | path('<int:pk>/new/', MessageCreateView.as_view(), |
Next line prediction: <|code_start|>
app_name = 'inbox'
urlpatterns = [
re_path(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
name='thread-detail'),
path('<int:pk>/new/', MessageCreateView.as_view(),
name='new-message'),
path('santa/', SantaThreadDetailView.as_view(), name='santa-detail'),
path('santee/', SanteeThreadDetailView.as_view(), name='santee-detail'),
<|code_end|>
. Use current file imports:
(from django.urls import path, re_path
from .views import (MessageCreateView, ThreadDetailView, ThreadListView,
SantaThreadDetailView, SanteeThreadDetailView))
and context including class names, function names, or small code snippets from other files:
# Path: della/inbox/views.py
# class MessageCreateView(CreateView):
# model = Message
# form_class = MessageCreateForm
# success_url = '/'
#
# def post(self, request, pk, *args, **kwargs):
# if not request.is_ajax():
# raise Http404('Haxxeru?')
# self.thread = self._validate_and_get_thread(thread_id=pk)
# if not self.thread:
# raise Http404('Haxxeru?')
# return super().post(request, pk, *args, **kwargs)
#
# def form_valid(self, form):
# message = form.save(commit=False)
# message.sent_by = self.request.user
# message.thread = self.thread
# super().form_valid(form)
# response = self._get_response()
# base_site_url = self.request.build_absolute_uri('/')
# tasks.send_email_notification(
# message_id=self.object.id, base_site_url=base_site_url)
# return JsonResponse(response)
#
# def _validate_and_get_thread(self, thread_id):
# user = self.request.user
# return Thread.objects.filter(
# Q(pk=thread_id) & Q(
# Q(participant_1=user) | Q(participant_2=user))).first()
#
# def _get_response(self):
# timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT')
# data = {
# 'text': self.object.text,
# 'signature': "{} | {}".format(self.object.sent_by.username,
# timestamp),
# }
# return {'status': True, 'data': data}
#
# class ThreadDetailView(BaseThreadDetailView):
# """
# To render (non-sneaky) message thread between two users
# """
#
# def get_object(self):
# user = self.request.user
# recipient_name = self.kwargs.get('recipient')
# recipient = get_object_or_404(User, username=recipient_name)
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=recipient)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2)
# thread.recipient = recipient_name
# return thread
#
# class ThreadListView(ListView):
# model = Thread
#
# def get_queryset(self):
# user = self.request.user
# return Thread.objects.prefetch_related('messages').filter(
# Q(participant_1=user) | Q(participant_2=user)).annotate(
# last_message_time=Max('messages__created_on')).order_by(
# '-last_message_time')
#
# def get_context_data(self, **kwargs):
# sender = self.request.user
# context = super().get_context_data(**kwargs)
# object_list = []
# sneaky_list = []
# for obj in context['object_list']:
# try:
# obj.latest_message = obj.messages.latest('created_on')
# except Message.DoesNotExist:
# continue
# if obj.is_sneaky:
# sneaky_list.append(self._get_sneaky_context(thread=obj))
# else:
# obj.recipient = inbox_service.get_recipient(
# thread=obj, sender=sender)
# object_list.append(obj)
# context['object_list'] = object_list
# context['sneaky_list'] = sneaky_list
# return context
#
# def _get_sneaky_context(self, thread):
# if thread.santa == self.request.user:
# thread.title = 'Santee Messages'
# thread.url = reverse('inbox:santee-detail')
# else:
# thread.title = 'Santa Messages'
# thread.url = reverse('inbox:santa-detail')
# return thread
#
# class SantaThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user and his santa
# """
#
# template_name = 'inbox/thread_detail_sneaky.html'
#
# def get_object(self):
# user = self.request.user
# try:
# # user.santa is a UserProfile
# self.santa = user.santa.user
# except user.userprofile.DoesNotExist:
# raise Http404("You don't have a Santa. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=self.santa)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=self.santa)
# thread.recipient = 'Santa'
# return thread
#
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# for message in context['thread_messages']:
# if message.sent_by == self.santa:
# message.sent_by.username = 'Santa'
# return context
#
# class SanteeThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user (santa) and his santee
# """
#
# def get_object(self):
# user = self.request.user
# santee = user.userprofile.santee
# if not santee:
# raise Http404("You don't have a Santee. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=santee)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=user)
# thread.recipient = "{} (Santee)".format(santee.username)
# return thread
. Output only the next line. | path('', ThreadListView.as_view(), name='threads') |
Given snippet: <|code_start|>
app_name = 'inbox'
urlpatterns = [
re_path(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
name='thread-detail'),
path('<int:pk>/new/', MessageCreateView.as_view(),
name='new-message'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.urls import path, re_path
from .views import (MessageCreateView, ThreadDetailView, ThreadListView,
SantaThreadDetailView, SanteeThreadDetailView)
and context:
# Path: della/inbox/views.py
# class MessageCreateView(CreateView):
# model = Message
# form_class = MessageCreateForm
# success_url = '/'
#
# def post(self, request, pk, *args, **kwargs):
# if not request.is_ajax():
# raise Http404('Haxxeru?')
# self.thread = self._validate_and_get_thread(thread_id=pk)
# if not self.thread:
# raise Http404('Haxxeru?')
# return super().post(request, pk, *args, **kwargs)
#
# def form_valid(self, form):
# message = form.save(commit=False)
# message.sent_by = self.request.user
# message.thread = self.thread
# super().form_valid(form)
# response = self._get_response()
# base_site_url = self.request.build_absolute_uri('/')
# tasks.send_email_notification(
# message_id=self.object.id, base_site_url=base_site_url)
# return JsonResponse(response)
#
# def _validate_and_get_thread(self, thread_id):
# user = self.request.user
# return Thread.objects.filter(
# Q(pk=thread_id) & Q(
# Q(participant_1=user) | Q(participant_2=user))).first()
#
# def _get_response(self):
# timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT')
# data = {
# 'text': self.object.text,
# 'signature': "{} | {}".format(self.object.sent_by.username,
# timestamp),
# }
# return {'status': True, 'data': data}
#
# class ThreadDetailView(BaseThreadDetailView):
# """
# To render (non-sneaky) message thread between two users
# """
#
# def get_object(self):
# user = self.request.user
# recipient_name = self.kwargs.get('recipient')
# recipient = get_object_or_404(User, username=recipient_name)
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=recipient)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2)
# thread.recipient = recipient_name
# return thread
#
# class ThreadListView(ListView):
# model = Thread
#
# def get_queryset(self):
# user = self.request.user
# return Thread.objects.prefetch_related('messages').filter(
# Q(participant_1=user) | Q(participant_2=user)).annotate(
# last_message_time=Max('messages__created_on')).order_by(
# '-last_message_time')
#
# def get_context_data(self, **kwargs):
# sender = self.request.user
# context = super().get_context_data(**kwargs)
# object_list = []
# sneaky_list = []
# for obj in context['object_list']:
# try:
# obj.latest_message = obj.messages.latest('created_on')
# except Message.DoesNotExist:
# continue
# if obj.is_sneaky:
# sneaky_list.append(self._get_sneaky_context(thread=obj))
# else:
# obj.recipient = inbox_service.get_recipient(
# thread=obj, sender=sender)
# object_list.append(obj)
# context['object_list'] = object_list
# context['sneaky_list'] = sneaky_list
# return context
#
# def _get_sneaky_context(self, thread):
# if thread.santa == self.request.user:
# thread.title = 'Santee Messages'
# thread.url = reverse('inbox:santee-detail')
# else:
# thread.title = 'Santa Messages'
# thread.url = reverse('inbox:santa-detail')
# return thread
#
# class SantaThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user and his santa
# """
#
# template_name = 'inbox/thread_detail_sneaky.html'
#
# def get_object(self):
# user = self.request.user
# try:
# # user.santa is a UserProfile
# self.santa = user.santa.user
# except user.userprofile.DoesNotExist:
# raise Http404("You don't have a Santa. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=self.santa)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=self.santa)
# thread.recipient = 'Santa'
# return thread
#
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# for message in context['thread_messages']:
# if message.sent_by == self.santa:
# message.sent_by.username = 'Santa'
# return context
#
# class SanteeThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user (santa) and his santee
# """
#
# def get_object(self):
# user = self.request.user
# santee = user.userprofile.santee
# if not santee:
# raise Http404("You don't have a Santee. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=santee)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=user)
# thread.recipient = "{} (Santee)".format(santee.username)
# return thread
which might include code, classes, or functions. Output only the next line. | path('santa/', SantaThreadDetailView.as_view(), name='santa-detail'), |
Based on the snippet: <|code_start|>
app_name = 'inbox'
urlpatterns = [
re_path(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
name='thread-detail'),
path('<int:pk>/new/', MessageCreateView.as_view(),
name='new-message'),
path('santa/', SantaThreadDetailView.as_view(), name='santa-detail'),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.urls import path, re_path
from .views import (MessageCreateView, ThreadDetailView, ThreadListView,
SantaThreadDetailView, SanteeThreadDetailView)
and context (classes, functions, sometimes code) from other files:
# Path: della/inbox/views.py
# class MessageCreateView(CreateView):
# model = Message
# form_class = MessageCreateForm
# success_url = '/'
#
# def post(self, request, pk, *args, **kwargs):
# if not request.is_ajax():
# raise Http404('Haxxeru?')
# self.thread = self._validate_and_get_thread(thread_id=pk)
# if not self.thread:
# raise Http404('Haxxeru?')
# return super().post(request, pk, *args, **kwargs)
#
# def form_valid(self, form):
# message = form.save(commit=False)
# message.sent_by = self.request.user
# message.thread = self.thread
# super().form_valid(form)
# response = self._get_response()
# base_site_url = self.request.build_absolute_uri('/')
# tasks.send_email_notification(
# message_id=self.object.id, base_site_url=base_site_url)
# return JsonResponse(response)
#
# def _validate_and_get_thread(self, thread_id):
# user = self.request.user
# return Thread.objects.filter(
# Q(pk=thread_id) & Q(
# Q(participant_1=user) | Q(participant_2=user))).first()
#
# def _get_response(self):
# timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT')
# data = {
# 'text': self.object.text,
# 'signature': "{} | {}".format(self.object.sent_by.username,
# timestamp),
# }
# return {'status': True, 'data': data}
#
# class ThreadDetailView(BaseThreadDetailView):
# """
# To render (non-sneaky) message thread between two users
# """
#
# def get_object(self):
# user = self.request.user
# recipient_name = self.kwargs.get('recipient')
# recipient = get_object_or_404(User, username=recipient_name)
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=recipient)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2)
# thread.recipient = recipient_name
# return thread
#
# class ThreadListView(ListView):
# model = Thread
#
# def get_queryset(self):
# user = self.request.user
# return Thread.objects.prefetch_related('messages').filter(
# Q(participant_1=user) | Q(participant_2=user)).annotate(
# last_message_time=Max('messages__created_on')).order_by(
# '-last_message_time')
#
# def get_context_data(self, **kwargs):
# sender = self.request.user
# context = super().get_context_data(**kwargs)
# object_list = []
# sneaky_list = []
# for obj in context['object_list']:
# try:
# obj.latest_message = obj.messages.latest('created_on')
# except Message.DoesNotExist:
# continue
# if obj.is_sneaky:
# sneaky_list.append(self._get_sneaky_context(thread=obj))
# else:
# obj.recipient = inbox_service.get_recipient(
# thread=obj, sender=sender)
# object_list.append(obj)
# context['object_list'] = object_list
# context['sneaky_list'] = sneaky_list
# return context
#
# def _get_sneaky_context(self, thread):
# if thread.santa == self.request.user:
# thread.title = 'Santee Messages'
# thread.url = reverse('inbox:santee-detail')
# else:
# thread.title = 'Santa Messages'
# thread.url = reverse('inbox:santa-detail')
# return thread
#
# class SantaThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user and his santa
# """
#
# template_name = 'inbox/thread_detail_sneaky.html'
#
# def get_object(self):
# user = self.request.user
# try:
# # user.santa is a UserProfile
# self.santa = user.santa.user
# except user.userprofile.DoesNotExist:
# raise Http404("You don't have a Santa. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=self.santa)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=self.santa)
# thread.recipient = 'Santa'
# return thread
#
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# for message in context['thread_messages']:
# if message.sent_by == self.santa:
# message.sent_by.username = 'Santa'
# return context
#
# class SanteeThreadDetailView(BaseThreadDetailView):
# """
# To render message thread between logged in user (santa) and his santee
# """
#
# def get_object(self):
# user = self.request.user
# santee = user.userprofile.santee
# if not santee:
# raise Http404("You don't have a Santee. Yet ;)")
# participant_1, participant_2 = inbox_service.get_participants(
# user_1=user, user_2=santee)
# thread = self._get_thread(
# participant_1=participant_1, participant_2=participant_2,
# santa=user)
# thread.recipient = "{} (Santee)".format(santee.username)
# return thread
. Output only the next line. | path('santee/', SanteeThreadDetailView.as_view(), name='santee-detail'), |
Next line prediction: <|code_start|>
class ImageUploadForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# make description optional field
self.fields['description'].required = False
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'Upload Image',
'title',
'file',
'description'
)
)
self.helper.form_class = 'form-horizontal'
self.helper.form_method = 'post'
self.helper.form_action = 'gallery:upload'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-10'
self.helper.add_input(Reset('reset', 'Cancel'))
self.helper.add_input(Submit('submit', 'Submit'))
class Meta:
<|code_end|>
. Use current file imports:
(from django.forms import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Reset, Layout, Fieldset
from .models import Image)
and context including class names, function names, or small code snippets from other files:
# Path: della/gallery/models.py
# class Image(TimeStampMixin):
# file = models.ImageField(upload_to='images/%Y/%m/%d')
# title = models.CharField(max_length=300)
# description = models.TextField(null=True)
# added_by = models.ForeignKey(User, on_delete=models.CASCADE)
. Output only the next line. | model = Image |
Next line prediction: <|code_start|>
class HomePageView(TemplateView):
template_name = 'home.html'
template_name_authenticated = 'home_authenticated.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
self.template_name = self.template_name_authenticated
return context
<|code_end|>
. Use current file imports:
(from django.views.generic.base import TemplateView
from della.user_manager.forms import SignupForm)
and context including class names, function names, or small code snippets from other files:
# Path: della/user_manager/forms.py
# class SignupForm(UserCreationForm):
# username = forms.CharField(max_length=20, validators=[alphanumericu])
# email = forms.EmailField(max_length=254, required=True)
# invite_code = forms.CharField(max_length=120)
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.helper = FormHelper()
# self.helper.layout = Layout(
# Fieldset(
# 'Signup',
# 'invite_code',
# 'username',
# 'email',
# 'password1',
# 'password2'
# )
# )
# self.helper.form_class = 'form-horizontal'
# self.helper.form_method = 'post'
# self.helper.form_action = 'user_manager:signup'
# self.helper.label_class = 'col-lg-2'
# self.helper.field_class = 'col-lg-10'
# self.helper.add_input(Reset('reset', 'Cancel'))
# self.helper.add_input(Submit('submit', 'Signup'))
#
# def clean_invite_code(self):
# error_message = 'Invalid invite code'
# invite_code = self.cleaned_data.get('invite_code')
# if not invite_code == settings.INVITE_CODE:
# raise forms.ValidationError(error_message)
# return invite_code
#
# def clean_email(self):
# error_message = 'An user with that email already exists'
# email = self.cleaned_data.get('email')
# if email and User.objects.filter(email=email).exists():
# raise forms.ValidationError(error_message)
# return email
#
# class Meta:
# model = User
# fields = ['email', 'username', ]
. Output only the next line. | context['form'] = SignupForm() |
Based on the snippet: <|code_start|>
@method_decorator(login_required, name='dispatch')
class ImageUploadView(CreateView):
model = Image
<|code_end|>
, predict the immediate next line with the help of imports:
from django.views.generic.edit import CreateView
from django.views.generic import DetailView, ListView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import reverse
from .models import Image
from .forms import ImageUploadForm
and context (classes, functions, sometimes code) from other files:
# Path: della/gallery/models.py
# class Image(TimeStampMixin):
# file = models.ImageField(upload_to='images/%Y/%m/%d')
# title = models.CharField(max_length=300)
# description = models.TextField(null=True)
# added_by = models.ForeignKey(User, on_delete=models.CASCADE)
#
# Path: della/gallery/forms.py
# class ImageUploadForm(ModelForm):
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
#
# # make description optional field
# self.fields['description'].required = False
#
# self.helper = FormHelper()
# self.helper.layout = Layout(
# Fieldset(
# 'Upload Image',
# 'title',
# 'file',
# 'description'
# )
# )
# self.helper.form_class = 'form-horizontal'
# self.helper.form_method = 'post'
# self.helper.form_action = 'gallery:upload'
# self.helper.label_class = 'col-lg-2'
# self.helper.field_class = 'col-lg-10'
# self.helper.add_input(Reset('reset', 'Cancel'))
# self.helper.add_input(Submit('submit', 'Submit'))
#
# class Meta:
# model = Image
# fields = ['title', 'file', 'description']
. Output only the next line. | form_class = ImageUploadForm |
Next line prediction: <|code_start|>"""della URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
urlpatterns = [
path('gallery/', include(
'della.gallery.urls', namespace='gallery')),
path('messages/', include(
'della.inbox.urls', namespace='inbox')),
path('', include(
'della.user_manager.urls', namespace='user_manager')),
<|code_end|>
. Use current file imports:
(from django.urls import include, path
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from .views import HomePageView)
and context including class names, function names, or small code snippets from other files:
# Path: della/views.py
# class HomePageView(TemplateView):
#
# template_name = 'home.html'
# template_name_authenticated = 'home_authenticated.html'
#
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# if self.request.user.is_authenticated:
# self.template_name = self.template_name_authenticated
# return context
# context['form'] = SignupForm()
# return context
. Output only the next line. | path('', HomePageView.as_view()), |
Next line prediction: <|code_start|> self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'Update Your Profile',
'avatar',
'bio',
'website_url',
'fb_profile_url',
'twitter_profile_url',
'wishlist_url',
HTML("""
<hr /><p><span class="help-block">Below fields are only visible
to your Santa</span></p>
"""),
'first_name',
'last_name',
'preferences',
'address',
'shipping_instructions'
)
)
self.helper.form_class = 'form-horizontal'
self.helper.form_method = 'post'
self.helper.form_action = 'user_manager:account'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-10'
self.helper.add_input(Reset('reset', 'Cancel'))
self.helper.add_input(Submit('submit', 'Submit'))
class Meta:
<|code_end|>
. Use current file imports:
(from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import RegexValidator, validate_email
from django.conf import settings
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Reset, Layout, Fieldset, HTML
from .models import UserProfile)
and context including class names, function names, or small code snippets from other files:
# Path: della/user_manager/models.py
# class UserProfile(TimeStampMixin):
# """
# To manage users and stuff. From default `User` we will use `username`,
# `email`, `password`, `first_name` and `last_name`.
# """
# bio = models.TextField(null=True)
# address = models.TextField(null=True)
# shipping_instructions = models.TextField(null=True)
# is_enabled_exchange = models.BooleanField(default=False)
# preferences = models.TextField(null=True)
# fb_profile_url = models.URLField(null=True)
# twitter_profile_url = models.URLField(null=True)
# website_url = models.URLField(null=True)
# wishlist_url = models.URLField(null=True)
# avatar = models.ImageField(
# upload_to=avatar_file_name, default='avatar.png')
#
# user = models.OneToOneField(User, on_delete=models.CASCADE)
# santee = models.OneToOneField(User, on_delete=models.CASCADE, related_name='santa', null=True)
#
# def __str__(self):
# return self.user.username
. Output only the next line. | model = UserProfile |
Predict the next line after this snippet: <|code_start|>def create_user_profile(user):
UserProfile.objects.create(user=user, is_enabled_exchange=False)
def activate_user(user):
if user.is_active:
return True
user.is_active = True
user.save()
return True
def enable_for_exchange(user):
if user.userprofile.is_enabled_exchange:
return True
user.userprofile.is_enabled_exchange = True
user.userprofile.save()
return True
def send_activation_email(request, user):
message_template = 'user_manager/account_activation_email.html'
subject_temaplte = 'user_manager/account_activation_subject.txt'
code = activation_service.generate_key(user)
path_params = {'username': user.username, 'code': code}
activation_url = request.build_absolute_uri(reverse(
'user_manager:activate-user', kwargs=path_params))
context = {'url': activation_url, 'username': user.username}
message = render_to_string(template_name=message_template, context=context)
subject = render_to_string(template_name=subject_temaplte)
<|code_end|>
using the current file's imports:
from django.template.loader import render_to_string
from django.urls import reverse
from della.email_service import send_email
from .models import UserProfile
from . import activation_service
and any relevant context from other files:
# Path: della/email_service/core.py
# def send_email(subject, message, recipient_list):
# send_mail(
# subject=subject,
# message=message,
# html_message=message.replace('\n', '<br />'),
# from_email=settings.SENDER_EMAIL,
# recipient_list=recipient_list,
# )
#
# Path: della/user_manager/models.py
# class UserProfile(TimeStampMixin):
# """
# To manage users and stuff. From default `User` we will use `username`,
# `email`, `password`, `first_name` and `last_name`.
# """
# bio = models.TextField(null=True)
# address = models.TextField(null=True)
# shipping_instructions = models.TextField(null=True)
# is_enabled_exchange = models.BooleanField(default=False)
# preferences = models.TextField(null=True)
# fb_profile_url = models.URLField(null=True)
# twitter_profile_url = models.URLField(null=True)
# website_url = models.URLField(null=True)
# wishlist_url = models.URLField(null=True)
# avatar = models.ImageField(
# upload_to=avatar_file_name, default='avatar.png')
#
# user = models.OneToOneField(User, on_delete=models.CASCADE)
# santee = models.OneToOneField(User, on_delete=models.CASCADE, related_name='santa', null=True)
#
# def __str__(self):
# return self.user.username
. Output only the next line. | send_email(subject=subject, message=message, recipient_list=[user.email]) |
Given the code snippet: <|code_start|>
@method_decorator(login_required, name='dispatch')
class MessageCreateView(CreateView):
model = Message
<|code_end|>
, generate the next line using the imports in this file:
from django.views.generic.edit import CreateView
from django.views.generic import DetailView, ListView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import reverse, get_object_or_404
from django.db.models import Q, Max
from django.http import Http404, JsonResponse
from django.contrib.auth.models import User
from django.utils.formats import date_format
from .forms import MessageCreateForm
from .models import Message, Thread
from . import inbox_service
from . import tasks
and context (functions, classes, or occasionally code) from other files:
# Path: della/inbox/forms.py
# class MessageCreateForm(ModelForm):
#
# class Meta:
# model = Message
# fields = ['text']
#
# Path: della/inbox/models.py
# class Message(TimeStampMixin):
# text = models.TextField()
#
# sent_by = models.ForeignKey(User, on_delete=models.CASCADE)
# thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name='messages')
#
# class Thread(TimeStampMixin):
# """
# `is_sneaky` flag will be used when the message thread is between santa and
# santee. If `is_sneaky` is set to `True` then `santa` shouldn't be null.
#
# `participant_1.id` will be always less than `participant_2.id`
# """
# is_sneaky = models.BooleanField(default=False)
#
# participant_1 = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name='participant_1_threads')
# participant_2 = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name='participant_2_threads')
# santa = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='santa_threads')
. Output only the next line. | form_class = MessageCreateForm |
Here is a snippet: <|code_start|>
@method_decorator(login_required, name='dispatch')
class MessageCreateView(CreateView):
model = Message
form_class = MessageCreateForm
success_url = '/'
def post(self, request, pk, *args, **kwargs):
if not request.is_ajax():
raise Http404('Haxxeru?')
self.thread = self._validate_and_get_thread(thread_id=pk)
if not self.thread:
raise Http404('Haxxeru?')
return super().post(request, pk, *args, **kwargs)
def form_valid(self, form):
message = form.save(commit=False)
message.sent_by = self.request.user
message.thread = self.thread
super().form_valid(form)
response = self._get_response()
base_site_url = self.request.build_absolute_uri('/')
tasks.send_email_notification(
message_id=self.object.id, base_site_url=base_site_url)
return JsonResponse(response)
def _validate_and_get_thread(self, thread_id):
user = self.request.user
<|code_end|>
. Write the next line using the current file imports:
from django.views.generic.edit import CreateView
from django.views.generic import DetailView, ListView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import reverse, get_object_or_404
from django.db.models import Q, Max
from django.http import Http404, JsonResponse
from django.contrib.auth.models import User
from django.utils.formats import date_format
from .forms import MessageCreateForm
from .models import Message, Thread
from . import inbox_service
from . import tasks
and context from other files:
# Path: della/inbox/forms.py
# class MessageCreateForm(ModelForm):
#
# class Meta:
# model = Message
# fields = ['text']
#
# Path: della/inbox/models.py
# class Message(TimeStampMixin):
# text = models.TextField()
#
# sent_by = models.ForeignKey(User, on_delete=models.CASCADE)
# thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name='messages')
#
# class Thread(TimeStampMixin):
# """
# `is_sneaky` flag will be used when the message thread is between santa and
# santee. If `is_sneaky` is set to `True` then `santa` shouldn't be null.
#
# `participant_1.id` will be always less than `participant_2.id`
# """
# is_sneaky = models.BooleanField(default=False)
#
# participant_1 = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name='participant_1_threads')
# participant_2 = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name='participant_2_threads')
# santa = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='santa_threads')
, which may include functions, classes, or code. Output only the next line. | return Thread.objects.filter( |
Given the following code snippet before the placeholder: <|code_start|>
app_name = 'gallery'
urlpatterns = [
path('upload/', ImageUploadView.as_view(), name='upload'),
<|code_end|>
, predict the next line using imports from the current file:
from django.urls import path
from .views import ImageUploadView, ImageDetailView, ImageListView
and context including class names, function names, and sometimes code from other files:
# Path: della/gallery/views.py
# class ImageUploadView(CreateView):
# model = Image
# form_class = ImageUploadForm
# template_name = 'generic_crispy_form_template.html'
#
# def form_valid(self, form):
# image = form.save(commit=False)
# image.added_by = self.request.user
# return super().form_valid(form)
#
# def get_success_url(self):
# return reverse('gallery:image-detail', args=(self.object.id,))
#
# class ImageDetailView(DetailView):
# model = Image
#
# class ImageListView(ListView):
# model = Image
#
# def get_queryset(self):
# queryset = super().get_queryset()
# return queryset.order_by('-created_on')
. Output only the next line. | path('<int:pk>/', ImageDetailView.as_view(), name='image-detail'), |
Next line prediction: <|code_start|>
app_name = 'gallery'
urlpatterns = [
path('upload/', ImageUploadView.as_view(), name='upload'),
path('<int:pk>/', ImageDetailView.as_view(), name='image-detail'),
<|code_end|>
. Use current file imports:
(from django.urls import path
from .views import ImageUploadView, ImageDetailView, ImageListView)
and context including class names, function names, or small code snippets from other files:
# Path: della/gallery/views.py
# class ImageUploadView(CreateView):
# model = Image
# form_class = ImageUploadForm
# template_name = 'generic_crispy_form_template.html'
#
# def form_valid(self, form):
# image = form.save(commit=False)
# image.added_by = self.request.user
# return super().form_valid(form)
#
# def get_success_url(self):
# return reverse('gallery:image-detail', args=(self.object.id,))
#
# class ImageDetailView(DetailView):
# model = Image
#
# class ImageListView(ListView):
# model = Image
#
# def get_queryset(self):
# queryset = super().get_queryset()
# return queryset.order_by('-created_on')
. Output only the next line. | path('', ImageListView.as_view(), name='image-list') |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-12-12 18:17:20
# @Author : yml_bright@163.com
class JWCHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write("hello")
def on_finish(self):
self.db.close()
def post(self):
retjson = {'code':200, 'content':''}
try:
<|code_end|>
, generate the next line using the imports in this file:
from .._config import jwcCacheTime
from BeautifulSoup import BeautifulSoup
from config import JWC_URL, TIME_OUT
from tornado.httpclient import HTTPRequest, HTTPClient
from ..models.jwc_cache import JWCCache
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime
import tornado.web
import tornado.gen
import json, base64
import urllib,traceback,os
and context (functions, classes, or occasionally code) from other files:
# Path: mod/_config.py
#
# Path: mod/models/jwc_cache.py
# class JWCCache(Base):
# __tablename__ = 'jwc'
# date = Column(Integer, primary_key=True)
# text = Column(String(10240), nullable=False)
. Output only the next line. | status = self.db.query(JWCCache).filter( JWCCache.date > int(time())-jwcCacheTime).order_by(JWCCache.date.desc()).all() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-12-12 18:17:20
# @Author : yml_bright@163.com
class JWCHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write("hello")
def on_finish(self):
self.db.close()
def post(self):
retjson = {'code':200, 'content':''}
try:
<|code_end|>
, predict the next line using imports from the current file:
from .._config import jwcCacheTime
from BeautifulSoup import BeautifulSoup
from config import JWC_URL, TIME_OUT
from tornado.httpclient import HTTPRequest, HTTPClient
from ..models.jwc_cache import JWCCache
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime
import tornado.web
import tornado.gen
import json, base64
import urllib,traceback,os
and context including class names, function names, and sometimes code from other files:
# Path: mod/_config.py
#
# Path: mod/models/jwc_cache.py
# class JWCCache(Base):
# __tablename__ = 'jwc'
# date = Column(Integer, primary_key=True)
# text = Column(String(10240), nullable=False)
. Output only the next line. | status = self.db.query(JWCCache).filter( JWCCache.date > int(time())-jwcCacheTime).order_by(JWCCache.date.desc()).all() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2016-03-14 17:34:57
# @Author : jerry.liangj@qq.com
class HotHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
HOT_URL = "http://www.libopac.seu.edu.cn:8080/top/top_lend.php"
retjson = {
'code':200,
'content':''
}
try:
<|code_end|>
. Write the next line using the current file imports:
from config import TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.library import LibraryHotCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import datetime
import tornado.gen
import urllib
import json, re,base64
and context from other files:
# Path: mod/models/library.py
# class LibraryHotCache(Base):
# __tablename__ = 'library_hot'
# id = Column(Integer,primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
, which may include functions, classes, or code. Output only the next line. | status = self.db.query(LibraryHotCache).one() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-10-26 12:46:36
# @Author : yml_bright@163.com
class LectureHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
status = self.db.query(LectureCache).filter( LectureCache.cardnum == cardnum ).one()
<|code_end|>
with the help of current file imports:
from .._config import lectureCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.lecture_cache import LectureCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64
import urllib, re
import traceback
and context from other files:
# Path: mod/_config.py
#
# Path: mod/models/lecture_cache.py
# class LectureCache(Base):
# __tablename__ = 'lecture'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096))
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
, which may contain function names, class names, or code. Output only the next line. | if status.date > int(time()) - lectureCacheTime and status.text != '*': |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-10-26 12:46:36
# @Author : yml_bright@163.com
class LectureHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
<|code_end|>
, predict the immediate next line with the help of imports:
from .._config import lectureCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.lecture_cache import LectureCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64
import urllib, re
import traceback
and context (classes, functions, sometimes code) from other files:
# Path: mod/_config.py
#
# Path: mod/models/lecture_cache.py
# class LectureCache(Base):
# __tablename__ = 'lecture'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096))
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | status = self.db.query(LectureCache).filter( LectureCache.cardnum == cardnum ).one() |
Next line prediction: <|code_start|> def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
status = self.db.query(LectureCache).filter( LectureCache.cardnum == cardnum ).one()
if status.date > int(time()) - lectureCacheTime and status.text != '*':
self.write(base64.b64decode(status.text))
self.db.close()
self.finish()
return
except NoResultFound:
status = LectureCache(cardnum=cardnum, text='*', date=int(time()))
self.db.add(status)
try:
self.db.commit()
except:
self.db.rollback()
try:
<|code_end|>
. Use current file imports:
(from .._config import lectureCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.lecture_cache import LectureCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64
import urllib, re
import traceback)
and context including class names, function names, or small code snippets from other files:
# Path: mod/_config.py
#
# Path: mod/models/lecture_cache.py
# class LectureCache(Base):
# __tablename__ = 'lecture'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096))
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | response = authApi(cardnum,self.get_argument('password')) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-10-26 12:46:36
# @Author : yml_bright@163.com
class PhylabHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
number = self.get_argument('number',default=None)
password = self.get_argument('password',default=None)
term = self.get_argument('term',default=None)
retjson = {'code':200, 'content':''}
if not number or not password or not term:
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
# read from cache
try:
status = self.db.query(PhylabCache).filter( PhylabCache.cardnum == number ).one()
<|code_end|>
, predict the immediate next line with the help of imports:
from .._config import phylabCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.phylab_cache import PhylabCache
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime
import tornado.web
import tornado.gen
import urllib
import json, base64
import datetime
import traceback
and context (classes, functions, sometimes code) from other files:
# Path: mod/_config.py
#
# Path: mod/models/phylab_cache.py
# class PhylabCache(Base):
# __tablename__ = 'phylab'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
. Output only the next line. | if status.date > int(time())-phylabCacheTime and status.text != '*':
|
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-10-26 12:46:36
# @Author : yml_bright@163.com
class PhylabHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
number = self.get_argument('number',default=None)
password = self.get_argument('password',default=None)
term = self.get_argument('term',default=None)
retjson = {'code':200, 'content':''}
if not number or not password or not term:
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
# read from cache
try:
<|code_end|>
, determine the next line of code. You have imports:
from .._config import phylabCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.phylab_cache import PhylabCache
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime
import tornado.web
import tornado.gen
import urllib
import json, base64
import datetime
import traceback
and context (class names, function names, or code) available:
# Path: mod/_config.py
#
# Path: mod/models/phylab_cache.py
# class PhylabCache(Base):
# __tablename__ = 'phylab'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(PhylabCache).filter( PhylabCache.cardnum == number ).one()
|
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-11-04 13:38:58
# @Author : yml_bright@163.com
class NICHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
data = {
'username':cardnum,
'password':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
<|code_end|>
, predict the next line using imports from the current file:
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient, HTTPClient
from bs4 import BeautifulSoup
from ..models.nic_cache import NicCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import tornado.gen
import urllib, re
import json, base64
and context including class names, function names, and sometimes code from other files:
# Path: mod/models/nic_cache.py
# class NicCache(Base):
# __tablename__ = 'nic'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(1024))
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(NicCache).filter( NicCache.cardnum == cardnum ).one() |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2016-03-24 16 16:34:57
# @Author : jerry.liangj@qq.com
def getCookie(db,cardnum,card_pwd):
state = 1
ret = {'code':200,'content':''}
try:
<|code_end|>
. Use current file imports:
import time,json
import urllib
from tornado.httpclient import HTTPRequest, HTTPClient,HTTPError
from ..models.cookie_cache import CookieCache
from sqlalchemy.orm.exc import NoResultFound
from config import *
from newHandler import newAuthApi
from handler import authApi
and context (classes, functions, or code) from other files:
# Path: mod/models/cookie_cache.py
# class CookieCache(Base):
# __tablename__ = 'cookie'
# cardnum = Column(Integer, primary_key=True)
# cookie = Column(String(256), nullable=False)
# date = Column(Integer, nullable=False)
. Output only the next line. | result = db.query(CookieCache).filter(CookieCache.cardnum==cardnum).one() |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class LibAuthCheckHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('herald web service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
retjson = {'code': 200, 'content': ''}
if not cardnum:
retjson['code'] = 400
retjson['content'] = u'parameters lack'
else:
try:
<|code_end|>
. Use current file imports:
(from config import *
from tornado.httpclient import HTTPClient
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from bs4 import BeautifulSoup
from ..models.library_auth_cache import LibraryAuthCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import re
import json
import urllib
import base64
import tornado.web, tornado.gen)
and context including class names, function names, or small code snippets from other files:
# Path: mod/models/library_auth_cache.py
# class LibraryAuthCache(Base):
# __tablename__ = 'library_auth'
# cardnum = Column(Integer, primary_key=True)
# cookie = Column(String(4096))
# captcha = Column(String(4096))
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(LibraryAuthCache).filter(LibraryAuthCache.cardnum == cardnum).one() |
Given the following code snippet before the placeholder: <|code_start|># @Date : 2014-06-27 14:36:45
# @Author : xindervella@gamil.com yml_bright@163.com
class SRTPHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
number = self.get_argument('number', default=None)
retjson = {'code':200, 'content':''}
status = None
if not number:
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
#read from cache
try:
status = self.db.query(SRTPCache).filter(SRTPCache.cardnum == number).one()
<|code_end|>
, predict the next line using imports from the current file:
from .._config import srtpCacheTime
from sqlalchemy.orm.exc import NoResultFound
from config import SRTP_URL, TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from time import time
from ..models.srtp_cache import SRTPCache
import base64
import tornado.web
import tornado.gen
import urllib
import json
import re
and context including class names, function names, and sometimes code from other files:
# Path: mod/_config.py
#
# Path: mod/models/srtp_cache.py
# class SRTPCache(Base):
# __tablename__ = 'srtp_cache'
# cardnum = Column(String(16), primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
. Output only the next line. | if status.date > int(time())-srtpCacheTime and status.text != '*': |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2014-06-27 14:36:45
# @Author : xindervella@gamil.com yml_bright@163.com
class SRTPHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
number = self.get_argument('number', default=None)
retjson = {'code':200, 'content':''}
status = None
if not number:
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
#read from cache
try:
<|code_end|>
using the current file's imports:
from .._config import srtpCacheTime
from sqlalchemy.orm.exc import NoResultFound
from config import SRTP_URL, TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from time import time
from ..models.srtp_cache import SRTPCache
import base64
import tornado.web
import tornado.gen
import urllib
import json
import re
and any relevant context from other files:
# Path: mod/_config.py
#
# Path: mod/models/srtp_cache.py
# class SRTPCache(Base):
# __tablename__ = 'srtp_cache'
# cardnum = Column(String(16), primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(SRTPCache).filter(SRTPCache.cardnum == number).one() |
Next line prediction: <|code_start|># @Date : 2014-10-26 12:46:36
# @Author : yml_bright@163.com
class NewCARDHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
timedelta = int(self.get_argument('timedelta', default=0))
# if int(timedelta)>7:
# timedelta = 7
cardnum = self.get_argument('cardnum')
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
<|code_end|>
. Use current file imports:
(from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import requests)
and context including class names, function names, or small code snippets from other files:
# Path: mod/models/card_cache.py
# class CardCache(Base):
# __tablename__ = 'card'
# cardnum = Column(BIGINT, primary_key=True)
# text = Column(LONGTEXT)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | status = self.db.query(CardCache).filter( CardCache.cardnum == cardnum ).one() |
Given snippet: <|code_start|> @tornado.web.asynchronous
@tornado.gen.engine
def post(self):
timedelta = int(self.get_argument('timedelta', default=0))
# if int(timedelta)>7:
# timedelta = 7
cardnum = self.get_argument('cardnum')
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
status = self.db.query(CardCache).filter( CardCache.cardnum == cardnum ).one()
if int(timedelta) == 0 and status.date > int(time())-600:
self.write(base64.b64decode(status.text))
self.db.close()
self.finish()
return
except NoResultFound:
status = CardCache(cardnum=cardnum, text='*', date=int(time()))
self.db.add(status)
try:
self.db.commit()
except:
self.db.rollback()
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import requests
and context:
# Path: mod/models/card_cache.py
# class CardCache(Base):
# __tablename__ = 'card'
# cardnum = Column(BIGINT, primary_key=True)
# text = Column(LONGTEXT)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
which might include code, classes, or functions. Output only the next line. | response = authApi(cardnum,self.get_argument('password')) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-03-17 12:06:02
# @Author : yml_bright@163.com
class LectureNoticeHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
def post(self):
retjson = {'code':500, 'content':u'暂无'}
date = mktime(strptime(strftime('%Y-%m-%d' ,localtime(time())), '%Y-%m-%d'))
# read from db
try:
<|code_end|>
, determine the next line of code. You have imports:
from config import *
from ..models.lecturedb import LectureDB
from sqlalchemy.orm.exc import NoResultFound
from time import time, strftime, mktime, localtime, strptime
import tornado.web
import tornado.gen
import json, base64
and context (class names, function names, or code) available:
# Path: mod/models/lecturedb.py
# class LectureDB(Base):
# __tablename__ = 'db_lecture'
# lid = Column(Integer, primary_key=True)
# date = Column(Integer, index=True)
# speaker = Column(String(128))
# time = Column(String(128))
# location = Column(String(256))
# topic = Column(String(256))
# detail = Column(String(256))
. Output only the next line. | status = self.db.query(LectureDB).filter( LectureDB.date >= date ).all() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2016-03-24 16 16:34:57
# @Author : jerry.liangj@qq.com
class YuyueHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
password = self.get_argument('password')
method_type = self.get_argument('method')
retjson = {'code':200, 'content':''}
try:
if method_type not in method.keys():
retjson['code'] = 500
retjson['content'] = 'method is not allowed'
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPClient
from tornado.httputil import url_concat
from sqlalchemy.orm.exc import NoResultFound
from tornado.web import MissingArgumentError
from ..models.cookie_cache import CookieCache
from ..auth.cookie import getCookie
import tornado.web
import tornado.gen
import urllib, json
import traceback
and context (classes, functions, sometimes code) from other files:
# Path: mod/models/cookie_cache.py
# class CookieCache(Base):
# __tablename__ = 'cookie'
# cardnum = Column(Integer, primary_key=True)
# cookie = Column(String(256), nullable=False)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/cookie.py
# def getCookie(db,cardnum,card_pwd):
# state = 1
# ret = {'code':200,'content':''}
# try:
# result = db.query(CookieCache).filter(CookieCache.cardnum==cardnum).one()
# if (result.date+COOKIE_TIMEOUT<int(time.time())):
# state = 0
# else:
# ret['content'] = result.cookie
# except NoResultFound:
# result = CookieCache(cardnum=cardnum,cookie="",date=int(time.time()))
# state = 0
# except Exception,e:
# ret['code'] = 500
# ret['content'] = str(e)
# if state==0:
# res = authApi(cardnum,card_pwd)
# if res['code']==200:
# cookie = res['content']
# ret['content'] = cookie
# result.cookie = cookie
# try:
# db.add(res)
# db.commit()
# except:
# db.rollback()
# else:
# ret['code'] = 500
# return ret
. Output only the next line. | cookie = getCookie(self.db,cardnum,password) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2015-03-19 16 16:34:57
# @Author : yml_bright@163.com
class UserHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
_number = self.get_argument('number')
retjson = {'code':500, 'content':''}
try:
now = int(time.time())
user = self.db.query(UserDetail).filter(_number == UserDetail.cardnum).one()
<|code_end|>
, predict the next line using imports from the current file:
from .._config import userCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPClient
from ..models.user_detail import UserDetail
from bs4 import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..auth.handler import authApi
from sqlalchemy import func, or_, not_
import tornado.web
import tornado.gen
import urllib, json
import time
and context including class names, function names, and sometimes code from other files:
# Path: mod/_config.py
#
# Path: mod/models/user_detail.py
# class UserDetail(Base):
# __tablename__ = 'user_detail'
# cardnum = Column(String(10), primary_key=True)
# schoolnum = Column(String(10), nullable=True)
# name = Column(String(50), nullable=False)
# sex = Column(String(10), nullable=True)
# nation = Column(String(50), nullable=True)
# room = Column(String(50), nullable=True)
# bed = Column(String(50), nullable=True)
# last_update = Column(BIGINT, nullable=True)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | if ((user.last_update != None) and (now - user.last_update) < userCacheTime): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2015-03-19 16 16:34:57
# @Author : yml_bright@163.com
class UserHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
_number = self.get_argument('number')
retjson = {'code':500, 'content':''}
try:
now = int(time.time())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .._config import userCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPClient
from ..models.user_detail import UserDetail
from bs4 import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..auth.handler import authApi
from sqlalchemy import func, or_, not_
import tornado.web
import tornado.gen
import urllib, json
import time
and context:
# Path: mod/_config.py
#
# Path: mod/models/user_detail.py
# class UserDetail(Base):
# __tablename__ = 'user_detail'
# cardnum = Column(String(10), primary_key=True)
# schoolnum = Column(String(10), nullable=True)
# name = Column(String(50), nullable=False)
# sex = Column(String(10), nullable=True)
# nation = Column(String(50), nullable=True)
# room = Column(String(50), nullable=True)
# bed = Column(String(50), nullable=True)
# last_update = Column(BIGINT, nullable=True)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
which might include code, classes, or functions. Output only the next line. | user = self.db.query(UserDetail).filter(_number == UserDetail.cardnum).one() |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-08-24 12:46:36
# @Author : LiangJ
class RoomHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
def on_finish(self):
self.db.close()
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
number = self.get_argument('number',default=None)
retjson = {'code':200, 'content':''}
data = {
'Login.Token1':number,
'Login.Token2':self.get_argument('password'),
}
# read from cache
try:
<|code_end|>
, determine the next line of code. You have imports:
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from sqlalchemy.orm.exc import NoResultFound
from ..models.user_detail import UserDetail
from ..models.room_cache import RoomCache
from time import time
from bs4 import BeautifulSoup
from time import time, localtime, strftime
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64
import urllib
import datetime
and context (class names, function names, or code) available:
# Path: mod/models/user_detail.py
# class UserDetail(Base):
# __tablename__ = 'user_detail'
# cardnum = Column(String(10), primary_key=True)
# schoolnum = Column(String(10), nullable=True)
# name = Column(String(50), nullable=False)
# sex = Column(String(10), nullable=True)
# nation = Column(String(50), nullable=True)
# room = Column(String(50), nullable=True)
# bed = Column(String(50), nullable=True)
# last_update = Column(BIGINT, nullable=True)
#
# Path: mod/models/room_cache.py
# class RoomCache(Base):
# __tablename__ = 'room'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | status = self.db.query(RoomCache).filter(RoomCache.cardnum == number).one() |
Next line prediction: <|code_start|> self.db.close()
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
number = self.get_argument('number',default=None)
retjson = {'code':200, 'content':''}
data = {
'Login.Token1':number,
'Login.Token2':self.get_argument('password'),
}
# read from cache
try:
status = self.db.query(RoomCache).filter(RoomCache.cardnum == number).one()
#if status.date > int(time())-600 and status.text != '*':
if status.text != '*':
self.write(base64.b64decode(status.text))
self.finish()
return
except NoResultFound:
status = RoomCache(cardnum = number,text = '*',date = int(time()))
self.db.add(status)
try:
self.db.commit()
except:
self.db.rollback()
try:
client = AsyncHTTPClient()
<|code_end|>
. Use current file imports:
(from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from sqlalchemy.orm.exc import NoResultFound
from ..models.user_detail import UserDetail
from ..models.room_cache import RoomCache
from time import time
from bs4 import BeautifulSoup
from time import time, localtime, strftime
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64
import urllib
import datetime)
and context including class names, function names, or small code snippets from other files:
# Path: mod/models/user_detail.py
# class UserDetail(Base):
# __tablename__ = 'user_detail'
# cardnum = Column(String(10), primary_key=True)
# schoolnum = Column(String(10), nullable=True)
# name = Column(String(50), nullable=False)
# sex = Column(String(10), nullable=True)
# nation = Column(String(50), nullable=True)
# room = Column(String(50), nullable=True)
# bed = Column(String(50), nullable=True)
# last_update = Column(BIGINT, nullable=True)
#
# Path: mod/models/room_cache.py
# class RoomCache(Base):
# __tablename__ = 'room'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | response = authApi(number,self.get_argument("password")) |
Here is a snippet: <|code_start|> @property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
def on_finish(self):
self.db.close()
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
state = 'success'
cardnum = self.get_argument('cardnum', default=None)
pwd = self.get_argument('pwd', default=cardnum)
retjson = {'code':200, 'content':''}
# pwd 缺省为 cardnum
if not cardnum:
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
result = yield self.get_pe_count(cardnum)
if result == -1:
state = 'time_out'
try:
# 超时取出缓存
<|code_end|>
. Write the next line using the current file imports:
from .._config import *
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from tornado.tcpclient import TCPClient
from tornado.ioloop import IOLoop
from BeautifulSoup import BeautifulSoup
from ..models.pe_models import PEUser
from ..models.tice_cache import TiceCache
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime,mktime,strptime
from datetime import datetime, timedelta, date
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
import tornado.web
import tornado.gen
import urllib
import random
import json,socket,base64,traceback
import functools
and context from other files:
# Path: mod/models/pe_models.py
# class PEUser(Base):
# __tablename__ = 'pe'
# cardnum = Column(Integer, primary_key=True)
# count = Column(String(10), nullable=False)
#
# def __repr__(self):
# return '<PE (%s, %d)' % (self.cardnum, self.count)
#
# Path: mod/models/tice_cache.py
# class TiceCache(Base):
# __tablename__ = 'tice'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
, which may include functions, classes, or code. Output only the next line. | user = self.db.query(PEUser).filter( |
Here is a snippet: <|code_start|> front_day = 6-current_date
front_day = front_day if front_day>0 else 0
back_remain = 5
all_week = (alldays-5-front_remain)/7
workday_count = (all_week+1)*5+front_day
if current_date<=6:
workday_count = workday_count-1
return workday_count if workday_count > 0 else 0
"""
#体测信息
class ticeInfoHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum',default=None)
retjson = {'code':200,'content':''}
state = 'fail'
if not cardnum:
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
#read from cache
try:
<|code_end|>
. Write the next line using the current file imports:
from .._config import *
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from tornado.tcpclient import TCPClient
from tornado.ioloop import IOLoop
from BeautifulSoup import BeautifulSoup
from ..models.pe_models import PEUser
from ..models.tice_cache import TiceCache
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime,mktime,strptime
from datetime import datetime, timedelta, date
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
import tornado.web
import tornado.gen
import urllib
import random
import json,socket,base64,traceback
import functools
and context from other files:
# Path: mod/models/pe_models.py
# class PEUser(Base):
# __tablename__ = 'pe'
# cardnum = Column(Integer, primary_key=True)
# count = Column(String(10), nullable=False)
#
# def __repr__(self):
# return '<PE (%s, %d)' % (self.cardnum, self.count)
#
# Path: mod/models/tice_cache.py
# class TiceCache(Base):
# __tablename__ = 'tice'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
, which may include functions, classes, or code. Output only the next line. | status = self.db.query(TiceCache).filter(TiceCache.cardnum == cardnum).one() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
# modified from old renewhandler.py
# by yml_bright@163.com
class LibRenewHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write("herald webservice")
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum')
# captcha = self.get_argument('captcha')
barcode = self.get_argument('barcode')
retjson = {'code': 200, 'content': u''}
if (not cardnum or not barcode):
retjson['code'] = 400
retjson['content'] = u'parameter lack'
else:
try:
<|code_end|>
, predict the immediate next line with the help of imports:
from config import *
from tornado.httpclient import HTTPClient
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from bs4 import BeautifulSoup
from ..models.library_auth_cache import LibraryAuthCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import re
import json
import urllib
import base64
import tornado.web, tornado.gen
and context (classes, functions, sometimes code) from other files:
# Path: mod/models/library_auth_cache.py
# class LibraryAuthCache(Base):
# __tablename__ = 'library_auth'
# cardnum = Column(Integer, primary_key=True)
# cookie = Column(String(4096))
# captcha = Column(String(4096))
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(LibraryAuthCache).filter(LibraryAuthCache.cardnum == cardnum).one() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-12-15 18:07:58
# @Author : yml_bright@163.com
class SchoolBusHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.init_db()
#self.write('Herald Web Service')
def post(self):
try:
<|code_end|>
using the current file's imports:
import tornado.web
import json, base64
from ..models.data_cache import DataCache
from sqlalchemy.orm.exc import NoResultFound
and any relevant context from other files:
# Path: mod/models/data_cache.py
# class DataCache(Base):
# __tablename__ = 'data'
# key = Column(Integer, primary_key=True)
# data = Column(String(10240), nullable=False)
. Output only the next line. | data = self.db.query(DataCache).filter( DataCache.key == 10001 ).one() |
Based on the snippet: <|code_start|>
def end_td(self):
self.flag -= 1
def handle_data(self, text):
if self.flag == 3 and self.form == 1:
self.row.append(text)
class pedetailHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
retjson = {'code':200,'content':''}
cardnum = self.get_argument('cardnum',default=None)
password = self.get_argument('password',default=None)
if not (cardnum and password):
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
# read from cache
try:
<|code_end|>
, predict the immediate next line with the help of imports:
from tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPError
from sgmllib import SGMLParser
from config import loginurl1,runurl
from sqlalchemy.orm.exc import NoResultFound
from ..models.pe_models import PeDetailCache
from time import time,localtime, strftime
import json
import tornado.web
import tornado.gen
import urllib
import base64
and context (classes, functions, sometimes code) from other files:
# Path: mod/models/pe_models.py
# class PeDetailCache(Base):
# __tablename__ = 'pedetail'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(10240))
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(PeDetailCache).filter(PeDetailCache.cardnum == cardnum).one() |
Given the code snippet: <|code_start|>
class CARDHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
timedelta = int(self.get_argument('timedelta', default=0))
# if int(timedelta)>7:
# timedelta = 7
cardnum = self.get_argument('cardnum')
cardnum_with_delta = cardnum + str(timedelta)
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
status = self.db.query(CardCache).filter( CardCache.cardnum == cardnum_with_delta ).one()
<|code_end|>
, generate the next line using the imports in this file:
from .._config import cardCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import IPython
and context (functions, classes, or occasionally code) from other files:
# Path: mod/_config.py
#
# Path: mod/models/card_cache.py
# class CardCache(Base):
# __tablename__ = 'card'
# cardnum = Column(BIGINT, primary_key=True)
# text = Column(LONGTEXT)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | if status.date > int(time())-cardCacheTime and status.text != '*': |
Next line prediction: <|code_start|># @Author : yml_bright@163.com
class CARDHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
timedelta = int(self.get_argument('timedelta', default=0))
# if int(timedelta)>7:
# timedelta = 7
cardnum = self.get_argument('cardnum')
cardnum_with_delta = cardnum + str(timedelta)
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
<|code_end|>
. Use current file imports:
(from .._config import cardCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import IPython)
and context including class names, function names, or small code snippets from other files:
# Path: mod/_config.py
#
# Path: mod/models/card_cache.py
# class CardCache(Base):
# __tablename__ = 'card'
# cardnum = Column(BIGINT, primary_key=True)
# text = Column(LONGTEXT)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | status = self.db.query(CardCache).filter( CardCache.cardnum == cardnum_with_delta ).one() |
Given snippet: <|code_start|> def post(self):
timedelta = int(self.get_argument('timedelta', default=0))
# if int(timedelta)>7:
# timedelta = 7
cardnum = self.get_argument('cardnum')
cardnum_with_delta = cardnum + str(timedelta)
data = {
'Login.Token1':cardnum,
'Login.Token2':self.get_argument('password'),
}
retjson = {'code':200, 'content':''}
# read from cache
try:
status = self.db.query(CardCache).filter( CardCache.cardnum == cardnum_with_delta ).one()
if status.date > int(time())-cardCacheTime and status.text != '*':
self.write(base64.b64decode(status.text))
self.db.close()
self.finish()
return
except NoResultFound:
status = CardCache(cardnum=cardnum_with_delta, text='*', date=int(time()))
self.db.add(status)
try:
self.db.commit()
except:
self.db.rollback()
try:
client = AsyncHTTPClient()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .._config import cardCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import IPython
and context:
# Path: mod/_config.py
#
# Path: mod/models/card_cache.py
# class CardCache(Base):
# __tablename__ = 'card'
# cardnum = Column(BIGINT, primary_key=True)
# text = Column(LONGTEXT)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
which might include code, classes, or functions. Output only the next line. | response = authApi(cardnum,self.get_argument('password')) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class LibListHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('herald webservice')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum', default=None)
password = self.get_argument('password', default=None)
retjson = {'code': 200, 'content': ''}
status = None
if not (cardnum and password):
retjson['code'] = 400
retjson['content'] = 'parameters lack'
else:
# 直接从数据库读取cookie,不做try的尝试
<|code_end|>
, predict the next line using imports from the current file:
from config import *
from tornado.httpclient import HTTPClient
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from bs4 import BeautifulSoup
from ..models.library_auth_cache import LibraryAuthCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import re
import json
import urllib
import base64
import tornado.web, tornado.gen
and context including class names, function names, and sometimes code from other files:
# Path: mod/models/library_auth_cache.py
# class LibraryAuthCache(Base):
# __tablename__ = 'library_auth'
# cardnum = Column(Integer, primary_key=True)
# cookie = Column(String(4096))
# captcha = Column(String(4096))
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(LibraryAuthCache).filter(LibraryAuthCache.cardnum == cardnum).one() |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-3 12:46:36
# @Author : jerry.liangj@qq.com
class ExamHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.gen.engine
def post(self):
number = self.get_argument('cardnum',default=None)
password = self.get_argument('password')
retjson = {'code':200, 'content':''}
# read from cache
try:
status = self.db.query(ExamCache).filter(ExamCache.cardnum == number).one()
<|code_end|>
, determine the next line of code. You have imports:
from .._config import examCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..models.exam_cache import ExamCache
from time import time,localtime, strftime
from PIL import Image
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64,traceback,urllib
import io
and context (class names, function names, or code) available:
# Path: mod/_config.py
#
# Path: mod/models/exam_cache.py
# class ExamCache(Base):
# __tablename__ = 'exam'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | if status.date > int(time())-examCacheTime and status.text != '*': |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-3 12:46:36
# @Author : jerry.liangj@qq.com
class ExamHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.gen.engine
def post(self):
number = self.get_argument('cardnum',default=None)
password = self.get_argument('password')
retjson = {'code':200, 'content':''}
# read from cache
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .._config import examCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..models.exam_cache import ExamCache
from time import time,localtime, strftime
from PIL import Image
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64,traceback,urllib
import io
and context:
# Path: mod/_config.py
#
# Path: mod/models/exam_cache.py
# class ExamCache(Base):
# __tablename__ = 'exam'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
which might include code, classes, or functions. Output only the next line. | status = self.db.query(ExamCache).filter(ExamCache.cardnum == number).one() |
Next line prediction: <|code_start|> self.finish()
return
except NoResultFound:
status = ExamCache(cardnum = number,text = '*',date = int(time()))
self.db.add(status)
try:
self.db.commit()
except:
self.db.rollback()
retjson = yield tornado.gen.Task(self.jwcHandler,number,password)
ret = json.dumps(retjson, ensure_ascii=False, indent=2)
self.write(ret)
self.finish()
# refresh cache
if retjson['code'] == 200:
status.date = int(time())
status.text = base64.b64encode(ret)
self.db.add(status)
try:
self.db.commit()
except Exception,e:
self.db.rollback()
finally:
self.db.remove()
@tornado.web.asynchronous
@tornado.gen.engine
def newSeuHandler(self,number,password,callback=None):
retjson = {'code':200, 'content':''}
try:
client = AsyncHTTPClient()
<|code_end|>
. Use current file imports:
(from .._config import examCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..models.exam_cache import ExamCache
from time import time,localtime, strftime
from PIL import Image
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64,traceback,urllib
import io)
and context including class names, function names, or small code snippets from other files:
# Path: mod/_config.py
#
# Path: mod/models/exam_cache.py
# class ExamCache(Base):
# __tablename__ = 'exam'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096), nullable=False)
# date = Column(Integer, nullable=False)
#
# Path: mod/auth/handler.py
# def authApi(username,password):
# data = {
# 'username':username,
# 'password':password
# }
# result = {'code':200,'content':''}
# try:
# client = HTTPClient()
# request = HTTPRequest(
# CHECK_URL,
# method='POST',
# body=urllib.urlencode(data),
# validate_cert=False,
# request_timeout=TIME_OUT)
# response = client.fetch(request)
# header = response.headers
# if 'Ssocookie' in header.keys():
# headertemp = json.loads(header['Ssocookie'])
# cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
# cookie += ";"+header['Set-Cookie'].split(";")[0]
# result['content'] = cookie
# else:
# result['code'] = 400
# except HTTPError as e:
# if e.code == 401:
# result['code'] = 401
# else:
# result['code'] = 500
# except Exception,e:
# result['code'] = 500
# return result
. Output only the next line. | response = authApi(number,password) |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-10-26 14:46:50
# @Author : jerry.liangj@qq.com
class PCHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def get(self):
self.write('Herald Web Service')
def post(self):
retjson = {'code':200, 'content':u'暂时关闭'}
try:
if self.ismorning():
<|code_end|>
. Use current file imports:
(from config import *
from tornado.httpclient import HTTPRequest, HTTPClient,HTTPError
from bs4 import BeautifulSoup
from ..models.pc_cache import PCCache
from sqlalchemy.orm.exc import NoResultFound
from time import time, localtime, strftime
import tornado.web
import tornado.gen
import datetime
import urllib, re
import json
import base64
import rsa,tea,traceback
import os, hashlib, re, tempfile, binascii, base64)
and context including class names, function names, or small code snippets from other files:
# Path: mod/models/pc_cache.py
# class PCCache(Base):
# __tablename__ = 'pc'
# date = Column(Integer, primary_key=True)
# text = Column(String(255), nullable=False)
# lastdate = Column(Integer)
. Output only the next line. | status = self.db.query(PCCache).filter( PCCache.date == self.today(),PCCache.lastdate+180>int(time())).one() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class LibAuthHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
cardnum = self.get_argument('cardnum', default=None)
if not cardnum:
# 因为需要返回图片,所以一卡通为空不做提示
raise Exception
try:
client = HTTPClient()
response = client.fetch(GET_CAPTCHA)
cookie = response.headers['Set-Cookie'].split(';')[0]
try:
<|code_end|>
, generate the next line using the imports in this file:
from config import *
from tornado.httpclient import HTTPClient
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from bs4 import BeautifulSoup
from ..models.library_auth_cache import LibraryAuthCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import re
import json
import urllib
import base64
import tornado.web, tornado.gen
and context (functions, classes, or occasionally code) from other files:
# Path: mod/models/library_auth_cache.py
# class LibraryAuthCache(Base):
# __tablename__ = 'library_auth'
# cardnum = Column(Integer, primary_key=True)
# cookie = Column(String(4096))
# captcha = Column(String(4096))
# date = Column(Integer, nullable=False)
. Output only the next line. | status = self.db.query(LibraryAuthCache).filter(LibraryAuthCache.cardnum == cardnum).one() |
Here is a snippet: <|code_start|> method='POST',
request_timeout=TIME_OUT)
response = yield tornado.gen.Task(client.fetch, request)
body = response.body
if not body:
retjson['code'] = 408
retjson['content'] = 'time out'
else:
pat = re.compile(ur'没有找到该学生信息', re.U)
match = pat.search(body)
if match:
retjson['code'] = 401
retjson['content'] = 'card number not exist'
else:
retjson['content'] = self.parser(body)
retjson['sidebar'] = self.sidebarparser(body)
#url = "http://58.192.114.179/classroom/common/gettermlistex"
#client = AsyncHTTPClient()
#request = HTTPRequest(
# url = url,
# method = "GET",
# request_timeout=3
#)
#response = yield tornado.gen.Task(client.fetch, request)
#content = json.loads(response.body)
#termTemp = term.split('-')
#term = "20"+termTemp[0]+"-"+"20"+termTemp[1]+"-"+termTemp[2]
retjson['content']['startdate']={
<|code_end|>
. Write the next line using the current file imports:
from .._config import start_date
from .._config import term as default_term
from BeautifulSoup import BeautifulSoup
from config import CURR_URL, TIME_OUT,TERM_URL,JWC_URL
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from collections import OrderedDict
from ..models.curriculum_cookie import Curriculum_CookieCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import tornado.gen
import urllib
import json
import re,sys,traceback
and context from other files:
# Path: mod/_config.py
#
# Path: mod/_config.py
#
# Path: mod/models/curriculum_cookie.py
# class Curriculum_CookieCache(Base):
# __tablename__ = 'curriculum_cookie'
# cid = Column(Integer, primary_key=True)
# cookie = Column(String(10240), nullable=False)
# date = Column(Integer, nullable=False)
# last = Column(Integer, nullable=False)
# time = Column(Integer, nullable=False)
, which may include functions, classes, or code. Output only the next line. | 'month': start_date.month - 1, |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# @Date : 2014-06-26 13:57:44
#Author : xindervella@gamil.com yml_bright@163.com
class CurriculumHandler(tornado.web.RequestHandler):
def get(self):
self.write('Herald Web Service')
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
cardnum = self.get_argument('cardnum', default=None)
<|code_end|>
. Use current file imports:
from .._config import start_date
from .._config import term as default_term
from BeautifulSoup import BeautifulSoup
from config import CURR_URL, TIME_OUT,TERM_URL,JWC_URL
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from collections import OrderedDict
from ..models.curriculum_cookie import Curriculum_CookieCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import tornado.gen
import urllib
import json
import re,sys,traceback
and context (classes, functions, or code) from other files:
# Path: mod/_config.py
#
# Path: mod/_config.py
#
# Path: mod/models/curriculum_cookie.py
# class Curriculum_CookieCache(Base):
# __tablename__ = 'curriculum_cookie'
# cid = Column(Integer, primary_key=True)
# cookie = Column(String(10240), nullable=False)
# date = Column(Integer, nullable=False)
# last = Column(Integer, nullable=False)
# time = Column(Integer, nullable=False)
. Output only the next line. | term = self.get_argument('term', default=default_term) |
Next line prediction: <|code_start|># @Author : xindervella@gamil.com yml_bright@163.com
# import Image
class GPAHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
username = self.get_argument('username', default=None)
pwd = self.get_argument('password', default=None)
status = None
retjson = {'code':200, 'content':''}
if not (username or pwd):
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
# read from cache
try:
status = self.db.query(GpaCache).filter(GpaCache.cardnum == username).one()
<|code_end|>
. Use current file imports:
(from .._config import gpaCacheTime
from config import VERCODE_URL, LOGIN_URL, INFO_URL
from config import STANDARD, TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from PIL import Image
from sqlalchemy.orm.exc import NoResultFound
from ..models.gpa_cache import GpaCache
from time import time,localtime, strftime
import tornado.web
import tornado.gen
import urllib
import json
import io
import base64)
and context including class names, function names, or small code snippets from other files:
# Path: mod/_config.py
#
# Path: mod/models/gpa_cache.py
# class GpaCache(Base):
# __tablename__ = 'gpa'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096))
# date = Column(Integer, nullable=False)
. Output only the next line. | if status.date > int(time())-gpaCacheTime and status.text != '*': |
Given snippet: <|code_start|># @Date : 2014-06-26 17:00:02
# @Author : xindervella@gamil.com yml_bright@163.com
# import Image
class GPAHandler(tornado.web.RequestHandler):
@property
def db(self):
return self.application.db
def on_finish(self):
self.db.close()
def get(self):
self.write('Herald Web Service')
@tornado.web.asynchronous
@tornado.gen.engine
def post(self):
username = self.get_argument('username', default=None)
pwd = self.get_argument('password', default=None)
status = None
retjson = {'code':200, 'content':''}
if not (username or pwd):
retjson['code'] = 400
retjson['content'] = 'params lack'
else:
# read from cache
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .._config import gpaCacheTime
from config import VERCODE_URL, LOGIN_URL, INFO_URL
from config import STANDARD, TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from PIL import Image
from sqlalchemy.orm.exc import NoResultFound
from ..models.gpa_cache import GpaCache
from time import time,localtime, strftime
import tornado.web
import tornado.gen
import urllib
import json
import io
import base64
and context:
# Path: mod/_config.py
#
# Path: mod/models/gpa_cache.py
# class GpaCache(Base):
# __tablename__ = 'gpa'
# cardnum = Column(Integer, primary_key=True)
# text = Column(String(4096))
# date = Column(Integer, nullable=False)
which might include code, classes, or functions. Output only the next line. | status = self.db.query(GpaCache).filter(GpaCache.cardnum == username).one() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : December 09, 2016
@Author : corvo
vim: set ts=4 sw=4 tw=99 et:
"""
class LogHandler(tornado.web.RequestHandler):
"""
本模块为日志分析后端模块, 预先分析好的日志先存储于数据库中,
使用时读取数据库中的json信息, 做简单处理后返回
"""
def get(self):
self.write('herald webservice')
def post(self):
retjson = {'code': '200', 'content': 'None'}
date_start = self.get_argument('date_start', default='unsolved')
date_cnt = int(self.get_argument('date_cnt', default='1'))
content = []
try:
<|code_end|>
, predict the next line using imports from the current file:
import json
import tornado.web
from mod.models.log import DayLogAnalyze
and context including class names, function names, and sometimes code from other files:
# Path: mod/models/log.py
# class DayLogAnalyze(Base):
# """
# 每日日志重要信息记录
# """
# __tablename__ = "DayLogAnalyze"
# id = Column(Integer, nullable=False, primary_key=True)
# date = Column(VARCHAR(32), nullable=False) # 表项名称access_api.log-date
# api_order = Column(TEXT, nullable=False) # 该日Api请求数目(保留前20)
# ip_order = Column(TEXT, nullable=False) # 该日ip请求数目(保留前30)
# every_hour_count = Column(VARCHAR(1024), nullable=False) # 该日每小时访问量
# device_distribute = Column(TEXT, nullable=False) # 该日发送请求的设备分布
# call_count = Column(Integer, nullable=False) # 该日请求次数
# ios_version = Column(TEXT, nullable=True) # ios设备版本分布
# android_version = Column(TEXT, nullable=True) # android设备版本分布
. Output only the next line. | log_list = self.db.query(DayLogAnalyze).\ |
Next line prediction: <|code_start|>def on_color_test_cases(request):
return request.param
@pytest.fixture(
scope="session",
ids=attrs_id_func,
params=[
# Supported attrs
(["bold"], ["bold"]),
(["dark"], ["dark"]),
(["underline"], ["underline"]),
(["blink"], ["blink"]),
(["reverse"], ["reverse"]),
(["concealed"], ["concealed"]),
# Multiple attrs
(["bold", "dark"], ["bold", "dark"]),
(["bold", "dark", "reverse"], ["bold", "dark", "reverse"]),
# Unsupported attrs
(["Dark"], ValueError()),
(["bold", "bar"], ValueError()),
],
)
def attrs_test_cases(request):
return request.param
@pytest.fixture(
scope="session",
ids=color_id_func,
<|code_end|>
. Use current file imports:
(import signal
import sys
import pytest
from yaspin.constants import COLOR_MAP
from yaspin.signal_handlers import default_handler, fancy_handler)
and context including class names, function names, or small code snippets from other files:
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# Path: yaspin/signal_handlers.py
# def default_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.fail()
# spinner.stop()
# sys.exit(0)
#
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
. Output only the next line. | params=sorted([k for k, v in COLOR_MAP.items() if v == "color"]), |
Based on the snippet: <|code_start|>@pytest.fixture(
scope="session",
params=[
# Empty
b"",
u"",
# Success
b"OK",
u"OK",
b"\xe2\x9c\x94",
u"✔",
# Sun
b"\xe2\x98\x80\xef\xb8\x8f",
u"☀️",
# Spark
b"\xf0\x9f\x92\xa5",
u"💥",
],
)
def final_text(request):
return request.param
@pytest.fixture(
scope="session",
params=[
None,
{signal.SIGUSR1: signal.SIG_DFL},
{signal.SIGTERM: signal.SIG_IGN},
{signal.SIGTERM: signal.default_int_handler},
<|code_end|>
, predict the immediate next line with the help of imports:
import signal
import sys
import pytest
from yaspin.constants import COLOR_MAP
from yaspin.signal_handlers import default_handler, fancy_handler
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# Path: yaspin/signal_handlers.py
# def default_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.fail()
# spinner.stop()
# sys.exit(0)
#
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
. Output only the next line. | {signal.SIGHUP: default_handler}, |
Next line prediction: <|code_start|> scope="session",
params=[
# Empty
b"",
u"",
# Success
b"OK",
u"OK",
b"\xe2\x9c\x94",
u"✔",
# Sun
b"\xe2\x98\x80\xef\xb8\x8f",
u"☀️",
# Spark
b"\xf0\x9f\x92\xa5",
u"💥",
],
)
def final_text(request):
return request.param
@pytest.fixture(
scope="session",
params=[
None,
{signal.SIGUSR1: signal.SIG_DFL},
{signal.SIGTERM: signal.SIG_IGN},
{signal.SIGTERM: signal.default_int_handler},
{signal.SIGHUP: default_handler},
<|code_end|>
. Use current file imports:
(import signal
import sys
import pytest
from yaspin.constants import COLOR_MAP
from yaspin.signal_handlers import default_handler, fancy_handler)
and context including class names, function names, or small code snippets from other files:
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# Path: yaspin/signal_handlers.py
# def default_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.fail()
# spinner.stop()
# sys.exit(0)
#
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
. Output only the next line. | {signal.SIGINT: fancy_handler}, |
Based on the snippet: <|code_start|>
@pytest.mark.parametrize(
"spinner, expected",
[
# None
(None, default_spinner),
# hasattr(spinner, "frames") and not hasattr(spinner, "interval")
(namedtuple("Spinner", "frames")("-\\|/"), default_spinner),
# not hasattr(spinner, "frames") and hasattr(spinner, "interval")
(namedtuple("Spinner", "interval")(42), default_spinner),
# Both attrs, not set
(Spinner("", 0), default_spinner),
# Both attrs, not frames
(Spinner("", 42), default_spinner),
# Both attrs, not interval
(Spinner("-\\|/", 0), default_spinner),
# Both attrs, are set
(Spinner("-\\|/", 42), Spinner("-\\|/", 42)),
],
ids=[
"None",
"no `interval` attr",
"no `frames` attr",
"attrs not set",
"`frames` not set",
"`interval` not set",
"both attrs are set",
],
)
def test_set_spinner(spinner, expected):
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
. Output only the next line. | sp = yaspin(spinner) |
Next line prediction: <|code_start|>"""
tests.test_yaspin
~~~~~~~~~~~~~~~~~
Basic unittests.
"""
@pytest.mark.parametrize(
"spinner, expected",
[
# None
(None, default_spinner),
# hasattr(spinner, "frames") and not hasattr(spinner, "interval")
(namedtuple("Spinner", "frames")("-\\|/"), default_spinner),
# not hasattr(spinner, "frames") and hasattr(spinner, "interval")
(namedtuple("Spinner", "interval")(42), default_spinner),
# Both attrs, not set
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
. Output only the next line. | (Spinner("", 0), default_spinner), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.