Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> # leaf nodes are strings which are file contents scaffold_structure = { module_name: { 'graphql_schema': { '__init__.py': GRAPHQL_INIT_SCAFFOLD, }, 'pent': { '__init__.py': PENT_INIT_SCAFFOLD, 'pents.py': PENTS_SCAFFOLD, }, 'kvetch': { '__init__.py': KVETCH_INIT_SCAFFOLD, 'kvetch_schema.py': KVETCH_SCHEMA_SCAFFOLD, }, 'config.py': PENT_CONFIG_TEMPLATE.format(module_name=module_name), }, 'serve.py': SERVE_SCAFFOLD.format(module_name=module_name), } write_scaffold(scaffold_structure, base_dir, overwrite=False) def overwrite_generated_files( module_dir: str, document_ast: GrappleDocument, module_name: str ) -> None: generated_files_scaffold = { 'graphql_schema': { 'generated.py': print_graphql_file(document_ast, module_name) }, 'pent': { <|code_end|> , predict the immediate next line with the help of imports: import os import re from typing import Any, Dict, Iterable, List, cast from .graphql_printer import print_graphql_file from .kvetch_printer import print_kvetch_decls from .parser import GrappleDocument, GrappleTypeDef, parse_grapple from .pent_printer import print_generated_pents_file, print_autopents_file and context (classes, functions, sometimes code) from other files: # Path: graphscale/grapple/graphql_printer.py # def print_graphql_file(document_ast: GrappleDocument, module_name: str) -> str: # return grapple_graphql_header(module_name) + '\n' + print_graphql_defs(document_ast) # # Path: graphscale/grapple/kvetch_printer.py # def print_kvetch_decls(document_ast: GrappleDocument) -> str: # # writer = CodeWriter() # writer.line(GRAPPLE_KVETCH_HEADER) # # writer.line("def generated_objects() -> List[ObjectDefinition]:") # writer.increase_indent() # writer.line('return [') # writer.increase_indent() # for pent_type in document_ast.pents(): # writer.line( # "ObjectDefinition(type_name='%s', type_id=%s)," % (pent_type.name, pent_type.type_id) # ) # writer.decrease_indent() # writer.line(']') # writer.decrease_indent() # writer.blank_line() # # print_kvetch_generated_edges(writer, document_ast) # # writer.line("def generated_indexes() -> List[IndexDefinition]:") # writer.increase_indent() # writer.line('return []') # writer.decrease_indent() # writer.blank_line() # # return writer.result() # # Path: graphscale/grapple/parser.py # class GrappleDocument: # def __init__(self, *, types: List[GrappleTypeDef]) -> None: # self._types = types # # def pents(self) -> List[GrappleTypeDef]: # return [obj_type for obj_type in self.object_types() if obj_type.is_pent] # # def pent_mutation_datas(self) -> List[GrappleTypeDef]: # return [in_type for in_type in self.input_types() if in_type.is_pent_mutation_data] # # def pent_payloads(self) -> List[GrappleTypeDef]: # return [obj_type for obj_type in self.object_types() if obj_type.is_pent_payload] # # def all_pentish(self) -> List[GrappleTypeDef]: # return self.pents() + self.pent_mutation_datas() + self.pent_payloads() + self.enum_types() # # def mutation_type(self) -> GrappleTypeDef: # for obj_type in self.object_types(): # if obj_type.name == 'Mutation': # return obj_type # return None # # def query_type(self) -> GrappleTypeDef: # for obj_type in self.object_types(): # if obj_type.name == 'Query': # return obj_type # return None # # def object_types(self) -> List[GrappleTypeDef]: # return [t for t in self._types if t.type_varietal == TypeVarietal.OBJECT] # # def input_types(self) -> List[GrappleTypeDef]: # return [t for t in self._types if t.type_varietal == TypeVarietal.INPUT] # # def enum_types(self) -> List[GrappleTypeDef]: # return [t for t in self._types if t.type_varietal == TypeVarietal.ENUM] # # def is_enum(self, name: str) -> bool: # ttype = self.type_named(name) # return ttype and ttype.type_varietal == TypeVarietal.ENUM # # def type_named(self, name: str) -> GrappleTypeDef: # for ttype in self._types: # if ttype.name == name: # return ttype # return None # # class GrappleTypeDef(NamedTuple): # name: str # fields: List[GrappleField] # values: List[Any] # type_id: int # is_pent: bool # is_pent_mutation_data: bool # is_pent_payload: bool # type_varietal: TypeVarietal # # def parse_grapple(grapple_string: str) -> GrappleDocument: # ast = parse(Source(grapple_string)) # grapple_types = [] # for type_node in ast.definitions: # grapple_types.append(create_grapple_type_definition(type_node)) # return GrappleDocument(types=grapple_types) # # Path: graphscale/grapple/pent_printer.py # def print_generated_pents_file(document_ast: GrappleDocument) -> str: # return GENERATED_PENT_HEADER + '\n' + print_generated_pents_file_body(document_ast) + '\n' # # def print_autopents_file(document_ast: GrappleDocument) -> str: # return ( # GENERATED_PENT_HEADER + '\n' + print_autopents_file_body(document_ast) + '\n' + # print_autopent_all_export(document_ast) + '\n' # ) . Output only the next line.
'autopents.py': print_autopents_file(document_ast),
Predict the next line after this snippet: <|code_start|> def test_reverse_dictionary() -> None: assert reverse_dict({1: '1', 2: '2'}) == {'2': 2, '1': 1} def test_reverse_dictionary_dup_key() -> None: assert reverse_dict({1: '1', 2: '1'}) @pytest.mark.asyncio async def test_async_list() -> None: async def gen_num(num: int) -> int: return num list_of_gens = [gen_num(1)] <|code_end|> using the current file's imports: import pytest from graphscale.utils import reverse_dict, async_list, async_tuple, is_camel_case, to_snake_case and any relevant context from other files: # Path: graphscale/utils.py # def reverse_dict(dict_to_reverse: Dict[K, V]) -> Dict[V, K]: # """Swap the keys and values of a dictionary. Duplicate values (that will become keys) # do not cause error. One of the keys will be the new value non-deterministically # """ # return {v: k for k, v in dict_to_reverse.items()} # # async def async_list(coros: List[Awaitable[T]]) -> List[T]: # """Use to await a list and return a list. # Example: list_of_results = await async_list(list_of_gens) # """ # return await asyncio.gather(*coros) # # async def async_tuple(*coros: Awaitable) -> Tuple[Any, ...]: # """Await on a parameters and get a tuple back. # Example: result_one, result_two = await async_tuple(gen_one(), gen_two()) # """ # return tuple(await asyncio.gather(*coros)) # # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
list_of_one = await async_list(list_of_gens)
Next line prediction: <|code_start|> def test_reverse_dictionary() -> None: assert reverse_dict({1: '1', 2: '2'}) == {'2': 2, '1': 1} def test_reverse_dictionary_dup_key() -> None: assert reverse_dict({1: '1', 2: '1'}) @pytest.mark.asyncio async def test_async_list() -> None: async def gen_num(num: int) -> int: return num list_of_gens = [gen_num(1)] list_of_one = await async_list(list_of_gens) assert list_of_one == [1] list_of_two = await async_list([gen_num(1), gen_num(2)]) assert list_of_two == [1, 2] @pytest.mark.asyncio async def test_async_tuple() -> None: async def gen_num(num: int) -> int: return num <|code_end|> . Use current file imports: (import pytest from graphscale.utils import reverse_dict, async_list, async_tuple, is_camel_case, to_snake_case) and context including class names, function names, or small code snippets from other files: # Path: graphscale/utils.py # def reverse_dict(dict_to_reverse: Dict[K, V]) -> Dict[V, K]: # """Swap the keys and values of a dictionary. Duplicate values (that will become keys) # do not cause error. One of the keys will be the new value non-deterministically # """ # return {v: k for k, v in dict_to_reverse.items()} # # async def async_list(coros: List[Awaitable[T]]) -> List[T]: # """Use to await a list and return a list. # Example: list_of_results = await async_list(list_of_gens) # """ # return await asyncio.gather(*coros) # # async def async_tuple(*coros: Awaitable) -> Tuple[Any, ...]: # """Await on a parameters and get a tuple back. # Example: result_one, result_two = await async_tuple(gen_one(), gen_two()) # """ # return tuple(await asyncio.gather(*coros)) # # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
one, two = await async_tuple(gen_num(1), gen_num(2))
Using the snippet: <|code_start|> list_of_one = await async_list(list_of_gens) assert list_of_one == [1] list_of_two = await async_list([gen_num(1), gen_num(2)]) assert list_of_two == [1, 2] @pytest.mark.asyncio async def test_async_tuple() -> None: async def gen_num(num: int) -> int: return num one, two = await async_tuple(gen_num(1), gen_num(2)) assert one == 1 assert two == 2 single_result = await async_tuple(gen_num(1)) assert single_result == (1, ) two, one = await async_tuple(gen_num(2), gen_num(1)) assert one == 1 assert two == 2 def test_is_camel_case() -> None: <|code_end|> , determine the next line of code. You have imports: import pytest from graphscale.utils import reverse_dict, async_list, async_tuple, is_camel_case, to_snake_case and context (class names, function names, or code) available: # Path: graphscale/utils.py # def reverse_dict(dict_to_reverse: Dict[K, V]) -> Dict[V, K]: # """Swap the keys and values of a dictionary. Duplicate values (that will become keys) # do not cause error. One of the keys will be the new value non-deterministically # """ # return {v: k for k, v in dict_to_reverse.items()} # # async def async_list(coros: List[Awaitable[T]]) -> List[T]: # """Use to await a list and return a list. # Example: list_of_results = await async_list(list_of_gens) # """ # return await asyncio.gather(*coros) # # async def async_tuple(*coros: Awaitable) -> Tuple[Any, ...]: # """Await on a parameters and get a tuple back. # Example: result_one, result_two = await async_tuple(gen_one(), gen_two()) # """ # return tuple(await asyncio.gather(*coros)) # # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
assert is_camel_case('testFoo') is True
Given the following code snippet before the placeholder: <|code_start|> assert list_of_two == [1, 2] @pytest.mark.asyncio async def test_async_tuple() -> None: async def gen_num(num: int) -> int: return num one, two = await async_tuple(gen_num(1), gen_num(2)) assert one == 1 assert two == 2 single_result = await async_tuple(gen_num(1)) assert single_result == (1, ) two, one = await async_tuple(gen_num(2), gen_num(1)) assert one == 1 assert two == 2 def test_is_camel_case() -> None: assert is_camel_case('testFoo') is True assert is_camel_case('test_foo') is False assert is_camel_case('testfoo') is False def test_to_snake_case() -> None: <|code_end|> , predict the next line using imports from the current file: import pytest from graphscale.utils import reverse_dict, async_list, async_tuple, is_camel_case, to_snake_case and context including class names, function names, and sometimes code from other files: # Path: graphscale/utils.py # def reverse_dict(dict_to_reverse: Dict[K, V]) -> Dict[V, K]: # """Swap the keys and values of a dictionary. Duplicate values (that will become keys) # do not cause error. One of the keys will be the new value non-deterministically # """ # return {v: k for k, v in dict_to_reverse.items()} # # async def async_list(coros: List[Awaitable[T]]) -> List[T]: # """Use to await a list and return a list. # Example: list_of_results = await async_list(list_of_gens) # """ # return await asyncio.gather(*coros) # # async def async_tuple(*coros: Awaitable) -> Tuple[Any, ...]: # """Await on a parameters and get a tuple back. # Example: result_one, result_two = await async_tuple(gen_one(), gen_two()) # """ # return tuple(await asyncio.gather(*coros)) # # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
assert to_snake_case('foo') == 'foo'
Using the snippet: <|code_start|> pytestmark = pytest.mark.asyncio class EnumTest(Enum): VALUE_ONE = 'VALUE_ONE' VALUE_TWO = 'VALUE_TWO' def define_schema(resolver: Callable, enumType: GraphQLObjectType) -> GraphQLSchema: def resolve_input(_obj: Any, args: dict, *_: Any) -> Any: assert isinstance(args['testEnumArg'], EnumTest) return args['testEnumArg'] query_type = GraphQLObjectType( name='Query', fields={ 'testEnum': GraphQLField(type=enumType, resolver=resolver), 'testEnumArg': GraphQLField( type=enumType, args={'testEnumArg': GraphQLArgument(type=enumType)}, resolver=resolve_input ) } ) return GraphQLSchema(query=query_type) <|code_end|> , determine the next line of code. You have imports: from enum import Enum from typing import Callable, Any from graphql import GraphQLObjectType, GraphQLField, graphql, GraphQLSchema, GraphQLArgument from graphscale.grapple.enum import GraphQLPythonEnumType import pytest and context (class names, function names, or code) available: # Path: graphscale/grapple/enum.py # class GraphQLPythonEnumType(GraphQLEnumType): # def __init__(self, python_enum_type: Any, description: str=None) -> None: # self.python_enum_type = python_enum_type # name = python_enum_type.__name__ # values = OrderedDict() # type: OrderedDict[Any, GraphQLEnumValue] # for enum_value in python_enum_type.__members__.keys(): # values[enum_value] = GraphQLEnumValue(value=enum_value) # super().__init__(name, values, description=description) # # def serialize(self, value: Enum) -> str: # return value.name # # def parse_value(self, value: str) -> Enum: # return self.python_enum_type(value) # type: ignore # # def parse_literal(self, value_ast: Value) -> Enum: # if not isinstance(value_ast, EnumValue): # return None # return self.python_enum_type(value_ast.value) # type: ignore . Output only the next line.
GraphQLEnumTest = GraphQLPythonEnumType(EnumTest)
Using the snippet: <|code_start|> def create_graphql_app( root_object: PentContextfulObject, schema: GraphQLSchema, debug: bool=True ) -> Sanic: """ Creates a Sanic app and adds a graphql/graphiql endpoint """ app = Sanic(__name__) app.debug = debug if debug: # hack from https://github.com/channelcat/sanic/issues/168 # for some reason pylint is confused by this import #E0611 no name in module #pylint: disable=E0611 reloader = LiveReloader() reloader.start_watcher_thread() # this is totally gross and I need a better story for managing context lifetime # versus loader lifetime. The context houses the in-memory shards in in memory # case currently so you cannot create a new one with every request. However # you do need a new loader every request because it is affined with its # asyncio event loop def root_factory() -> Any: <|code_end|> , determine the next line of code. You have imports: from typing import Callable, Any from graphql import GraphQLSchema from sanic import Sanic from sanic_graphql import GraphQLView from .pent import PentContextfulObject, PentLoader from aoiklivereload import LiveReloader and context (class names, function names, or code) available: # Path: graphscale/pent.py # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context # # class PentLoader(DataLoader): # def __init__(self, context: PentContext) -> None: # super().__init__(batch_load_fn=self._load_pents) # self.context = context # # async def _load_pents(self, ids: List[UUID]) -> Sequence[Pent]: # obj_dict = await self._actual_load_pent_dict(ids) # return list(obj_dict.values()) # # async def _actual_load_pent_dict(self, ids: List[UUID]) -> Dict[UUID, Pent]: # obj_dict = await self.context.kvetch.gen_objects(ids) # pent_dict = OrderedDict() # type: OrderedDict[UUID, Pent] # for obj_id, data in obj_dict.items(): # if not data: # pent_dict[obj_id] = None # else: # cls = self.context.config.get_type(data['type_id']) # pent_dict[obj_id] = cls(self.context, obj_id, data) # return pent_dict . Output only the next line.
root_object.context.loader = PentLoader(root_object.context)
Predict the next line for this snippet: <|code_start|> def enum_types(self) -> List[GrappleTypeDef]: return [t for t in self._types if t.type_varietal == TypeVarietal.ENUM] def is_enum(self, name: str) -> bool: ttype = self.type_named(name) return ttype and ttype.type_varietal == TypeVarietal.ENUM def type_named(self, name: str) -> GrappleTypeDef: for ttype in self._types: if ttype.name == name: return ttype return None def parse_grapple(grapple_string: str) -> GrappleDocument: ast = parse(Source(grapple_string)) grapple_types = [] for type_node in ast.definitions: grapple_types.append(create_grapple_type_definition(type_node)) return GrappleDocument(types=grapple_types) def has_directive(ast: Node, name: str) -> bool: return name in [dir_node.name.value for dir_node in ast.directives] def get_directive(ast: Node, name: str) -> Directive: for dir_node in ast.directives: if dir_node.name.value == name: <|code_end|> with the help of current file imports: from datetime import datetime from enum import Enum, auto from typing import NamedTuple, List, Any, Union from uuid import UUID from graphql.language.ast import ( EnumTypeDefinition, InputObjectTypeDefinition, ListType, NamedType, NonNullType, ObjectTypeDefinition, IntValue, StringValue, BooleanValue, Node, TypeDefinition, Value, InputValueDefinition, Directive, FieldDefinition, Type ) from graphql.language.parser import parse from graphql.language.source import Source from graphscale import check from graphscale.utils import is_camel_case, to_snake_case and context from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/utils.py # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() , which may contain function names, class names, or code. Output only the next line.
check.isinst(dir_node, Directive)
Next line prediction: <|code_start|> edge_name: str edge_id: int field: str class DeletePentData(NamedTuple): type: str FieldVarietalsUnion = Union[EdgeToStoredIdData, DeletePentData] class GrappleFieldData(NamedTuple): name: str type_ref: GrappleTypeRef args: Any field_varietal: FieldVarietal field_varietal_data: FieldVarietalsUnion class GrappleField(GrappleFieldData): @property def is_custom_field(self) -> bool: return self.field_varietal == FieldVarietal.CUSTOM @property def python_name(self) -> str: if self.name == 'id': return 'obj_id' name = self.name <|code_end|> . Use current file imports: (from datetime import datetime from enum import Enum, auto from typing import NamedTuple, List, Any, Union from uuid import UUID from graphql.language.ast import ( EnumTypeDefinition, InputObjectTypeDefinition, ListType, NamedType, NonNullType, ObjectTypeDefinition, IntValue, StringValue, BooleanValue, Node, TypeDefinition, Value, InputValueDefinition, Directive, FieldDefinition, Type ) from graphql.language.parser import parse from graphql.language.source import Source from graphscale import check from graphscale.utils import is_camel_case, to_snake_case) and context including class names, function names, or small code snippets from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/utils.py # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
if is_camel_case(name):
Using the snippet: <|code_start|> edge_id: int field: str class DeletePentData(NamedTuple): type: str FieldVarietalsUnion = Union[EdgeToStoredIdData, DeletePentData] class GrappleFieldData(NamedTuple): name: str type_ref: GrappleTypeRef args: Any field_varietal: FieldVarietal field_varietal_data: FieldVarietalsUnion class GrappleField(GrappleFieldData): @property def is_custom_field(self) -> bool: return self.field_varietal == FieldVarietal.CUSTOM @property def python_name(self) -> str: if self.name == 'id': return 'obj_id' name = self.name if is_camel_case(name): <|code_end|> , determine the next line of code. You have imports: from datetime import datetime from enum import Enum, auto from typing import NamedTuple, List, Any, Union from uuid import UUID from graphql.language.ast import ( EnumTypeDefinition, InputObjectTypeDefinition, ListType, NamedType, NonNullType, ObjectTypeDefinition, IntValue, StringValue, BooleanValue, Node, TypeDefinition, Value, InputValueDefinition, Directive, FieldDefinition, Type ) from graphql.language.parser import parse from graphql.language.source import Source from graphscale import check from graphscale.utils import is_camel_case, to_snake_case and context (class names, function names, or code) available: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/utils.py # def is_camel_case(string: str) -> bool: # """Is the string potentially camel case? Only checks for capital letters currently""" # return bool(re.search('[A-Z]', string)) # # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
name = to_snake_case(name)
Predict the next line for this snippet: <|code_start|> except pymysql.err.OperationalError as error: print('Could not connect to local mysql instance:') print('All tests will run locally') print(error) MagnusConn.is_up = False else: MagnusConn.is_up = True conn.close() # type: ignore return MagnusConn.is_up @staticmethod def get_conn_info(db_name: str) -> ConnectionInfo: return ConnectionInfo( host='localhost', user='magnus', password='magnus', db=db_name, ) def db_mem_fixture(*, mem: Callable, db: Callable) -> List[Callable]: fixture_funcs = [] if MagnusConn.is_db_unittest_up(): fixture_funcs.append(db) fixture_funcs.append(mem) return fixture_funcs async def async_test_graphql( query: str, <|code_end|> with the help of current file imports: import traceback import pymysql import pymysql.cursors from typing import Callable, List, Dict, Any from graphql import GraphQLSchema, graphql from graphscale import check from graphscale.pent import PentContext, PentContextfulObject from graphscale.sql import ConnectionInfo, pymysql_conn_from_info from graphscale.utils import print_error and context from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context # # Path: graphscale/sql.py # class ConnectionInfo(NamedTuple): # host: str # user: str # password: str # db: str # charset: str = 'utf8mb4' # # def pymysql_conn_from_info(conn_info: ConnectionInfo) -> pymysql.Connection: # return pymysql.connect( # host=conn_info.host, # user=conn_info.user, # password=conn_info.password, # db=conn_info.db, # charset=conn_info.charset, # cursorclass=pymysql.cursors.DictCursor, # autocommit=True, # ) # # Path: graphscale/utils.py # def print_error(val: Any) -> None: # """Print value to stderr""" # sys.stderr.write(str(val) + '\n') , which may contain function names, class names, or code. Output only the next line.
pent_context: PentContext,
Given snippet: <|code_start|> print('All tests will run locally') print(error) MagnusConn.is_up = False else: MagnusConn.is_up = True conn.close() # type: ignore return MagnusConn.is_up @staticmethod def get_conn_info(db_name: str) -> ConnectionInfo: return ConnectionInfo( host='localhost', user='magnus', password='magnus', db=db_name, ) def db_mem_fixture(*, mem: Callable, db: Callable) -> List[Callable]: fixture_funcs = [] if MagnusConn.is_db_unittest_up(): fixture_funcs.append(db) fixture_funcs.append(mem) return fixture_funcs async def async_test_graphql( query: str, pent_context: PentContext, graphql_schema: GraphQLSchema, <|code_end|> , continue by predicting the next line. Consider current file imports: import traceback import pymysql import pymysql.cursors from typing import Callable, List, Dict, Any from graphql import GraphQLSchema, graphql from graphscale import check from graphscale.pent import PentContext, PentContextfulObject from graphscale.sql import ConnectionInfo, pymysql_conn_from_info from graphscale.utils import print_error and context: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context # # Path: graphscale/sql.py # class ConnectionInfo(NamedTuple): # host: str # user: str # password: str # db: str # charset: str = 'utf8mb4' # # def pymysql_conn_from_info(conn_info: ConnectionInfo) -> pymysql.Connection: # return pymysql.connect( # host=conn_info.host, # user=conn_info.user, # password=conn_info.password, # db=conn_info.db, # charset=conn_info.charset, # cursorclass=pymysql.cursors.DictCursor, # autocommit=True, # ) # # Path: graphscale/utils.py # def print_error(val: Any) -> None: # """Print value to stderr""" # sys.stderr.write(str(val) + '\n') which might include code, classes, or functions. Output only the next line.
root_value: PentContextfulObject=None,
Predict the next line after this snippet: <|code_start|> class MagnusConn: is_up = None @staticmethod <|code_end|> using the current file's imports: import traceback import pymysql import pymysql.cursors from typing import Callable, List, Dict, Any from graphql import GraphQLSchema, graphql from graphscale import check from graphscale.pent import PentContext, PentContextfulObject from graphscale.sql import ConnectionInfo, pymysql_conn_from_info from graphscale.utils import print_error and any relevant context from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context # # Path: graphscale/sql.py # class ConnectionInfo(NamedTuple): # host: str # user: str # password: str # db: str # charset: str = 'utf8mb4' # # def pymysql_conn_from_info(conn_info: ConnectionInfo) -> pymysql.Connection: # return pymysql.connect( # host=conn_info.host, # user=conn_info.user, # password=conn_info.password, # db=conn_info.db, # charset=conn_info.charset, # cursorclass=pymysql.cursors.DictCursor, # autocommit=True, # ) # # Path: graphscale/utils.py # def print_error(val: Any) -> None: # """Print value to stderr""" # sys.stderr.write(str(val) + '\n') . Output only the next line.
def get_unittest_conn_info() -> ConnectionInfo:
Next line prediction: <|code_start|> class MagnusConn: is_up = None @staticmethod def get_unittest_conn_info() -> ConnectionInfo: return MagnusConn.get_conn_info('graphscale-unittest') @staticmethod def is_db_unittest_up() -> bool: """Tests to see if the unittest-mysql is up and running on the localhost This allows for the conditional execution of tests on the db shards in addition to the memory shards""" if MagnusConn.is_up is not None: return MagnusConn.is_up try: conn_info = MagnusConn.get_unittest_conn_info() <|code_end|> . Use current file imports: (import traceback import pymysql import pymysql.cursors from typing import Callable, List, Dict, Any from graphql import GraphQLSchema, graphql from graphscale import check from graphscale.pent import PentContext, PentContextfulObject from graphscale.sql import ConnectionInfo, pymysql_conn_from_info from graphscale.utils import print_error) and context including class names, function names, or small code snippets from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context # # Path: graphscale/sql.py # class ConnectionInfo(NamedTuple): # host: str # user: str # password: str # db: str # charset: str = 'utf8mb4' # # def pymysql_conn_from_info(conn_info: ConnectionInfo) -> pymysql.Connection: # return pymysql.connect( # host=conn_info.host, # user=conn_info.user, # password=conn_info.password, # db=conn_info.db, # charset=conn_info.charset, # cursorclass=pymysql.cursors.DictCursor, # autocommit=True, # ) # # Path: graphscale/utils.py # def print_error(val: Any) -> None: # """Print value to stderr""" # sys.stderr.write(str(val) + '\n') . Output only the next line.
conn = pymysql_conn_from_info(conn_info)
Based on the snippet: <|code_start|> def db_mem_fixture(*, mem: Callable, db: Callable) -> List[Callable]: fixture_funcs = [] if MagnusConn.is_db_unittest_up(): fixture_funcs.append(db) fixture_funcs.append(mem) return fixture_funcs async def async_test_graphql( query: str, pent_context: PentContext, graphql_schema: GraphQLSchema, root_value: PentContextfulObject=None, variable_values: Dict[str, Any]=None, ): # check.str_param(query, 'query') # check.param(pent_context, PentContext, 'pent_context') # check.param(graphql_schema, GraphQLSchema, 'graphql_schema') # check.opt_dict_param(variable_values, 'variable_values') result = await graphql( graphql_schema, query, context_value=pent_context, root_value=root_value, variable_values=variable_values ) if result.errors: error = result.errors[0] <|code_end|> , predict the immediate next line with the help of imports: import traceback import pymysql import pymysql.cursors from typing import Callable, List, Dict, Any from graphql import GraphQLSchema, graphql from graphscale import check from graphscale.pent import PentContext, PentContextfulObject from graphscale.sql import ConnectionInfo, pymysql_conn_from_info from graphscale.utils import print_error and context (classes, functions, sometimes code) from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context # # Path: graphscale/sql.py # class ConnectionInfo(NamedTuple): # host: str # user: str # password: str # db: str # charset: str = 'utf8mb4' # # def pymysql_conn_from_info(conn_info: ConnectionInfo) -> pymysql.Connection: # return pymysql.connect( # host=conn_info.host, # user=conn_info.user, # password=conn_info.password, # db=conn_info.db, # charset=conn_info.charset, # cursorclass=pymysql.cursors.DictCursor, # autocommit=True, # ) # # Path: graphscale/utils.py # def print_error(val: Any) -> None: # """Print value to stderr""" # sys.stderr.write(str(val) + '\n') . Output only the next line.
print_error('GRAPHQL ERROR')
Given the following code snippet before the placeholder: <|code_start|> class GraphQLArg(NamedTuple): name: str arg_type: str value: Any class InProcessGraphQLClient: def __init__(self, root_value: PentContextfulObject, graphql_schema: GraphQLSchema) -> None: self.root_value = root_value self.graphql_schema = graphql_schema @property <|code_end|> , predict the next line using imports from the current file: from typing import Any, Dict, NamedTuple, cast from graphql import graphql as graphql_main from graphql import GraphQLSchema from graphql.execution import ExecutionResult from .pent import PentContext, PentContextfulObject import traceback and context including class names, function names, and sometimes code from other files: # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context . Output only the next line.
def context(self) -> PentContext:
Here is a snippet: <|code_start|> class GraphQLArg(NamedTuple): name: str arg_type: str value: Any class InProcessGraphQLClient: <|code_end|> . Write the next line using the current file imports: from typing import Any, Dict, NamedTuple, cast from graphql import graphql as graphql_main from graphql import GraphQLSchema from graphql.execution import ExecutionResult from .pent import PentContext, PentContextfulObject import traceback and context from other files: # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # class PentContextfulObject: # def __init__(self, context: PentContext) -> None: # self.__context = context # # @property # def context(self) -> PentContext: # return self.__context , which may include functions, classes, or code. Output only the next line.
def __init__(self, root_value: PentContextfulObject, graphql_schema: GraphQLSchema) -> None:
Continue the code snippet: <|code_start|> def pythonify_dict(input_data: Dict[str, Any]) -> Dict[str, Any]: data = {} for name, value in input_data.items(): python_name = to_snake_case(name) data[python_name] = pythonify_dict(value) if isinstance(value, dict) else value return data def process_args(args: Dict[str, Any]) -> Dict[str, Any]: if 'id' in args: args['obj_id'] = args['id'] del args['id'] return pythonify_dict(args) def define_pent_mutation_resolver(python_name: str, pent_data_cls_name: str) -> Callable: @async_field_error_boundary async def mutation_resolver(obj: Any, args: Dict[str, Any], context: PentContext, *_: Any) -> Any: args = process_args(args) pent_data_cls = context.cls_from_name(pent_data_cls_name) pent_data = pent_data_cls(**args['data']) args['data'] = pent_data prop = getattr(obj, python_name) <|code_end|> . Use current file imports: from typing import Any, Callable, Dict from graphscale import check from graphscale.errors import async_field_error_boundary, field_error_boundary from graphscale.pent import PentContext from graphscale.utils import to_snake_case and context (classes, functions, or code) from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/errors.py # def async_field_error_boundary(async_resolver: Callable) -> Callable: # @wraps(async_resolver) # async def inner(*args: Any, **kwargs: Any) -> Any: # try: # return await async_resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # def field_error_boundary(resolver: Callable) -> Callable: # @wraps(resolver) # def inner(*args: Any, **kwargs: Any) -> Any: # try: # return resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # Path: graphscale/utils.py # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
check.invariant(callable(prop), 'must be async function')
Based on the snippet: <|code_start|> def pythonify_dict(input_data: Dict[str, Any]) -> Dict[str, Any]: data = {} for name, value in input_data.items(): python_name = to_snake_case(name) data[python_name] = pythonify_dict(value) if isinstance(value, dict) else value return data def process_args(args: Dict[str, Any]) -> Dict[str, Any]: if 'id' in args: args['obj_id'] = args['id'] del args['id'] return pythonify_dict(args) def define_pent_mutation_resolver(python_name: str, pent_data_cls_name: str) -> Callable: <|code_end|> , predict the immediate next line with the help of imports: from typing import Any, Callable, Dict from graphscale import check from graphscale.errors import async_field_error_boundary, field_error_boundary from graphscale.pent import PentContext from graphscale.utils import to_snake_case and context (classes, functions, sometimes code) from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/errors.py # def async_field_error_boundary(async_resolver: Callable) -> Callable: # @wraps(async_resolver) # async def inner(*args: Any, **kwargs: Any) -> Any: # try: # return await async_resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # def field_error_boundary(resolver: Callable) -> Callable: # @wraps(resolver) # def inner(*args: Any, **kwargs: Any) -> Any: # try: # return resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # Path: graphscale/utils.py # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
@async_field_error_boundary
Continue the code snippet: <|code_start|> @async_field_error_boundary async def mutation_resolver(obj: Any, args: Dict[str, Any], context: PentContext, *_: Any) -> Any: args = process_args(args) pent_data_cls = context.cls_from_name(pent_data_cls_name) pent_data = pent_data_cls(**args['data']) args['data'] = pent_data prop = getattr(obj, python_name) check.invariant(callable(prop), 'must be async function') return await prop(**args) return mutation_resolver def define_default_gen_resolver(python_name: str) -> Callable: @async_field_error_boundary async def the_resolver(obj: Any, args: Dict[str, Any], *_: Any): if args: if 'id' in args: args['obj_id'] = args['id'] del args['id'] args = pythonify_dict(args) prop = getattr(obj, python_name) check.invariant(callable(prop), 'must be async function') return await prop(**args) return the_resolver def define_default_resolver(python_name: str) -> Callable: <|code_end|> . Use current file imports: from typing import Any, Callable, Dict from graphscale import check from graphscale.errors import async_field_error_boundary, field_error_boundary from graphscale.pent import PentContext from graphscale.utils import to_snake_case and context (classes, functions, or code) from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/errors.py # def async_field_error_boundary(async_resolver: Callable) -> Callable: # @wraps(async_resolver) # async def inner(*args: Any, **kwargs: Any) -> Any: # try: # return await async_resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # def field_error_boundary(resolver: Callable) -> Callable: # @wraps(resolver) # def inner(*args: Any, **kwargs: Any) -> Any: # try: # return resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # Path: graphscale/utils.py # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
@field_error_boundary
Given the following code snippet before the placeholder: <|code_start|> def pythonify_dict(input_data: Dict[str, Any]) -> Dict[str, Any]: data = {} for name, value in input_data.items(): python_name = to_snake_case(name) data[python_name] = pythonify_dict(value) if isinstance(value, dict) else value return data def process_args(args: Dict[str, Any]) -> Dict[str, Any]: if 'id' in args: args['obj_id'] = args['id'] del args['id'] return pythonify_dict(args) def define_pent_mutation_resolver(python_name: str, pent_data_cls_name: str) -> Callable: @async_field_error_boundary <|code_end|> , predict the next line using imports from the current file: from typing import Any, Callable, Dict from graphscale import check from graphscale.errors import async_field_error_boundary, field_error_boundary from graphscale.pent import PentContext from graphscale.utils import to_snake_case and context including class names, function names, and sometimes code from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/errors.py # def async_field_error_boundary(async_resolver: Callable) -> Callable: # @wraps(async_resolver) # async def inner(*args: Any, **kwargs: Any) -> Any: # try: # return await async_resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # def field_error_boundary(resolver: Callable) -> Callable: # @wraps(resolver) # def inner(*args: Any, **kwargs: Any) -> Any: # try: # return resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # Path: graphscale/utils.py # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
async def mutation_resolver(obj: Any, args: Dict[str, Any], context: PentContext,
Given the following code snippet before the placeholder: <|code_start|> def pythonify_dict(input_data: Dict[str, Any]) -> Dict[str, Any]: data = {} for name, value in input_data.items(): <|code_end|> , predict the next line using imports from the current file: from typing import Any, Callable, Dict from graphscale import check from graphscale.errors import async_field_error_boundary, field_error_boundary from graphscale.pent import PentContext from graphscale.utils import to_snake_case and context including class names, function names, and sometimes code from other files: # Path: graphscale/check.py # def isinst(obj: Any, ttype: Type, _msg: str=None) -> None: # def invariant(condition: Any, msg: str) -> None: # def failed(msg: str) -> NoReturn: # # Path: graphscale/errors.py # def async_field_error_boundary(async_resolver: Callable) -> Callable: # @wraps(async_resolver) # async def inner(*args: Any, **kwargs: Any) -> Any: # try: # return await async_resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # def field_error_boundary(resolver: Callable) -> Callable: # @wraps(resolver) # def inner(*args: Any, **kwargs: Any) -> Any: # try: # return resolver(*args, **kwargs) # except Exception as error: # raise GraphQLFieldError(error) # # return inner # # Path: graphscale/pent.py # class PentContext: # def __init__(self, *, kvetch: Kvetch, config: PentConfig) -> None: # self.__kvetch = kvetch # self.__config = config # self.loader = PentLoader(self) # # def cls_from_name(self, name: str) -> Type: # return self.__config.get_class_from_name(name) # # @property # def kvetch(self) -> Kvetch: # return self.__kvetch # # @property # def config(self) -> PentConfig: # return self.__config # # # had to change things to nuke loader at beginning of request again # # @property # # def loader(self) -> 'PentLoader': # # return self.__loader # # Path: graphscale/utils.py # def to_snake_case(camel_case: str) -> str: # """Convert a camel case string to snake case. e.g. fooBar ==> foo_bar""" # with_underscores = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_case) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', with_underscores).lower() . Output only the next line.
python_name = to_snake_case(name)
Based on the snippet: <|code_start|> @fixture def mock_client(request): client = MockClient() request.addfinalizer(client.on_stop) return client @fixture def mock_transport(): <|code_end|> , predict the immediate next line with the help of imports: import sys import asyncio from concurrent.futures import ThreadPoolExecutor from pytest import fixture from .mocks import MockClient, MockTransport from oshino.augments.stats import SimpleMovingAverage and context (classes, functions, sometimes code) from other files: # Path: tests/mocks.py # class MockClient(AugmentFixture): # # def __init__(self, transport=None): # self.events = [] # self.augments = {} # self.tasks = [] # self.transport = transport # # def event(self, **kwargs): # self.tasks.append(self.apply_augment(copy(kwargs))) # self.events.append(kwargs) # # def clear_queue(self): # self.events = [] # # def flush(self, transport): # response = transport.send(self.events) # self.clear_queue() # return response # # class MockTransport(BlankTransport): # # def __init__(self, host=None, port=None, broken=False): # self.connected = False # self.broken = broken # self.sneaky = False # # def connect(self): # if self.broken: # raise ConnectionRefusedError # self.connected = True # # def disconnect(self): # self.connected = False # # def send(self, message): # if self.broken or self.sneaky: # raise RiemannError # # return True # # Path: oshino/augments/stats.py # class SimpleMovingAverage(AugmentBase): # # def __init__(self, *args, **kwargs): # super(SimpleMovingAverage, self).__init__(*args, **kwargs) # self.dq = deque(maxlen=self.step) # # @property # def step(self): # return self._data.get("step", 5) # # def activate(self, client, g): # step = self.step # # stopped = False # while not stopped: # # try: # event = next(g) # self.dq.append(event) # except StopIteration: # stopped = True # break # # data = list(map(lambda x: x["metric_f"], list(self.dq))) # if len(data) == step: # output = sum(data) / len(data) # # self.send_event(client, # service=self.prefix + "value", # metric_f=output, # state="ok") . Output only the next line.
return MockTransport()
Given the code snippet: <|code_start|> @fixture def mock_transport(): return MockTransport() @fixture def broken_transport(): return MockTransport(broken=True) @fixture(scope="session") def executor(request): loop = asyncio.get_event_loop() print("Loop: {0}".format(loop)) ex = ThreadPoolExecutor(max_workers=3) def on_stop(): ex.shutdown(wait=True) loop.close() print("done closing") loop.set_default_executor(ex) request.addfinalizer(on_stop) return ex @fixture def moving_avg(): <|code_end|> , generate the next line using the imports in this file: import sys import asyncio from concurrent.futures import ThreadPoolExecutor from pytest import fixture from .mocks import MockClient, MockTransport from oshino.augments.stats import SimpleMovingAverage and context (functions, classes, or occasionally code) from other files: # Path: tests/mocks.py # class MockClient(AugmentFixture): # # def __init__(self, transport=None): # self.events = [] # self.augments = {} # self.tasks = [] # self.transport = transport # # def event(self, **kwargs): # self.tasks.append(self.apply_augment(copy(kwargs))) # self.events.append(kwargs) # # def clear_queue(self): # self.events = [] # # def flush(self, transport): # response = transport.send(self.events) # self.clear_queue() # return response # # class MockTransport(BlankTransport): # # def __init__(self, host=None, port=None, broken=False): # self.connected = False # self.broken = broken # self.sneaky = False # # def connect(self): # if self.broken: # raise ConnectionRefusedError # self.connected = True # # def disconnect(self): # self.connected = False # # def send(self, message): # if self.broken or self.sneaky: # raise RiemannError # # return True # # Path: oshino/augments/stats.py # class SimpleMovingAverage(AugmentBase): # # def __init__(self, *args, **kwargs): # super(SimpleMovingAverage, self).__init__(*args, **kwargs) # self.dq = deque(maxlen=self.step) # # @property # def step(self): # return self._data.get("step", 5) # # def activate(self, client, g): # step = self.step # # stopped = False # while not stopped: # # try: # event = next(g) # self.dq.append(event) # except StopIteration: # stopped = True # break # # data = list(map(lambda x: x["metric_f"], list(self.dq))) # if len(data) == step: # output = sum(data) / len(data) # # self.send_event(client, # service=self.prefix + "value", # metric_f=output, # state="ok") . Output only the next line.
return SimpleMovingAverage({
Using the snippet: <|code_start|> logger = logging.getLogger(__name__) def with_retry(fn): def wrapper(*args, **kwargs): for i in range(0, 10): try: result = fn(*args, **kwargs) return result except Exception as ex: time.sleep(1) continue pytest.fail("Retry limit reached") return wrapper @with_retry def test_query_healthcheck(): <|code_end|> , determine the next line of code. You have imports: import time import logging import pytest import wait from riemann_client.client import Client from oshino.config import load and context (class names, function names, or code) available: # Path: oshino/config.py # def load(config_file): # """ # Processes and loads config file. # """ # with open(config_file, "r") as f: # # def env_get(): # return dict(os.environ) # tmpl = Template(f.read()) # return Config(yaml.safe_load(tmpl.render(**env_get()))) . Output only the next line.
cfg = load("config.yaml")
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__name__) try: load_dotenv(find_dotenv()) except Exception as ex: logger.error("Error while loading .env: '{}'. Ignoring.".format(ex)) def main(args): if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) <|code_end|> , predict the next line using imports from the current file: import logging from argparse import ArgumentParser from dotenv import load_dotenv, find_dotenv from .config import load from .core.heart import start_loop and context including class names, function names, and sometimes code from other files: # Path: oshino/config.py # def load(config_file): # """ # Processes and loads config file. # """ # with open(config_file, "r") as f: # # def env_get(): # return dict(os.environ) # tmpl = Template(f.read()) # return Config(yaml.safe_load(tmpl.render(**env_get()))) # # Path: oshino/core/heart.py # def start_loop(cfg: Config, noop=False): # logger.info("Initializing Oshino v{0}".format(get_version())) # logger.info("Running forever in {0} seconds interval. Press Ctrl+C to exit" # .format(cfg.interval)) # if cfg.sentry_dsn: # try: # client = SentryClient(cfg.sentry_dsn) # logging.root.handlers.append(SentryHandler(client, # level=logging.ERROR, # bubble=True)) # except InvalidDsn: # logger.warn("Invalid Sentry DSN '{0}' providen. Skipping" # .format(cfg.sentry_dsn)) # # # loop = create_loop() # try: # loop.run_until_complete(main_loop(cfg, # cfg.riemann.get_transport(noop), # forever, # loop=loop)) # finally: # loop.close() . Output only the next line.
cfg = load(args.config)
Using the snippet: <|code_start|> logger = logging.getLogger(__name__) try: load_dotenv(find_dotenv()) except Exception as ex: logger.error("Error while loading .env: '{}'. Ignoring.".format(ex)) def main(args): if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) cfg = load(args.config) <|code_end|> , determine the next line of code. You have imports: import logging from argparse import ArgumentParser from dotenv import load_dotenv, find_dotenv from .config import load from .core.heart import start_loop and context (class names, function names, or code) available: # Path: oshino/config.py # def load(config_file): # """ # Processes and loads config file. # """ # with open(config_file, "r") as f: # # def env_get(): # return dict(os.environ) # tmpl = Template(f.read()) # return Config(yaml.safe_load(tmpl.render(**env_get()))) # # Path: oshino/core/heart.py # def start_loop(cfg: Config, noop=False): # logger.info("Initializing Oshino v{0}".format(get_version())) # logger.info("Running forever in {0} seconds interval. Press Ctrl+C to exit" # .format(cfg.interval)) # if cfg.sentry_dsn: # try: # client = SentryClient(cfg.sentry_dsn) # logging.root.handlers.append(SentryHandler(client, # level=logging.ERROR, # bubble=True)) # except InvalidDsn: # logger.warn("Invalid Sentry DSN '{0}' providen. Skipping" # .format(cfg.sentry_dsn)) # # # loop = create_loop() # try: # loop.run_until_complete(main_loop(cfg, # cfg.riemann.get_transport(noop), # forever, # loop=loop)) # finally: # loop.close() . Output only the next line.
start_loop(cfg, args.noop)
Using the snippet: <|code_start|> def create_loop(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop def error_stub(): raise RuntimeError("Simply failing") @mark.integration @patch("oshino.core.heart.forever", lambda: False) @patch("oshino.core.heart.create_loop", create_loop) def test_startup(): args = argparse.Namespace(config="tests/data/test_config.yml", noop=True, debug=False) with raises(SystemExit): <|code_end|> , determine the next line of code. You have imports: import argparse import asyncio from pytest import mark, raises from oshino.run import main from mock import patch and context (class names, function names, or code) available: # Path: oshino/run.py # def main(args): # if args.debug: # logging.basicConfig(level=logging.DEBUG) # else: # logging.basicConfig(level=logging.INFO) # # cfg = load(args.config) # start_loop(cfg, args.noop) . Output only the next line.
main(args)
Based on the snippet: <|code_start|> class ConfigBase(object): """ Base config class """ def is_valid(self): return True class InstanceMixin(object): """ Mixin used for configs which are loaded dynamically """ @property def module(self): return self._data["module"] @property def instance(self): if self._instance is None: <|code_end|> , predict the immediate next line with the help of imports: import os import yaml import logging import riemann_client.transport from functools import partial from riemann_client.transport import BlankTransport, TLSTransport, TCPTransport from jinja2 import Template from .util import dynamic_import and context (classes, functions, sometimes code) from other files: # Path: oshino/util.py # def dynamic_import(path): # module, builder = path.rsplit(".", 1) # return getattr(__import__(module, fromlist=[builder]), builder) . Output only the next line.
self._instance = dynamic_import(self.module)(self._data)
Given snippet: <|code_start|> Fork responds to node names as functions. The function arguments are the same as node constructor (__init__ method) arguments. Each call will append new node to the fork and will connect the new node to the previous node in the fork. To configure current node you can use ``fork.node``, like:: fork.csv_source("fork.csv") fork.node.read_header = True To set actual node name use ``set_name()``:: fork.csv_source("fork.csv") fork.set_name("source") ... source_node = stream.node("source") To fork a fork, just call ``fork()`` """ return _StreamFork(self) def update(self, nodes = None, connections = None): """Adds nodes and connections specified in the dictionary. Dictionary might contain node names instead of real classes. You can use this method for creating stream from a dictionary that was created from a JSON file, for example. """ <|code_end|> , continue by predicting the next line. Consider current file imports: import threading import sys from brewery.nodes.base import node_dictionary, TargetNode, NodeFinished from brewery.utils import get_logger from brewery.nodes import * from brewery.common import * from .graph import * and context: # Path: brewery/nodes/base.py # def node_dictionary(): # """Return a dictionary containing node name as key and node class as # value. This will be depreciated soon in favour of # :func:`node_catalogue()`""" # # classes = node_subclasses(Node) # dictionary = {} # # for c in classes: # try: # name = c.identifier() # dictionary[name] = c # except AttributeError: # # If node does not provide identifier, we consider it to be # # private or abstract class # pass # # return dictionary # # class TargetNode(Node): # """Abstract class for all target nodes # # .. abstract_node # # """ # def __init__(self): # super(TargetNode, self).__init__() # self.fields = None # # @property # def output_fields(self): # raise RuntimeError("Output fields asked from a target object.") # # def add_output(self, pipe): # raise RuntimeError("Should not add output pipe to a target node") # # class NodeFinished(Exception): # """Exception raised when node has no active outputs - each output node signalised that it # requires no more data.""" # pass # # Path: brewery/utils.py # def get_logger(): # """Get brewery default logger""" # global logger # # if logger: # return logger # else: # return create_logger() which might include code, classes, or functions. Output only the next line.
node_dict = node_dictionary()
Continue the code snippet: <|code_start|> self.logger.info("initializing stream") self.logger.debug("sorting nodes") sorted_nodes = self.sorted_nodes() self.pipes = [] self.logger.debug("flushing pipes") for node in sorted_nodes: node.inputs = [] node.outputs = [] # Create pipes and connect nodes for node in sorted_nodes: self.logger.debug("creating pipes for node %s" % node) targets = self.node_targets(node) for target in targets: self.logger.debug(" connecting with %s" % (target)) pipe = Pipe() node.add_output(pipe) target.add_input(pipe) self.pipes.append(pipe) # Initialize fields for node in sorted_nodes: self.logger.debug("initializing node of type %s" % node.__class__) self.logger.debug(" node has %d inputs and %d outputs" % (len(node.inputs), len(node.outputs))) node.initialize() # Ignore target nodes <|code_end|> . Use current file imports: import threading import sys from brewery.nodes.base import node_dictionary, TargetNode, NodeFinished from brewery.utils import get_logger from brewery.nodes import * from brewery.common import * from .graph import * and context (classes, functions, or code) from other files: # Path: brewery/nodes/base.py # def node_dictionary(): # """Return a dictionary containing node name as key and node class as # value. This will be depreciated soon in favour of # :func:`node_catalogue()`""" # # classes = node_subclasses(Node) # dictionary = {} # # for c in classes: # try: # name = c.identifier() # dictionary[name] = c # except AttributeError: # # If node does not provide identifier, we consider it to be # # private or abstract class # pass # # return dictionary # # class TargetNode(Node): # """Abstract class for all target nodes # # .. abstract_node # # """ # def __init__(self): # super(TargetNode, self).__init__() # self.fields = None # # @property # def output_fields(self): # raise RuntimeError("Output fields asked from a target object.") # # def add_output(self, pipe): # raise RuntimeError("Should not add output pipe to a target node") # # class NodeFinished(Exception): # """Exception raised when node has no active outputs - each output node signalised that it # requires no more data.""" # pass # # Path: brewery/utils.py # def get_logger(): # """Get brewery default logger""" # global logger # # if logger: # return logger # else: # return create_logger() . Output only the next line.
if isinstance(node, TargetNode):
Next line prediction: <|code_start|> self.logger.debug("finalizing node %s" % node_label(node)) node.finalize() def node_label(node): """Debug label for a node: node identifier with python object id.""" return "%s(%s)" % (node.identifier() or str(type(node)), id(node)) class _StreamNodeThread(threading.Thread): def __init__(self, node): """Creates a stream node thread. :Attributes: * `node`: a Node object * `exception`: attribute will contain exception if one occurs during run() * `traceback`: will contain traceback if exception occurs """ super(_StreamNodeThread, self).__init__() self.node = node self.exception = None self.traceback = None self.logger = get_logger() def run(self): """Wrapper method for running a node""" label = node_label(self.node) self.logger.debug("%s: start" % label) try: self.node.run() <|code_end|> . Use current file imports: (import threading import sys from brewery.nodes.base import node_dictionary, TargetNode, NodeFinished from brewery.utils import get_logger from brewery.nodes import * from brewery.common import * from .graph import *) and context including class names, function names, or small code snippets from other files: # Path: brewery/nodes/base.py # def node_dictionary(): # """Return a dictionary containing node name as key and node class as # value. This will be depreciated soon in favour of # :func:`node_catalogue()`""" # # classes = node_subclasses(Node) # dictionary = {} # # for c in classes: # try: # name = c.identifier() # dictionary[name] = c # except AttributeError: # # If node does not provide identifier, we consider it to be # # private or abstract class # pass # # return dictionary # # class TargetNode(Node): # """Abstract class for all target nodes # # .. abstract_node # # """ # def __init__(self): # super(TargetNode, self).__init__() # self.fields = None # # @property # def output_fields(self): # raise RuntimeError("Output fields asked from a target object.") # # def add_output(self, pipe): # raise RuntimeError("Should not add output pipe to a target node") # # class NodeFinished(Exception): # """Exception raised when node has no active outputs - each output node signalised that it # requires no more data.""" # pass # # Path: brewery/utils.py # def get_logger(): # """Get brewery default logger""" # global logger # # if logger: # return logger # else: # return create_logger() . Output only the next line.
except NodeFinished:
Next line prediction: <|code_start|> return self._closed def done_sending(self): """Close pipe from sender side""" self._flush(True) def done_receiving(self): """Close pipe from either side""" self._note("C not_empty acq? r") self.not_empty.acquire() self._note("C closing") self._closed = True self._note("C notif close") self.not_full.notify() self.not_empty.release() self._note("C not_empty rel! r") class Stream(Graph): """Data processing stream""" def __init__(self, nodes=None, connections=None): """Creates a data stream. :Parameters: * `nodes` - dictionary with keys as node names and values as nodes * `connections` - list of two-item tuples. Each tuple contains source and target node or source and target node name. * `stream` - another stream or """ super(Stream, self).__init__(nodes, connections) <|code_end|> . Use current file imports: (import threading import sys from brewery.nodes.base import node_dictionary, TargetNode, NodeFinished from brewery.utils import get_logger from brewery.nodes import * from brewery.common import * from .graph import *) and context including class names, function names, or small code snippets from other files: # Path: brewery/nodes/base.py # def node_dictionary(): # """Return a dictionary containing node name as key and node class as # value. This will be depreciated soon in favour of # :func:`node_catalogue()`""" # # classes = node_subclasses(Node) # dictionary = {} # # for c in classes: # try: # name = c.identifier() # dictionary[name] = c # except AttributeError: # # If node does not provide identifier, we consider it to be # # private or abstract class # pass # # return dictionary # # class TargetNode(Node): # """Abstract class for all target nodes # # .. abstract_node # # """ # def __init__(self): # super(TargetNode, self).__init__() # self.fields = None # # @property # def output_fields(self): # raise RuntimeError("Output fields asked from a target object.") # # def add_output(self, pipe): # raise RuntimeError("Should not add output pipe to a target node") # # class NodeFinished(Exception): # """Exception raised when node has no active outputs - each output node signalised that it # requires no more data.""" # pass # # Path: brewery/utils.py # def get_logger(): # """Get brewery default logger""" # global logger # # if logger: # return logger # else: # return create_logger() . Output only the next line.
self.logger = get_logger()
Based on the snippet: <|code_start|> class Graph(object): """Data processing stream""" def __init__(self, nodes=None, connections=None): """Creates a node graph with connections. :Parameters: * `nodes` - dictionary with keys as node names and values as nodes * `connections` - list of two-item tuples. Each tuple contains source and target node or source and target node name. """ super(Graph, self).__init__() self.nodes = OrderedDict() self.connections = set() <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from brewery.utils import get_logger and context (classes, functions, sometimes code) from other files: # Path: brewery/utils.py # def get_logger(): # """Get brewery default logger""" # global logger # # if logger: # return logger # else: # return create_logger() . Output only the next line.
self.logger = get_logger()
Predict the next line after this snippet: <|code_start|> :Arguments: - `limit`: read only specified number of records from dataset to guess field properties - `collapse`: whether records are collapsed into flat structure or not Returns: tuple with Field objects. Order of fields is datastore adapter specific. """ keys = [] probes = {} def probe_record(record, parent = None): for key, value in record.items(): full_key = parent + "." + key if parent else key if self.expand and type(value) == dict: probe_record(value, full_key) continue if not full_key in probes: probe = brewery.dq.FieldTypeProbe(full_key) probes[full_key] = probe keys.append(full_key) else: probe = probes[full_key] probe.probe(value) count = 0 for record in self.records(): if collapse: <|code_end|> using the current file's imports: import urllib2 import urlparse import brewery.dq from brewery.metadata import collapse_record, Field and any relevant context from other files: # Path: brewery/metadata.py # def collapse_record(record, separator = '.', root = None): # """See :func:`brewery.expand_record` for reverse operation. # """ # # result = {} # for key, value in record.items(): # if root: # collapsed_key = root + separator + key # else: # collapsed_key = key # # if type(value) == dict: # collapsed = collapse_record(value, separator, collapsed_key) # result.update(collapsed) # else: # result[collapsed_key] = value # return result # # class Field(object): # """Metadata - information about a field in a dataset or in a datastream. # # :Attributes: # * `name` - field name # * `label` - optional human readable field label # * `storage_type` - Normalized data storage type. The data storage type # is abstracted # * `concrete_storage_type` (optional, recommended) - Data store/database # dependent storage type - this is the real name of data type as used # in a database where the field comes from or where the field is going # to be created (this might be null if unknown) # * `analytical_type` - data type used in data mining algorithms # * `missing_values` (optional) - Array of values that represent missing # values in the dataset for given field # """ # # def __init__(self, name, storage_type="unknown", # analytical_type="typeless", concrete_storage_type=None, # missing_values=None, label=None): # self.name = name # self.label = label # self.storage_type = storage_type # self.analytical_type = analytical_type # self.concrete_storage_type = concrete_storage_type # self.missing_values = missing_values # # def to_dict(self): # """Return dictionary representation of the field.""" # d = { # "name": self.name, # "label": self.label, # "storage_type": self.storage_type, # "analytical_type": self.analytical_type, # "concrete_storage_type": self.concrete_storage_type, # "missing_values": self.missing_values # } # return d # # def __str__(self): # """Return field name as field string representation.""" # # return self.name # # def __repr__(self): # return "<%s(%s)>" % (self.__class__, self.to_dict()) # # def __eq__(self, other): # if self is other: # return True # if self.name != other.name or self.label != other.label: # return False # elif self.storage_type != other.storage_type or self.analytical_type != other.analytical_type: # return False # elif self.concrete_storage_type != other.concrete_storage_type: # return False # elif self.missing_values != other.missing_values: # return False # else: # return True # # def __ne__(self,other): # return not self.__eq__(other) . Output only the next line.
record = collapse_record(record)
Next line prediction: <|code_start|> def probe_record(record, parent = None): for key, value in record.items(): full_key = parent + "." + key if parent else key if self.expand and type(value) == dict: probe_record(value, full_key) continue if not full_key in probes: probe = brewery.dq.FieldTypeProbe(full_key) probes[full_key] = probe keys.append(full_key) else: probe = probes[full_key] probe.probe(value) count = 0 for record in self.records(): if collapse: record = collapse_record(record) probe_record(record) if limit and count >= limit: break count += 1 fields = [] for key in keys: probe = probes[key] <|code_end|> . Use current file imports: (import urllib2 import urlparse import brewery.dq from brewery.metadata import collapse_record, Field) and context including class names, function names, or small code snippets from other files: # Path: brewery/metadata.py # def collapse_record(record, separator = '.', root = None): # """See :func:`brewery.expand_record` for reverse operation. # """ # # result = {} # for key, value in record.items(): # if root: # collapsed_key = root + separator + key # else: # collapsed_key = key # # if type(value) == dict: # collapsed = collapse_record(value, separator, collapsed_key) # result.update(collapsed) # else: # result[collapsed_key] = value # return result # # class Field(object): # """Metadata - information about a field in a dataset or in a datastream. # # :Attributes: # * `name` - field name # * `label` - optional human readable field label # * `storage_type` - Normalized data storage type. The data storage type # is abstracted # * `concrete_storage_type` (optional, recommended) - Data store/database # dependent storage type - this is the real name of data type as used # in a database where the field comes from or where the field is going # to be created (this might be null if unknown) # * `analytical_type` - data type used in data mining algorithms # * `missing_values` (optional) - Array of values that represent missing # values in the dataset for given field # """ # # def __init__(self, name, storage_type="unknown", # analytical_type="typeless", concrete_storage_type=None, # missing_values=None, label=None): # self.name = name # self.label = label # self.storage_type = storage_type # self.analytical_type = analytical_type # self.concrete_storage_type = concrete_storage_type # self.missing_values = missing_values # # def to_dict(self): # """Return dictionary representation of the field.""" # d = { # "name": self.name, # "label": self.label, # "storage_type": self.storage_type, # "analytical_type": self.analytical_type, # "concrete_storage_type": self.concrete_storage_type, # "missing_values": self.missing_values # } # return d # # def __str__(self): # """Return field name as field string representation.""" # # return self.name # # def __repr__(self): # return "<%s(%s)>" % (self.__class__, self.to_dict()) # # def __eq__(self, other): # if self is other: # return True # if self.name != other.name or self.label != other.label: # return False # elif self.storage_type != other.storage_type or self.analytical_type != other.analytical_type: # return False # elif self.concrete_storage_type != other.concrete_storage_type: # return False # elif self.missing_values != other.missing_values: # return False # else: # return True # # def __ne__(self,other): # return not self.__eq__(other) . Output only the next line.
field = Field(probe.field)
Here is a snippet: <|code_start|>RNNCell = tf.nn.rnn_cell.RNNCell LSTMStateTuple = tf.nn.rnn_cell.LSTMStateTuple def _conv2d(x, W, strides=None): if strides is None: strides = [1, 1] return tf.nn.conv2d(x, W, strides=[1] + strides + [1], padding="SAME") def dynamic_conv_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None): # inputs should have shape (time, batch, height, width, feature) <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from network.Util import smart_shape and context from other files: # Path: network/Util.py # def conv2d(x, W, strides=(1, 1), padding="SAME"): # def conv3d(x, W, strides=(1, 1), padding="SAME"): # def conv2d_transpose(x, W, strides=(1, 1), padding="SAME"): # def conv2d_dilated(x, W, dilation, padding="SAME"): # def create_batch_norm_vars(n_out, tower_setup, scope_name="bn"): # def get_activation(act_str): # def prepare_input(inputs): # def apply_dropout(inp, dropout): # def max_pool(x, shape, strides=None, padding="SAME"): # def max_pool3d(x, shape, strides=None, padding="SAME"): # def bootstrapped_ce_loss(raw_ce, fraction, n_valid_pixels_per_im): # def bootstrapped_ce_for_one_img(args): # def class_balanced_ce_loss(raw_ce, targets, n_classes): # def class_balanced_ce_for_one_img(args): , which may include functions, classes, or code. Output only the next line.
input_shape = smart_shape(inputs)
Given the following code snippet before the placeholder: <|code_start|> _registered_datasets = {} def register_dataset(name, **args): name = name.lower() def _register(dataset): _registered_datasets[name] = (dataset, args) return dataset return _register def load_dataset(config, subset, session, name): if not hasattr(load_dataset, "_imported"): load_dataset._imported = True <|code_end|> , predict the next line using imports from the current file: from core.Util import import_submodules and context including class names, function names, and sometimes code from other files: # Path: core/Util.py # def import_submodules(package_name): # package = sys.modules[package_name] # for importer, name, is_package in pkgutil.walk_packages(package.__path__): # # not sure why this check is necessary... # if not importer.path.startswith(package.__path__[0]): # continue # name_with_package = package_name + "." + name # importlib.import_module(name_with_package) # if is_package: # import_submodules(name_with_package) . Output only the next line.
import_submodules("datasets")
Predict the next line for this snippet: <|code_start|> DEFAULT_PATH = "/home/" + username() + "/data/KITTI_instance/" NAME = "KITTI_instance" @register_dataset(NAME) <|code_end|> with the help of current file imports: from datasets.Loader import register_dataset from datasets.Mapillary.MapillaryLike_instance import MapillaryLikeInstanceDataset from datasets.util.Util import username and context from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/Mapillary/MapillaryLike_instance.py # class MapillaryLikeInstanceDataset(FileListDataset): # def __init__(self, config, subset, name, default_path, data_list_path, id_divisor, cat_ids_to_use): # super().__init__(config, name, subset, default_path, NUM_CLASSES) # self.validation_set_size = self.config.int("validation_set_size", -1) # # note: in case of mapillary the min sizes are always based on the sizes in quarter resolution! # self.min_size = config.int("min_size", 0) # self._cat_ids_to_use = cat_ids_to_use # self._data_list_path = data_list_path # self._id_divisor = id_divisor # self.name = name # # def read_inputfile_lists(self): # data_list = "training.txt" if self.subset == "train" else "validation.txt" # print("{} ({}): using data_dir:".format(self.name, self.subset), self.data_dir, file=log.v5) # data_list = self._data_list_path + "/" + data_list # imgs_ans = [] # with open(data_list) as f: # for l in f: # im, an, *im_ids_and_sizes = l.strip().split() # im = self.data_dir + im # an = self.data_dir + an # for id_and_size in im_ids_and_sizes: # id_ = id_and_size.split(":")[0] # size_ = int(id_and_size.split(":")[1]) # if self.subset == "train" and size_ < self.min_size: # continue # cat_id = int(id_) // self._id_divisor # if self._cat_ids_to_use is not None and cat_id not in self._cat_ids_to_use: # continue # imgs_ans.append((im, an + ":" + id_)) # if self.subset == "train": # shuffle(imgs_ans) # elif self.validation_set_size != -1: # imgs_ans = imgs_ans[:self.validation_set_size] # imgs = [x[0] for x in imgs_ans] # ans = [x[1] for x in imgs_ans] # return imgs, ans # # def load_annotation(self, img, img_filename, annotation_filename): # annotation_filename_without_id = tf.string_split([annotation_filename], ':').values[0] # ann_data = tf.read_file(annotation_filename_without_id) # ann = tf.image.decode_png(ann_data, dtype=tf.uint16, channels=1) # ann.set_shape(img.get_shape().as_list()[:-1] + [1]) # ann = self.postproc_annotation(annotation_filename, ann) # return ann # # def postproc_annotation(self, ann_filename, ann): # id_str = tf.string_split([ann_filename], ':').values[1] # id_ = tf.string_to_number(id_str, out_type=tf.int32) # ann_postproc = tf.cast(tf.equal(tf.cast(ann, tf.int32), id_), tf.uint8) # return ann_postproc # # Path: datasets/util/Util.py # def username(): # return os.environ["USER"] , which may contain function names, class names, or code. Output only the next line.
class KittiInstanceDataset(MapillaryLikeInstanceDataset):
Predict the next line after this snippet: <|code_start|> def __init__(self, name, inputs, tower_setup, initial_weights, hack_gradient_magnitude=1.0): super().__init__() assert len(initial_weights) == len(inputs) with tf.variable_scope(name): initializer = tf.constant_initializer(initial_weights) weights = self.create_bias_variable("linear_combination_weights", len(inputs), tower_setup, initializer=initializer) if hack_gradient_magnitude > 1.0: # https://stackoverflow.com/a/43948872 @tf.custom_gradient def amplify_gradient_layer(x): def grad(dy): return hack_gradient_magnitude * dy return tf.identity(x), grad weights = amplify_gradient_layer(weights) y = inputs[0] * weights[0] for n in range(1, len(inputs)): y += inputs[n] * weights[n] self.outputs.append(y) for n in range(len(inputs)): self.add_scalar_summary(weights[n], "linear_combination_weights_" + str(n)) class NNUpsizing(Layer): output_layer = False def __init__(self, name, inputs, tower_setup, factor=2): super().__init__() with tf.variable_scope(name): <|code_end|> using the current file's imports: import tensorflow as tf from network.Layer import Layer from network.Util import prepare_input and any relevant context from other files: # Path: network/Layer.py # class Layer: # BATCH_NORM_DECAY_DEFAULT = 0.95 # BATCH_NORM_EPSILON = 1e-5 # L2_DEFAULT = 1e-4 # # def __init__(self): # self.summaries = [] # self.regularizers = [] # self.losses = [] # self.update_ops = [] # self.outputs = [] # self.placeholders = [] # self.measures = {} # self.extractions = {} # self.n_params = 0 # # def add_scalar_summary(self, op, name): # summary = tf.summary.scalar(name, op) # self.summaries.append(summary) # # def add_image_summary(self, im, name): # summary = tf.summary.image(name, im) # self.summaries.append(summary) # # def create_and_apply_batch_norm(self, inp, n_features, decay, tower_setup, scope_name="bn", freeze_batchnorm_override=None): # beta, gamma, moving_mean, moving_var = create_batch_norm_vars(n_features, tower_setup, scope_name) # self.n_params += 2 * n_features # if tower_setup.is_main_train_tower: # assert tower_setup.is_training # if tower_setup.is_training and\ # (not tower_setup.freeze_batchnorm or (freeze_batchnorm_override is not None and freeze_batchnorm_override)): # xn, batch_mean, batch_var = tf.nn.fused_batch_norm(inp, gamma, beta, epsilon=Layer.BATCH_NORM_EPSILON, # is_training=True) # if tower_setup.is_main_train_tower: # update_op1 = moving_averages.assign_moving_average( # moving_mean, batch_mean, decay, zero_debias=False, name='mean_ema_op') # update_op2 = moving_averages.assign_moving_average( # moving_var, batch_var, decay, zero_debias=False, name='var_ema_op') # self.update_ops.append(update_op1) # self.update_ops.append(update_op2) # return xn # else: # # According to the tensorpack code, this updates gamma and beta but not the moving averages # # Fused version should have better performance. # xn, _, _ = tf.nn.fused_batch_norm(inp, gamma, beta, moving_mean, moving_var, Layer.BATCH_NORM_EPSILON, is_training=False) # return xn # # def create_weight_variable(self, name, shape, l2, tower_setup, trainable=True, initializer=None): # with tf.device(tower_setup.variable_device): # if initializer is None: # # He initialization # initializer = tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False) # self.n_params += np.prod(shape) # if type(initializer) == np.ndarray: # W = tf.get_variable(name, dtype=tower_setup.dtype, initializer=initializer, trainable=trainable) # else: # W = tf.get_variable(name, shape, tower_setup.dtype, initializer, trainable=trainable) # if l2 > 0.0: # self.regularizers.append(l2 * tf.nn.l2_loss(W)) # if tower_setup.use_weight_summaries: # summ = tf.summary.histogram(name, W) # self.summaries.append(summ) # self.add_scalar_summary(tf.reduce_max(tf.abs(W)), name + "/W_abs_max") # return W # # def create_bias_variable(self, name, shape, tower_setup, trainable=True, initializer=None): # with tf.device(tower_setup.variable_device): # if initializer is None: # initializer = tf.constant_initializer(0.0, dtype=tower_setup.dtype) # self.n_params += np.prod(shape) # b = tf.get_variable(name, shape, tower_setup.dtype, initializer, trainable=trainable) # if tower_setup.use_weight_summaries: # summ = tf.summary.histogram(name, b) # self.summaries.append(summ) # self.add_scalar_summary(tf.reduce_max(tf.abs(b)), name + "/b_abs_max") # return b # # Path: network/Util.py # def prepare_input(inputs): # if len(inputs) == 1: # inp = inputs[0] # dim = int(inp.get_shape()[-1]) # else: # dims = [int(inp.get_shape()[3]) for inp in inputs] # dim = sum(dims) # inp = tf.concat(inputs, axis=3) # return inp, dim . Output only the next line.
inp, dim = prepare_input(inputs)
Predict the next line after this snippet: <|code_start|> NUM_CLASSES = 2 class MapillaryLikeInstanceDataset(FileListDataset): def __init__(self, config, subset, name, default_path, data_list_path, id_divisor, cat_ids_to_use): super().__init__(config, name, subset, default_path, NUM_CLASSES) self.validation_set_size = self.config.int("validation_set_size", -1) # note: in case of mapillary the min sizes are always based on the sizes in quarter resolution! self.min_size = config.int("min_size", 0) self._cat_ids_to_use = cat_ids_to_use self._data_list_path = data_list_path self._id_divisor = id_divisor self.name = name def read_inputfile_lists(self): data_list = "training.txt" if self.subset == "train" else "validation.txt" <|code_end|> using the current file's imports: from random import shuffle from datasets.Dataset import FileListDataset from core.Log import log import tensorflow as tf and any relevant context from other files: # Path: datasets/Dataset.py # class FileListDataset(AbstractDataset): # def __init__(self, config, dataset_name, subset, default_path, num_classes): # super().__init__(config, subset, num_classes) # self.inputfile_lists = None # self.fraction = config.float("data_fraction", 1.0) # self.data_dir = config.string(dataset_name + "_data_dir", default_path) # self._num_parallel_calls = config.int("num_parallel_calls", 32) # self._prefetch_buffer_size = config.int("prefetch_buffer_size", 20) # # def _load_inputfile_lists(self): # if self.inputfile_lists is not None: # return # self.inputfile_lists = self.read_inputfile_lists() # assert len(self.inputfile_lists) > 0 # for l in self.inputfile_lists: # assert len(l) > 0 # # make sure all lists have the same length # assert all([len(l) == len(self.inputfile_lists[0]) for l in self.inputfile_lists]) # if self.fraction < 1.0: # n = int(self.fraction * len(self.inputfile_lists[0])) # self.inputfile_lists = tuple([l[:n] for l in self.inputfile_lists]) # # def n_examples_per_epoch(self): # self._load_inputfile_lists() # n_examples = super().n_examples_per_epoch() # if n_examples is None: # return len(self.inputfile_lists[0]) # else: # return n_examples # # def create_input_tensors_dict(self, batch_size): # self._load_inputfile_lists() # if self.subset == "train": # # shuffle lists together, for this zip, shuffle, and unzip # zipped = list(zip(*self.inputfile_lists)) # shuffle(zipped) # inputfile_lists_shuffled = tuple([x[idx] for x in zipped] for idx in range(len(self.inputfile_lists))) # else: # inputfile_lists_shuffled = self.inputfile_lists # tfdata = tf.data.Dataset.from_tensor_slices(inputfile_lists_shuffled) # if self.subset == "train": # tfdata = tfdata.shuffle(buffer_size=self.shuffle_buffer_size) # # def _load_example(*input_filenames): # example = self.load_example(input_filenames) # # this has different sizes and therefore cannot be batched # if batch_size > 1: # if DataKeys.SEGMENTATION_LABELS_ORIGINAL_SIZE in example: # del example[DataKeys.SEGMENTATION_LABELS_ORIGINAL_SIZE] # if DataKeys.RAW_IMAGES in example: # del example[DataKeys.RAW_IMAGES] # return example # # def _filter_example(tensors): # if DataKeys.SKIP_EXAMPLE in tensors: # return tf.logical_not(tensors[DataKeys.SKIP_EXAMPLE]) # else: # return tf.constant(True) # # tfdata = tfdata.map(_load_example, num_parallel_calls=self._num_parallel_calls) # tfdata = tfdata.filter(_filter_example) # tfdata = tfdata.repeat() # tfdata = self._batch(tfdata, batch_size) # tfdata = tfdata.prefetch(buffer_size=self._prefetch_buffer_size) # # TODO: maybe we can improve the performance like this # #tf.contrib.data.prefetch_to_device("/gpu:0", self._prefetch_buffer_size) # res = tfdata.make_one_shot_iterator().get_next() # # if self.use_summaries: # self.create_summaries(res) # return res # # def _batch(self, tfdata, batch_size): # if batch_size > 1: # tfdata = tfdata.batch(batch_size, drop_remainder=True) # elif batch_size == 1: # # like this we are able to retain the batch size in the shape information # tfdata = tfdata.map(lambda x: {k: tf.expand_dims(v, axis=0) for k, v in x.items()}) # else: # assert False, ("invalid batch size", batch_size) # return tfdata # # # Override to add extraction keys that will be used by trainer. # def get_extraction_keys(self): # return [] # # @abstractmethod # def read_inputfile_lists(self): # raise NotImplementedError # # Path: core/Log.py # class Stream: # class Log(object): # def __init__(self, log, lvl): # def write(self, msg): # def flush(self): # def initialize(self, logs=[], verbosity=[], formatter=[]): # def write(self, msg): . Output only the next line.
print("{} ({}): using data_dir:".format(self.name, self.subset), self.data_dir, file=log.v5)
Given the code snippet: <|code_start|> class FeedDataset(AbstractDataset): def __init__(self, config, subset, data_keys_to_use, num_classes=2): super().__init__(config, subset, num_classes) self._data_keys_to_use = data_keys_to_use self._batch_size = -1 if subset == "val": self._batch_size = config.int("batch_size_val", -1) if self._batch_size == -1: self._batch_size = config.int("batch_size_eval", -1) if self._batch_size == -1: self._batch_size = config.int("batch_size") self._placeholders = self._create_placeholders() def get_batch_size(self): return self._batch_size def _create_placeholders(self): dtypes_and_shapes = { <|code_end|> , generate the next line using the imports in this file: from abc import abstractmethod from datasets.Dataset import AbstractDataset, DataKeys import tensorflow as tf and context (functions, classes, or occasionally code) from other files: # Path: datasets/Dataset.py # class AbstractDataset(ABC): # class FileListDataset(AbstractDataset): # def __init__(self, config, subset, num_classes): # def n_examples_per_epoch(self): # def create_input_tensors_dict(self, batch_size): # def num_classes(self): # def load_example(self, input_filenames): # def process_raw_example(self, example): # def load_raw_example(self, img_filename, label_filename=None, *args): # def load_image(self, img_filename): # def load_annotation(self, img, img_filename, annotation_filename): # def postproc_annotation(self, ann_filename, ann): # def resize_example(self, tensors): # def jointly_resize_examples(self, tensors_batch): # def augment_example_before_resize(self, tensors): # def augment_example_after_resize(self, tensors): # def jointly_augment_examples_before_resize(self, tensors_batch): # def jointly_augment_examples_after_resize(self, tensors_batch): # def postproc_example_initial(self, tensors): # def postproc_example_before_assembly(self, tensors): # def postproc_example_before_resize(self, tensors): # def assemble_example(self, tensors): # def create_summaries(self, data): # def __init__(self, config, dataset_name, subset, default_path, num_classes): # def _load_inputfile_lists(self): # def n_examples_per_epoch(self): # def create_input_tensors_dict(self, batch_size): # def _load_example(*input_filenames): # def _filter_example(tensors): # def _batch(self, tfdata, batch_size): # def get_extraction_keys(self): # def read_inputfile_lists(self): . Output only the next line.
DataKeys.IMAGES: (tf.float32, (None, None, 3)),
Next line prediction: <|code_start|> class Augmentor: def apply_before_resize(self, tensors): return tensors def apply_after_resize(self, tensors): return tensors def batch_apply_before_resize(self, tensors_batch): return tensors_batch def batch_apply_after_resize(self, tensors_batch): return tensors_batch class GammaAugmentor(Augmentor): def __init__(self, gamma_range=(-0.1, 0.1)): self.gamma_range = gamma_range def apply_after_resize(self, tensors, factor=None): """ Augments the images. Expects it to be in the [0, 1] range """ with tf.name_scope('gamma_augmentor'): <|code_end|> . Use current file imports: (import tensorflow as tf import math from datasets import DataKeys from core.Log import log from datasets.util.Util import flip_coords_horizontal_y0x0y1x1, flip_coords_horizontal_x0y0x1y1) and context including class names, function names, or small code snippets from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: core/Log.py # class Stream: # class Log(object): # def __init__(self, log, lvl): # def write(self, msg): # def flush(self): # def initialize(self, logs=[], verbosity=[], formatter=[]): # def write(self, msg): # # Path: datasets/util/Util.py # def flip_coords_horizontal_y0x0y1x1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([tensor[..., 0], original_width_f - tensor[..., 3], tensor[..., 2], # original_width_f - tensor[..., 1]], axis=-1) # # def flip_coords_horizontal_x0y0x1y1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([original_width_f - tensor[..., 2], tensor[..., 1], original_width_f - tensor[..., 0], # tensor[..., 3]], axis=-1) . Output only the next line.
img = tensors[DataKeys.IMAGES]
Based on the snippet: <|code_start|> class Augmentor: def apply_before_resize(self, tensors): return tensors def apply_after_resize(self, tensors): return tensors def batch_apply_before_resize(self, tensors_batch): return tensors_batch def batch_apply_after_resize(self, tensors_batch): return tensors_batch class GammaAugmentor(Augmentor): def __init__(self, gamma_range=(-0.1, 0.1)): self.gamma_range = gamma_range def apply_after_resize(self, tensors, factor=None): """ Augments the images. Expects it to be in the [0, 1] range """ with tf.name_scope('gamma_augmentor'): img = tensors[DataKeys.IMAGES] # Sample a gamma factor if factor is None: factor = self._sample_factor() <|code_end|> , predict the immediate next line with the help of imports: import tensorflow as tf import math from datasets import DataKeys from core.Log import log from datasets.util.Util import flip_coords_horizontal_y0x0y1x1, flip_coords_horizontal_x0y0x1y1 and context (classes, functions, sometimes code) from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: core/Log.py # class Stream: # class Log(object): # def __init__(self, log, lvl): # def write(self, msg): # def flush(self): # def initialize(self, logs=[], verbosity=[], formatter=[]): # def write(self, msg): # # Path: datasets/util/Util.py # def flip_coords_horizontal_y0x0y1x1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([tensor[..., 0], original_width_f - tensor[..., 3], tensor[..., 2], # original_width_f - tensor[..., 1]], axis=-1) # # def flip_coords_horizontal_x0y0x1y1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([original_width_f - tensor[..., 2], tensor[..., 1], original_width_f - tensor[..., 0], # tensor[..., 3]], axis=-1) . Output only the next line.
gamma = tf.log(0.5 + 1 / math.sqrt(2) * factor) / tf.log(0.5 - 1 / math.sqrt(2) * factor)
Continue the code snippet: <|code_start|> return aug_tensors def _sample_factor(self): return tf.random_uniform(shape=[], minval=self.gamma_range[0], maxval=self.gamma_range[1], dtype=tf.float32) def batch_apply_after_resize(self, tensors_batch): factor = self._sample_factor() return [self.apply_after_resize(x, factor) for x in tensors_batch] class FlipAugmentor(Augmentor): def __init__(self, p=0.5): """ :param p: The probability that the image will be flipped. """ self.p = p def apply_after_resize(self, tensors, doit=None): with tf.name_scope("flip_augmentor"): aug_tensors = tensors.copy() if doit is None: doit = self._sample_doit() def maybe_flip(key_, image_flip, y0x0y1x1=False): if key_ in tensors: val = tensors[key_] if image_flip: flipped = tf.image.flip_left_right(val) elif y0x0y1x1: <|code_end|> . Use current file imports: import tensorflow as tf import math from datasets import DataKeys from core.Log import log from datasets.util.Util import flip_coords_horizontal_y0x0y1x1, flip_coords_horizontal_x0y0x1y1 and context (classes, functions, or code) from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: core/Log.py # class Stream: # class Log(object): # def __init__(self, log, lvl): # def write(self, msg): # def flush(self): # def initialize(self, logs=[], verbosity=[], formatter=[]): # def write(self, msg): # # Path: datasets/util/Util.py # def flip_coords_horizontal_y0x0y1x1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([tensor[..., 0], original_width_f - tensor[..., 3], tensor[..., 2], # original_width_f - tensor[..., 1]], axis=-1) # # def flip_coords_horizontal_x0y0x1y1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([original_width_f - tensor[..., 2], tensor[..., 1], original_width_f - tensor[..., 0], # tensor[..., 3]], axis=-1) . Output only the next line.
flipped = flip_coords_horizontal_y0x0y1x1(val, tf.shape(tensors[DataKeys.IMAGES])[1])
Predict the next line for this snippet: <|code_start|> def _sample_factor(self): return tf.random_uniform(shape=[], minval=self.gamma_range[0], maxval=self.gamma_range[1], dtype=tf.float32) def batch_apply_after_resize(self, tensors_batch): factor = self._sample_factor() return [self.apply_after_resize(x, factor) for x in tensors_batch] class FlipAugmentor(Augmentor): def __init__(self, p=0.5): """ :param p: The probability that the image will be flipped. """ self.p = p def apply_after_resize(self, tensors, doit=None): with tf.name_scope("flip_augmentor"): aug_tensors = tensors.copy() if doit is None: doit = self._sample_doit() def maybe_flip(key_, image_flip, y0x0y1x1=False): if key_ in tensors: val = tensors[key_] if image_flip: flipped = tf.image.flip_left_right(val) elif y0x0y1x1: flipped = flip_coords_horizontal_y0x0y1x1(val, tf.shape(tensors[DataKeys.IMAGES])[1]) else: <|code_end|> with the help of current file imports: import tensorflow as tf import math from datasets import DataKeys from core.Log import log from datasets.util.Util import flip_coords_horizontal_y0x0y1x1, flip_coords_horizontal_x0y0x1y1 and context from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: core/Log.py # class Stream: # class Log(object): # def __init__(self, log, lvl): # def write(self, msg): # def flush(self): # def initialize(self, logs=[], verbosity=[], formatter=[]): # def write(self, msg): # # Path: datasets/util/Util.py # def flip_coords_horizontal_y0x0y1x1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([tensor[..., 0], original_width_f - tensor[..., 3], tensor[..., 2], # original_width_f - tensor[..., 1]], axis=-1) # # def flip_coords_horizontal_x0y0x1y1(tensor, original_width): # original_width_f = tf.cast(original_width, tensor.dtype) # return tf.stack([original_width_f - tensor[..., 2], tensor[..., 1], original_width_f - tensor[..., 0], # tensor[..., 3]], axis=-1) , which may contain function names, class names, or code. Output only the next line.
flipped = flip_coords_horizontal_x0y0x1y1(val, tf.shape(tensors[DataKeys.IMAGES])[1])
Based on the snippet: <|code_start|> NAME = "MOTS_challenge_feed_test" DEFAULT_PATH = "/globalwork/voigtlaender/data/MOTS_challenge/test/" SEQ_IDS_TRAIN = [] SEQ_IDS_VAL = ["%04d" % idx for idx in [1, 6, 7, 12]] TIMESTEPS_PER_SEQ = {"0001": 450, "0006": 1194, "0007": 500, "0012": 900} <|code_end|> , predict the immediate next line with the help of imports: import glob from datasets.Loader import register_dataset from datasets.KITTI.segtrack.KITTI_segtrack_feed import KittiSegtrackLikeFeedDataset and context (classes, functions, sometimes code) from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/KITTI/segtrack/KITTI_segtrack_feed.py # class KittiSegtrackLikeFeedDataset(FeedDataset): # def __init__(self, config, subset, dataset_name, default_path, seq_ids_train, seq_ids_val, preload_images): # super().__init__(config, subset, data_keys_to_use=DATA_KEYS_TO_USE, num_classes=NUM_CLASSES) # self.time_starts_at_1 = False # self.data_dir = config.string(dataset_name + "_data_dir", default_path) # video_tags_config = config.string_list("video_tags_to_load", []) # if len(video_tags_config) > 0: # self._video_tags = video_tags_config # else: # if self.subset == "train": # self._video_tags = seq_ids_train # else: # self._video_tags = seq_ids_val # self._video_idx = None # self._imgs = None # self._curr_time = None # self._filenames = None # self._preload_images = preload_images # init_anchors(config) # # This is somewhat hacky # self._num_context_frames = 0 # if self.config.bool("offset_matching", False): # self._num_context_frames = self.config.int("num_space_time_targets", 1) # print("Supplying", self._num_context_frames, "context frames so actual batch size will decrease") # # def set_video_idx(self, idx): # self._curr_time = 0 # if self._video_idx == idx: # return # self._video_idx = idx # self._filenames = self.get_filenames_for_video_idx(idx) # if self.config.bool("short_videos_for_testing", False): # print("Warning, shortening video to 2 frames for testing", file=log.v1) # self._filenames = self._filenames[:2] # if self._preload_images: # print("loading images for seq", self.get_video_tag(), file=log.v5) # with Pool(8) as pool: # self._imgs = pool.map(_load_img, self._filenames) # print("done", file=log.v5) # # @abstractmethod # def get_filenames_for_video_idx(self, idx): # raise NotImplementedError # # def n_videos(self): # return len(self._video_tags) # # def n_examples_per_epoch(self): # assert self._video_idx is not None # return len(self._filenames) # # def get_video_tag(self): # assert self._video_idx is not None # return self._video_tags[self._video_idx] # # def get_feed_dict_for_next_step(self): # assert self._video_idx is not None # feed_dict = {} # for idx in range(self._batch_size): # if self._curr_time > 0: # time_idx = self._curr_time - self._num_context_frames + idx # else: # time_idx = self._curr_time + idx # # On the last batch, repeat the final image to fill up batch # if time_idx >= len(self._filenames): # time_idx = len(self._filenames) - 1 # if self._preload_images: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = self._imgs[time_idx] # else: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = _load_img(self._filenames[time_idx]) # feed_dict[self._placeholders[DataKeys.IMAGE_FILENAMES][idx]] = self._filenames[time_idx] # self._curr_time += self._batch_size - self._num_context_frames # return feed_dict . Output only the next line.
@register_dataset(NAME)
Based on the snippet: <|code_start|> NAME = "MOTS_challenge_feed_test" DEFAULT_PATH = "/globalwork/voigtlaender/data/MOTS_challenge/test/" SEQ_IDS_TRAIN = [] SEQ_IDS_VAL = ["%04d" % idx for idx in [1, 6, 7, 12]] TIMESTEPS_PER_SEQ = {"0001": 450, "0006": 1194, "0007": 500, "0012": 900} @register_dataset(NAME) <|code_end|> , predict the immediate next line with the help of imports: import glob from datasets.Loader import register_dataset from datasets.KITTI.segtrack.KITTI_segtrack_feed import KittiSegtrackLikeFeedDataset and context (classes, functions, sometimes code) from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/KITTI/segtrack/KITTI_segtrack_feed.py # class KittiSegtrackLikeFeedDataset(FeedDataset): # def __init__(self, config, subset, dataset_name, default_path, seq_ids_train, seq_ids_val, preload_images): # super().__init__(config, subset, data_keys_to_use=DATA_KEYS_TO_USE, num_classes=NUM_CLASSES) # self.time_starts_at_1 = False # self.data_dir = config.string(dataset_name + "_data_dir", default_path) # video_tags_config = config.string_list("video_tags_to_load", []) # if len(video_tags_config) > 0: # self._video_tags = video_tags_config # else: # if self.subset == "train": # self._video_tags = seq_ids_train # else: # self._video_tags = seq_ids_val # self._video_idx = None # self._imgs = None # self._curr_time = None # self._filenames = None # self._preload_images = preload_images # init_anchors(config) # # This is somewhat hacky # self._num_context_frames = 0 # if self.config.bool("offset_matching", False): # self._num_context_frames = self.config.int("num_space_time_targets", 1) # print("Supplying", self._num_context_frames, "context frames so actual batch size will decrease") # # def set_video_idx(self, idx): # self._curr_time = 0 # if self._video_idx == idx: # return # self._video_idx = idx # self._filenames = self.get_filenames_for_video_idx(idx) # if self.config.bool("short_videos_for_testing", False): # print("Warning, shortening video to 2 frames for testing", file=log.v1) # self._filenames = self._filenames[:2] # if self._preload_images: # print("loading images for seq", self.get_video_tag(), file=log.v5) # with Pool(8) as pool: # self._imgs = pool.map(_load_img, self._filenames) # print("done", file=log.v5) # # @abstractmethod # def get_filenames_for_video_idx(self, idx): # raise NotImplementedError # # def n_videos(self): # return len(self._video_tags) # # def n_examples_per_epoch(self): # assert self._video_idx is not None # return len(self._filenames) # # def get_video_tag(self): # assert self._video_idx is not None # return self._video_tags[self._video_idx] # # def get_feed_dict_for_next_step(self): # assert self._video_idx is not None # feed_dict = {} # for idx in range(self._batch_size): # if self._curr_time > 0: # time_idx = self._curr_time - self._num_context_frames + idx # else: # time_idx = self._curr_time + idx # # On the last batch, repeat the final image to fill up batch # if time_idx >= len(self._filenames): # time_idx = len(self._filenames) - 1 # if self._preload_images: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = self._imgs[time_idx] # else: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = _load_img(self._filenames[time_idx]) # feed_dict[self._placeholders[DataKeys.IMAGE_FILENAMES][idx]] = self._filenames[time_idx] # self._curr_time += self._batch_size - self._num_context_frames # return feed_dict . Output only the next line.
class MOTSSegtrackFeedDataset(KittiSegtrackLikeFeedDataset):
Using the snippet: <|code_start|> NAME = "Mapillary_detection" DATA_LIST_PATH = "datasets/Mapillary/" DEFAULT_PATH = "/fastwork/" + username() + "/mywork/data/mapillary_quarter/" N_MAX_DETECTIONS = 300 ID_DIVISOR = 256 CLASS_IDS_WITH_INSTANCES = [0, 1, 8, 19, 20, 21, 22, 23, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 60, 61, 62] NUM_CLASSES = len(CLASS_IDS_WITH_INSTANCES) + 1 <|code_end|> , determine the next line of code. You have imports: from datasets.Loader import register_dataset from datasets.DetectionDataset import MapillaryLikeDetectionFileListDataset from datasets.util.Util import username and context (class names, function names, or code) available: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/DetectionDataset.py # class MapillaryLikeDetectionFileListDataset(DetectionFileListDataset): # def __init__(self, config, dataset_name, subset, default_path, num_classes, n_max_detections, # class_ids_with_instances, id_divisor, crowd_id=None): # super().__init__(config, dataset_name, subset, default_path, num_classes) # self._n_max_detections = n_max_detections # self._class_ids_with_instances = class_ids_with_instances # self._id_divisor = id_divisor # self._crowd_id = crowd_id # # self._preload_dataset = config.bool("preload_dataset", False) # if self._preload_dataset: # print("Preloading ENTIRE!!! dataset into memory!!!", file=log.v1) # imgs, anns = self.read_inputfile_lists() # self.imgs_preload_dict = {img_filename: np.array(Image.open(img_filename), dtype=np.float32) / 255.0 # for img_filename in imgs} # self.anns_preload_dict = {ann_filename: np.array(Image.open(ann_filename)) for ann_filename in anns} # self._load_ann_np = self._anns_preload_dict_lookup # else: # self._load_ann_np = partial(load_instance_seg_annotation_np, n_max_detections=self._n_max_detections, # class_ids_with_instances=self._class_ids_with_instances, id_divisor=self._id_divisor, # crowd_id=self._crowd_id) # # def _anns_preload_dict_lookup(self, ann_filename): # ann_filename = ann_filename.decode("utf-8") # ann = self.anns_preload_dict[ann_filename] # return load_instance_seg_annotation_from_img_array_np(ann, n_max_detections=self._n_max_detections, # class_ids_with_instances=self._class_ids_with_instances, id_divisor=self._id_divisor, # crowd_id=self._crowd_id) # # def _imgs_preload_dict_lookup(self, img_filename): # img_filename = img_filename.decode("utf-8") # img = self.imgs_preload_dict[img_filename] # return img # # def load_image(self, img_filename): # if self._preload_dataset: # img = tf.py_func(self._imgs_preload_dict_lookup, [img_filename], tf.float32, name="imgs_preload_dict_lookup_np") # img.set_shape((None, None, 3)) # else: # img = super(MapillaryLikeDetectionFileListDataset, self).load_image(img_filename) # return img # # def load_annotation(self, img, img_filename, annotation_filename): # bboxes, ids, classes, is_crowd, mask = tf.py_func(self._load_ann_np, [annotation_filename], # [tf.float32, tf.int32, tf.int32, tf.int32, tf.uint8], # name="postproc_ann_np") # bboxes.set_shape((self._n_max_detections, 4)) # ids.set_shape((self._n_max_detections,)) # classes.set_shape((self._n_max_detections,)) # is_crowd.set_shape((self._n_max_detections,)) # mask.set_shape((None, None, self._n_max_detections)) # # return_dict = {DataKeys.BBOXES_y0x0y1x1: bboxes, DataKeys.CLASSES: classes, DataKeys.IDS: ids, # DataKeys.IS_CROWD: is_crowd} # if self.add_masks: # return_dict[DataKeys.SEGMENTATION_MASK] = mask # return_dict = self.postproc_annotation(annotation_filename, return_dict) # return return_dict # # Path: datasets/util/Util.py # def username(): # return os.environ["USER"] . Output only the next line.
@register_dataset(NAME)
Continue the code snippet: <|code_start|> NAME = "Mapillary_detection" DATA_LIST_PATH = "datasets/Mapillary/" DEFAULT_PATH = "/fastwork/" + username() + "/mywork/data/mapillary_quarter/" N_MAX_DETECTIONS = 300 ID_DIVISOR = 256 CLASS_IDS_WITH_INSTANCES = [0, 1, 8, 19, 20, 21, 22, 23, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 60, 61, 62] NUM_CLASSES = len(CLASS_IDS_WITH_INSTANCES) + 1 @register_dataset(NAME) <|code_end|> . Use current file imports: from datasets.Loader import register_dataset from datasets.DetectionDataset import MapillaryLikeDetectionFileListDataset from datasets.util.Util import username and context (classes, functions, or code) from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/DetectionDataset.py # class MapillaryLikeDetectionFileListDataset(DetectionFileListDataset): # def __init__(self, config, dataset_name, subset, default_path, num_classes, n_max_detections, # class_ids_with_instances, id_divisor, crowd_id=None): # super().__init__(config, dataset_name, subset, default_path, num_classes) # self._n_max_detections = n_max_detections # self._class_ids_with_instances = class_ids_with_instances # self._id_divisor = id_divisor # self._crowd_id = crowd_id # # self._preload_dataset = config.bool("preload_dataset", False) # if self._preload_dataset: # print("Preloading ENTIRE!!! dataset into memory!!!", file=log.v1) # imgs, anns = self.read_inputfile_lists() # self.imgs_preload_dict = {img_filename: np.array(Image.open(img_filename), dtype=np.float32) / 255.0 # for img_filename in imgs} # self.anns_preload_dict = {ann_filename: np.array(Image.open(ann_filename)) for ann_filename in anns} # self._load_ann_np = self._anns_preload_dict_lookup # else: # self._load_ann_np = partial(load_instance_seg_annotation_np, n_max_detections=self._n_max_detections, # class_ids_with_instances=self._class_ids_with_instances, id_divisor=self._id_divisor, # crowd_id=self._crowd_id) # # def _anns_preload_dict_lookup(self, ann_filename): # ann_filename = ann_filename.decode("utf-8") # ann = self.anns_preload_dict[ann_filename] # return load_instance_seg_annotation_from_img_array_np(ann, n_max_detections=self._n_max_detections, # class_ids_with_instances=self._class_ids_with_instances, id_divisor=self._id_divisor, # crowd_id=self._crowd_id) # # def _imgs_preload_dict_lookup(self, img_filename): # img_filename = img_filename.decode("utf-8") # img = self.imgs_preload_dict[img_filename] # return img # # def load_image(self, img_filename): # if self._preload_dataset: # img = tf.py_func(self._imgs_preload_dict_lookup, [img_filename], tf.float32, name="imgs_preload_dict_lookup_np") # img.set_shape((None, None, 3)) # else: # img = super(MapillaryLikeDetectionFileListDataset, self).load_image(img_filename) # return img # # def load_annotation(self, img, img_filename, annotation_filename): # bboxes, ids, classes, is_crowd, mask = tf.py_func(self._load_ann_np, [annotation_filename], # [tf.float32, tf.int32, tf.int32, tf.int32, tf.uint8], # name="postproc_ann_np") # bboxes.set_shape((self._n_max_detections, 4)) # ids.set_shape((self._n_max_detections,)) # classes.set_shape((self._n_max_detections,)) # is_crowd.set_shape((self._n_max_detections,)) # mask.set_shape((None, None, self._n_max_detections)) # # return_dict = {DataKeys.BBOXES_y0x0y1x1: bboxes, DataKeys.CLASSES: classes, DataKeys.IDS: ids, # DataKeys.IS_CROWD: is_crowd} # if self.add_masks: # return_dict[DataKeys.SEGMENTATION_MASK] = mask # return_dict = self.postproc_annotation(annotation_filename, return_dict) # return return_dict # # Path: datasets/util/Util.py # def username(): # return os.environ["USER"] . Output only the next line.
class MapillaryDetectionDataset(MapillaryLikeDetectionFileListDataset):
Predict the next line after this snippet: <|code_start|> class BboxDetectionRefinementForwarder(Forwarder): def __init__(self, engine): super().__init__(engine) self.model_name = self.config.string("model") def forward(self): out_folder = "forwarded/" + self.model_name + "/detection_bbox_refined/" tf.gfile.MakeDirs(out_folder) data = self.val_data n_examples_per_epoch = data.n_examples_per_epoch() <|code_end|> using the current file's imports: import pycocotools.mask as cocomask import numpy as np import tensorflow as tf from core import Extractions from datasets import DataKeys from forwarding.Forwarder import Forwarder from forwarding.tracking.TrackingForwarder_util import export_detections_for_sequence from datasets.KITTI.segtrack.KITTI_MOTS_info import SEQ_IDS_VAL and any relevant context from other files: # Path: core/Extractions.py # EXTRACTIONS = "extractions" # CLASS_POSTERIORS = "class_posteriors" # SEGMENTATION_POSTERIORS = "segmentation_posteriors" # SEGMENTATION_MASK_ORIGINAL_SIZE = "segmentation_mask_original_size" # SEGMENTATION_MASK_INPUT_SIZE = "segmentation_mask_input_size" # RECURRENT_STATE = "recurrent_state" # REID_FEATURES = "reid_features" # DET_BOXES = "det_boxes" # DET_PROBS = "det_probs" # DET_LABELS = "det_labels" # DET_MASKS = "det_masks" # IMAGE_ID = "img_id" # CUSTOM_STRING = "custom_string" # PRED_SPACE_TIME_OFFSETS = "pred_space_time_offsets" # PIXEL_POSITIONS = "pixel_positions" # FEATUREMAP_SIZE = "featuremap_size" # def accumulate_extractions(extractions_accumulator, *new_extractions): # def extract_batch_size_1(extractions, key): # # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: forwarding/Forwarder.py # class Forwarder(ABC): # def __init__(self, engine): # self.engine = engine # self.config = engine.config # self.session = engine.session # self.val_data = self.engine.valid_data # self.train_data = self.engine.train_data # self.trainer = self.engine.trainer # self.saver = self.engine.saver # # @abstractmethod # def forward(self): # pass # # Path: forwarding/tracking/TrackingForwarder_util.py # def export_detections_for_sequence(tag, boxes, scores, reids, classes, masks, model_str, epoch, add_masks, out_folder=""): # if out_folder == "": # out_folder = "forwarded/" + model_str + "/detections/" + str(epoch) # os.makedirs(out_folder, exist_ok=True) # out_filename = out_folder + "/" + tag + ".txt" # with open(out_filename, "w") as f: # t = 0 # for boxes_t, scores_t, reids_t, classes_t, masks_t in zip(boxes, scores, reids, classes, masks): # for box, score, reid, class_, mask in zip(boxes_t, scores_t, reids_t, classes_t, masks_t): # if add_masks: # print(t, *box, score, class_, *mask['size'], mask['counts'].decode(encoding='UTF-8'), *reid, file=f) # else: # print(t, *box, score, class_, *reid, file=f) # t = t + 1 # # Path: datasets/KITTI/segtrack/KITTI_MOTS_info.py # SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 6, 7, 8, 10, 13, 14, 16, 18]] . Output only the next line.
extraction_keys = [Extractions.DET_MASKS, DataKeys.IMAGE_FILENAMES, DataKeys.IDS]
Next line prediction: <|code_start|> class BboxDetectionRefinementForwarder(Forwarder): def __init__(self, engine): super().__init__(engine) self.model_name = self.config.string("model") def forward(self): out_folder = "forwarded/" + self.model_name + "/detection_bbox_refined/" tf.gfile.MakeDirs(out_folder) data = self.val_data n_examples_per_epoch = data.n_examples_per_epoch() <|code_end|> . Use current file imports: (import pycocotools.mask as cocomask import numpy as np import tensorflow as tf from core import Extractions from datasets import DataKeys from forwarding.Forwarder import Forwarder from forwarding.tracking.TrackingForwarder_util import export_detections_for_sequence from datasets.KITTI.segtrack.KITTI_MOTS_info import SEQ_IDS_VAL) and context including class names, function names, or small code snippets from other files: # Path: core/Extractions.py # EXTRACTIONS = "extractions" # CLASS_POSTERIORS = "class_posteriors" # SEGMENTATION_POSTERIORS = "segmentation_posteriors" # SEGMENTATION_MASK_ORIGINAL_SIZE = "segmentation_mask_original_size" # SEGMENTATION_MASK_INPUT_SIZE = "segmentation_mask_input_size" # RECURRENT_STATE = "recurrent_state" # REID_FEATURES = "reid_features" # DET_BOXES = "det_boxes" # DET_PROBS = "det_probs" # DET_LABELS = "det_labels" # DET_MASKS = "det_masks" # IMAGE_ID = "img_id" # CUSTOM_STRING = "custom_string" # PRED_SPACE_TIME_OFFSETS = "pred_space_time_offsets" # PIXEL_POSITIONS = "pixel_positions" # FEATUREMAP_SIZE = "featuremap_size" # def accumulate_extractions(extractions_accumulator, *new_extractions): # def extract_batch_size_1(extractions, key): # # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: forwarding/Forwarder.py # class Forwarder(ABC): # def __init__(self, engine): # self.engine = engine # self.config = engine.config # self.session = engine.session # self.val_data = self.engine.valid_data # self.train_data = self.engine.train_data # self.trainer = self.engine.trainer # self.saver = self.engine.saver # # @abstractmethod # def forward(self): # pass # # Path: forwarding/tracking/TrackingForwarder_util.py # def export_detections_for_sequence(tag, boxes, scores, reids, classes, masks, model_str, epoch, add_masks, out_folder=""): # if out_folder == "": # out_folder = "forwarded/" + model_str + "/detections/" + str(epoch) # os.makedirs(out_folder, exist_ok=True) # out_filename = out_folder + "/" + tag + ".txt" # with open(out_filename, "w") as f: # t = 0 # for boxes_t, scores_t, reids_t, classes_t, masks_t in zip(boxes, scores, reids, classes, masks): # for box, score, reid, class_, mask in zip(boxes_t, scores_t, reids_t, classes_t, masks_t): # if add_masks: # print(t, *box, score, class_, *mask['size'], mask['counts'].decode(encoding='UTF-8'), *reid, file=f) # else: # print(t, *box, score, class_, *reid, file=f) # t = t + 1 # # Path: datasets/KITTI/segtrack/KITTI_MOTS_info.py # SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 6, 7, 8, 10, 13, 14, 16, 18]] . Output only the next line.
extraction_keys = [Extractions.DET_MASKS, DataKeys.IMAGE_FILENAMES, DataKeys.IDS]
Here is a snippet: <|code_start|> tensors, crop_offset = random_crop_tensors(tensors, crop_size, crop_offset) resized_and_cropped_tensors.append(tensors) return resized_and_cropped_tensors def fixed_resize_and_crop(tensors, size): assert len(size) in (1, 2) if len(size) == 2: assert size[0] == size[1] crop_size = size else: crop_size = [size, size] tensors = scale_with_min_size(tensors, min_size=crop_size) tensors = object_crop_fixed_offset(tensors, crop_size) return tensors def random_crop_tensors(tensors, size, offset=None): tensors_cropped = tensors.copy() keys_to_crop = [DataKeys.IMAGES, DataKeys.SEGMENTATION_LABELS, DataKeys.SEGMENTATION_LABELS_ORIGINAL_SIZE, DataKeys.BBOX_GUIDANCE, DataKeys.RAW_SEGMENTATION_LABELS, DataKeys.SEGMENTATION_INSTANCE_LABELS] # offset = None def _crop(key_, offset_): if key_ in tensors: val = tensors[key_] <|code_end|> . Write the next line using the current file imports: from enum import Enum, unique from functools import partial from datasets import DataKeys from datasets.util.Util import resize_image, random_crop_image, resize_coords_yxyx, resize_coords_xy, \ get_crop_offset import tensorflow as tf import numpy as np and context from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: datasets/util/Util.py # def resize_image(img, out_size, bilinear): # if bilinear: # img = tf.image.resize_images(img, out_size) # else: # img = tf.image.resize_nearest_neighbor(tf.expand_dims(img, 0), out_size) # img = tf.squeeze(img, 0) # return img # # def random_crop_image(img, size, offset=None): # # adapted from code from tf.random_crop # shape = tf.shape(img) # #remove the assertion for now since it makes the queue filling slow for some reason # #check = tf.Assert( # # tf.reduce_all(shape[:2] >= size), # # ["Need value.shape >= size, got ", shape, size]) # #with tf.control_dependencies([check]): # # img = tf.identity(img) # if offset is None: # offset = get_crop_offset(shape, size) # size0 = size[0] if isinstance(size[0], int) else None # size1 = size[1] if isinstance(size[1], int) else None # size_im = tf.stack([size[0], size[1], img.get_shape().as_list()[2]]) # img_cropped = tf.slice(img, offset, size_im) # out_shape_img = [size0, size1, img.get_shape()[2]] # img_cropped.set_shape(out_shape_img) # return img_cropped, offset # # def resize_coords_yxyx(tensor, out_size, original_size): # y_ratio = tf.ones([tf.shape(tensor)[0], 1]) * tf.cast(out_size[0] / original_size[0], tf.float32) # x_ratio = tf.ones([tf.shape(tensor)[0], 1]) * tf.cast(out_size[1] / original_size[1], tf.float32) # # tensor = tf.cast(tensor, tf.float32) * tf.concat([y_ratio, x_ratio, y_ratio, x_ratio], axis=1) # return tensor # # def resize_coords_xy(tensor, out_size, original_size): # y_ratio = tf.cast(out_size[0], tf.float32) / tf.cast(original_size[0], tf.float32) # x_ratio = tf.cast(out_size[1], tf.float32) / tf.cast(original_size[1], tf.float32) # # tensor = tf.cast(tensor, tf.float32) * tf.stack([x_ratio, y_ratio]) # return tensor # # def get_crop_offset(img_shape, crop_size): # limit = img_shape[:2] - crop_size + 1 # dtype = tf.int32 # offset = tf.random_uniform(shape=(2,), dtype=dtype, maxval=dtype.max, seed=None) % limit # offset = tf.stack([offset[0], offset[1], 0]) # return offset , which may include functions, classes, or code. Output only the next line.
cropped, offset_ = random_crop_image(val, size, offset_)
Here is a snippet: <|code_start|>def random_resize_and_crop(tensors, size): assert len(size) in (1, 2) if len(size) == 2: assert size[0] == size[1] crop_size = size else: crop_size = [size, size] tensors, _, _ = resize_random_scale_with_min_size(tensors, min_size=crop_size) tensors, _ = random_crop_tensors(tensors, crop_size) return tensors def joint_random_resize_and_crop(tensors_batch, size): assert len(size) in (1, 2) if len(size) == 2: assert size[0] == size[1] crop_size = size else: crop_size = [size, size] img = tensors_batch[0][DataKeys.IMAGES] img_h = tf.shape(img)[0] img_w = tf.shape(img)[1] scaled_size, scale_factor = get_resize_random_scale_with_min_size_factor(img_h, img_w, min_size=crop_size) resized_tensors = [] for tensors in tensors_batch: tensors = resize_fixed_size(tensors, scaled_size) resized_tensors.append(tensors) <|code_end|> . Write the next line using the current file imports: from enum import Enum, unique from functools import partial from datasets import DataKeys from datasets.util.Util import resize_image, random_crop_image, resize_coords_yxyx, resize_coords_xy, \ get_crop_offset import tensorflow as tf import numpy as np and context from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: datasets/util/Util.py # def resize_image(img, out_size, bilinear): # if bilinear: # img = tf.image.resize_images(img, out_size) # else: # img = tf.image.resize_nearest_neighbor(tf.expand_dims(img, 0), out_size) # img = tf.squeeze(img, 0) # return img # # def random_crop_image(img, size, offset=None): # # adapted from code from tf.random_crop # shape = tf.shape(img) # #remove the assertion for now since it makes the queue filling slow for some reason # #check = tf.Assert( # # tf.reduce_all(shape[:2] >= size), # # ["Need value.shape >= size, got ", shape, size]) # #with tf.control_dependencies([check]): # # img = tf.identity(img) # if offset is None: # offset = get_crop_offset(shape, size) # size0 = size[0] if isinstance(size[0], int) else None # size1 = size[1] if isinstance(size[1], int) else None # size_im = tf.stack([size[0], size[1], img.get_shape().as_list()[2]]) # img_cropped = tf.slice(img, offset, size_im) # out_shape_img = [size0, size1, img.get_shape()[2]] # img_cropped.set_shape(out_shape_img) # return img_cropped, offset # # def resize_coords_yxyx(tensor, out_size, original_size): # y_ratio = tf.ones([tf.shape(tensor)[0], 1]) * tf.cast(out_size[0] / original_size[0], tf.float32) # x_ratio = tf.ones([tf.shape(tensor)[0], 1]) * tf.cast(out_size[1] / original_size[1], tf.float32) # # tensor = tf.cast(tensor, tf.float32) * tf.concat([y_ratio, x_ratio, y_ratio, x_ratio], axis=1) # return tensor # # def resize_coords_xy(tensor, out_size, original_size): # y_ratio = tf.cast(out_size[0], tf.float32) / tf.cast(original_size[0], tf.float32) # x_ratio = tf.cast(out_size[1], tf.float32) / tf.cast(original_size[1], tf.float32) # # tensor = tf.cast(tensor, tf.float32) * tf.stack([x_ratio, y_ratio]) # return tensor # # def get_crop_offset(img_shape, crop_size): # limit = img_shape[:2] - crop_size + 1 # dtype = tf.int32 # offset = tf.random_uniform(shape=(2,), dtype=dtype, maxval=dtype.max, seed=None) % limit # offset = tf.stack([offset[0], offset[1], 0]) # return offset , which may include functions, classes, or code. Output only the next line.
crop_offset = get_crop_offset(scaled_size, crop_size)
Continue the code snippet: <|code_start|> self.load_init_savers = None try: self.load_init = config.string("load_init", "") if self.load_init == "": self.load_init = [] else: self.load_init = [self.load_init] except TypeError: self.load_init = config.string_list("load_init", []) def save_model(self, epoch): tf.gfile.MakeDirs(self.model_dir) self.tf_saver.save(self.session, self.model_dir + self.model, epoch) def try_load_weights(self): start_epoch = 0 fn = None if self.load != "": fn = self.load.replace(".index", "") else: files = sorted(glob.glob(self.model_dir + self.model + "-*.index")) if len(files) > 0: if self.load_epoch_no > 0: epoch_string = str(self.load_epoch_no).zfill(8) files = [f for f in files if epoch_string in f] if len(files) > 0: fn = files[-1].replace(".index", "") if fn is not None: if self.build_networks: <|code_end|> . Use current file imports: import glob import numpy as np import tensorflow as tf import pickle from core.Log import log from tensorflow.contrib.framework import list_variables from tensorflow.contrib.framework import load_variable and context (classes, functions, or code) from other files: # Path: core/Log.py # class Stream: # class Log(object): # def __init__(self, log, lvl): # def write(self, msg): # def flush(self): # def initialize(self, logs=[], verbosity=[], formatter=[]): # def write(self, msg): . Output only the next line.
print("loading model from", fn, file=log.v1)
Using the snippet: <|code_start|> # See also savitar1 class FullyConnected(Layer): def __init__(self, name, inputs, n_features, tower_setup, activation="relu", dropout=0.0, batch_norm=False, batch_norm_decay=Layer.BATCH_NORM_DECAY_DEFAULT, l2=Layer.L2_DEFAULT, W_initializer=None): super(FullyConnected, self).__init__() <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf from network.Layer import Layer from network.Util import get_activation, prepare_input, apply_dropout and context (class names, function names, or code) available: # Path: network/Layer.py # class Layer: # BATCH_NORM_DECAY_DEFAULT = 0.95 # BATCH_NORM_EPSILON = 1e-5 # L2_DEFAULT = 1e-4 # # def __init__(self): # self.summaries = [] # self.regularizers = [] # self.losses = [] # self.update_ops = [] # self.outputs = [] # self.placeholders = [] # self.measures = {} # self.extractions = {} # self.n_params = 0 # # def add_scalar_summary(self, op, name): # summary = tf.summary.scalar(name, op) # self.summaries.append(summary) # # def add_image_summary(self, im, name): # summary = tf.summary.image(name, im) # self.summaries.append(summary) # # def create_and_apply_batch_norm(self, inp, n_features, decay, tower_setup, scope_name="bn", freeze_batchnorm_override=None): # beta, gamma, moving_mean, moving_var = create_batch_norm_vars(n_features, tower_setup, scope_name) # self.n_params += 2 * n_features # if tower_setup.is_main_train_tower: # assert tower_setup.is_training # if tower_setup.is_training and\ # (not tower_setup.freeze_batchnorm or (freeze_batchnorm_override is not None and freeze_batchnorm_override)): # xn, batch_mean, batch_var = tf.nn.fused_batch_norm(inp, gamma, beta, epsilon=Layer.BATCH_NORM_EPSILON, # is_training=True) # if tower_setup.is_main_train_tower: # update_op1 = moving_averages.assign_moving_average( # moving_mean, batch_mean, decay, zero_debias=False, name='mean_ema_op') # update_op2 = moving_averages.assign_moving_average( # moving_var, batch_var, decay, zero_debias=False, name='var_ema_op') # self.update_ops.append(update_op1) # self.update_ops.append(update_op2) # return xn # else: # # According to the tensorpack code, this updates gamma and beta but not the moving averages # # Fused version should have better performance. # xn, _, _ = tf.nn.fused_batch_norm(inp, gamma, beta, moving_mean, moving_var, Layer.BATCH_NORM_EPSILON, is_training=False) # return xn # # def create_weight_variable(self, name, shape, l2, tower_setup, trainable=True, initializer=None): # with tf.device(tower_setup.variable_device): # if initializer is None: # # He initialization # initializer = tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False) # self.n_params += np.prod(shape) # if type(initializer) == np.ndarray: # W = tf.get_variable(name, dtype=tower_setup.dtype, initializer=initializer, trainable=trainable) # else: # W = tf.get_variable(name, shape, tower_setup.dtype, initializer, trainable=trainable) # if l2 > 0.0: # self.regularizers.append(l2 * tf.nn.l2_loss(W)) # if tower_setup.use_weight_summaries: # summ = tf.summary.histogram(name, W) # self.summaries.append(summ) # self.add_scalar_summary(tf.reduce_max(tf.abs(W)), name + "/W_abs_max") # return W # # def create_bias_variable(self, name, shape, tower_setup, trainable=True, initializer=None): # with tf.device(tower_setup.variable_device): # if initializer is None: # initializer = tf.constant_initializer(0.0, dtype=tower_setup.dtype) # self.n_params += np.prod(shape) # b = tf.get_variable(name, shape, tower_setup.dtype, initializer, trainable=trainable) # if tower_setup.use_weight_summaries: # summ = tf.summary.histogram(name, b) # self.summaries.append(summ) # self.add_scalar_summary(tf.reduce_max(tf.abs(b)), name + "/b_abs_max") # return b # # Path: network/Util.py # def get_activation(act_str): # assert act_str.lower() in _activations, "Unknown activation function " + act_str # return _activations[act_str.lower()] # # def prepare_input(inputs): # if len(inputs) == 1: # inp = inputs[0] # dim = int(inp.get_shape()[-1]) # else: # dims = [int(inp.get_shape()[3]) for inp in inputs] # dim = sum(dims) # inp = tf.concat(inputs, axis=3) # return inp, dim # # def apply_dropout(inp, dropout): # if dropout == 0.0: # return inp # else: # keep_prob = 1.0 - dropout # return tf.nn.dropout(inp, keep_prob) . Output only the next line.
inp, n_features_inp = prepare_input(inputs)
Given snippet: <|code_start|> # See also savitar1 class FullyConnected(Layer): def __init__(self, name, inputs, n_features, tower_setup, activation="relu", dropout=0.0, batch_norm=False, batch_norm_decay=Layer.BATCH_NORM_DECAY_DEFAULT, l2=Layer.L2_DEFAULT, W_initializer=None): super(FullyConnected, self).__init__() inp, n_features_inp = prepare_input(inputs) with tf.variable_scope(name): <|code_end|> , continue by predicting the next line. Consider current file imports: import tensorflow as tf from network.Layer import Layer from network.Util import get_activation, prepare_input, apply_dropout and context: # Path: network/Layer.py # class Layer: # BATCH_NORM_DECAY_DEFAULT = 0.95 # BATCH_NORM_EPSILON = 1e-5 # L2_DEFAULT = 1e-4 # # def __init__(self): # self.summaries = [] # self.regularizers = [] # self.losses = [] # self.update_ops = [] # self.outputs = [] # self.placeholders = [] # self.measures = {} # self.extractions = {} # self.n_params = 0 # # def add_scalar_summary(self, op, name): # summary = tf.summary.scalar(name, op) # self.summaries.append(summary) # # def add_image_summary(self, im, name): # summary = tf.summary.image(name, im) # self.summaries.append(summary) # # def create_and_apply_batch_norm(self, inp, n_features, decay, tower_setup, scope_name="bn", freeze_batchnorm_override=None): # beta, gamma, moving_mean, moving_var = create_batch_norm_vars(n_features, tower_setup, scope_name) # self.n_params += 2 * n_features # if tower_setup.is_main_train_tower: # assert tower_setup.is_training # if tower_setup.is_training and\ # (not tower_setup.freeze_batchnorm or (freeze_batchnorm_override is not None and freeze_batchnorm_override)): # xn, batch_mean, batch_var = tf.nn.fused_batch_norm(inp, gamma, beta, epsilon=Layer.BATCH_NORM_EPSILON, # is_training=True) # if tower_setup.is_main_train_tower: # update_op1 = moving_averages.assign_moving_average( # moving_mean, batch_mean, decay, zero_debias=False, name='mean_ema_op') # update_op2 = moving_averages.assign_moving_average( # moving_var, batch_var, decay, zero_debias=False, name='var_ema_op') # self.update_ops.append(update_op1) # self.update_ops.append(update_op2) # return xn # else: # # According to the tensorpack code, this updates gamma and beta but not the moving averages # # Fused version should have better performance. # xn, _, _ = tf.nn.fused_batch_norm(inp, gamma, beta, moving_mean, moving_var, Layer.BATCH_NORM_EPSILON, is_training=False) # return xn # # def create_weight_variable(self, name, shape, l2, tower_setup, trainable=True, initializer=None): # with tf.device(tower_setup.variable_device): # if initializer is None: # # He initialization # initializer = tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False) # self.n_params += np.prod(shape) # if type(initializer) == np.ndarray: # W = tf.get_variable(name, dtype=tower_setup.dtype, initializer=initializer, trainable=trainable) # else: # W = tf.get_variable(name, shape, tower_setup.dtype, initializer, trainable=trainable) # if l2 > 0.0: # self.regularizers.append(l2 * tf.nn.l2_loss(W)) # if tower_setup.use_weight_summaries: # summ = tf.summary.histogram(name, W) # self.summaries.append(summ) # self.add_scalar_summary(tf.reduce_max(tf.abs(W)), name + "/W_abs_max") # return W # # def create_bias_variable(self, name, shape, tower_setup, trainable=True, initializer=None): # with tf.device(tower_setup.variable_device): # if initializer is None: # initializer = tf.constant_initializer(0.0, dtype=tower_setup.dtype) # self.n_params += np.prod(shape) # b = tf.get_variable(name, shape, tower_setup.dtype, initializer, trainable=trainable) # if tower_setup.use_weight_summaries: # summ = tf.summary.histogram(name, b) # self.summaries.append(summ) # self.add_scalar_summary(tf.reduce_max(tf.abs(b)), name + "/b_abs_max") # return b # # Path: network/Util.py # def get_activation(act_str): # assert act_str.lower() in _activations, "Unknown activation function " + act_str # return _activations[act_str.lower()] # # def prepare_input(inputs): # if len(inputs) == 1: # inp = inputs[0] # dim = int(inp.get_shape()[-1]) # else: # dims = [int(inp.get_shape()[3]) for inp in inputs] # dim = sum(dims) # inp = tf.concat(inputs, axis=3) # return inp, dim # # def apply_dropout(inp, dropout): # if dropout == 0.0: # return inp # else: # keep_prob = 1.0 - dropout # return tf.nn.dropout(inp, keep_prob) which might include code, classes, or functions. Output only the next line.
inp = apply_dropout(inp, dropout)
Given snippet: <|code_start|> NAME = "MOTS_challenge_feed" DEFAULT_PATH = "/globalwork/voigtlaender/data/MOTS_challenge/train/" SEQ_IDS_TRAIN = [] SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 5, 9, 11]] <|code_end|> , continue by predicting the next line. Consider current file imports: import glob from datasets.Loader import register_dataset from datasets.KITTI.segtrack.KITTI_segtrack_feed import KittiSegtrackLikeFeedDataset and context: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/KITTI/segtrack/KITTI_segtrack_feed.py # class KittiSegtrackLikeFeedDataset(FeedDataset): # def __init__(self, config, subset, dataset_name, default_path, seq_ids_train, seq_ids_val, preload_images): # super().__init__(config, subset, data_keys_to_use=DATA_KEYS_TO_USE, num_classes=NUM_CLASSES) # self.time_starts_at_1 = False # self.data_dir = config.string(dataset_name + "_data_dir", default_path) # video_tags_config = config.string_list("video_tags_to_load", []) # if len(video_tags_config) > 0: # self._video_tags = video_tags_config # else: # if self.subset == "train": # self._video_tags = seq_ids_train # else: # self._video_tags = seq_ids_val # self._video_idx = None # self._imgs = None # self._curr_time = None # self._filenames = None # self._preload_images = preload_images # init_anchors(config) # # This is somewhat hacky # self._num_context_frames = 0 # if self.config.bool("offset_matching", False): # self._num_context_frames = self.config.int("num_space_time_targets", 1) # print("Supplying", self._num_context_frames, "context frames so actual batch size will decrease") # # def set_video_idx(self, idx): # self._curr_time = 0 # if self._video_idx == idx: # return # self._video_idx = idx # self._filenames = self.get_filenames_for_video_idx(idx) # if self.config.bool("short_videos_for_testing", False): # print("Warning, shortening video to 2 frames for testing", file=log.v1) # self._filenames = self._filenames[:2] # if self._preload_images: # print("loading images for seq", self.get_video_tag(), file=log.v5) # with Pool(8) as pool: # self._imgs = pool.map(_load_img, self._filenames) # print("done", file=log.v5) # # @abstractmethod # def get_filenames_for_video_idx(self, idx): # raise NotImplementedError # # def n_videos(self): # return len(self._video_tags) # # def n_examples_per_epoch(self): # assert self._video_idx is not None # return len(self._filenames) # # def get_video_tag(self): # assert self._video_idx is not None # return self._video_tags[self._video_idx] # # def get_feed_dict_for_next_step(self): # assert self._video_idx is not None # feed_dict = {} # for idx in range(self._batch_size): # if self._curr_time > 0: # time_idx = self._curr_time - self._num_context_frames + idx # else: # time_idx = self._curr_time + idx # # On the last batch, repeat the final image to fill up batch # if time_idx >= len(self._filenames): # time_idx = len(self._filenames) - 1 # if self._preload_images: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = self._imgs[time_idx] # else: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = _load_img(self._filenames[time_idx]) # feed_dict[self._placeholders[DataKeys.IMAGE_FILENAMES][idx]] = self._filenames[time_idx] # self._curr_time += self._batch_size - self._num_context_frames # return feed_dict which might include code, classes, or functions. Output only the next line.
@register_dataset(NAME)
Next line prediction: <|code_start|> NAME = "MOTS_challenge_feed" DEFAULT_PATH = "/globalwork/voigtlaender/data/MOTS_challenge/train/" SEQ_IDS_TRAIN = [] SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 5, 9, 11]] @register_dataset(NAME) <|code_end|> . Use current file imports: (import glob from datasets.Loader import register_dataset from datasets.KITTI.segtrack.KITTI_segtrack_feed import KittiSegtrackLikeFeedDataset) and context including class names, function names, or small code snippets from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/KITTI/segtrack/KITTI_segtrack_feed.py # class KittiSegtrackLikeFeedDataset(FeedDataset): # def __init__(self, config, subset, dataset_name, default_path, seq_ids_train, seq_ids_val, preload_images): # super().__init__(config, subset, data_keys_to_use=DATA_KEYS_TO_USE, num_classes=NUM_CLASSES) # self.time_starts_at_1 = False # self.data_dir = config.string(dataset_name + "_data_dir", default_path) # video_tags_config = config.string_list("video_tags_to_load", []) # if len(video_tags_config) > 0: # self._video_tags = video_tags_config # else: # if self.subset == "train": # self._video_tags = seq_ids_train # else: # self._video_tags = seq_ids_val # self._video_idx = None # self._imgs = None # self._curr_time = None # self._filenames = None # self._preload_images = preload_images # init_anchors(config) # # This is somewhat hacky # self._num_context_frames = 0 # if self.config.bool("offset_matching", False): # self._num_context_frames = self.config.int("num_space_time_targets", 1) # print("Supplying", self._num_context_frames, "context frames so actual batch size will decrease") # # def set_video_idx(self, idx): # self._curr_time = 0 # if self._video_idx == idx: # return # self._video_idx = idx # self._filenames = self.get_filenames_for_video_idx(idx) # if self.config.bool("short_videos_for_testing", False): # print("Warning, shortening video to 2 frames for testing", file=log.v1) # self._filenames = self._filenames[:2] # if self._preload_images: # print("loading images for seq", self.get_video_tag(), file=log.v5) # with Pool(8) as pool: # self._imgs = pool.map(_load_img, self._filenames) # print("done", file=log.v5) # # @abstractmethod # def get_filenames_for_video_idx(self, idx): # raise NotImplementedError # # def n_videos(self): # return len(self._video_tags) # # def n_examples_per_epoch(self): # assert self._video_idx is not None # return len(self._filenames) # # def get_video_tag(self): # assert self._video_idx is not None # return self._video_tags[self._video_idx] # # def get_feed_dict_for_next_step(self): # assert self._video_idx is not None # feed_dict = {} # for idx in range(self._batch_size): # if self._curr_time > 0: # time_idx = self._curr_time - self._num_context_frames + idx # else: # time_idx = self._curr_time + idx # # On the last batch, repeat the final image to fill up batch # if time_idx >= len(self._filenames): # time_idx = len(self._filenames) - 1 # if self._preload_images: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = self._imgs[time_idx] # else: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = _load_img(self._filenames[time_idx]) # feed_dict[self._placeholders[DataKeys.IMAGE_FILENAMES][idx]] = self._filenames[time_idx] # self._curr_time += self._batch_size - self._num_context_frames # return feed_dict . Output only the next line.
class MOTSSegtrackFeedDataset(KittiSegtrackLikeFeedDataset):
Using the snippet: <|code_start|> class Layer: BATCH_NORM_DECAY_DEFAULT = 0.95 BATCH_NORM_EPSILON = 1e-5 L2_DEFAULT = 1e-4 def __init__(self): self.summaries = [] self.regularizers = [] self.losses = [] self.update_ops = [] self.outputs = [] self.placeholders = [] self.measures = {} self.extractions = {} self.n_params = 0 def add_scalar_summary(self, op, name): summary = tf.summary.scalar(name, op) self.summaries.append(summary) def add_image_summary(self, im, name): summary = tf.summary.image(name, im) self.summaries.append(summary) def create_and_apply_batch_norm(self, inp, n_features, decay, tower_setup, scope_name="bn", freeze_batchnorm_override=None): <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf import numpy as np from tensorflow.python.training import moving_averages from network.Util import create_batch_norm_vars and context (class names, function names, or code) available: # Path: network/Util.py # def create_batch_norm_vars(n_out, tower_setup, scope_name="bn"): # with tf.device(tower_setup.variable_device), tf.variable_scope(scope_name): # initializer_zero = tf.constant_initializer(0.0, dtype=tf.float32) # beta = tf.get_variable("beta", [n_out], tf.float32, initializer_zero) # initializer_gamma = tf.constant_initializer(1.0, dtype=tf.float32) # gamma = tf.get_variable("gamma", [n_out], tf.float32, initializer_gamma) # mean_ema = tf.get_variable("mean_ema", [n_out], tf.float32, initializer_zero, trainable=False) # var_ema = tf.get_variable("var_ema", [n_out], tf.float32, initializer_zero, trainable=False) # return beta, gamma, mean_ema, var_ema . Output only the next line.
beta, gamma, moving_mean, moving_var = create_batch_norm_vars(n_features, tower_setup, scope_name)
Given the following code snippet before the placeholder: <|code_start|> DEFAULT_PATH = "/fastwork/" + username() + "/mywork/data/mapillary/" NAME = "mapillary_instance" @register_dataset("mapillary_instance_full", resolution="full") @register_dataset("mapillary_instance_half", resolution="half") @register_dataset("mapillary_instance_quarter", resolution="quarter") <|code_end|> , predict the next line using imports from the current file: from datasets.Loader import register_dataset from datasets.Mapillary.MapillaryLike_instance import MapillaryLikeInstanceDataset from datasets.util.Util import username and context including class names, function names, and sometimes code from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/Mapillary/MapillaryLike_instance.py # class MapillaryLikeInstanceDataset(FileListDataset): # def __init__(self, config, subset, name, default_path, data_list_path, id_divisor, cat_ids_to_use): # super().__init__(config, name, subset, default_path, NUM_CLASSES) # self.validation_set_size = self.config.int("validation_set_size", -1) # # note: in case of mapillary the min sizes are always based on the sizes in quarter resolution! # self.min_size = config.int("min_size", 0) # self._cat_ids_to_use = cat_ids_to_use # self._data_list_path = data_list_path # self._id_divisor = id_divisor # self.name = name # # def read_inputfile_lists(self): # data_list = "training.txt" if self.subset == "train" else "validation.txt" # print("{} ({}): using data_dir:".format(self.name, self.subset), self.data_dir, file=log.v5) # data_list = self._data_list_path + "/" + data_list # imgs_ans = [] # with open(data_list) as f: # for l in f: # im, an, *im_ids_and_sizes = l.strip().split() # im = self.data_dir + im # an = self.data_dir + an # for id_and_size in im_ids_and_sizes: # id_ = id_and_size.split(":")[0] # size_ = int(id_and_size.split(":")[1]) # if self.subset == "train" and size_ < self.min_size: # continue # cat_id = int(id_) // self._id_divisor # if self._cat_ids_to_use is not None and cat_id not in self._cat_ids_to_use: # continue # imgs_ans.append((im, an + ":" + id_)) # if self.subset == "train": # shuffle(imgs_ans) # elif self.validation_set_size != -1: # imgs_ans = imgs_ans[:self.validation_set_size] # imgs = [x[0] for x in imgs_ans] # ans = [x[1] for x in imgs_ans] # return imgs, ans # # def load_annotation(self, img, img_filename, annotation_filename): # annotation_filename_without_id = tf.string_split([annotation_filename], ':').values[0] # ann_data = tf.read_file(annotation_filename_without_id) # ann = tf.image.decode_png(ann_data, dtype=tf.uint16, channels=1) # ann.set_shape(img.get_shape().as_list()[:-1] + [1]) # ann = self.postproc_annotation(annotation_filename, ann) # return ann # # def postproc_annotation(self, ann_filename, ann): # id_str = tf.string_split([ann_filename], ':').values[1] # id_ = tf.string_to_number(id_str, out_type=tf.int32) # ann_postproc = tf.cast(tf.equal(tf.cast(ann, tf.int32), id_), tf.uint8) # return ann_postproc # # Path: datasets/util/Util.py # def username(): # return os.environ["USER"] . Output only the next line.
class MapillaryInstanceDataset(MapillaryLikeInstanceDataset):
Next line prediction: <|code_start|> self.gt_data = {seq: [] for seq in self.seq_ids} self.visibility_threshold = config.float("visibility_threshold", 0.5) # Boxes with visibility < this are ignored parent_folder = os.path.join(self.data_dir, "train") for seq in self.seq_ids: gt_filename = os.path.join(parent_folder, seq, "gt", "gt.txt") self.gt_data[seq].append(np.genfromtxt(gt_filename, delimiter=gt_delimiter)) self.classes_to_cat = [0, 1, 3] self.cat_to_class = {v: i for i, v in enumerate(self.classes_to_cat)} def read_inputfile_lists(self): parent_folder = os.path.join(self.data_dir, "train") imgs = [] for seq in self.seq_ids: imgs += sorted(glob.glob(os.path.join(parent_folder, seq, "img1", "/*.jpg"))) return (imgs, ) def load_annotation(self, img, img_filename, annotation_filename): img_shape = tf.shape(img) bboxes, ids, classes, is_crowd = tf.py_func(self.get_data_arrays_for_file, [img_filename, img_shape[0], img_shape[1]], [tf.float32, tf.int32, tf.int32, tf.int32], name="get_data_arrays_for_file") bboxes.set_shape((N_MAX_DETECTIONS, 4)) ids.set_shape((N_MAX_DETECTIONS,)) classes.set_shape((N_MAX_DETECTIONS,)) is_crowd.set_shape((N_MAX_DETECTIONS,)) return_dict = {} <|code_end|> . Use current file imports: (import glob import os import tensorflow as tf import numpy as np from datasets.DetectionDataset import DetectionFileListDataset from datasets import DataKeys) and context including class names, function names, or small code snippets from other files: # Path: datasets/DetectionDataset.py # class DetectionFileListDataset(FileListDataset): # def __init__(self, config, dataset_name, subset, default_path, num_classes): # super().__init__(config, dataset_name, subset, default_path, num_classes) # self.add_masks = config.bool("add_masks", True) # self.prefer_gt_to_ignore = config.bool("prefer_gt_to_ignore", False) # self.use_ioa_for_ignore = config.bool("use_ioa_for_ignore", False) # self.use_masks_for_ignore = config.bool("use_masks_for_ignore", False) # init_anchors(config) # # def assemble_example(self, tensors): # tensors = super().assemble_example(tensors) # if DataKeys.BBOXES_y0x0y1x1 in tensors: # tensors = add_rpn_data(tensors, self.prefer_gt_to_ignore, use_masks_for_ignore=self.use_masks_for_ignore, # use_ioa_for_ignore=self.use_ioa_for_ignore) # return tensors # # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" . Output only the next line.
return_dict[DataKeys.BBOXES_y0x0y1x1] = bboxes
Here is a snippet: <|code_start|> NAME = "KITTI_segtrack_amodal" @register_dataset(NAME) class KittiSegtrackAmodalDataset(KittiSegtrackDataset): def __init__(self, config, subset): super().__init__(config, subset, NAME) def postproc_annotation(self, ann_filename, ann): ann = super().postproc_annotation(ann_filename, ann) if not isinstance(ann, dict): <|code_end|> . Write the next line using the current file imports: import numpy as np import tensorflow as tf from datasets import DataKeys from datasets.KITTI.segtrack.KITTI_segtrack import KittiSegtrackDataset from datasets.Loader import register_dataset and context from other files: # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: datasets/KITTI/segtrack/KITTI_segtrack.py # class KittiSegtrackDataset(KittiSegtrackDetectionDataset): # def __init__(self, config, subset, name=NAME, default_path=DEFAULT_PATH): # # batch size here is the number of time steps considered in a chunk # # TODO: what do we do at test time? # self._batch_size = config.int("batch_size") # assert self._batch_size > 1, "use KittiSegtrackDetectionDataset for single image training" # super().__init__(config, subset, name, default_path) # # def read_inputfile_lists(self): # seq_ids = self.seq_ids_train if self.subset == "train" else self.seq_ids_val # anns = [] # for seq_id in seq_ids: # anns_vid = sorted(glob.glob(self.data_dir + "/instances/" + seq_id + "/*.png")) # starting_points = anns_vid[:-(self._batch_size - 1)] # anns += starting_points # # imgs = [x.replace("/instances/", "/images/") for x in anns] # return imgs, anns # # def _batch(self, tfdata, batch_size): # return tfdata # # def load_example(self, input_filenames): # examples = [] # for delta_t in range(self._batch_size): # input_filenames_t = [successor_frame_filename(fn, delta_t) for fn in input_filenames] # raw_example = self.load_raw_example(*input_filenames_t) # examples.append(raw_example) # # # cf process_raw_example # # here we need to do it jointly to synchronize the augmentation (e.g. flipping) # examples = [self.postproc_example_initial(example) for example in examples] # examples = self.jointly_augment_examples_before_resize(examples) # examples = [self.postproc_example_before_resize(example) for example in examples] # examples = [self.resize_example(example) for example in examples] # examples = self.jointly_augment_examples_after_resize(examples) # examples = [self.postproc_example_before_assembly(example) for example in examples] # examples = [self.assemble_example(example) for example in examples] # # # stack everything together # examples_stacked = {} # for key in examples[0].keys(): # if key == DataKeys.SKIP_EXAMPLE: # stacked = tf.reduce_any([example[key] for example in examples]) # else: # stacked = tf.stack([example[key] for example in examples], axis=0) # examples_stacked[key] = stacked # return examples_stacked # # def n_examples_per_epoch(self): # n_examples = super().n_examples_per_epoch() # if n_examples == len(self.inputfile_lists[0]): # return n_examples * self._batch_size # # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register , which may include functions, classes, or code. Output only the next line.
ann = {DataKeys.SEGMENTATION_LABELS: ann}
Predict the next line after this snippet: <|code_start|> NAME = "MOTS_challenge" DEFAULT_PATH = "/globalwork/voigtlaender/data/MOTS_challenge/train/" SEQ_IDS_TRAIN = ["%04d" % idx for idx in [2, 5, 9, 11]] SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 5, 9, 11]] TIMESTEPS_PER_SEQ = {"0002": 600, "0005": 837, "0009": 525, "0011": 900} @register_dataset(NAME) <|code_end|> using the current file's imports: import glob from datasets.KITTI.segtrack.KITTI_segtrack import KittiSegtrackDataset from datasets.Loader import register_dataset and any relevant context from other files: # Path: datasets/KITTI/segtrack/KITTI_segtrack.py # class KittiSegtrackDataset(KittiSegtrackDetectionDataset): # def __init__(self, config, subset, name=NAME, default_path=DEFAULT_PATH): # # batch size here is the number of time steps considered in a chunk # # TODO: what do we do at test time? # self._batch_size = config.int("batch_size") # assert self._batch_size > 1, "use KittiSegtrackDetectionDataset for single image training" # super().__init__(config, subset, name, default_path) # # def read_inputfile_lists(self): # seq_ids = self.seq_ids_train if self.subset == "train" else self.seq_ids_val # anns = [] # for seq_id in seq_ids: # anns_vid = sorted(glob.glob(self.data_dir + "/instances/" + seq_id + "/*.png")) # starting_points = anns_vid[:-(self._batch_size - 1)] # anns += starting_points # # imgs = [x.replace("/instances/", "/images/") for x in anns] # return imgs, anns # # def _batch(self, tfdata, batch_size): # return tfdata # # def load_example(self, input_filenames): # examples = [] # for delta_t in range(self._batch_size): # input_filenames_t = [successor_frame_filename(fn, delta_t) for fn in input_filenames] # raw_example = self.load_raw_example(*input_filenames_t) # examples.append(raw_example) # # # cf process_raw_example # # here we need to do it jointly to synchronize the augmentation (e.g. flipping) # examples = [self.postproc_example_initial(example) for example in examples] # examples = self.jointly_augment_examples_before_resize(examples) # examples = [self.postproc_example_before_resize(example) for example in examples] # examples = [self.resize_example(example) for example in examples] # examples = self.jointly_augment_examples_after_resize(examples) # examples = [self.postproc_example_before_assembly(example) for example in examples] # examples = [self.assemble_example(example) for example in examples] # # # stack everything together # examples_stacked = {} # for key in examples[0].keys(): # if key == DataKeys.SKIP_EXAMPLE: # stacked = tf.reduce_any([example[key] for example in examples]) # else: # stacked = tf.stack([example[key] for example in examples], axis=0) # examples_stacked[key] = stacked # return examples_stacked # # def n_examples_per_epoch(self): # n_examples = super().n_examples_per_epoch() # if n_examples == len(self.inputfile_lists[0]): # return n_examples * self._batch_size # # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register . Output only the next line.
class MotsChallengeDataset(KittiSegtrackDataset):
Predict the next line after this snippet: <|code_start|> NAME = "MOTS_challenge" DEFAULT_PATH = "/globalwork/voigtlaender/data/MOTS_challenge/train/" SEQ_IDS_TRAIN = ["%04d" % idx for idx in [2, 5, 9, 11]] SEQ_IDS_VAL = ["%04d" % idx for idx in [2, 5, 9, 11]] TIMESTEPS_PER_SEQ = {"0002": 600, "0005": 837, "0009": 525, "0011": 900} <|code_end|> using the current file's imports: import glob from datasets.KITTI.segtrack.KITTI_segtrack import KittiSegtrackDataset from datasets.Loader import register_dataset and any relevant context from other files: # Path: datasets/KITTI/segtrack/KITTI_segtrack.py # class KittiSegtrackDataset(KittiSegtrackDetectionDataset): # def __init__(self, config, subset, name=NAME, default_path=DEFAULT_PATH): # # batch size here is the number of time steps considered in a chunk # # TODO: what do we do at test time? # self._batch_size = config.int("batch_size") # assert self._batch_size > 1, "use KittiSegtrackDetectionDataset for single image training" # super().__init__(config, subset, name, default_path) # # def read_inputfile_lists(self): # seq_ids = self.seq_ids_train if self.subset == "train" else self.seq_ids_val # anns = [] # for seq_id in seq_ids: # anns_vid = sorted(glob.glob(self.data_dir + "/instances/" + seq_id + "/*.png")) # starting_points = anns_vid[:-(self._batch_size - 1)] # anns += starting_points # # imgs = [x.replace("/instances/", "/images/") for x in anns] # return imgs, anns # # def _batch(self, tfdata, batch_size): # return tfdata # # def load_example(self, input_filenames): # examples = [] # for delta_t in range(self._batch_size): # input_filenames_t = [successor_frame_filename(fn, delta_t) for fn in input_filenames] # raw_example = self.load_raw_example(*input_filenames_t) # examples.append(raw_example) # # # cf process_raw_example # # here we need to do it jointly to synchronize the augmentation (e.g. flipping) # examples = [self.postproc_example_initial(example) for example in examples] # examples = self.jointly_augment_examples_before_resize(examples) # examples = [self.postproc_example_before_resize(example) for example in examples] # examples = [self.resize_example(example) for example in examples] # examples = self.jointly_augment_examples_after_resize(examples) # examples = [self.postproc_example_before_assembly(example) for example in examples] # examples = [self.assemble_example(example) for example in examples] # # # stack everything together # examples_stacked = {} # for key in examples[0].keys(): # if key == DataKeys.SKIP_EXAMPLE: # stacked = tf.reduce_any([example[key] for example in examples]) # else: # stacked = tf.stack([example[key] for example in examples], axis=0) # examples_stacked[key] = stacked # return examples_stacked # # def n_examples_per_epoch(self): # n_examples = super().n_examples_per_epoch() # if n_examples == len(self.inputfile_lists[0]): # return n_examples * self._batch_size # # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register . Output only the next line.
@register_dataset(NAME)
Predict the next line for this snippet: <|code_start|> class MOTFeedDataset(KittiSegtrackLikeFeedDataset): def __init__(self, config, subset, name, default_path, seq_ids_train, seq_ids_val): super().__init__(config, subset, name, default_path, seq_ids_train, seq_ids_val, False) def get_filenames_for_video_idx(self, idx): path = os.path.join(self.data_dir, "train", self._video_tags[idx], "img1", "*.jpg") return sorted(glob.glob(path)) <|code_end|> with the help of current file imports: import glob import os from datasets.Loader import register_dataset from datasets.KITTI.segtrack.KITTI_segtrack_feed import KittiSegtrackLikeFeedDataset from datasets.MOT.MOT17 import DEFAULT_PATH, SEQ_IDS_TRAIN, SEQ_IDS_VAL from datasets.MOT.MOT15 import DEFAULT_PATH, SEQ_IDS_TRAIN, SEQ_IDS_VAL from datasets.MOT.PathTrack import DEFAULT_PATH, SEQ_IDS_TRAIN, SEQ_IDS_VAL and context from other files: # Path: datasets/Loader.py # def register_dataset(name, **args): # name = name.lower() # # def _register(dataset): # _registered_datasets[name] = (dataset, args) # return dataset # return _register # # Path: datasets/KITTI/segtrack/KITTI_segtrack_feed.py # class KittiSegtrackLikeFeedDataset(FeedDataset): # def __init__(self, config, subset, dataset_name, default_path, seq_ids_train, seq_ids_val, preload_images): # super().__init__(config, subset, data_keys_to_use=DATA_KEYS_TO_USE, num_classes=NUM_CLASSES) # self.time_starts_at_1 = False # self.data_dir = config.string(dataset_name + "_data_dir", default_path) # video_tags_config = config.string_list("video_tags_to_load", []) # if len(video_tags_config) > 0: # self._video_tags = video_tags_config # else: # if self.subset == "train": # self._video_tags = seq_ids_train # else: # self._video_tags = seq_ids_val # self._video_idx = None # self._imgs = None # self._curr_time = None # self._filenames = None # self._preload_images = preload_images # init_anchors(config) # # This is somewhat hacky # self._num_context_frames = 0 # if self.config.bool("offset_matching", False): # self._num_context_frames = self.config.int("num_space_time_targets", 1) # print("Supplying", self._num_context_frames, "context frames so actual batch size will decrease") # # def set_video_idx(self, idx): # self._curr_time = 0 # if self._video_idx == idx: # return # self._video_idx = idx # self._filenames = self.get_filenames_for_video_idx(idx) # if self.config.bool("short_videos_for_testing", False): # print("Warning, shortening video to 2 frames for testing", file=log.v1) # self._filenames = self._filenames[:2] # if self._preload_images: # print("loading images for seq", self.get_video_tag(), file=log.v5) # with Pool(8) as pool: # self._imgs = pool.map(_load_img, self._filenames) # print("done", file=log.v5) # # @abstractmethod # def get_filenames_for_video_idx(self, idx): # raise NotImplementedError # # def n_videos(self): # return len(self._video_tags) # # def n_examples_per_epoch(self): # assert self._video_idx is not None # return len(self._filenames) # # def get_video_tag(self): # assert self._video_idx is not None # return self._video_tags[self._video_idx] # # def get_feed_dict_for_next_step(self): # assert self._video_idx is not None # feed_dict = {} # for idx in range(self._batch_size): # if self._curr_time > 0: # time_idx = self._curr_time - self._num_context_frames + idx # else: # time_idx = self._curr_time + idx # # On the last batch, repeat the final image to fill up batch # if time_idx >= len(self._filenames): # time_idx = len(self._filenames) - 1 # if self._preload_images: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = self._imgs[time_idx] # else: # feed_dict[self._placeholders[DataKeys.IMAGES][idx]] = _load_img(self._filenames[time_idx]) # feed_dict[self._placeholders[DataKeys.IMAGE_FILENAMES][idx]] = self._filenames[time_idx] # self._curr_time += self._batch_size - self._num_context_frames # return feed_dict , which may contain function names, class names, or code. Output only the next line.
@register_dataset("MOT17_feed")
Given the code snippet: <|code_start|> use_masks_for_ignore=False, crowd_masks=None): """ Label each anchor as fg/bg/ignore. Args: anchors: Ax4 float gt_boxes: Bx4 float crowd_boxes: Cx4 float Returns: anchor_labels: (A,) int. Each element is {-1, 0, 1} anchor_boxes: Ax4. Contains the target gt_box for each anchor when the anchor is fg. """ # This function will modify labels and return the filtered inds def filter_box_label(labels, value, max_num): curr_inds = np.where(labels == value)[0] if len(curr_inds) > max_num: disable_inds = np.random.choice( curr_inds, size=(len(curr_inds) - max_num), replace=False) labels[disable_inds] = -1 # ignore them curr_inds = np.where(labels == value)[0] return curr_inds NA, NB = len(anchors), len(gt_boxes) if NB <= 0: # empty images should have been filtered already anchor_labels = np.ones((NA,), dtype='int32') anchor_boxes = np.zeros((NA, 4), dtype='float32') return anchor_labels, anchor_boxes, True <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf import numpy as np from PIL import Image from core.Util import calculate_ious, calculate_ioas from datasets import DataKeys from datasets.util.BoundingBox import get_bbox_from_segmentation_mask_np from functools import partial from skimage.transform import integral_image and context (functions, classes, or occasionally code) from other files: # Path: core/Util.py # def calculate_ious(bboxes1, bboxes2): # # assume layout (x0, y0, x1, y1) # min_ = np.minimum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) # max_ = np.maximum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) # I = np.maximum(min_[..., 2] - max_[..., 0], 0) * np.maximum(min_[..., 3] - max_[..., 1], 0) # area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1]) # area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) # U = area1[:, np.newaxis] + area2[np.newaxis, :] - I # assert (U > 0).all() # IOUs = I / U # assert (IOUs >= 0).all() # assert (IOUs <= 1).all() # return IOUs # # def calculate_ioas(bboxes1, bboxes2): # # assume layout (x0, y0, x1, y1) # min_ = np.minimum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) # max_ = np.maximum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) # I = np.maximum(min_[..., 2] - max_[..., 0], 0) * np.maximum(min_[..., 3] - max_[..., 1], 0) # area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1]) # #area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) # A = area1[:, np.newaxis] # assert (A > 0).all() # IOAs = I / A # assert (IOAs >= 0).all() # assert (IOAs <= 1).all() # return IOAs # # Path: datasets/DataKeys.py # SEGMENTATION_LABELS = "segmentation_labels" # SEGMENTATION_LABELS_ORIGINAL_SIZE = "segmentation_labels_original_size" # BBOX_GUIDANCE = "bbox_guidance" # UNSIGNED_DISTANCE_TRANSFORM_GUIDANCE = "unsigned_distance_transform_guidance" # SIGNED_DISTANCE_TRANSFORM_GUIDANCE = "signed_distance_transform_guidance" # LASER_GUIDANCE = "laser_guidance" # IMAGES = "images" # RAW_IMAGES = "raw_images" # INPUTS = "inputs" # IMAGE_FILENAMES = "image_filenames" # CLASSES = "classes" # IDS = "ids" # bounding box number 1,2,3... or 0 if no bounding box # DT_METHOD = "dt_method" # RAW_SEGMENTATION_LABELS = "raw_segmentation_labels" # CLICK_MAPS = "clicks_maps" # NEG_CLICKS = "neg_clicks" # POS_CLICKS = "pos_clicks" # OBJ_TAGS = "obj_tags" # FEATUREMAP_LABELS = "featuremap_labels" # FEATUREMAP_BOXES = "featuremap_boxes" # IMAGE_ID = "image_id" # IS_CROWD = "is_crowd" # SEGMENTATION_MASK = "segmentation_mask" # SKIP_EXAMPLE = "skip_example" # If true, filter the corresponding example from the datastream. Useful, when an example # RAW_IMAGE_SIZES = "raw_image_sizes" # h, w # TIME_OFFSETS = "time_offsets" # SPACE_OFFSETS = "space_offsets" # SEGMENTATION_INSTANCE_LABELS = "segmentation_instance_labels" # N_VALID_IDS = "n_valid_ids" # # Path: datasets/util/BoundingBox.py # def get_bbox_from_segmentation_mask_np(mask): # # TODO check if this was a correct translation from the tensorflow version above # object_locations = (np.stack(np.where(np.equal(mask, 1))).T[:, :2]).astype(np.int32) # y0 = np.min(object_locations[:, 0]) # x0 = np.min(object_locations[:, 1]) # y1 = np.max(object_locations[:, 0]) + 1 # x1 = np.max(object_locations[:, 1]) + 1 # bbox = np.stack([y0, x0, y1, x1]) # return bbox . Output only the next line.
box_ious = calculate_ious(anchors, gt_boxes) # NA x NB
Given the following code snippet before the placeholder: <|code_start|> def make_disjoint(tracks, strategy): def get_max_y(obj): _, y, _, h = cocomask.toBbox(obj.mask) return y + h for frame, objects in enumerate(tracks): if len(objects) == 0: continue if strategy == "y_pos": objects_sorted = sorted(objects, key=lambda x: get_max_y(x), reverse=True) elif strategy == "score": objects_sorted = sorted(objects, key=lambda x: x.score, reverse=True) else: assert False, "Unknown mask_disjoint_strategy" objects_disjoint = [objects_sorted[0]] used_pixels = objects_sorted[0].mask for obj in objects_sorted[1:]: new_mask = obj.mask if cocomask.area(cocomask.merge([used_pixels, obj.mask], intersect=True)) > 0.0: obj_mask_decoded = cocomask.decode(obj.mask) used_pixels_decoded = cocomask.decode(used_pixels) obj_mask_decoded[np.where(used_pixels_decoded > 0)] = 0 new_mask = cocomask.encode(obj_mask_decoded) used_pixels = cocomask.merge([used_pixels, obj.mask], intersect=False) <|code_end|> , predict the next line using imports from the current file: import glob import os import numpy as np import pickle import png from pycocotools import mask as cocomask from forwarding.tracking.Util_tracking import TrackElement and context including class names, function names, and sometimes code from other files: # Path: forwarding/tracking/Util_tracking.py # def track_single_sequence(tracker_options, boxes, scores, reids, classes, masks, optical_flow=None): # def tracker_per_class(tracker_options, boxes, scores, reids, classes, masks, class_to_track, start_track_id, # optical_flow=None): # def tracker_per_class_new_reid(tracker_options, boxes, scores, reids, classes, masks, class_to_track, start_track_id, # optical_flow=None): # def calculate_association_similarities(detections_t, last_tracks, flow_tm1_t, tracker_options): # def warp_flow(mask_as_rle, flow): # def _warp(img, flow): # def bbox_iou(box1, box2): # def warp_box(box, flow): # I = max(x1_min - x0_max, 0) * max(y1_min - y0_max, 0) # U = (x1_max - x0_min) * (y1_max - y0_min) . Output only the next line.
objects_disjoint.append(TrackElement(box=obj.box, track_id=obj.track_id, class_=obj.class_, score=obj.score,
Here is a snippet: <|code_start|># encoding: utf-8 # pylint: disable=invalid-name,missing-docstring def test_User_repr(user_instance): assert len(str(user_instance)) > 0 def test_User_auth(user_instance): assert user_instance.is_authenticated assert not user_instance.is_anonymous @pytest.mark.parametrize( 'init_static_roles,is_internal,is_admin,is_regular_user,is_active', [ (_init_static_roles, _is_internal, _is_admin, _is_regular_user, _is_active) \ for _init_static_roles in ( 0, <|code_end|> . Write the next line using the current file imports: import pytest from app.modules.users import models and context from other files: # Path: app/modules/users/models.py # def _get_is_static_role_property(role_name, static_role): # def _is_static_role_property(self): # def _is_static_role_property(self, value): # def mask(self): # def title(self): # def __repr__(self): # def has_static_role(self, role): # def set_static_role(self, role): # def unset_static_role(self, role): # def check_owner(self, user): # def is_authenticated(self): # def is_anonymous(self): # def find_with_password(cls, username, password): # class User(db.Model, Timestamp): # class StaticRoles(enum.Enum): # INTERNAL = (0x8000, "Internal") # ADMIN = (0x4000, "Admin") # REGULAR_USER = (0x2000, "Regular User") # ACTIVE = (0x1000, "Active Account") , which may include functions, classes, or code. Output only the next line.
(models.User.StaticRoles.INTERNAL.mask
Given the code snippet: <|code_start|> @pytest.yield_fixture() def patch_User_password_scheme(): # pylint: disable=invalid-name,protected-access """ By default, the application uses ``bcrypt`` to store passwords securely. However, ``bcrypt`` is a slow hashing algorithm (by design), so it is better to downgrade it to ``plaintext`` while testing, since it will save us quite some time. """ # NOTE: It seems a hacky way, but monkeypatching is a hack anyway. password_field_context = models.User.password.property.columns[0].type.context # NOTE: This is used here to forcefully resolve the LazyCryptContext password_field_context.context_kwds password_field_context._config._init_scheme_list(('plaintext', )) password_field_context._config._init_records() password_field_context._config._init_default_schemes() yield password_field_context._config._init_scheme_list(('bcrypt', )) password_field_context._config._init_records() password_field_context._config._init_default_schemes() @pytest.fixture() def user_instance(patch_User_password_scheme): # pylint: disable=unused-argument,invalid-name user_id = 1 <|code_end|> , generate the next line using the imports in this file: import pytest from flask_login import current_user, login_user, logout_user from tests import utils from app.modules.users import models and context (functions, classes, or occasionally code) from other files: # Path: tests/utils.py # class AutoAuthFlaskClient(FlaskClient): # class JSONResponse(Response): # def __init__(self, *args, **kwargs): # def login(self, user, auth_scopes=None): # def open(self, *args, **kwargs): # def json(self): # def generate_user_instance( # user_id=None, # username="username", # password=None, # email=None, # first_name="First Name", # middle_name="Middle Name", # last_name="Last Name", # created=None, # updated=None, # is_active=True, # is_regular_user=True, # is_admin=False, # is_internal=False # ): # # Path: app/modules/users/models.py # def _get_is_static_role_property(role_name, static_role): # def _is_static_role_property(self): # def _is_static_role_property(self, value): # def mask(self): # def title(self): # def __repr__(self): # def has_static_role(self, role): # def set_static_role(self, role): # def unset_static_role(self, role): # def check_owner(self, user): # def is_authenticated(self): # def is_anonymous(self): # def find_with_password(cls, username, password): # class User(db.Model, Timestamp): # class StaticRoles(enum.Enum): # INTERNAL = (0x8000, "Internal") # ADMIN = (0x4000, "Admin") # REGULAR_USER = (0x2000, "Regular User") # ACTIVE = (0x1000, "Active Account") . Output only the next line.
_user_instance = utils.generate_user_instance(user_id=user_id)
Based on the snippet: <|code_start|># encoding: utf-8 # pylint: disable=missing-docstring,redefined-outer-name @pytest.yield_fixture() def patch_User_password_scheme(): # pylint: disable=invalid-name,protected-access """ By default, the application uses ``bcrypt`` to store passwords securely. However, ``bcrypt`` is a slow hashing algorithm (by design), so it is better to downgrade it to ``plaintext`` while testing, since it will save us quite some time. """ # NOTE: It seems a hacky way, but monkeypatching is a hack anyway. <|code_end|> , predict the immediate next line with the help of imports: import pytest from flask_login import current_user, login_user, logout_user from tests import utils from app.modules.users import models and context (classes, functions, sometimes code) from other files: # Path: tests/utils.py # class AutoAuthFlaskClient(FlaskClient): # class JSONResponse(Response): # def __init__(self, *args, **kwargs): # def login(self, user, auth_scopes=None): # def open(self, *args, **kwargs): # def json(self): # def generate_user_instance( # user_id=None, # username="username", # password=None, # email=None, # first_name="First Name", # middle_name="Middle Name", # last_name="Last Name", # created=None, # updated=None, # is_active=True, # is_regular_user=True, # is_admin=False, # is_internal=False # ): # # Path: app/modules/users/models.py # def _get_is_static_role_property(role_name, static_role): # def _is_static_role_property(self): # def _is_static_role_property(self, value): # def mask(self): # def title(self): # def __repr__(self): # def has_static_role(self, role): # def set_static_role(self, role): # def unset_static_role(self, role): # def check_owner(self, user): # def is_authenticated(self): # def is_anonymous(self): # def find_with_password(cls, username, password): # class User(db.Model, Timestamp): # class StaticRoles(enum.Enum): # INTERNAL = (0x8000, "Internal") # ADMIN = (0x4000, "Admin") # REGULAR_USER = (0x2000, "Regular User") # ACTIVE = (0x1000, "Active Account") . Output only the next line.
password_field_context = models.User.password.property.columns[0].type.context
Given the code snippet: <|code_start|># encoding: utf-8 # pylint: disable=missing-docstring def test_new_team_creation(flask_app_client, db, regular_user): # pylint: disable=invalid-name team_title = "Test Team Title" with flask_app_client.login(regular_user, auth_scopes=('teams:write', )): response = flask_app_client.post('/api/v1/teams/', data={'title': team_title}) assert response.status_code == 200 assert response.content_type == 'application/json' assert set(response.json.keys()) >= {'id', 'title'} assert response.json['title'] == team_title # Cleanup <|code_end|> , generate the next line using the imports in this file: import json from app.modules.teams import models and context (functions, classes, or occasionally code) from other files: # Path: app/modules/teams/models.py # class TeamMember(db.Model): # class Team(db.Model, Timestamp): # def __repr__(self): # def check_owner(self, user): # def check_supervisor(self, user): # def __repr__(self): # def validate_title(self, key, title): # pylint: disable=unused-argument,no-self-use # def check_owner(self, user): . Output only the next line.
team = models.Team.query.get(response.json['id'])
Predict the next line after this snippet: <|code_start|># encoding: utf-8 # pylint: disable=too-few-public-methods,invalid-name,abstract-method,method-hidden """ RESTful API Rules ----------------------- """ class DenyAbortMixin(object): """ A helper permissions mixin raising an HTTP Error (specified in ``DENY_ABORT_CODE``) on deny. NOTE: Apply this mixin before Rule class so it can override NotImplemented deny method. """ DENY_ABORT_HTTP_CODE = HTTPStatus.FORBIDDEN DENY_ABORT_MESSAGE = None def deny(self): """ Abort HTTP request by raising HTTP error exception with a specified HTTP code. """ <|code_end|> using the current file's imports: from flask_login import current_user from flask_restplus._http import HTTPStatus from permission import Rule as BaseRule from app.extensions.api import abort and any relevant context from other files: # Path: app/extensions/api/http_exceptions.py # def abort(code, message=None, **kwargs): # """ # Custom abort function used to provide extra information in the error # response, namely, ``status`` and ``message`` info. # """ # if message is None: # if code in API_DEFAULT_HTTP_CODE_MESSAGES: # pylint: disable=consider-using-get # message = API_DEFAULT_HTTP_CODE_MESSAGES[code] # else: # message = HTTPStatus(code).description # pylint: disable=no-value-for-parameter # restplus_abort(code=code, status=code, message=message, **kwargs) . Output only the next line.
return abort(code=self.DENY_ABORT_HTTP_CODE, message=self.DENY_ABORT_MESSAGE)
Based on the snippet: <|code_start|># encoding: utf-8 """ Webargs Parser wrapper module ----------------------------- """ class CustomWebargsParser(FlaskParser): """ This custom Webargs Parser aims to overload :meth:``handle_error`` in order to call our custom :func:``abort`` function. See the following issue and the related PR for more details: https://github.com/sloria/webargs/issues/122 """ def handle_error(self, error, *args, **kwargs): # pylint: disable=arguments-differ """ Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error. """ status_code = getattr(error, 'status_code', self.DEFAULT_VALIDATION_STATUS) <|code_end|> , predict the immediate next line with the help of imports: from webargs.flaskparser import FlaskParser from .http_exceptions import abort and context (classes, functions, sometimes code) from other files: # Path: app/extensions/api/http_exceptions.py # def abort(code, message=None, **kwargs): # """ # Custom abort function used to provide extra information in the error # response, namely, ``status`` and ``message`` info. # """ # if message is None: # if code in API_DEFAULT_HTTP_CODE_MESSAGES: # pylint: disable=consider-using-get # message = API_DEFAULT_HTTP_CODE_MESSAGES[code] # else: # message = HTTPStatus(code).description # pylint: disable=no-value-for-parameter # restplus_abort(code=code, status=code, message=message, **kwargs) . Output only the next line.
abort(status_code, messages=error.messages)
Given snippet: <|code_start|>from __future__ import unicode_literals User = get_user_model() class UserProfileInline(admin.StackedInline): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from authtools.admin import NamedUserAdmin from .models import Profile from django.contrib.auth import get_user_model from django.urls import reverse from django.utils.html import format_html and context: # Path: src/profiles/models.py # class Profile(BaseProfile): # def __str__(self): # return "{}'s profile".format(self.user) which might include code, classes, or functions. Output only the next line.
model = Profile
Next line prediction: <|code_start|> class MyDoc(object): __database__ = Dingus() __collection__ = Dingus() self.document = MyDoc self.returned = self.connection.connect_document(self.document) def should_return_subclass_of_original(self): assert issubclass(self.returned, self.document) def should_set_connection_on_returned(self): assert self.returned.connection is self.connection def should_set_database_on_returned(self): assert self.returned.database == self.connection[ self.document.__database__] def should_set_collection_on_returned(self): assert self.returned.collection == self.connection[ self.document.__database__][self.document.__collection__] class DescribeModelsGetter(BaseConnectionTest): def setup(self): BaseConnectionTest.setup(self) self.returned = self.connection.models def should_create_document_proxy(self): <|code_end|> . Use current file imports: (from dingus import Dingus, DingusTestCase from nose.tools import assert_raises from scalymongo.connection import DocumentProxy, Connection import scalymongo.connection as mod) and context including class names, function names, or small code snippets from other files: # Path: scalymongo/connection.py # class DocumentProxy(object): # """A proxy object for accessing or creating :class:`Document` models.""" # # def __init__(self, connection, registered): # self.connection = connection # self.registered = {} # for cls in registered: # if cls.__name__ in self.registered: # warnings.warn( # 'Multiple models have been found with the name {0}.' # ' The result of connection.models[{0}] will be undefined.' # .format(repr(cls.__name__))) # self.registered[cls.__name__] = cls # # def __getitem__(self, name): # cls = self._find_document_class(name) # if not cls: # raise KeyError('Unknown document {0}'.format(repr(name))) # return cls # # def __getattr__(self, name): # cls = self._find_document_class(name) # if not cls: # raise AttributeError('Unknown document {0}'.format(repr(name))) # return cls # # def _find_document_class(self, name): # cls = self.registered.get(name) # if not cls: # return None # return self.connection.connect_document(cls) # # def __iter__(self): # """A generator for all models registered on this connection.""" # for value in self.registered.itervalues(): # yield self.connection.connect_document(value) # # class Connection(MongoClient): # """A connection to a MongoDB database. # # This is a wrapper for a :class:`pymongo.mongo_client.MongoClient`. # # """ # # def connect_document(self, document): # """Connect a document by creating a new type and injecting the # connection. # # """ # attrs = { # 'connection': self, # 'database': self[document.__database__], # 'collection': self[document.__database__][document.__collection__], # } # return type('Connected{0}'.format(document.__name__), # (document,), # attrs) # # @property # def models(self): # return DocumentProxy(self, get_concrete_classes()) . Output only the next line.
assert mod.DocumentProxy.calls(
Based on the snippet: <|code_start|> self.field_validator(path, value, sub_structure) def _check_for_unknown_fields(body, structure, path): """Check `body` for any keys not present in `structure`. This only checks the first level of keys. Any keys from :class:`dict`s in the `body`\ 's values will not be checked. """ type_keys = tuple([key for key in structure if isclass(key)]) existing_fields = set([key for key in body if not isclass(key)]) unknown_fields = existing_fields.difference(structure.keys()) # If there are valid types for a key filter out unknown fields that match a # type. if type_keys: unknown_fields = [key for key in unknown_fields if not isinstance(key, type_keys)] if unknown_fields: unknown_fields = ', '.join([repr(field) for field in unknown_fields]) if path: err = ('Encountered field(s), in subdocument at {0},' ' not present in structure: {1}'.format( path, unknown_fields)) else: err = 'Encountered field(s) not present in structure: {0}'.format( unknown_fields) <|code_end|> , predict the immediate next line with the help of imports: from inspect import isclass from scalymongo.errors import ValidationError and context (classes, functions, sometimes code) from other files: # Path: scalymongo/errors.py # class ValidationError(Exception): # """Raised when a model has failed validation.""" # pass . Output only the next line.
raise ValidationError(err)
Using the snippet: <|code_start|>========== """ class Connection(MongoClient): """A connection to a MongoDB database. This is a wrapper for a :class:`pymongo.mongo_client.MongoClient`. """ def connect_document(self, document): """Connect a document by creating a new type and injecting the connection. """ attrs = { 'connection': self, 'database': self[document.__database__], 'collection': self[document.__database__][document.__collection__], } return type('Connected{0}'.format(document.__name__), (document,), attrs) @property def models(self): <|code_end|> , determine the next line of code. You have imports: import warnings from pymongo import MongoClient from scalymongo.document import get_concrete_classes and context (class names, function names, or code) available: # Path: scalymongo/document.py # def get_concrete_classes(): # """Return a set of all non-abstract :class:`Document` subclasses.""" # return DocumentMetaclass.concrete_classes . Output only the next line.
return DocumentProxy(self, get_concrete_classes())
Predict the next line for this snippet: <|code_start|> def run_ensure_indexes(): """Run ensure_indexes.py with the example documents. """ os.environ['PYTHONPATH'] = os.getcwd() process_args = [ 'python', 'scalymongo/manage/ensure_indexes.py', 'tests.acceptance.manage.ensure_indexes_documents', 'localhost:27017', ] return subprocess.check_call(process_args) <|code_end|> with the help of current file imports: import os import subprocess import tests.acceptance.manage.ensure_indexes_documents from tests.acceptance.base_acceptance_test import BaseAcceptanceTest and context from other files: # Path: tests/acceptance/base_acceptance_test.py # class BaseAcceptanceTest(object): # # @classmethod # def setup_class(cls): # cls.connection = Connection() # # @classmethod # def teardown_class(cls): # cls.connection.disconnect() , which may contain function names, class names, or code. Output only the next line.
class TestEnsureIndex(BaseAcceptanceTest):
Given the code snippet: <|code_start|> self.spec = {'foo': Dingus(), 'bar': Dingus()} self.MyDoc.check_query_sharding(self.spec) def should_not_crash(self): pass class WhenShardIndexNotSpecified(BaseDocumentSubclassTest): def setup(self): BaseDocumentSubclassTest.setup(self) self.MyDoc.shard_index = None self.spec = {'foo': Dingus(), 'bar': Dingus()} self.MyDoc.check_query_sharding(self.spec) def should_not_crash(self): pass class WhenShardIndexNotSpecified(BaseDocumentSubclassTest): def setup(self): BaseDocumentSubclassTest.setup(self) self.MyDoc.shard_index = {'fields': ['biz']} self.spec = {'foo': Dingus()} def should_raise_global_query_exception(self): assert_raises( <|code_end|> , generate the next line using the imports in this file: from deterministic_dingus import DeterministicDingus from dingus import DingusTestCase, Dingus, exception_raiser from nose.tools import assert_raises from scalymongo.document import * from scalymongo.errors import GlobalQueryException, ModifyFailedError import scalymongo.document as mod and context (functions, classes, or occasionally code) from other files: # Path: scalymongo/errors.py # class GlobalQueryException(Exception): # """Raised when a query will hit multiple shards. # # This exception is raised by default when doing a # :meth:`~scalymongo.document.Document.find`, # :meth:`~scalymongo.document.Document.remove` or any other type of query # when the query is likely to hit multiple shards. This check is done in # order to warn developers of behavior that may not perform well at scale. # # """ # pass # # class ModifyFailedError(Exception): # """Raised when :meth:`~scalymongo.document.Document.modify` fails.""" # pass . Output only the next line.
GlobalQueryException, self.MyDoc.check_query_sharding, self.spec)
Using the snippet: <|code_start|> ): def setup(self): BaseModify.setup(self) self.my_doc.modify(self.update) class TestModifyWithExplicitQuerySpec( BaseModify, PropertyModifyWithExplicitQuerySpec, PropertyModifyUpdatesLocalCopy, ): def setup(self): BaseModify.setup(self) self.query = {'blarg': Dingus('blarg')} self.my_doc.modify(self.update, query=self.query) class WhenFindAndModifyReturnsNone( BaseModify, ): def setup(self): BaseModify.setup(self) self.query = {'blarg': Dingus('blarg')} self.MyDoc.reload = Dingus('reload') self.MyDoc.find_and_modify.return_value = None assert_raises( <|code_end|> , determine the next line of code. You have imports: from deterministic_dingus import DeterministicDingus from dingus import DingusTestCase, Dingus, exception_raiser from nose.tools import assert_raises from scalymongo.document import * from scalymongo.errors import GlobalQueryException, ModifyFailedError import scalymongo.document as mod and context (class names, function names, or code) available: # Path: scalymongo/errors.py # class GlobalQueryException(Exception): # """Raised when a query will hit multiple shards. # # This exception is raised by default when doing a # :meth:`~scalymongo.document.Document.find`, # :meth:`~scalymongo.document.Document.remove` or any other type of query # when the query is likely to hit multiple shards. This check is done in # order to warn developers of behavior that may not perform well at scale. # # """ # pass # # class ModifyFailedError(Exception): # """Raised when :meth:`~scalymongo.document.Document.modify` fails.""" # pass . Output only the next line.
ModifyFailedError,
Predict the next line after this snippet: <|code_start|> class BaseCursorTestCase(DingusWhitelistTestCase): module = mod additional_mocks = ['wrapped_cursor'] def setup(self): DingusWhitelistTestCase.setup(self) self.document_type = DeterministicDingus('document_type') <|code_end|> using the current file's imports: from deterministic_dingus import DingusWhitelistTestCase, Dingus, DeterministicDingus from scalymongo.cursor import Cursor import scalymongo.cursor as mod and any relevant context from other files: # Path: scalymongo/cursor.py # class Cursor(object): # """Wrapper for :class:`pymongo.cursor.Cursor` objects. # # This class is a thin wrapper which takes results returned by the underlying # cursor and wraps them in the appropriate # :class:`~scalymongo.document.Document` subclass. # # """ # # def __init__(self, wrapped_cursor, document_type): # self.__wrapped_cursor = wrapped_cursor # self.__document_type = document_type # # def __getitem__(self, index): # """Get the item(s) at `index`. # # :param index: may also be a slice. # """ # returned = self.__wrapped_cursor[index] # # If the index is a slice then the result is a new cursor with the skip # # and limit already applied. # if isinstance(index, slice): # return Cursor(returned, self.__document_type) # return self.__document_type(returned) # # def next(self): # """Return the next document for this cursor.""" # return self.__document_type(self.__wrapped_cursor.next()) # # def __iter__(self): # return self # # # Wrap all methods that return a pymongo.cursor.Cursor. # batch_size = _make_cursor_wrapper_method('batch_size') # clone = _make_cursor_wrapper_method('clone') # hint = _make_cursor_wrapper_method('hint') # limit = _make_cursor_wrapper_method('limit') # max_scan = _make_cursor_wrapper_method('max_scan') # rewind = _make_cursor_wrapper_method('rewind') # skip = _make_cursor_wrapper_method('skip') # sort = _make_cursor_wrapper_method('sort') # where = _make_cursor_wrapper_method('where') # # def __getattr__(self, attr): # """All other methods and properties are those of the wrapped cursor.""" # return getattr(self.__wrapped_cursor, attr) . Output only the next line.
self.cursor = Cursor(self.wrapped_cursor, self.document_type)
Using the snippet: <|code_start|>## validate_single_field ## class DescribeValidateSingleField( DingusTestCase(validate_single_field, ['ValidationError'])): def setup(self): super(DescribeValidateSingleField, self).setup() self.path = Dingus('path') self.value = Dingus('value') self.expected_type = Dingus('expected_type') class WhenFieldIsExpectedType(DescribeValidateSingleField): def setup(self): DescribeValidateSingleField.setup(self) mod.is_field_of_expected_type.return_value = True def should_not_crash(self): validate_single_field(self.path, self.value, self.expected_type) class WhenFieldIsNotExpectedType(DescribeValidateSingleField): def setup(self): DescribeValidateSingleField.setup(self) mod.is_field_of_expected_type.return_value = False def should_not_crash(self): <|code_end|> , determine the next line of code. You have imports: import datetime import scalymongo.schema as mod from dingus import Dingus, DingusTestCase, DontCare from nose.tools import assert_raises from scalymongo.schema import * from tests.helpers import assert_raises_with_message and context (class names, function names, or code) available: # Path: tests/helpers.py # def assert_raises_with_message( # exception_type, message, function, *args, **kwargs): # """Assert that a function raises an exception with :param message: as its # message. # """ # try: # function(*args, **kwargs) # except exception_type as ex: # if str(ex) != message: # raise AssertionError( # 'Expected {0} with message of {1}, but message was {2}' # .format(exception_type.__name__, repr(message), repr(str(ex)))) # return # raise AssertionError('{0} not raised'.format(exception_type.__name__)) . Output only the next line.
assert_raises_with_message(
Given the code snippet: <|code_start|> def should_print_help(self): assert self.parser.calls('print_help') #### ## ## main ## #### class DescribeParseArguments(DingusWhitelistTestCase): module = mod module_mocks = [ 'parse_arguments', '__import__', 'Connection', 'ensure_indexes'] additional_mocks = ['options', 'module_name', 'endpoint'] def run(self): self.module.parse_arguments.return_value = ( self.options, self.module_name, self.endpoint) main() def should_import_module(self): assert self.module.__import__.calls('()', self.module_name) def should_make_Connection(self): assert self.module.Connection.calls('()', self.endpoint) def should_ensure_indexes(self): <|code_end|> , generate the next line using the imports in this file: from deterministic_dingus import DingusWhitelistTestCase, Dingus from nose.tools import assert_raises, assert_equals from scalymongo.manage.ensure_indexes import ( ensure_indexes, main, parse_arguments, ) import scalymongo.manage.ensure_indexes as mod and context (functions, classes, or occasionally code) from other files: # Path: scalymongo/manage/ensure_indexes.py # def ensure_indexes(connection, options): # for model in connection.models: # model.ensure_indexes(background=options.background) # # def main(): # options, module_name, endpoint = parse_arguments() # # # Import the models so that they get registered with Connection. # __import__(module_name) # # connection = Connection(endpoint) # ensure_indexes(connection, options) # # def parse_arguments(): # """Parse and validate the arguments. # # This returns a tuple like ``(options, module_name, endpoint)``. # # """ # parser = OptionParser() # parser.usage = '%prog [options] MODULE ENDPOINT' # parser.add_option( # '--background', action='store_true', # help='create indexes as a non-blocking operation [default]', # ) # parser.add_option( # '--no-background', action='store_false', dest='background', # help='disable background index creation', # ) # parser.set_defaults(background=True) # # options, arguments = parser.parse_args() # # if len(arguments) != 2: # parser.print_help() # exit(1) # # module_name, endpoint = arguments # return options, module_name, endpoint . Output only the next line.
assert self.module.ensure_indexes.calls(
Next line prediction: <|code_start|> additional_mocks = ['arguments'] def setup(self): BaseParseArgumentsTestCase.setup(self) self.parser.parse_args.return_value = (self.options, self.arguments) assert_raises(SystemExit, parse_arguments) def should_print_help(self): assert self.parser.calls('print_help') #### ## ## main ## #### class DescribeParseArguments(DingusWhitelistTestCase): module = mod module_mocks = [ 'parse_arguments', '__import__', 'Connection', 'ensure_indexes'] additional_mocks = ['options', 'module_name', 'endpoint'] def run(self): self.module.parse_arguments.return_value = ( self.options, self.module_name, self.endpoint) <|code_end|> . Use current file imports: (from deterministic_dingus import DingusWhitelistTestCase, Dingus from nose.tools import assert_raises, assert_equals from scalymongo.manage.ensure_indexes import ( ensure_indexes, main, parse_arguments, ) import scalymongo.manage.ensure_indexes as mod) and context including class names, function names, or small code snippets from other files: # Path: scalymongo/manage/ensure_indexes.py # def ensure_indexes(connection, options): # for model in connection.models: # model.ensure_indexes(background=options.background) # # def main(): # options, module_name, endpoint = parse_arguments() # # # Import the models so that they get registered with Connection. # __import__(module_name) # # connection = Connection(endpoint) # ensure_indexes(connection, options) # # def parse_arguments(): # """Parse and validate the arguments. # # This returns a tuple like ``(options, module_name, endpoint)``. # # """ # parser = OptionParser() # parser.usage = '%prog [options] MODULE ENDPOINT' # parser.add_option( # '--background', action='store_true', # help='create indexes as a non-blocking operation [default]', # ) # parser.add_option( # '--no-background', action='store_false', dest='background', # help='disable background index creation', # ) # parser.set_defaults(background=True) # # options, arguments = parser.parse_args() # # if len(arguments) != 2: # parser.print_help() # exit(1) # # module_name, endpoint = arguments # return options, module_name, endpoint . Output only the next line.
main()
Next line prediction: <|code_start|> def should_add_background_option(self): assert self.parser.calls( 'add_option', '--background', action='store_true', help='create indexes as a non-blocking operation [default]', ) def should_add_no_background_option(self): assert self.parser.calls( 'add_option', '--no-background', action='store_false', dest='background', help='disable background index creation', ) def should_set_default_to_background_True(self): assert self.parser.calls('set_defaults', background=True) def should_parse_args(self): assert self.parser.calls('parse_args') class WhenArgumentsParseSuccessfully(BaseParseArgumentsTestCase): additional_mocks = ['module_name', 'endpoint'] def setup(self): BaseParseArgumentsTestCase.setup(self) self.arguments = (self.module_name, self.endpoint) self.parser.parse_args.return_value = (self.options, self.arguments) <|code_end|> . Use current file imports: (from deterministic_dingus import DingusWhitelistTestCase, Dingus from nose.tools import assert_raises, assert_equals from scalymongo.manage.ensure_indexes import ( ensure_indexes, main, parse_arguments, ) import scalymongo.manage.ensure_indexes as mod) and context including class names, function names, or small code snippets from other files: # Path: scalymongo/manage/ensure_indexes.py # def ensure_indexes(connection, options): # for model in connection.models: # model.ensure_indexes(background=options.background) # # def main(): # options, module_name, endpoint = parse_arguments() # # # Import the models so that they get registered with Connection. # __import__(module_name) # # connection = Connection(endpoint) # ensure_indexes(connection, options) # # def parse_arguments(): # """Parse and validate the arguments. # # This returns a tuple like ``(options, module_name, endpoint)``. # # """ # parser = OptionParser() # parser.usage = '%prog [options] MODULE ENDPOINT' # parser.add_option( # '--background', action='store_true', # help='create indexes as a non-blocking operation [default]', # ) # parser.add_option( # '--no-background', action='store_false', dest='background', # help='disable background index creation', # ) # parser.set_defaults(background=True) # # options, arguments = parser.parse_args() # # if len(arguments) != 2: # parser.print_help() # exit(1) # # module_name, endpoint = arguments # return options, module_name, endpoint . Output only the next line.
self.returned = parse_arguments()
Continue the code snippet: <|code_start|> """ parser = OptionParser() parser.usage = '%prog [options] MODULE ENDPOINT' parser.add_option( '--background', action='store_true', help='create indexes as a non-blocking operation [default]', ) parser.add_option( '--no-background', action='store_false', dest='background', help='disable background index creation', ) parser.set_defaults(background=True) options, arguments = parser.parse_args() if len(arguments) != 2: parser.print_help() exit(1) module_name, endpoint = arguments return options, module_name, endpoint def main(): options, module_name, endpoint = parse_arguments() # Import the models so that they get registered with Connection. __import__(module_name) <|code_end|> . Use current file imports: from optparse import OptionParser from scalymongo.connection import Connection and context (classes, functions, or code) from other files: # Path: scalymongo/connection.py # class Connection(MongoClient): # """A connection to a MongoDB database. # # This is a wrapper for a :class:`pymongo.mongo_client.MongoClient`. # # """ # # def connect_document(self, document): # """Connect a document by creating a new type and injecting the # connection. # # """ # attrs = { # 'connection': self, # 'database': self[document.__database__], # 'collection': self[document.__database__][document.__collection__], # } # return type('Connected{0}'.format(document.__name__), # (document,), # attrs) # # @property # def models(self): # return DocumentProxy(self, get_concrete_classes()) . Output only the next line.
connection = Connection(endpoint)
Predict the next line for this snippet: <|code_start|> class BaseAcceptanceTest(object): @classmethod def setup_class(cls): <|code_end|> with the help of current file imports: from scalymongo import Connection and context from other files: # Path: scalymongo/connection.py # class Connection(MongoClient): # """A connection to a MongoDB database. # # This is a wrapper for a :class:`pymongo.mongo_client.MongoClient`. # # """ # # def connect_document(self, document): # """Connect a document by creating a new type and injecting the # connection. # # """ # attrs = { # 'connection': self, # 'database': self[document.__database__], # 'collection': self[document.__database__][document.__collection__], # } # return type('Connected{0}'.format(document.__name__), # (document,), # attrs) # # @property # def models(self): # return DocumentProxy(self, get_concrete_classes()) , which may contain function names, class names, or code. Output only the next line.
cls.connection = Connection()
Given snippet: <|code_start|> class BaseStructureWalker(object): @classmethod def setup_class(self): self.field_validator = Dingus('field_validator') <|code_end|> , continue by predicting the next line. Consider current file imports: from dingus import Dingus from scalymongo.structure_walker import StructureWalker and context: # Path: scalymongo/structure_walker.py # class StructureWalker(object): # """A helper class to recurse a :class:`dict`-like object in accordance with # a structure. # # :param field_translator: should be function mapping the ``value`` and # ``type_`` to the new value for a key. # # """ # # def __init__(self, field_validator): # self.field_validator = field_validator # # def walk_dict(self, body, structure, path=None): # """Validate a dictionary in accordance with `structure`. # # A :class:`ValidationError` is raised if any fields in `body` are # not present in `structure`. # # """ # _check_for_unknown_fields(body, structure, path) # # for field, sub_structure in structure.iteritems(): # if isclass(field): # field_type = field # # For structures like {<TYPE>: {<STRUCT>}} iterate values # # in the body with keys of <TYPE> and verify each against # # <STRUCT>. # for key, value in body.iteritems(): # if isinstance(key, field_type): # self._recurse_or_validate_field( # value, sub_structure, _join(path, key)) # # if field in body: # self._recurse_or_validate_field( # body[field], sub_structure, _join(path, field)) # # def _recurse_or_validate_field(self, value, sub_structure, path): # if isinstance(sub_structure, list): # assert len(sub_structure) == 1 # if isinstance(value, dict): # # If the structure is a dict this is fine so long as all of the # # keys are integers or the positional operator (`$`). This # # happens with the $set update modifier since we expand # # {'foo.0.bar': 1} to {'foo': {'0': {'bar': 1}}} # for key, value in value.iteritems(): # assert key.isdigit() or key == '$' # self._recurse_or_validate_field( # value, sub_structure[0], _join(path, key)) # else: # # Validate each value in the list against the specified content # # type. # for i, value in enumerate(value): # self._recurse_or_validate_field( # value, sub_structure[0], _join(path, i)) # return # # if isinstance(sub_structure, dict): # self.walk_dict(value, sub_structure, path) # return # # self.field_validator(path, value, sub_structure) which might include code, classes, or functions. Output only the next line.
self.structure_walker = StructureWalker(self.field_validator)
Predict the next line for 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. ############################################################################### # Helper Functions ############################################################################### def define_LNR(nf=64, texture_channels=16, texture_res=16, n_textures=25, gpu_ids=[]): """Create a layered neural renderer. Parameters: nf (int) -- the number of channels in the first/last conv layers texture_channels (int) -- the number of channels in the neural texture texture_res (int) -- the size of each individual texture map n_textures (int) -- the number of individual texture maps gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a layered neural rendering model. """ net = LayeredNeuralRenderer(nf, texture_channels, texture_res, n_textures) <|code_end|> with the help of current file imports: import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from third_party.models.networks import init_net and context from other files: # Path: third_party/models/networks.py # def init_net(net, gpu_ids=[]): # """Initialize a network by registering CPU/GPU device (with multi-GPU support) # Parameters: # net (network) -- the network to be initialized # gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 # # Return an initialized network. # """ # if len(gpu_ids) > 0: # assert (torch.cuda.is_available()) # net.to(gpu_ids[0]) # net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs # return net , which may contain function names, class names, or code. Output only the next line.
return init_net(net, gpu_ids)
Given snippet: <|code_start|># limitations under the License. class LayeredVideoDataset(BaseDataset): """A dataset class for video layers. It assumes that the directory specified by 'dataroot' contains metadata.json, and the directories iuv, rgb_256, and rgb_512. The 'iuv' directory should contain directories named 01, 02, etc. for each layer, each containing per-frame UV images. """ @staticmethod def modify_commandline_options(parser, is_train): parser.add_argument('--height', type=int, default=256, help='image height') parser.add_argument('--width', type=int, default=448, help='image width') parser.add_argument('--trimap_width', type=int, default=20, help='trimap gray area width') parser.add_argument('--use_mask_images', action='store_true', default=False, help='use custom masks') parser.add_argument('--use_homographies', action='store_true', default=False, help='handle camera motion') return parser def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) rgbdir = os.path.join(opt.dataroot, 'rgb_256') if opt.do_upsampling: rgbdir = os.path.join(opt.dataroot, 'rgb_512') uvdir = os.path.join(opt.dataroot, 'iuv') <|code_end|> , continue by predicting the next line. Consider current file imports: import cv2 import torchvision.transforms as transforms import torch.nn.functional as F import os import torch import numpy as np import json from third_party.data.base_dataset import BaseDataset from third_party.data.image_folder import make_dataset from PIL import Image and context: # Path: third_party/data/base_dataset.py # class BaseDataset(data.Dataset, ABC): # """This class is an abstract base class (ABC) for datasets. # # To create a subclass, you need to implement the following four functions: # -- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt). # -- <__len__>: return the size of dataset. # -- <__getitem__>: get a data point. # -- <modify_commandline_options>: (optionally) add dataset-specific options and set default options. # """ # # def __init__(self, opt): # """Initialize the class; save the options in the class # # Parameters: # opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions # """ # self.opt = opt # self.root = opt.dataroot # # @staticmethod # def modify_commandline_options(parser, is_train): # """Add new dataset-specific options, and rewrite default values for existing options. # # Parameters: # parser -- original option parser # is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. # # Returns: # the modified parser. # """ # return parser # # @abstractmethod # def __len__(self): # """Return the total number of images in the dataset.""" # return 0 # # @abstractmethod # def __getitem__(self, index): # """Return a data point and its metadata information. # # Parameters: # index - - a random integer for data indexing # # Returns: # a dictionary of data with their names. It ususally contains the data itself and its metadata information. # """ # pass # # Path: third_party/data/image_folder.py # def make_dataset(dir, max_dataset_size=float("inf")): # images = [] # assert os.path.isdir(dir), '%s is not a valid directory' % dir # # for root, _, fnames in sorted(os.walk(dir)): # for fname in fnames: # if is_image_file(fname): # path = os.path.join(root, fname) # images.append(path) # images = sorted(images) # return images[:min(max_dataset_size, len(images))] which might include code, classes, or functions. Output only the next line.
self.image_paths = sorted(make_dataset(rgbdir, opt.max_dataset_size))
Predict the next line after this snippet: <|code_start|> sys.exit("There was an error parsing " + compounds_file + "\n" + "I/O error({0}): {1}".format(e.errno, e.strerror)) return cpds def reactions(organism_type="", rctf='Biochemistry/reactions.master.tsv', verbose=False): """ Parse the reaction information in Biochemistry/reactions.master.tsv One reaction ID is associated with one equation and thus many compounds and parts. If the boolean verbose is set we will print out error/debugging messages. You can supply an alternative reactions file (rctf) if you don't like the default. :param organism_type: The type of organism, eg. microbial, gram_negative, gram_positive :type organism_type: str :param rctf: The optional reaction file to provide :type rctf: str :param verbose: Print more output :type verbose: bool :return: Two components, a dict of the reactions and a dict of all the compounds used in the reactions. :rtype: dict, dict """ <|code_end|> using the current file's imports: import copy import os import re import sys import io import PyFBA from .model_seed import location and any relevant context from other files: # Path: PyFBA/parse/model_seed.py # def location() -> Dict[str, str]: # """Parse or return the codes for the locations. The ModelSEEDDatabase # uses codes, and has a compartments file but they do not match up. # # This is currently hardcoded, but is put here so we can rewrite it as # if the compartments file is updated # # :return: A dict of location numeric IDs and string IDs # :rtype: dict # """ # # # 0: cytoplasmic, 1: extracellular, 2: chloroplast # # all_locations = {'0': 'c', '1': 'e', '2': 'h'} # return all_locations . Output only the next line.
locations = location()
Given snippet: <|code_start|> lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.) dip_type = h.fixed("dip_vae.dip_type", "ii") config_dip_vae_ii = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # BetaTCVAE config. model_name = h.fixed("model.name", "beta_tc_vae") model_fn = h.fixed("model.model", "@beta_tc_vae()") betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.])) config_beta_tc_vae = h.zipit([model_name, model_fn, betas]) all_models = h.chainit([ config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii, config_beta_tc_vae, config_annealed_beta_vae ]) return all_models def get_config(): """Returns the hyperparameter configs for different experiments.""" arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1) arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1) architecture = h.zipit([arch_enc, arch_dec]) return h.product([ get_datasets(), architecture, get_default_models(), get_seeds(5), ]) <|code_end|> , continue by predicting the next line. Consider current file imports: from disentanglement_lib.config import study from disentanglement_lib.utils import resources from six.moves import range import disentanglement_lib.utils.hyperparams as h and context: # Path: disentanglement_lib/config/study.py # class Study(object): # def get_model_config(self, model_num=0): # def print_model_config(self, model_num=0): # def get_postprocess_config_files(self): # def print_postprocess_config(self): # def get_eval_config_files(self): # def print_eval_config(self): # # Path: disentanglement_lib/utils/resources.py # def get_file(path): # def get_files_in_folder(path): which might include code, classes, or functions. Output only the next line.
class AbstractReasoningStudyV1(study.Study):
Using the snippet: <|code_start|> model_fn = h.fixed("model.model", "@beta_tc_vae()") betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.])) config_beta_tc_vae = h.zipit([model_name, model_fn, betas]) all_models = h.chainit([ config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii, config_beta_tc_vae, config_annealed_beta_vae ]) return all_models def get_config(): """Returns the hyperparameter configs for different experiments.""" arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1) arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1) architecture = h.zipit([arch_enc, arch_dec]) return h.product([ get_datasets(), architecture, get_default_models(), get_seeds(5), ]) class AbstractReasoningStudyV1(study.Study): """Defines the study for the paper.""" def get_model_config(self, model_num=0): """Returns model bindings and config file.""" config = get_config()[model_num] model_bindings = h.to_bindings(config) <|code_end|> , determine the next line of code. You have imports: from disentanglement_lib.config import study from disentanglement_lib.utils import resources from six.moves import range import disentanglement_lib.utils.hyperparams as h and context (class names, function names, or code) available: # Path: disentanglement_lib/config/study.py # class Study(object): # def get_model_config(self, model_num=0): # def print_model_config(self, model_num=0): # def get_postprocess_config_files(self): # def print_postprocess_config(self): # def get_eval_config_files(self): # def print_eval_config(self): # # Path: disentanglement_lib/utils/resources.py # def get_file(path): # def get_files_in_folder(path): . Output only the next line.
model_config_file = resources.get_file(
Using the snippet: <|code_start|># 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. """Tests for relational_layers.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function def _create_positional_encoding_matrices(): """Shared input/output pair for the positional encoding tests.""" input_array = np.arange(24, dtype=np.float64).reshape((1, 4, 3, 2)) output_array = np.eye(4) output_array = np.repeat(np.expand_dims(output_array, -1), 2, axis=-1) output_array = np.expand_dims(output_array, 0) return input_array, output_array class RelationalLayersTest(tf.test.TestCase): def test_repeat_for_tensor(self): a = np.arange(24).reshape((1, 4, 3, 2)) shouldbe = np.concatenate([a] * 3, axis=-2) <|code_end|> , determine the next line of code. You have imports: from disentanglement_lib.evaluation.abstract_reasoning import relational_layers import numpy as np import tensorflow.compat.v1 as tf and context (class names, function names, or code) available: # Path: disentanglement_lib/evaluation/abstract_reasoning/relational_layers.py # class RelationalLayer(tf.keras.layers.Layer): # class PairwiseEdgeEmbeddings(tf.keras.layers.Layer): # class AddPositionalEncoding(tf.keras.layers.Layer): # class StackAnswers(tf.keras.layers.Layer): # class MultiDimBatchApply(tf.keras.layers.Layer): # def __init__(self, edge_layer, reduce_layer): # def call(self, inputs, **kwargs): # def call(self, inputs, **kwargs): # def repeat(tensor, num, axis): # def positional_encoding_like(tensor, positional_encoding_axis=-2, # value_axis=-1): # def __init__(self, positional_encoding_axis=-2, embedding_axis=-1): # def call(self, inputs, **kwargs): # def __init__(self, answer_axis=-2, stack_axis=-3): # def call(self, inputs, **kwargs): # def __init__(self, layer, num_dims_to_keep=3): # def call(self, inputs, **kwargs): . Output only the next line.
result = self.evaluate(relational_layers.repeat(tf.constant(a), 3, axis=-2))
Next line prediction: <|code_start|> num_train=gin.REQUIRED, num_test_points_per_class=gin.REQUIRED, batch_size=16): """Computes unfairness scores. We first compute either the mean or maximum total variation for a given sensitive and target variable. Then, we either average or take the maximum with respect to target and sensitive variable. For convenience, we compute and save all combinations. The score used in Section 4 of the paper is here called mean_fairness:mean_pred:mean_sens. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Optional path to directory where artifacts can be saved. num_train: Number of points used for training. num_test_points_per_class: Number of points used for testing. batch_size: Batch size for sampling. Returns: Dictionary with scores. """ del artifact_dir factor_counts = ground_truth_data.factors_num_values num_factors = len(factor_counts) scores = {} # Training a predictive model. <|code_end|> . Use current file imports: (from disentanglement_lib.evaluation.metrics import utils from six.moves import range import numpy as np import gin.tf) and context including class names, function names, or small code snippets from other files: # Path: disentanglement_lib/evaluation/metrics/utils.py # def generate_batch_factor_code(ground_truth_data, representation_function, # num_points, random_state, batch_size): # def split_train_test(observations, train_percentage): # def obtain_representation(observations, representation_function, batch_size): # def discrete_mutual_info(mus, ys): # def discrete_entropy(ys): # def make_discretizer(target, num_bins=gin.REQUIRED, # discretizer_fn=gin.REQUIRED): # def _histogram_discretize(target, num_bins=gin.REQUIRED): # def normalize_data(data, mean=None, stddev=None): # def make_predictor_fn(predictor_fn=gin.REQUIRED): # def logistic_regression_cv(): # def gradient_boosting_classifier(): . Output only the next line.
mus_train, ys_train = utils.generate_batch_factor_code(
Given the code snippet: <|code_start|> @gin.configurable("evaluation", blacklist=["model_dirs", "output_dir"]) def evaluate(model_dirs, output_dir, evaluation_fn=gin.REQUIRED, random_seed=gin.REQUIRED, name=""): """Loads a trained estimator and evaluates it according to beta-VAE metric.""" # The name will be part of the gin config and can be used to tag results. del name # Set up time to keep track of elapsed time in results. experiment_timer = time.time() # Automatically set the proper dataset if necessary. We replace the active # gin config as this will lead to a valid gin config file where the dataset # is present. if gin.query_parameter("dataset.name") == "auto": # Obtain the dataset name from the gin config of the previous step. gin_config_file = os.path.join(model_dirs[0], "results", "gin", "train.gin") gin_dict = results.gin_dict(gin_config_file) with gin.unlock_config(): print(gin_dict["dataset.name"]) gin.bind_parameter("dataset.name", gin_dict["dataset.name"].replace("'", "")) output_dir = os.path.join(output_dir) if tf.io.gfile.isdir(output_dir): tf.io.gfile.rmtree(output_dir) <|code_end|> , generate the next line using the imports in this file: import contextlib import os import time import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub import gin.tf from absl import flags from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.evaluation.udr.metrics import udr # pylint: disable=unused-import from disentanglement_lib.utils import results and context (functions, classes, or occasionally code) from other files: # Path: disentanglement_lib/data/ground_truth/named_data.py # def get_named_ground_truth_data(name): # # Path: disentanglement_lib/evaluation/udr/metrics/udr.py # def relative_strength_disentanglement(corr_matrix): # def spearman_correlation_conv(vec1, vec2): # def lasso_correlation_matrix(vec1, vec2, random_state=None): # def _generate_representation_batch(ground_truth_data, representation_functions, # batch_size, random_state): # def _generate_representation_dataset(ground_truth_data, # representation_functions, batch_size, # num_data_points, random_state): # def compute_udr_sklearn(ground_truth_data, # representation_functions, # random_state, # batch_size, # num_data_points, # correlation_matrix="lasso", # filter_low_kl=True, # include_raw_correlations=True, # kl_filter_threshold=0.01): # # Path: disentanglement_lib/utils/results.py # def update_result_directory(result_directory, # step_name, # results_dict, # old_result_directory=None): # def _copy_recursively(path_to_old_dir, path_to_new_dir): # def copydir(path_to_old_dir, path_to_new_dir): # def save_gin(config_path): # def default(self, obj): # def save_dict(config_path, dict_with_info): # def gin_dict(config_path=None): # def namespaced_dict(base_dict=None, **named_dicts): # def aggregate_json_results(base_path): # class Encoder(json.JSONEncoder): . Output only the next line.
dataset = named_data.get_named_ground_truth_data()
Given the code snippet: <|code_start|>(https://arxiv.org/abs/1905.12614) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function FLAGS = flags.FLAGS @gin.configurable("evaluation", blacklist=["model_dirs", "output_dir"]) def evaluate(model_dirs, output_dir, evaluation_fn=gin.REQUIRED, random_seed=gin.REQUIRED, name=""): """Loads a trained estimator and evaluates it according to beta-VAE metric.""" # The name will be part of the gin config and can be used to tag results. del name # Set up time to keep track of elapsed time in results. experiment_timer = time.time() # Automatically set the proper dataset if necessary. We replace the active # gin config as this will lead to a valid gin config file where the dataset # is present. if gin.query_parameter("dataset.name") == "auto": # Obtain the dataset name from the gin config of the previous step. gin_config_file = os.path.join(model_dirs[0], "results", "gin", "train.gin") <|code_end|> , generate the next line using the imports in this file: import contextlib import os import time import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub import gin.tf from absl import flags from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.evaluation.udr.metrics import udr # pylint: disable=unused-import from disentanglement_lib.utils import results and context (functions, classes, or occasionally code) from other files: # Path: disentanglement_lib/data/ground_truth/named_data.py # def get_named_ground_truth_data(name): # # Path: disentanglement_lib/evaluation/udr/metrics/udr.py # def relative_strength_disentanglement(corr_matrix): # def spearman_correlation_conv(vec1, vec2): # def lasso_correlation_matrix(vec1, vec2, random_state=None): # def _generate_representation_batch(ground_truth_data, representation_functions, # batch_size, random_state): # def _generate_representation_dataset(ground_truth_data, # representation_functions, batch_size, # num_data_points, random_state): # def compute_udr_sklearn(ground_truth_data, # representation_functions, # random_state, # batch_size, # num_data_points, # correlation_matrix="lasso", # filter_low_kl=True, # include_raw_correlations=True, # kl_filter_threshold=0.01): # # Path: disentanglement_lib/utils/results.py # def update_result_directory(result_directory, # step_name, # results_dict, # old_result_directory=None): # def _copy_recursively(path_to_old_dir, path_to_new_dir): # def copydir(path_to_old_dir, path_to_new_dir): # def save_gin(config_path): # def default(self, obj): # def save_dict(config_path, dict_with_info): # def gin_dict(config_path=None): # def namespaced_dict(base_dict=None, **named_dicts): # def aggregate_json_results(base_path): # class Encoder(json.JSONEncoder): . Output only the next line.
gin_dict = results.gin_dict(gin_config_file)
Based on the snippet: <|code_start|># coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for fairness.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports class FairnessTest(absltest.TestCase): def test_metric(self): gin.bind_parameter("predictor.predictor_fn", utils.gradient_boosting_classifier) <|code_end|> , predict the immediate next line with the help of imports: from absl.testing import absltest from disentanglement_lib.data.ground_truth import dummy_data from disentanglement_lib.evaluation.metrics import fairness from disentanglement_lib.evaluation.metrics import utils import numpy as np import gin.tf and context (classes, functions, sometimes code) from other files: # Path: disentanglement_lib/data/ground_truth/dummy_data.py # class IdentityObservationsData(ground_truth_data.GroundTruthData): # class DummyData(ground_truth_data.GroundTruthData): # def num_factors(self): # def observation_shape(self): # def factors_num_values(self): # def sample_factors(self, num, random_state): # def sample_observations_from_factors(self, factors, random_state): # def factor_names(self): # def num_factors(self): # def factors_num_values(self): # def observation_shape(self): # def sample_factors(self, num, random_state): # def sample_observations_from_factors(self, factors, random_state): # # Path: disentanglement_lib/evaluation/metrics/fairness.py # def compute_fairness(ground_truth_data, # representation_function, # random_state, # artifact_dir=None, # num_train=gin.REQUIRED, # num_test_points_per_class=gin.REQUIRED, # batch_size=16): # def compute_scores_dict(metric, prefix): # def inter_group_fairness(counts): # # Path: disentanglement_lib/evaluation/metrics/utils.py # def generate_batch_factor_code(ground_truth_data, representation_function, # num_points, random_state, batch_size): # def split_train_test(observations, train_percentage): # def obtain_representation(observations, representation_function, batch_size): # def discrete_mutual_info(mus, ys): # def discrete_entropy(ys): # def make_discretizer(target, num_bins=gin.REQUIRED, # discretizer_fn=gin.REQUIRED): # def _histogram_discretize(target, num_bins=gin.REQUIRED): # def normalize_data(data, mean=None, stddev=None): # def make_predictor_fn(predictor_fn=gin.REQUIRED): # def logistic_regression_cv(): # def gradient_boosting_classifier(): . Output only the next line.
ground_truth_data = dummy_data.DummyData()
Predict the next line for this snippet: <|code_start|># 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. """Tests for fairness.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports class FairnessTest(absltest.TestCase): def test_metric(self): gin.bind_parameter("predictor.predictor_fn", utils.gradient_boosting_classifier) ground_truth_data = dummy_data.DummyData() def representation_function(x): return np.array(x, dtype=np.float64)[:, :, 0, 0] random_state = np.random.RandomState(0) <|code_end|> with the help of current file imports: from absl.testing import absltest from disentanglement_lib.data.ground_truth import dummy_data from disentanglement_lib.evaluation.metrics import fairness from disentanglement_lib.evaluation.metrics import utils import numpy as np import gin.tf and context from other files: # Path: disentanglement_lib/data/ground_truth/dummy_data.py # class IdentityObservationsData(ground_truth_data.GroundTruthData): # class DummyData(ground_truth_data.GroundTruthData): # def num_factors(self): # def observation_shape(self): # def factors_num_values(self): # def sample_factors(self, num, random_state): # def sample_observations_from_factors(self, factors, random_state): # def factor_names(self): # def num_factors(self): # def factors_num_values(self): # def observation_shape(self): # def sample_factors(self, num, random_state): # def sample_observations_from_factors(self, factors, random_state): # # Path: disentanglement_lib/evaluation/metrics/fairness.py # def compute_fairness(ground_truth_data, # representation_function, # random_state, # artifact_dir=None, # num_train=gin.REQUIRED, # num_test_points_per_class=gin.REQUIRED, # batch_size=16): # def compute_scores_dict(metric, prefix): # def inter_group_fairness(counts): # # Path: disentanglement_lib/evaluation/metrics/utils.py # def generate_batch_factor_code(ground_truth_data, representation_function, # num_points, random_state, batch_size): # def split_train_test(observations, train_percentage): # def obtain_representation(observations, representation_function, batch_size): # def discrete_mutual_info(mus, ys): # def discrete_entropy(ys): # def make_discretizer(target, num_bins=gin.REQUIRED, # discretizer_fn=gin.REQUIRED): # def _histogram_discretize(target, num_bins=gin.REQUIRED): # def normalize_data(data, mean=None, stddev=None): # def make_predictor_fn(predictor_fn=gin.REQUIRED): # def logistic_regression_cv(): # def gradient_boosting_classifier(): , which may contain function names, class names, or code. Output only the next line.
_ = fairness.compute_fairness(ground_truth_data, representation_function,