text:
from oslo.config import cfg
from sqlalchemy import exc as sql_exc
from sqlalchemy.orm import exc as sa_exc

from neutron.agent import securitygroups_rpc as sg_rpc
from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api
from neutron.api.v2 import attributes
from neutron.common import constants as const
from neutron.common import exceptions as exc
from neutron.common import topics
from neutron.db import agentschedulers_db
from neutron.db import allowedaddresspairs_db as addr_pair_db
from neutron.db import db_base_plugin_v2
from neutron.db import external_net_db
from neutron.db import extradhcpopt_db
from neutron.db import models_v2
from neutron.db import quota_db  # noqa
from neutron.db import securitygroups_rpc_base as sg_db_rpc
from neutron.extensions import allowedaddresspairs as addr_pair
from neutron.extensions import extra_dhcp_opt as edo_ext
from neutron.extensions import multiprovidernet as mpnet
from neutron.extensions import portbindings
from neutron.extensions import providernet as provider
from neutron import manager
from neutron.openstack.common import db as os_db
from neutron.openstack.common import excutils
from neutron.openstack.common import importutils
from neutron.openstack.common import jsonutils
from neutron.openstack.common import log
from neutron.openstack.common import rpc as c_rpc
from neutron.plugins.common import constants as service_constants
from neutron.plugins.ml2.common import exceptions as ml2_exc
from neutron.plugins.ml2 import config  # noqa
from neutron.plugins.ml2 import db
from neutron.plugins.ml2 import driver_api as api
from neutron.plugins.ml2 import driver_context
from neutron.plugins.ml2 import managers
from neutron.plugins.ml2 import models
from neutron.plugins.ml2 import rpc

LOG = log.getLogger(__name__)

# REVISIT(rkukura): Move this and other network_type constants to
# providernet.py?
TYPE_MULTI_SEGMENT = 'multi-segment'

class Ml2Plugin(db_base_plugin_v2.NeutronDbPluginV2,
                external_net_db.External_net_db_mixin,
                sg_db_rpc.SecurityGroupServerRpcMixin,
                agentschedulers_db.DhcpAgentSchedulerDbMixin,
                addr_pair_db.AllowedAddressPairsMixin,
                extradhcpopt_db.ExtraDhcpOptMixin):

    """Implement the Neutron L2 abstractions using modules.

    Ml2Plugin is a Neutron plugin based on separately extensible sets
    of network types and mechanisms for connecting to networks of
    those types. The network types and mechanisms are implemented as
    drivers loaded via Python entry points. Networks can be made up of
    multiple segments (not yet fully implemented).
    """

    # This attribute specifies whether the plugin supports or not
    # bulk/pagination/sorting operations. Name mangling is used in
    # order to ensure it is qualified by class
    __native_bulk_support = True
    __native_pagination_support = True
    __native_sorting_support = True

    # List of supported extensions
    _supported_extension_aliases = ["provider", "external-net", "binding",
                                    "quotas", "security-group", "agent",
                                    "dhcp_agent_scheduler",
                                    "multi-provider", "allowed-address-pairs",
                                    "extra_dhcp_opt"]

    @property
    def supported_extension_aliases(self):
        if not hasattr(self, '_aliases'):
            aliases = self._supported_extension_aliases[:]
            sg_rpc.disable_security_group_extension_if_noop_driver(aliases)
            self._aliases = aliases
        return self._aliases

    def __init__(self):
        # First load drivers, then initialize DB, then initialize drivers
        self.type_manager = managers.TypeManager()
        self.mechanism_manager = managers.MechanismManager()
        super(Ml2Plugin, self).__init__()
        self.type_manager.initialize()
        self.mechanism_manager.initialize()
        # bulk support depends on the underlying drivers
        self.__native_bulk_support = self.mechanism_manager.native_bulk_support

        self._setup_rpc()

        # REVISIT(rkukura): Use stevedore for these?
        self.network_scheduler = importutils.import_object(
            cfg.CONF.network_scheduler_driver
        )

        LOG.info(_("Modular L2 Plugin initialization complete"))

    def _setup_rpc(self):
        self.notifier = rpc.AgentNotifierApi(topics.AGENT)
        self.agent_notifiers[const.AGENT_TYPE_DHCP] = (
            dhcp_rpc_agent_api.DhcpAgentNotifyAPI()
        )

    def start_rpc_listener(self):
        self.callbacks = rpc.RpcCallbacks(self.notifier, self.type_manager)
        self.topic = topics.PLUGIN
        self.conn = c_rpc.create_connection(new=True)
        self.dispatcher = self.callbacks.create_rpc_dispatcher()
        self.conn.create_consumer(self.topic, self.dispatcher,
                                  fanout=False)
        return self.conn.consume_in_thread()

    def _process_provider_segment(self, segment):
        network_type = self._get_attribute(segment, provider.NETWORK_TYPE)
        physical_network = self._get_attribute(segment,
                                               provider.PHYSICAL_NETWORK)
        segmentation_id = self._get_attribute(segment,
                                              provider.SEGMENTATION_ID)

        if attributes.is_attr_set(network_type):
            segment = {api.NETWORK_TYPE: network_type,
                       api.PHYSICAL_NETWORK: physical_network,
                       api.SEGMENTATION_ID: segmentation_id}
            self.type_manager.validate_provider_segment(segment)
            return segment

        msg = _("network_type required")
        raise exc.InvalidInput(error_message=msg)

    def _process_provider_create(self, network):
        segments = []

        if any(attributes.is_attr_set(network.get(f))
               for f in (provider.NETWORK_TYPE, provider.PHYSICAL_NETWORK,
                         provider.SEGMENTATION_ID)):
            # Verify that multiprovider and provider attributes are not set
            # at the same time.
            if attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
                raise mpnet.SegmentsSetInConjunctionWithProviders()

            network_type = self._get_attribute(network, provider.NETWORK_TYPE)
            physical_network = self._get_attribute(network,
                                                   provider.PHYSICAL_NETWORK)
            segmentation_id = self._get_attribute(network,
                                                  provider.SEGMENTATION_ID)
            segments = [{provider.NETWORK_TYPE: network_type,
                         provider.PHYSICAL_NETWORK: physical_network,
                         provider.SEGMENTATION_ID: segmentation_id}]
        elif attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
            segments = network[mpnet.SEGMENTS]
        else:
            return

        return [self._process_provider_segment(s) for s in segments]

    def _get_attribute(self, attrs, key):
        value = attrs.get(key)
        if value is attributes.ATTR_NOT_SPECIFIED:
            value = None
        return value

    def _extend_network_dict_provider(self, context, network):
        id = network['id']
        segments = db.get_network_segments(context.session, id)
        if not segments:
            LOG.error(_("Network %s has no segments"), id)
            network[provider.NETWORK_TYPE] = None
            network[provider.PHYSICAL_NETWORK] = None
            network[provider.SEGMENTATION_ID] = None
        elif len(segments) > 1:
            network[mpnet.SEGMENTS] = [
                {provider.NETWORK_TYPE: segment[api.NETWORK_TYPE],
                 provider.PHYSICAL_NETWORK: segment[api.PHYSICAL_NETWORK],
                 provider.SEGMENTATION_ID: segment[api.SEGMENTATION_ID]}
                for segment in segments]
        else:
            segment = segments[0]
            network[provider.NETWORK_TYPE] = segment[api.NETWORK_TYPE]
            network[provider.PHYSICAL_NETWORK] = segment[api.PHYSICAL_NETWORK]
            network[provider.SEGMENTATION_ID] = segment[api.SEGMENTATION_ID]

    def _filter_nets_provider(self, context, nets, filters):
        # TODO(rkukura): Implement filtering.
        return nets

    def _process_port_binding(self, mech_context, attrs):
        binding = mech_context._binding
        port = mech_context.current
        self._update_port_dict_binding(port, binding)

        host = attrs and attrs.get(portbindings.HOST_ID)
        host_set = attributes.is_attr_set(host)

        vnic_type = attrs and attrs.get(portbindings.VNIC_TYPE)
        vnic_type_set = attributes.is_attr_set(vnic_type)

        # CLI can't send {}, so treat None as {}
        profile = attrs and attrs.get(portbindings.PROFILE)
        profile_set = profile is not attributes.ATTR_NOT_SPECIFIED
        if profile_set and not profile:
            profile = {}

        if binding.vif_type != portbindings.VIF_TYPE_UNBOUND:
            if (not host_set and not vnic_type_set and not profile_set and
                binding.segment and
                self.mechanism_manager.validate_port_binding(mech_context)):
                return False
            self.mechanism_manager.unbind_port(mech_context)
            self._update_port_dict_binding(port, binding)

        # Return True only if an agent notification is needed.
        # This will happen if a new host, vnic_type, or profile was specified
        # that differs from the current one. Note that host_set is True
        # even if the host is an empty string
        ret_value = ((host_set and binding.get('host') != host) or
                     (vnic_type_set and
                      binding.get('vnic_type') != vnic_type) or
                     (profile_set and self._get_profile(binding) != profile))

        if host_set:
            binding.host = host
            port[portbindings.HOST_ID] = host

        if vnic_type_set:
            binding.vnic_type = vnic_type
            port[portbindings.VNIC_TYPE] = vnic_type

        if profile_set:
            binding.profile = jsonutils.dumps(profile)
            if len(binding.profile) > models.BINDING_PROFILE_LEN:
                msg = _("binding:profile value too large")
                raise exc.InvalidInput(error_message=msg)
            port[portbindings.PROFILE] = profile

        # To try to [re]bind if host is non-empty.
        if binding.host:
            self.mechanism_manager.bind_port(mech_context)
            self._update_port_dict_binding(port, binding)

        return ret_value

    def _update_port_dict_binding(self, port, binding):
        port[portbindings.HOST_ID] = binding.host
        port[portbindings.VNIC_TYPE] = binding.vnic_type
        port[portbindings.PROFILE] = self._get_profile(binding)
        port[portbindings.VIF_TYPE] = binding.vif_type
        port[portbindings.VIF_DETAILS] = self._get_vif_details(binding)

    def _get_vif_details(self, binding):
        if binding.vif_details:
            try:
                return jsonutils.loads(binding.vif_details)
            except Exception:
                LOG.error(_("Serialized vif_details DB value '%(value)s' "
                            "for port %(port)s is invalid"),
                          {'value': binding.vif_details,
                           'port': binding.port_id})
        return {}

    def _get_profile(self, binding):
        if binding.profile:
            try:
                return jsonutils.loads(binding.profile)
            except Exception:
                LOG.error(_("Serialized profile DB value '%(value)s' for "
                            "port %(port)s is invalid"),
                          {'value': binding.profile,
                           'port': binding.port_id})
        return {}

    def _delete_port_binding(self, mech_context):
        binding = mech_context._binding
        port = mech_context.current
        self._update_port_dict_binding(port, binding)
        self.mechanism_manager.unbind_port(mech_context)
        self._update_port_dict_binding(port, binding)

    def _ml2_extend_port_dict_binding(self, port_res, port_db):
        # None when called during unit tests for other plugins.
        if port_db.port_binding:
            self._update_port_dict_binding(port_res, port_db.port_binding)

    db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs(
        attributes.PORTS, ['_ml2_extend_port_dict_binding'])

    # Note - The following hook methods have "ml2" in their names so
    # that they are not called twice during unit tests due to global
    # registration of hooks in portbindings_db.py used by other
    # plugins.

    def _ml2_port_model_hook(self, context, original_model, query):
        query = query.outerjoin(models.PortBinding,
                                (original_model.id ==
                                 models.PortBinding.port_id))
        return query

    def _ml2_port_result_filter_hook(self, query, filters):
        values = filters and filters.get(portbindings.HOST_ID, [])
        if not values:
            return query
        return query.filter(models.PortBinding.host.in_(values))

    db_base_plugin_v2.NeutronDbPluginV2.register_model_query_hook(
        models_v2.Port,
        "ml2_port_bindings",
        '_ml2_port_model_hook',
        None,
        '_ml2_port_result_filter_hook')

    def _notify_port_updated(self, mech_context):
        port = mech_context._port
        segment = mech_context.bound_segment
        if not segment:
            # REVISIT(rkukura): This should notify agent to unplug port
            network = mech_context.network.current
            LOG.warning(_("In _notify_port_updated(), no bound segment for "
                          "port %(port_id)s on network %(network_id)s"),
                        {'port_id': port['id'],
                         'network_id': network['id']})
            return
        self.notifier.port_update(mech_context._plugin_context, port,
                                  segment[api.NETWORK_TYPE],
                                  segment[api.SEGMENTATION_ID],
                                  segment[api.PHYSICAL_NETWORK])

    # TODO(apech): Need to override bulk operations

    def create_network(self, context, network):
        net_data = network['network']
        segments = self._process_provider_create(net_data)
        tenant_id = self._get_tenant_id_for_create(context, net_data)

        session = context.session
        with session.begin(subtransactions=True):
            self._ensure_default_security_group(context, tenant_id)
            result = super(Ml2Plugin, self).create_network(context, network)
            network_id = result['id']
            self._process_l3_create(context, result, net_data)
            # REVISIT(rkukura): Consider moving all segment management
            # to TypeManager.
            if segments:
                for segment in segments:
                    self.type_manager.reserve_provider_segment(session,
                                                               segment)
                    db.add_network_segment(session, network_id, segment)
            else:
                segment = self.type_manager.allocate_tenant_segment(session)
                db.add_network_segment(session, network_id, segment)
            self._extend_network_dict_provider(context, result)
            mech_context = driver_context.NetworkContext(self, context,
                                                         result)
            self.mechanism_manager.create_network_precommit(mech_context)

        try:
            self.mechanism_manager.create_network_postcommit(mech_context)
        except ml2_exc.MechanismDriverError:
            with excutils.save_and_reraise_exception():
                LOG.error(_("mechanism_manager.create_network_postcommit "
                            "failed, deleting network '%s'"), result['id'])
                self.delete_network(context, result['id'])
        return result

    def update_network(self, context, id, network):
        provider._raise_if_updates_provider_attributes(network['network'])

        session = context.session
        with session.begin(subtransactions=True):
            original_network = super(Ml2Plugin, self).get_network(context, id)
            updated_network = super(Ml2Plugin, self).update_network(context,
                                                                    id,
                                                                    network)
            self._process_l3_update(context, updated_network,
                                    network['network'])
            self._extend_network_dict_provider(context, updated_network)
            mech_context = driver_context.NetworkContext(
                self, context, updated_network,
                original_network=original_network)
            self.mechanism_manager.update_network_precommit(mech_context)

        # TODO(apech) - handle errors raised by update_network, potentially
        # by re-calling update_network with the previous attributes. For
        # now the error is propogated to the caller, which is expected to
        # either undo/retry the operation or delete the resource.
        self.mechanism_manager.update_network_postcommit(mech_context)
        return updated_network

    def get_network(self, context, id, fields=None):
        session = context.session
        with session.begin(subtransactions=True):
            result = super(Ml2Plugin, self).get_network(context, id, None)
            self._extend_network_dict_provider(context, result)

        return self._fields(result, fields)

    def get_networks(self, context, filters=None, fields=None,
                     sorts=None, limit=None, marker=None, page_reverse=False):
        session = context.session
        with session.begin(subtransactions=True):
            nets = super(Ml2Plugin,
                         self).get_networks(context, filters, None, sorts,
                                            limit, marker, page_reverse)
            for net in nets:
                self._extend_network_dict_provider(context, net)

            nets = self._filter_nets_provider(context, nets, filters)
            nets = self._filter_nets_l3(context, nets, filters)

        return [self._fields(net, fields) for net in nets]

    def delete_network(self, context, id):
        # REVISIT(rkukura) The super(Ml2Plugin, self).delete_network()
        # function is not used because it auto-deletes ports and
        # subnets from the DB without invoking the derived class's
        # delete_port() or delete_subnet(), preventing mechanism
        # drivers from being called. This approach should be revisited
        # when the API layer is reworked during icehouse.

        LOG.debug(_("Deleting network %s"), id)
        session = context.session
        while True:
            try:
                with session.begin(subtransactions=True):
                    # Get ports to auto-delete.
                    ports = (session.query(models_v2.Port).
                             enable_eagerloads(False).
                             filter_by(network_id=id).
                             with_lockmode('update').all())
                    LOG.debug(_("Ports to auto-delete: %s"), ports)
                    only_auto_del = all(p.device_owner
                                        in db_base_plugin_v2.
                                        AUTO_DELETE_PORT_OWNERS
                                        for p in ports)
                    if not only_auto_del:
                        LOG.debug(_("Tenant-owned ports exist"))
                        raise exc.NetworkInUse(net_id=id)

                    # Get subnets to auto-delete.
                    subnets = (session.query(models_v2.Subnet).
                               enable_eagerloads(False).
                               filter_by(network_id=id).
                               with_lockmode('update').all())
                    LOG.debug(_("Subnets to auto-delete: %s"), subnets)

                    if not (ports or subnets):
                        network = self.get_network(context, id)
                        mech_context = driver_context.NetworkContext(self,
                                                                     context,
                                                                     network)
                        self.mechanism_manager.delete_network_precommit(
                            mech_context)

                        record = self._get_network(context, id)
                        LOG.debug(_("Deleting network record %s"), record)
                        session.delete(record)

                        for segment in mech_context.network_segments:
                            self.type_manager.release_segment(session, segment)

                        # The segment records are deleted via cascade from the
                        # network record, so explicit removal is not necessary.
                        LOG.debug(_("Committing transaction"))
                        break
            except os_db.exception.DBError as e:
                if isinstance(e.inner_exception, sql_exc.IntegrityError):
                    msg = _("A concurrent port creation has occurred")
                    LOG.warning(msg)
                    continue
                else:
                    raise

            for port in ports:
                try:
                    self.delete_port(context, port.id)
                except Exception:
                    LOG.exception(_("Exception auto-deleting port %s"),
                                  port.id)
                    raise

            for subnet in subnets:
                try:
                    self.delete_subnet(context, subnet.id)
                except Exception:
                    LOG.exception(_("Exception auto-deleting subnet %s"),
                                  subnet.id)
                    raise

        try:
            self.mechanism_manager.delete_network_postcommit(mech_context)
        except ml2_exc.MechanismDriverError:
            # TODO(apech) - One or more mechanism driver failed to
            # delete the network.  Ideally we'd notify the caller of
            # the fact that an error occurred.
            LOG.error(_("mechanism_manager.delete_network_postcommit failed"))
        self.notifier.network_delete(context, id)

    def create_subnet(self, context, subnet):
        session = context.session
        with session.begin(subtransactions=True):
            result = super(Ml2Plugin, self).create_subnet(context, subnet)
            mech_context = driver_context.SubnetContext(self, context, result)
            self.mechanism_manager.create_subnet_precommit(mech_context)

        try:
            self.mechanism_manager.create_subnet_postcommit(mech_context)
        except ml2_exc.MechanismDriverError:
            with excutils.save_and_reraise_exception():
                LOG.error(_("mechanism_manager.create_subnet_postcommit "
                            "failed, deleting subnet '%s'"), result['id'])
                self.delete_subnet(context, result['id'])
        return result

    def update_subnet(self, context, id, subnet):
        session = context.session
        with session.begin(subtransactions=True):
            original_subnet = super(Ml2Plugin, self).get_subnet(context, id)
            updated_subnet = super(Ml2Plugin, self).update_subnet(
                context, id, subnet)
            mech_context = driver_context.SubnetContext(
                self, context, updated_subnet, original_subnet=original_subnet)
            self.mechanism_manager.update_subnet_precommit(mech_context)

        # TODO(apech) - handle errors raised by update_subnet, potentially
        # by re-calling update_subnet with the previous attributes. For
        # now the error is propogated to the caller, which is expected to
        # either undo/retry the operation or delete the resource.
        self.mechanism_manager.update_subnet_postcommit(mech_context)
        return updated_subnet

    def delete_subnet(self, context, id):
        # REVISIT(rkukura) The super(Ml2Plugin, self).delete_subnet()
        # function is not used because it auto-deletes ports from the
        # DB without invoking the derived class's delete_port(),
        # preventing mechanism drivers from being called. This
        # approach should be revisited when the API layer is reworked
        # during icehouse.

        LOG.debug(_("Deleting subnet %s"), id)
        session = context.session
        while True:
            with session.begin(subtransactions=True):
                subnet = self.get_subnet(context, id)
                # Get ports to auto-delete.
                allocated = (session.query(models_v2.IPAllocation).
                             filter_by(subnet_id=id).
                             join(models_v2.Port).
                             filter_by(network_id=subnet['network_id']).
                             with_lockmode('update').all())
                LOG.debug(_("Ports to auto-delete: %s"), allocated)
                only_auto_del = all(not a.port_id or
                                    a.ports.device_owner in db_base_plugin_v2.
                                    AUTO_DELETE_PORT_OWNERS
                                    for a in allocated)
                if not only_auto_del:
                    LOG.debug(_("Tenant-owned ports exist"))
                    raise exc.SubnetInUse(subnet_id=id)

                if not allocated:
                    mech_context = driver_context.SubnetContext(self, context,
                                                                subnet)
                    self.mechanism_manager.delete_subnet_precommit(
                        mech_context)

                    LOG.debug(_("Deleting subnet record"))
                    record = self._get_subnet(context, id)
                    session.delete(record)

                    LOG.debug(_("Committing transaction"))
                    break

            for a in allocated:
                try:
                    self.delete_port(context, a.port_id)
                except Exception:
                    LOG.exception(_("Exception auto-deleting port %s"),
                                  a.port_id)
                    raise

        try:
            self.mechanism_manager.delete_subnet_postcommit(mech_context)
        except ml2_exc.MechanismDriverError:
            # TODO(apech) - One or more mechanism driver failed to
            # delete the subnet.  Ideally we'd notify the caller of
            # the fact that an error occurred.
            LOG.error(_("mechanism_manager.delete_subnet_postcommit failed"))

    def create_port(self, context, port):
        attrs = port['port']
        attrs['status'] = const.PORT_STATUS_DOWN

        session = context.session
        with session.begin(subtransactions=True):
            self._ensure_default_security_group_on_port(context, port)
            sgids = self._get_security_groups_on_port(context, port)
            dhcp_opts = port['port'].get(edo_ext.EXTRADHCPOPTS, [])
            result = super(Ml2Plugin, self).create_port(context, port)
            self._process_port_create_security_group(context, result, sgids)
            network = self.get_network(context, result['network_id'])
            mech_context = driver_context.PortContext(self, context, result,
                                                      network)
            self._process_port_binding(mech_context, attrs)
            result[addr_pair.ADDRESS_PAIRS] = (
                self._process_create_allowed_address_pairs(
                    context, result,
                    attrs.get(addr_pair.ADDRESS_PAIRS)))
            self._process_port_create_extra_dhcp_opts(context, result,
                                                      dhcp_opts)
            self.mechanism_manager.create_port_precommit(mech_context)

        try:
            self.mechanism_manager.create_port_postcommit(mech_context)
        except ml2_exc.MechanismDriverError:
            with excutils.save_and_reraise_exception():
                LOG.error(_("mechanism_manager.create_port_postcommit "
                            "failed, deleting port '%s'"), result['id'])
                self.delete_port(context, result['id'])
        self.notify_security_groups_member_updated(context, result)
        return result

    def update_port(self, context, id, port):
        attrs = port['port']
        need_port_update_notify = False

        session = context.session
        changed_fixed_ips = 'fixed_ips' in port['port']
        with session.begin(subtransactions=True):
            try:
                port_db = (session.query(models_v2.Port).
                           enable_eagerloads(False).
                           filter_by(id=id).with_lockmode('update').one())
            except sa_exc.NoResultFound:
                raise exc.PortNotFound(port_id=id)
            original_port = self._make_port_dict(port_db)
            updated_port = super(Ml2Plugin, self).update_port(context, id,
                                                              port)
            if self.is_address_pairs_attribute_updated(original_port, port):
                self._delete_allowed_address_pairs(context, id)
                self._process_create_allowed_address_pairs(
                    context, updated_port,
                    port['port'][addr_pair.ADDRESS_PAIRS])
                need_port_update_notify = True
            elif changed_fixed_ips:
                self._check_fixed_ips_and_address_pairs_no_overlap(
                    context, updated_port)
            need_port_update_notify |= self.update_security_group_on_port(
                context, id, port, original_port, updated_port)
            network = self.get_network(context, original_port['network_id'])
            need_port_update_notify |= self._update_extra_dhcp_opts_on_port(
                context, id, port, updated_port)
            mech_context = driver_context.PortContext(
                self, context, updated_port, network,
                original_port=original_port)
            need_port_update_notify |= self._process_port_binding(
                mech_context, attrs)
            self.mechanism_manager.update_port_precommit(mech_context)

        # TODO(apech) - handle errors raised by update_port, potentially
        # by re-calling update_port with the previous attributes. For
        # now the error is propogated to the caller, which is expected to
        # either undo/retry the operation or delete the resource.
        self.mechanism_manager.update_port_postcommit(mech_context)

        need_port_update_notify |= self.is_security_group_member_updated(
            context, original_port, updated_port)

        if original_port['admin_state_up'] != updated_port['admin_state_up']:
            need_port_update_notify = True

        if need_port_update_notify:
            self._notify_port_updated(mech_context)

        return updated_port

    def delete_port(self, context, id, l3_port_check=True):
        LOG.debug(_("Deleting port %s"), id)
        l3plugin = manager.NeutronManager.get_service_plugins().get(
            service_constants.L3_ROUTER_NAT)
        if l3plugin and l3_port_check:
            l3plugin.prevent_l3_port_deletion(context, id)

        session = context.session
        with session.begin(subtransactions=True):
            if l3plugin:
                l3plugin.disassociate_floatingips(context, id)
            try:
                port_db = (session.query(models_v2.Port).
                           enable_eagerloads(False).
                           filter_by(id=id).with_lockmode('update').one())
            except sa_exc.NoResultFound:
                # the port existed when l3plugin.prevent_l3_port_deletion
                # was called but now is already gone
                LOG.debug(_("The port '%s' was deleted"), id)
                return
            port = self._make_port_dict(port_db)

            network = self.get_network(context, port['network_id'])
            mech_context = driver_context.PortContext(self, context, port,
                                                      network)
            self.mechanism_manager.delete_port_precommit(mech_context)
            self._delete_port_binding(mech_context)
            self._delete_port_security_group_bindings(context, id)
            LOG.debug(_("Calling base delete_port"))
            super(Ml2Plugin, self).delete_port(context, id)

        try:
            self.mechanism_manager.delete_port_postcommit(mech_context)
        except ml2_exc.MechanismDriverError:
            # TODO(apech) - One or more mechanism driver failed to
            # delete the port.  Ideally we'd notify the caller of the
            # fact that an error occurred.
            LOG.error(_("mechanism_manager.delete_port_postcommit failed"))
        self.notify_security_groups_member_updated(context, port)

    def update_port_status(self, context, port_id, status):
        updated = False
        session = context.session
        with session.begin(subtransactions=True):
            port = db.get_port(session, port_id)
            if not port:
                LOG.warning(_("Port %(port)s updated up by agent not found"),
                            {'port': port_id})
                return False
            if port.status != status:
                original_port = self._make_port_dict(port)
                port.status = status
                updated_port = self._make_port_dict(port)
                network = self.get_network(context,
                                           original_port['network_id'])
                mech_context = driver_context.PortContext(
                    self, context, updated_port, network,
                    original_port=original_port)
                self.mechanism_manager.update_port_precommit(mech_context)
                updated = True

        if updated:
            self.mechanism_manager.update_port_postcommit(mech_context)

        return True

    def port_bound_to_host(self, port_id, host):
        port_host = db.get_port_binding_host(port_id)
        return (port_host == host)


text: export * from './ng2-simple-table-factory';

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/OfficeDev/O365-Android-Microsoft-Graph-Profile.svg?branch=master)](https://travis-ci.org/OfficeDev/O365-Android-Microsoft-Graph-Profile)

**Note:** This repo is archived and no longer actively maintained. Security vulnerabilities may exist in the project, or its dependencies. If you plan to reuse or run any code from this repo, be sure to perform appropriate security checks on the code or dependencies first. Do not use this project as the starting point of a production Office Add-in. Always start your production code by using the Office/SharePoint development workload in Visual Studio, or the [Yeoman generator for Office Add-ins](https://github.com/OfficeDev/generator-office), and follow security best practices as you develop the add-in.

The first page presents you with a list of users. The second page displays information about any user you choose to view. All of this information, including files shared with the user, the user's alias, hire date, manager, direct reports, and groups comes from [Microsoft Graph](http://graph.microsoft.io/ "Overview of Microsoft Graph") (previously called Office 365 unified API).

The following image shows the user's page that displays the information mentioned above:

![Office 365 Profile sample](/readme-images/O365-Android-Profile-Thumbnail.png)

## Device requirements

To run the Profile sample, your device needs to meet the following requirements:

* Android API level 14 or later.

## Prerequisites

To use the Office 365 Profile sample for Android you need the following:

* [Android Studio](http://developer.android.com/sdk/index.html) version 1.0 or later.
* An Office 365 account. You can [join the Office 365 Developer Program and get a free 1 year subscription to Office 365](https://aka.ms/devprogramsignup) that includes the resources that you need to start building Office 365 apps.
      > Note: If you already have a subscription, the previous link sends you to a page that says *Sorry, you can't add that to your current account*. In that case use an account from your current Office 365 subscription.
* A client ID and redirect URI values of an application registered in Microsoft Azure. The application must run the   following permissions:
    * **Microsoft Graph**
        * Read items in all site collections
        * Read all files that user can access
        * Access directory as the signed in user
        * Read all users' basic profiles

You can also [add a native client application in Azure](https://msdn.microsoft.com/office/office365/HowTo/add-common-consent-manually#bk_RegisterNativeApp) and [grant proper permissions](https://github.com/OfficeDev/O365-Android-Profile/wiki/Grant-permissions-to-the-Profile-application-in-Azure) to it.

## Open the sample using Android Studio

1. Install [Android Studio](http://developer.android.com/tools/studio/index.html#install-updates) and add the Android SDK packages according to the [instructions](http://developer.android.com/sdk/installing/adding-packages.html) on developer.android.com.
2. Download or clone this sample.
3. Start Android Studio.
	1. Select **Open an existing Android Studio project**.
	2. Browse to your local repository and select the O365-Android-Profile project. Click **OK**.
4. Open the Constants.java file.
	1. Find the CLIENT\_ID constant and set its String value equal to the client id you registered in Azure Active Directory.
	2. Find the REDIRECT\_URI constant and set its String value equal to the redirect URI you registered in Azure Active Directory.
    ![Office 365 Profile sample](/readme-images/O365-Android-Profile-Constants.png "Client ID and Redirect URI values in Constants file")

    > Note: If you don't have CLIENT\_ID and REDIRECT\_URI values, [add a native client application in Azure](https://msdn.microsoft.com/office/office365/HowTo/add-common-consent-manually#bk_RegisterNativeApp) and take note of the CLIENT\_ID and REDIRECT_URI.

Once you've built the Profile sample, you can run it on an emulator or device.

## Questions and comments

We'd love to get your feedback on the O365 Android Profile project. You can send your questions and suggestions to us in the [Issues](https://github.com/OfficeDev/O365-Android-Profile/issues) section of this repository.

Questions about Office 365 development in general should be posted to [Stack Overflow](http://stackoverflow.com/questions/tagged/Office365+API). Make sure that your questions or comments are tagged with [Office365] and [API].

## Additional resources

* [Office 365 APIs platform overview](https://msdn.microsoft.com/office/office365/howto/platform-development-overview)
* [Overview of Microsoft Graph](http://graph.microsoft.io/)
* [Office 365 SDK for Android](https://github.com/OfficeDev/Office-365-SDK-for-Android)
* [Get started with Office 365 APIs in apps](https://msdn.microsoft.com/office/office365/howto/getting-started-Office-365-APIs)
* [Office 365 API code samples and videos](https://msdn.microsoft.com/office/office365/howto/starter-projects-and-code-samples)
* [Other Office 365 Profile samples](https://github.com/OfficeDev?utf8=%E2%9C%93&query=Profile)
* [Office 365 Connect Sample for Android](https://github.com/OfficeDev/O365-Android-Connect)
* [Office 365 Code Snippets for Android](https://github.com/OfficeDev/O365-Android-Snippets)
* [Office 365 APIs Starter Project for Android](https://github.com/OfficeDev/O365-Android-Start)

## Copyright
Copyright (c) 2015 Microsoft. All rights reserved.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.


text:
package com.tang.intellij.lua.comment.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.tang.intellij.lua.ty.ITy;

public interface LuaDocGenericTy extends LuaDocTy {

  @NotNull
  List<LuaDocTy> getTyList();

  @NotNull
  ITy getType();

}


text:
package com.connorhaigh.jootil.core.interfaces;

public interface Rebindable
{
	/**
	 * Rebinds this rebindable.
	 */
	public void rebind();
}


text:
package org.lwjgl.openvr;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;

/**
 *
Layout

 *
 *

 * struct VREvent_SeatedZeroPoseReset_t {
 *     bool bResetBySystemMenu;
 * }

 */
@NativeType("struct VREvent_SeatedZeroPoseReset_t")
public class VREventSeatedZeroPoseReset extends Struct {

    /** The struct size in bytes. */
    public static final int SIZEOF;

    /** The struct alignment in bytes. */
    public static final int ALIGNOF;

    /** The struct member offsets. */
    public static final int
        BRESETBYSYSTEMMENU;

    static {
        Layout layout = __struct(
            __member(1)
        );

        SIZEOF = layout.getSize();
        ALIGNOF = layout.getAlignment();

        BRESETBYSYSTEMMENU = layout.offsetof(0);
    }

    /**
     * Creates a {@code VREventSeatedZeroPoseReset} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public VREventSeatedZeroPoseReset(ByteBuffer container) {
        super(memAddress(container), __checkContainer(container, SIZEOF));
    }

    @Override
    public int sizeof() { return SIZEOF; }

    /** @return the value of the {@code bResetBySystemMenu} field. */
    @NativeType("bool")
    public boolean bResetBySystemMenu() { return nbResetBySystemMenu(address()); }

    // -----------------------------------

    /** Returns a new {@code VREventSeatedZeroPoseReset} instance for the specified memory address. */
    public static VREventSeatedZeroPoseReset create(long address) {
        return wrap(VREventSeatedZeroPoseReset.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VREventSeatedZeroPoseReset createSafe(long address) {
        return address == NULL ? null : wrap(VREventSeatedZeroPoseReset.class, address);
    }

    /**
     * Create a {@link VREventSeatedZeroPoseReset.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static VREventSeatedZeroPoseReset.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VREventSeatedZeroPoseReset.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

    // -----------------------------------

    /** Unsafe version of {@link #bResetBySystemMenu}. */
    public static boolean nbResetBySystemMenu(long struct) { return UNSAFE.getByte(null, struct + VREventSeatedZeroPoseReset.BRESETBYSYSTEMMENU) != 0; }

    // -----------------------------------

    /** An array of {@link VREventSeatedZeroPoseReset} structs. */
    public static class Buffer extends StructBuffer<VREventSeatedZeroPoseReset, Buffer> {

        private static final VREventSeatedZeroPoseReset ELEMENT_FACTORY = VREventSeatedZeroPoseReset.create(-1L);

        /**
         * Creates a new {@code VREventSeatedZeroPoseReset.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link VREventSeatedZeroPoseReset#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container, container.remaining() / SIZEOF);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected VREventSeatedZeroPoseReset getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** @return the value of the {@code bResetBySystemMenu} field. */
        @NativeType("bool")
        public boolean bResetBySystemMenu() { return VREventSeatedZeroPoseReset.nbResetBySystemMenu(address()); }

    }

}


text:
python curl反防盗链抓取连接
===

curl 反盗链抓取网页内容

源码地址: https://github.com/maicong/OpenAPI/blob/master/curl_get.php
翻译为python版

依赖
---
需要安装pycurl

pycurl安装时如果ssl backend不同会报错

    import pycurl

    ImportError: pycurl: libcurl link-time ssl backend (openssl) is differ
    ent from compile-time ssl backend (gnutls)

    pip uninstall pycurl
    export PYCURL_SSL_LIBRARY=openssl
    pip install pycurl

Simple Usage
---

    from resist_hotlinking import curl_get

    print curl_get('http://www.baidu.com')


text:
'use strict';

const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const getFilenamePrefix = require('../../../lighthouse-core/lib/file-namer').getFilenamePrefix;

class ExperimentDatabase {
  constructor() {
    this._fsRoot = fs.mkdtempSync(`${__dirname}/experiment-data-`);
    this._timeStamps = {};
  }

  get timeStamps() {
    return this._timeStamps;
  }

  get fsRoot() {
    return this._fsRoot;
  }

  /*
   * Save experiment data
   * @param {!Object} lhFlags
   * @param {!Object} lhResults
   */
  saveData(lhFlags, lhResults) {
    const id = getFilenamePrefix(lhResults);
    this._timeStamps[id] = lhResults.generatedTime;

    const dirPath = path.join(this._fsRoot, id);
    fs.mkdirSync(dirPath);
    fs.writeFileSync(path.join(dirPath, 'flags.json'), JSON.stringify(lhFlags));
    fs.writeFileSync(path.join(dirPath, 'results.json'), JSON.stringify(lhResults));
    return id;
  }

  /*
   * Get report.html
   * @param {string} id
   */
  getResults(id) {
    return JSON.parse(fs.readFileSync(path.join(this._fsRoot, id, 'results.json'), 'utf8'));
  }

  /*
   * Get flags.json
   * @param {string} id
   */
  getFlags(id) {
    return JSON.parse(fs.readFileSync(path.join(this._fsRoot, id, 'flags.json'), 'utf8'));
  }

  /*
   * Delete all the files created by this object
   */
  clear() {
    rimraf.sync(this._fsRoot);
  }
}

module.exports = ExperimentDatabase;


text:
namespace g{
namespace Uno{

// public delegate void Action<T>(T arg) :11
uDelegateType* Action1_typeof();

}} // ::g::Uno


text:
haki
====

Simple server deploying environment based on SSH-ying on production server and running the deploy script


text:
.. _nbt-specification:

Named Binary Tag specification
==============================

This specification was written by Markus Persson and was available at http://www.minecraft.net/docs/NBT.txt between 2010 and 2011.

NBT (Named Binary Tag) is a tag based binary format designed to carry large amounts of binary data with smaller amounts of additional data.

An NBT file consists of a single GZIPped Named Tag of type TAG_Compound.

A Named Tag has the following format::

    byte tagType
    TAG_String name
    [payload]

The tagType is a single byte defining the contents of the payload of the tag.

The name is a descriptive name, and can be anything (eg "cat", "banana", "Hello World!"). It has nothing to do with the tagType.
The purpose for this name is to name tags so parsing is easier and can be made to only look for certain recognized tag names.
Exception: If tagType is TAG_End, the name is skipped and assumed to be "".

The *[payload]* varies by tagType.

Note that **only** Named Tags carry the name and tagType data. Explicitly identified Tags (such as TAG_String above) only contains the payload.

The tag types and respective payloads are:

    Key:
        Value

..

    :TYPE:    0
    :NAME:    TAG_End
    :Payload: None.
    :Note:    This tag is used to mark the end of a compound list.
              Cannot be named! If type 0 appears where a Named Tag is expected, the name is assumed to be "".
              (In other words, this Tag is always just a single 0 byte when named, and nothing in all other cases).

..

    :TYPE:    1
    :NAME:    TAG_Byte
    :Payload: - A single signed byte (8 bits).

..

    :TYPE:    2
    :NAME:    TAG_Short
    :Payload: - A signed short (16 bits, big endian).

..

    :TYPE:    3
    :NAME:    TAG_Int
    :Payload: - A signed short (32 bits, big endian).

...

    :TYPE:    4
    :NAME:    TAG_Long
    :Payload: - A signed long (64 bits, big endian).

..

    :TYPE:    5
    :NAME:    TAG_Float
    :Payload: - A floating point value (32 bits, big endian, IEEE 754-2008, binary32).

..

    :TYPE:    6
    :NAME:    TAG_Double
    :Payload: - A floating point value (64 bits, big endian, IEEE 754-2008, binary64).

..

    :TYPE:    7
    :NAME:    TAG_Byte_Array
    :Payload: - TAG_Int length
              - An array of bytes of unspecified format. The length of this array is <length> bytes.

..

    :TYPE:    8
    :NAME:    TAG_String
    :Payload: - TAG_Short length.
              - An array of bytes defining a string in UTF-8 format. The length of this array is <length> bytes.

..

    :TYPE:    9
    :NAME:    TAG_List
    :Payload: - TAG_Byte tagId.
              - TAG_Int length.
              - A sequential list of Tags (not Named Tags), of type <typeId>. The length of this array is <length> Tags.
    :Notes:   All tags share the same type.

..

    :TYPE:    10
    :NAME:    TAG_Compound
    :Payload: - A sequential list of Named Tags. This array keeps going until a TAG_End is found.
              - TAG_End end.
    :Notes:   If there's a nested TAG_Compound within this tag, that one will also have a TAG_End, so simply reading until the next TAG_End will not work.
             The names of the named tags have to be unique within each TAG_Compound.
             The order of the tags is not guaranteed.

..

    :TYPE:    11
    :NAME:    TAG_Int_Array
    :Payload: - TAG_Int length.
              - An array of signed integers (32 bits, big endian). The length of this array is <4*length> bytes.
    :Notes:   This payload type was added to the specification in March 2012.

Decoding example:
(Use http://www.minecraft.net/docs/test.nbt to test your implementation)

First we start by reading a Named Tag.
After unzipping the stream, the first byte is a 10. That means the tag is a TAG_Compound (as expected by the specification).

The next two bytes are 0 and 11, meaning the name string consists of 11 UTF-8 characters. In this case, they happen to be "hello world".
That means our root tag is named "hello world". We can now move on to the payload.

From the specification, we see that TAG_Compound consists of a series of Named Tags, so we read another byte to find the tagType.
It happens to be an 8. The name is 4 letters long, and happens to be "name". Type 8 is TAG_String, meaning we read another two bytes to get the length,
then read that many bytes to get the contents. In this case, it's "Bananrama".

So now we know the TAG_Compound contains a TAG_String named "name" with the content "Bananrama"

We move on to reading the next Named Tag, and get a 0. This is TAG_End, which always has an implied name of "". That means that the list of entries
in the TAG_Compound is over, and indeed all of the NBT file.

So we ended up with this::

    TAG_Compound("hello world"): 1 entries
    {
       TAG_String("name"): Bananrama
    }

For a slightly longer test, download http://www.minecraft.net/docs/bigtest.nbt.
You should end up with this::

    TAG_Compound("Level"): 11 entries
    {
       TAG_Short("shortTest"): 32767
       TAG_Long("longTest"): 9223372036854775807
       TAG_Float("floatTest"): 0.49823147
       TAG_String("stringTest"): HELLO WORLD THIS IS A TEST STRING ÅÄÖ!
       TAG_Int("intTest"): 2147483647
       TAG_Compound("nested compound test"): 2 entries
       {
          TAG_Compound("ham"): 2 entries
          {
             TAG_String("name"): Hampus
             TAG_Float("value"): 0.75
          }
          TAG_Compound("egg"): 2 entries
          {
             TAG_String("name"): Eggbert
             TAG_Float("value"): 0.5
          }
       }
       TAG_List("listTest (long)"): 5 entries of type TAG_Long
       {
          TAG_Long: 11
          TAG_Long: 12
          TAG_Long: 13
          TAG_Long: 14
          TAG_Long: 15
       }
       TAG_Byte("byteTest"): 127
       TAG_List("listTest (compound)"): 2 entries of type TAG_Compound
       {
          TAG_Compound: 2 entries
          {
             TAG_String("name"): Compound tag #0
             TAG_Long("created-on"): 1264099775885
          }
          TAG_Compound: 2 entries
          {
             TAG_String("name"): Compound tag #1
             TAG_Long("created-on"): 1264099775885
          }
       }
       TAG_Byte_Array("byteArrayTest (the first 1000 values of (n*n*255+n*7)%100, starting with n=0 (0, 62, 34, 16, 8, ...))"): [1000 bytes]
       TAG_Double("doubleTest"): 0.4931287132182315
    }


text:
package org.anvard.springxml;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class MenuNamespaceHandler extends NamespaceHandlerSupport {

	@Override
	public void init() {
		registerBeanDefinitionParser("menu", new MenuDefinitionParser());
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.gintechsystems.gincose"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true"/>

    <application
        android:name=".GINcoseWrapper"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
@class ALAssetsGroup;

@interface PBAssetsRequest : NSObject

@property (nonatomic, readonly) ALAssetsGroup *assetGroup;

@property (nonatomic, readonly) NSEnumerationOptions options;

+ (instancetype)newWithAssetGroup:(ALAssetsGroup *)assetGroup
             withEnumerateOptions:(NSEnumerationOptions)options;

@end


text:
@interface DXFormViewController () <DXKeyboardObserverDelegate>

@property (nonatomic, strong) DXKeyboardObserver *keyboardObserver;

@end

@implementation DXFormViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    UIScrollView *scrollView = (UIScrollView *)self.view;
    scrollView.contentSize = self.view.frame.size;

    self.keyboardObserver = [DXKeyboardObserver new];
    self.keyboardObserver.scrollView = scrollView;
    self.keyboardObserver.viewToHideByTap = self.view;
    self.keyboardObserver.observerDelegate = self;
    self.keyboardObserver.visibleRectOnKeyboardAppearence = CGRectMake(0, 120, 320, 264);
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.keyboardObserver = nil;
    [super viewWillDisappear:animated];
}

#pragma mark -
#pragma mark - DXKeyboardObserverDelegate methods

- (void)keyboardWillAppear:(DXKeyboardUserInfo *)userInfo
{
    NSLog(@"keyboardWillAppear:");
}

- (void)keyboardDidAppear:(DXKeyboardUserInfo *)userInfo
{
    NSLog(@"keyboardDidAppear:");
}

- (void)keyboardWillDisappear:(DXKeyboardUserInfo *)userInfo
{
    NSLog(@"keyboardWillDisappear:");
}

- (void)keyboardDidDisappear:(DXKeyboardUserInfo *)userInfo
{
    NSLog(@"keyboardDidDisappear:");
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.londatiga.android.bluetooth"
    android:versionCode="1"
    android:versionName="1.0.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="net.londatiga.android.bluetooth.MainActivity"
            android:label="@string/app_name" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity
            android:name=".DeviceListActivity"
            android:label="@string/app_name">

            <intent-filter>
				<action android:name="android.intent.action.VIEW" />
            </intent-filter>

        </activity>

    </application>

</manifest>


text:
"""
This file creates templates for characters we want to be able to detect.
Templates are simple, front facing images without any distortions, blemishes, etc.
"""

import PIL.ImageFont
import cv2
import net.data
import string
import os
import re
import warnings
import configobj

import tqdm
import net.utilities

def get_hiragana_set():

    hiragana = {chr(index) for index in range(0x3042, 0x3090)}
    blacklist = {chr(0x3043), chr(0x3045), chr(0x3047), chr(0x3049), chr(0x3083),
                 chr(0x3085), chr(0x3087), chr(0x308E)}

    return sorted(list(hiragana.difference(blacklist)))

def get_katakana_set():

    katakana = {chr(index) for index in range(0x30A2, 0x30F0)}
    blacklist = {chr(0x30A3), chr(0x30A5), chr(0x30A7), chr(0x30A9), chr(0x30C3),
                 chr(0x30E3), chr(0x30E5), chr(0x30E7), chr(0x30EE)}

    return sorted(list(katakana.difference(blacklist)))

def get_digits_set():

    return [str(index) for index in range(0, 10)]

def get_kanji_set():

    try:

        with open("../../data/characters/kanji.txt") as file:

            content = file.read()
            return re.findall(r'\w', content)

    except FileNotFoundError:
        warnings.warn("Kanji file not found. No kanji will be included in templates.")
        return []

def main():

    font = PIL.ImageFont.truetype("/Library/Fonts/Osaka.ttf", size=100)

    characters = list(string.ascii_uppercase) + get_hiragana_set() +\
                 get_katakana_set() + get_digits_set() + get_kanji_set()

    characters = net.utilities.remove_visually_identical_characters(characters)

    config = configobj.ConfigObj('configuration.ini')
    image_size = [int(value) for value in config['image_size']]

    templates_maker = net.data.TemplatesMaker(font, tuple(image_size))

    base_path = "../../data/characters/templates/"
    os.makedirs(base_path, exist_ok=True)

    for character in tqdm.tqdm(characters):

        image = templates_maker.create_template(character)
        cv2.imwrite(base_path + character + ".jpg", image)

if __name__ == "__main__":

    main()


text:
export default `
.comment-content p {
  margin: 0;
  padding: 0;
}

.comment-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  padding: 5px 8px;
  color: #000;
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  font-size: 0.94em;
  border-radius: 3px;
  background-color: #F8F8F8;
  border: 1px solid #f1f1f1;
}

.comment-content pre code {
  border: 0px !important;
  background: transparent !important;
  line-height: 1.3em;
}

.comment-content code {
  padding: 0 3px 0 3px;
  color: #000;
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  font-size: 0.94em;
  border-radius: 3px;
  background-color: #F8F8F8;
  border: 1px solid #f1f1f1;
}

.comment-content blockquote {
  color: #666666;
  margin: 3px 0;
  padding-left: 12px;
  border-left: 0.5em #EEE solid;
}

.comment-content ul, .comment-content ol {
  margin: 1em 0;
  padding: 0 0 0 2em;
}

.comment-content a {
  color: #0645ad;
  text-decoration: none;
}
`;


text:
package org.eulerframework.web.module.oauth2.vo;

import java.util.Collection;

/**
 * @author cFrost
 *
 */
public class UserInfo {
    private OAuth2User user;
    private Collection<String> authority;

    public OAuth2User getUser() {
        return user;
    }

    public void setUser(OAuth2User user) {
        this.user = user;
    }

    public Collection<String> getAuthority() {
        return authority;
    }

    public void setAuthority(Collection<String> authority) {
        this.authority = authority;
    }

}


text:
python-logstash
===============

Python logging handler for Logstash.
http://logstash.net/

Changelog
=========
0.4.8
  - Fixed Python 3 issues with JSON serialization.
0.4.7
  - Add couple of sensitive fields to the skip_list
0.4.6
  - Updated field names to match java counterparts supported by logstash crew
0.4.5
  - Allow passing exchange's routing key to AMQP handler
0.4.4
  - Fixed urllib import python3 compatibility.
  - Added long type to easy_types.
0.4.3
  - Added AMQP handler.
0.4.2
  - Updated README
  - Added ``tags`` parameter to handler
0.4.1
  - Added TCP handler.
0.3.1
  - Added support for Python 3
0.2.2
  - Split Handler into Handler and Formatter classes
0.2.1
  - Added support for the new JSON schema in Logstash 1.2.x. See details in
    http://tobrunet.ch/2013/09/logstash-1-2-0-upgrade-notes-included/ and
    https://logstash.jira.com/browse/LOGSTASH-675

    - Added ``version`` parameter. Available values: 1 (Logstash 1.2.x version format), 0 - default (previous version).

Installation
============

Using pip::

  pip install python-logstash

Usage
=====

``LogstashHandler`` is a custom logging handler which sends Logstash messages using UDP.

For example::

  import logging
  import logstash
  import sys

  host = 'localhost'

  test_logger = logging.getLogger('python-logstash-logger')
  test_logger.setLevel(logging.INFO)
  test_logger.addHandler(logstash.LogstashHandler(host, 5959, version=1))
  # test_logger.addHandler(logstash.TCPLogstashHandler(host, 5959, version=1))

  test_logger.error('python-logstash: test logstash error message.')
  test_logger.info('python-logstash: test logstash info message.')
  test_logger.warning('python-logstash: test logstash warning message.')

  # add extra field to logstash message
  extra = {
      'test_string': 'python version: ' + repr(sys.version_info),
      'test_boolean': True,
      'test_dict': {'a': 1, 'b': 'c'},
      'test_float': 1.23,
      'test_integer': 123,
      'test_list': [1, 2, '3'],
  }
  test_logger.info('python-logstash: test extra fields', extra=extra)

When using ``extra`` field make sure you don't use reserved names. From `Python documentation <https://docs.python.org/2/library/logging.html>`_.
     | "The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the `Formatter <https://docs.python.org/2/library/logging.html#logging.Formatter>`_ documentation for more information on which keys are used by the logging system.)"

To use the AMQPLogstashHandler you will need to install pika first.

   pip install pika

For example::

  import logging
  import logstash

  test_logger = logging.getLogger('python-logstash-logger')
  test_logger.setLevel(logging.INFO)
  test_logger.addHandler(logstash.AMQPLogstashHandler(host='localhost', version=1))

  test_logger.info('python-logstash: test logstash info message.')
  try:
      1/0
  except:
      test_logger.exception('python-logstash-logger: Exception with stack trace!')

Using with Django
=================

Modify your ``settings.py`` to integrate ``python-logstash`` with Django's logging::

  LOGGING = {
    ...
    'handlers': {
        'logstash': {
            'level': 'DEBUG',
            'class': 'logstash.LogstashHandler',
            'host': 'localhost',
            'port': 5959, # Default value: 5959
            'version': 1, # Version of logstash event schema. Default value: 0 (for backward compatibility of the library)
            'message_type': 'logstash',  # 'type' field in logstash message. Default value: 'logstash'.
            'fqdn': False, # Fully qualified domain name. Default value: false.
            'tags': ['tag1', 'tag2'], # list of tags. Default: None.
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['logstash'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
    ...
  }

Example Logstash Configuration
==============================

Example Logstash Configuration (``logstash.conf``) for Receiving Events from python-logstash is::

  input {
    udp {
      port => 5959
      codec => json
    }
  }
  output {
    stdout {
      codec => rubydebug
    }
  }

For TCP input you need to change the logstash's input to ``tcp`` and modify django log handler's class to ``logstash.TCPLogstashHandler``


text:
/**************************************************************************/
/*!
    @file     ssd1306_i2c.h
    @author   K. Townsend (microBuilder.eu)

    @section LICENSE

    Software License Agreement (BSD License)

    Copyright (c) 2012 K. Townsend
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holders nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef __SSD1306_I2C_H__
#define __SSD1306_I2C_H__

#ifdef __cplusplus
extern "C" {
#endif

#include "projectconfig.h"

#include "drivers/displays/smallfonts.h"

/*=========================================================================
    Display Size
    -----------------------------------------------------------------------
    The driver is used in multiple displays (128x64, 128x32, etc.).
    Select the appropriate display below to create an appropriately
    sized framebuffer, etc.

    SSD1306_128_64  128x64 pixel display

    SSD1306_128_32  128x32 pixel display

    You also need to set the LCDWIDTH and LCDHEIGHT defines to an
    appropriate size

    -----------------------------------------------------------------------*/
    #define SSD1306_128_64
    // #define SSD1306_128_32

    #if defined SSD1306_128_64 && defined SSD1306_128_32
      #error "Only one SSD1306 display can be specified at once in ssd1306.h"
    #endif
    #if !defined SSD1306_128_64 && !defined SSD1306_128_32
      #error "At least one SSD1306 display must be specified in ssd1306.h"
    #endif

    #if defined SSD1306_128_64
      #define SSD1306_LCDWIDTH            (128)
      #define SSD1306_LCDHEIGHT           (64)
    #endif
    #if defined SSD1306_128_32
      #define SSD1306_LCDWIDTH            (128)
      #define SSD1306_LCDHEIGHT           (32)
    #endif
/*=========================================================================*/

/*=========================================================================
    I2C Address - 011110+SA0 ... 0x3C for SA0 = 0, 0x3D for SA0 = 1
    ---------------------------------------------------------------------*/
    #define SSD1306_I2C_ADDRESS           (0x3D << 1)
    #define SSD1306_I2C_READWRITE         (0x01)
/*=========================================================================*/

/*=========================================================================
    Commands
    ---------------------------------------------------------------------*/
    #define SSD1306_SETCONTRAST           0x81
    #define SSD1306_DISPLAYALLON_RESUME   0xA4
    #define SSD1306_DISPLAYALLON          0xA5
    #define SSD1306_NORMALDISPLAY         0xA6
    #define SSD1306_INVERTDISPLAY         0xA7
    #define SSD1306_DISPLAYOFF            0xAE
    #define SSD1306_DISPLAYON             0xAF
    #define SSD1306_SETDISPLAYOFFSET      0xD3
    #define SSD1306_SETCOMPINS            0xDA
    #define SSD1306_SETVCOMDETECT         0xDB
    #define SSD1306_SETDISPLAYCLOCKDIV    0xD5
    #define SSD1306_SETPRECHARGE          0xD9
    #define SSD1306_SETMULTIPLEX          0xA8
    #define SSD1306_SETLOWCOLUMN          0x00
    #define SSD1306_SETHIGHCOLUMN         0x10
    #define SSD1306_SETSTARTLINE          0x40
    #define SSD1306_MEMORYMODE            0x20
    #define SSD1306_COMSCANINC            0xC0
    #define SSD1306_COMSCANDEC            0xC8
    #define SSD1306_SEGREMAP              0xA0
    #define SSD1306_CHARGEPUMP            0x8D
    #define SSD1306_EXTERNALVCC           0x01
    #define SSD1306_INTERNALVCC           0x02
    #define SSD1306_SWITCHCAPVCC          0x02
/*=========================================================================*/

err_t ssd1306Init ( uint8_t vccstate );
void    ssd1306DrawPixel ( uint8_t x, uint8_t y );
void    ssd1306ClearPixel ( uint8_t x, uint8_t y );
uint8_t ssd1306GetPixel ( uint8_t x, uint8_t y );
void    ssd1306ClearScreen ( void );
void    ssd1306Refresh ( void );
void    ssd1306DrawString( uint16_t x, uint16_t y, char* text, struct FONT_DEF font );
void    ssd1306ShiftFrameBuffer( uint8_t height );

#ifdef __cplusplus
}
#endif

#endif


text:
#include "powerSleep.h"

#include <Arduino.h>
#include <Wire.h>
#include <avr/sleep.h>
#include <avr/power.h>

/***************************************\
 * Function Name: enterSleep()
 * Purpose:       Put the controller to
 *                "sleep" (low-power).
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *   Setup sleep options
 *   Put processor to sleep
 *   Continue on wake-up
 *   Return
\***************************************/

void enterSleep()
{
  /*** Setup Sleep options ***/

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);  // Lowest powerdown mode
  sleep_enable();                       // Enable sleep

  /*** Put processor to sleep ***/

  sleep_mode();

  /*** Continue ***/

  sleep_disable();

  return;
}

/**********************************************\
 * Function Name: disableUnneededPeripherals
 * Purpose:       Cut all power to peripherals
 *                to save battery life. Some
 *                will be turned on again
 *                temporarily.
 * Inputs:        None
 * Outputs:       None
 * Pseudocode:
 *   Disable ADC
 *   Disable Timer0
 *   Disable Timer1
 *   Disable Timer2
 *   Disable TWI
 *   Disable USART0
 *   Disable SPI
 *   Return
\**********************************************/

void disableUnneededPeripherals()
{
  /*** Disable Uneeded Peripherals ***/
  ADCSRA = 0;   // Disable ADC
  power_adc_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_timer2_disable();
  power_twi_disable();
  power_usart0_disable();
  power_spi_disable();

  return;
}

/**********************************\
 * Function Name: twiPowerUp()
 * Purpose:       Enable power to
 *                the TWI interface
 *                when needed.
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *  Power on the TWI interface
 *  Initialize the TWI class
 *  Return
\**********************************/

void twiPowerUp()
{
  power_twi_enable();
  _delay_ms(10);
  Wire.begin();
  _delay_ms(10);

  return;
}

/**********************************\
 * Function Name: twiPowerDown()
 * Purpose:       Disable power to
 *                the TWI interface
 *                when finished.
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *  Power down the TWI interface
 *  Return
\**********************************/

void twiPowerDown()
{
  power_twi_disable();

  return;
}

/*************************************\
 * Function Name: serialPowerUp()
 * Purpose:       Enable power to
 *                the serial interface
 *                when needed.
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *  Power on the serial interface
 *  Pause 10 miliseconds
 *  Initialize Serial at 9600 Baud
 *  Pause 10 miliseconds
 *  Prompt user
 *  Return
\*************************************/

void serialPowerUp()
{
  power_usart0_enable();
  _delay_ms(10);
  Serial.begin(9600);
  _delay_ms(10);
  Serial.print(F(">> Logger: Logger ready.\n>> User:   "));

  return;
}

/*************************************\
 * Function Name: serialPowerDown()
 * Purpose:       Disable power to
 *                the serial interface
 *                when finished.
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *  Power down the serial interface
 *  Return
\*************************************/

void serialPowerDown()
{
  power_usart0_disable();

  return;
}

/**********************************\
 * Function Name: SDPowerUp()
 * Purpose:       Enable power to
 *                the SD Card when
 *                needed.
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *  Power on the SPI interface
 *  Enable power to the SD Card
 *  Return
\**********************************/

void SDPowerUp()
{
  power_spi_enable();
  digitalWrite(4, LOW);

  return;
}

/**********************************\
 * Function Name: SDPowerDown()
 * Purpose:       Disable power to
 *                the SD Card when
 *                finished.
 * Inputs:        None
 * Outputs:       None
 * pseudocode:
 *  Cut power to the SD Card
 *  Power down the SPI interface
 *  Return
\**********************************/

void SDPowerDown()
{
  digitalWrite(4, HIGH);  // Cut power to the SD Card
  power_spi_disable();    // Power down the SPI interface

  return;
}


text:
package org.efaps.esjp.accounting.report.balance;

import org.efaps.admin.event.Parameter;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.esjp.accounting.report.balance.BalanceReport316DS_Base.Bean316;
import org.efaps.esjp.accounting.util.AccountingSettings;
import org.efaps.util.EFapsException;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 *
 */
@EFapsUUID("29bd591f-f26a-4cb7-a582-7543fe87827c")
@EFapsApplication("eFapsApp-Accounting")
public abstract class BalanceReport316DS_Base
    extends AbstractBalanceReportDS<Bean316>
{

    /**
     * {@inheritDoc}
     */
    @Override
    public Bean316 getBean(final Parameter _parameter)
        throws EFapsException
    {
        return new Bean316();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getKey(final Parameter _parameter)
        throws EFapsException
    {
        return AccountingSettings.PERIOD_REPORT316ACCOUNT;
    }

    public static class Bean316
        extends AbstractDataBean
    {

    }
}


text:
Installation
============

## Step 1: Install with Composer

```bash
composer require scheb/tombstone-logger
```

## Step 2: Define a tombstone function

The easiest way is to define a function `tombstone(string ...$arguments): void` in the global scope, which is sending
tombstone calls to the graveyard.

The library is shipped with a standard implementation. Include `tombstone-function.php` from the logger's directory in
your bootstrap. It is recommended to define this function as early as possible, so that executed code (which potentially
can contain tombstones) doesn't run into "Call to undefined function" errors.

```php
<?php
require 'vendor/scheb/tombstone-logger/tombstone-function.php';
```

Alternatively, you can name the function however you like or place it in a namespace. You can also create a class static
method. The only requirements are: it has to be a function or class static method (class instance methods, don't work),
and it has to take strings as arguments. You can have multiple tombstone functions, it's up to you.

If you do so, when you want to [generate reports](../analyzer/index.md), please remember to configure the fully
qualified names of your tombstone functions in the [analyzer's YAML configuration](../analyzer/configuration.md).

## Step 3: Create a graveyard

The graveyard is the central component responsible for logging calls to tombstones. The simplest way to create a
graveyard is this. Include the code in your bootstrap right after defining the tombstone function.

```php
<?php

use Scheb\Tombstone\Logger\Graveyard\GraveyardBuilder;

(new GraveyardBuilder())
    // Absolute path to the directory containing all the code that can have tombstones.
    ->rootDirectory(__DIR__.'/src')
    ->autoRegister()
    ->build();
```

## Step 4: Register a handler

By default, the graveyard isn't doing anything with the tombstone calls. You have to register a
handler.

What you usually want is the `StreamHandler`, which writes formatted log records to a file:

```php
<?php

use Scheb\Tombstone\Logger\Handler\StreamHandler;

$streamHandler = new StreamHandler('logs/tombstones.log');
```

If you want to [generate reports](../analyzer/index.md) you need the `AnalyzerLogHandler`:

```php
<?php

use Scheb\Tombstone\Logger\Handler\AnalyzerLogHandler;

$analyzerLogHandler = new AnalyzerLogHandler('logs/tombstones');
```

Register handlers to the graveyard via the `GraveyardBuilder`:

```php
<?php

use Scheb\Tombstone\Logger\Graveyard\GraveyardBuilder;

(new GraveyardBuilder())
    ->rootDirectory(__DIR__.'/src')
    ->autoRegister()
    ->withHandler($streamHandler)
    ->withHandler($analyzerLogHandler)  // You can add as many as you want
    ->build();
```

### Further Steps

See [all configuration options](graveyard.md) of the `GraveyardBuilder`.

Read more how to configure [handlers and formatters](handlers_formatters.md) or how to write your own
ones.


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifndef _WIN32

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DISABLE_PCSC_WINPR

/**
 * PCSC-WinPR (optional for Mac OS X):
 *
 * PCSC-WinPR is a static build of libpcsclite with
 * minor modifications meant to avoid an ABI conflict.
 *
 * At this point, it is only a work in progress, as I was not
 * yet able to make it work properly. However, if we could make it
 * work, we might be able to build against a version of pcsc-lite
 * that doesn't have issues present in Apple's SmartCard Services.
 *
 * Patch pcsc-lite/src/PCSC/wintypes.h:
 * Change "unsigned long" to "unsigned int" for
 *
 * typedef unsigned int ULONG;
 * typedef unsigned int DWORD;
 *
 * This is important as ULONG and DWORD are supposed to be 32-bit,
 * but unsigned long on 64-bit OS X is 64-bit, not 32-bit.
 * More importantly, Apple's SmartCard Services uses unsigned int,
 * while vanilla pcsc-lite still uses unsigned long.
 *
 * Patch pcsc-lite/src/PCSC/pcsclite.h.in:
 *
 * Add the WinPR_PCSC_* definitions that follow "#define WinPR_PCSC"
 * in this source file at the beginning of the pcsclite.h.in.
 *
 * Change "unsigned long" to "unsigned int" in the definition
 * of the SCARD_IO_REQUEST structure:
 *
 * unsigned int dwProtocol;
 * unsigned int cbPciLength;
 *
 * Configure pcsc-lite with the following options (Mac OS X):
 *
 * ./configure --enable-static --prefix=/usr --program-suffix=winpr
 *	--enable-usbdropdir=/usr/libexec/SmartCardServices/drivers
 *	--enable-confdir=/etc --enable-ipcdir=/var/run
 *
 * Build pcsc-lite, and then copy libpcsclite.a to libpcsc-winpr.a:
 *
 * make
 * cp ./src/.libs/libpcsclite.a libpcsc-winpr.a
 *
 * Validate that libpcsc-winpr.a has a modified ABI:
 *
 * nm libpcsc-winpr.a | grep " T " | grep WinPR
 *
 * If the ABI has been successfully modified, you should
 * see pcsc-lite functions prefixed with "WinPR_PCSC_".
 *
 * You can keep this custom pcsc-lite build for later.
 * To install the library, copy it to /usr/lib or /usr/local/lib.
 *
 * The FreeRDP build system will then automatically pick it up
 * as long as it is present on the system. To ensure PCSC-WinPR
 * is properly detected at cmake generation time, look for the
 * following debug output:
 *
 * -- Found PCSC-WinPR: /usr/lib/libpcsc-winpr.a
 */

#if 0
#define WinPR_PCSC

#define SCardEstablishContext WinPR_PCSC_SCardEstablishContext
#define SCardReleaseContext WinPR_PCSC_SCardReleaseContext
#define SCardIsValidContext WinPR_PCSC_SCardIsValidContext
#define SCardConnect WinPR_PCSC_SCardConnect
#define SCardReconnect WinPR_PCSC_SCardReconnect
#define SCardDisconnect WinPR_PCSC_SCardDisconnect
#define SCardBeginTransaction WinPR_PCSC_SCardBeginTransaction
#define SCardEndTransaction WinPR_PCSC_SCardEndTransaction
#define SCardStatus WinPR_PCSC_SCardStatus
#define SCardGetStatusChange WinPR_PCSC_SCardGetStatusChange
#define SCardControl WinPR_PCSC_SCardControl
#define SCardTransmit WinPR_PCSC_SCardTransmit
#define SCardListReaderGroups WinPR_PCSC_SCardListReaderGroups
#define SCardListReaders WinPR_PCSC_SCardListReaders
#define SCardFreeMemory WinPR_PCSC_SCardFreeMemory
#define SCardCancel WinPR_PCSC_SCardCancel
#define SCardGetAttrib WinPR_PCSC_SCardGetAttrib
#define SCardSetAttrib WinPR_PCSC_SCardSetAttrib

#define g_rgSCardT0Pci WinPR_PCSC_g_rgSCardT0Pci
#define g_rgSCardT1Pci WinPR_PCSC_g_rgSCardT1Pci
#define g_rgSCardRawPci WinPR_PCSC_g_rgSCardRawPci
#endif

#ifdef WITH_WINPR_PCSC
extern void* WinPR_PCSC_SCardEstablishContext();
extern void* WinPR_PCSC_SCardReleaseContext();
extern void* WinPR_PCSC_SCardIsValidContext();
extern void* WinPR_PCSC_SCardConnect();
extern void* WinPR_PCSC_SCardReconnect();
extern void* WinPR_PCSC_SCardDisconnect();
extern void* WinPR_PCSC_SCardBeginTransaction();
extern void* WinPR_PCSC_SCardEndTransaction();
extern void* WinPR_PCSC_SCardStatus();
extern void* WinPR_PCSC_SCardGetStatusChange();
extern void* WinPR_PCSC_SCardControl();
extern void* WinPR_PCSC_SCardTransmit();
extern void* WinPR_PCSC_SCardListReaderGroups();
extern void* WinPR_PCSC_SCardListReaders();
extern void* WinPR_PCSC_SCardFreeMemory();
extern void* WinPR_PCSC_SCardCancel();
extern void* WinPR_PCSC_SCardGetAttrib();
extern void* WinPR_PCSC_SCardSetAttrib();
#endif

struct _PCSCFunctionTable
{
	void* pfnSCardEstablishContext;
	void* pfnSCardReleaseContext;
	void* pfnSCardIsValidContext;
	void* pfnSCardConnect;
	void* pfnSCardReconnect;
	void* pfnSCardDisconnect;
	void* pfnSCardBeginTransaction;
	void* pfnSCardEndTransaction;
	void* pfnSCardStatus;
	void* pfnSCardGetStatusChange;
	void* pfnSCardControl;
	void* pfnSCardTransmit;
	void* pfnSCardListReaderGroups;
	void* pfnSCardListReaders;
	void* pfnSCardFreeMemory;
	void* pfnSCardCancel;
	void* pfnSCardGetAttrib;
	void* pfnSCardSetAttrib;
};
typedef struct _PCSCFunctionTable PCSCFunctionTable;

PCSCFunctionTable g_PCSC_Link = { 0 };

int PCSC_InitializeSCardApi_Link(void)
{
	int status = -1;

#ifdef DISABLE_PCSC_WINPR
	return -1;
#endif

#ifdef WITH_WINPR_PCSC
	g_PCSC_Link.pfnSCardEstablishContext = (void*) WinPR_PCSC_SCardEstablishContext;
	g_PCSC_Link.pfnSCardReleaseContext = (void*) WinPR_PCSC_SCardReleaseContext;
	g_PCSC_Link.pfnSCardIsValidContext = (void*) WinPR_PCSC_SCardIsValidContext;
	g_PCSC_Link.pfnSCardConnect = (void*) WinPR_PCSC_SCardConnect;
	g_PCSC_Link.pfnSCardReconnect = (void*) WinPR_PCSC_SCardReconnect;
	g_PCSC_Link.pfnSCardDisconnect = (void*) WinPR_PCSC_SCardDisconnect;
	g_PCSC_Link.pfnSCardBeginTransaction = (void*) WinPR_PCSC_SCardBeginTransaction;
	g_PCSC_Link.pfnSCardEndTransaction = (void*) WinPR_PCSC_SCardEndTransaction;
	g_PCSC_Link.pfnSCardStatus = (void*) WinPR_PCSC_SCardStatus;
	g_PCSC_Link.pfnSCardGetStatusChange = (void*) WinPR_PCSC_SCardGetStatusChange;
	g_PCSC_Link.pfnSCardControl = (void*) WinPR_PCSC_SCardControl;
	g_PCSC_Link.pfnSCardTransmit = (void*) WinPR_PCSC_SCardTransmit;
	g_PCSC_Link.pfnSCardListReaderGroups = (void*) WinPR_PCSC_SCardListReaderGroups;
	g_PCSC_Link.pfnSCardListReaders = (void*) WinPR_PCSC_SCardListReaders;
	//g_PCSC_Link.pfnSCardFreeMemory = (void*) WinPR_PCSC_SCardFreeMemory;
	g_PCSC_Link.pfnSCardFreeMemory = (void*) NULL;
	g_PCSC_Link.pfnSCardCancel = (void*) WinPR_PCSC_SCardCancel;
	g_PCSC_Link.pfnSCardGetAttrib = (void*) WinPR_PCSC_SCardGetAttrib;
	g_PCSC_Link.pfnSCardSetAttrib = (void*) WinPR_PCSC_SCardSetAttrib;

	status = 1;
#endif

	return status;
}

#endif


text:
const test = require('ava')
const Koa = require('../../helpers/koaMock')
const renderText = require('../../../server/render/text')

test('ok', function *(t) {
  t.plan(1)
  const koa = new Koa()
  renderText.apply(koa)
  t.is(koa.body, 'https://example.com/0123456789abcdef0123456789abcdef.png')
})


text:
package org.geotools.feature.collection;

import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;

import org.geotools.feature.FeatureIterator;
import org.opengis.feature.Feature;

/**
 * A closeable iterator wrapped around a provided feature iterator.
 *
 * @see org.geotools.data.DataUtilities#iterator(org.geotools.feature.FeatureIterator)
 * @see org.geotools.data.DataUtilities#close(java.util.Iterator)
 * @author Jody Garnett (LISAsoft)
 */
public class BridgeIterator<F extends Feature> implements Iterator<F>, Closeable {
    FeatureIterator<F> delegate;
    public BridgeIterator(FeatureIterator<F> features) {
        this.delegate = features;
    }

    @Override
    public boolean hasNext() {
        return delegate.hasNext();
    }

    @Override
    public F next() {
        return delegate.next();
    }

    @Override
    public void remove() {
    }

    @Override
    public void close() throws IOException {
        delegate.close();
    }
}


text:
layout: post
title: 2007 Chevrolet Cobalt Cabin Air Filter Replacement
tags: [automotive, diy]
keywords: [2007 chevrolet cobalt cabin air filter, chevrolet cobalt cabin air filter, chevrolet cobalt, cobalt, cabin air filter]
image: /images/2007-chevrolet-cobalt-cabin-air-filter/cabin-air-filter-box.jpg
---

The other day my wife noticed that my car wasn't smelling too fresh. She doesn't ride in my car that often since [we bought a van]({{ site.url }}/we-bought-a-van/), so I figured that the smell had been building for some time. I figured I might as well change the cabin air filter - after all, it had been *three years since* I replaced said cabin air filter.

**Skip my ramblings and [jump to the installation steps below!](#onto-the-steps)**

Three years ago I used an [ACDelco brand cabin air filter](https://www.amazon.com/gp/product/B000EPT390/?tag=hendrixjoseph-20). Back then it cost me $18.59.

Yeah, I keep records - plus it's in my Amazon order history.

This time I opted for a [Fram brand cabin air filter](https://www.amazon.com/gp/product/B001CEJGUS/?tag=hendrixjoseph-20). I'm not a huge fan of Fram - their products are sometimes a bit sub-par - but the price was right. It was $13.97, minus a 15% discount of $2.10 for using Amazon's "subscribe and save" option.

The subscribe and save means they'll ship me one every six months. I'm not sure I'll need a new cabin air filter every six months, especially considering I went three years on the last one. Thankfully, I can cancel the subscribe and save - there's no obligation.

*Keep in mind these are the prices I paid at the times I ordered. Amazon's prices fluctuate frequently, so the prices might be different than what I paid.*

## Similar Makes, Models, and Years

My Chevy Cobalt is a 2007 model year, which is a part of the first (and only in the US) generation. This generation had seven years in it, and the installation steps should be similar to the other years:

* 2004 Chevrolet Cobalt
* 2005 Chevrolet Cobalt
* 2006 Chevrolet Cobalt
* 2007 Chevrolet Cobalt
* 2008 Chevrolet Cobalt
* 2009 Chevrolet Cobalt
* 2010 Chevrolet Cobalt

Since the Cobalt is on the [GM Delta Platform](https://en.wikipedia.org/wiki/GM_Delta_platform), I would expect the procedure to be similar, if not identical to the other cars on the platform. The other cars are, in the US, the Saturn Ion, the Pontiac G5, and the Chevrolet HHR.

The applicable years for each of the other cars are as follows:

### Saturn Ion

* 2003 Saturn Ion
* 2004 Saturn Ion
* 2005 Saturn Ion
* 2006 Saturn Ion
* 2007 Saturn Ion

### Pontiac G5

* 2005 Pontiac G5
* 2006 Pontiac G5
* 2007 Pontiac G5
* 2008 Pontiac G5
* 2009 Pontiac G5

### Chevrolet HHR

* 2006 Chevrolet HHR
* 2007 Chevrolet HHR
* 2008 Chevrolet HHR
* 2009 Chevrolet HHR
* 2010 Chevrolet HHR
* 2011 Chevrolet HHR

## Onto the steps

### 1. Open the glove box.

![The glove box, unopened.](/images/2007-chevrolet-cobalt-cabin-air-filter/closed-glove-box.jpg)
*The glove box, unopened. Do I really need to tell you how to open it?*

### 2. Remove stuff from the glove box and set aside.

### 3. Disconnect the hanger on the right side of the glove box.

![Glove Box hanger on the right side.](/images/2007-chevrolet-cobalt-cabin-air-filter/glove-box-hanger.jpg)
*Glove Box hanger on the right side.*

### 4. Pull the glove box stoppers/retainers inward on either side of the glove box so that they can go past their holding area.

![The open glove box.](/images/2007-chevrolet-cobalt-cabin-air-filter/open-glove-box.jpg)
*The glove box opened with the retainers labeled, as well as the hanger from the previous step.*

### 5. Fully open the glove box.

![Fully opened glove box.](/images/2007-chevrolet-cobalt-cabin-air-filter/behind-the-glove-box.jpg)
*The fully opened glove box. If you skipped step 2, the stuff in the glove box is probably now on the floor.*

### 5. Open the door to the cabin air filter.

![The three snap-latches](/images/2007-chevrolet-cobalt-cabin-air-filter/the-three-snap-latches.jpg)
*There are three snap-latches that keep the door closed. They easily open from the top side.*

### 6. Remove the cabin air filter by pulling it straight out.

![The dirty cabin air filter still installed.](/images/2007-chevrolet-cobalt-cabin-air-filter/dirty-cabin-air-filter-still-installed.jpg)
*The dirty cabin air filter still installed. Note the air flow direction.*

### 7. Verify the new cabin air filter is the correct part.

![The old cabin air filter next to the dirty cabin air filter.](/images/2007-chevrolet-cobalt-cabin-air-filter/dirty-and-new-cabin-air-filter.jpg)
*The old cabin air filter next to the dirty cabin air filter.*

### 8. Installation is the reverse of removal.

Make sure you install the cabin air filter such that the airflow is in the right direction. It won't be the end of the world if you install it backward, but you might not get as a decent a breeze from your blower motor.

Or nothing will happen. I don't know, I put it in right.


text:
Quickstarts
===========

Welcome the fabric quickstarts which demonstrates how to use fabric with various technologies.

The quickstarts are categorized accordingly to the container being used:

* [cdi](cdi) - examples for using standalone CDI containers
* [java](java) - examples for standalone Java applications
* [karaf](karaf) - examples for Apache Karaf containers (OSGi)
* [spring](spring) - examples for using Java applications with Spring
* [spring-boot](spring-boot) - examples for using Spring Boot
* [vert](vertx) - examples using [Vert.x](http://vertx.io/)
* [war](war) - examples as WAR deployment which can run on containers such as Apache Tomcat, Jetty, and Wildfly


text:
package com.indyzalab.appversioncontroller.version.object;

import android.content.Context;

import com.google.gson.annotations.SerializedName;
import com.indyzalab.appversioncontroller.R;

public class AppVersion {

    @SerializedName("is_forced")
    private boolean isForcedUpdate;

    @SerializedName("is_recommended")
    private boolean isRecommendedUpdate;

    @SerializedName("version")
    private String appVersion = "";

    @SerializedName("title")
    private String title = "";

    @SerializedName("description")
    private String description = "";

    @SerializedName("enable_link")
    private boolean enableLink;

    @SerializedName("link_title")
    private String linkTitle = "";

    @SerializedName("link_url")
    private String linkUrl = "";

    @SerializedName("allow_dont_show_again")
    private boolean allowDontShowAgain;

    @SerializedName("can_repeat_alert")
    private boolean canRepeatAlert;

    @SerializedName("repeat_alert_every")
    private int repeatAlertAfter;

    public AppVersion(boolean isForcedUpdate, boolean isRecommendedUpdate, String appVersion
            , String title, String description, boolean enableLink, String linkTitle, String linkUrl
            , boolean allowDontShowAgain, boolean canRepeatAlert, int repeatAlertAfter) {
        this.isForcedUpdate = isForcedUpdate;
        this.isRecommendedUpdate = isRecommendedUpdate;
        this.appVersion = appVersion;
        this.title = title;
        this.description = description;
        this.enableLink = enableLink;
        this.linkTitle = linkTitle;
        this.linkUrl = linkUrl;
        this.allowDontShowAgain = allowDontShowAgain;
        this.canRepeatAlert = canRepeatAlert;
        this.repeatAlertAfter = repeatAlertAfter;
    }

    public void setIsForcedUpdate(boolean isForcedUpdate) {
        this.isForcedUpdate = isForcedUpdate;
    }

    public boolean isForcedUpdate() {
        return isForcedUpdate;
    }

    public boolean isRecommendedUpdate() {
        return isRecommendedUpdate;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getUpdateTitle(Context mContext) {
        if(isEnableLink()){
            return getLinkTitle();
        }else{
            return mContext.getString(R.string.update);
        }
    }

    public boolean isEnableLink() {
        return enableLink;
    }

    private String getLinkTitle() {
        return linkTitle;
    }

    public String getLinkUrl() {
        return linkUrl;
    }

    public boolean isAllowDontShowAgain() {
        return allowDontShowAgain;
    }

    public boolean isCanRepeatAlert() {
        return canRepeatAlert;
    }

    public int getRepeatAlertAfter() {
        return repeatAlertAfter;
    }

    @Override
    public String toString() {
        return "AppVersion{" +
                "isForcedUpdate=" + isForcedUpdate +
                ", isRecommendedUpdate=" + isRecommendedUpdate +
                ", appVersion='" + appVersion + '\'' +
                ", title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", enableLink=" + enableLink +
                ", linkTitle='" + linkTitle + '\'' +
                ", linkUrl='" + linkUrl + '\'' +
                ", allowDontShowAgain=" + allowDontShowAgain +
                ", canRepeatAlert=" + canRepeatAlert +
                ", repeatAlertAfter=" + repeatAlertAfter +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof AppVersion)) return false;

        AppVersion that = (AppVersion) o;

        if (isForcedUpdate() != that.isForcedUpdate()) return false;
        if (isRecommendedUpdate() != that.isRecommendedUpdate()) return false;
        if (isEnableLink() != that.isEnableLink()) return false;
        if (isAllowDontShowAgain() != that.isAllowDontShowAgain()) return false;
        if (isCanRepeatAlert() != that.isCanRepeatAlert()) return false;
        if (getRepeatAlertAfter() != that.getRepeatAlertAfter()) return false;
        if (!getAppVersion().equals(that.getAppVersion())) return false;
        if (!getTitle().equals(that.getTitle())) return false;
        if (!getDescription().equals(that.getDescription())) return false;
        if (!getLinkTitle().equals(that.getLinkTitle())) return false;
        return getLinkUrl().equals(that.getLinkUrl());

    }

    @Override
    public int hashCode() {
        int result = (isForcedUpdate() ? 1 : 0);
        result = 31 * result + (isRecommendedUpdate() ? 1 : 0);
        result = 31 * result + getAppVersion().hashCode();
        result = 31 * result + getTitle().hashCode();
        result = 31 * result + getDescription().hashCode();
        result = 31 * result + (isEnableLink() ? 1 : 0);
        result = 31 * result + getLinkTitle().hashCode();
        result = 31 * result + getLinkUrl().hashCode();
        result = 31 * result + (isAllowDontShowAgain() ? 1 : 0);
        result = 31 * result + (isCanRepeatAlert() ? 1 : 0);
        result = 31 * result + getRepeatAlertAfter();
        return result;
    }
}