text:
package com.diozero.internal.spi;

import java.util.stream.Stream;

import com.diozero.api.DeviceMode;
import com.diozero.sbc.BoardInfo;
import com.diozero.util.ServiceLoaderUtil;

public interface NativeDeviceFactoryInterface extends GpioDeviceFactoryInterface, SpiDeviceFactoryInterface,
		I2CDeviceFactoryInterface, PwmOutputDeviceFactoryInterface, ServoDeviceFactoryInterface,
		AnalogInputDeviceFactoryInterface, AnalogOutputDeviceFactoryInterface, SerialDeviceFactoryInterface {
	void registerDeviceFactory(DeviceFactoryInterface deviceFactory);

	BoardInfo getBoardInfo();

	int getGpioValue(int gpio);

	DeviceMode getGpioMode(int gpio);

	float getCpuTemperature();

	static Stream<NativeDeviceFactoryInterface> loadInstances() {
		/*-
		return StreamSupport.stream(ServiceLoader.load(NativeDeviceFactoryInterface.class).spliterator(), false);
		*/
		return ServiceLoaderUtil.stream(NativeDeviceFactoryInterface.class);
	}
}


text:
package com.titanic.ventapasajes.modelo;

import java.io.Serializable;

/**
 * Created by josediaz on 1/11/16.
 */
public class Seguridad implements Serializable {

    private static final long serialVersionUID = 1L;

    private String ruc;
    private String usuario;
    private String clave;
    private String partida;

    public String getPartida() {
        return partida;
    }

    public void setPartida(String partida) {
        this.partida = partida;
    }

    public String getRuc() {
        return ruc;
    }

    public void setRuc(String ruc) {
        this.ruc = ruc;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getClave() {
        return clave;
    }

    public void setClave(String clave) {
        this.clave = clave;
    }

    @Override
    public String toString() {
        return "Seguridad{" +
                "ruc='" + ruc + '\'' +
                ", usuario='" + usuario + '\'' +
                ", clave='" + clave + '\'' +
                ", partida='" + partida + '\'' +
                '}';
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.labservices.generated;

import com.azure.core.util.Context;

/** Samples for Skus List. */
public final class SkusListSamples {
    /*
     * x-ms-original-file: specification/labservices/resource-manager/Microsoft.LabServices/stable/2022-08-01/examples/Skus/listSkus.json
     */
    /**
     * Sample code: listSkus.
     *
     * @param manager Entry point to LabServicesManager.
     */
    public static void listSkus(com.azure.resourcemanager.labservices.LabServicesManager manager) {
        manager.skus().list(null, Context.NONE);
    }
}


text:
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
	Q_OBJECT

public:
	explicit MainWindow(QWidget *parent = 0);
	~MainWindow();

private slots:
	void on_btnRun_clicked();
	void on_actionSafe_triggered();
	void on_actionOpen_triggered();
	void on_actionAbout_triggered();

	void on_actionBrowse_XVSQ_triggered();

	void on_actionSet_As_Default_triggered();

private:
	Ui::MainWindow *ui;
	QShortcut *saveShortCut;
	QShortcut *openShortCut;

	TermainalOutput terminal;

	int load(QString path);
	int save(QString path);
};

#endif // MAINWINDOW_H


text:
#ifndef mozilla_Omnijar_h
#define mozilla_Omnijar_h

class nsILocalFile;
class nsZipArchive;

#ifdef MOZ_OMNIJAR

namespace mozilla {

/**
 * This returns the path to the omnijar.
 * If the omnijar isn't available, this function will return null.
 * Callers should fallback to flat packaging if null.
 */
nsILocalFile *OmnijarPath();
nsZipArchive *OmnijarReader();
void SetOmnijar(nsILocalFile* aPath);

} /* namespace mozilla */

#endif /* MOZ_OMNIJAR */

#endif /* mozilla_Omnijar_h */


text:
.. _str: https://docs.python.org/2/library/stdtypes.html

.. _vmodl.DynamicData: ../../vmodl/DynamicData.rst

vim.host.IpRouteConfig
======================
  IP Route Configuration. All IPv4 addresses, subnet addresses, and netmasks are specified as strings using dotted decimal notation. For example, "192.0.2.1". IPv6 addresses are 128-bit addresses represented as eight fields of up to four hexadecimal digits. A colon separates each field (:). For example, 2001:DB8:101::230:6eff:fe04:d9ff. The address can also consist of symbol '::' to represent multiple 16-bit groups of contiguous 0's only once in an address as described in RFC 2373.
:extends: vmodl.DynamicData_

Attributes:
    defaultGateway (`str`_, optional):

       The default gateway address.
    gatewayDevice (`str`_, optional):

       The gateway device. This applies to service console gateway only, it is ignored otherwise.
    ipV6DefaultGateway (`str`_, optional):

       The default ipv6 gateway address
    ipV6GatewayDevice (`str`_, optional):

       The ipv6 gateway device. This applies to service console gateway only, it


text:
package com.ltsllc.miranda.cluster.states;

import com.ltsllc.miranda.State;
import com.ltsllc.miranda.clientinterface.MirandaException;
import com.ltsllc.miranda.cluster.ClusterFile;
import com.ltsllc.miranda.file.states.SingleFileStartingState;

/**
 * Created by Clark on 5/18/2017.
 */
public class ClusterFileStartingState extends SingleFileStartingState {
    public ClusterFile getClusterFile() {
        return (ClusterFile) getContainer();
    }

    public ClusterFileStartingState(ClusterFile clusterFile) throws MirandaException {
        super(clusterFile);
    }

    public State getReadyState() throws MirandaException {
        return new ClusterFileReadyState(getClusterFile());
    }
}


text:
#import <Foundation/Foundation.h>
#import "ZXPDFDocumentObject.h"
#import "ZXPDFPageObject.h"
#import "ZXPDFPageView.h"

// this is not completed implementation.
// TODO: complete this.
@interface ZXPDFPageThumbnailController : NSObject {

}

@property (nonatomic, strong) NSURL *fileURL;
@property (nonatomic, strong) NSURL *cacheURL;

+ (CGSize)thumbnailSize;
+ (NSString *)thumbnailNamePrefix;
+ (NSString *)thumbnailNameWithPageNumber:(NSInteger)pageNumber;

- (id)initWithPDFDocument:(ZXPDFDocumentObject *)aPDFDocument;
+ (id)thumbnailControllerWithPDFDocument:(ZXPDFDocumentObject *)aPDFDocument;

- (NSURL *)thumnailURLAtPageNumber:(NSInteger)pageNumber;
- (BOOL)hasThumbnailAtPageNumber:(NSInteger)pageNumber;
- (UIImage *)thumnailAtPageNumber:(NSInteger)pageNumber;
- (BOOL)createThumbnailAtPageNumber:(NSInteger)pageNumber; // heavy operation, typically should call in another thread.

@end


text:
# Arbiter

Manage Laravel User abilities that target Users.

[![Source Code][badge-source]][source]
[![Latest Version][badge-release]][release]
[![Software License][badge-license]][license]
[![Build Status][badge-build]][build]
[![Coverage Status][badge-coverage]][coverage]
[![Total Downloads][badge-downloads]][downloads]

## About

Determining a way to authorize what actions can be performed by one User on another may seem like a simple problem at first.
Most Role based permission modules are designed to allow multiple roles per user.
This is an extremely powerful and flexible design pattern but creates a hard to define authorization case:
When User-A can *update* users with Role-1, and User-B has Role-1 and Role-2, how should your application determine if User-A *update* User-B?

Arbiter provides a solution to this problem without getting in the way of an existing or separate multi-role based authorization system.

## Requirements

 - PHP >= 5.5.9
 - Laravel >= 5.2

## Installation

The preferred method of installation is via [Packagist][] and [Composer][].
Run the following command to install the package and add it as a requirement to your project's `composer.json`:

```bash
composer require unstoppablecarl/arbiter
```

## Overview

Each User has exactly one **Primary Role**. Primary Roles are used to determine what actions a user can perform on other users and vice-versa. Each Primary Role is identified with a unique name string.

The `UserWithPrimaryRole` interface is implemented on the User model.

```php
<?php
interface UserWithPrimaryRole {

    /*
     * Get the Primary Role of this user.
     * @return string
     */
    public function getPrimaryRoleName();
}
```

The developer implements the interface with a strategy for determining what the Primary Role of a user is.

### Primary Role Implementation Strategies

 - Using an existing multi-role based system:
   - Define some roles as "Primary". Each User has exactly one Primary Role.
   - Define a numeric priority to each Role. The Primary Role of a User is the Role with the highest priority assigned to them.
 - Users have exactly one Role which is used as the Primary Role. This is often a good starting point projects where it is unclear how complex the roles/permissions requirements will become.

## Basic Usage

### User

Implement the `UserWithPrimaryRole` Interface on your `User` model.

See [`UnstoppableCarl\Arbiter\Contracts\UserWithPrimaryRole`](src/Contracts/UserWithPrimaryRole.php)

```php
<?php

namespace App;

use UnstoppableCarl\Arbiter\Contracts\UserWithPrimaryRole;

class User implements UserWithPrimaryRole
{
    public function getPrimaryRoleName()
    {
        // @TODO implement Primary Role strategy

        // simple example
        // not recommended
        return $this->primary_role ?: 'default_primary_role';
    }
}
```

### User Policy

Create `App\Policies\UserPolicy` and set it as the policy for the `User` model in `App\Providers\AuthServiceProvider`

See [`UserPolicy`](src/Policies/UserPolicy.php)

```php
<?php

namespace App\Policies;

use UnstoppableCarl\Arbiter\Policies\UserPolicy as ArbiterUserPolicy;

class UserPolicy extends ArbiterUserPolicy
{

}
```

### User Authority

Create and bind an implementation of the `UserAuthorityContract` in your `AuthServiceProvider` or continue with the Config Based User Authority below.

#### Config Based Implementation

Arbiter includes a simple config based `UserAuthority` implementation to quickly get your project up and running.

##### ArbiterServiceProvider

Add the Service Provider to `config/app.php`

`UnstoppableCarl\Arbiter\Providers\ArbiterServiceProvider::class,`

##### Configure

Publish the config file.

`php artisan vendor:publish --provider=UnstoppableCarl\Arbiter\Providers\ArbiterServiceProvider`

Primary Role Abilities can be configured in `config/arbiter.php`.

## Customizing The User Policy

The `UserPolicy` functionality is organized into seperate traits to allow use of only the functionality you want.

 - See
   - [`Concerns`](src/Policies/Concerns)
   - [`UserPolicy`](src/Policies/UserPolicy.php)

#### UserPolicy Trait: HasUserAuthority

[`HasUserAuthority`](src/Policies/Concerns/HasUserAuthority.php)

Adds a reference to the `UserAuthority` instance.

 - Required for `HasAbilities` and `HasGetters` traits.
 - Gets the primary role of ability targets that implement the `UserWithPrimaryRole` interface via a `toPrimaryRole` method.

#### Trait: HasAbilities

[`HasAbilities`](src/Policies/Concerns/HasAbilities.php)

Adds the typical abilities of a `UserPolicy` matching them to the methods and abilities of the `UserAuthority`.

 - Requires `HasUserAuthority` trait.
 - Methods
   - create
   - update
   - delete
   - view
   - changePrimaryRoleFrom
   - changePrimaryRoleTo
   - changePrimaryRole

#### Trait: HasGetters

[`HasGetters`](src/Policies/Concerns/HasGetters.php)

Adds getters to allow retrieval of all primary roles a user can perform given abilities on.

 - Requires `HasUserAuthority` trait.
 - Methods
   - getViewablePrimaryRoles
   - getCreatablePrimaryRoles
   - getChangeableFromPrimaryRoles
   - getChangeableToPrimaryRoles
   - getDeletablePrimaryRoles
   - getPrimaryRoles

#### Trait: HasTargetSelfOverrides

[`HasTargetSelfOverrides`](src/Policies/Concerns/HasTargetSelfOverrides.php)

Allows overriding the returned value of a `UserPolicy` ability check, when the source and target of the check are the same `User`. The ability check is overriden by using the `before` method behavior of Laravel Policies.

- The `$targetSelfOverrides` property must be set to an implementation of the [`TargetSelfOverridesContract`](src/Contracts/TargetSelfOverridesContract.php). In the included [`UserPolicy`](src/UnstoppableCarl\Arbiter\Policies\UserPolicy.php) it is set via the constructor.
-  [`TargetSelfOverrides`](src/TargetSelfOverrides.php) is a minimal implementation included and used by default in the [`ArbiterServiceProvider`](src/Providers/ArbiterServiceProvider).

#### Adding User Authority Abilities

The following shows how to add an ability to the `UserPolicy` that checks a custom ability set in the `UserAuthority`.

```php
<?php

namespace App\Policies;

use UnstoppableCarl\Arbiter\Contracts\UserWithPrimaryRole;
use UnstoppableCarl\Arbiter\Policies\UserPolicy as ArbiterUserPolicy;

class UserPolicy extends ArbiterUserPolicy
{
    /**
     * Can ban users with $target Primary Role
     * @param UserWithPrimaryRole $source
     * @param UserWithPrimaryRole|null $target
     * @return
     */
    public function ban(UserWithPrimaryRole $source, $target = null)
    {
        $source  = $this->toPrimaryRole($source);
        $target  = $this->toPrimaryRole($target);
        $ability = 'ban';
        return $this->userAuthority()->canOrAny($source, $ability, $target);
    }
}
```

## Running Tests

Run Unit Tests

```
$ composer phpunit
```

Run Codesniffer (psr-2)

```
$ composer phpcs
```

Run both

```
$ composer test
```

## Contributing

Contributions and Pull Requests welcome!

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

## Authors

* **Carl Olsen** - *Initial work* - [Unstoppable Carl](https://github.com/unstoppablecarl)

See also the list of [contributors][] who participated in this project.

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

[composer]: http://getcomposer.org/
[contributors]: https://github.com/unstoppablecarl/arbiter/contributors
[packagist]: https://packagist.org/packages/unstoppablecarl/arbiter

[badge-source]: https://img.shields.io/badge/source-unstoppablecarl/arbiter-blue.svg
[badge-release]: https://img.shields.io/packagist/v/unstoppablecarl/arbiter.svg?style=flat-square
[badge-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[badge-build]: https://img.shields.io/travis/unstoppablecarl/arbiter/master.svg?style=flat-square
[badge-coverage]: https://img.shields.io/coveralls/unstoppablecarl/arbiter/master.svg?style=flat-square
[badge-downloads]: https://img.shields.io/packagist/dt/unstoppablecarl/arbiter.svg?style=flat-square

[source]: https://github.com/unstoppablecarl/arbiter
[release]: https://packagist.org/packages/unstoppablecarl/arbiter
[license]: https://github.com/unstoppablecarl/arbiter/blob/master/LICENSE
[build]: https://travis-ci.org/unstoppablecarl/arbiter
[coverage]: https://coveralls.io/r/unstoppablecarl/arbiter?branch=master
[downloads]: https://packagist.org/packages/unstoppablecarl/arbiter


text:
package org.springside.examples.showcase.unit.jmx;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springside.examples.showcase.jmx.client.JmxClientService;
import org.springside.examples.showcase.jmx.server.ServerConfigMBean;
import org.springside.modules.log.Log4jMBean;
import org.springside.modules.test.spring.SpringContextTestCase;
import org.springside.modules.utils.jmx.JmxClientTemplate;

/**
 * springside-extension中{@link JmxClientTemplate}的测试用例.
 *
 * @author calvin
 */
@DirtiesContext
@ContextConfiguration(locations = { "/applicationContext-test.xml", "/jmx/applicationContext-jmx-server.xml",
		"/log/applicationContext-log.xml" })
public class JmxClientTemplateTest extends SpringContextTestCase {

	private JmxClientTemplate jmxClientTemplate;
	private ServerConfigMBean serverConfigMbean;

	@Before
	public void setUp() throws Exception {
		jmxClientTemplate = new JmxClientTemplate("service:jmx:rmi:///jndi/rmi://localhost:18080/jmxrmi");
		serverConfigMbean = jmxClientTemplate.createMBeanProxy(ServerConfigMBean.SERVER_CONFIG_MBEAN_NAME,
				ServerConfigMBean.class);
	}

	@After
	public void tearDown() throws Exception {
		jmxClientTemplate.close();
	}

	@Test
	public void accessMBeanAttribute() {
		String oldName = serverConfigMbean.getNodeName();

		serverConfigMbean.setNodeName("foo");
		assertEquals("foo", serverConfigMbean.getNodeName());

		serverConfigMbean.setNodeName(oldName);
	}

	@Test
	public void accessMBeanAttributeByReflection() {
		String oldName = (String) jmxClientTemplate
				.getAttribute(ServerConfigMBean.SERVER_CONFIG_MBEAN_NAME, "NodeName");

		jmxClientTemplate.setAttribute(ServerConfigMBean.SERVER_CONFIG_MBEAN_NAME, "NodeName", "foo");
		assertEquals("foo", jmxClientTemplate.getAttribute(ServerConfigMBean.SERVER_CONFIG_MBEAN_NAME, "NodeName"));

		jmxClientTemplate.setAttribute(ServerConfigMBean.SERVER_CONFIG_MBEAN_NAME, "NodeName", oldName);
	}

	@Test
	public void invokeMBeanMethodByReflection() {
		//无参数
		jmxClientTemplate.inoke(JmxClientService.TRACE_MBEAN_NAME, "startTrace");

		//以参数Class名描述函数签名
		assertEquals("WARN", jmxClientTemplate.invoke(Log4jMBean.LOG4J_MBEAN_NAME, "getLoggerLevel",
				new String[] { "java.lang.String" }, new Object[] { "foo" }));

		//以参数Class类描述函数签名
		assertEquals("WARN", jmxClientTemplate.invoke(Log4jMBean.LOG4J_MBEAN_NAME, "getLoggerLevel",
				new Class[] { String.class }, new Object[] { "foo" }));
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 9(1-6): 546 (1955)

#### Original name
Hypocenia caespitosa Petr.

### Remarks
null


text:
1. Substring

2. String to Array of characters

   var str = "pradeep";
   str.split("");

3. Char array to String

   var s = ['H', 'e', 'l', 'l', 'o'];
   s.join("");

4. Replace all forward slashes with back slashes

   s = s.replace(/\\/g,'/');

5. Converting string to number

   var str = "10";
   var num = parseInt(str);
   if(num === 10){
      \\ Parsed successfully
   }

6. Converting string to boolean


text:
cask 'gisto' do
  version '0.3.2'
  sha256 '5a3666977eca39099f99e52e77c82244cb2baf52baeb8f21efcf3b369de27789'

  # github.com/Gisto/Gisto was verified as official when first introduced to the cask
  url "https://github.com/Gisto/Gisto/releases/download/#{version}-beta/Gisto-v#{version}-macos-x64.dmg"
  appcast 'https://github.com/Gisto/Gisto/releases.atom'
  name 'Gisto'
  homepage 'https://www.gistoapp.com/'

  app 'Gisto.app'
end


text:
/* Options */
#graph-section-top{
    grid-template-columns: .6fr 1fr 1fr 1fr .7fr;
}

#png-button, #svg-button, #fullscreen-button {
    display: none;
}

/* Multicloud */
#multicloud {
    display: grid;
    grid-template-columns: repeat(auto-fit, 46rem);
    grid-gap: var(--gap);
    align-items: center;
    justify-content: center;
    overflow-y: auto;
}

/* Word cloud */
.word-cloud-wrapper {
    width: 46rem;
    height: 50rem;
    background-color: var(--foreground-color-alternate);
    overflow: hidden;
}

.word-cloud-wrapper .title {
    overflow: hidden;
    margin-right: var(--small-gap);
    white-space: nowrap;
}

.word-cloud {
    display: flex;
    justify-content: center;
    align-items: center;
    background: var(--foreground-color-alternate);
    height: calc(100% - 4rem);
}

.word-cloud-wrapper .button {
    background-color: var(--foreground-color);
}

.word-cloud-wrapper .button:hover {
    background-color: var(--highlight-color-light);
}


text:
layout: default
---

About Me

I'm a tech enthusiast who loves to explore new solutions to old problems and who codes for fun!

{% include fa-icon.html id="desktop" add-class="fa-index" %} Software Developer

{% include fa-icon.html id="map-pin" add-class="fa-index" %} Belo Horizonte-MG, Brazil

{% include fa-icon.html id="envelope" add-class="fa-about" %} hello@italolelis.com

{% include svg-icons.html %}

    {{ content }}


text:
/* polish-disable */

#wont-fail-despite-rules {
  color: green;
}


text:
from __future__ import generator_stop

import os
import sys
#import inspect
#import types
import unittest
import contextlib

#from unittest import mock

#from test.support import import_module

#asyncio = import_module("asyncio")

ZERO = 0

try:
    if sys.version_info[:2] == (3, 4):
        # asnycio in Py3.4 does not support awaitable coroutines (requires iterators instead)
        raise ImportError
    import asyncio
except ImportError:
    try:
        from unittest import skip
    except ImportError:
        def requires_asyncio(c):
            return None
    else:
        requires_asyncio = skip("tests require asyncio")
    asyncio = None
else:
    def requires_asyncio(c):
        return c

def needs_py36_asyncio(f):
    if sys.version_info >= (3, 6) or asyncio is None:
        # Py<3.4 doesn't have asyncio at all => avoid having to special case 2.6's unittest below
        return f

    from unittest import skip
    return skip("needs Python 3.6 or later")(f)

try:
    from types import coroutine as types_coroutine
except ImportError:
    def types_coroutine(func):
        from functools import wraps
        wrapped = wraps(func)

        # copied from types.py in Py3.6
        class _GeneratorWrapper(object):
            # TODO: Implement this in C.
            def __init__(self, gen):
                self.__wrapped = gen
                self.__isgen = hasattr(gen, 'gi_running')
                self.__name__ = getattr(gen, '__name__', None)
                self.__qualname__ = getattr(gen, '__qualname__', None)

            def send(self, val):
                return self.__wrapped.send(val)

            def throw(self, tp, *rest):
                return self.__wrapped.throw(tp, *rest)

            def close(self):
                return self.__wrapped.close()

            @property
            def gi_code(self):
                return self.__wrapped.gi_code

            @property
            def gi_frame(self):
                return self.__wrapped.gi_frame

            @property
            def gi_running(self):
                return self.__wrapped.gi_running

            @property
            def gi_yieldfrom(self):
                return self.__wrapped.gi_yieldfrom

            cr_code = gi_code
            cr_frame = gi_frame
            cr_running = gi_running
            cr_await = gi_yieldfrom

            def __next__(self):
                return next(self.__wrapped)
            next = __next__

            def __iter__(self):
                if self.__isgen:
                    return self.__wrapped
                return self

            __await__ = __iter__

        @wrapped
        def call(*args, **kwargs):
            return wrapped(_GeneratorWrapper(func(*args, **kwargs)))

        return call

try:
    from inspect import isawaitable as inspect_isawaitable
except ImportError:
    def inspect_isawaitable(o):
        return hasattr(o, '__await__')

# compiled exec()
def exec(code_string, l, g):
    from Cython.Compiler.Errors import CompileError
    from Cython.Shadow import inline
    try:
        from StringIO import StringIO
    except ImportError:
        from io import StringIO

    old_stderr = sys.stderr
    try:
        sys.stderr = StringIO()
        ns = inline(code_string, locals=l, globals=g, lib_dir=os.path.dirname(__file__))
    except CompileError as exc:
        raise SyntaxError(str(exc))
    finally:
        sys.stderr = old_stderr
    g.update(ns)

class AwaitException(Exception):
    pass

@types_coroutine
def awaitable(*, throw=False):
    if throw:
        yield ('throw',)
    else:
        yield ('result',)

def run_until_complete(coro):
    exc = False
    while True:
        try:
            if exc:
                exc = False
                fut = coro.throw(AwaitException)
            else:
                fut = coro.send(None)
        except StopIteration as ex:
            return ex.args[0]

        if fut == ('throw',):
            exc = True

def to_list(gen):
    async def iterate():
        res = []
        async for i in gen:
            res.append(i)
        return res

    return run_until_complete(iterate())

class AsyncGenSyntaxTest(unittest.TestCase):

    @contextlib.contextmanager
    def assertRaisesRegex(self, exc_type, regex):
        # the error messages usually don't match, so we just ignore them
        try:
            yield
        except exc_type:
            self.assertTrue(True)
        else:
            self.assertTrue(False)

    def test_async_gen_syntax_01(self):
        code = '''async def foo():
            await abc
            yield from 123
        '''

        with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):
            exec(code, {}, {})

    def test_async_gen_syntax_02(self):
        code = '''async def foo():
            yield from 123
        '''

        with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):
            exec(code, {}, {})

    def test_async_gen_syntax_03(self):
        code = '''async def foo():
            await abc
            yield
            return 123
        '''

        with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
            exec(code, {}, {})

    def test_async_gen_syntax_04(self):
        code = '''async def foo():
            yield
            return 123
        '''

        with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
            exec(code, {}, {})

    def test_async_gen_syntax_05(self):
        code = '''async def foo():
            if 0:
                yield
            return 12
        '''

        with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
            exec(code, {}, {})

class AsyncGenTest(unittest.TestCase):

    if sys.version_info < (3, 3):
        @contextlib.contextmanager
        def assertRaisesRegex(self, exc_type, regex=None):
            # the error messages usually don't match, so we just ignore them
            try:
                yield
            except exc_type:
                self.assertTrue(True)
            else:
                self.assertTrue(False)

    def compare_generators(self, sync_gen, async_gen):
        def sync_iterate(g):
            res = []
            while True:
                try:
                    res.append(next(g))
                except StopIteration:
                    res.append('STOP')
                    break
                except Exception as ex:
                    res.append(str(type(ex)))
            return res

        def async_iterate(g):
            res = []
            while True:
                an = g.__anext__()
                try:
                    while True:
                        try:
                            next(an)
                        except StopIteration as ex:
                            if ex.args:
                                res.append(ex.args[0])
                                break
                            else:
                                res.append('EMPTY StopIteration')
                                break
                        except StopAsyncIteration:
                            raise
                        except Exception as ex:
                            res.append(str(type(ex)))
                            break
                except StopAsyncIteration:
                    res.append('STOP')
                    break
            return res

        sync_gen_result = sync_iterate(sync_gen)
        async_gen_result = async_iterate(async_gen)
        self.assertEqual(sync_gen_result, async_gen_result)
        return async_gen_result

    def test_async_gen_iteration_01(self):
        async def gen():
            await awaitable()
            a = yield 123
            self.assertIs(a, None)
            await awaitable()
            yield 456
            await awaitable()
            yield 789

        self.assertEqual(to_list(gen()), [123, 456, 789])

    def test_async_gen_iteration_02(self):
        async def gen():
            await awaitable()
            yield 123
            await awaitable()

        g = gen()
        ai = g.__aiter__()

        an = ai.__anext__()
        self.assertEqual(next(an), ('result',))

        try:
            next(an)
        except StopIteration as ex:
            self.assertEqual(ex.args[0], 123)
        else:
            self.fail('StopIteration was not raised')

        an = ai.__anext__()
        self.assertEqual(next(an), ('result',))

        try:
            next(an)
        except StopAsyncIteration as ex:
            self.assertFalse(ex.args)
        else:
            self.fail('StopAsyncIteration was not raised')

    def test_async_gen_exception_03(self):
        async def gen():
            await awaitable()
            yield 123
            await awaitable(throw=True)
            yield 456

        with self.assertRaises(AwaitException):
            to_list(gen())

    def test_async_gen_exception_04(self):
        async def gen():
            await awaitable()
            yield 123
            1 / ZERO

        g = gen()
        ai = g.__aiter__()

        an = ai.__anext__()
        self.assertEqual(next(an), ('result',))

        try:
            next(an)
        except StopIteration as ex:
            self.assertEqual(ex.args[0], 123)
        else:
            self.fail('StopIteration was not raised')

        with self.assertRaises(ZeroDivisionError):
            next(ai.__anext__())

    def test_async_gen_exception_05(self):
        async def gen():
            yield 123
            raise StopAsyncIteration

        with self.assertRaisesRegex(RuntimeError,
                                    'async generator.*StopAsyncIteration'):
            to_list(gen())

    def test_async_gen_exception_06(self):
        async def gen():
            yield 123
            raise StopIteration

        with self.assertRaisesRegex(RuntimeError,
                                    'async generator.*StopIteration'):
            to_list(gen())

    def test_async_gen_exception_07(self):
        def sync_gen():
            try:
                yield 1
                1 / ZERO
            finally:
                yield 2
                yield 3

            yield 100

        async def async_gen():
            try:
                yield 1
                1 / ZERO
            finally:
                yield 2
                yield 3

            yield 100

        self.compare_generators(sync_gen(), async_gen())

    def test_async_gen_exception_08(self):
        def sync_gen():
            try:
                yield 1
            finally:
                yield 2
                1 / ZERO
                yield 3

            yield 100

        async def async_gen():
            try:
                yield 1
                await awaitable()
            finally:
                await awaitable()
                yield 2
                1 / ZERO
                yield 3

            yield 100

        self.compare_generators(sync_gen(), async_gen())

    def test_async_gen_exception_09(self):
        def sync_gen():
            try:
                yield 1
                1 / ZERO
            finally:
                yield 2
                yield 3

            yield 100

        async def async_gen():
            try:
                await awaitable()
                yield 1
                1 / ZERO
            finally:
                yield 2
                await awaitable()
                yield 3

            yield 100

        self.compare_generators(sync_gen(), async_gen())

    def test_async_gen_exception_10(self):
        async def gen():
            yield 123
        with self.assertRaisesRegex(TypeError,
                                    "non-None value .* async generator"):
            gen().__anext__().send(100)

    def test_async_gen_exception_11(self):
        def sync_gen():
            yield 10
            yield 20

        def sync_gen_wrapper():
            yield 1
            sg = sync_gen()
            sg.send(None)
            try:
                sg.throw(GeneratorExit())
            except GeneratorExit:
                yield 2
            yield 3

        async def async_gen():
            yield 10
            yield 20

        async def async_gen_wrapper():
            yield 1
            asg = async_gen()
            await asg.asend(None)
            try:
                await asg.athrow(GeneratorExit())
            except GeneratorExit:
                yield 2
            yield 3

        self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())

    def test_async_gen_api_01(self):
        async def gen():
            yield 123

        g = gen()

        self.assertEqual(g.__name__, 'gen')
        g.__name__ = '123' if sys.version_info[0] >= 3 else b'123'
        self.assertEqual(g.__name__, '123')

        self.assertIn('.gen', g.__qualname__)
        g.__qualname__ = '123' if sys.version_info[0] >= 3 else b'123'
        self.assertEqual(g.__qualname__, '123')

        #self.assertIsNone(g.ag_await)
        #self.assertIsInstance(g.ag_frame, types.FrameType)
        self.assertFalse(g.ag_running)
        #self.assertIsInstance(g.ag_code, types.CodeType)

        self.assertTrue(inspect_isawaitable(g.aclose()))

@requires_asyncio
class AsyncGenAsyncioTest(unittest.TestCase):

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

    def tearDown(self):
        self.loop.close()
        self.loop = None

    async def to_list(self, gen):
        res = []
        async for i in gen:
            res.append(i)
        return res

    def test_async_gen_asyncio_01(self):
        async def gen():
            yield 1
            await asyncio.sleep(0.01)
            yield 2
            await asyncio.sleep(0.01)
            return
            yield 3

        res = self.loop.run_until_complete(self.to_list(gen()))
        self.assertEqual(res, [1, 2])

    def test_async_gen_asyncio_02(self):
        async def gen():
            yield 1
            await asyncio.sleep(0.01)
            yield 2
            1 / ZERO
            yield 3

        with self.assertRaises(ZeroDivisionError):
            self.loop.run_until_complete(self.to_list(gen()))

    def test_async_gen_asyncio_03(self):
        loop = self.loop

        class Gen:
            async def __aiter__(self):
                yield 1
                await asyncio.sleep(0.01)
                yield 2

        res = loop.run_until_complete(self.to_list(Gen()))
        self.assertEqual(res, [1, 2])

    def test_async_gen_asyncio_anext_04(self):
        async def foo():
            yield 1
            await asyncio.sleep(0.01)
            try:
                yield 2
                yield 3
            except ZeroDivisionError:
                yield 1000
            await asyncio.sleep(0.01)
            yield 4

        async def run1():
            it = foo().__aiter__()

            self.assertEqual(await it.__anext__(), 1)
            self.assertEqual(await it.__anext__(), 2)
            self.assertEqual(await it.__anext__(), 3)
            self.assertEqual(await it.__anext__(), 4)
            with self.assertRaises(StopAsyncIteration):
                await it.__anext__()
            with self.assertRaises(StopAsyncIteration):
                await it.__anext__()

        async def run2():
            it = foo().__aiter__()

            self.assertEqual(await it.__anext__(), 1)
            self.assertEqual(await it.__anext__(), 2)
            try:
                it.__anext__().throw(ZeroDivisionError)
            except StopIteration as ex:
                self.assertEqual(ex.args[0], 1000)
            else:
                self.fail('StopIteration was not raised')
            self.assertEqual(await it.__anext__(), 4)
            with self.assertRaises(StopAsyncIteration):
                await it.__anext__()

        self.loop.run_until_complete(run1())
        self.loop.run_until_complete(run2())

    def test_async_gen_asyncio_anext_05(self):
        async def foo():
            v = yield 1
            v = yield v
            yield v * 100

        async def run():
            it = foo().__aiter__()

            try:
                it.__anext__().send(None)
            except StopIteration as ex:
                self.assertEqual(ex.args[0], 1)
            else:
                self.fail('StopIteration was not raised')

            try:
                it.__anext__().send(10)
            except StopIteration as ex:
                self.assertEqual(ex.args[0], 10)
            else:
                self.fail('StopIteration was not raised')

            try:
                it.__anext__().send(12)
            except StopIteration as ex:
                self.assertEqual(ex.args[0], 1200)
            else:
                self.fail('StopIteration was not raised')

            with self.assertRaises(StopAsyncIteration):
                await it.__anext__()

        self.loop.run_until_complete(run())

    def test_async_gen_asyncio_anext_06(self):
        DONE = 0

        # test synchronous generators
        def foo():
            try:
                yield
            except:
                pass
        g = foo()
        g.send(None)
        with self.assertRaises(StopIteration):
            g.send(None)

        # now with asynchronous generators

        async def gen():
            nonlocal DONE
            try:
                yield
            except:
                pass
            DONE = 1

        async def run():
            nonlocal DONE
            g = gen()
            await g.asend(None)
            with self.assertRaises(StopAsyncIteration):
                await g.asend(None)
            DONE += 10

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 11)

    def test_async_gen_asyncio_anext_tuple(self):
        async def foo():
            try:
                yield (1,)
            except ZeroDivisionError:
                yield (2,)

        async def run():
            it = foo().__aiter__()

            self.assertEqual(await it.__anext__(), (1,))
            with self.assertRaises(StopIteration) as cm:
                it.__anext__().throw(ZeroDivisionError)
            self.assertEqual(cm.exception.args[0], (2,))
            with self.assertRaises(StopAsyncIteration):
                await it.__anext__()

        self.loop.run_until_complete(run())

    def test_async_gen_asyncio_anext_stopiteration(self):
        async def foo():
            try:
                yield StopIteration(1)
            except ZeroDivisionError:
                yield StopIteration(3)

        async def run():
            it = foo().__aiter__()

            v = await it.__anext__()
            self.assertIsInstance(v, StopIteration)
            self.assertEqual(v.value, 1)
            with self.assertRaises(StopIteration) as cm:
                it.__anext__().throw(ZeroDivisionError)
            v = cm.exception.args[0]
            self.assertIsInstance(v, StopIteration)
            self.assertEqual(v.value, 3)
            with self.assertRaises(StopAsyncIteration):
                await it.__anext__()

        self.loop.run_until_complete(run())

    def test_async_gen_asyncio_aclose_06(self):
        async def foo():
            try:
                yield 1
                1 / ZERO
            finally:
                await asyncio.sleep(0.01)
                yield 12

        async def run():
            gen = foo()
            it = gen.__aiter__()
            await it.__anext__()
            await gen.aclose()

        with self.assertRaisesRegex(
                RuntimeError,
                "async generator ignored GeneratorExit"):
            self.loop.run_until_complete(run())

    def test_async_gen_asyncio_aclose_07(self):
        DONE = 0

        async def foo():
            nonlocal DONE
            try:
                yield 1
                1 / ZERO
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE += 1
            DONE += 1000

        async def run():
            gen = foo()
            it = gen.__aiter__()
            await it.__anext__()
            await gen.aclose()

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_aclose_08(self):
        DONE = 0

        fut = asyncio.Future(loop=self.loop)

        async def foo():
            nonlocal DONE
            try:
                yield 1
                await fut
                DONE += 1000
                yield 2
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE += 1
            DONE += 1000

        async def run():
            gen = foo()
            it = gen.__aiter__()
            self.assertEqual(await it.__anext__(), 1)
            await gen.aclose()

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

        # Silence ResourceWarnings
        fut.cancel()
        self.loop.run_until_complete(asyncio.sleep(0.01))

    @needs_py36_asyncio
    def test_async_gen_asyncio_gc_aclose_09(self):
        DONE = 0

        async def gen():
            nonlocal DONE
            try:
                while True:
                    yield 1
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE = 1

        async def run():
            g = gen()
            await g.__anext__()
            await g.__anext__()
            del g

            await asyncio.sleep(0.2)

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_aclose_10(self):
        DONE = 0

        # test synchronous generators
        def foo():
            try:
                yield
            except:
                pass
        g = foo()
        g.send(None)
        g.close()

        # now with asynchronous generators

        async def gen():
            nonlocal DONE
            try:
                yield
            except:
                pass
            DONE = 1

        async def run():
            nonlocal DONE
            g = gen()
            await g.asend(None)
            await g.aclose()
            DONE += 10

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 11)

    def test_async_gen_asyncio_aclose_11(self):
        DONE = 0

        # test synchronous generators
        def foo():
            try:
                yield
            except:
                pass
            yield
        g = foo()
        g.send(None)
        with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):
            g.close()

        # now with asynchronous generators

        async def gen():
            nonlocal DONE
            try:
                yield
            except:
                pass
            yield
            DONE += 1

        async def run():
            nonlocal DONE
            g = gen()
            await g.asend(None)
            with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):
                await g.aclose()
            DONE += 10

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 10)

    def test_async_gen_asyncio_aclose_12(self):
        DONE = 0

        async def target():
            await asyncio.sleep(0.01)
            1 / ZERO

        async def foo():
            nonlocal DONE
            task = self.loop.create_task(target())
            try:
                yield 1
            finally:
                try:
                    await task
                except ZeroDivisionError:
                    DONE = 1

        async def run():
            gen = foo()
            it = gen.__aiter__()
            await it.__anext__()
            await gen.aclose()

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_asend_01(self):
        DONE = 0

        # Sanity check:
        def sgen():
            v = yield 1
            yield v * 2
        sg = sgen()
        v = sg.send(None)
        self.assertEqual(v, 1)
        v = sg.send(100)
        self.assertEqual(v, 200)

        async def gen():
            nonlocal DONE
            try:
                await asyncio.sleep(0.01)
                v = yield 1
                await asyncio.sleep(0.01)
                yield v * 2
                await asyncio.sleep(0.01)
                return
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE = 1

        async def run():
            g = gen()

            v = await g.asend(None)
            self.assertEqual(v, 1)

            v = await g.asend(100)
            self.assertEqual(v, 200)

            with self.assertRaises(StopAsyncIteration):
                await g.asend(None)

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_asend_02(self):
        DONE = 0

        async def sleep_n_crash(delay):
            await asyncio.sleep(delay)
            1 / ZERO

        async def gen():
            nonlocal DONE
            try:
                await asyncio.sleep(0.01)
                v = yield 1
                await sleep_n_crash(0.01)
                DONE += 1000
                yield v * 2
            finally:
                assert sys.exc_info()[0] == ZeroDivisionError
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE += 1

        async def run():
            g = gen()

            v = await g.asend(None)
            self.assertEqual(v, 1)

            await g.asend(100)

        with self.assertRaises(ZeroDivisionError):
            self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_asend_03(self):
        DONE = 0

        async def sleep_n_crash(delay):
            fut = asyncio.ensure_future(asyncio.sleep(delay),
                                        loop=self.loop)
            self.loop.call_later(delay / 2, lambda: fut.cancel())
            return await fut

        async def gen():
            nonlocal DONE
            try:
                await asyncio.sleep(0.01)
                v = yield 1
                await sleep_n_crash(0.01)
                DONE += 1000
                yield v * 2
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE = 1

        async def run():
            g = gen()

            v = await g.asend(None)
            self.assertEqual(v, 1)

            await g.asend(100)

        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_athrow_01(self):
        DONE = 0

        class FooEr(Exception):
            pass

        # Sanity check:
        def sgen():
            try:
                v = yield 1
            except FooEr:
                v = 1000
            yield v * 2
        sg = sgen()
        v = sg.send(None)
        self.assertEqual(v, 1)
        v = sg.throw(FooEr)
        self.assertEqual(v, 2000)
        with self.assertRaises(StopIteration):
            sg.send(None)

        async def gen():
            nonlocal DONE
            try:
                await asyncio.sleep(0.01)
                try:
                    v = yield 1
                except FooEr:
                    v = 1000
                    await asyncio.sleep(0.01)
                yield v * 2
                await asyncio.sleep(0.01)
                # return
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE = 1

        async def run():
            g = gen()

            v = await g.asend(None)
            self.assertEqual(v, 1)

            v = await g.athrow(FooEr)
            self.assertEqual(v, 2000)

            with self.assertRaises(StopAsyncIteration):
                await g.asend(None)

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_athrow_02(self):
        DONE = 0

        class FooEr(Exception):
            pass

        async def sleep_n_crash(delay):
            fut = asyncio.ensure_future(asyncio.sleep(delay),
                                        loop=self.loop)
            self.loop.call_later(delay / 2, lambda: fut.cancel())
            return await fut

        async def gen():
            nonlocal DONE
            try:
                await asyncio.sleep(0.01)
                try:
                    v = yield 1
                except FooEr:
                    await sleep_n_crash(0.01)
                yield v * 2
                await asyncio.sleep(0.01)
                # return
            finally:
                await asyncio.sleep(0.01)
                await asyncio.sleep(0.01)
                DONE = 1

        async def run():
            g = gen()

            v = await g.asend(None)
            self.assertEqual(v, 1)

            try:
                await g.athrow(FooEr)
            except asyncio.CancelledError:
                self.assertEqual(DONE, 1)
                raise
            else:
                self.fail('CancelledError was not raised')

        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(run())
        self.assertEqual(DONE, 1)

    def test_async_gen_asyncio_athrow_03(self):
        DONE = 0

        # test synchronous generators
        def foo():
            try:
                yield
            except:
                pass
        g = foo()
        g.send(None)
        with self.assertRaises(StopIteration):
            g.throw(ValueError)

        # now with asynchronous generators

        async def gen():
            nonlocal DONE
            try:
                yield
            except:
                pass
            DONE = 1

        async def run():
            nonlocal DONE
            g = gen()
            await g.asend(None)
            with self.assertRaises(StopAsyncIteration):
                await g.athrow(ValueError)
            DONE += 10

        self.loop.run_until_complete(run())
        self.assertEqual(DONE, 11)

    def test_async_gen_asyncio_athrow_tuple(self):
        async def gen():
            try:
                yield 1
            except ZeroDivisionError:
                yield (2,)

        async def run():
            g = gen()
            v = await g.asend(None)
            self.assertEqual(v, 1)
            v = await g.athrow(ZeroDivisionError)
            self.assertEqual(v, (2,))
            with self.assertRaises(StopAsyncIteration):
                await g.asend(None)

        self.loop.run_until_complete(run())

    def test_async_gen_asyncio_athrow_stopiteration(self):
        async def gen():
            try:
                yield 1
            except ZeroDivisionError:
                yield StopIteration(2)

        async def run():
            g = gen()
            v = await g.asend(None)
            self.assertEqual(v, 1)
            v = await g.athrow(ZeroDivisionError)
            self.assertIsInstance(v, StopIteration)
            self.assertEqual(v.value, 2)
            with self.assertRaises(StopAsyncIteration):
                await g.asend(None)

        self.loop.run_until_complete(run())

    @needs_py36_asyncio
    def test_async_gen_asyncio_shutdown_01(self):
        finalized = 0

        async def waiter(timeout):
            nonlocal finalized
            try:
                await asyncio.sleep(timeout)
                yield 1
            finally:
                await asyncio.sleep(0)
                finalized += 1

        async def wait():
            async for _ in waiter(1):
                pass

        t1 = self.loop.create_task(wait())
        t2 = self.loop.create_task(wait())

        self.loop.run_until_complete(asyncio.sleep(0.1))

        # Silence warnings
        t1.cancel()
        t2.cancel()

        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(t1)
        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(t2)

        self.loop.run_until_complete(self.loop.shutdown_asyncgens())

        self.assertEqual(finalized, 2)

    """
    def test_async_gen_expression_01(self):
        async def arange(n):
            for i in range(n):
                await asyncio.sleep(0.01)
                yield i

        def make_arange(n):
            # This syntax is legal starting with Python 3.7
            return (i * 2 async for i in arange(n))

        async def run():
            return [i async for i in make_arange(10)]

        res = self.loop.run_until_complete(run())
        self.assertEqual(res, [i * 2 for i in range(10)])

    def test_async_gen_expression_02(self):
        async def wrap(n):
            await asyncio.sleep(0.01)
            return n

        def make_arange(n):
            # This syntax is legal starting with Python 3.7
            return (i * 2 for i in range(n) if await wrap(i))

        async def run():
            return [i async for i in make_arange(10)]

        res = self.loop.run_until_complete(run())
        self.assertEqual(res, [i * 2 for i in range(1, 10)])
    """

    def test_asyncgen_nonstarted_hooks_are_cancellable(self):
        # See https://bugs.python.org/issue38013
        messages = []

        def exception_handler(loop, context):
            messages.append(context)

        async def async_iterate():
            yield 1
            yield 2

        async def main():
            # loop = asyncio.get_running_loop()
            loop = self.loop
            loop.set_exception_handler(exception_handler)

            async for i in async_iterate():
                break

        # asyncio.run(main())
        self.loop.run_until_complete(main())

        self.assertEqual([], messages)

    def test_async_gen_await_same_anext_coro_twice(self):
        async def async_iterate():
            yield 1
            yield 2

        async def run():
            it = async_iterate()
            nxt = it.__anext__()
            await nxt
            with self.assertRaisesRegex(
                    RuntimeError,
                    r"cannot reuse already awaited __anext__\(\)/asend\(\)"
            ):
                await nxt

            await it.aclose()  # prevent unfinished iterator warning

        self.loop.run_until_complete(run())

    def test_async_gen_await_same_aclose_coro_twice(self):
        async def async_iterate():
            yield 1
            yield 2

        async def run():
            it = async_iterate()
            nxt = it.aclose()
            await nxt
            with self.assertRaisesRegex(
                    RuntimeError,
                    r"cannot reuse already awaited aclose\(\)/athrow\(\)"
            ):
                await nxt

        self.loop.run_until_complete(run())

    def test_async_gen_aclose_twice_with_different_coros(self):
        # Regression test for https://bugs.python.org/issue39606
        async def async_iterate():
            yield 1
            yield 2

        async def run():
            it = async_iterate()
            await it.aclose()
            await it.aclose()

        self.loop.run_until_complete(run())

    def test_async_gen_aclose_after_exhaustion(self):
        # Regression test for https://bugs.python.org/issue39606
        async def async_iterate():
            yield 1
            yield 2

        async def run():
            it = async_iterate()
            async for _ in it:
                pass
            await it.aclose()

        self.loop.run_until_complete(run())

    """
    def test_async_gen_aclose_compatible_with_get_stack(self):
        async def async_generator():
            yield object()

        async def run():
            ag = async_generator()
            self.loop.create_task(ag.aclose())
            tasks = asyncio.all_tasks()
            for task in tasks:
                # No AttributeError raised
                task.get_stack()

        self.loop.run_until_complete(run())
    """

if __name__ == "__main__":
    unittest.main()


text:
module Thinkspace
  module Casespace
    module Api
      class PhasesController < ::Totem::Settings.class.thinkspace.authorization_api_controller
        load_and_authorize_resource class: totem_controller_model_class
        totem_action_authorize! read: [:load]
        totem_action_serializer_options

        def show
          controller_render(@phase)
        end

        def select
          controller_render(@phases)
        end

        def load
          controller_render_plural_root(@phase)  # Note: If left as a singular key on a query, ember-data ignores the record.
        end

        def submit
          can_update = can?(:update, assignment)
          ownerable  = totem_action_authorize.params_ownerable
          totem_action_authorize.send(:authorize_phase_ownerable, @phase, ownerable) if @phase.team_ownerable?
          processor = ::Thinkspace::Casespace::PhaseActions::Processor.new(@phase, current_user, action: :submit, can_update: can_update)
          processor.process_action(ownerable)
          phase_states = assignment.get_user_phase_states(assignment_phases, ownerable, current_user, can_update: can_update)
          hash         = controller_as_json(phase_states)
          hash[controller_plural_path] = []
          controller_render_json(hash)
        end

        private

        def assignment; @assignment ||= @phase.thinkspace_casespace_assignment; end

        def assignment_phases; @assignment_phases ||= assignment.thinkspace_casespace_phases.accessible_by(current_ability, :read); end

      end
    end
  end
end


text:
#include "XMLParserEntityResolver.h"
#include <stdlib.h>

#ifdef USE_XML
#include <xercesc/util/XMLString.hpp>
#include <framework/MemBufInputSource.hpp>

#include <iostream>
#include <fstream>
#include <fcntl.h>

#ifdef __linux
#include <sys/stat.h>
#endif
#ifdef WIN32
#include <stat.h>
// I think in WIN32
#endif

#ifdef __SVR4
   #include <sys/types.h>
   #include <sys/stat.h>
   #include <unistd.h>
#endif

XMLParserEntityResolver::XMLParserEntityResolver() {
   // Read "isab-mc2.dtd"
   const char* fileName = "isab-mc2.dtd";
   struct stat status;
   m_isabmc2dtd = NULL;
   stat( fileName , &status );
   uint32 fSize = status.st_size;
   FILE* f = fopen( fileName, "rb" );
   if ( f != NULL ) {
      m_isabmc2dtdLength = fSize;
      m_isabmc2dtd = new byte[ m_isabmc2dtdLength ];
      if ( fread( m_isabmc2dtd, 1, m_isabmc2dtdLength, f )
           != m_isabmc2dtdLength )
      {
         mc2log << fatal << "XMLParserEntityResolver failed to read "
                << "all of \""
                << fileName <<  "\"!" << endl;
         exit ( 1 );
      }
      fclose( f );
   } else {
      mc2log << fatal << "XMLParserEntityResolver failed to open \""
             << fileName <<  "\"!" << endl;
      exit ( 1 );
   }
}

XMLParserEntityResolver::~XMLParserEntityResolver() {
   delete [] m_isabmc2dtd;
}

InputSource*
XMLParserEntityResolver::resolveEntity( const XMLCh* const publicId,
                                        const XMLCh* const systemId )
{
   InputSource* res = NULL;
   char* sysId = XMLString::transcode( systemId );
   if ( XMLString::compareString( sysId, "isab-mc2" ) == 0 ) {
      res = new MemBufInputSource(
         m_isabmc2dtd, m_isabmc2dtdLength, "isab-mc2.dtd" );
   }
   delete [] sysId;

   return res;
}

#endif // USE_XML


text:
namespace widgetzeug
{

void enableDarkFusionStyle()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));

    auto darkPalette = QPalette{};
    darkPalette.setColor(QPalette::Window, QColor{53,53,53});
    darkPalette.setColor(QPalette::WindowText, Qt::white);
    darkPalette.setColor(QPalette::Base, QColor{25,25,25});
    darkPalette.setColor(QPalette::AlternateBase, QColor{53,53,53});
    darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
    darkPalette.setColor(QPalette::ToolTipText, Qt::white);
    darkPalette.setColor(QPalette::Text, Qt::white);
    darkPalette.setColor(QPalette::Button, QColor{53,53,53});
    darkPalette.setColor(QPalette::ButtonText, Qt::white);
    darkPalette.setColor(QPalette::BrightText, Qt::red);
    darkPalette.setColor(QPalette::Link, QColor{42, 130, 218});

    darkPalette.setColor(QPalette::Highlight, QColor{42, 130, 218});
    darkPalette.setColor(QPalette::HighlightedText, Qt::black);

    darkPalette.setColor(QPalette::Disabled, QPalette::Text, Qt::darkGray);
    darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::darkGray);

    qApp->setPalette(darkPalette);
    qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #353535; border: 1px solid white; }");
}

} // namespace widgetzeug


text:
package com.navercorp.pinpoint.bootstrap.plugin.monitor.metric;

/**
 * @author Taejin Koo
 */
public interface DoubleGauge extends CustomMetric {

    double getValue();

}


text: Sistema de inventario y rotacion de bienes


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.Storage.Blobs.Models
{
    /// <summary> The BlockList. </summary>
    public partial class BlockList
    {
        /// <summary> Initializes a new instance of BlockList. </summary>
        internal BlockList()
        {
            CommittedBlocks = new ChangeTrackingList<BlobBlock>();
            UncommittedBlocks = new ChangeTrackingList<BlobBlock>();
        }

        /// <summary> Initializes a new instance of BlockList. </summary>
        /// <param name="committedBlocks"></param>
        /// <param name="uncommittedBlocks"></param>
        internal BlockList(IEnumerable<BlobBlock> committedBlocks, IEnumerable<BlobBlock> uncommittedBlocks)
        {
            CommittedBlocks = committedBlocks;
            UncommittedBlocks = uncommittedBlocks;
        }
    }
}


text:
#include <gvg_planner/SelectBearing.h>
#include "Planner.h"
#include <gvg_mapper/RetrieveBearings.h>
#include <gvg_mapper/RetrievePath.h>
#include <gvg_mapper/CheckRelocalize.h>
#include <localizer/MinUncertainty.h>
#include <localizer/MaxUncertainty.h>
#include <gvg_mapper/GVGEdgeMsg.h>
#include <gvg_mapper/RetrieveEdges.h>
#include <sstream>

Relocalization_Simulation::Relocalization_Simulation(double laser_offset_x, double laser_offset_y, double Wvv, double Wvw, double Www, int nL, VectorXd state, MatrixXd cov) {

  retrieve_edges_cln = nh.serviceClient<gvg_mapper::RetrieveEdges>("/retrieve_edges");

  this->laser_offset_x = laser_offset_x;
  this->laser_offset_y = laser_offset_y;

  this->nL = nL;
  X = VectorXd(3*nL+3);
  P = MatrixXd::Zero(3*nL+3, 3*nL+3);

  for(int i = 0; i < state.size(); i++) {
    X(i) = state(i);
  }
  for(unsigned int i = 0; i < cov.rows(); i++) {
    for(unsigned int j = 0; j < cov.cols(); j++) {
      P(i,j) = cov(i,j);
    }
  }
  this->Wvv = Wvv;
  this->Wvw = Wvw;
  this->Www = Www;
}

// A* search guided by uncertainty and minimizing path length
std::vector<int> Relocalization_Simulation::find_optimal(int source, int target, double start_shortest_distance, double alpha, double &uncertainty) {

  std::vector<ekf_sim> paths;

  std::set<int> open_set;
  std::set<int> closed_set;
  std::map<int, int> came_from;

  ekf_sim init_sim(Wvv, Wvw, Www, alpha, nL, X, P, source);
  // Push the first few directions into the stack
  open_set.insert(source);
  init_sim.last_node = source;
  init_sim.current_node = source;
  init_sim.total_distance = 0.0;
  init_sim.start_shortest_distance = start_shortest_distance;
  paths.push_back(init_sim);
  /* Iterate through all different paths
   * At every step we take one path out and propagate the edge to its destination
   */
  while (!paths.empty()) {

    ekf_sim current = paths.at(0);
    int min_index = 0;
    for (int i = 1; i < paths.size(); i++) {
      if (paths.at(i).computeCost(target) < current.computeCost(target)) {
        current = paths.at(i);
        min_index = i;
      }
    }

    //ROS_INFO("Next min cost node: %d", current.current_node);

    paths.erase(paths.begin() + min_index);
    // Maintain open/closed set
    open_set.erase(current.current_node);
    closed_set.insert(current.current_node);

    /*ROS_INFO("Open set:" );
    for (set<int>::iterator it = open_set.begin(); it != open_set.end(); ++it) {
      cout << ' ' << *it;
    }
    cout << "\n";

    ROS_INFO("Closed set:" );
    for (set<int>::iterator it = closed_set.begin(); it != closed_set.end(); ++it) {
      cout << ' ' << *it;
    }
    cout << "\n";*/

    // Need to get all edges to current node of the path
    if (current.current_node == target) {
      cout << "Total distance travelled: " << current.total_distance << " | trace uncertainty: " << current.P.block(3, 3, 3*nL, 3*nL).trace() << endl;
      /*ofstream myfile;
      string uncertainty_output = "/home/thalassa/qzhang32/Downloads/" + temp + "/uncertainty.csv";
      myfile.open(uncertainty_output.c_str(), ios::app);
      myfile << start_shortest_distance << "," << (1.0-(current.P.block(3, 3, 3*nL, 3*nL).trace()/current.start_map_trace)) << "\n";
      myfile.close();
      string distance_output = "/home/thalassa/qzhang32/Downloads/" + temp + "/distance.csv";
      myfile.open(distance_output.c_str(), ios::app);
      myfile << start_shortest_distance << "," << current.total_distance << "\n";*/
      uncertainty = current.P.block(3, 3, 3*nL, 3*nL).trace();
      return backtrace(came_from, source, target);
    }

    gvg_mapper::RetrieveEdges edges_srv;
    edges_srv.request.node_id = current.current_node;
    if (!retrieve_edges_cln.call(edges_srv)) {
      ROS_WARN("Could not check relocalize from Mapper!");
    }
    vector<gvg_mapper::GVGEdgeMsg> current_edges = edges_srv.response.edges;

    // Enqueue all the other directions we can go, if we have never visited those nodes
    for (int i = 0; i < current_edges.size(); i++) {
      //ROS_INFO("source %d target %d", current_edges.at(i).source, current_edges.at(i).target);
      // Check that its not part of closed set
      gvg_mapper::GVGEdgeMsg traversing_edge = current_edges.at(i);
      int next_node;
      bool forward;
      if (traversing_edge.target == current.current_node) {
        forward = false;
        next_node = traversing_edge.source;
        std::set<int>::iterator it;
        it = closed_set.find(next_node);
        if (it != closed_set.end()) {
          continue;
        }
      }
      else {
        forward = true;
        next_node = current_edges.at(i).target;
        std::set<int>::iterator it;
        it = closed_set.find(traversing_edge.target);
        if (it != closed_set.end()) {
          continue;
        }
      }
      //cout << "adding node " << next_node << endl;
      ekf_sim temp(Wvv, Wvw, Www, alpha);
      temp.copy(current);

      // Calculate how much rotation to reach the edges orientation
      double current_angle = X(2);
      double target_angle;
      if (forward) target_angle = traversing_edge.line.at(0).point.z;
      else {
        target_angle = traversing_edge.line.at(traversing_edge.line.size() - 1).point.z + M_PI;
        if (target_angle > M_PI) target_angle -= 2*M_PI;
      }

      double ang_vel = 0.0;
      nh.getParam("/indoor/gvg/agent/ang_vel", ang_vel);

      double rotation = target_angle - current_angle;
      // To rotate smallest angle, just follow the sign of rotation
      if (fabs(rotation) < M_PI) {
        double time = fabs(rotation/ang_vel);
        int steps = floor(time*10);
        for (int j = steps; j > 0; j--) {
          geometry_msgs::PointStamped ps;
          if (forward) {
            ps = traversing_edge.line.at(0);
            int timesteps = j;
            while (timesteps >= 10) {
              ps.header.stamp.sec -= 1;
              timesteps -= 10;
            }
            int nsecs = ps.header.stamp.nsec - timesteps*100000000;
            while (nsecs < 0) {
              nsecs += 1000000000;
              ps.header.stamp.sec -= 1;
            }
            ps.header.stamp.nsec = nsecs;
          }
          else {
            ps = traversing_edge.line.at(traversing_edge.line.size() - 1);
            int timesteps = j;
            while (timesteps >= 10) {
              ps.header.stamp.sec += 1;
              timesteps -= 10;
            }
            int nsecs = ps.header.stamp.nsec + timesteps*100000000;
            while (nsecs > 1000000000) {
              nsecs -= 1000000000;
              ps.header.stamp.sec += 1;
            }
            ps.header.stamp.nsec = nsecs;
          }

          ps.point.z = current_angle + (steps-j)*ang_vel/10;
          while (ps.point.z < -M_PI) ps.point.z += 2*M_PI;
          while (ps.point.z > M_PI) ps.point.z -= 2*M_PI;
          temp.propagate(ps);
        }
      }
      // Following sign of rotation will be larger angle, so follow negative sign
      else {
        rotation = 2*M_PI - fabs(rotation);
        double time = rotation/ang_vel;
        int steps = floor(time*10);
        for (int j = steps; j > 0; j--) {
          geometry_msgs::PointStamped ps;
          if (forward) {
            ps = traversing_edge.line.at(0);
            int timesteps = j;
            while (timesteps >= 10) {
              ps.header.stamp.sec -= 1;
              timesteps -= 10;
            }
            int nsecs = ps.header.stamp.nsec - timesteps*100000000;
            while (nsecs < 0) {
              nsecs += 1000000000;
              ps.header.stamp.sec -= 1;
            }
            ps.header.stamp.nsec = nsecs;
          }
          else {
            ps = traversing_edge.line.at(traversing_edge.line.size() - 1);
            int timesteps = j;
            while (timesteps >= 10) {
              ps.header.stamp.sec += 1;
              timesteps -= 10;
            }
            int nsecs = ps.header.stamp.nsec + timesteps*100000000;
            while (nsecs > 1000000000) {
              nsecs -= 1000000000;
              ps.header.stamp.sec += 1;
            }
            ps.header.stamp.nsec = nsecs;
          }

          ps.point.z = current_angle - (steps-j)*ang_vel/10;
          while (ps.point.z < -M_PI) ps.point.z += 2*M_PI;
          while (ps.point.z > M_PI) ps.point.z -= 2*M_PI;
          temp.propagate(ps);
        }
      }

      // Propagate the edge for the EKF simulating that transition
      // Find the edge that connects current node to previous node so we can simulate
      if (forward) {
        for (int j = 0; j < traversing_edge.line.size(); j++) {
          temp.propagate(traversing_edge.line.at(j));
        }
      }
      else {
        for (int j = traversing_edge.line.size()-1; j >= 0; j--) {
          // Have to flip the orientation of the robot as if it had traversed it from other direction
          geometry_msgs::PointStamped ps = traversing_edge.line.at(j);
          double reversed_angle = ps.point.z + M_PI;
          if (reversed_angle > M_PI) reversed_angle -= 2*M_PI;
          ps.point.z = reversed_angle;
          temp.propagate(ps);
        }
      }

      geometry_msgs::Point32 pl;
      pl.x = temp.X(3*next_node + 3);
      pl.y = temp.X(3*next_node + 4);
      geometry_msgs::Point32 measurement;
      measurement.x = this->laser_offset_x;
      measurement.y = this->laser_offset_y;
      temp.update(next_node, pl, measurement);

      // 2 cases: not in open_set or in open set. If in open set, need to check if current path to that node is quicker than previous path
      // Find if it is in open set
      bool within_open = true;
      if (forward) {
        std::set<int>::iterator it;
        if (open_set.empty()) {
          within_open = false;
        }
        else {
          it = open_set.find(current_edges.at(i).target);
          if (it == open_set.end())
            within_open = false;
        }
      }
      else {
        std::set<int>::iterator it;
        if (open_set.empty()) {
          within_open = false;
        }
        else {
          it = open_set.find(current_edges.at(i).source);
          if (it == open_set.end())
            within_open = false;
        }
      }
      // already in open set, so look through paths to compare new path and old path
      if (within_open) {
        int index = 0;
        for (int j = 0; j < paths.size(); j++) {
          if (paths.at(j).current_node == next_node) {
            index = j;
            break;
          }
        }

        temp.total_distance += traversing_edge.length;

        // Remove old path because it has higher cost than new path to the same node
        if (temp.computeCost(target) < paths.at(index).computeCost(target)) {
          paths.erase(paths.begin() + index);
          came_from[next_node] = current.current_node;
          temp.last_node = current.current_node;
          temp.current_node = next_node;
          paths.push_back(temp);
        }
      }
      else {
        if (forward) {
          came_from[next_node] = current.current_node;
          temp.last_node = current.current_node;
          temp.current_node = next_node;
          open_set.insert(next_node);
          temp.total_distance += traversing_edge.length;
        } else {
          came_from[next_node] = current.current_node;
          temp.last_node = current.current_node;
          temp.current_node = next_node;
          open_set.insert(next_node);
          temp.total_distance += traversing_edge.length;
        }
        paths.push_back(temp);
      }
    }
  }
}

std::vector<int> Relocalization_Simulation::backtrace(std::map<int, int> map, int source, int target) {
  std::vector<int> result;
  int current = target;
  while (current != source) {
    result.push_back(current);
    current = map[current];
  }
  return result;
}

/*
 * Pass meetpoint/endpoint signatures from Follower to Mapper.
 */

Planner::Planner() {
  this->state = 0;
  this->select_bearing_srv = nh.advertiseService("select_bearing", &Planner::SelectBearingGVG, this);
  this->retrieve_bearings_cln = nh.serviceClient<gvg_mapper::RetrieveBearings>("/retrieve_bearings");
  this->retrieve_path_cln = nh.serviceClient<gvg_mapper::RetrievePath>("/retrieve_path");
  this->check_relocalize_cln = nh.serviceClient<gvg_mapper::CheckRelocalize>("/check_relocalize");
  this->min_uncertainty_cln = nh.serviceClient<localizer::MinUncertainty>("/indoor/gvg/MinUncertainty");
  this->max_uncertainty_cln = nh.serviceClient<localizer::MaxUncertainty>("/indoor/gvg/MaxUncertainty");
  this->map_sub = nh.subscribe("/indoor/gvg/theMap", 1, &Planner::handleMap, this);

  frontier_min_uncertainty_exploration = false;
  nh.getParam("/gvg_planner/frontier_min_uncertainty_exploration", frontier_min_uncertainty_exploration);
  nh.getParam("/gvg_planner/random_reloc_target", random_reloc_target);
  nL = 0;
  X=VectorXd(3);
  X << 0,0,0;
  P = MatrixXd::Zero(3,3); // The covariance matrix
  goto_min_frontier = true;
}

void Planner::handleMap(const localizer::GVGmap& map) {
  if ((unsigned) X.size() < map.state.size()) {
    X.conservativeResize(map.state.size());
  }
  nL = (map.state.size()-3)/3;
  int i = 0;
  for(std::vector<double>::const_iterator it = map.state.begin();it != map.state.end(); ++it) {
    X(i) = *it;
    i++;
  }
  std::vector<double>::const_iterator it = map.cov.begin();
  unsigned int covSize = 3*nL+3;
  if(P.cols() != covSize) {
    P.conservativeResize(covSize,covSize);
  }
  for(unsigned int i = 0; i < covSize; i++) {
    for(unsigned int j = 0; j < covSize; j++) {
      P(i,j) = *it;
      it++;
    }
  }
}

/*
 * Query the Mapper for information about current node and retrieve selected bearing for next exploration.
 * If the meetpoint has all visited edges, retrieve path plan from Mapper to return to previous meetpoint with unexplored edges.
 */
bool Planner::SelectBearingGVG(gvg_planner::SelectBearing::Request& req, gvg_planner::SelectBearing::Response& res) {

  // Exploration state
  if (state == 0) {

    /* Check relocalize */
    gvg_mapper::CheckRelocalize relocalize_srv;
    if (!check_relocalize_cln.call(relocalize_srv)) {
      ROS_WARN("Could not check relocalize from Mapper!");
      res.success = false;
      return true;
    }

    if (frontier_min_uncertainty_exploration && goto_min_frontier && nL > 1) {
      goto_min_frontier = false;
      // Before running retrieve Bearings and checking which direction to go next from current node, run heuristic search
      // and find the node that will most reduce uncertainty then continue exploration
      double Wvv = 0.0;
      double Www = 0.0;
      double Wvw = 0.0;
      nh.getParam("/indoor/gvg/localizerGVGNode/Wvv", Wvv);
      nh.getParam("/indoor/gvg/localizerGVGNode/Www", Www);
      nh.getParam("/indoor/gvg/localizerGVGNode/Wvw", Wvw);

      double laser_offset_x = 0.0;
      double laser_offset_y = 0.0;
      nh.getParam("/gvg_mapper/laser_distance_x", laser_offset_x);
      nh.getParam("/gvg_mapper/laser_distance_y", laser_offset_y);

      ROS_WARN("Current trace uncertainty: %f", P.block(3, 3, 3*nL, 3*nL).trace());

      Relocalization_Simulation reloc_sim(laser_offset_x, laser_offset_y, Wvv, Wvw, Www, nL, X, P);

      // Run this code to print out the heuristic search output to all nodes in map

      // Use relocalization sim to find path to min uncertainty node
      double min_uncertainty = INFINITY;

      double alpha = 0.0;
      nh.getParam("/gvg_planner/Astar_weight", alpha);

      for (int j = 0; j < nL; j++) {
        if (req.node_id != j) {

          double start_shortest_distance = INFINITY;
          gvg_mapper::RetrievePath pathsrv;
          pathsrv.request.source = req.node_id;
          pathsrv.request.target = j;
          if (!retrieve_path_cln.call(pathsrv)) {
            ROS_WARN("Could not retrieve shortest distance to target from Mapper!");
          }
          else {
            start_shortest_distance = pathsrv.response.distance;
          }
          if (!pathsrv.response.frontier) {
            continue;
          }
          ROS_INFO("Running heuristic search from %d to %d", req.node_id, j);
          double uncertainty = 0.0;
          vector<int> temp_path = reloc_sim.find_optimal(req.node_id, j, start_shortest_distance, alpha, uncertainty);
          if (uncertainty < min_uncertainty) {
            vertex_list.assign(temp_path.begin(), temp_path.end());
            min_uncertainty = uncertainty;
          }
        }
      }

      ROS_WARN("Final min uncertainty: %f", min_uncertainty);
      cout << "Output path from heuristic search: ";
      for (int i = vertex_list.size() - 1; i >= 0; i--) {
        if (i != 0) std::cout << vertex_list.at(i) << " -> ";
        else std::cout << vertex_list.at(i) << std::endl;
      }

      if (vertex_list.size() > 0) {
        this->state = 1;

        target = vertex_list.back();
        vertex_list.pop_back();

        // Retrieve the bearing we need to head next.
        gvg_mapper::RetrieveBearings srv;
        srv.request.node_id = req.node_id;
        srv.request.target = target;
        if (!retrieve_bearings_cln.call(srv)) {
          ROS_WARN("Could not retrieve bearings from Mapper!");
          res.success = false;
          return true;
        }
        double chosen_bearing = srv.response.chosen_bearing;

        ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
        res.selected_bearing = chosen_bearing;

        res.success = true;
        if (vertex_list.size() == 0) this->state = 0;
        return true;
      }
    }

    goto_min_frontier = true;

    /* Retrieve available bearings from gvg_mapper */
    gvg_mapper::RetrieveBearings srv;
    srv.request.node_id = req.node_id;
    srv.request.target = -1;
    if (!retrieve_bearings_cln.call(srv)) {
      ROS_WARN("Could not retrieve bearings from Mapper!");
      res.success = false;
      return true;
    }

    // Relocalize, pathplan to node with MIN uncertainty
    if (relocalize_srv.response.relocalize == 1) {
      ROS_INFO("Robot uncertainty too large. Path planning to minimum uncertainty vertex.");
      localizer::MinUncertainty minsrv;
      if (!min_uncertainty_cln.call(minsrv)) {
        ROS_WARN("Could not get minimum uncertainty vertex from localizer!");
        res.success = false;
        return true;
      }
      gvg_mapper::RetrievePath pathsrv;
      pathsrv.request.source = req.node_id;
      pathsrv.request.target = minsrv.response.id;
      if (!retrieve_path_cln.call(pathsrv)) {
        ROS_WARN("Could not retrieve path plan from Mapper!");
        res.success = false;
        return true;
      }

      vertex_list = pathsrv.response.vertex_list;
      this->state = 1;

      target = vertex_list.back();
      vertex_list.pop_back();

      // Retrieve the bearing we need to head next.
      gvg_mapper::RetrieveBearings srv;
      srv.request.node_id = req.node_id;
      srv.request.target = target;
      if (!retrieve_bearings_cln.call(srv)) {
        ROS_WARN("Could not retrieve bearings from Mapper!");
        res.success = false;
        return true;
      }
      double chosen_bearing = srv.response.chosen_bearing;

      ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
      res.selected_bearing = chosen_bearing;

      res.success = true;
      if (vertex_list.size() == 0) this->state = 0;
      return true;
    }

    // Random relocalization, path plan to MIN uncertainty vertex
    if (relocalize_srv.response.relocalize == 2) {
      ROS_INFO("Random relocalization. Path planning to minimum uncertainty vertex.");

      // The model noise covariance (linear and angular velocity) defined in localizer launch files
      double Wvv = 0.0;
      double Www = 0.0;
      double Wvw = 0.0;
      nh.getParam("/indoor/gvg/localizerGVGNode/Wvv", Wvv);
      nh.getParam("/indoor/gvg/localizerGVGNode/Www", Www);
      nh.getParam("/indoor/gvg/localizerGVGNode/Wvw", Wvw);

      double laser_offset_x = 0.0;
      double laser_offset_y = 0.0;
      nh.getParam("/gvg_mapper/laser_distance_x", laser_offset_x);
      nh.getParam("/gvg_mapper/laser_distance_y", laser_offset_y);

      Relocalization_Simulation reloc_sim(laser_offset_x, laser_offset_y, Wvv, Wvw, Www, nL, X, P);

      // Run this code to print out the heuristic search output to all nodes in map

      // Use relocalization sim to find path to min uncertainty node
      double min_uncertainty = INFINITY;

      double alpha = 0.0;
      nh.getParam("/gvg_planner/Astar_weight", alpha);

      for (int j = 0; j < nL; j++) {
        if (req.node_id != j) {

          double start_shortest_distance = INFINITY;
          gvg_mapper::RetrievePath pathsrv;
          pathsrv.request.source = req.node_id;
          pathsrv.request.target = j;
          if (!retrieve_path_cln.call(pathsrv)) {
            ROS_WARN("Could not retrieve shortest distance to target from Mapper!");
          }
          else {
            start_shortest_distance = pathsrv.response.distance;
          }

          ROS_INFO("Running heuristic search from %d to %d", req.node_id, j);
          double uncertainty = 0.0;
          vector<int> temp_path = reloc_sim.find_optimal(req.node_id, j, start_shortest_distance, alpha, uncertainty);
          if (uncertainty < min_uncertainty) {
            vertex_list.assign(temp_path.begin(), temp_path.end());
            min_uncertainty = uncertainty;
          }
        }
      }

      ROS_WARN("Final min uncertainty: %f", min_uncertainty);
      cout << "Output path from heuristic search: ";
      for (int i = vertex_list.size() - 1; i >= 0; i--) {
        if (i != 0) std::cout << vertex_list.at(i) << " -> ";
        else std::cout << vertex_list.at(i) << std::endl;
      }

      /*
      localizer::MinUncertainty minsrv;
      if (!min_uncertainty_cln.call(minsrv)) {
        ROS_WARN("Could not get minimum uncertainty vertex from localizer!");
        res.success = false;
        return true;
      }

      gvg_mapper::RetrievePath pathsrv;
      pathsrv.request.source = req.node_id;
      pathsrv.request.target = minsrv.response.id;
      if (!retrieve_path_cln.call(pathsrv)) {
        ROS_WARN("Could not retrieve path plan from Mapper!");
        res.success = false;
        return true;
      }

      vertex_list = pathsrv.response.vertex_list;*/
      this->state = 1;

      target = vertex_list.back();
      vertex_list.pop_back();

      // Retrieve the bearing we need to head next.
      gvg_mapper::RetrieveBearings srv;
      srv.request.node_id = req.node_id;
      srv.request.target = target;
      if (!retrieve_bearings_cln.call(srv)) {
        ROS_WARN("Could not retrieve bearings from Mapper!");
        res.success = false;
        return true;
      }
      double chosen_bearing = srv.response.chosen_bearing;

      ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
      res.selected_bearing = chosen_bearing;

      res.success = true;
      if (vertex_list.size() == 0) this->state = 0;
      return true;
    }

    double chosen_bearing = srv.response.chosen_bearing;

    // Still unexplored edges to visit
    if (chosen_bearing != NULL) {
      ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
      res.selected_bearing = chosen_bearing;

      res.success = true;
      return true;
    }
    // Explored all edges at this vertex, path plan to previously nonexplored edges vertex.
    else {
      ROS_INFO("All edges explored at this vertex. Requesting path to previously non-explored edges vertex.");
      gvg_mapper::RetrievePath pathsrv;
      pathsrv.request.source = req.node_id;
      pathsrv.request.target = -1;
      if (!retrieve_path_cln.call(pathsrv)) {
        ROS_WARN("Could not retrieve path plan from Mapper!");
        res.success = false;
        return true;
      }

      // Relocalization
      if ((int) pathsrv.response.vertex_list.size() == 0) {
        /*if (!repositioned) {
          repositioned = true;
          ROS_WARN("Where to reposition to?");
          string str = "";
          getline(cin, str);
          stringstream stream(str);
          int target;
          stream >> target;

          pathsrv.request.source = req.node_id;
          pathsrv.request.target = target;
          if (!retrieve_path_cln.call(pathsrv)) {
            ROS_WARN("Could not retrieve path plan from Mapper!");
            res.success = false;
            return true;
          }
          vertex_list = pathsrv.response.vertex_list;
          ROS_INFO("Path planning to return to vertex %d", vertex_list[0]);
          std::cout << "Shortest path proposed: ";
          for (int i = vertex_list.size() - 1; i >= 0; i--) {
            if (i != 0) std::cout << vertex_list.at(i) << " -> ";
            else std::cout << vertex_list.at(i) << std::endl;
          }
        }*/
        ROS_WARN("Entire map has been explored. Relocalizing...");
        ROS_WARN("Current trace of covariance: %.2f", P.block(3, 3, 3*nL, 3*nL).trace());

        int target_node;

        if (random_reloc_target) {
          target_node = req.node_id;
          while (target_node == req.node_id) {
            target_node = rand() % nL;
          }
        }
        else {
          localizer::MaxUncertainty maxsrv;
          if (!max_uncertainty_cln.call(maxsrv)) {
            ROS_WARN("Could not get maximum uncertainty vertex from localizer!");
            res.success = false;
            return true;
          }
          target_node = maxsrv.response.id;
          if (req.node_id == maxsrv.response.id) {
            localizer::MaxUncertainty minsrv;
            if (!min_uncertainty_cln.call(minsrv)) {
              ROS_WARN("Could not get minimum uncertainty vertex from localizer!");
              res.success = false;
              return true;
            }
            target_node = minsrv.response.id;
          }
        }

        // The model noise covariance (linear and angular velocity) defined in localizer launch files
        double Wvv = 0.0;
        double Www = 0.0;
        double Wvw = 0.0;
        nh.getParam("/indoor/gvg/localizerGVGNode/Wvv", Wvv);
        nh.getParam("/indoor/gvg/localizerGVGNode/Www", Www);
        nh.getParam("/indoor/gvg/localizerGVGNode/Wvw", Wvw);

        double laser_offset_x = 0.0;
        double laser_offset_y = 0.0;
        nh.getParam("/gvg_mapper/laser_distance_x", laser_offset_x);
        nh.getParam("/gvg_mapper/laser_distance_y", laser_offset_y);

        Relocalization_Simulation reloc_sim(laser_offset_x, laser_offset_y, Wvv, Wvw, Www, nL, X, P);

        // Run this code to print out the heuristic search output to all nodes in map

        // Use relocalization sim to find path to min uncertainty node
        double min_uncertainty = INFINITY;

        double alpha = 0.0;
        nh.getParam("/gvg_planner/Astar_weight", alpha);

        for (int j = 0; j < nL; j++) {
          if (req.node_id != j) {

            double start_shortest_distance = INFINITY;
            pathsrv.request.source = req.node_id;
            pathsrv.request.target = j;
            if (!retrieve_path_cln.call(pathsrv)) {
              ROS_WARN("Could not retrieve shortest distance to target from Mapper!");
            }
            else {
              start_shortest_distance = pathsrv.response.distance;
            }

            ROS_INFO("Running heuristic search from %d to %d", req.node_id, j);
            double uncertainty = 0.0;
            vector<int> temp_path = reloc_sim.find_optimal(req.node_id, j, start_shortest_distance, alpha, uncertainty);
            if (uncertainty < min_uncertainty) {
              vertex_list.assign(temp_path.begin(), temp_path.end());
              min_uncertainty = uncertainty;
            }
          }
        }

        ROS_WARN("Final min uncertainty: %f", min_uncertainty);
        cout << "Output path from heuristic search: ";
        for (int i = vertex_list.size() - 1; i >= 0; i--) {
          if (i != 0) std::cout << vertex_list.at(i) << " -> ";
          else std::cout << vertex_list.at(i) << std::endl;
        }
        // Run this code to actually relocalize to max/min uncertainty node
        /*
        double start_shortest_distance = INFINITY;
        pathsrv.request.source = req.node_id;
        pathsrv.request.target = target_node;
        if (!retrieve_path_cln.call(pathsrv)) {
          ROS_WARN("Could not retrieve shortest distance to target from Mapper!");
        }
        else {
          start_shortest_distance = pathsrv.response.distance;
        }

        double alpha = 0.0;
        nh.getParam("/gvg_planner/Astar_weight", alpha);

        ROS_INFO("Running heuristic search from %d to %d", req.node_id, target_node);
        vertex_list = reloc_sim.find_optimal(req.node_id, target_node, start_shortest_distance, alpha);
        cout << "Output path from heuristic search: ";
        for (int i = vertex_list.size() - 1; i >= 0; i--) {
          if (i != 0) std::cout << vertex_list.at(i) << " -> ";
          else std::cout << vertex_list.at(i) << std::endl;
        }*/

        /*STOP AFTER A FEW ITERATIONS I SUPPOSE
         * nh.setParam("/indoor/gvg/agent/do_move", false);
        res.success = true;
        return true;*/
      }
      else {
        vertex_list = pathsrv.response.vertex_list;
        ROS_INFO("Path planning to return to vertex %d", vertex_list[0]);
        std::cout << "Shortest path proposed: ";
        for (int i = vertex_list.size() - 1; i >= 0; i--) {
          if (i != 0) std::cout << vertex_list.at(i) << " -> ";
          else std::cout << vertex_list.at(i) << std::endl;
        }
      }
      this->state = 1;

      target = vertex_list.back();
      vertex_list.pop_back();

      // Retrieve the bearing we need to head next.
      gvg_mapper::RetrieveBearings srv;
      srv.request.node_id = req.node_id;
      srv.request.target = target;
      if (!retrieve_bearings_cln.call(srv)) {
        ROS_WARN("Could not retrieve bearings from Mapper!");
        res.success = false;
        return true;
      }
      double chosen_bearing = srv.response.chosen_bearing;

      ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
      res.selected_bearing = chosen_bearing;

      res.success = true;
      if (vertex_list.size() == 0) this->state = 0;
      return true;
    }

  // Pathplanning state
  } else {
    if (target != req.node_id) {
      ROS_WARN("Robot did not reach the planned target. Restarting path planning.");
      gvg_mapper::RetrievePath pathsrv;
      pathsrv.request.source = req.node_id;
      if (!retrieve_path_cln.call(pathsrv)) {
        ROS_WARN("Could not retrieve path plan from Mapper!");
        res.success = false;
        return true;
      }
      vertex_list = pathsrv.response.vertex_list;
      this->state = 1;

      target = vertex_list.back();
      vertex_list.pop_back();

      // Retrieve the bearing we need to head next.
      gvg_mapper::RetrieveBearings srv;
      srv.request.node_id = req.node_id;
      srv.request.target = target;
      if (!retrieve_bearings_cln.call(srv)) {
        ROS_WARN("Could not retrieve bearings from Mapper!");
        res.success = false;
        return true;
      }
      double chosen_bearing = srv.response.chosen_bearing;

      ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
      res.selected_bearing = chosen_bearing;

      res.success = true;
      if (vertex_list.size() == 0) this->state = 0;
      return true;
    }
    target = vertex_list.back();
    vertex_list.pop_back();

    // Retrieve the bearing we need to head next.
    gvg_mapper::RetrieveBearings srv;
    srv.request.node_id = req.node_id;
    srv.request.target = target;
    if (!retrieve_bearings_cln.call(srv)) {
      ROS_WARN("Could not retrieve bearings from Mapper!");
      res.success = false;
      return true;
    }
    double chosen_bearing = srv.response.chosen_bearing;

    ROS_INFO("Requested direction from GVG Follower: %.2f", chosen_bearing * 180.0/M_PI);
    res.selected_bearing = chosen_bearing;

    res.success = true;
    if (vertex_list.size() == 0) this->state = 0;
    return true;
  }
}