text:
using System;
using System.Net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;

namespace OpenSim.Region.CoreModules.Framework.EventQueue
{
    public class EventQueueHelper
    {
        private EventQueueHelper() {} // no construction possible, it's an utility class

        private static byte[] ulongToByteArray(ulong uLongValue)
        {
            // Reverse endianness of RegionHandle
            return new byte[]
            {
                (byte)((uLongValue >> 56) % 256),
                (byte)((uLongValue >> 48) % 256),
                (byte)((uLongValue >> 40) % 256),
                (byte)((uLongValue >> 32) % 256),
                (byte)((uLongValue >> 24) % 256),
                (byte)((uLongValue >> 16) % 256),
                (byte)((uLongValue >> 8) % 256),
                (byte)(uLongValue % 256)
            };
        }

        private static byte[] uintToByteArray(uint uIntValue)
        {
            byte[] resultbytes = Utils.UIntToBytes(uIntValue);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(resultbytes);

            return resultbytes;
        }

        public static OSD buildEvent(string eventName, OSD eventBody)
        {
            OSDMap llsdEvent = new OSDMap(2);
            llsdEvent.Add("message", new OSDString(eventName));
            llsdEvent.Add("body", eventBody);

            return llsdEvent;
        }

        public static OSD EnableSimulator(ulong handle, IPEndPoint endPoint)
        {
            OSDMap llsdSimInfo = new OSDMap(3);

            llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle)));
            llsdSimInfo.Add("IP", new OSDBinary(endPoint.Address.GetAddressBytes()));
            llsdSimInfo.Add("Port", new OSDInteger(endPoint.Port));

            OSDArray arr = new OSDArray(1);
            arr.Add(llsdSimInfo);

            OSDMap llsdBody = new OSDMap(1);
            llsdBody.Add("SimulatorInfo", arr);

            return buildEvent("EnableSimulator", llsdBody);
        }

        public static OSD DisableSimulator(ulong handle)
        {
            //OSDMap llsdSimInfo = new OSDMap(1);

            //llsdSimInfo.Add("Handle", new OSDBinary(regionHandleToByteArray(handle)));

            //OSDArray arr = new OSDArray(1);
            //arr.Add(llsdSimInfo);

            OSDMap llsdBody = new OSDMap(0);
            //llsdBody.Add("SimulatorInfo", arr);

            return buildEvent("DisableSimulator", llsdBody);
        }

        public static OSD CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
                                      IPEndPoint newRegionExternalEndPoint,
                                      string capsURL, UUID agentID, UUID sessionID)
        {
            OSDArray lookAtArr = new OSDArray(3);
            lookAtArr.Add(OSD.FromReal(lookAt.X));
            lookAtArr.Add(OSD.FromReal(lookAt.Y));
            lookAtArr.Add(OSD.FromReal(lookAt.Z));

            OSDArray positionArr = new OSDArray(3);
            positionArr.Add(OSD.FromReal(pos.X));
            positionArr.Add(OSD.FromReal(pos.Y));
            positionArr.Add(OSD.FromReal(pos.Z));

            OSDMap infoMap = new OSDMap(2);
            infoMap.Add("LookAt", lookAtArr);
            infoMap.Add("Position", positionArr);

            OSDArray infoArr = new OSDArray(1);
            infoArr.Add(infoMap);

            OSDMap agentDataMap = new OSDMap(2);
            agentDataMap.Add("AgentID", OSD.FromUUID(agentID));
            agentDataMap.Add("SessionID",  OSD.FromUUID(sessionID));

            OSDArray agentDataArr = new OSDArray(1);
            agentDataArr.Add(agentDataMap);

            OSDMap regionDataMap = new OSDMap(4);
            regionDataMap.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(handle)));
            regionDataMap.Add("SeedCapability", OSD.FromString(capsURL));
            regionDataMap.Add("SimIP", OSD.FromBinary(newRegionExternalEndPoint.Address.GetAddressBytes()));
            regionDataMap.Add("SimPort", OSD.FromInteger(newRegionExternalEndPoint.Port));

            OSDArray regionDataArr = new OSDArray(1);
            regionDataArr.Add(regionDataMap);

            OSDMap llsdBody = new OSDMap(3);
            llsdBody.Add("Info", infoArr);
            llsdBody.Add("AgentData", agentDataArr);
            llsdBody.Add("RegionData", regionDataArr);

            return buildEvent("CrossedRegion", llsdBody);
        }

        public static OSD TeleportFinishEvent(
            ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
            uint locationID, uint flags, string capsURL, UUID agentID)
        {
            OSDMap info = new OSDMap();
            info.Add("AgentID", OSD.FromUUID(agentID));
            info.Add("LocationID", OSD.FromInteger(4)); // TODO what is this?
            info.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(regionHandle)));
            info.Add("SeedCapability", OSD.FromString(capsURL));
            info.Add("SimAccess", OSD.FromInteger(simAccess));
            info.Add("SimIP", OSD.FromBinary(regionExternalEndPoint.Address.GetAddressBytes()));
            info.Add("SimPort", OSD.FromInteger(regionExternalEndPoint.Port));
            info.Add("TeleportFlags", OSD.FromBinary(1L << 4)); // AgentManager.TeleportFlags.ViaLocation

            OSDArray infoArr = new OSDArray();
            infoArr.Add(info);

            OSDMap body = new OSDMap();
            body.Add("Info", infoArr);

            return buildEvent("TeleportFinish", body);
        }

        public static OSD ScriptRunningReplyEvent(UUID objectID, UUID itemID, bool running, bool mono)
        {
            OSDMap script = new OSDMap();
            script.Add("ObjectID", OSD.FromUUID(objectID));
            script.Add("ItemID", OSD.FromUUID(itemID));
            script.Add("Running", OSD.FromBoolean(running));
            script.Add("Mono", OSD.FromBoolean(mono));

            OSDArray scriptArr = new OSDArray();
            scriptArr.Add(script);

            OSDMap body = new OSDMap();
            body.Add("Script", scriptArr);

            return buildEvent("ScriptRunningReply", body);
        }

        public static OSD EstablishAgentCommunication(UUID agentID, string simIpAndPort, string seedcap)
        {
            OSDMap body = new OSDMap(3);
            body.Add("agent-id", new OSDUUID(agentID));
            body.Add("sim-ip-and-port", new OSDString(simIpAndPort));
            body.Add("seed-capability", new OSDString(seedcap));

            return buildEvent("EstablishAgentCommunication", body);
        }

        public static OSD KeepAliveEvent()
        {
            return buildEvent("FAKEEVENT", new OSDMap());
        }

        public static OSD AgentParams(UUID agentID, bool checkEstate, int godLevel, bool limitedToEstate)
        {
            OSDMap body = new OSDMap(4);

            body.Add("agent_id", new OSDUUID(agentID));
            body.Add("check_estate", new OSDInteger(checkEstate ? 1 : 0));
            body.Add("god_level", new OSDInteger(godLevel));
            body.Add("limited_to_estate", new OSDInteger(limitedToEstate ? 1 : 0));

            return body;
        }

        public static OSD InstantMessageParams(UUID fromAgent, string message, UUID toAgent,
            string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
            Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
        {
            OSDMap messageParams = new OSDMap(15);
            messageParams.Add("type", new OSDInteger((int)dialog));

            OSDArray positionArray = new OSDArray(3);
            positionArray.Add(OSD.FromReal(position.X));
            positionArray.Add(OSD.FromReal(position.Y));
            positionArray.Add(OSD.FromReal(position.Z));
            messageParams.Add("position", positionArray);

            messageParams.Add("region_id", new OSDUUID(UUID.Zero));
            messageParams.Add("to_id", new OSDUUID(toAgent));
            messageParams.Add("source", new OSDInteger(0));

            OSDMap data = new OSDMap(1);
            data.Add("binary_bucket", OSD.FromBinary(binaryBucket));
            messageParams.Add("data", data);
            messageParams.Add("message", new OSDString(message));
            messageParams.Add("id", new OSDUUID(transactionID));
            messageParams.Add("from_name", new OSDString(fromName));
            messageParams.Add("timestamp", new OSDInteger((int)timeStamp));
            messageParams.Add("offline", new OSDInteger(offline ? 1 : 0));
            messageParams.Add("parent_estate_id", new OSDInteger(parentEstateID));
            messageParams.Add("ttl", new OSDInteger((int)ttl));
            messageParams.Add("from_id", new OSDUUID(fromAgent));
            messageParams.Add("from_group", new OSDInteger(fromGroup ? 1 : 0));

            return messageParams;
        }

        public static OSD InstantMessage(UUID fromAgent, string message, UUID toAgent,
            string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
            Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket,
            bool checkEstate, int godLevel, bool limitedToEstate)
        {
            OSDMap im = new OSDMap(2);
            im.Add("message_params", InstantMessageParams(fromAgent, message, toAgent,
            fromName, dialog, timeStamp, offline, parentEstateID,
            position, ttl, transactionID, fromGroup, binaryBucket));

            im.Add("agent_params", AgentParams(fromAgent, checkEstate, godLevel, limitedToEstate));

            return im;
        }

        public static OSD ChatterboxInvitation(UUID sessionID, string sessionName,
            UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog,
            uint timeStamp, bool offline, int parentEstateID, Vector3 position,
            uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
        {
            OSDMap body = new OSDMap(5);
            body.Add("session_id", new OSDUUID(sessionID));
            body.Add("from_name", new OSDString(fromName));
            body.Add("session_name", new OSDString(sessionName));
            body.Add("from_id", new OSDUUID(fromAgent));

            body.Add("instantmessage", InstantMessage(fromAgent, message, toAgent,
            fromName, dialog, timeStamp, offline, parentEstateID, position,
            ttl, transactionID, fromGroup, binaryBucket, true, 0, true));

            OSDMap chatterboxInvitation = new OSDMap(2);
            chatterboxInvitation.Add("message", new OSDString("ChatterBoxInvitation"));
            chatterboxInvitation.Add("body", body);
            return chatterboxInvitation;
        }

        public static OSD ChatterBoxSessionAgentListUpdates(UUID sessionID,
            UUID agentID, bool canVoiceChat, bool isModerator, bool textMute)
        {
            OSDMap body = new OSDMap();
            OSDMap agentUpdates = new OSDMap();
            OSDMap infoDetail = new OSDMap();
            OSDMap mutes = new OSDMap();

            mutes.Add("text", OSD.FromBoolean(textMute));
            infoDetail.Add("can_voice_chat", OSD.FromBoolean(canVoiceChat));
            infoDetail.Add("is_moderator", OSD.FromBoolean(isModerator));
            infoDetail.Add("mutes", mutes);
            OSDMap info = new OSDMap();
            info.Add("info", infoDetail);
            agentUpdates.Add(agentID.ToString(), info);
            body.Add("agent_updates", agentUpdates);
            body.Add("session_id", OSD.FromUUID(sessionID));
            body.Add("updates", new OSD());

            OSDMap chatterBoxSessionAgentListUpdates = new OSDMap();
            chatterBoxSessionAgentListUpdates.Add("message", OSD.FromString("ChatterBoxSessionAgentListUpdates"));
            chatterBoxSessionAgentListUpdates.Add("body", body);

            return chatterBoxSessionAgentListUpdates;
        }

        public static OSD ParcelProperties(ParcelPropertiesPacket parcelPropertiesPacket)
        {
            OSDMap parcelProperties = new OSDMap();
            OSDMap body = new OSDMap();

            OSDArray ageVerificationBlock = new OSDArray();
            OSDMap ageVerificationMap = new OSDMap();
            ageVerificationMap.Add("RegionDenyAgeUnverified",
                OSD.FromBoolean(parcelPropertiesPacket.AgeVerificationBlock.RegionDenyAgeUnverified));
            ageVerificationBlock.Add(ageVerificationMap);
            body.Add("AgeVerificationBlock", ageVerificationBlock);

            // LL sims send media info in this event queue message but it's not in the UDP
            // packet we construct this event queue message from. This should be refactored in
            // other areas of the code so it can all be send in the same message. Until then we will
            // still send the media info via UDP

            //OSDArray mediaData = new OSDArray();
            //OSDMap mediaDataMap = new OSDMap();
            //mediaDataMap.Add("MediaDesc", OSD.FromString(""));
            //mediaDataMap.Add("MediaHeight", OSD.FromInteger(0));
            //mediaDataMap.Add("MediaLoop", OSD.FromInteger(0));
            //mediaDataMap.Add("MediaType", OSD.FromString("type/type"));
            //mediaDataMap.Add("MediaWidth", OSD.FromInteger(0));
            //mediaDataMap.Add("ObscureMedia", OSD.FromInteger(0));
            //mediaDataMap.Add("ObscureMusic", OSD.FromInteger(0));
            //mediaData.Add(mediaDataMap);
            //body.Add("MediaData", mediaData);

            OSDArray parcelData = new OSDArray();
            OSDMap parcelDataMap = new OSDMap();
            OSDArray AABBMax = new OSDArray(3);
            AABBMax.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.AABBMax.X));
            AABBMax.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.AABBMax.Y));
            AABBMax.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.AABBMax.Z));
            parcelDataMap.Add("AABBMax", AABBMax);

            OSDArray AABBMin = new OSDArray(3);
            AABBMin.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.AABBMin.X));
            AABBMin.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.AABBMin.Y));
            AABBMin.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.AABBMin.Z));
            parcelDataMap.Add("AABBMin", AABBMin);

            parcelDataMap.Add("Area", OSD.FromInteger(parcelPropertiesPacket.ParcelData.Area));
            parcelDataMap.Add("AuctionID", OSD.FromBinary(uintToByteArray(parcelPropertiesPacket.ParcelData.AuctionID)));
            parcelDataMap.Add("AuthBuyerID", OSD.FromUUID(parcelPropertiesPacket.ParcelData.AuthBuyerID));
            parcelDataMap.Add("Bitmap", OSD.FromBinary(parcelPropertiesPacket.ParcelData.Bitmap));
            parcelDataMap.Add("Category", OSD.FromInteger((int)parcelPropertiesPacket.ParcelData.Category));
            parcelDataMap.Add("ClaimDate", OSD.FromInteger(parcelPropertiesPacket.ParcelData.ClaimDate));
            parcelDataMap.Add("ClaimPrice", OSD.FromInteger(parcelPropertiesPacket.ParcelData.ClaimPrice));
            parcelDataMap.Add("Desc", OSD.FromString(Utils.BytesToString(parcelPropertiesPacket.ParcelData.Desc)));
            parcelDataMap.Add("GroupID", OSD.FromUUID(parcelPropertiesPacket.ParcelData.GroupID));
            parcelDataMap.Add("GroupPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.GroupPrims));
            parcelDataMap.Add("IsGroupOwned", OSD.FromBoolean(parcelPropertiesPacket.ParcelData.IsGroupOwned));
            parcelDataMap.Add("LandingType", OSD.FromInteger(parcelPropertiesPacket.ParcelData.LandingType));
            parcelDataMap.Add("LocalID", OSD.FromInteger(parcelPropertiesPacket.ParcelData.LocalID));
            parcelDataMap.Add("MaxPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.MaxPrims));
            parcelDataMap.Add("MediaAutoScale", OSD.FromInteger((int)parcelPropertiesPacket.ParcelData.MediaAutoScale));
            parcelDataMap.Add("MediaID", OSD.FromUUID(parcelPropertiesPacket.ParcelData.MediaID));
            parcelDataMap.Add("MediaURL", OSD.FromString(Utils.BytesToString(parcelPropertiesPacket.ParcelData.MediaURL)));
            parcelDataMap.Add("MusicURL", OSD.FromString(Utils.BytesToString(parcelPropertiesPacket.ParcelData.MusicURL)));
            parcelDataMap.Add("Name", OSD.FromString(Utils.BytesToString(parcelPropertiesPacket.ParcelData.Name)));
            parcelDataMap.Add("OtherCleanTime", OSD.FromInteger(parcelPropertiesPacket.ParcelData.OtherCleanTime));
            parcelDataMap.Add("OtherCount", OSD.FromInteger(parcelPropertiesPacket.ParcelData.OtherCount));
            parcelDataMap.Add("OtherPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.OtherPrims));
            parcelDataMap.Add("OwnerID", OSD.FromUUID(parcelPropertiesPacket.ParcelData.OwnerID));
            parcelDataMap.Add("OwnerPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.OwnerPrims));
            parcelDataMap.Add("ParcelFlags", OSD.FromBinary(uintToByteArray(parcelPropertiesPacket.ParcelData.ParcelFlags)));
            parcelDataMap.Add("ParcelPrimBonus", OSD.FromReal(parcelPropertiesPacket.ParcelData.ParcelPrimBonus));
            parcelDataMap.Add("PassHours", OSD.FromReal(parcelPropertiesPacket.ParcelData.PassHours));
            parcelDataMap.Add("PassPrice", OSD.FromInteger(parcelPropertiesPacket.ParcelData.PassPrice));
            parcelDataMap.Add("PublicCount", OSD.FromInteger(parcelPropertiesPacket.ParcelData.PublicCount));
            parcelDataMap.Add("RegionDenyAnonymous", OSD.FromBoolean(parcelPropertiesPacket.ParcelData.RegionDenyAnonymous));
            parcelDataMap.Add("RegionDenyIdentified", OSD.FromBoolean(parcelPropertiesPacket.ParcelData.RegionDenyIdentified));
            parcelDataMap.Add("RegionDenyTransacted", OSD.FromBoolean(parcelPropertiesPacket.ParcelData.RegionDenyTransacted));

            parcelDataMap.Add("RegionPushOverride", OSD.FromBoolean(parcelPropertiesPacket.ParcelData.RegionPushOverride));
            parcelDataMap.Add("RentPrice", OSD.FromInteger(parcelPropertiesPacket.ParcelData.RentPrice));
            parcelDataMap.Add("RequestResult", OSD.FromInteger(parcelPropertiesPacket.ParcelData.RequestResult));
            parcelDataMap.Add("SalePrice", OSD.FromInteger(parcelPropertiesPacket.ParcelData.SalePrice));
            parcelDataMap.Add("SelectedPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.SelectedPrims));
            parcelDataMap.Add("SelfCount", OSD.FromInteger(parcelPropertiesPacket.ParcelData.SelfCount));
            parcelDataMap.Add("SequenceID", OSD.FromInteger(parcelPropertiesPacket.ParcelData.SequenceID));
            parcelDataMap.Add("SimWideMaxPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.SimWideMaxPrims));
            parcelDataMap.Add("SimWideTotalPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.SimWideTotalPrims));
            parcelDataMap.Add("SnapSelection", OSD.FromBoolean(parcelPropertiesPacket.ParcelData.SnapSelection));
            parcelDataMap.Add("SnapshotID", OSD.FromUUID(parcelPropertiesPacket.ParcelData.SnapshotID));
            parcelDataMap.Add("Status", OSD.FromInteger((int)parcelPropertiesPacket.ParcelData.Status));
            parcelDataMap.Add("TotalPrims", OSD.FromInteger(parcelPropertiesPacket.ParcelData.TotalPrims));

            OSDArray UserLocation = new OSDArray(3);
            UserLocation.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.UserLocation.X));
            UserLocation.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.UserLocation.Y));
            UserLocation.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.UserLocation.Z));
            parcelDataMap.Add("UserLocation", UserLocation);

            OSDArray UserLookAt = new OSDArray(3);
            UserLookAt.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.UserLookAt.X));
            UserLookAt.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.UserLookAt.Y));
            UserLookAt.Add(OSD.FromReal(parcelPropertiesPacket.ParcelData.UserLookAt.Z));
            parcelDataMap.Add("UserLookAt", UserLookAt);

            parcelData.Add(parcelDataMap);
            body.Add("ParcelData", parcelData);
            parcelProperties.Add("body", body);
            parcelProperties.Add("message", OSD.FromString("ParcelProperties"));

            return parcelProperties;
        }

        public static OSD GroupMembership(AgentGroupDataUpdatePacket groupUpdatePacket)
        {
            OSDMap groupUpdate = new OSDMap();
            groupUpdate.Add("message", OSD.FromString("AgentGroupDataUpdate"));

            OSDMap body = new OSDMap();
            OSDArray agentData = new OSDArray();
            OSDMap agentDataMap = new OSDMap();
            agentDataMap.Add("AgentID", OSD.FromUUID(groupUpdatePacket.AgentData.AgentID));
            agentData.Add(agentDataMap);
            body.Add("AgentData", agentData);

            OSDArray groupData = new OSDArray();

            foreach (AgentGroupDataUpdatePacket.GroupDataBlock groupDataBlock in groupUpdatePacket.GroupData)
            {
                OSDMap groupDataMap = new OSDMap();
                groupDataMap.Add("ListInProfile", OSD.FromBoolean(false));
                groupDataMap.Add("GroupID", OSD.FromUUID(groupDataBlock.GroupID));
                groupDataMap.Add("GroupInsigniaID", OSD.FromUUID(groupDataBlock.GroupInsigniaID));
                groupDataMap.Add("Contribution", OSD.FromInteger(groupDataBlock.Contribution));
                groupDataMap.Add("GroupPowers", OSD.FromBinary(ulongToByteArray(groupDataBlock.GroupPowers)));
                groupDataMap.Add("GroupName", OSD.FromString(Utils.BytesToString(groupDataBlock.GroupName)));
                groupDataMap.Add("AcceptNotices", OSD.FromBoolean(groupDataBlock.AcceptNotices));

                groupData.Add(groupDataMap);

            }
            body.Add("GroupData", groupData);
            groupUpdate.Add("body", body);

            return groupUpdate;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
{% load i18n xadmin_tags %}

    {% get_language_info for LANGUAGE_CODE as l %}{{ l.name_local }}

  <form id="setlang-form" action="{% url 'xadmin:set_language' %}" method="post" style="display:none;">
    {% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <input id="setlang-id_language" name="language" type="hidden" value="{{ LANGUAGE_CODE }}" />
  </form>

    {% get_language_info_list for LANGUAGES as languages %}
    {% for language in languages %}

 {{ language.name_local }} ({{ language.code }})

    {% endfor %}


text:
"""
Some test functions used to sanity check during development. Not
unit tests.
"""

import sys
sys.path.insert(0, '..')
from clarify_python import clarify

def delete_bundle(client, href):
    """Delete bundle at href."""

    print('*** Deleting ' + href)
    client.delete_bundle(href)

def delete_all_bundles(client):
    """Delete all bundles."""

    client.bundle_list_map(delete_bundle)

def all_tests(apikey):
    """Set API key and call all test functions."""

    client = clarify.Client(apikey)

    print('===== delete_all_bundles() =====')
    delete_all_bundles(client)

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print('Usage: ' + sys.argv[0] + ' <apikey>')
        exit(1)

    all_tests(sys.argv[1])


text:
Opencv project to detect and play with faces detection.

Add the charls chaplin hat and moustache over all faces detected. They are resized to adapt your face.

I have removed green rectangle from webcam capture, but code remains on source code but it's commented.

Also there are som alternative lbp cascades available on code.


text:
import React from 'react';
import DataTable, {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableExpandHeader,
  TableExpandRow,
  TableExpandedRow,
  TableHead,
  TableHeader,
  TableRow,
} from '../../DataTable';
import { initialRows, headers } from './shared';

export default props => (
  <DataTable
    rows={initialRows}
    headers={headers}
    {...props}
    render={({ rows, headers, getHeaderProps, getRowProps, getTableProps }) => (
      <TableContainer title="DataTable" description="With expansion">

          <TableHead>
            <TableRow>
              <TableExpandHeader />
              {headers.map(header => (
                <TableHeader {...getHeaderProps({ header })}>
                  {header.header}
                </TableHeader>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map(row => (
              <React.Fragment key={row.id}>
                <TableExpandRow {...getRowProps({ row })}>
                  {row.cells.map(cell => (
                    <TableCell key={cell.id}>{cell.value}</TableCell>
                  ))}
                </TableExpandRow>
                <TableExpandedRow colSpan={headers.length + 1}>

Expandable row content

Description here

                </TableExpandedRow>
              </React.Fragment>
            ))}
          </TableBody>

      </TableContainer>
    )}
  />
);


text:
<Record>
<Term>Ribavirin</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Ribasphere</Synonym>
<Synonym>Virazole</Synonym>
<Synonym>Copegus</Synonym>
<Synonym>Rebetol</Synonym>
<Synonym>Ribavarin</Synonym>
<Synonym>Ribavirin</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
      Vendor

   back to reports
  <form>

     Vendor:

      <ui-select ng-model="$parent.selected_vendor" on-select="vendorChanged()">
        <ui-select-match placeholder="Select">
          {{$select.selected.name}}
        </ui-select-match>
        <ui-select-choices repeat="vendor.id as vendor in vendors | filter: $select.search">

        </ui-select-choices>
      </ui-select>

      Bill Start Date:

      <input class="form-control" type="text" datepicker-popup="MM/dd/yy" ng-model="start_date" is-open="date_start" datepicker-options="dateOptions" close-text="Close" show-weeks="false" id="date" name="date" style="width:35%;display:inline-block" ng-change="setStartDate()">
      <button type="button" class="btn btn-default" ng-click="openDatePicker($event, 'date_start')"></button>

      Bill End Date:

      <input class="form-control" type="text" datepicker-popup="MM/dd/yy" ng-model="end_date" is-open="date_end" datepicker-options="dateOptions" close-text="Close" show-weeks="false" id="date" name="date" style="width:35%;display:inline-block" ng-change="setEndDate()">
      <button type="button" class="btn btn-default" ng-click="openDatePicker($event, 'date_end')"></button>

      Class/Location:

      <select ng-options="class.id as class.name for class in qb_classes" ng-model="selected_class" ng-change="classChanged()" ng-if="currentIndividual.user.locations_feature" style="width: 100%;"></select>

  </form>

            Name
            Name

            Outstanding
            Outstanding

            Avg. Yearly Volume
            Avg. Yearly Volume

            Time Period
            Time Period

            % in the time Period
            % in the time Period

            # of bills in the time period
            # of bills in the time period

            # of price changes
            # of price changes

          {{vendor.name}}
          ${{vendor.outstanding | number: 2}}
          ${{vendor.average_yearly_volume | number: 2}}
          ${{vendor.total_spend_time_period | number: 2}}
          {{vendor.percent_time_period | number: 2}}%
          {{vendor.bills_time_period}}
          {{vendor.num_price_changes}}


text: Renseigner l'adresse du serveur proxy web


text:
using JetBrains.Application.changes;
using JetBrains.Application.Progress;
using JetBrains.Application.Threading;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Transaction;
using JetBrains.RdBackend.Common.Features.Documents;
using JetBrains.ReSharper.Plugins.Unity.Core.Psi.Modules;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.Util;
using JetBrains.Util.dataStructures;

namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.Core.Psi.Modules
{
    // Rider requires us to have an IProjectFile for the IPsiSourceFiles in the external files module. This is primarily
    // because PSI modifications won't be saved without one. When a PSI transaction completes, Rider looks for a project
    // file for the modified document. If it finds one, it binds the document to the protocol and all changes are passed
    // to the frontend. When the transaction saves, it only saves on the frontend, and because the frontend document has
    // been modified, the changes are saved. Without a project file, the changes are not sent to the frontend, and the
    // frontend document is not modified (and possibly doesn't exist) and therefore nothing is saved.
    // Arguably, the platform should still bind documents that don't have project files.
    // We do not modify .meta files, so we don't need a project file for them (there's too many of them anyway. Perhaps
    // the platform could allow us to create on demand?)
    // ReSharper does not require project files for saving documents (but has its own workarounds for similar issues).
    // Creating project files in the Misc Files project is not allowed - this project needs to be kept in sync with VS.
    [SolutionComponent]
    public class RiderMiscFilesProjectFileManager : IChangeProvider
    {
        private readonly ISolution mySolution;

        public RiderMiscFilesProjectFileManager(Lifetime lifetime,
                                                ISolution solution,
                                                ChangeManager changeManager,
                                                UnityExternalFilesModuleProcessor externalFilesProcessor)
        {
            mySolution = solution;

            changeManager.RegisterChangeProvider(lifetime, this);
            changeManager.AddDependency(lifetime, this, externalFilesProcessor);
        }

        public object Execute(IChangeMap changeMap)
        {
            using (new ProjectModelBatchChangeCookie(mySolution, SimpleTaskExecutor.Instance))
            using (mySolution.Locks.UsingWriteLock())
            {
                foreach (var psiModuleChange in changeMap.GetChanges<PsiModuleChange>())
                {
                    foreach (var fileChange in psiModuleChange.FileChanges)
                    {
                        if (fileChange.Item is not UnityExternalPsiSourceFile file)
                            continue;

                        switch (fileChange.Type)
                        {
                            case PsiModuleChange.ChangeType.Added:
                                // We don't need a project file for meta files
                                if (!file.Location.IsMeta())
                                    AddExternalProjectFiles(file.Location);
                                break;

                            case PsiModuleChange.ChangeType.Removed:
                                RemoveExternalProjectFiles(file.Location);
                                break;

                            case PsiModuleChange.ChangeType.Modified:
                            case PsiModuleChange.ChangeType.Invalidated:
                                break;
                        }
                    }
                }
            }

            return null;
        }

        private void AddExternalProjectFiles(VirtualFileSystemPath path)
        {
            if (mySolution.FindProjectItemsByLocation(path).Count > 0)
                return;

            // Avoid SolutionMiscFiles.CreateMiscFile as this will involve transactions, and loading/saving the document
            // for each file
            DocumentHostProjectFileUtil.CreateMiscFile(mySolution, path);
        }

        private void RemoveExternalProjectFiles(VirtualFileSystemPath path)
        {
            var toRemove = new FrugalLocalList<ProjectItemBase>();
            foreach (var projectItem in mySolution.FindProjectItemsByLocation(path))
            {
                if (projectItem is ProjectItemBase projectFile && projectFile.IsMiscProjectItem())
                    toRemove.Add(projectFile);
            }

            foreach (var projectItemBase in toRemove)
                projectItemBase.DoRemove();
        }
    }
}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/shell_dialogs/select_file_dialog_linux_portal.h"

#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "components/dbus/thread_linux/dbus_thread_linux.h"
#include "dbus/object_path.h"
#include "dbus/property.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/linux/linux_ui_delegate.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#include "ui/strings/grit/ui_strings.h"
#include "url/gurl.h"
#include "url/url_util.h"

namespace ui {

namespace {

constexpr char kDBusMethodNameHasOwner[] = "NameHasOwner";
constexpr char kDBusMethodListActivatableNames[] = "ListActivatableNames";
constexpr char kMethodStartServiceByName[] = "StartServiceByName";

constexpr char kXdgPortalService[] = "org.freedesktop.portal.Desktop";
constexpr char kXdgPortalObject[] = "/org/freedesktop/portal/desktop";

constexpr int kXdgPortalRequiredVersion = 3;

constexpr char kXdgPortalRequestInterfaceName[] =
    "org.freedesktop.portal.Request";
constexpr char kXdgPortalResponseSignal[] = "Response";

constexpr char kFileChooserInterfaceName[] =
    "org.freedesktop.portal.FileChooser";

constexpr char kFileChooserMethodOpenFile[] = "OpenFile";
constexpr char kFileChooserMethodSaveFile[] = "SaveFile";

constexpr char kFileChooserOptionHandleToken[] = "handle_token";
constexpr char kFileChooserOptionAcceptLabel[] = "accept_label";
constexpr char kFileChooserOptionMultiple[] = "multiple";
constexpr char kFileChooserOptionDirectory[] = "directory";
constexpr char kFileChooserOptionFilters[] = "filters";
constexpr char kFileChooserOptionCurrentFilter[] = "current_filter";
constexpr char kFileChooserOptionCurrentFolder[] = "current_folder";
constexpr char kFileChooserOptionCurrentName[] = "current_name";

constexpr int kFileChooserFilterKindGlob = 0;

constexpr char kFileUriPrefix[] = "file://";

// Time to wait for the notification service to start, in milliseconds.
constexpr base::TimeDelta kStartServiceTimeout = base::Seconds(1);

struct FileChooserProperties : dbus::PropertySet {
  dbus::Property<uint32_t> version;

  explicit FileChooserProperties(dbus::ObjectProxy* object_proxy)
      : dbus::PropertySet(object_proxy, kFileChooserInterfaceName, {}) {
    RegisterProperty("version", &version);
  }

  ~FileChooserProperties() override = default;
};

void AppendStringOption(dbus::MessageWriter* writer,
                        const std::string& name,
                        const std::string& value) {
  dbus::MessageWriter option_writer(nullptr);
  writer->OpenDictEntry(&option_writer);

  option_writer.AppendString(name);
  option_writer.AppendVariantOfString(value);

  writer->CloseContainer(&option_writer);
}

void AppendByteStringOption(dbus::MessageWriter* writer,
                            const std::string& name,
                            const std::string& value) {
  dbus::MessageWriter option_writer(nullptr);
  writer->OpenDictEntry(&option_writer);

  option_writer.AppendString(name);

  dbus::MessageWriter value_writer(nullptr);
  option_writer.OpenVariant("ay", &value_writer);

  value_writer.AppendArrayOfBytes(
      reinterpret_cast<const std::uint8_t*>(value.c_str()),
      // size + 1 will include the null terminator.
      value.size() + 1);

  option_writer.CloseContainer(&value_writer);
  writer->CloseContainer(&option_writer);
}

void AppendBoolOption(dbus::MessageWriter* writer,
                      const std::string& name,
                      bool value) {
  dbus::MessageWriter option_writer(nullptr);
  writer->OpenDictEntry(&option_writer);

  option_writer.AppendString(name);
  option_writer.AppendVariantOfBool(value);

  writer->CloseContainer(&option_writer);
}

scoped_refptr<dbus::Bus>* AcquireBusStorageOnBusThread() {
  static base::NoDestructor<scoped_refptr<dbus::Bus>> bus(nullptr);
  if (!*bus) {
    dbus::Bus::Options options;
    options.bus_type = dbus::Bus::SESSION;
    options.connection_type = dbus::Bus::PRIVATE;
    options.dbus_task_runner = dbus_thread_linux::GetTaskRunner();

    *bus = base::MakeRefCounted<dbus::Bus>(options);
  }

  return bus.get();
}

dbus::Bus* AcquireBusOnBusThread() {
  return AcquireBusStorageOnBusThread()->get();
}

void DestroyBusOnBusThread() {
  scoped_refptr<dbus::Bus>* bus_storage = AcquireBusStorageOnBusThread();
  (*bus_storage)->ShutdownAndBlock();

  // If the connection is restarted later on, we need to make sure the entire
  // bus is newly created. Otherwise, references to an old, invalid task runner
  // may persist.
  bus_storage->reset();
}

}  // namespace

SelectFileDialogLinuxPortal::SelectFileDialogLinuxPortal(
    Listener* listener,
    std::unique_ptr<ui::SelectFilePolicy> policy)
    : SelectFileDialogLinux(listener, std::move(policy)) {}

SelectFileDialogLinuxPortal::~SelectFileDialogLinuxPortal() = default;

// static
void SelectFileDialogLinuxPortal::StartAvailabilityTestInBackground() {
  if (GetAvailabilityTestCompletionFlag()->IsSet())
    return;

  dbus_thread_linux::GetTaskRunner()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &SelectFileDialogLinuxPortal::CheckPortalAvailabilityOnBusThread));
}

// static
bool SelectFileDialogLinuxPortal::IsPortalAvailable() {
  if (!GetAvailabilityTestCompletionFlag()->IsSet())
    LOG(WARNING) << "Portal availability checked before test was complete";

  return is_portal_available_;
}

// static
void SelectFileDialogLinuxPortal::DestroyPortalConnection() {
  dbus_thread_linux::GetTaskRunner()->PostTask(
      FROM_HERE, base::BindOnce(&DestroyBusOnBusThread));
}

bool SelectFileDialogLinuxPortal::IsRunning(
    gfx::NativeWindow parent_window) const {
  if (parent_window && parent_window->GetHost()) {
    auto window = parent_window->GetHost()->GetAcceleratedWidget();
    return parent_ && parent_.value() == window;
  }

  return false;
}

void SelectFileDialogLinuxPortal::SelectFileImpl(
    Type type,
    const std::u16string& title,
    const base::FilePath& default_path,
    const FileTypeInfo* file_types,
    int file_type_index,
    const base::FilePath::StringType& default_extension,
    gfx::NativeWindow owning_window,
    void* params,
    const GURL* caller) {
  auto info = base::MakeRefCounted<DialogInfo>(
      base::BindOnce(&SelectFileDialogLinuxPortal::CompleteOpenOnMainThread,
                     this),
      base::BindOnce(&SelectFileDialogLinuxPortal::CancelOpenOnMainThread,
                     this));
  info_ = info;
  info->type = type;
  info->main_task_runner = base::SequencedTaskRunner::GetCurrentDefault();
  listener_params_ = params;

  if (owning_window && owning_window->GetHost()) {
    parent_ = owning_window->GetHost()->GetAcceleratedWidget();
  }

  if (file_types)
    set_file_types(*file_types);

  set_file_type_index(file_type_index);

  PortalFilterSet filter_set = BuildFilterSet();

  // Keep a copy of the filters so the index of the chosen one can be identified
  // and returned to listeners later.
  filters_ = filter_set.filters;

  if (parent_) {
    auto* delegate = ui::LinuxUiDelegate::GetInstance();
    if (delegate &&
        delegate->ExportWindowHandle(
            *parent_,
            base::BindOnce(
                &SelectFileDialogLinuxPortal::SelectFileImplWithParentHandle,
                this, title, default_path, filter_set, default_extension))) {
      // Return early to skip the fallback below.
      return;
    } else {
      LOG(WARNING) << "Failed to export window handle for portal select dialog";
    }
  }

  // No parent, so just use a blank parent handle.
  SelectFileImplWithParentHandle(title, default_path, filter_set,
                                 default_extension, "");
}

bool SelectFileDialogLinuxPortal::HasMultipleFileTypeChoicesImpl() {
  return file_types().extensions.size() > 1;
}

// static
void SelectFileDialogLinuxPortal::CheckPortalAvailabilityOnBusThread() {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  base::AtomicFlag* availability_test_complete =
      GetAvailabilityTestCompletionFlag();
  if (availability_test_complete->IsSet())
    return;

  dbus::Bus* bus = AcquireBusOnBusThread();

  dbus::ObjectProxy* dbus_proxy =
      bus->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS));

  if (IsPortalRunningOnBusThread(dbus_proxy) ||
      IsPortalActivatableOnBusThread(dbus_proxy)) {
    dbus::ObjectPath portal_path(kXdgPortalObject);
    dbus::ObjectProxy* portal =
        bus->GetObjectProxy(kXdgPortalService, portal_path);

    FileChooserProperties properties(portal);
    if (!properties.GetAndBlock(&properties.version)) {
      LOG(ERROR) << "Failed to read portal version property";
    } else if (properties.version.value() >= kXdgPortalRequiredVersion) {
      is_portal_available_ = true;
    }
  }

  VLOG(1) << "File chooser portal available: "
          << (is_portal_available_ ? "yes" : "no");
  availability_test_complete->Set();
}

// static
bool SelectFileDialogLinuxPortal::IsPortalRunningOnBusThread(
    dbus::ObjectProxy* dbus_proxy) {
  dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kDBusMethodNameHasOwner);
  dbus::MessageWriter writer(&method_call);
  writer.AppendString(kXdgPortalService);

  std::unique_ptr<dbus::Response> response = dbus_proxy->CallMethodAndBlock(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT);
  if (!response)
    return false;

  dbus::MessageReader reader(response.get());
  bool owned = false;
  if (!reader.PopBool(&owned)) {
    LOG(ERROR) << "Failed to read response";
    return false;
  }

  return owned;
}

// static
bool SelectFileDialogLinuxPortal::IsPortalActivatableOnBusThread(
    dbus::ObjectProxy* dbus_proxy) {
  dbus::MethodCall method_call(DBUS_INTERFACE_DBUS,
                               kDBusMethodListActivatableNames);

  std::unique_ptr<dbus::Response> response = dbus_proxy->CallMethodAndBlock(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT);
  if (!response)
    return false;

  dbus::MessageReader reader(response.get());
  std::vector<std::string> names;
  if (!reader.PopArrayOfStrings(&names)) {
    LOG(ERROR) << "Failed to read response";
    return false;
  }

  if (base::Contains(names, kXdgPortalService)) {
    dbus::MethodCall start_service_call(DBUS_INTERFACE_DBUS,
                                        kMethodStartServiceByName);
    dbus::MessageWriter start_service_writer(&start_service_call);
    start_service_writer.AppendString(kXdgPortalService);
    start_service_writer.AppendUint32(/*flags=*/0);
    auto start_service_response = dbus_proxy->CallMethodAndBlock(
        &start_service_call, kStartServiceTimeout.InMilliseconds());
    if (!start_service_response)
      return false;
    dbus::MessageReader start_service_reader(start_service_response.get());
    uint32_t start_service_reply = 0;
    if (start_service_reader.PopUint32(&start_service_reply) &&
        (start_service_reply == DBUS_START_REPLY_SUCCESS ||
         start_service_reply == DBUS_START_REPLY_ALREADY_RUNNING)) {
      return true;
    }
  }
  return false;
}

SelectFileDialogLinuxPortal::PortalFilter::PortalFilter() = default;
SelectFileDialogLinuxPortal::PortalFilter::PortalFilter(
    const PortalFilter& other) = default;
SelectFileDialogLinuxPortal::PortalFilter::PortalFilter(PortalFilter&& other) =
    default;
SelectFileDialogLinuxPortal::PortalFilter::~PortalFilter() = default;

SelectFileDialogLinuxPortal::PortalFilterSet::PortalFilterSet() = default;
SelectFileDialogLinuxPortal::PortalFilterSet::PortalFilterSet(
    const PortalFilterSet& other) = default;
SelectFileDialogLinuxPortal::PortalFilterSet::PortalFilterSet(
    PortalFilterSet&& other) = default;
SelectFileDialogLinuxPortal::PortalFilterSet::~PortalFilterSet() = default;

SelectFileDialogLinuxPortal::DialogInfo::DialogInfo(
    OnSelectFileExecutedCallback selected_callback,
    OnSelectFileCanceledCallback canceled_callback)
    : selected_callback_(std::move(selected_callback)),
      canceled_callback_(std::move(canceled_callback)) {}
SelectFileDialogLinuxPortal::DialogInfo::~DialogInfo() = default;

// static
base::AtomicFlag*
SelectFileDialogLinuxPortal::GetAvailabilityTestCompletionFlag() {
  static base::NoDestructor<base::AtomicFlag> flag;
  return flag.get();
}

SelectFileDialogLinuxPortal::PortalFilterSet
SelectFileDialogLinuxPortal::BuildFilterSet() {
  PortalFilterSet filter_set;

  for (size_t i = 0; i < file_types().extensions.size(); ++i) {
    PortalFilter filter;

    for (const std::string& extension : file_types().extensions[i]) {
      if (extension.empty())
        continue;

      filter.patterns.push_back("*." + base::ToLowerASCII(extension));
      auto upper = "*." + base::ToUpperASCII(extension);
      if (upper != filter.patterns.back())
        filter.patterns.push_back(std::move(upper));
    }

    if (filter.patterns.empty())
      continue;

    // If there is no matching description, use a default description based on
    // the filter.
    if (i < file_types().extension_description_overrides.size()) {
      filter.name =
          base::UTF16ToUTF8(file_types().extension_description_overrides[i]);
    } else {
      std::vector<std::string> patterns_vector(filter.patterns.begin(),
                                               filter.patterns.end());
      filter.name = base::JoinString(patterns_vector, ",");
    }

    // The -1 is required to match against the right filter because
    // |file_type_index_| is 1-indexed.
    if (i == file_type_index() - 1)
      filter_set.default_filter = filter;

    filter_set.filters.push_back(std::move(filter));
  }

  if (file_types().include_all_files && !filter_set.filters.empty()) {
    // Add the *.* filter, but only if we have added other filters (otherwise it
    // is implied).
    PortalFilter filter;
    filter.name = l10n_util::GetStringUTF8(IDS_SAVEAS_ALL_FILES);
    filter.patterns.push_back("*.*");

    filter_set.filters.push_back(std::move(filter));
  }

  return filter_set;
}

void SelectFileDialogLinuxPortal::SelectFileImplWithParentHandle(
    std::u16string title,
    base::FilePath default_path,
    PortalFilterSet filter_set,
    base::FilePath::StringType default_extension,
    std::string parent_handle) {
  bool default_path_exists = CallDirectoryExistsOnUIThread(default_path);
  dbus_thread_linux::GetTaskRunner()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &SelectFileDialogLinuxPortal::DialogInfo::SelectFileImplOnBusThread,
          info_, std::move(title), std::move(default_path), default_path_exists,
          std::move(filter_set), std::move(default_extension),
          std::move(parent_handle)));
}

void SelectFileDialogLinuxPortal::DialogInfo::SelectFileImplOnBusThread(
    std::u16string title,
    base::FilePath default_path,
    const bool default_path_exists,
    PortalFilterSet filter_set,
    base::FilePath::StringType default_extension,
    std::string parent_handle) {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  dbus::Bus* bus = AcquireBusOnBusThread();
  if (!bus->Connect())
    LOG(ERROR) << "Could not connect to bus for XDG portal";

  std::string method;
  switch (type) {
    case SELECT_FOLDER:
    case SELECT_UPLOAD_FOLDER:
    case SELECT_EXISTING_FOLDER:
    case SELECT_OPEN_FILE:
    case SELECT_OPEN_MULTI_FILE:
      method = kFileChooserMethodOpenFile;
      break;
    case SELECT_SAVEAS_FILE:
      method = kFileChooserMethodSaveFile;
      break;
    case SELECT_NONE:
      NOTREACHED();
      break;
  }

  dbus::MethodCall method_call(kFileChooserInterfaceName, method);
  dbus::MessageWriter writer(&method_call);

  writer.AppendString(parent_handle);

  if (!title.empty()) {
    writer.AppendString(base::UTF16ToUTF8(title));
  } else {
    int message_id = 0;
    if (type == SELECT_SAVEAS_FILE) {
      message_id = IDS_SAVEAS_ALL_FILES;
    } else if (type == SELECT_OPEN_MULTI_FILE) {
      message_id = IDS_OPEN_FILES_DIALOG_TITLE;
    } else {
      message_id = IDS_OPEN_FILE_DIALOG_TITLE;
    }
    writer.AppendString(l10n_util::GetStringUTF8(message_id));
  }

  std::string response_handle_token =
      base::StringPrintf("handle_%d", handle_token_counter_++);

  AppendOptions(&writer, response_handle_token, default_path,
                default_path_exists, filter_set);

  // The sender part of the handle object contains the D-Bus connection name
  // without the prefix colon and with all dots replaced with underscores.
  std::string sender_part;
  base::ReplaceChars(bus->GetConnectionName().substr(1), ".", "_",
                     &sender_part);

  dbus::ObjectPath expected_handle_path(
      base::StringPrintf("/org/freedesktop/portal/desktop/request/%s/%s",
                         sender_part.c_str(), response_handle_token.c_str()));

  response_handle_ =
      bus->GetObjectProxy(kXdgPortalService, expected_handle_path);
  ConnectToHandle();

  dbus::ObjectPath portal_path(kXdgPortalObject);
  dbus::ObjectProxy* portal =
      bus->GetObjectProxy(kXdgPortalService, portal_path);
  portal->CallMethodWithErrorResponse(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&DialogInfo::OnCallResponse, this, base::Unretained(bus)));
}

void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions(
    dbus::MessageWriter* writer,
    const std::string& response_handle_token,
    const base::FilePath& default_path,
    const bool default_path_exists,
    const SelectFileDialogLinuxPortal::PortalFilterSet& filter_set) {
  dbus::MessageWriter options_writer(nullptr);
  writer->OpenArray("{sv}", &options_writer);

  AppendStringOption(&options_writer, kFileChooserOptionHandleToken,
                     response_handle_token);

  if (type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER) {
    AppendStringOption(&options_writer, kFileChooserOptionAcceptLabel,
                       l10n_util::GetStringUTF8(
                           IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON));
  }

  if (type == SelectFileDialog::Type::SELECT_FOLDER ||
      type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER ||
      type == SelectFileDialog::Type::SELECT_EXISTING_FOLDER) {
    AppendBoolOption(&options_writer, kFileChooserOptionDirectory, true);
  } else if (type == SelectFileDialog::Type::SELECT_OPEN_MULTI_FILE) {
    AppendBoolOption(&options_writer, kFileChooserOptionMultiple, true);
  }

  if (type == SelectFileDialog::Type::SELECT_SAVEAS_FILE &&
      !default_path.empty()) {
    if (default_path_exists) {
      // If this is an existing directory, navigate to that directory, with no
      // filename.
      AppendByteStringOption(&options_writer, kFileChooserOptionCurrentFolder,
                             default_path.value());
    } else {
      // The default path does not exist, or is an existing file. We use
      // current_folder followed by current_name, as per the recommendation of
      // the GTK docs and the pattern followed by SelectFileDialogLinuxGtk.
      AppendByteStringOption(&options_writer, kFileChooserOptionCurrentFolder,
                             default_path.DirName().value());
      AppendStringOption(&options_writer, kFileChooserOptionCurrentName,
                         default_path.BaseName().value());
    }
  }

  AppendFiltersOption(&options_writer, filter_set.filters);
  if (filter_set.default_filter) {
    dbus::MessageWriter option_writer(nullptr);
    options_writer.OpenDictEntry(&option_writer);

    option_writer.AppendString(kFileChooserOptionCurrentFilter);

    dbus::MessageWriter value_writer(nullptr);
    option_writer.OpenVariant("(sa(us))", &value_writer);

    AppendFilterStruct(&value_writer, *filter_set.default_filter);

    option_writer.CloseContainer(&value_writer);
    options_writer.CloseContainer(&option_writer);
  }

  writer->CloseContainer(&options_writer);
}

void SelectFileDialogLinuxPortal::DialogInfo::AppendFiltersOption(
    dbus::MessageWriter* writer,
    const std::vector<PortalFilter>& filters) {
  dbus::MessageWriter option_writer(nullptr);
  writer->OpenDictEntry(&option_writer);

  option_writer.AppendString(kFileChooserOptionFilters);

  dbus::MessageWriter variant_writer(nullptr);
  option_writer.OpenVariant("a(sa(us))", &variant_writer);

  dbus::MessageWriter filters_writer(nullptr);
  variant_writer.OpenArray("(sa(us))", &filters_writer);

  for (const PortalFilter& filter : filters) {
    AppendFilterStruct(&filters_writer, filter);
  }

  variant_writer.CloseContainer(&filters_writer);
  option_writer.CloseContainer(&variant_writer);
  writer->CloseContainer(&option_writer);
}

void SelectFileDialogLinuxPortal::DialogInfo::AppendFilterStruct(
    dbus::MessageWriter* writer,
    const PortalFilter& filter) {
  dbus::MessageWriter filter_writer(nullptr);
  writer->OpenStruct(&filter_writer);

  filter_writer.AppendString(filter.name);

  dbus::MessageWriter patterns_writer(nullptr);
  filter_writer.OpenArray("(us)", &patterns_writer);

  for (const std::string& pattern : filter.patterns) {
    dbus::MessageWriter pattern_writer(nullptr);
    patterns_writer.OpenStruct(&pattern_writer);

    pattern_writer.AppendUint32(kFileChooserFilterKindGlob);
    pattern_writer.AppendString(pattern);

    patterns_writer.CloseContainer(&pattern_writer);
  }

  filter_writer.CloseContainer(&patterns_writer);
  writer->CloseContainer(&filter_writer);
}

void SelectFileDialogLinuxPortal::DialogInfo::ConnectToHandle() {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  response_handle_->ConnectToSignal(
      kXdgPortalRequestInterfaceName, kXdgPortalResponseSignal,
      base::BindRepeating(&DialogInfo::OnResponseSignalEmitted, this),
      base::BindOnce(&DialogInfo::OnResponseSignalConnected, this));
}

void SelectFileDialogLinuxPortal::DialogInfo::CompleteOpen(
    std::vector<base::FilePath> paths,
    std::string current_filter) {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  response_handle_->Detach();
  main_task_runner->PostTask(
      FROM_HERE, base::BindOnce(std::move(selected_callback_), std::move(paths),
                                std::move(current_filter)));
}

void SelectFileDialogLinuxPortal::DialogInfo::CancelOpen() {
  response_handle_->Detach();
  main_task_runner->PostTask(FROM_HERE, std::move(canceled_callback_));
}

void SelectFileDialogLinuxPortal::CompleteOpenOnMainThread(
    std::vector<base::FilePath> paths,
    std::string current_filter) {
  UnparentOnMainThread();

  if (listener_) {
    if (info_->type == SELECT_OPEN_MULTI_FILE) {
      listener_->MultiFilesSelected(paths, listener_params_);
    } else if (paths.size() > 1) {
      LOG(ERROR) << "Got >1 file URI from a single-file chooser";
    } else {
      int index = 1;
      for (size_t i = 0; i < filters_.size(); ++i) {
        if (filters_[i].name == current_filter) {
          index = 1 + i;
          break;
        }
      }
      listener_->FileSelected(paths.front(), index, listener_params_);
    }
  }
}

void SelectFileDialogLinuxPortal::CancelOpenOnMainThread() {
  UnparentOnMainThread();

  if (listener_)
    listener_->FileSelectionCanceled(listener_params_);
}

void SelectFileDialogLinuxPortal::UnparentOnMainThread() {
  if (parent_) {
    parent_.reset();
  }
}

void SelectFileDialogLinuxPortal::DialogInfo::OnCallResponse(
    dbus::Bus* bus,
    dbus::Response* response,
    dbus::ErrorResponse* error_response) {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  if (response) {
    dbus::MessageReader reader(response);
    dbus::ObjectPath actual_handle_path;
    if (!reader.PopObjectPath(&actual_handle_path)) {
      LOG(ERROR) << "Invalid portal response";
    } else {
      if (response_handle_->object_path() != actual_handle_path) {
        VLOG(1) << "Re-attaching response handle to "
                << actual_handle_path.value();

        response_handle_->Detach();
        response_handle_ =
            bus->GetObjectProxy(kXdgPortalService, actual_handle_path);
        ConnectToHandle();
      }

      // Return before the operation is cancelled.
      return;
    }
  } else if (error_response) {
    std::string error_name = error_response->GetErrorName();
    std::string error_message;
    dbus::MessageReader reader(error_response);
    reader.PopString(&error_message);

    LOG(ERROR) << "Portal returned error: " << error_name << ": "
               << error_message;
  } else {
    NOTREACHED();
  }

  // All error paths end up here.
  CancelOpen();
}

void SelectFileDialogLinuxPortal::DialogInfo::OnResponseSignalConnected(
    const std::string& interface,
    const std::string& signal,
    bool connected) {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  if (!connected) {
    LOG(ERROR) << "Could not connect to Response signal";
    CancelOpen();
  }
}

void SelectFileDialogLinuxPortal::DialogInfo::OnResponseSignalEmitted(
    dbus::Signal* signal) {
  DCHECK(dbus_thread_linux::GetTaskRunner()->RunsTasksInCurrentSequence());
  dbus::MessageReader reader(signal);

  std::vector<std::string> uris;
  std::string current_filter;
  if (!CheckResponseCode(&reader) ||
      !ReadResponseResults(&reader, &uris, &current_filter)) {
    CancelOpen();
    return;
  }

  std::vector<base::FilePath> paths = ConvertUrisToPaths(uris);
  if (!paths.empty())
    CompleteOpen(std::move(paths), std::move(current_filter));
  else
    CancelOpen();
}

bool SelectFileDialogLinuxPortal::DialogInfo::CheckResponseCode(
    dbus::MessageReader* reader) {
  std::uint32_t response = 0;
  if (!reader->PopUint32(&response)) {
    LOG(ERROR) << "Failed to read response ID";
    return false;
  } else if (response != 0) {
    return false;
  }

  return true;
}

bool SelectFileDialogLinuxPortal::DialogInfo::ReadResponseResults(
    dbus::MessageReader* reader,
    std::vector<std::string>* uris,
    std::string* current_filter) {
  dbus::MessageReader results_reader(nullptr);
  if (!reader->PopArray(&results_reader)) {
    LOG(ERROR) << "Failed to read file chooser variant";
    return false;
  }

  while (results_reader.HasMoreData()) {
    dbus::MessageReader entry_reader(nullptr);
    std::string key;
    if (!results_reader.PopDictEntry(&entry_reader) ||
        !entry_reader.PopString(&key)) {
      LOG(ERROR) << "Failed to read response entry";
      return false;
    }

    if (key == "uris") {
      dbus::MessageReader uris_reader(nullptr);
      if (!entry_reader.PopVariant(&uris_reader) ||
          !uris_reader.PopArrayOfStrings(uris)) {
        LOG(ERROR) << "Failed to read <uris> response entry value";
        return false;
      }
    }
    if (key == "current_filter") {
      dbus::MessageReader current_filter_reader(nullptr);
      dbus::MessageReader current_filter_struct_reader(nullptr);
      if (!entry_reader.PopVariant(&current_filter_reader) ||
          !current_filter_reader.PopStruct(&current_filter_struct_reader) ||
          !current_filter_struct_reader.PopString(current_filter)) {
        LOG(ERROR) << "Failed to read <current_filter> response entry value";
      }
    }
  }

  return true;
}

std::vector<base::FilePath>
SelectFileDialogLinuxPortal::DialogInfo::ConvertUrisToPaths(
    const std::vector<std::string>& uris) {
  std::vector<base::FilePath> paths;
  for (const std::string& uri : uris) {
    if (!base::StartsWith(uri, kFileUriPrefix, base::CompareCase::SENSITIVE)) {
      LOG(WARNING) << "Ignoring unknown file chooser URI: " << uri;
      continue;
    }

    base::StringPiece encoded_path(uri);
    encoded_path.remove_prefix(strlen(kFileUriPrefix));

    url::RawCanonOutputT<char16_t> decoded_path;
    url::DecodeURLEscapeSequences(encoded_path.data(), encoded_path.size(),
                                  url::DecodeURLMode::kUTF8OrIsomorphic,
                                  &decoded_path);
    paths.emplace_back(base::UTF16ToUTF8(
        base::StringPiece16(decoded_path.data(), decoded_path.length())));
  }

  return paths;
}

bool SelectFileDialogLinuxPortal::is_portal_available_ = false;
int SelectFileDialogLinuxPortal::handle_token_counter_ = 0;

}  // namespace ui


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/main"
	android:layout_height="300px"
	android:background="@drawable/background"
	android:layout_width="160dp"
	android:orientation="vertical">
	<TextView
		android:id="@+id/paddingTop"
		android:layout_width="fill_parent"
		android:layout_height="20px"
		android:gravity="center_vertical|center_horizontal"
		android:textColor="@android:color/black"
		android:text=""
		android:textSize="9pt"
		android:longClickable="true" />
	<TextView
		android:id="@+id/price1"
		android:layout_width="fill_parent"
		android:layout_height="45px"
		android:gravity="center_vertical|center_horizontal"
		android:textColor="@android:color/black"
		android:text="price1"
		android:textSize="9pt"
		android:longClickable="true" />
	<TextView
		android:id="@+id/change1"
		android:layout_width="fill_parent"
		android:layout_height="21px"
		android:gravity="center_vertical|right"
		android:textColor="@android:color/black"
		android:text="+ 0.67       "
		android:textSize="6pt"
		android:longClickable="true" />
	<TextView
		android:id="@+id/price2"
		android:layout_width="fill_parent"
		android:layout_height="45px"
		android:gravity="center_vertical|center_horizontal"
		android:textColor="@android:color/black"
		android:text="price2"
		android:textSize="9pt"
		android:longClickable="true" />
	<TextView
		android:id="@+id/change2"
		android:layout_width="fill_parent"
		android:layout_height="21px"
		android:gravity="center_vertical|right"
		android:textColor="@android:color/black"
		android:text="+ 0.67       "
		android:textSize="6pt"
		android:longClickable="true" />
	<TextView
		android:id="@+id/price3"
		android:layout_width="fill_parent"
		android:layout_height="45px"
		android:gravity="center_vertical|center_horizontal"
		android:textColor="@android:color/black"
		android:text="price3"
		android:textSize="9pt"
		android:longClickable="true" />
	<TextView
		android:id="@+id/change3"
		android:layout_width="fill_parent"
		android:layout_height="21px"
		android:gravity="center_vertical|right"
		android:textColor="@android:color/black"
		android:text="+ 0.67       "
		android:textSize="6pt"
		android:longClickable="true" />
	<LinearLayout
		android:id="@+id/main"
		android:layout_height="60px"
		android:layout_width="fill_parent"
		android:orientation="horizontal">
		<TextView
			android:id="@+id/filler"
			android:layout_width="28px"
			android:layout_height="fill_parent"
			android:gravity="center_vertical|center_horizontal"
			android:textColor="@android:color/black"
			android:text=""
			android:textStyle="italic"
			android:textSize="4pt"
			android:longClickable="true" />
		<ImageView
			android:id="@+id/logo"
			android:layout_height="57px"
			android:layout_width="57px"
			android:src="@drawable/citylogo" />
		<LinearLayout
			android:id="@+id/main"
			android:layout_height="60px"
			android:layout_width="fill_parent"
			android:orientation="vertical">
			<TextView
				android:id="@+id/lastLabel"
				android:layout_width="fill_parent"
				android:layout_height="25px"
				android:gravity="center_vertical|left"
				android:textColor="@android:color/black"
				android:text="Last updated:"
				android:textStyle="italic"
				android:textSize="6pt"
				android:longClickable="true" />
			<TextView
				android:id="@+id/lastValue"
				android:layout_width="fill_parent"
				android:layout_height="35px"
				android:gravity="center_vertical|center_horizontal"
				android:textColor="@android:color/black"
				android:text="13:53Z"
				android:textStyle="italic"
				android:textSize="6pt"
				android:longClickable="true" />
		</LinearLayout>
	</LinearLayout>
</LinearLayout>


text:
template<typename eT>
inline
SpSubview<eT>::iterator_base::iterator_base(const SpSubview<eT>& in_M)
  : M(in_M)
  , internal_col(0)
  , internal_pos(0)
  , skip_pos(0)
  {
  // Technically this iterator is invalid (it may not point to a real element).
  }

template<typename eT>
inline
SpSubview<eT>::iterator_base::iterator_base(const SpSubview<eT>& in_M, const uword in_col, const uword in_pos, const uword in_skip_pos)
  : M(in_M)
  , internal_col(in_col)
  , internal_pos(in_pos)
  , skip_pos    (in_skip_pos)
  {
  // Nothing to do.
  }

template<typename eT>
inline
eT
SpSubview<eT>::iterator_base::operator*() const
  {
  return M.m.values[internal_pos + skip_pos];
  }

///////////////////////////////////////////////////////////////////////////////
// SpSubview::const_iterator implementation                                  //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
SpSubview<eT>::const_iterator::const_iterator(const SpSubview<eT>& in_M, const uword initial_pos)
  : iterator_base(in_M, 0, initial_pos, 0)
  {
  // Corner case for empty subviews.
  if(in_M.n_nonzero == 0)
    {
    iterator_base::internal_col = in_M.n_cols;
    iterator_base::skip_pos     = in_M.m.n_nonzero;
    return;
    }

  // Figure out the row and column of the position.
  // lskip_pos holds the number of values which aren't part of this subview.
  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_rows = iterator_base::M.n_rows;
  const uword ln_cols = iterator_base::M.n_cols;

  uword cur_pos   = 0; // off by one because we might be searching for pos 0
  uword lskip_pos = iterator_base::M.m.col_ptrs[aux_col];
  uword cur_col   = 0;

  while(cur_pos < (iterator_base::internal_pos + 1))
    {
    // Have we stepped forward a column (or multiple columns)?
    while(((lskip_pos + cur_pos) >= iterator_base::M.m.col_ptrs[cur_col + aux_col + 1]) && (cur_col < ln_cols))
      {
      ++cur_col;
      }

    // See if the current position is in the subview.
    const uword row_index = iterator_base::M.m.row_indices[cur_pos + lskip_pos];
    if(row_index < aux_row)
      {
      ++lskip_pos; // not valid
      }
    else if(row_index < (aux_row + ln_rows))
      {
      ++cur_pos; // valid, in the subview
      }
    else
      {
      // skip to end of column
      const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];
      lskip_pos += (next_colptr - (cur_pos + lskip_pos));
      }
    }

  iterator_base::internal_col = cur_col;
  iterator_base::skip_pos     = lskip_pos;
  }

template<typename eT>
inline
SpSubview<eT>::const_iterator::const_iterator(const SpSubview<eT>& in_M, const uword in_row, const uword in_col)
  : iterator_base(in_M, in_col, 0, 0)
  {
  // Corner case for empty subviews.
  if(in_M.n_nonzero == 0)
    {
    // We must be at the last position.
    iterator_base::internal_col = in_M.n_cols;
    iterator_base::skip_pos = in_M.m.n_nonzero;
    return;
    }

  // We have a destination we want to be just after, but don't know what position that is.
  // Because we have to count the points in this subview and not in this subview, this becomes a little difficult and slow.
  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_rows = iterator_base::M.n_rows;
  const uword ln_cols = iterator_base::M.n_cols;

  uword cur_pos = 0;
  uword skip_pos = iterator_base::M.m.col_ptrs[aux_col];
  uword cur_col = 0;

  while(cur_col < in_col)
    {
    // See if the current position is in the subview.
    const uword row_index = iterator_base::M.m.row_indices[cur_pos + skip_pos];
    if(row_index < aux_row)
      {
      ++skip_pos;
      }
    else if(row_index < (aux_row + ln_rows))
      {
      ++cur_pos;
      }
    else
      {
      // skip to end of column
      const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];
      skip_pos += (next_colptr - (cur_pos + skip_pos));
      }

    // Have we stepped forward a column (or multiple columns)?
    while(((skip_pos + cur_pos) >= iterator_base::M.m.col_ptrs[cur_col + aux_col + 1]) && (cur_col < ln_cols))
      {
      ++cur_col;
      }
    }

  // Now we are either on the right column or ahead of it.
  if(cur_col == in_col)
    {
    // We have to find the right row index.
    uword row_index = iterator_base::M.m.row_indices[cur_pos + skip_pos];
    while((row_index < (in_row + aux_row)))
      {
      if(row_index < aux_row)
        {
        ++skip_pos;
        }
      else
        {
        ++cur_pos;
        }

      // Ensure we didn't step forward a column; if we did, we need to stop.
      while(((skip_pos + cur_pos) >= iterator_base::M.m.col_ptrs[cur_col + aux_col + 1]) && (cur_col < ln_cols))
        {
        ++cur_col;
        }

      if(cur_col != in_col)
        {
        break;
        }

      row_index = iterator_base::M.m.row_indices[cur_pos + skip_pos];
      }
    }

  // Now we need to find the next valid position in the subview.
  uword row_index;
  while(true)
    {
    const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];
    row_index = iterator_base::M.m.row_indices[cur_pos + skip_pos];

    // Are we at the last position?
    if(cur_col >= ln_cols)
      {
      cur_col = ln_cols;
      // Make sure we will be pointing at the last element in the parent matrix.
      skip_pos = iterator_base::M.m.n_nonzero - iterator_base::M.n_nonzero;
      break;
      }

    if(row_index < aux_row)
      {
      ++skip_pos;
      }
    else if(row_index < (aux_row + ln_rows))
      {
      break; // found
      }
    else
      {
      skip_pos += (next_colptr - (cur_pos + skip_pos));
      }

    // Did we move any columns?
    while(((skip_pos + cur_pos) >= iterator_base::M.m.col_ptrs[cur_col + aux_col + 1]) && (cur_col < ln_cols))
      {
      ++cur_col;
      }
    }

  // It is possible we have moved another column.
  while(((skip_pos + cur_pos) >= iterator_base::M.m.col_ptrs[cur_col + aux_col + 1]) && (cur_col < ln_cols))
    {
    ++cur_col;
    }

  iterator_base::internal_pos = cur_pos;
  iterator_base::skip_pos     = skip_pos;
  iterator_base::internal_col = cur_col;
  }

template<typename eT>
inline
SpSubview<eT>::const_iterator::const_iterator(const SpSubview<eT>& in_M, uword in_row, uword in_col, uword in_pos, uword in_skip_pos)
  : iterator_base(in_M, in_col, in_pos, in_skip_pos)
  {
  arma_ignore(in_row);

  // Nothing to do.
  }

template<typename eT>
inline
SpSubview<eT>::const_iterator::const_iterator(const const_iterator& other)
  : iterator_base(other.M, other.internal_col, other.internal_pos, other.skip_pos)
  {
  // Nothing to do.
  }

template<typename eT>
inline
typename SpSubview<eT>::const_iterator&
SpSubview<eT>::const_iterator::operator++()
  {
  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_rows = iterator_base::M.n_rows;
  const uword ln_cols = iterator_base::M.n_cols;

  uword cur_col   = iterator_base::internal_col;
  uword cur_pos   = iterator_base::internal_pos + 1;
  uword lskip_pos = iterator_base::skip_pos;
  uword row_index;

  while(true)
    {
    const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];
    row_index = iterator_base::M.m.row_indices[cur_pos + lskip_pos];

    // Did we move any columns?
    while((cur_col < ln_cols) && ((lskip_pos + cur_pos) >= iterator_base::M.m.col_ptrs[cur_col + aux_col + 1]))
      {
      ++cur_col;
      }

    // Are we at the last position?
    if(cur_col >= ln_cols)
      {
      cur_col = ln_cols;
      // Make sure we will be pointing at the last element in the parent matrix.
      lskip_pos = iterator_base::M.m.n_nonzero - iterator_base::M.n_nonzero;
      break;
      }

    if(row_index < aux_row)
      {
      ++lskip_pos;
      }
    else if(row_index < (aux_row + ln_rows))
      {
      break; // found
      }
    else
      {
      lskip_pos += (next_colptr - (cur_pos + lskip_pos));
      }
    }

  iterator_base::internal_pos = cur_pos;
  iterator_base::internal_col = cur_col;
  iterator_base::skip_pos     = lskip_pos;

  return *this;
  }

template<typename eT>
inline
typename SpSubview<eT>::const_iterator
SpSubview<eT>::const_iterator::operator++(int)
  {
  typename SpSubview<eT>::const_iterator tmp(*this);

  ++(*this);

  return tmp;
  }

template<typename eT>
inline
typename SpSubview<eT>::const_iterator&
SpSubview<eT>::const_iterator::operator--()
  {
  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_rows = iterator_base::M.n_rows;

  uword cur_col  = iterator_base::internal_col;
  uword cur_pos  = iterator_base::internal_pos - 1;
  uword skip_pos = iterator_base::skip_pos;

  // Special condition for end of iterator.
  if((skip_pos + cur_pos + 1) == iterator_base::M.m.n_nonzero)
    {
    // We are at the last element.  So we need to set skip_pos back to what it
    // would be if we didn't manually modify it back in operator++().
    skip_pos = iterator_base::M.m.col_ptrs[cur_col + aux_col] - iterator_base::internal_pos;
    }

  uword row_index;

  while(true)
    {
    const uword colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col];
    row_index = iterator_base::M.m.row_indices[cur_pos + skip_pos];

    // Did we move back any columns?
    while((skip_pos + cur_pos) < iterator_base::M.m.col_ptrs[cur_col + aux_col])
      {
      --cur_col;
      }

    if(row_index < aux_row)
      {
      skip_pos -= (colptr - (cur_pos + skip_pos) + 1);
      }
    else if(row_index < (aux_row + ln_rows))
      {
      break; // found
      }
    else
      {
      --skip_pos;
      }
    }

  iterator_base::internal_pos = cur_pos;
  iterator_base::skip_pos     = skip_pos;
  iterator_base::internal_col = cur_col;

  return *this;
  }

template<typename eT>
inline
typename SpSubview<eT>::const_iterator
SpSubview<eT>::const_iterator::operator--(int)
  {
  typename SpSubview<eT>::const_iterator tmp(*this);

  --(*this);

  return tmp;
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator==(const const_iterator& rhs) const
  {
  return (rhs.row() == (*this).row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator!=(const const_iterator& rhs) const
  {
  return (rhs.row() != (*this).row()) || (rhs.col() != iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator==(const typename SpMat<eT>::const_iterator& rhs) const
  {
  return (rhs.row() == (*this).row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator!=(const typename SpMat<eT>::const_iterator& rhs) const
  {
  return (rhs.row() != (*this).row()) || (rhs.col() != iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator==(const const_row_iterator& rhs) const
  {
  return (rhs.row() == (*this).row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator!=(const const_row_iterator& rhs) const
  {
  return (rhs.row() != (*this).row()) || (rhs.col() != iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator==(const typename SpMat<eT>::const_row_iterator& rhs) const
  {
  return (rhs.row() == (*this).row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_iterator::operator!=(const typename SpMat<eT>::const_row_iterator& rhs) const
  {
  return (rhs.row() != (*this).row()) || (rhs.col() != iterator_base::internal_col);
  }

///////////////////////////////////////////////////////////////////////////////
// SpSubview<eT>::iterator implementation                                    //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
SpValProxy<SpSubview<eT> >
SpSubview<eT>::iterator::operator*()
  {
  return SpValProxy<SpSubview<eT> >(
    iterator_base::row(),
    iterator_base::col(),
    access::rw(iterator_base::M),
    &(access::rw(iterator_base::M.m.values[iterator_base::internal_pos + iterator_base::skip_pos])));
  }

template<typename eT>
inline
typename SpSubview<eT>::iterator&
SpSubview<eT>::iterator::operator++()
  {
  const_iterator::operator++();
  return *this;
  }

template<typename eT>
inline
typename SpSubview<eT>::iterator
SpSubview<eT>::iterator::operator++(int)
  {
  typename SpSubview<eT>::iterator tmp(*this);

  const_iterator::operator++();

  return tmp;
  }

template<typename eT>
inline
typename SpSubview<eT>::iterator&
SpSubview<eT>::iterator::operator--()
  {
  const_iterator::operator--();
  return *this;
  }

template<typename eT>
inline
typename SpSubview<eT>::iterator
SpSubview<eT>::iterator::operator--(int)
  {
  typename SpSubview<eT>::iterator tmp(*this);

  const_iterator::operator--();

  return tmp;
  }

///////////////////////////////////////////////////////////////////////////////
// SpSubview<eT>::const_row_iterator implementation                          //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
SpSubview<eT>::const_row_iterator::const_row_iterator(const SpSubview<eT>& in_M, uword initial_pos)
  : iterator_base(in_M, 0, initial_pos, 0)
  , internal_row(0)
  , actual_pos(0)
  {
  // Corner case for empty subviews.
  if(in_M.n_nonzero == 0)
    {
    iterator_base::internal_col = 0;
    internal_row = in_M.n_rows;
    iterator_base::skip_pos = in_M.m.n_nonzero;
    return;
    }

  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_cols = iterator_base::M.n_cols;

  // We don't know where the elements are in each row.  What we will do is
  // loop across all valid columns looking for elements in row 0 (and add to
  // our sum), then in row 1, and so forth, until we get to the desired
  // position.
  uword cur_pos = -1;
  uword cur_row = 0;
  uword cur_col = 0;

  while(true)
    {
    // Is there anything in the column we are looking at?
    const uword colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col];
    const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];

    for(uword ind = colptr; (ind < next_colptr) && (iterator_base::M.m.row_indices[ind] <= (cur_row + aux_row)); ++ind)
      {
      // There is something in this column.  Is it in the row we are looking at?
      const uword row_index = iterator_base::M.m.row_indices[ind];
      if(row_index == (cur_row + aux_row))
        {
        // Yes, it is in the right row.
        if(++cur_pos == iterator_base::internal_pos)
          {
          iterator_base::internal_col = cur_col;
          internal_row = cur_row;
          actual_pos = ind;

          return;
          }

        // We are done with this column.  Break to the column incrementing code (directly below).
        break;
        }
      else if(row_index > (cur_row + aux_row))
        {
        break; // Can't be in this column.
        }
      }

    cur_col++; // Done with the column.  Move on.
    if(cur_col == ln_cols)
      {
      // Out of columns.  Loop back to the beginning and look on the next row.
      cur_col = 0;
      cur_row++;
      }
    }
  }

template<typename eT>
inline
SpSubview<eT>::const_row_iterator::const_row_iterator(const SpSubview<eT>& in_M, uword in_row, uword in_col)
  : iterator_base(in_M, in_col, 0, 0)
  , internal_row(0)
  , actual_pos(0)
  {
  // We have a destination we want to be just after, but don't know what that
  // position is.  Because we will have to loop over everything anyway, create
  // another iterator and loop it until it is at the right place, then take its
  // information.
  const_row_iterator it(in_M, 0);
  while((it.row() < in_row) || ((it.row() == in_row) && (it.col() < in_col)))
    {
    ++it;
    }

  iterator_base::internal_col = it.col();
  iterator_base::internal_pos = it.pos();
  iterator_base::skip_pos = it.skip_pos;
  internal_row = it.internal_row;
  actual_pos = it.actual_pos;
  }

template<typename eT>
inline
SpSubview<eT>::const_row_iterator::const_row_iterator(const const_row_iterator& other)
  : iterator_base(other.M, other.internal_col, other.internal_pos, other.skip_pos)
  , internal_row(other.internal_row)
  , actual_pos(other.actual_pos)
  {
  // Nothing to do.
  }

template<typename eT>
inline
typename SpSubview<eT>::const_row_iterator&
SpSubview<eT>::const_row_iterator::operator++()
  {
  // We just need to find the next nonzero element.
  ++iterator_base::internal_pos;

  // If we have exceeded the bounds, update accordingly.
  if(iterator_base::internal_pos >= iterator_base::M.n_nonzero)
    {
    internal_row = iterator_base::M.n_rows;
    iterator_base::internal_col = 0;
    actual_pos = iterator_base::M.m.n_nonzero;

    return *this;
    }

  // Otherwise, we need to search.
  uword cur_col = iterator_base::internal_col;
  uword cur_row = internal_row;

  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_cols = iterator_base::M.n_cols;

  while(true)
    {
    // Increment the current column and see if we are on a new row.
    if(++cur_col == ln_cols)
      {
      cur_col = 0;
      ++cur_row;
      }

    // Is there anything in this new column?
    const uword colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col];
    const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];

    for(uword ind = colptr; (ind < next_colptr) && (iterator_base::M.m.row_indices[ind] <= (cur_row + aux_row)); ++ind)
      {
      const uword row_index = iterator_base::M.m.row_indices[ind];

      if((row_index - aux_row) == cur_row)
        {
        // We have successfully incremented.
        internal_row = cur_row;
        actual_pos = ind;
        iterator_base::internal_col = cur_col;

        return *this;
        }
      }
    }
  }

template<typename eT>
inline
typename SpSubview<eT>::const_row_iterator
SpSubview<eT>::const_row_iterator::operator++(int)
  {
  typename SpSubview<eT>::const_row_iterator tmp(*this);

  ++(*this);

  return tmp;
  }

template<typename eT>
inline
typename SpSubview<eT>::const_row_iterator&
SpSubview<eT>::const_row_iterator::operator--()
  {
  // We just need to find the previous element.
//  if(iterator_base::pos == 0)
//    {
//    // We cannot decrement.
//    return *this;
//    }
//  else if(iterator_base::pos == iterator_base::M.n_nonzero)
//    {
//    // We will be coming off the last element.  We need to reset the row correctly, because we set row = 0 in the last matrix position.
//    iterator_base::row = iterator_base::M.n_rows - 1;
//    }
//  else if(iterator_base::pos > iterator_base::M.n_nonzero)
//    {
//    // This shouldn't happen...
//    iterator_base::pos--;
//    return *this;
//    }

  iterator_base::internal_pos--;

  // We have to search backwards.
  uword cur_col = iterator_base::internal_col;
  uword cur_row = internal_row;

  const uword aux_col = iterator_base::M.aux_col1;
  const uword aux_row = iterator_base::M.aux_row1;
  const uword ln_cols = iterator_base::M.n_cols;

  while(true)
    {
    // Decrement the current column and see if we are on a new row.
    if(--cur_col > ln_cols)
      {
      cur_col = ln_cols - 1;
      cur_row--;
      }

    // Is there anything in this new column?
    const uword colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col];
    const uword next_colptr = iterator_base::M.m.col_ptrs[cur_col + aux_col + 1];

    for(uword ind = colptr; (ind < next_colptr) && (iterator_base::M.m.row_indices[ind] <= (cur_row + aux_row)); ++ind)
      {
      const uword row_index = iterator_base::M.m.row_indices[ind];

      if((row_index - aux_row) == cur_row)
        {
        iterator_base::internal_col = cur_col;
        internal_row = cur_row;
        actual_pos = ind;

        return *this;
        }
      }
    }
  }

template<typename eT>
inline
typename SpSubview<eT>::const_row_iterator
SpSubview<eT>::const_row_iterator::operator--(int)
  {
  typename SpSubview<eT>::const_row_iterator tmp(*this);

  --(*this);

  return tmp;
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator==(const const_iterator& rhs) const
  {
  return (rhs.row() == row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator!=(const const_iterator& rhs) const
  {
  return (rhs.row() != row()) || (rhs.col() != iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator==(const typename SpMat<eT>::const_iterator& rhs) const
  {
  return (rhs.row() == row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator!=(const typename SpMat<eT>::const_iterator& rhs) const
  {
  return (rhs.row() != row()) || (rhs.col() != iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator==(const const_row_iterator& rhs) const
  {
  return (rhs.row() == row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator!=(const const_row_iterator& rhs) const
  {
  return (rhs.row() != row()) || (rhs.col() != iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator==(const typename SpMat<eT>::const_row_iterator& rhs) const
  {
  return (rhs.row() == row()) && (rhs.col() == iterator_base::internal_col);
  }

template<typename eT>
inline
bool
SpSubview<eT>::const_row_iterator::operator!=(const typename SpMat<eT>::const_row_iterator& rhs) const
  {
  return (rhs.row() != row()) || (rhs.col() != iterator_base::internal_col);
  }

///////////////////////////////////////////////////////////////////////////////
// SpSubview<eT>::row_iterator implementation                                //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
SpValProxy<SpSubview<eT> >
SpSubview<eT>::row_iterator::operator*()
  {
  return SpValProxy<SpSubview<eT> >(
    const_row_iterator::internal_row,
    iterator_base::internal_col,
    access::rw(iterator_base::M),
    &access::rw(iterator_base::M.m.values[const_row_iterator::actual_pos]));
  }

template<typename eT>
inline
typename SpSubview<eT>::row_iterator&
SpSubview<eT>::row_iterator::operator++()
  {
  const_row_iterator::operator++();
  return *this;
  }

template<typename eT>
inline
typename SpSubview<eT>::row_iterator
SpSubview<eT>::row_iterator::operator++(int)
  {
  typename SpSubview<eT>::row_iterator tmp(*this);

  ++(*this);

  return tmp;
  }

template<typename eT>
inline
typename SpSubview<eT>::row_iterator&
SpSubview<eT>::row_iterator::operator--()
  {
  const_row_iterator::operator--();
  return *this;
  }

template<typename eT>
inline
typename SpSubview<eT>::row_iterator
SpSubview<eT>::row_iterator::operator--(int)
  {
  typename SpSubview<eT>::row_iterator tmp(*this);

  --(*this);

  return tmp;
  }

//! @}


text:
class Solution(object):
    def binarySearch(self, nums, target):
        left, right = 0, len(nums) - 1

        while left <= right:
            mid = (left + right) // 2
            if target < nums[mid]:
                right = mid - 1
            elif target > nums[mid]:
                left = mid + 1
            else:
                return True

        return False

    def searchMatrix(self, matrix, target):
        m = len(matrix)

        for i in range(m):
            if self.binarySearch(matrix[i], target):
                return True

        return False


text:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle"  xmlns:dc="http://purl.org/dc/elements/1.1/">
   <channel>
      <title>SysEx Librarian's Changelog</title>
      <link>https://www.snoize.com/SysExLibrarian/SysExLibrarian.xml</link>
      <description>Most recent changes with links to updates.</description>
      <language>en</language>
          <item>
              <title>Version 1.4.1</title>
              <sparkle:minimumSystemVersion>10.9.0</sparkle:minimumSystemVersion>
              <description><![CDATA[

Version 1.4.1

Changes:

Updated to support macOS 11.0 "Big Sur" and Apple Silicon Macs.

              ]]>
              </description>
              <pubDate>Sun, 8 Nov 2020 17:18:00 -0800</pubDate>
              <enclosure url="https://www.snoize.com/SysExLibrarian/SysExLibrarian_1_4_1.zip" sparkle:version="1.4.1" sparkle:dsaSignature="MCwCFHZOw86RQJ/rdOEm4EKfFH2WTFsNAhRGblND5fq9ZQ7a6CW1lEVvjp5UDw==" sparkle:edSignature="Yl6MZiHUEIIKZoLmEMJSrEg/PxwPH4jQULS2wIh2jm30dB3W1ZqTH2kFwmkztE5bWBeagS5XF4E/4ud+2NULBQ==" length="3363623" type="application/octet-stream"/>
          </item>
          <item>
              <title>Version 1.4</title>
              <sparkle:minimumSystemVersion>10.9.0</sparkle:minimumSystemVersion>
              <description><![CDATA[

Version 1.4

Changes:

Updated for macOS 10.14 Mojave, including Dark Mode.

Bug fixes:

Allow setting the buffer size for sending sysex. Some MIDI interfaces may work better with a smaller buffer size.

Added menu items and key equivalents to play and record. Press space to play, r to record, R to record all.

At startup, if sysex files can't be found, don't ask the user to find every single one.

Updated MIDI manufacturer names and IDs.

Show program changes as 1-128 or 0-127 depending on a preference.

Increased the maximum interval between sent messages up to 5 seconds.

Improved error handling at launch when the library directory doesn't exist or isn't writable.

              ]]>
              </description>
              <pubDate>Sat, 22 Sep 2018 12:43:29 -0700</pubDate>
              <enclosure url="https://www.snoize.com/SysExLibrarian/SysExLibrarian_1_4.zip" sparkle:version="1.4" sparkle:dsaSignature="MC0CFHhUZC7WO5D4i5fnqXiIRRiagkU/AhUAgsuYiQH5+rqg/rXmsSZzQiNtFg4=" length="2818504" type="application/octet-stream"/>
          </item>
          <item>
              <title>Version 1.3.1</title>
              <sparkle:minimumSystemVersion>10.7.0</sparkle:minimumSystemVersion>
              <description><![CDATA[

Version 1.3.1:

First update in a while!

Changes:

Modernized UI slightly: lists now fill the whole window.

Fixed behavior of split view in sysex details.

Updated app signature so it launches without warning on Mac OS X 10.9.5.

              ]]>
              </description>
              <pubDate>Wed, 20 Aug 2014 19:30:14 -0700</pubDate>
              <enclosure url="https://www.snoize.com/SysExLibrarian/SysExLibrarian_1_3_1.zip" sparkle:version="1.3.1" sparkle:dsaSignature="MC0CFQCrh1k0KvqV03e3rM6qhU/9lZKCUAIUWf9w5YWXXK8sNX47WgpYROd7k9Y=" length="2027501" type="application/octet-stream"/>
         </item>
         <item>
            <title>Version 1.3</title>
            <description><![CDATA[

First version that supported Sparkle.

You should never see this text.

            ]]>
            </description>
            <pubDate>Mon, 3 Sep 2012 21:22:00 -0700</pubDate>
            <enclosure url="https://www.snoize.com/SysExLibrarian/SysExLibrarian_1_3.zip" sparkle:version="1.3" length="1335575" type="application/octet-stream" sparkle:dsaSignature="MC0CFAw6iKfx5v64vU1DJSNgYhWRcha4AhUA5rd9onpXmKjQDula4vNTe0QRjMU=" />
         </item>
   </channel>
</rss>


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <display-name>game-service</display-name>

</web-app>