gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, message_queue: Queue = None) -> None:
    self.messages = Queue() if not message_queue else message_queue


# Traceback (MemoryError)
2019-01-14 08:40:41 INFO     rasa_nlu.training_data.loading  - Training data format of rasa_classification_train_set.md is md
2019-01-14 08:40:43 INFO     rasa_nlu.training_data.training_data  - Training data stats:
- intent examples: 73962 (38 distinct intents)
** removing entity names **
- entity examples: 0 (0 distinct entities)
- found entities:

2019-01-14 08:40:46 INFO     rasa_nlu.model  - Starting to train component tokenizer_whitespace
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Finished training component.
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Starting to train component ner_crf
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Finished training component.
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Starting to train component ner_synonyms
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Finished training component.
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Starting to train component intent_featurizer_count_vectors
Traceback (most recent call last):
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\train.py", line 184, in <module>
num_threads=cmdline_args.num_threads)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\train.py", line 154, in do_train
interpreter = trainer.train(training_data, **kwargs)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\model.py", line 196, in train
**context)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\featurizers\count_vectors_featurizer.py", line 214, in train
X = self.vect.fit_transform(lem_exs).toarray()
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 947, in toarray
out = self._process_toarray_args(order, out)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 1184, in _process_toarray_args
return np.zeros(self.shape, dtype=self.dtype, order=order)
MemoryError

# Fixed code
def __init__(self, message_queue: Queue = None) -> None:
    super(QueueOutputChannel).__init__()
    self.messages = Queue() if not message_queue else message_queue
# Buggy code
def last_issued(self) -> int:
    """Return number of the ticket that was last added.

    Returns:
         Number of `Ticket` that was last added. `NO_TICKET_ISSUED` if no
         tickets exist.
    """

    ticket_number = self._ticket_number_for(-1)
    if ticket_number is not None:
        return ticket_number

    return NO_TICKET_ISSUED


# Traceback (rasa.core.lock_store.TicketExistsError)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.
rasa-production_1  | 2019-12-06 15:13:45 ERROR    rasa.core.lock_store  - Ticket could not be issued. Issuing new ticket and retrying...
rasa-production_1  | Traceback (most recent call last):
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 109, in issue_ticket
rasa-production_1  |     self.ensure_ticket_available(lock)
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 251, in ensure_ticket_available
rasa-production_1  |     "".format(existing_lock.last_issued, lock.conversation_id)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.
rasa-production_1  | 2019-12-06 15:13:45 ERROR    rasa.core.lock_store  - Ticket could not be issued. Issuing new ticket and retrying...
rasa-production_1  | Traceback (most recent call last):
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 109, in issue_ticket
rasa-production_1  |     self.ensure_ticket_available(lock)
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 251, in ensure_ticket_available
rasa-production_1  |     "".format(existing_lock.last_issued, lock.conversation_id)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.

# Fixed code
def last_issued(self) -> int:
    """Return number of the ticket that was last added.

    Returns:
         Number of `Ticket` that was last added. `NO_TICKET_ISSUED` if no
         tickets exist.
    """

    ticket_number = self._ticket_number_for(-1)

    return ticket_number if ticket_number is not None else NO_TICKET_ISSUED
# Buggy code
def issue_ticket(
    self, conversation_id: Text, lock_lifetime: Union[float, int] = LOCK_LIFETIME
) -> int:
    """Issue new ticket with `lock_lifetime` for lock associated with
    `conversation_id`.

    Creates a new lock if none is found.
    """

    lock = self.get_or_create_lock(conversation_id)
    ticket = lock.issue_ticket(lock_lifetime)

    while True:
        try:
            self.ensure_ticket_available(lock)
            break
        except TicketExistsError:
            # issue a new ticket if current ticket number has been issued twice
            logger.exception(
                "Ticket could not be issued. Issuing new ticket and retrying..."
            )
            ticket = lock.issue_ticket(lock_lifetime)

    self.save_lock(lock)

    return ticket


# Traceback (rasa.core.lock_store.TicketExistsError)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.
rasa-production_1  | 2019-12-06 15:13:45 ERROR    rasa.core.lock_store  - Ticket could not be issued. Issuing new ticket and retrying...
rasa-production_1  | Traceback (most recent call last):
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 109, in issue_ticket
rasa-production_1  |     self.ensure_ticket_available(lock)
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 251, in ensure_ticket_available
rasa-production_1  |     "".format(existing_lock.last_issued, lock.conversation_id)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.
rasa-production_1  | 2019-12-06 15:13:45 ERROR    rasa.core.lock_store  - Ticket could not be issued. Issuing new ticket and retrying...
rasa-production_1  | Traceback (most recent call last):
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 109, in issue_ticket
rasa-production_1  |     self.ensure_ticket_available(lock)
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 251, in ensure_ticket_available
rasa-production_1  |     "".format(existing_lock.last_issued, lock.conversation_id)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.

# Fixed code
def issue_ticket(
    self, conversation_id: Text, lock_lifetime: float = LOCK_LIFETIME
) -> int:
    """Issue new ticket with `lock_lifetime` for lock associated with
    `conversation_id`.

    Creates a new lock if none is found.
    """

    lock = self.get_or_create_lock(conversation_id)
    ticket = lock.issue_ticket(lock_lifetime)
    self.save_lock(lock)

    return ticket
# Buggy code
async def lock(
    self,
    conversation_id: Text,
    lock_lifetime: int = LOCK_LIFETIME,
    wait_time_in_seconds: Union[int, float] = 1,
) -> AsyncGenerator[TicketLock, None]:
    """Acquire lock with lifetime `lock_lifetime`for `conversation_id`.

    Try acquiring lock with a wait time of `wait_time_in_seconds` seconds
    between attempts. Raise a `LockError` if lock has expired.
    """

    ticket = self.issue_ticket(conversation_id, lock_lifetime)

    try:
        yield await self._acquire_lock(conversation_id, ticket, wait_time_in_seconds)

    finally:
        self.cleanup(conversation_id, ticket)


# Traceback (rasa.core.lock_store.TicketExistsError)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.
rasa-production_1  | 2019-12-06 15:13:45 ERROR    rasa.core.lock_store  - Ticket could not be issued. Issuing new ticket and retrying...
rasa-production_1  | Traceback (most recent call last):
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 109, in issue_ticket
rasa-production_1  |     self.ensure_ticket_available(lock)
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 251, in ensure_ticket_available
rasa-production_1  |     "".format(existing_lock.last_issued, lock.conversation_id)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.
rasa-production_1  | 2019-12-06 15:13:45 ERROR    rasa.core.lock_store  - Ticket could not be issued. Issuing new ticket and retrying...
rasa-production_1  | Traceback (most recent call last):
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 109, in issue_ticket
rasa-production_1  |     self.ensure_ticket_available(lock)
rasa-production_1  |   File "/build/lib/python3.6/site-packages/rasa/core/lock_store.py", line 251, in ensure_ticket_available
rasa-production_1  |     "".format(existing_lock.last_issued, lock.conversation_id)
rasa-production_1  | rasa.core.lock_store.TicketExistsError: Ticket '11874' already exists for conversation ID '8e001a2806b1489897accc755dd9b24f'.

# Fixed code
async def lock(
    self,
    conversation_id: Text,
    lock_lifetime: float = LOCK_LIFETIME,
    wait_time_in_seconds: float = 1,
) -> AsyncGenerator[TicketLock, None]:
    """Acquire lock with lifetime `lock_lifetime`for `conversation_id`.

    Try acquiring lock with a wait time of `wait_time_in_seconds` seconds
    between attempts. Raise a `LockError` if lock has expired.
    """

    ticket = self.issue_ticket(conversation_id, lock_lifetime)

    try:
        yield await self._acquire_lock(conversation_id, ticket, wait_time_in_seconds)

    finally:
        self.cleanup(conversation_id, ticket)
# Buggy code
def configure_cors(app: Sanic, cors_origins: Union[Text, List[Text]] = "") -> None:
    """Configure CORS origins for the given app."""

    # Workaround so that socketio works with requests from other origins.
    # https://github.com/miguelgrinberg/python-socketio/issues/205#issuecomment-493769183
    app.config.CORS_AUTOMATIC_OPTIONS = True
    app.config.CORS_SUPPORTS_CREDENTIALS = True

    CORS(app, resources={r"/*": {"origins": cors_origins}}, automatic_options=True)


# Traceback (TypeError)
Exception occurred in one of response middleware handlers
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/sanic/app.py", line 985, in handle_request
request, response
File "/usr/local/lib/python3.6/site-packages/spf/framework.py", line 579, in _run_response_middleware
_response = await _response
File "/usr/local/lib/python3.6/site-packages/sanic_cors/extension.py", line 267, in unapplied_cors_response_middleware
set_cors_headers(req, resp, context, res_options)
File "/usr/local/lib/python3.6/site-packages/sanic_cors/core.py", line 254, in set_cors_headers
headers_to_set = get_cors_headers(options, req.headers, req.method)
File "/usr/local/lib/python3.6/site-packages/sanic_cors/core.py", line 174, in get_cors_headers
origins_to_set = get_cors_origins(options, request_headers.get('Origin'))
File "/usr/local/lib/python3.6/site-packages/sanic_cors/core.py", line 149, in get_cors_origins
return sorted([o for o in origins if not probably_regex(o)])
File "/usr/local/lib/python3.6/site-packages/sanic_cors/core.py", line 149, in <listcomp>
return sorted([o for o in origins if not probably_regex(o)])
File "/usr/local/lib/python3.6/site-packages/sanic_cors/core.py", line 273, in probably_regex
return any((c in maybe_regex for c in common_regex_chars))
File "/usr/local/lib/python3.6/site-packages/sanic_cors/core.py", line 273, in <genexpr>
return any((c in maybe_regex for c in common_regex_chars))
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def configure_cors(
    app: Sanic, cors_origins: Union[Text, List[Text], None] = ""
) -> None:
    """Configure CORS origins for the given app."""

    # Workaround so that socketio works with requests from other origins.
    # https://github.com/miguelgrinberg/python-socketio/issues/205#issuecomment-493769183
    app.config.CORS_AUTOMATIC_OPTIONS = True
    app.config.CORS_SUPPORTS_CREDENTIALS = True

    CORS(
        app, resources={r"/*": {"origins": cors_origins or ""}}, automatic_options=True
    )
# Buggy code
def list_directory(path: Text) -> List[Text]:
    """Returns all files and folders excluding hidden files.

    If the path points to a file, returns the file. This is a recursive
    implementation returning files in any depth of the path."""

    if not isinstance(path, str):
        raise ValueError(
            "`resource_name` must be a string type. Got `{}` instead".format(type(path))
        )

    if os.path.isfile(path):
        return [path]
    elif os.path.isdir(path):
        results = []
        for base, dirs, files in os.walk(path):
            # remove hidden files
            goodfiles = filter(lambda x: not x.startswith("."), files)
            results.extend(os.path.join(base, f) for f in goodfiles)
        return results
    else:
        raise ValueError(
            "Could not locate the resource '{}'.".format(os.path.abspath(path))
        )


# Traceback (FileNotFoundError)
rasa test nlu -u dataset/full.json --config all_configs
2019-08-05 01:58:51 INFO     rasa.cli.test  - Multiple configuration files specified, running nlu comparison mode.

Traceback (most recent call last):
File "/Users/tom/Documents/RASA/rasa/rasa/utils/io.py", line 130, in read_file
with open(filename, encoding=encoding) as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/tom/Documents/RASA/wordpieces/pretrained_spacy.yml'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/tom/miniconda3/bin/rasa", line 11, in <module>
load_entry_point('rasa', 'console_scripts', 'rasa')()
File "/Users/tom/Documents/RASA/rasa/rasa/__main__.py", line 76, in main
cmdline_arguments.func(cmdline_arguments)
File "/Users/tom/Documents/RASA/rasa/rasa/cli/test.py", line 123, in test_nlu
io_utils.read_file(file),
File "/Users/tom/Documents/RASA/rasa/rasa/utils/io.py", line 133, in read_file
raise ValueError("File '{}' does not exist.".format(filename))
ValueError: File '/Users/tom/Documents/RASA/wordpieces/pretrained_spacy.yml' does not exist.

# Fixed code
def list_directory(path: Text) -> List[Text]:
    """Returns all files and folders excluding hidden files.

    If the path points to a file, returns the file. This is a recursive
    implementation returning files in any depth of the path."""

    if not isinstance(path, str):
        raise ValueError(
            "`resource_name` must be a string type. Got `{}` instead".format(type(path))
        )

    if os.path.isfile(path):
        return [path]
    elif os.path.isdir(path):
        results = []
        for base, dirs, files in os.walk(path):
            # add not hidden files
            good_files = filter(lambda x: not x.startswith("."), files)
            results.extend(os.path.join(base, f) for f in good_files)
            # add not hidden directories
            good_directories = filter(lambda x: not x.startswith("."), dirs)
            results.extend(os.path.join(base, f) for f in good_directories)
        return results
    else:
        raise ValueError(
            "Could not locate the resource '{}'.".format(os.path.abspath(path))
        )
# Buggy code
async def send_quick_replies(
    self,
    recipient_id: Text,
    text: Text,
    quick_replies: List[Dict[Text, Any]],
    **kwargs: Any,
) -> None:
    """Sends quick replies to the output."""

    self._add_text_info(quick_replies)
    self.send(recipient_id, FBText(text=text, quick_replies=quick_replies))


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/channels/facebook.py", line 94, in _handle_user_message
await self.on_new_message(user_msg)
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/channels/channel.py", line 68, in handler
await app.agent.handle_message(*args, **kwargs)
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/agent.py", line 441, in handle_message
return await processor.handle_message(message)
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/processor.py", line 74, in handle_message
await self._predict_and_execute_next_action(message, tracker)
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/processor.py", line 342, in _predict_and_execute_next_action
action, tracker, message.output_channel, self.nlg, policy, confidence
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/processor.py", line 453, in _run_action
await self._send_bot_messages(events, tracker, output_channel)
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/processor.py", line 374, in _send_bot_messages
await output_channel.send_response(tracker.sender_id, e.message())
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/channels/channel.py", line 173, in send_response
**message
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/channels/facebook.py", line 181, in send_quick_replies
self.send(recipient_id, FBText(text=text, quick_replies=quick_replies))
File "/home/rogers/paysikabot/lib/python3.7/site-packages/rasa/core/channels/facebook.py", line 120, in send
self.messenger_client.send(element.to_dict(), recipient_id, "RESPONSE")
File "/home/rogers/paysikabot/lib/python3.7/site-packages/fbmessenger/elements.py", line 27, in to_dict
d['quick_replies'] = self.quick_replies.to_dict()
AttributeError: 'list' object has no attribute 'to_dict'

# Fixed code
async def send_quick_replies(
    self,
    recipient_id: Text,
    text: Text,
    quick_replies: List[Dict[Text, Any]],
    **kwargs: Any,
) -> None:
    """Sends quick replies to the output."""

    quick_replies = self._convert_to_quick_reply(quick_replies)
    self.send(recipient_id, FBText(text=text, quick_replies=quick_replies))
# Buggy code
def collect_intent_properties(intent_list):
    intent_properties = {}
    for intent in intent_list:
        if isinstance(intent, dict):
            for properties in intent.values():
                if "use_entities" not in properties:
                    properties["use_entities"] = True
            intent_properties.update(intent)
        else:
            intent = {intent: {"use_entities": True}}
            intent_properties.update(intent)
    return intent_properties


# Traceback (AttributeError)
Starting Rasa X in local mode... 🚀
Traceback (most recent call last):
File "/.../.venv/bin/rasa", line 12, in <module>
sys.exit(main())
File "/.../.venv/lib/python3.6/site-packages/rasa/__main__.py", line 70, in main
cmdline_arguments.func(cmdline_arguments)
File "/.../.venv/lib/python3.6/site-packages/rasa/cli/x.py", line 243, in rasa_x
local.main(args, project_path, args.data, token=rasa_x_token)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 194, in main
session)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 144, in _initialize_with_local_data
LOCAL_PROJECT_NAME,
File "/.../.venv/lib/python3.6/site-packages/rasax/community/api/initialise.py", line 170, in inject_domain
username=username)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 48, in store_domain
templates = _templates(domain, username, project_id)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in _templates
for template, responses in templates.items() for response in responses
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in <listcomp>
for template, responses in templates.items() for response in responses
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def collect_intent_properties(intent_list):
    intent_properties = {}
    for intent in intent_list:
        if isinstance(intent, dict):
            name = list(intent.keys())[0]
            for properties in intent.values():
                if "use_entities" not in properties:
                    properties["use_entities"] = True
        else:
            name = intent
            intent = {intent: {"use_entities": True}}

        if name in intent_properties.keys():
            raise InvalidDomain(
                "Intents are not unique! Found two intents with name '{}'. "
                "Either rename or remove one of them.".format(name)
            )

        intent_properties.update(intent)
    return intent_properties
# Buggy code
def __init__(
    self,
    intent_properties: Dict[Text, Any],
    entities: List[Text],
    slots: List[Slot],
    templates: Dict[Text, Any],
    action_names: List[Text],
    form_names: List[Text],
    store_entities_as_slots: bool = True,
) -> None:
    self.intent_properties = intent_properties
    self.entities = entities
    self.form_names = form_names
    self.slots = slots
    self.templates = templates

    # only includes custom actions and utterance actions
    self.user_actions = action_names
    # includes all actions (custom, utterance, default actions and forms)
    self.action_names = (
        action.combine_user_with_default_actions(action_names) + form_names
    )
    self.store_entities_as_slots = store_entities_as_slots

    action.ensure_action_name_uniqueness(self.action_names)


# Traceback (AttributeError)
Starting Rasa X in local mode... 🚀
Traceback (most recent call last):
File "/.../.venv/bin/rasa", line 12, in <module>
sys.exit(main())
File "/.../.venv/lib/python3.6/site-packages/rasa/__main__.py", line 70, in main
cmdline_arguments.func(cmdline_arguments)
File "/.../.venv/lib/python3.6/site-packages/rasa/cli/x.py", line 243, in rasa_x
local.main(args, project_path, args.data, token=rasa_x_token)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 194, in main
session)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 144, in _initialize_with_local_data
LOCAL_PROJECT_NAME,
File "/.../.venv/lib/python3.6/site-packages/rasax/community/api/initialise.py", line 170, in inject_domain
username=username)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 48, in store_domain
templates = _templates(domain, username, project_id)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in _templates
for template, responses in templates.items() for response in responses
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in <listcomp>
for template, responses in templates.items() for response in responses
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def __init__(
    self,
    intent_properties: Dict[Text, Any],
    entities: List[Text],
    slots: List[Slot],
    templates: Dict[Text, Any],
    action_names: List[Text],
    form_names: List[Text],
    store_entities_as_slots: bool = True,
) -> None:
    self.intent_properties = intent_properties
    self.entities = entities
    self.form_names = form_names
    self.slots = slots
    self.templates = templates

    # only includes custom actions and utterance actions
    self.user_actions = action_names
    # includes all actions (custom, utterance, default actions and forms)
    self.action_names = (
        action.combine_user_with_default_actions(action_names) + form_names
    )
    self.store_entities_as_slots = store_entities_as_slots

    self._check_domain_sanity()
# Buggy code
def check_mappings(intent_properties):
    """Check whether intent-action mappings use proper action names."""

    incorrect = list()
    for intent, properties in intent_properties.items():
        if "triggers" in properties:
            if properties.get("triggers") not in domain.action_names:
                incorrect.append((intent, properties["triggers"]))
    return incorrect


# Traceback (AttributeError)
Starting Rasa X in local mode... 🚀
Traceback (most recent call last):
File "/.../.venv/bin/rasa", line 12, in <module>
sys.exit(main())
File "/.../.venv/lib/python3.6/site-packages/rasa/__main__.py", line 70, in main
cmdline_arguments.func(cmdline_arguments)
File "/.../.venv/lib/python3.6/site-packages/rasa/cli/x.py", line 243, in rasa_x
local.main(args, project_path, args.data, token=rasa_x_token)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 194, in main
session)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 144, in _initialize_with_local_data
LOCAL_PROJECT_NAME,
File "/.../.venv/lib/python3.6/site-packages/rasax/community/api/initialise.py", line 170, in inject_domain
username=username)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 48, in store_domain
templates = _templates(domain, username, project_id)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in _templates
for template, responses in templates.items() for response in responses
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in <listcomp>
for template, responses in templates.items() for response in responses
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def check_mappings(intent_properties):
    """Check whether intent-action mappings use proper action names."""

    incorrect = list()
    for intent, properties in intent_properties.items():
        if "triggers" in properties:
            if properties.get("triggers") not in self.action_names:
                incorrect.append((intent, properties["triggers"]))
    return incorrect
# Buggy code
def get_duplicate_exception_message(duplicates: List[Tuple[List[Text], Text]]) -> Text:
    """Return a message given a list of duplicates."""

    message = ""
    for d, name in duplicates:
        if d:
            if message:
                message += "\n"
            message += (
                "Duplicate {0} in domain. "
                "These {0} occur more than once in "
                "the domain: {1}".format(name, ", ".join(d))
            )
    return message


# Traceback (AttributeError)
Starting Rasa X in local mode... 🚀
Traceback (most recent call last):
File "/.../.venv/bin/rasa", line 12, in <module>
sys.exit(main())
File "/.../.venv/lib/python3.6/site-packages/rasa/__main__.py", line 70, in main
cmdline_arguments.func(cmdline_arguments)
File "/.../.venv/lib/python3.6/site-packages/rasa/cli/x.py", line 243, in rasa_x
local.main(args, project_path, args.data, token=rasa_x_token)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 194, in main
session)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/local.py", line 144, in _initialize_with_local_data
LOCAL_PROJECT_NAME,
File "/.../.venv/lib/python3.6/site-packages/rasax/community/api/initialise.py", line 170, in inject_domain
username=username)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 48, in store_domain
templates = _templates(domain, username, project_id)
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in _templates
for template, responses in templates.items() for response in responses
File "/.../.venv/lib/python3.6/site-packages/rasax/community/services/projects_service.py", line 259, in <listcomp>
for template, responses in templates.items() for response in responses
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def get_duplicate_exception_message(duplicates: List[Tuple[List[Text], Text]]) -> Text:
    """Return a message given a list of duplicates."""

    message = ""
    for d, name in duplicates:
        if d:
            if message:
                message += "\n"
            message += (
                "Duplicate {0} in domain. "
                "These {0} occur more than once in "
                "the domain: '{1}'".format(name, "', '".join(d))
            )
    return message
# Buggy code
def persist(self, model_dir):
    # type: (Text) -> Dict[Text, Any]
    file_name = self.name + ".json"
    full_name = os.path.join(model_dir, file_name)
    with io.open(full_name, "w") as f:
        f.write(json.dumps({"dimensions": self.dimensions}))
    return {"ner_duckling_persisted": file_name}


# Traceback (TypeError)
INFO:root:Finished training component.
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/vagrant/devFolder/rasa-nlu-env/src/rasa_nlu/rasa_nlu/train.py", line 83, in <module>
do_train(config)
File "/vagrant/devFolder/rasa-nlu-env/src/rasa_nlu/rasa_nlu/train.py", line 74, in do_train
persisted_path = trainer.persist(config['path'], persistor, model_name=config['name'])
File "rasa_nlu/model.py", line 183, in persist
update = component.persist(dir_name)
File "rasa_nlu/extractors/duckling_extractor.py", line 104, in persist
f.write(json.dumps({"dimensions": self.dimensions}))
TypeError: must be unicode, not str

# Fixed code
def persist(self, model_dir):
    # type: (Text) -> Dict[Text, Any]
    file_name = self.name + ".json"
    full_name = os.path.join(model_dir, file_name)
    with io.open(full_name, "w") as f:
        f.write(str(json.dumps({"dimensions": self.dimensions})))
    return {"ner_duckling_persisted": file_name}
# Buggy code
def train_entity_extractor(self, entity_examples):
    trainer = ner_trainer(self.fe_file)
    for example in entity_examples:
        tokens = tokenize(example["text"])
        sample = ner_training_instance(tokens)
        for ent in example["entities"]:
            _slice = example["text"][ent["start"] : ent["end"]]
            val_tokens = tokenize(_slice)
            start, end = self.start_and_end(tokens, val_tokens)
            sample.add_entity(xrange(start, end), ent["entity"])
        trainer.add(sample)

    ner = trainer.train()
    return ner


# Traceback (IndexError)
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "build/bdist.macosx-10.11-intel/egg/rasa_nlu/train.py", line 65, in <module>
File "build/bdist.macosx-10.11-intel/egg/rasa_nlu/train.py", line 59, in do_train
File "build/bdist.macosx-10.11-intel/egg/rasa_nlu/trainers/mitie_trainer.py", line 25, in train
File "build/bdist.macosx-10.11-intel/egg/rasa_nlu/trainers/mitie_trainer.py", line 42, in train_entity_extractor
File "build/bdist.macosx-10.11-intel/egg/rasa_nlu/trainers/mitie_trainer.py", line 31, in start_and_end
IndexError: list index out of range

# Fixed code
def train_entity_extractor(self, entity_examples):
    trainer = ner_trainer(self.fe_file)
    for example in entity_examples:
        tokens = tokenize(example["text"])
        sample = ner_training_instance(tokens)
        for ent in example["entities"]:
            _slice = example["text"][ent["start"] : ent["end"]]
            val_tokens = tokenize(_slice)
            entity_location = self.find_location_of_entity(tokens, val_tokens)
            if entity_location:
                sample.add_entity(
                    xrange(entity_location[0], entity_location[1]), ent["entity"]
                )
            else:
                logging.warn(
                    "Ignored invalid entity example. Make sure indices are correct. "
                    + 'Text: "{}", Invalid entity: "{}".'.format(
                        example["text"], _slice
                    )
                )
        trainer.add(sample)

    ner = trainer.train()
    return ner
# Buggy code
def align_diff_series(func, this_series, *args, how="full"):
    from databricks.koalas.base import IndexOpsMixin
    from databricks.koalas.series import Series

    cols = [arg for arg in args if isinstance(arg, IndexOpsMixin)]
    combined = combine_frames(this_series.to_frame(), *cols, how=how)

    that_columns = [
        combined["that"][arg._internal.column_labels[0]]._scol
        if isinstance(arg, IndexOpsMixin)
        else arg
        for arg in args
    ]

    scol = func(
        combined["this"][this_series._internal.column_labels[0]]._scol, *that_columns
    )

    return Series(
        combined._internal.copy(
            scol=scol, column_labels=this_series._internal.column_labels
        ),
        anchor=combined,
    )


# Traceback (AssertionError)
pidx = pd.Index([1, 2, 3, 4, 5])
kidx1 = ks.Index([1, 2, 3, 4, 5])
kidx2 = ks.Index(pidx)
kidx3 = ks.from_pandas(pidx)
kidx1.to_series() == kidx2.to_series() == kidx3.to_series()
Traceback (most recent call last):
...
AssertionError: (1, 0)

# Fixed code
def align_diff_series(func, this_series, *args, how="full"):
    from databricks.koalas.base import IndexOpsMixin
    from databricks.koalas.series import Series

    cols = [arg for arg in args if isinstance(arg, IndexOpsMixin)]
    combined = combine_frames(this_series.to_frame(), *cols, how=how)

    scol = func(
        combined["this"]._internal.column_scols[0],
        *combined["that"]._internal.column_scols,
    )

    return Series(
        combined._internal.copy(
            scol=scol, column_labels=this_series._internal.column_labels
        ),
        anchor=combined,
    )
# Buggy code
def _map_series_op(self, op, other):
    if isinstance(other, DataFrame) or is_sequence(other):
        raise ValueError(
            "%s with another DataFrame or a sequence is currently not supported; "
            "however, got %s." % (op, type(other))
        )

    applied = []
    for column in self._internal.data_columns:
        applied.append(getattr(self[column], op)(other))

    sdf = self._sdf.select(self._internal.index_columns + [c._scol for c in applied])
    internal = self._internal.copy(sdf=sdf, data_columns=[c.name for c in applied])
    return DataFrame(internal)


# Traceback (KeyError)
df = ks.read_parquet("/mnt/ivan/sample.parquet")
df['a.b']

# KeyError: 'a.b'
# ---------------------------------------------------------------------------
# KeyError                                  Traceback (most recent call last)
# <command-3188040896828876> in <module>()
#       1 df = ks.read_parquet("/mnt/ivan/sample.parquet")
# ----> 2 df['a.b']
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in __getitem__(self, key)
#     448
#     449     def __getitem__(self, key):
# --> 450         return self._pd_getitem(key)
#     451
#     452     def __setitem__(self, key, value):
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in _pd_getitem(self, key)
#     427                 return Series(self._sdf.__getitem__(key), self, self._metadata.index_info)
#     428             except AnalysisException:
# --> 429                 raise KeyError(key)
#     430         if np.isscalar(key) or isinstance(key, (tuple, string_types)):
#     431             raise NotImplementedError(key)
#
# KeyError: 'a.b'

# Fixed code
def _map_series_op(self, op, other):
    if isinstance(other, DataFrame) or is_sequence(other):
        raise ValueError(
            "%s with another DataFrame or a sequence is currently not supported; "
            "however, got %s." % (op, type(other))
        )

    applied = []
    for column in self._internal.data_columns:
        applied.append(getattr(self[column], op)(other))

    sdf = self._sdf.select(self._internal.index_scols + [c._scol for c in applied])
    internal = self._internal.copy(sdf=sdf, data_columns=[c.name for c in applied])
    return DataFrame(internal)
# Buggy code
def columns(self, names):
    old_names = self._internal.data_columns
    if len(old_names) != len(names):
        raise ValueError(
            "Length mismatch: Expected axis has %d elements, new values have %d elements"
            % (len(old_names), len(names))
        )
    sdf = self._sdf.select(
        self._internal.index_columns
        + [
            self[old_name]._scol.alias(new_name)
            for (old_name, new_name) in zip(old_names, names)
        ]
    )
    self._internal = self._internal.copy(sdf=sdf, data_columns=names)


# Traceback (KeyError)
df = ks.read_parquet("/mnt/ivan/sample.parquet")
df['a.b']

# KeyError: 'a.b'
# ---------------------------------------------------------------------------
# KeyError                                  Traceback (most recent call last)
# <command-3188040896828876> in <module>()
#       1 df = ks.read_parquet("/mnt/ivan/sample.parquet")
# ----> 2 df['a.b']
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in __getitem__(self, key)
#     448
#     449     def __getitem__(self, key):
# --> 450         return self._pd_getitem(key)
#     451
#     452     def __setitem__(self, key, value):
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in _pd_getitem(self, key)
#     427                 return Series(self._sdf.__getitem__(key), self, self._metadata.index_info)
#     428             except AnalysisException:
# --> 429                 raise KeyError(key)
#     430         if np.isscalar(key) or isinstance(key, (tuple, string_types)):
#     431             raise NotImplementedError(key)
#
# KeyError: 'a.b'

# Fixed code
def columns(self, names):
    old_names = self._internal.data_columns
    if len(old_names) != len(names):
        raise ValueError(
            "Length mismatch: Expected axis has %d elements, new values have %d elements"
            % (len(old_names), len(names))
        )
    sdf = self._sdf.select(
        self._internal.index_scols
        + [
            self[old_name]._scol.alias(new_name)
            for (old_name, new_name) in zip(old_names, names)
        ]
    )
    self._internal = self._internal.copy(sdf=sdf, data_columns=names)
# Buggy code
def _cum(self, func, skipna: bool):
    # This is used for cummin, cummax, cumxum, etc.
    if func == F.min:
        func = "cummin"
    elif func == F.max:
        func = "cummax"
    elif func == F.sum:
        func = "cumsum"
    elif func.__name__ == "cumprod":
        func = "cumprod"

    if len(self._internal.index_columns) == 0:
        raise ValueError("Index must be set.")

    applied = []
    for column in self._internal.data_columns:
        applied.append(getattr(self[column], func)(skipna))

    sdf = self._sdf.select(self._internal.index_columns + [c._scol for c in applied])
    internal = self._internal.copy(sdf=sdf, data_columns=[c.name for c in applied])
    return DataFrame(internal)


# Traceback (KeyError)
df = ks.read_parquet("/mnt/ivan/sample.parquet")
df['a.b']

# KeyError: 'a.b'
# ---------------------------------------------------------------------------
# KeyError                                  Traceback (most recent call last)
# <command-3188040896828876> in <module>()
#       1 df = ks.read_parquet("/mnt/ivan/sample.parquet")
# ----> 2 df['a.b']
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in __getitem__(self, key)
#     448
#     449     def __getitem__(self, key):
# --> 450         return self._pd_getitem(key)
#     451
#     452     def __setitem__(self, key, value):
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in _pd_getitem(self, key)
#     427                 return Series(self._sdf.__getitem__(key), self, self._metadata.index_info)
#     428             except AnalysisException:
# --> 429                 raise KeyError(key)
#     430         if np.isscalar(key) or isinstance(key, (tuple, string_types)):
#     431             raise NotImplementedError(key)
#
# KeyError: 'a.b'

# Fixed code
def _cum(self, func, skipna: bool):
    # This is used for cummin, cummax, cumxum, etc.
    if func == F.min:
        func = "cummin"
    elif func == F.max:
        func = "cummax"
    elif func == F.sum:
        func = "cumsum"
    elif func.__name__ == "cumprod":
        func = "cumprod"

    if len(self._internal.index_columns) == 0:
        raise ValueError("Index must be set.")

    applied = []
    for column in self._internal.data_columns:
        applied.append(getattr(self[column], func)(skipna))

    sdf = self._sdf.select(self._internal.index_scols + [c._scol for c in applied])
    internal = self._internal.copy(sdf=sdf, data_columns=[c.name for c in applied])
    return DataFrame(internal)
# Buggy code
def _reindex_columns(self, columns):
    label_columns = list(columns)
    null_columns = [
        F.lit(np.nan).alias(label_column)
        for label_column in label_columns
        if label_column not in self.columns
    ]

    # Concatenate all fields
    sdf = self._sdf.select(
        self._internal.index_columns + list(map(F.col, self.columns)) + null_columns
    )

    # Only select label_columns (with index columns)
    sdf = sdf.select(self._internal.index_columns + label_columns)
    return self._internal.copy(sdf=sdf, data_columns=label_columns)


# Traceback (KeyError)
df = ks.read_parquet("/mnt/ivan/sample.parquet")
df['a.b']

# KeyError: 'a.b'
# ---------------------------------------------------------------------------
# KeyError                                  Traceback (most recent call last)
# <command-3188040896828876> in <module>()
#       1 df = ks.read_parquet("/mnt/ivan/sample.parquet")
# ----> 2 df['a.b']
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in __getitem__(self, key)
#     448
#     449     def __getitem__(self, key):
# --> 450         return self._pd_getitem(key)
#     451
#     452     def __setitem__(self, key, value):
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in _pd_getitem(self, key)
#     427                 return Series(self._sdf.__getitem__(key), self, self._metadata.index_info)
#     428             except AnalysisException:
# --> 429                 raise KeyError(key)
#     430         if np.isscalar(key) or isinstance(key, (tuple, string_types)):
#     431             raise NotImplementedError(key)
#
# KeyError: 'a.b'

# Fixed code
def _reindex_columns(self, columns):
    label_columns = list(columns)
    null_columns = [
        F.lit(np.nan).alias(label_column)
        for label_column in label_columns
        if label_column not in self.columns
    ]

    # Concatenate all fields
    sdf = self._sdf.select(
        self._internal.index_scols
        + list(map(self._internal.scol_for, self.columns))
        + null_columns
    )

    # Only select label_columns (with index columns)
    sdf = sdf.select(
        self._internal.index_scols + [scol_for(sdf, col) for col in label_columns]
    )
    return self._internal.copy(sdf=sdf, data_columns=label_columns)
# Buggy code
def __getattr__(self, key: str) -> Any:
    from databricks.koalas.series import Series

    if key.startswith("__") or key.startswith("_pandas_") or key.startswith("_spark_"):
        raise AttributeError(key)
    if hasattr(_MissingPandasLikeDataFrame, key):
        property_or_func = getattr(_MissingPandasLikeDataFrame, key)
        if isinstance(property_or_func, property):
            return property_or_func.fget(self)  # type: ignore
        else:
            return partial(property_or_func, self)
    return Series(self._internal.copy(scol=self._sdf.__getattr__(key)), anchor=self)


# Traceback (KeyError)
df = ks.read_parquet("/mnt/ivan/sample.parquet")
df['a.b']

# KeyError: 'a.b'
# ---------------------------------------------------------------------------
# KeyError                                  Traceback (most recent call last)
# <command-3188040896828876> in <module>()
#       1 df = ks.read_parquet("/mnt/ivan/sample.parquet")
# ----> 2 df['a.b']
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in __getitem__(self, key)
#     448
#     449     def __getitem__(self, key):
# --> 450         return self._pd_getitem(key)
#     451
#     452     def __setitem__(self, key, value):
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in _pd_getitem(self, key)
#     427                 return Series(self._sdf.__getitem__(key), self, self._metadata.index_info)
#     428             except AnalysisException:
# --> 429                 raise KeyError(key)
#     430         if np.isscalar(key) or isinstance(key, (tuple, string_types)):
#     431             raise NotImplementedError(key)
#
# KeyError: 'a.b'

# Fixed code
def __getattr__(self, key: str) -> Any:
    from databricks.koalas.series import Series

    if key.startswith("__") or key.startswith("_pandas_") or key.startswith("_spark_"):
        raise AttributeError(key)
    if hasattr(_MissingPandasLikeDataFrame, key):
        property_or_func = getattr(_MissingPandasLikeDataFrame, key)
        if isinstance(property_or_func, property):
            return property_or_func.fget(self)  # type: ignore
        else:
            return partial(property_or_func, self)
    if key not in self.columns:
        raise AttributeError(
            "'%s' object has no attribute '%s'" % (self.__class__.__name__, key)
        )
    return Series(self._internal.copy(scol=self._internal.scol_for(key)), anchor=self)
# Buggy code
def cumprod(scol):
    @pandas_udf(returnType=self._kdf._sdf.schema[self.name].dataType)
    def negative_check(s):
        assert len(s) == 0 or ((s > 0) | (s.isnull())).all(), (
            "values should be bigger than 0: %s" % s
        )
        return s

    return F.sum(F.log(negative_check(scol)))


# Traceback (KeyError)
df = ks.read_parquet("/mnt/ivan/sample.parquet")
df['a.b']

# KeyError: 'a.b'
# ---------------------------------------------------------------------------
# KeyError                                  Traceback (most recent call last)
# <command-3188040896828876> in <module>()
#       1 df = ks.read_parquet("/mnt/ivan/sample.parquet")
# ----> 2 df['a.b']
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in __getitem__(self, key)
#     448
#     449     def __getitem__(self, key):
# --> 450         return self._pd_getitem(key)
#     451
#     452     def __setitem__(self, key, value):
#
# /databricks/python/lib/python3.5/site-packages/databricks/koalas/frame.py in _pd_getitem(self, key)
#     427                 return Series(self._sdf.__getitem__(key), self, self._metadata.index_info)
#     428             except AnalysisException:
# --> 429                 raise KeyError(key)
#     430         if np.isscalar(key) or isinstance(key, (tuple, string_types)):
#     431             raise NotImplementedError(key)
#
# KeyError: 'a.b'

# Fixed code
def cumprod(scol):
    @pandas_udf(returnType=self._kdf._internal.spark_type_for(self.name))
    def negative_check(s):
        assert len(s) == 0 or ((s > 0) | (s.isnull())).all(), (
            "values should be bigger than 0: %s" % s
        )
        return s

    return F.sum(F.log(negative_check(scol)))