text:
package test;

import org.apache.felix.dm.Component;
import org.apache.felix.dm.ComponentState;
import org.apache.felix.dm.ComponentStateListener;
import org.apache.felix.dm.impl.ComponentImpl;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author Felix Project Team
 */
@SuppressWarnings("unused")
public class ComponentTest {
	static class MyComponent {
		public MyComponent() {
		}
	}

	@Test
	public void createStartAndStopComponent() {
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(MyComponent.class);
		Assert.assertEquals("should not be available until started", false, c.isAvailable());
		c.start();
		Assert.assertEquals("should be available", true, c.isAvailable());
		c.stop();
		Assert.assertEquals("should no longer be available when stopped", false, c.isAvailable());
	}

	@Test
	public void testInitCallbackOfComponent() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			void init() {
				e.step(2);
			}
            void start() {
				e.step(3);
			}
			void stop() {
				e.step(5);
			}
			void destroy() {
				e.step(6);
			}
		});
		e.step(1);
		c.start();
		e.step(4);
		c.stop();
		e.step(7);
	}

	@Test
	public void testAddDependencyFromInitCallback() {
		final Ensure e = new Ensure();
		final SimpleServiceDependency d = new SimpleServiceDependency();
		d.setRequired(true);
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			void init(Component c) {
				e.step(2);
				c.add(d);
			}
			void start() {
				e.step(4);
			}
			void stop() {
				e.step(6);
			}
			void destroy() {
				e.step(7);
			}
		});
		e.step(1);
		c.start();
		e.step(3);
		d.add(new EventImpl()); // NPE?!
		e.step(5);
		d.remove(new EventImpl());
		c.stop();
		e.step(8);
	}

    @Test
    public void testAddAvailableDependencyFromInitCallback() {
        final Ensure e = new Ensure();
        final SimpleServiceDependency d = new SimpleServiceDependency();
        d.setRequired(true);
        final SimpleServiceDependency d2 = new SimpleServiceDependency();
        d2.setRequired(true);
        ComponentImpl c = new ComponentImpl();
        c.setImplementation(new Object() {
            void init(Component c) {
                System.out.println("init");
                e.step(2);
                c.add(d);
                d.add(new EventImpl());
                c.add(d2);
            }
            void start() {
                System.out.println("start");
                e.step();
            }
            void stop() {
                System.out.println("stop");
                e.step();
            }
            void destroy() {
                System.out.println("destroy");
                e.step(7);
            }
        });
        e.step(1);
        c.start();
        e.step(3);
        d2.add(new EventImpl());
        e.step(5);
        d.remove(new EventImpl());
        c.stop();
        e.step(8);
    }

	@Test
	public void testAtomicallyAddMultipleDependenciesFromInitCallback() {
		final Ensure e = new Ensure();
		final SimpleServiceDependency d = new SimpleServiceDependency();
		d.setRequired(true);

		final SimpleServiceDependency d2 = new SimpleServiceDependency();
		d2.setRequired(true);

		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			void init(Component c) {
				System.out.println("init");
				e.step(2);
				c.add(d, d2);
				d.add(new EventImpl()); // won't trigger start because d2 is not yet available
			}
			void start() {
				System.out.println("start");
				e.step(4);
			}
			void stop() {
				System.out.println("stop");
				e.step(6);
			}
			void destroy() {
				System.out.println("destroy");
				e.step(7);
			}
		});
		e.step(1);
		c.start();
		e.step(3);
		d2.add(new EventImpl());
		e.step(5);
		d.remove(new EventImpl());
		c.stop();
		e.step(8);
	}

	@Test
	public void createComponentAddDependencyAndStartComponent() {
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(MyComponent.class);
		SimpleServiceDependency d = new SimpleServiceDependency();
		d.setRequired(true);
		c.add(d);
		c.start();
		Assert.assertEquals("should not be available when started because of missing dependency", false, c.isAvailable());
		c.stop();
		c.remove(d);
	}

	@Test
	public void createComponentStartItAndAddDependency() {
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(MyComponent.class);
		SimpleServiceDependency d = new SimpleServiceDependency();
		d.setRequired(true);
		c.start();
		Assert.assertEquals("should be available when started", true, c.isAvailable());
		c.add(d);
		Assert.assertEquals("dependency should not be available", false, d.isAvailable());
		Assert.assertEquals("Component should not be available", false, c.isAvailable());
		c.remove(d);
		c.stop();
	}

	@Test
	public void createComponentStartItAddDependencyAndMakeDependencyAvailable() {
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(MyComponent.class);
		SimpleServiceDependency d = new SimpleServiceDependency();
		d.setRequired(true);
		c.start();
		c.add(d);
		Assert.assertEquals("Component should not be available: it is started but the dependency is not available", false, c.isAvailable());
		d.add(new EventImpl());
		Assert.assertEquals("dependency is available, component should be too", true, c.isAvailable());
		d.remove(new EventImpl());
		Assert.assertEquals("dependency is no longer available, component should not be either", false, c.isAvailable());
		c.remove(d);
		Assert.assertEquals("dependency is removed, component should be available again", true, c.isAvailable());
		c.stop();
		Assert.assertEquals("Component is stopped, should be unavailable now", false, c.isAvailable());
	}

	@Test
	public void createComponentStartItAddDependencyAndListenerMakeDependencyAvailableAndUnavailableImmediately() {
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(MyComponent.class);
		final SimpleServiceDependency d = new SimpleServiceDependency();
		d.setRequired(true);
		ComponentStateListener l = new ComponentStateListener() {
			@Override
			public void changed(Component c, ComponentState state) {
				// make the dependency unavailable
				d.remove(new EventImpl());
			}
		};
		c.start();
		c.add(d);
		// we add a listener here which immediately triggers an 'external event' that
		// makes the dependency unavailable again as soon as it's invoked
		c.add(l);
		Assert.assertEquals("Component unavailable, dependency unavailable", false, c.isAvailable());
		// so even though we make the dependency available here, before our call returns it
		// is made unavailable again
		d.add(new EventImpl());
		Assert.assertEquals("Component *still* unavailable, because the listener immediately makes the dependency unavailable", false, c.isAvailable());
		c.remove(l);
		Assert.assertEquals("listener removed, component still unavailable", false, c.isAvailable());
		c.remove(d);
		Assert.assertEquals("dependency removed, component available", true, c.isAvailable());
		c.stop();
		Assert.assertEquals("Component stopped, should be unavailable", false, c.isAvailable());
	}

	@Test
	public void createComponentAddTwoDependenciesMakeBothAvailableAndUnavailable() {
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(MyComponent.class);
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setRequired(true);
		SimpleServiceDependency d2 = new SimpleServiceDependency();
		d2.setRequired(true);
		c.start();
		c.add(d1);
		c.add(d2);
		Assert.assertEquals("Component should be unavailable, both dependencies are too", false, c.isAvailable());
		d1.add(new EventImpl());
		Assert.assertEquals("one dependency available, component should still be unavailable", false, c.isAvailable());
		d2.add(new EventImpl());
		Assert.assertEquals("both dependencies available, component should be available", true, c.isAvailable());
		d1.remove(new EventImpl());
		Assert.assertEquals("one dependency unavailable again, component should be unavailable too", false, c.isAvailable());
		d2.remove(new EventImpl());
		Assert.assertEquals("both dependencies unavailable, component should be too", false, c.isAvailable());
		c.remove(d2);
		Assert.assertEquals("removed one dependency, still unavailable", false, c.isAvailable());
		c.remove(d1);
		Assert.assertEquals("removed the other dependency, component should be available now", true, c.isAvailable());
		c.stop();
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createComponentAddDependencyMakeAvailableAndUnavailableWithCallbacks() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
            public void add() {
				e.step(1);
			}
            public void remove() {
				e.step(3);
			}
		});
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "remove");
		d1.setRequired(true);
		// add the dependency to the component
		c.add(d1);
		// start the component
		c.start();
		// make the dependency available, we expect the add callback
		// to be invoked here
		d1.add(new EventImpl());
		e.step(2);
		// remove the dependency, should trigger the remove callback
		d1.remove(new EventImpl());
		e.step(4);
		c.stop();
		c.remove(d1);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createAndStartComponentAddDependencyMakeAvailableAndUnavailableWithCallbacks() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step(1);
			}
			public void remove() {
				e.step(3);
			}
		});
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "remove");
		d1.setRequired(true);
		// start the ComponentImpl (it should become available)
		c.start();
		// add the dependency (it should become unavailable)
		c.add(d1);
		// make the dependency available, which should invoke the
		// add callback
		d1.add(new EventImpl());
		e.step(2);
		// make the dependency unavailable, should trigger the
		// remove callback
		d1.remove(new EventImpl());
		e.step(4);
		c.remove(d1);
		c.stop();
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createComponentAddTwoDependenciesMakeBothAvailableAndUnavailableWithCallbacks() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step();
			}
			public void remove() {
				e.step();
			}
		});
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "remove");
		d1.setRequired(true);
		SimpleServiceDependency d2 = new SimpleServiceDependency();
		d2.setCallbacks("add", "remove");
		d2.setRequired(true);
		// start the component, which should become active because there are no
		// dependencies yet
		c.start();
		// now add the dependencies, making the ComponentImpl unavailable
		c.add(d1);
		c.add(d2);
		// make the first dependency available, should have no effect on the
		// component
		d1.add(new EventImpl());
		e.step(1);
		// second dependency available, now all the add callbacks should be
		// invoked
		d2.add(new EventImpl());
		e.step(4);
		// remove the first dependency, triggering the remove callbacks
		d1.remove(new EventImpl());
		e.step(7);
		// remove the second dependency, should not trigger more callbacks
		d2.remove(new EventImpl());
		e.step(8);
		c.remove(d2);
		c.remove(d1);
		c.stop();
		// still, no more callbacks should have been invoked
		e.step(9);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createAndStartComponentAddTwoDependenciesMakeBothAvailableAndUnavailableWithCallbacks() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step();
			}
			public void remove() {
				e.step();
			}
		});
		// start the component, it should become available
		c.start();
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "remove");
		d1.setRequired(true);
		SimpleServiceDependency d2 = new SimpleServiceDependency();
		d2.setCallbacks("add", "remove");
		d2.setRequired(true);
		// add the first dependency, ComponentImpl should be unavailable
		c.add(d1);
		c.add(d2);
		// make first dependency available, ComponentImpl should still be unavailable
		d1.add(new EventImpl());
		e.step(1);
		// make second dependency available, ComponentImpl available, callbacks should
		// be invoked
		d2.add(new EventImpl());
		e.step(4);
		// remove the first dependency, callbacks should be invoked
		d1.remove(new EventImpl());
		e.step(7);
		// remove second dependency, no callbacks should be invoked
		d2.remove(new EventImpl());
		e.step(8);
		c.remove(d2);
		c.remove(d1);
		c.stop();
		e.step(9);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createAndStartComponentAddTwoDependenciesWithMultipleServicesWithCallbacks() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step();
			}
			public void remove() {
				e.step();
			}
		});
		// start component
		c.start();
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "remove");
		d1.setRequired(true);
		SimpleServiceDependency d2 = new SimpleServiceDependency();
		d2.setCallbacks("add", "remove");
		d2.setRequired(true);
		c.add(d1);
		c.add(d2);
		// add three instances to first dependency, no callbacks should
		// be triggered
		d1.add(new EventImpl(1));
		d1.add(new EventImpl(2));
		d1.add(new EventImpl(3));
		e.step(1);
		// add two instances to the second dependency, callbacks should
		// be invoked (4x)
		d2.add(new EventImpl(1));
		e.step(6);
		// add another dependency, triggering another callback
		d2.add(new EventImpl(2));
		e.step(8);
		// remove first dependency (all three of them) which makes the
		// ComponentImpl unavailable so it should trigger calling remove for
		// all of them (so 5x)
		d1.remove(new EventImpl(1));
		d1.remove(new EventImpl(2));
		d1.remove(new EventImpl(3));
		e.step(14);
		// remove second dependency, should not trigger further callbacks
		d2.remove(new EventImpl(1));
		d2.remove(new EventImpl(2));
		e.step(15);
		c.remove(d2);
		c.remove(d1);
		c.stop();
		e.step(16);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createComponentAddDependencyMakeAvailableChangeAndUnavailableWithCallbacks() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step(1);
			}
			public void change() {
				e.step(3);
			}
			public void remove() {
				e.step(5);
			}
		});
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "change", "remove");
		d1.setRequired(true);
		// add the dependency to the component
		c.add(d1);
		// start the component
		c.start();
		// make the dependency available, we expect the add callback
		// to be invoked here
		d1.add(new EventImpl());
		e.step(2);
		// change the dependency
		d1.change(new EventImpl());
		e.step(4);
		// remove the dependency, should trigger the remove callback
		d1.remove(new EventImpl());
		e.step(6);
		c.stop();
		c.remove(d1);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createComponentWithOptionalDependency() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step(1);
			}
			public void change() {
				e.step(3);
			}
			public void remove() {
				e.step(5);
			}
		});
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "change", "remove");
		d1.setRequired(false);
		// add the dependency to the component
		c.add(d1);
		// start the component
		c.start();
		Assert.assertEquals("Component started with an optional dependency, should be available", true, c.isAvailable());
		// make the dependency available, we expect the add callback
		// to be invoked here
		d1.add(new EventImpl());
		e.step(2);
		Assert.assertEquals("Component started with an optional dependency, should be available", true, c.isAvailable());
		// change the dependency
		d1.change(new EventImpl());
		e.step(4);
		Assert.assertEquals("Component started with an optional dependency, should be available", true, c.isAvailable());
		// remove the dependency, should trigger the remove callback
		d1.remove(new EventImpl());
		Assert.assertEquals("Component started with an optional dependency, should be available", true, c.isAvailable());
		e.step(6);
		c.stop();
		c.remove(d1);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createComponentWithOptionalAndRequiredDependency() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			public void add() {
				e.step();
			}
			public void remove() {
				e.step();
			}
		});
		SimpleServiceDependency d1 = new SimpleServiceDependency();
		d1.setCallbacks("add", "remove");
		d1.setRequired(false);
		SimpleServiceDependency d2 = new SimpleServiceDependency();
		d2.setCallbacks("add", "remove");
		d2.setRequired(true);
		// add the dependencies to the component
		c.add(d1);
		c.add(d2);
		// start the component
		c.start();
		Assert.assertEquals("Component started with a required and optional dependency, should not be available", false, c.isAvailable());
		// make the optional dependency available
		d1.add(new EventImpl());
		e.step(1);
		Assert.assertEquals("Component should not be available", false, c.isAvailable());
		// make the required dependency available
		d2.add(new EventImpl());
		e.step(4);
		Assert.assertEquals("Component should be available", true, c.isAvailable());
		// remove the optional dependency
		d1.remove(new EventImpl());
		e.step(6);
		Assert.assertEquals("Component should be available", true, c.isAvailable());
		// remove the required dependency
		d1.remove(new EventImpl());
		e.step(8);
		Assert.assertEquals("Component should be available", true, c.isAvailable());
		c.stop();
		c.remove(d1);
		Assert.assertEquals("Component stopped, should be unavailable again", false, c.isAvailable());
	}

	@Test
	public void createComponentAddAvailableDependencyRemoveDependencyCheckStopCalledBeforeUnbind() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			void add() {
				e.step(1);
			}
			void start() {
				e.step(2);
			}
			void stop() {
				e.step(4);
			}
			void remove() {
				e.step(5);
			}
		});
		SimpleServiceDependency d = new SimpleServiceDependency();
		d.setCallbacks("add", "remove");
		d.setRequired(true);
		// add the dependency to the component
		c.add(d);
		// start the component
		c.start();
		// make the dependency available, we expect the add callback
		// to be invoked here, then start is called.
		d.add(new EventImpl());
		e.step(3);
		// remove the dependency, should trigger the stop, then remove callback
		d.remove(new EventImpl());
		e.step(6);
		c.stop();
		c.remove(d);
		Assert.assertEquals("Component stopped, should be unavailable", false, c.isAvailable());
	}

	@Test
	public void createDependenciesWithCallbackInstance() {
		final Ensure e = new Ensure();
		ComponentImpl c = new ComponentImpl();
		c.setImplementation(new Object() {
			void start() {
				e.step(2);
			}

			void stop() {
				e.step(4);
			}
		});

		Object callbackInstance = new Object() {
			void add() {
				e.step(1);
			}

			void remove() {
				e.step(5);
			}
		};

		SimpleServiceDependency d = new SimpleServiceDependency();
		d.setCallbacks(callbackInstance, "add", "remove");
		d.setRequired(true);
		// add the dependency to the component
		c.add(d);
		// start the component
		c.start();
		// make the dependency available, we expect the add callback
		// to be invoked here, then start is called.
		d.add(new EventImpl());
		e.step(3);
		// remove the dependency, should trigger the stop, then remove callback
		d.remove(new EventImpl());
		e.step(6);
		c.stop();
		c.remove(d);
		Assert.assertEquals("Component stopped, should be unavailable", false, c.isAvailable());
	}
}


text:
from oslo.config import cfg

from nova.api.openstack.compute.plugins.v3 import attach_interfaces
from nova.compute import api as compute_api
from nova import context
from nova import exception
from nova.network import api as network_api
from nova.openstack.common import jsonutils
from nova import test
from nova.tests import fake_network_cache_model

import webob
from webob import exc

CONF = cfg.CONF

FAKE_UUID1 = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
FAKE_UUID2 = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'

FAKE_PORT_ID1 = '11111111-1111-1111-1111-111111111111'
FAKE_PORT_ID2 = '22222222-2222-2222-2222-222222222222'
FAKE_PORT_ID3 = '33333333-3333-3333-3333-333333333333'

FAKE_NET_ID1 = '44444444-4444-4444-4444-444444444444'
FAKE_NET_ID2 = '55555555-5555-5555-5555-555555555555'
FAKE_NET_ID3 = '66666666-6666-6666-6666-666666666666'

port_data1 = {
    "id": FAKE_PORT_ID1,
    "network_id": FAKE_NET_ID1,
    "admin_state_up": True,
    "status": "ACTIVE",
    "mac_address": "aa:aa:aa:aa:aa:aa",
    "fixed_ips": ["10.0.1.2"],
    "device_id": FAKE_UUID1,
}

port_data2 = {
    "id": FAKE_PORT_ID2,
    "network_id": FAKE_NET_ID2,
    "admin_state_up": True,
    "status": "ACTIVE",
    "mac_address": "bb:bb:bb:bb:bb:bb",
    "fixed_ips": ["10.0.2.2"],
    "device_id": FAKE_UUID1,
}

port_data3 = {
    "id": FAKE_PORT_ID3,
    "network_id": FAKE_NET_ID3,
    "admin_state_up": True,
    "status": "ACTIVE",
    "mac_address": "bb:bb:bb:bb:bb:bb",
    "fixed_ips": ["10.0.2.2"],
    "device_id": '',
}

fake_networks = [FAKE_NET_ID1, FAKE_NET_ID2]
ports = [port_data1, port_data2, port_data3]

def fake_list_ports(self, *args, **kwargs):
    result = []
    for port in ports:
        if port['device_id'] == kwargs['device_id']:
            result.append(port)
    return {'ports': result}

def fake_show_port(self, context, port_id, **kwargs):
    for port in ports:
        if port['id'] == port_id:
            return {'port': port}

def fake_attach_interface(self, context, instance, network_id, port_id,
                          requested_ip='192.168.1.3'):
    if not network_id:
    # if no network_id is given when add a port to an instance, use the
    # first default network.
        network_id = fake_networks[0]
    if network_id == 'bad_id':
        raise exception.NetworkNotFound(network_id=network_id)
    if not port_id:
        port_id = ports[fake_networks.index(network_id)]['id']
    vif = fake_network_cache_model.new_vif()
    vif['id'] = port_id
    vif['network']['id'] = network_id
    vif['network']['subnets'][0]['ips'][0]['address'] = requested_ip
    return vif

def fake_detach_interface(self, context, instance, port_id):
    for port in ports:
        if port['id'] == port_id:
            return
    raise exception.PortNotFound(port_id=port_id)

def fake_get_instance(self, *args, **kwargs):
    return {}

class InterfaceAttachTests(test.NoDBTestCase):
    def setUp(self):
        super(InterfaceAttachTests, self).setUp()
        self.flags(neutron_auth_strategy=None)
        self.flags(neutron_url='http://anyhost/')
        self.flags(neutron_url_timeout=30)
        self.stubs.Set(network_api.API, 'show_port', fake_show_port)
        self.stubs.Set(network_api.API, 'list_ports', fake_list_ports)
        self.stubs.Set(compute_api.API, 'get', fake_get_instance)
        self.context = context.get_admin_context()
        self.expected_show = {'interface_attachment':
            {'net_id': FAKE_NET_ID1,
             'port_id': FAKE_PORT_ID1,
             'mac_addr': port_data1['mac_address'],
             'port_state': port_data1['status'],
             'fixed_ips': port_data1['fixed_ips'],
            }}

    def test_item_instance_not_found(self):
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank('/v3/servers/fake/os-attach-interfaces/')
        req.method = 'GET'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        def fake_get_instance_exception(self, context, instance_uuid,
                                        **kwargs):
            raise exception.InstanceNotFound(instance_id=instance_uuid)

        self.stubs.Set(compute_api.API, 'get', fake_get_instance_exception)
        self.assertRaises(exc.HTTPNotFound, attachments.index,
                          req, 'fake')

    def test_show(self):
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank('/v3/servers/fake/os-attach-interfaces/show')
        req.method = 'POST'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        result = attachments.show(req, FAKE_UUID1, FAKE_PORT_ID1)
        self.assertEqual(self.expected_show, result)

    def test_show_instance_not_found(self):
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank('/v3/servers/fake/os-attach-interfaces/show')
        req.method = 'POST'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        def fake_get_instance_exception(self, context, instance_uuid,
                                        **kwargs):
            raise exception.InstanceNotFound(instance_id=instance_uuid)

        self.stubs.Set(compute_api.API, 'get', fake_get_instance_exception)
        self.assertRaises(exc.HTTPNotFound, attachments.show,
                          req, 'fake', FAKE_PORT_ID1)

    def test_show_invalid(self):
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank('/v3/servers/fake/os-attach-interfaces/show')
        req.method = 'POST'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPNotFound,
                          attachments.show, req, FAKE_UUID2, FAKE_PORT_ID1)

    def test_delete(self):
        self.stubs.Set(compute_api.API, 'detach_interface',
                       fake_detach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/delete')
        req.method = 'DELETE'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        result = attachments.delete(req, FAKE_UUID1, FAKE_PORT_ID1)
        self.assertEqual('202 Accepted', result.status)

    def test_detach_interface_instance_locked(self):
        def fake_detach_interface_from_locked_server(self, context,
            instance, port_id):
            raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1)

        self.stubs.Set(compute_api.API,
                       'detach_interface',
                       fake_detach_interface_from_locked_server)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/delete')
        req.method = 'POST'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPConflict,
                          attachments.delete,
                          req,
                          FAKE_UUID1,
                          FAKE_PORT_ID1)

    def test_delete_interface_not_found(self):
        self.stubs.Set(compute_api.API, 'detach_interface',
                       fake_detach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/delete')
        req.method = 'DELETE'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPNotFound,
                          attachments.delete,
                          req,
                          FAKE_UUID1,
                          'invaid-port-id')

    def test_delete_instance_not_found(self):
        self.stubs.Set(compute_api.API, 'detach_interface',
                       fake_detach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/delete')
        req.method = 'DELETE'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        def fake_get_instance_exception(self, context, instance_uuid,
                                        **kwargs):
            raise exception.InstanceNotFound(instance_id=instance_uuid)

        self.stubs.Set(compute_api.API, 'get', fake_get_instance_exception)
        self.assertRaises(exc.HTTPNotFound,
                          attachments.delete,
                          req,
                          'fake',
                          'invaid-port-id')

    def test_attach_interface_instance_locked(self):
        def fake_attach_interface_to_locked_server(self, context,
            instance, network_id, port_id, requested_ip):
            raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1)

        self.stubs.Set(compute_api.API,
                       'attach_interface',
                       fake_attach_interface_to_locked_server)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/attach')
        req.method = 'POST'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        self.assertRaises(exc.HTTPConflict,
                          attachments.create, req, FAKE_UUID1,
                          jsonutils.loads(req.body))

    def test_attach_interface_without_network_id(self):
        self.stubs.Set(compute_api.API, 'attach_interface',
                       fake_attach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/attach')
        req.method = 'POST'
        req.body = jsonutils.dumps({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        result = attachments.create(req, FAKE_UUID1,
                                    jsonutils.loads(req.body))
        self.assertEqual(result['interface_attachment']['net_id'],
                         FAKE_NET_ID1)

    def test_attach_interface_with_network_id(self):
        self.stubs.Set(compute_api.API, 'attach_interface',
                       fake_attach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/attach')
        req.method = 'POST'
        req.body = jsonutils.dumps({'interface_attachment':
                                   {'net_id': FAKE_NET_ID2}})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        result = attachments.create(req,
                                    FAKE_UUID1, jsonutils.loads(req.body))
        self.assertEqual(result['interface_attachment']['net_id'],
                         FAKE_NET_ID2)

    def test_attach_interface_with_port_and_network_id(self):
        self.stubs.Set(compute_api.API, 'attach_interface',
                       fake_attach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/attach')
        req.method = 'POST'
        req.body = jsonutils.dumps({'interface_attachment':
                                   {'port_id': FAKE_PORT_ID1,
                                    'net_id': FAKE_NET_ID2}})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        self.assertRaises(exc.HTTPBadRequest,
                          attachments.create, req, FAKE_UUID1,
                          jsonutils.loads(req.body))

    def test_attach_interface_instance_not_found(self):
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/attach')
        req.method = 'POST'
        req.body = jsonutils.dumps({'interface_attachment':
                                   {'net_id': FAKE_NET_ID2}})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        def fake_get_instance_exception(self, context, instance_uuid,
                                        **kwargs):
            raise exception.InstanceNotFound(instance_id=instance_uuid)

        self.stubs.Set(compute_api.API, 'get', fake_get_instance_exception)
        self.assertRaises(exc.HTTPNotFound,
                          attachments.create, req, 'fake',
                          jsonutils.loads(req.body))

    def test_attach_interface_with_invalid_data(self):
        self.stubs.Set(compute_api.API, 'attach_interface',
                       fake_attach_interface)
        attachments = attach_interfaces.InterfaceAttachmentController()
        req = webob.Request.blank(
            '/v3/servers/fake/os-attach-interfaces/attach')
        req.method = 'POST'
        req.body = jsonutils.dumps({'interface_attachment':
                                    {'net_id': 'bad_id'}})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        self.assertRaises(exc.HTTPBadRequest,
                          attachments.create, req, FAKE_UUID1,
                          jsonutils.loads(req.body))

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.packageDependencies.ui;

import com.intellij.analysis.AnalysisScopeBundle;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.util.Consumer;
import com.intellij.util.concurrency.EdtExecutorService;

import javax.swing.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class PanelProgressIndicator extends ProgressIndicatorBase {
  private final MyProgressPanel myProgressPanel;
  private boolean myPaintInQueue;
  private final Consumer<JComponent> myComponentUpdater;
  private Future<?> myAlarm = CompletableFuture.completedFuture(null);

  public PanelProgressIndicator(Consumer<JComponent> componentUpdater) {
    myProgressPanel = new MyProgressPanel();
    myProgressPanel.myFractionProgress.setMaximum(100);
    myComponentUpdater = componentUpdater;
  }

  @Override
  public void start() {
    super.start();
    myComponentUpdater.consume(myProgressPanel.myPanel);
  }

  @Override
  public void stop() {
    super.stop();
    if (isCanceled()) {
      JLabel label = new JLabel(AnalysisScopeBundle.message("usage.view.canceled"));
      label.setHorizontalAlignment(SwingConstants.CENTER);
      myComponentUpdater.consume(label);
    }
  }

  @Override
  public void setText(String text) {
    if (!text.equals(getText())) {
      super.setText(text);
    }
  }

  @Override
  public void setFraction(double fraction) {
    if (fraction != getFraction()) {
      super.setFraction(fraction);
    }
  }

  @Override
  public void setIndeterminate(final boolean indeterminate) {
    if (isIndeterminate() == indeterminate) return;
    super.setIndeterminate(indeterminate);
  }

  public void update(final String scanningPackagesMessage, final boolean indeterminate, final double ffraction) {
    if (myPaintInQueue) return;
    checkCanceled();
    myPaintInQueue = true;
    myAlarm.cancel(false);
    myAlarm = EdtExecutorService.getScheduledExecutorInstance().schedule(() -> {
      myPaintInQueue = false;
      myProgressPanel.myTextLabel.setText(scanningPackagesMessage);
      int fraction = (int)(ffraction * 99 + 0.5);
      myProgressPanel.myFractionLabel.setText(fraction + "%");
      if (fraction != -1) {
        myProgressPanel.myFractionProgress.setValue(fraction);
      }
      myProgressPanel.myFractionProgress.setIndeterminate(indeterminate);
    }, 10, TimeUnit.MILLISECONDS);
  }

  public void setBordersVisible(final boolean visible) {
    myProgressPanel.myLeftPanel.setVisible(visible);
    myProgressPanel.myRightPanel.setVisible(visible);
  }

  private static class MyProgressPanel {
    public JLabel myFractionLabel;
    public JLabel myTextLabel;
    public JPanel myPanel;
    private JProgressBar myFractionProgress;
    private JPanel myLeftPanel;
    private JPanel myRightPanel;
  }
}


text:
package com.vmware.vim25;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

@SuppressWarnings("all")
public class ProfileExecuteResult extends DynamicData {
    public String status;
    public HostConfigSpec configSpec;
    public String[] inapplicablePath;
    public ProfileDeferredPolicyOptionParameter[] requireInput;
    public ProfileExecuteError[] error;

    public String getStatus() {
        return this.status;
    }

    public HostConfigSpec getConfigSpec() {
        return this.configSpec;
    }

    public String[] getInapplicablePath() {
        return this.inapplicablePath;
    }

    public ProfileDeferredPolicyOptionParameter[] getRequireInput() {
        return this.requireInput;
    }

    public ProfileExecuteError[] getError() {
        return this.error;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setConfigSpec(HostConfigSpec configSpec) {
        this.configSpec = configSpec;
    }

    public void setInapplicablePath(String[] inapplicablePath) {
        this.inapplicablePath = inapplicablePath;
    }

    public void setRequireInput(ProfileDeferredPolicyOptionParameter[] requireInput) {
        this.requireInput = requireInput;
    }

    public void setError(ProfileExecuteError[] error) {
        this.error = error;
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Closure Performance Tests - UTF8 encoding and decoding</title>
  <link rel="stylesheet" type="text/css"
        href="../testing/performancetable.css"/>

Closure Performance Tests - UTF8 encoding and decoding

    User-agent:


text:
package at.ac.tuwien.infosys.events;

import io.hummer.util.Util;
import io.hummer.util.ws.AbstractNode;

import org.apache.log4j.Logger;

import at.ac.tuwien.infosys.events.ws.WSEvent;
import at.ac.tuwien.infosys.events.ws.WebServiceClientUtil;

public class EventingNode extends AbstractNode {

	private static final Logger LOGGER = Util.getLogger(EventingNode.class);

	private EventTypeRepository eventTypeRepository;

	public EventTypeRepository getEventTypeRepository() {
		return eventTypeRepository;
	}
	public void setEventTypeRepository(EventTypeRepository eventTypeRepository) {
		this.eventTypeRepository = eventTypeRepository;
	}

	public void sendEvent(Event event) throws Exception {
		LOGGER.debug("Sending event '" + event.getIdentifier() + "'.");
		final WSEvent wsEvent = WSEvent.toWSEvent(eventTypeRepository, event);
		WebServiceClientUtil.execute(getEPR(), wsEvent, null);
	}

}


text:
boost::uint64_t jobs = 1000;

boost::context::execution_context * mctx;

static void foo( void *) {
    while ( true) {
        ( * mctx)();
    }
}

duration_type measure_time() {
    boost::context::execution_context ctx_ =
        boost::context::execution_context::current();
    mctx = & ctx_;
    boost::context::execution_context ctx( foo);
    // cache warum-up
    ctx();
    time_point_type start( clock_type::now() );
    for ( std::size_t i = 0; i < jobs; ++i) {
        ctx();
    }
    duration_type total = clock_type::now() - start;
    total -= overhead_clock(); // overhead of measurement
    total /= jobs;  // loops
    total /= 2;  // 2x jump_fcontext
    return total;
}

#ifdef BOOST_CONTEXT_CYCLE
cycle_type measure_cycles() {
    boost::context::execution_context ctx_ =
        boost::context::execution_context::current();
    mctx = & ctx_;
    boost::context::execution_context ctx( foo);
    // cache warum-up
    ctx();
    cycle_type start( cycles() );
    for ( std::size_t i = 0; i < jobs; ++i) {
        ctx();
    }
    cycle_type total = cycles() - start;
    total -= overhead_cycle(); // overhead of measurement
    total /= jobs;  // loops
    total /= 2;  // 2x jump_fcontext

    return total;
}
#endif

int main( int argc, char * argv[]) {
    try {
        bind_to_processor( 0);
        boost::program_options::options_description desc("allowed options");
        desc.add_options()
            ("help", "help message")
            ("jobs,j", boost::program_options::value< boost::uint64_t >( & jobs), "jobs to run");
        boost::program_options::variables_map vm;
        boost::program_options::store(
                boost::program_options::parse_command_line(
                    argc,
                    argv,
                    desc),
                vm);
        boost::program_options::notify( vm);
        if ( vm.count("help") ) {
            std::cout << desc << std::endl;
            return EXIT_SUCCESS;
        }
        boost::uint64_t res = measure_time().count();
        std::cout << "execution_context: average of " << res << " nano seconds" << std::endl;
#ifdef BOOST_CONTEXT_CYCLE
        res = measure_cycles();
        std::cout << "execution_context: average of " << res << " cpu cycles" << std::endl;
#endif
        return EXIT_SUCCESS;
    } catch ( std::exception const& e) {
        std::cerr << "exception: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "unhandled exception" << std::endl;
    }
    return EXIT_FAILURE;
}


text:
package com.facebook.buck.features.filegroup;

import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.filesystems.RelPath;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.HasOutputName;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.CustomFieldBehavior;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.features.filebundler.CopyingFileBundler;
import com.facebook.buck.features.filebundler.FileBundler;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.modern.BuildCellRelativePathFactory;
import com.facebook.buck.rules.modern.Buildable;
import com.facebook.buck.rules.modern.ModernBuildRule;
import com.facebook.buck.rules.modern.OutputPath;
import com.facebook.buck.rules.modern.OutputPathResolver;
import com.facebook.buck.rules.modern.RemoteExecutionEnabled;
import com.facebook.buck.step.Step;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;

/** A build rule that copies inputs provided in {@code srcs} to an output directory. */
public class Filegroup extends ModernBuildRule<Filegroup> implements HasOutputName, Buildable {

  @AddToRuleKey private final String name;
  @AddToRuleKey private final ImmutableSortedSet<SourcePath> srcs;
  @AddToRuleKey private final OutputPath outputPath;

  @CustomFieldBehavior(RemoteExecutionEnabled.class)
  private final boolean enabled = false;

  public Filegroup(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      SourcePathRuleFinder ruleFinder,
      String name,
      ImmutableSortedSet<SourcePath> srcs) {
    super(buildTarget, projectFilesystem, ruleFinder, Filegroup.class);
    this.name = name;
    this.srcs = srcs;

    outputPath = new OutputPath(name);
  }

  @Override
  public ImmutableList<Step> getBuildSteps(
      BuildContext buildContext,
      ProjectFilesystem filesystem,
      OutputPathResolver outputPathResolver,
      BuildCellRelativePathFactory buildCellPathFactory) {
    RelPath outputPath = outputPathResolver.resolvePath(this.outputPath);

    FileBundler bundler = new CopyingFileBundler(filesystem, getBuildTarget());

    ImmutableList.Builder<Step> steps = ImmutableList.builder();

    bundler.copy(
        filesystem,
        buildCellPathFactory,
        steps,
        outputPath.getPath(),
        srcs,
        buildContext.getSourcePathResolver());

    return steps.build();
  }

  @Override
  public SourcePath getSourcePathToOutput() {
    return getSourcePath(outputPath);
  }

  @Override
  public String getOutputName(OutputLabel outputLabel) {
    return name;
  }
}


text:
package tests_test

import (
	"context"
	"fmt"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	cdiv1alpha1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1alpha1"
	cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
	"kubevirt.io/containerized-data-importer/tests/framework"
	"kubevirt.io/containerized-data-importer/tests/utils"
)

var _ = Describe("Alpha API tests", func() {
	f := framework.NewFramework("alpha-api-test", framework.Config{})

	Context("with v1alpha1 api", func() {

		It("[test_id:4944]should get CDI config", func() {
			config, err := f.CdiClient.CdiV1alpha1().CDIConfigs().Get(context.TODO(), "config", metav1.GetOptions{})
			Expect(err).ToNot(HaveOccurred())
			Expect(config).ToNot(BeNil())
		})

		It("[test_id:4945]should", func() {
			By("create a upload DataVolume")
			out, err := f.RunKubectlCommand("create", "-f", "manifests/dvAlphaUpload.yaml", "-n", f.Namespace.Name)
			fmt.Fprintf(GinkgoWriter, "INFO: Output from kubectl: %s\n", out)
			Expect(err).ToNot(HaveOccurred())

			By("waiting for DataVolume to be ready")
			err = utils.WaitForDataVolumePhase(f, f.Namespace.Name, cdiv1.UploadReady, "upload")
			Expect(err).ToNot(HaveOccurred())

			By("create a upload token")
			out, err = f.RunKubectlCommand("create", "-f", "manifests/tokenAlpha.yaml", "-n", f.Namespace.Name)
			fmt.Fprintf(GinkgoWriter, "INFO: Output from kubectl: %s\n", out)
			Expect(err).ToNot(HaveOccurred())
		})

		It("[test_id:4946]should clone across namespace with alpha", func() {
			By("create source PVC")
			pvcDef := utils.NewPVCDefinition("source-pvc", "1G", nil, nil)
			source, err := f.K8sClient.CoreV1().PersistentVolumeClaims(f.Namespace.Name).Create(context.TODO(), pvcDef, metav1.CreateOptions{})
			Expect(err).ToNot(HaveOccurred())
			f.ForceBindIfWaitForFirstConsumer(source)

			By("create target namespace")
			targetNs, err := f.CreateNamespace(f.NsPrefix, map[string]string{
				framework.NsPrefixLabel: f.NsPrefix,
			})
			Expect(err).ToNot(HaveOccurred())
			f.AddNamespaceToDelete(targetNs)

			targetDef := createCloneDataVolume("target-dv", source)
			target, err := f.CdiClient.CdiV1alpha1().DataVolumes(targetNs.Name).Create(context.TODO(), targetDef, metav1.CreateOptions{})
			Expect(err).ToNot(HaveOccurred())

			By("waiting for DataVolume to be complete")
			err = utils.WaitForDataVolumePhase(f, target.Namespace, cdiv1.Succeeded, target.Name)
			Expect(err).ToNot(HaveOccurred())
		})

		It("[test_id:4947]should not", func() {
			By("create a upload DataVolume")
			out, err := f.RunKubectlCommand("create", "-f", "manifests/dvAlphaMissingAccessModes.yaml", "-n", f.Namespace.Name)
			fmt.Fprintf(GinkgoWriter, "INFO: Output from kubectl: %s\n", out)
			Expect(out).Should(ContainSubstring("at least 1 access mode is required"))
			Expect(err).To(HaveOccurred())
		})

		Context("with deletion blocked", func() {
			var originalStrategy *cdiv1.CDIUninstallStrategy

			BeforeEach(func() {
				strategy := cdiv1.CDIUninstallStrategyBlockUninstallIfWorkloadsExist
				originalStrategy = updateUninstallStrategy(f.CdiClient, &strategy)
			})

			AfterEach(func() {
				updateUninstallStrategy(f.CdiClient, originalStrategy)
			})

			It("[test_id:4948]should block cdi delete", func() {
				By("create a upload DataVolume")
				out, err := f.RunKubectlCommand("create", "-f", "manifests/dvAlphaUpload.yaml", "-n", f.Namespace.Name)
				fmt.Fprintf(GinkgoWriter, "INFO: Output from kubectl: %s\n", out)
				Expect(err).ToNot(HaveOccurred())

				By("waiting for DataVolume to be ready")
				err = utils.WaitForDataVolumePhase(f, f.Namespace.Name, cdiv1.UploadReady, "upload")

				// tests listing alpha api
				alphaCDIs, err := f.CdiClient.CdiV1alpha1().CDIs().List(context.TODO(), metav1.ListOptions{})
				Expect(err).ToNot(HaveOccurred())
				Expect(alphaCDIs.Items).Should(HaveLen(1))

				// will invoke webhook for alpha
				err = f.CdiClient.CdiV1alpha1().CDIs().Delete(context.TODO(), alphaCDIs.Items[0].Name, metav1.DeleteOptions{DryRun: []string{"All"}})
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("there are still DataVolumes present"))
			})

		})
	})
})

func createCloneDataVolume(name string, source *corev1.PersistentVolumeClaim) *cdiv1alpha1.DataVolume {
	dv := &cdiv1alpha1.DataVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Spec: cdiv1alpha1.DataVolumeSpec{
			Source: cdiv1alpha1.DataVolumeSource{
				PVC: &cdiv1alpha1.DataVolumeSourcePVC{
					Namespace: source.Namespace,
					Name:      source.Name,
				},
			},
			PVC: &corev1.PersistentVolumeClaimSpec{
				AccessModes:      source.Spec.AccessModes,
				Resources:        source.Spec.Resources,
				VolumeMode:       source.Spec.VolumeMode,
				StorageClassName: source.Spec.StorageClassName,
			},
		},
	}

	return dv
}


text:
package org.eclipse.om2m.commons.entities;

import java.math.BigInteger;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

import org.eclipse.om2m.commons.constants.ShortName;

/**
 * Container announced JPA entity
 *
 */
@Entity(name = ShortName.CNT_ANNC)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class ContainerAnncEntity extends ResourceEntity {

	// TODO acp ids ???

	@Column(name = ShortName.EXPIRATION_TIME)
	protected String expirationTime;
	@Column(name = ShortName.LINK)
	protected String link;

	@Column(name= ShortName.STATETAG)
	protected BigInteger stateTag;
	@Column(name= ShortName.MAX_NR_OF_INSTANCES)
	protected BigInteger maxNrOfInstances;
	@Column(name= ShortName.MAX_BYTE_SIZE)
	protected BigInteger maxByteSize;
	@Column(name= ShortName.MAX_INSTANCE_AGE)
	protected BigInteger maxInstanceAge;
	@Column(name= ShortName.CURRENT_NUMBER_OF_INSTANCES)
	protected BigInteger currentNrOfInstances;
	@Column(name= ShortName.CURRENT_BYTE_SIZE)
	protected BigInteger currentByteSize;
	@Column(name= ShortName.LOCATION_ID)
	protected String locationID;
	@Column(name= ShortName.ONTOLOGY_REF)
	protected String ontologyRef;

	// TODO add link cnt
	// TODO add link cntA
	// TODO add link cin
	// TODO add link cinA
	// TODO add link sub

}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/talent/v4/common.proto

namespace Google\Cloud\Talent\V4;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Metadata used for long running operations returned by CTS batch APIs.
 * It's used to replace [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata].
 *
 * Generated from protobuf message google.cloud.talent.v4.BatchOperationMetadata
 */
class BatchOperationMetadata extends \Google\Protobuf\Internal\Message
{
    /**
     * The state of a long running operation.
     *
     * Generated from protobuf field .google.cloud.talent.v4.BatchOperationMetadata.State state = 1;
     */
    private $state = 0;
    /**
     * More detailed information about operation state.
     *
     * Generated from protobuf field string state_description = 2;
     */
    private $state_description = '';
    /**
     * Count of successful item(s) inside an operation.
     *
     * Generated from protobuf field int32 success_count = 3;
     */
    private $success_count = 0;
    /**
     * Count of failed item(s) inside an operation.
     *
     * Generated from protobuf field int32 failure_count = 4;
     */
    private $failure_count = 0;
    /**
     * Count of total item(s) inside an operation.
     *
     * Generated from protobuf field int32 total_count = 5;
     */
    private $total_count = 0;
    /**
     * The time when the batch operation is created.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 6;
     */
    private $create_time = null;
    /**
     * The time when the batch operation status is updated. The metadata and the
     * [update_time][google.cloud.talent.v4.BatchOperationMetadata.update_time] is refreshed every minute otherwise cached data is
     * returned.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 7;
     */
    private $update_time = null;
    /**
     * The time when the batch operation is finished and
     * [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to `true`.
     *
     * Generated from protobuf field .google.protobuf.Timestamp end_time = 8;
     */
    private $end_time = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type int $state
     *           The state of a long running operation.
     *     @type string $state_description
     *           More detailed information about operation state.
     *     @type int $success_count
     *           Count of successful item(s) inside an operation.
     *     @type int $failure_count
     *           Count of failed item(s) inside an operation.
     *     @type int $total_count
     *           Count of total item(s) inside an operation.
     *     @type \Google\Protobuf\Timestamp $create_time
     *           The time when the batch operation is created.
     *     @type \Google\Protobuf\Timestamp $update_time
     *           The time when the batch operation status is updated. The metadata and the
     *           [update_time][google.cloud.talent.v4.BatchOperationMetadata.update_time] is refreshed every minute otherwise cached data is
     *           returned.
     *     @type \Google\Protobuf\Timestamp $end_time
     *           The time when the batch operation is finished and
     *           [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to `true`.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Talent\V4\Common::initOnce();
        parent::__construct($data);
    }

    /**
     * The state of a long running operation.
     *
     * Generated from protobuf field .google.cloud.talent.v4.BatchOperationMetadata.State state = 1;
     * @return int
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * The state of a long running operation.
     *
     * Generated from protobuf field .google.cloud.talent.v4.BatchOperationMetadata.State state = 1;
     * @param int $var
     * @return $this
     */
    public function setState($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Talent\V4\BatchOperationMetadata\State::class);
        $this->state = $var;

        return $this;
    }

    /**
     * More detailed information about operation state.
     *
     * Generated from protobuf field string state_description = 2;
     * @return string
     */
    public function getStateDescription()
    {
        return $this->state_description;
    }

    /**
     * More detailed information about operation state.
     *
     * Generated from protobuf field string state_description = 2;
     * @param string $var
     * @return $this
     */
    public function setStateDescription($var)
    {
        GPBUtil::checkString($var, True);
        $this->state_description = $var;

        return $this;
    }

    /**
     * Count of successful item(s) inside an operation.
     *
     * Generated from protobuf field int32 success_count = 3;
     * @return int
     */
    public function getSuccessCount()
    {
        return $this->success_count;
    }

    /**
     * Count of successful item(s) inside an operation.
     *
     * Generated from protobuf field int32 success_count = 3;
     * @param int $var
     * @return $this
     */
    public function setSuccessCount($var)
    {
        GPBUtil::checkInt32($var);
        $this->success_count = $var;

        return $this;
    }

    /**
     * Count of failed item(s) inside an operation.
     *
     * Generated from protobuf field int32 failure_count = 4;
     * @return int
     */
    public function getFailureCount()
    {
        return $this->failure_count;
    }

    /**
     * Count of failed item(s) inside an operation.
     *
     * Generated from protobuf field int32 failure_count = 4;
     * @param int $var
     * @return $this
     */
    public function setFailureCount($var)
    {
        GPBUtil::checkInt32($var);
        $this->failure_count = $var;

        return $this;
    }

    /**
     * Count of total item(s) inside an operation.
     *
     * Generated from protobuf field int32 total_count = 5;
     * @return int
     */
    public function getTotalCount()
    {
        return $this->total_count;
    }

    /**
     * Count of total item(s) inside an operation.
     *
     * Generated from protobuf field int32 total_count = 5;
     * @param int $var
     * @return $this
     */
    public function setTotalCount($var)
    {
        GPBUtil::checkInt32($var);
        $this->total_count = $var;

        return $this;
    }

    /**
     * The time when the batch operation is created.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 6;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    public function hasCreateTime()
    {
        return isset($this->create_time);
    }

    public function clearCreateTime()
    {
        unset($this->create_time);
    }

    /**
     * The time when the batch operation is created.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 6;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setCreateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->create_time = $var;

        return $this;
    }

    /**
     * The time when the batch operation status is updated. The metadata and the
     * [update_time][google.cloud.talent.v4.BatchOperationMetadata.update_time] is refreshed every minute otherwise cached data is
     * returned.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 7;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getUpdateTime()
    {
        return $this->update_time;
    }

    public function hasUpdateTime()
    {
        return isset($this->update_time);
    }

    public function clearUpdateTime()
    {
        unset($this->update_time);
    }

    /**
     * The time when the batch operation status is updated. The metadata and the
     * [update_time][google.cloud.talent.v4.BatchOperationMetadata.update_time] is refreshed every minute otherwise cached data is
     * returned.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 7;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setUpdateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->update_time = $var;

        return $this;
    }

    /**
     * The time when the batch operation is finished and
     * [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to `true`.
     *
     * Generated from protobuf field .google.protobuf.Timestamp end_time = 8;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getEndTime()
    {
        return $this->end_time;
    }

    public function hasEndTime()
    {
        return isset($this->end_time);
    }

    public function clearEndTime()
    {
        unset($this->end_time);
    }

    /**
     * The time when the batch operation is finished and
     * [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to `true`.
     *
     * Generated from protobuf field .google.protobuf.Timestamp end_time = 8;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setEndTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->end_time = $var;

        return $this;
    }

}


text:
% Copyright 2010 Raytheon BBN Technologies
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% File: optimize_mixer_ampPhase.m
%
% Description: Searches for optimal amplitude and phase correction on an
% I/Q mixer.

function [ampFactor, phaseSkew] = optimize_mixer_ampPhase_bySearch(obj)
    % unpack constants from cfg file
    ExpParams = obj.expParams;
    awg_amp = obj.awgAmp;

    fssb = ExpParams.SSBFreq; % SSB modulation frequency (usually 10 MHz)

    simul_amp = 1.0;
    simul_phase = 0.0;

    verbose = ExpParams.verbose;
    simulate = simulate = ExpParams.SoftwareDevelopmentMode;

    % initialize instruments
    if ~simulate
        % grab instrument objects
        sa = obj.sa;
        awg = obj.awg;

        sa.center_frequency = obj.specgen.frequency * 1e9 - fssb;

        awg.run();
        awg.waitForAWGtoStartRunning();
    else
        awg_amp = 1.0;
    end

    % initial guess has no amplitude or phase correction
    x0 = [awg_amp, 0];
    % options for Levenberg-Marquardt
    if verbose
        displayMode = 'iter';
    else
        displayMode = 'none';
    end

    fprintf('\nStarting search for optimal amp/phase\n');

    % Leven-Marquardt search
    options = optimset(...
        'TolX', 2e-3, ... %2e-3
        'TolFun', 2e-4, ...
        'MaxFunEvals', 1000, ...
        'OutputFcn', @obj.LMStoppingCondition, ...
        'DiffMinChange', 1e-3, ... %1e-4 worked well in simulation
        'Jacobian', 'off', ... % use finite-differences to compute Jacobian
        'Algorithm', {'levenberg-marquardt',1e-2}, ... % starting value for lambda = 1e-1
        'ScaleProblem', 'none', ... % 'Jacobian' or 'none'
        'Display', displayMode);
    [x0, optPower] = lsqnonlin(@SSBObjectiveFcn,x0,[],[],options);

    % commented out section for fminunc search
%     options = optimset(...
%         'TolX', 1e-3, ... %2e-3
%         'TolFun', 1e-4, ...
%         'MaxFunEvals', 100, ...
%         'DiffMinChange', 5e-3, ... %1e-4 worked well in simulation
%         'LargeScale', 'off',...
%         'Display', displayMode);
%     [x0, optPower] = fminunc(@SSBObjectiveFcn,x0,options);
%     optPower = optPower^2;

    % Nelder-Meade Simplex search
%     options = optimset(...
%         'TolX', 1e-3, ... %2e-3
%         'TolFun', 1e-4, ...
%         'MaxFunEvals', 100, ...
%         'Display', displayMode);
%     [x0, optPower] = fminsearch(@SSBObjectiveFcn,x0,options);
%     optPower = optPower^2;

    ampFactor = x0(1)/awg_amp;
    skew = x0(2);
    fprintf('Optimal amp/phase parameters:\n');
    fprintf('a: %.3g, skew: %.3f (%.3f degrees)\n', [ampFactor, skew, skew*180/pi]);
    fprintf('SSB power: %.2f\n', 10*log10(optPower));

    phaseSkew = skew*180/pi;

    % restore instruments to a normal state
    if ~simulate
        obj.setInstrument(x0(1), skew);
    end

    % local functions
    function cost = SSBObjectiveFcn(x)
        if verbose, fprintf('amp: %.3f, phase: %.3f\n', x(1), x(2)); end
        if ~simulate
            obj.setInstrument(x(1), x(2));
            pause(0.02);
        else
            simul_amp = x(1);
            simul_phase = x(2);
        end
        power = readPower();
        cost = 10^(power/20);
        if verbose, fprintf('Power: %.3f, Cost: %.3f\n', power, cost); end
    end

    function power = readPower()
        if ~simulate
            sa.sweep();
            power = sa.peakAmplitude();
        else
            best_amp = 1.05;
            best_phase = 0.1;
            a = simul_amp/best_amp;
            phi = simul_phase - best_phase;
            errorVec = [a - cos(phi); sin(phi)];
            power = 20*log10(norm(errorVec));
        end
    end
end


text:
  <mat-table [dataSource]="dataSource">

    <ng-container cdkColumnDef="source">
      <mat-header-cell *cdkHeaderCellDef [ngClass]="'nameWidth'">Name</mat-header-cell>
      <mat-cell *cdkCellDef="let row" [ngClass]="'nameWidth'">
        <mat-form-field>
          <input matInput #text
                 [ngModel]="row.key"
                 (change)="doChange(row,$event.target.value)">
        </mat-form-field>
      </mat-cell>
    </ng-container>

    <ng-container cdkColumnDef="mapped">
      <mat-header-cell *cdkHeaderCellDef [ngClass]="'valueWidth'">Value</mat-header-cell>
      <mat-cell *cdkCellDef="let row" [ngClass]="'valueWidth'">
        <mat-form-field>
          <input matInput
                 [ngModel]="attributes[row.key]"
                 (ngModelChange)="attributes[row.key] = $event.split(',')">
        </mat-form-field>
      </mat-cell>
    </ng-container>

    <ng-container cdkColumnDef="delete">
      <mat-header-cell *cdkHeaderCellDef [ngClass]="'actionWidth'"></mat-header-cell>
      <mat-cell *cdkCellDef="let row" [ngClass]="'actionWidth'">
        <button mat-icon-button (click)="delete(row)"><mat-icon style="font-size: medium">delete</mat-icon></button>
      </mat-cell>
    </ng-container>

    <mat-header-row *cdkHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *cdkRowDef="let row; columns: displayedColumns;"></mat-row>

  </mat-table>

    <button mat-mini-fab (click)="addRow()" style="float:right;">+</button>


text:
<html>
<head>
    <title>Dual-context-foo: frontend</title>
    <script data-main="js/main" src="js/vendor/require.js"></script>
</head>
<body>

</body>
</html>


text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Cloud.Kms.V1;
using System;
using System.Xml.Linq;
using Xunit;

namespace Google.Cloud.AspNetCore.DataProtection.Kms.Tests
{
    public class KmsXmlEncryptorDecryptorTest
    {
        [Theory]
        [InlineData(100)]
        [InlineData(1000)]
        [InlineData(1_000_000)]
        public void Roundtrip(int dataSize)
        {
            var key = new CryptoKeyName("projectId", "locationId", "keyRingId", Guid.NewGuid().ToString());
            var client = new FakeKmsClient();
            var encryptor = new KmsXmlEncryptor(client, key);
            var decryptor = new KmsXmlDecryptor(client);
            var plain = new XElement("Original", new string ('x', dataSize));
            var encrypted = encryptor.Encrypt(plain);
            Assert.DoesNotContain("Plaintext value", encrypted.EncryptedElement.ToString());
            var decrypted = decryptor.Decrypt(encrypted.EncryptedElement);
            Assert.Equal(plain.ToString(), decrypted.ToString());
        }

        [Fact]
        public void EncryptFormat()
        {
            var key = new CryptoKeyName("projectId", "locationId", "keyRingId", Guid.NewGuid().ToString());
            var encryptor = new KmsXmlEncryptor(new FakeKmsClient(), key);
            var plain = new XElement("Original", "Plaintext value");
            var encrypted = encryptor.Encrypt(plain);

            Assert.Equal(typeof(KmsXmlDecryptor), encrypted.DecryptorType);
            var element = encrypted.EncryptedElement;
            Assert.Equal(KmsXmlConstants.EncryptedElement, element.Name);
            Assert.Equal(key.ToString(), element.Attribute(KmsXmlConstants.KmsKeyNameAttribute).Value);
            // Validate that the key data contains valid base64 data
            Convert.FromBase64String(element.Attribute(KmsXmlConstants.LocalKeyDataAttribute).Value);
            // Validate that the payload contains valid base64 data.
            Convert.FromBase64String(element.Element(KmsXmlConstants.PayloadElement).Value);
        }
    }
}


text:
<?php

namespace Dml\TodoBundle\Paginador;

use Dml\TodoBundle\Pager\Pager;

/**
 * Detalle de la clase Paginador
 * La presente nos ayuda a iniciar el paginador ya que usa métodos definidos
 * de una clase padre llamada Pager.php
 *
 * @author Oswaldo Rojas, Sáb 15 Mar 2014 10:17:11
 */
class Paginador extends Pager {

    /**
     * Declaracion de variables protegidas para la utilizacion del paginador
     * y de las clases que se extienden de la misma
     */
    protected
        $select            = null,
        $tableMethodName   = null,
        $tableMethodCalled = false;

    /**
     * Iniciando el paginador con las opciones indicadas por el usuario
     */
    public function init() {
        $countQuery = $this->getCountQuery(); // clono la consulta previamente
        $count      = count($countQuery->getQuery()->getArrayResult());

        $this->setNbResults($count);

        $query = $this->getSelect();

        if (0 == $this->getPage() ||
            0 == $this->getMaxPerPage() ||
            0 == $this->getNbResults()):
            $this->setLastPage(0);
        else:
            $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
            $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
            $query->setFirstResult($offset)
                  ->setMaxResults($this->getMaxPerPage());
        endif;
    }

    /**
     * Retorna la consulta o query para el paginador
     *
     * @return QueryBuilder
     */
    public function getSelect() { return $this->select; }

    /**
     * Guarda el objeto de la consulta o query para el paginador
     *
     * @param QueryBuilder $select
     */
    public function setSelect($select) { $this->select = $select; }

    /**
     * Retorna una consulta o query builder clonada para despues ser ejecutada
     * y devolver el total de resultados
     *
     * @return QueryBuilder
     */
    public function getCountQuery() { return clone $this->getSelect(); }

    /**
     * Obtiene todos los resultados para la instancia de la página
     *
     * @param mixed $hydrationMode Un modo de identificador de hidratación
     * @return Doctrine_Collection|array
     */
    public function getResults($hydrationMode = \Doctrine\ORM\Query::HYDRATE_ARRAY) {
        return $this->getSelect()->getQuery()->getResult($hydrationMode);
    }

    /**
     * Obtiene el query nativo usado para obtener los datos consultado en el motor
     * de basede datos.
     *
     * @return string
     */
    public function getSqlQuery() {
        return $this->getCountQuery()->getQuery()->getSQL();
    }

    /**
     * Obtiene la suma de un campo ecibido como parametro para esta consulta personalizada
     * y es un adicional que se puede trabajar desde este paginador.
     *
     * @param string $field Campo que hace referencia a la BDD.
     * @return Doctrine_Collection|array
     */
    public function getSumQuery($field) {
        $qb = $this->getCountQuery();
        $alias = current($qb->getDQLPart('from'))->getAlias();
        $qb = $qb->addSelect("SUM({$alias}.{$field}) as total".ucfirst($field)."")
                 ->groupBy("{$alias}.moTipo")
                 ->setFirstResult(0); // seteo el valor del offset ya que la suma no aplica con el valor > 0
//        return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); // Debido a que la consulta devuelve un fila y varios campos.
        return $qb->getQuery()->getSQL(); // Debido a que la consulta devuelve un fila y varios campos.

//        $qb = $this->getCountQuery();
//        $alias = current($qb->getDQLPart('from'))->getAlias();
//        $qb = $qb->addSelect("SUM({$alias}.{$field}) as total".ucfirst($field)."")
////                 ->andWhere($alias.'.'.$where)
////                 ->setParameter($paramTxt, $paramVal)
//                 ->setFirstResult(0); // seteo el valor del offset ya que la suma no aplica con el valor > 0
//        return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); // Debido a que la consulta devuelve un fila y varios campos.
////        return $qb->getQuery()->getSQL(); // Debido a que la consulta devuelve un fila y varios campos.
//        SELECT
//	SUM(
//        (
//            SELECT SUM(mo.mo_monto)
//            FROM MOVIMIENTOS mo
//            INNER JOIN AHORROS ah ON mo.ahorros_ah_id = ah.ah_id
//            WHERE mo.mo_borrado_logico = 0 AND
//                  ah.ah_id = 1 AND
//                  mo.mo_concepto LIKE '%internet%' AND
//                  mo.mo_tipo = 'C'
//        ) - (
//            SELECT SUM(mo.mo_monto)
//            FROM MOVIMIENTOS mo
//            INNER JOIN AHORROS ah ON mo.ahorros_ah_id = ah.ah_id
//            WHERE mo.mo_borrado_logico = 0 AND
//                  ah.ah_id = 1 AND
//                  mo.mo_concepto LIKE '%internet%' AND
//                  mo.mo_tipo = 'D'
//    	)
//    )AS suma2
//FROM MOVIMIENTOS
    }
}


text:
package com.arshiya.mapsapi.geocodermanager;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;

import static com.arshiya.mapsapi.common.Constants.ACTION_SEARCH;

/**
 * Created by arshiya on 10/30/2015.
 * Process the search action - converts the input named location string to an array of addresses
 */
public class PlaceSearchHandler {

    private static final String TAG = PlaceSearchHandler.class.getSimpleName();
    private Context mContext;
    private static PlaceSearchHandler mPlaceSearchHandler = new PlaceSearchHandler();
    private Messenger mMessenger;

    private PlaceSearchHandler() {
    }

    public static PlaceSearchHandler getInstance() {
        return mPlaceSearchHandler;
    }

    public void search(Context context, String searchString, Messenger messenger) {
        mContext = context;
        mMessenger = messenger;
        new GeoCoderTask().execute(searchString);
    }

    /**
     * Asynchronously fetches an array of addresses that are known to describe named Location
     * and sends the result back to the result handler
     */
    private class GeoCoderTask extends AsyncTask<String, Void, List<Address>> {

        @Override
        protected List<Address> doInBackground(String... locationName) {
            Log.d("GeoCoderTask", "address : " + locationName);
            Geocoder geocoder = new Geocoder(mContext);
            List<Address> addresses = null;

            try {
                Log.d("GeoCoderTask", "address : " + locationName[0]);
                addresses = geocoder.getFromLocationName(locationName[0], 5);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addresses;
        }

        @Override
        protected void onPostExecute(List<Address> addresses) {
            if (null == addresses || 0 == addresses.size()) {
                Toast.makeText(mContext, "No location found", Toast.LENGTH_SHORT).show();
            } else {
                Log.d(TAG, "got addresses");
            }
            Message result = Message.obtain();
            result.obj = addresses;
            result.arg1 = ACTION_SEARCH;

            try {
                mMessenger.send(result);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}


text:
package org.apache.cloudstack;

import com.cloud.user.DomainManager;
import com.cloud.user.User;
import com.cloud.user.UserVO;
import com.cloud.user.dao.UserDao;
import junit.framework.TestCase;
import org.apache.cloudstack.framework.security.keystore.KeystoreDao;
import org.apache.cloudstack.saml.SAML2AuthManagerImpl;
import org.apache.cloudstack.saml.SAMLTokenDao;
import org.apache.cloudstack.saml.SAMLTokenVO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import java.lang.reflect.Field;

@RunWith(MockitoJUnitRunner.class)
public class SAML2AuthManagerImplTest extends TestCase {
    @Mock
    private KeystoreDao ksDao;

    @Mock
    private SAMLTokenDao samlTokenDao;

    @Mock
    private UserDao userDao;

    @Mock
    DomainManager domainMgr;

    SAML2AuthManagerImpl saml2AuthManager;

    @Override
    @Before
    public void setUp() throws NoSuchFieldException, IllegalAccessException {
        saml2AuthManager = Mockito.spy(new SAML2AuthManagerImpl());

        Field ksDaoField = SAML2AuthManagerImpl.class.getDeclaredField("_ksDao");
        ksDaoField.setAccessible(true);
        ksDaoField.set(saml2AuthManager, ksDao);

        Field samlTokenDaoField = SAML2AuthManagerImpl.class.getDeclaredField("_samlTokenDao");
        samlTokenDaoField.setAccessible(true);
        samlTokenDaoField.set(saml2AuthManager, samlTokenDao);

        Field userDaoField = SAML2AuthManagerImpl.class.getDeclaredField("_userDao");
        userDaoField.setAccessible(true);
        userDaoField.set(saml2AuthManager, userDao);

        Field domainMgrField = SAML2AuthManagerImpl.class.getDeclaredField("_domainMgr");
        domainMgrField.setAccessible(true);
        domainMgrField.set(saml2AuthManager, domainMgr);

        // enable the plugin
        Mockito.doReturn(true).when(saml2AuthManager).isSAMLPluginEnabled();
    }

    @Test
    public void testIsUserAuthorized() {
        final String entityID = "some IDP ID";

        // Test unauthorized user
        UserVO user = new UserVO(200L);
        user.setUsername("someuser");
        user.setSource(User.Source.UNKNOWN);
        user.setExternalEntity(entityID);
        Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(user);
        assertFalse(saml2AuthManager.isUserAuthorized(user.getId(), "someID"));

        // Test authorized user with wrong IDP
        user.setSource(User.Source.SAML2);
        Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(user);
        assertFalse(saml2AuthManager.isUserAuthorized(user.getId(), "someID"));

        // Test authorized user with wrong IDP
        user.setSource(User.Source.SAML2);
        Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(user);
        assertTrue(saml2AuthManager.isUserAuthorized(user.getId(), entityID));
    }

    @Test
    public void testAuthorizeUser() {
        // Test invalid user
        Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(null);
        assertFalse(saml2AuthManager.authorizeUser(1L, "someID", true));

        // Test valid user
        UserVO user = new UserVO(200L);
        user.setUsername("someuser");
        Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(user);
        assertTrue(saml2AuthManager.authorizeUser(1L, "someID", true));
        Mockito.verify(userDao, Mockito.atLeastOnce()).update(Mockito.anyLong(), Mockito.any(user.getClass()));
    }

    @Test
    public void testSaveToken() {
        // duplicate token test
        Mockito.when(samlTokenDao.findByUuid(Mockito.anyString())).thenReturn(new SAMLTokenVO());
        saml2AuthManager.saveToken("someAuthnID", null, "https://idp.bhaisaab.org/profile/shibboleth");
        Mockito.verify(samlTokenDao, Mockito.times(0)).persist(Mockito.any(SAMLTokenVO.class));

        // valid test
        Mockito.when(samlTokenDao.findByUuid(Mockito.anyString())).thenReturn(null);
        saml2AuthManager.saveToken("someAuthnID", null, "https://idp.bhaisaab.org/profile/shibboleth");
        Mockito.verify(samlTokenDao, Mockito.times(1)).persist(Mockito.any(SAMLTokenVO.class));
    }

    @Test
    public void testGetToken() {
        SAMLTokenVO randomToken = new SAMLTokenVO("uuid", 1L, "someIDPDI");
        Mockito.when(samlTokenDao.findByUuid(Mockito.anyString())).thenReturn(randomToken);
        assertEquals(saml2AuthManager.getToken("someAuthnID"), randomToken);
    }

    @Test
    public void testExpireToken() {
        saml2AuthManager.expireTokens();
        Mockito.verify(samlTokenDao, Mockito.atLeast(1)).expireTokens();
    }

    @Test
    public void testPluginEnabled() {
        assertTrue(saml2AuthManager.isSAMLPluginEnabled());
    }

    @Test
    public void testPluginComponentName() {
        assertEquals(saml2AuthManager.getConfigComponentName(), "SAML2-PLUGIN");
    }

    @Test
    public void testGetCommands() {
        // Plugin enabled
        assertTrue(saml2AuthManager.getCommands().size() > 0);
        assertTrue(saml2AuthManager.getAuthCommands().size() > 0);

        // Plugin disabled
        Mockito.doReturn(false).when(saml2AuthManager).isSAMLPluginEnabled();
        assertTrue(saml2AuthManager.getCommands().size() == 0);
        assertTrue(saml2AuthManager.getAuthCommands().size() == 0);
        // Re-enable the plugin
        Mockito.doReturn(true).when(saml2AuthManager).isSAMLPluginEnabled();
    }

    @Test
    public void testConfigKeys() {
        assertTrue(saml2AuthManager.getConfigKeys().length > 0);
    }
}


text:
package com.chain;

public class TenDollarDispenser implements DispenseChain {
    private DispenseChain chain;

    @Override
    public void setNextChain(DispenseChain nextChain) {
        this.chain=nextChain;
    }

    @Override
    public void dispense(Currency cur) {
        if(cur.getAmount() >= 10){
            int num = cur.getAmount()/10;
            int remainder = cur.getAmount() % 10;
            System.out.println("Dispensing "+num+" 10$ note");
            if(remainder !=0) this.chain.dispense(new Currency(remainder));
        }else{
            this.chain.dispense(cur);
        }
    }
}


text:
/** \file termiterator.h
 * \brief Classes for iterating through term lists
 */
/* Copyright 1999,2000,2001 BrightStation PLC
 * Copyright 2002 Ananova Ltd
 * Copyright 2003,2004,2005,2006,2007,2008,2009,2012 Olly Betts
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */

#ifndef XAPIAN_INCLUDED_TERMITERATOR_H
#define XAPIAN_INCLUDED_TERMITERATOR_H

#include <iterator>
#include <string>

#include <xapian/base.h>
#include <xapian/derefwrapper.h>
#include <xapian/types.h>
#include <xapian/positioniterator.h>
#include <xapian/visibility.h>

namespace Xapian {

class Database;

/** An iterator pointing to items in a list of terms.
 */
class XAPIAN_VISIBILITY_DEFAULT TermIterator {
    public:
	class Internal;
	/// @internal Reference counted internals.
	Xapian::Internal::RefCntPtr<Internal> internal;

	/// @internal Reference counted internals.
	explicit TermIterator(Internal *internal_);

	/// Default constructor - for declaring an uninitialised iterator.
	TermIterator();

	/// Destructor.
	~TermIterator();

	/** Copying is allowed.  The internals are reference counted, so
	 *  copying is also cheap.
	 */
	TermIterator(const TermIterator &other);

	/** Assignment is allowed.  The internals are reference counted,
	 *  so assignment is also cheap.
	 */
	void operator=(const TermIterator &other);

	/// Return the current term.
	std::string operator *() const;

	/// Advance the iterator to the next position.
	TermIterator & operator++();

	/// Advance the iterator to the next position (postfix version).
	DerefWrapper_<std::string> operator++(int) {
	    const std::string & term(**this);
	    operator++();
	    return DerefWrapper_<std::string>(term);
	}

	/** Advance the iterator to the specified term.
	 *
	 *  If the specified term isn't in the list, position ourselves on the
	 *  first term after it (or at_end() if no greater terms are present).
	 */
	void skip_to(const std::string & tname);

	/** Return the wdf of the current term (if meaningful).
	 *
	 *  The wdf (within document frequency) is the number of occurrences
	 *  of a term in a particular document.
	 */
	Xapian::termcount get_wdf() const;

	/** Return the term frequency of the current term (if meaningful).
	 *
	 *  The term frequency is the number of documents which a term indexes.
	 */
	Xapian::doccount get_termfreq() const;

	/** Return length of positionlist for current term.
	 */
	Xapian::termcount positionlist_count() const;

	/** Return PositionIterator pointing to start of positionlist for
	 *  current term.
	 */
	PositionIterator positionlist_begin() const;

	/** Return PositionIterator pointing to end of positionlist for
	 *  current term.
	 */
	PositionIterator positionlist_end() const {
	    return PositionIterator();
	}

	/// Return a string describing this object.
	std::string get_description() const;

	/// Allow use as an STL iterator
	//@{
	typedef std::input_iterator_tag iterator_category;
	typedef std::string value_type;
	typedef Xapian::termcount_diff difference_type;
	typedef std::string * pointer;
	typedef std::string & reference;
	//@}
};

/// Equality test for TermIterator objects.
inline bool
operator==(const TermIterator &a, const TermIterator &b)
{
    return (a.internal.get() == b.internal.get());
}

/// Inequality test for TermIterator objects.
inline bool
operator!=(const TermIterator &a, const TermIterator &b)
{
    return !(a == b);
}

}

#endif /* XAPIAN_INCLUDED_TERMITERATOR_H */


text:
All notable changes to this project will be documented from version 3.5.9 forward
in this file.

## [3.5.9](https://github.com/workshopper/learnyounode/compare/v3.5.8...v3.5.9) (2017-02-16)


text:
use TelerikAcademy;
go

create function ufn_SelectEmployeesAndTownsNamesContainingCharacters(@chars varchar(50))
returns @table table(Name varchar(50))
as
begin
	declare @NameCursor cursor;
	declare @Name varchar(50);
	set @NameCursor = cursor for
		select e.FirstName from Employees e
		union
		select i.LastName from Employees i
		union
		select t.Name from Towns t;

	open @NameCursor
	fetch next from @NameCursor
	into @Name;
	while @@fetch_status = 0
	begin
		declare @meetsRequirements bit;
		set @meetsRequirements = 1;

		declare @i int;
		set @i = 1;

		while @i <= len(@Name)
		begin
			declare @c char;
			set @c = lower(substring(@Name, @i, 1));

			if(charindex(@c, lower(@chars)) = 0)
			begin
				set @meetsRequirements = 0;
			end
			set @i += 1;
		end
		if(@meetsRequirements = 1)
		begin
			insert into @table(Name) values (@Name);
		end
		fetch next from @NameCursor
		into @Name;
	end
	return;
end
go

select * from ufn_SelectEmployeesAndTownsNamesContainingCharacters('oistmiahf');


text:
<!DOCTYPE html>

	<title>gSchool, Meet Paul</title>

	<meta charset="UTF-8">

	<link href="paulstyles.css" rel="stylesheet" />

Paul Cullen Rowe

Man - Myth - Legend

Me Right Meow

Future Me

			Aspirations After gSchool

			I want to rule the world.

				But actually, I'd really like to create something among a team of people who are WAY better than me.  I want to join or lead a team to build something that challenges the way we interact with information.  I want to continue to learn, improve and grow every day, and turn that information into something that can change the world.

			My Sick Skills After gSchool

			That monster is me.  And that little dude? That's all the code I'm gonna eat. Nom nom nom nom nom.

Contact Me

Paul Rowe

|

prowe214@gmail.com

|

(914) 557-6006


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>Ilwis-Objects: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Ilwis-Objects
    1.0

GIS and Remote Sensing framework for data access and processing

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Enumerations

a

b

c

d

e

f

g

h

i

k

l

m

n

o

p

r

s

t

u

v

x

y

z

~

 All Classes Functions Enumerations Pages

Here is a list of all documented class members with links to the class documentation for each member:

- a -

add()
: Ilwis::ColorPalette
, Ilwis::IndexedIdentifierRange
, Ilwis::ItemRange
, Ilwis::NumericItemRange
, Ilwis::NamedIdentifierRange
, Ilwis::NumericItemRange
, Ilwis::IndexedIdentifierRange
, Ilwis::NamedIdentifierRange
, Ilwis::ItemRange

addColumn()
: Ilwis::DatabaseTable
, Ilwis::FlatTable
, Ilwis::Table
, Ilwis::AttributeTable
, Ilwis::BaseTable

addContainer()
: Ilwis::Resource
, Ilwis::MasterCatalog

addCreateItem()
: Ilwis::ItemRange

addCreator()
: Ilwis::ConnectorFactory

addFactory()
: Ilwis::Kernel

addItem()
: Ilwis::ItemDomain< D >

addItems()
: Ilwis::MasterCatalog

addProperty()
: Ilwis::Resource

addRange()
: Ilwis::NumericItemRange
, Ilwis::ItemRange

addTypeFunction()
: Ilwis::IlwisObject

attributeTable()
: Ilwis::Coverage

AttributeType
: Ilwis::Coverage

<address class="footer">
Generated on Fri Mar 28 2014 13:51:05 for Ilwis-Objects by

 1.8.3.1
</address>