text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Rikasta kihti

See tööriist rikastab teie andmeid, hankides fakte inimeste, kohtade ja äride kohta, mis ümbritsevad teie andmeid ruumiliselt ja võimaldab teil vastata uutele küsimustele paikade kohta, millele muidu ei oskaks kaardilt vastata. Näiteks: millised inimesed siin piirkonnas elavad? Millega inimesed siin piirkonnas vabal ajal tegelevad? Millised on nende harjumused ja elustiil? Millist tüüpi ettevõtted siin piirkonnas tegutsevad?

Tulemuseks on kiht, mis sisaldab lisaks geograafilisele teabele informatsiooni ka demograafilistest näitajatest jne.  Vastav uus info lisatakse väljadena tabelisse.

Kui  Kasuta kaardi ulatust on sisse lülitatud, kasutatakse analüüsil ainult neid objekte, mis antud hetkel on ekraanil nähtavad.  Kui vastav tingimus on välja lülitatud, kasutatakse analüüsil mõlema kihi kõiki objekte sõltumata asjaolust, kas need on analüüsi käivitamise hetkel ekraanil nähtavad või mitte.

Rikastamise muutujad

Klikkige  andmebrauseri avamiseks nuppu Vali muutujad. Andmebrauser aitab teil otsida ja valida rikastamise muutujaid eraldi või kogude kaupa.

Teie andmete põhjal valitakse automaatselt piirkond. Kui teie andmed katavad rohkem kui ühte riiki, saate valida teise piirkonna.

Rikastamise muutujad organiseeritakse hõlpsaks juurdepääsuks andmekogudesse.   Andmekogu valimisel kuvab brauser mõned selle kogu populaarseimad rikastamise muutujad.  Jaotises  Jätka sirvimist kuvatakse ka selle kogu kategooriad. Iga kategooria piires saate valida terveid alamkategooriaid või sirvida alamkategooriat ja valida rikastamise muutujad eraldi. Saate otsinguvälja abil ka kategooria kindlat muutujat otsida.

Rikastamise muutujate valimisel lisatakse need  andmebrauseri nurgas asuvasse ostukorvi. Ostukorvi saate jälgida valitud muutujate arvu.

Iga valitud muutuja lisatakse tulemkihis väljana.

Määra piirkonnad analüüsiks

Need on piirkonnad, mida on vastavate andmekogude kaudu võimalik täiendavalt rikastada. Juhul kui analüüsikiht sisaldab punkte, luuakse pinnad iga punkti ümber kas sirgjoonelise kauguse, sõidu vahemaa või sõiduks kuluva aja alusel.

Tulemkihi nimi

See on kihi nimi, mis luuakse kasutaja  Minu sisu  alla ning lisatakse kaardile.  Vaikimisi nimi on tuletatud kihi analüüsi sisust. Kui see kiht juba eksisteerib, küsitakse teie käest selle ülekirjutamise otsuse kohta.

Kasutades  Salvesta tulemus rippmenüüd, saate te täpsustada Minu sisu alla salvestamise asukoha


text:
                  <?php include_once(APPPATH.'views/fe/common/common_buyer_search.tpl.php'); ?>

            <?php include_once(APPPATH.'views/fe/common/buyer_left_menu.tpl.php'); ?>

 <?php echo get_title_string(t('Active Jobs'))?> (<?php echo $i_active_jobs;?>)

<?php echo t('All jobs that you have posted and have been approved by admin are listed below')?>

                  	<?php echo $job_contents;?>

History

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

 Rahul has posted the Job: Painter on 08/09/2011

                                                      Admin has approved the Job: Painter.

redpajama_set_name: RedPajamaGithub


text:
{{{
  "title": "Login to AppFog using the Cloud Foundry CLI",
  "date": "04-10-2015",
  "author": "Chris Sterling",
  "attachments": [],
  "related-products" : [],
  "contentIsHTML": false,
  "sticky": true
}}}

### Audience

Application developers

### Overview

In this article we will install the [Cloud Foundry Command Line Interface (CLI)](https://github.com/cloudfoundry/cli/) so that we can login to AppFog from the command line. Currently, AppFog only supports deployment of applications and provisioning services via the command line. This article will focus on authenticating to AppFog using your CenturyLink Control Portal credentials. Other articles will go into detail on how to use other Cloud Foundry CLI commands to interact with AppFog capabilities.

### Install Cloud Foundry CLI

Download the appropriate [binary distribution of the Cloud Foundry CLI](https://github.com/cloudfoundry/cli/blob/master/README.md#downloads). Install the downloaded binary distribution of Cloud Foundry CLI. To verify Cloud Foundry CLI is installed run the following command from a terminal shell:

```
$ cf -v
cf version 6.11.0-bba7fcf-2015-04-14T16:45:03+00:00
```

**NOTE:** The Ruby Gem based Cloud Foundry CLI is no longer supported and will not work with AppFog. Please make sure that you use the appropriate binary distribution from:

[https://github.com/cloudfoundry/cli/blob/master/README.md#downloads](https://github.com/cloudfoundry/cli/blob/master/README.md#downloads)

### Login to AppFog

Now that we have the Cloud Foundry CLI installed, lets login to AppFog. Go to the AppFog overview page in the Control Portal by navigation using the "AppFog" link listed in the drop down navigation bar:

![AppFog in Dropdown Navigation](../images/appfog-in-dropdown-nav.png)

Or you may also navigate to AppFog via the icon on the left-side vertical navigation bar:

![AppFog icon in Vertical Navigation](../images/appfog-icon-nav.png)

Now navigate to the "US East" AppFog region from the left-side navigation tree:

![AppFog Organization Overview in US East Region](../images/appfog-org-overview.png)

Copy the full `cf login` shell command from the "Overview" tab. The command should look similar to:

```
cf login -a https://api.useast.appfog.ctl.io -o C007 -u csterling_demo
```

Now paste the `cf login` command into a terminal shell and run it. You should be prompted for your CenturyLink Cloud Control Portal password.

![AppFog Login Prompt](../images/cf-cli-login-prompt.png)

Please type in your password and hit enter. After successfully authenticating with your credentials, you should be prompted for which AppFog Space to target for application deployments:

![AppFog Space Target Prompt](../images/cf-cli-space-prompt.png)

Choose Space number 1 "Dev" as shown in the image above. You are now logged in and ready to learn more about AppFog capabilities.


text:
/** Example partys_tallest_guests.cpp \file partys_tallest_guests.cpp
    \brief Using <i>aggregate on overlap</i> the heights of the party's tallest
           guests are computed.

    In partys_tallest_guests.cpp we use a different instantiation of
    interval map templates to compute maxima of guest heights.

    Instead of aggregating groups of people attending the party in time
    we aggregate the maximum of guest height for the time intervals.

    Using a joining interval_map results in a smaller map: All interval
    value pairs are joined if the maximum does not change in time. Using
    a split_interval_map results in a larger map: All splits of intervals
    that occur due to entering and leaving of guests are preserved in
    the split_interval_map.

    \include partys_tallest_guests_/partys_tallest_guests.cpp
*/
//[example_partys_tallest_guests
// The next line includes <boost/date_time/posix_time/posix_time.hpp>
// and a few lines of adapter code.
#include <boost/icl/ptime.hpp>
#include <iostream>
#include <boost/icl/interval_map.hpp>
#include <boost/icl/split_interval_map.hpp>

using namespace std;
using namespace boost::posix_time;
using namespace boost::icl;

// A party's height shall be defined as the maximum height of all guests ;-)
// The last parameter 'inplace_max' is a functor template that calls a max
// aggregation on overlap.
typedef interval_map<ptime, int, partial_absorber, less, inplace_max>
    PartyHeightHistoryT;

// Using a split_interval_map we preserve interval splittings that occurred via insertion.
typedef split_interval_map<ptime, int, partial_absorber, less, inplace_max>
    PartyHeightSplitHistoryT;

void partys_height()
{
    PartyHeightHistoryT tallest_guest;

    tallest_guest +=
      make_pair(
        discrete_interval<ptime>::right_open(
          time_from_string("2008-05-20 19:30"),
          time_from_string("2008-05-20 23:00")),
        180); // Mary & Harry: Harry is 1,80 m tall.

    tallest_guest +=
      make_pair(
        discrete_interval<ptime>::right_open(
          time_from_string("2008-05-20 20:10"),
          time_from_string("2008-05-21 00:00")),
        170); // Diana & Susan: Diana is 1,70 m tall.

    tallest_guest +=
      make_pair(
        discrete_interval<ptime>::right_open(
          time_from_string("2008-05-20 22:15"),
          time_from_string("2008-05-21 00:30")),
        200); // Peters height is 2,00 m

    PartyHeightHistoryT::iterator height_ = tallest_guest.begin();
    cout << "-------------- History of maximum guest height -------------------\n";
    while(height_ != tallest_guest.end())
    {
        discrete_interval<ptime> when = height_->first;
        // Of what height are the tallest guests within the time interval 'when' ?
        int height = (*height_++).second;
        cout << "[" << first(when) << " - " << upper(when) << ")"
             << ": " << height <<" cm = " << height/30.48 << " ft" << endl;
    }

}

// Next we are using a split_interval_map instead of a joining interval_map
void partys_split_height()
{
    PartyHeightSplitHistoryT tallest_guest;

    // adding an element can be done wrt. simple aggregate functions
    // like e.g. min, max etc. in their 'inplace' or op= incarnation
    tallest_guest +=
      make_pair(
        discrete_interval<ptime>::right_open(
          time_from_string("2008-05-20 19:30"),
          time_from_string("2008-05-20 23:00")),
        180); // Mary & Harry: Harry is 1,80 m tall.

    tallest_guest +=
      make_pair(
        discrete_interval<ptime>::right_open(
          time_from_string("2008-05-20 20:10"),
          time_from_string("2008-05-21 00:00")),
        170); // Diana & Susan: Diana is 1,70 m tall.

    tallest_guest +=
      make_pair(
        discrete_interval<ptime>::right_open(
          time_from_string("2008-05-20 22:15"),
          time_from_string("2008-05-21 00:30")),
        200); // Peters height is 2,00 m

    PartyHeightSplitHistoryT::iterator height_ = tallest_guest.begin();
    cout << "\n";
    cout << "-------- Split History of maximum guest height -------------------\n";
    cout << "--- Same map as above but split for every interval insertion.  ---\n";
    while(height_ != tallest_guest.end())
    {
        discrete_interval<ptime> when = height_->first;
        // Of what height are the tallest guests within the time interval 'when' ?
        int height = (*height_++).second;
        cout << "[" << first(when) << " - " << upper(when) << ")"
             << ": " << height <<" cm = " << height/30.48 << " ft" << endl;
    }

}

int main()
{
    cout << ">>Interval Container Library: Sample partys_tallest_guests.cpp  <<\n";
    cout << "------------------------------------------------------------------\n";
    partys_height();
    partys_split_height();
    return 0;
}

// Program output:
/*-----------------------------------------------------------------------------
>>Interval Container Library: Sample partys_tallest_guests.cpp  <<
------------------------------------------------------------------
-------------- History of maximum guest height -------------------
[2008-May-20 19:30:00 - 2008-May-20 22:15:00): 180 cm = 5.90551 ft
[2008-May-20 22:15:00 - 2008-May-21 00:30:00): 200 cm = 6.56168 ft

-------- Split History of maximum guest height -------------------
--- Same map as above but split for every interval insertion.  ---
[2008-May-20 19:30:00 - 2008-May-20 20:10:00): 180 cm = 5.90551 ft
[2008-May-20 20:10:00 - 2008-May-20 22:15:00): 180 cm = 5.90551 ft
[2008-May-20 22:15:00 - 2008-May-20 23:00:00): 200 cm = 6.56168 ft
[2008-May-20 23:00:00 - 2008-May-21 00:00:00): 200 cm = 6.56168 ft
[2008-May-21 00:00:00 - 2008-May-21 00:30:00): 200 cm = 6.56168 ft
-----------------------------------------------------------------------------*/
//]


text:
<?php

defined('_JEXEC') or die;
?>
<?php if($this->juser->guest) : ?>

			<?php if(!VmConfig::get('oncheckout_show_register') && !VmConfig::get('oncheckout_only_registered')) : ?>

<?php echo vmText::_('COM_VIRTUEMART_CHECKOUT_AS_GUEST')?>

			<?php elseif(VmConfig::get('oncheckout_only_registered')) : ?>

<?php echo vmText::_('COM_VIRTUEMART_CART_ONLY_REGISTERED')?>

			<?php else : ?>

<?php echo JText::_('PLG_VPONEPAGECHECKOUT_CHECKOUT_AS_GUEST_REGISTER')?>

			<?php endif; ?>

				<?php if(!VmConfig::get('oncheckout_show_register') && !VmConfig::get('oncheckout_only_registered')) : ?>

<?php echo vmText::_('COM_VIRTUEMART_ENTER_A_VALID_EMAIL_ADDRESS')?>

							<?php echo $this->loadTemplate('guest'); ?>

				<?php elseif(VmConfig::get('oncheckout_only_registered')) : ?>

<?php echo JText::_('PLG_VPONEPAGECHECKOUT_REGISTER_CONVINIENCE')?>

							<?php echo $this->loadTemplate('register'); ?>

				<?php else : ?>

<?php echo JText::_('PLG_VPONEPAGECHECKOUT_REGISTER_CONVINIENCE')?>

						<input type="radio" name="proopc-method" value="guest"<?php echo $this->params->get('registration_by_default', 0) ? '' : ' checked'; ?> autocomplete="off" />
						<?php echo vmText::_('COM_VIRTUEMART_CHECKOUT_AS_GUEST') ?>

					<div class="proopc-guest-form<?php echo $this->params->get('registration_by_default', 0) ? ' soft-hide' : ''; ?>">

							<?php echo $this->loadTemplate ('guest'); ?>

						<input type="radio" name="proopc-method" value="register"<?php echo $this->params->get('registration_by_default', 0) ? ' checked' : ''; ?> autocomplete="off" />
						<?php echo vmText::_('COM_VIRTUEMART_REGISTER') ?>

					<div class="proopc-reg-form<?php echo $this->params->get('registration_by_default', 0) ? '' : ' soft-hide'; ?>">

							<?php echo $this->loadTemplate ('register'); ?>

					<div class="proopc-reg-advantages<?php echo $this->params->get('registration_by_default', 0) ? ' soft-hide' : ''; ?>">
						<?php
						$registration_message = trim($this->params->get('registration_message', ''));
						if(empty($registration_message))
						{
							echo JText::_('PLG_VPONEPAGECHECKOUT_DEFAULT_REGISTRATION_ADVANTAGE_MSG');
						}
						else
						{
							echo $registration_message;
						} ?>

				<?php endif; ?>

<?php echo JText::_('PLG_VPONEPAGECHECKOUT_LOGIN_AND_CHECKOUT') ?>

				<?php echo $this->loadTemplate('login'); ?>

<?php endif; ?>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Common.Logging;
using Rhino.PersistentHashTable;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Exceptions;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Transport;

namespace Rhino.ServiceBus.RhinoQueues
{
    public class PhtSubscriptionStorage : ISubscriptionStorage, IDisposable, IMessageModule
    {
        private const string SubscriptionsKey = "subscriptions";

        private readonly Hashtable<string, List<WeakReference>> localInstanceSubscriptions =
            new Hashtable<string, List<WeakReference>>();

        private readonly ILog logger = LogManager.GetLogger(typeof (PhtSubscriptionStorage));

        private readonly IMessageSerializer messageSerializer;
        private PersistentHashTable.PersistentHashTable pht;
        private readonly IReflection reflection;

        private readonly MultiValueIndexHashtable<Guid, string, Uri, int> remoteInstanceSubscriptions =
            new MultiValueIndexHashtable<Guid, string, Uri, int>();

        private readonly Hashtable<TypeAndUriKey, IList<int>> subscriptionMessageIds =
            new Hashtable<TypeAndUriKey, IList<int>>();

        private readonly string subscriptionPath;
        private readonly Hashtable<string, HashSet<Uri>> subscriptions = new Hashtable<string, HashSet<Uri>>();

    	private bool currentlyLoadingPersistentData;

        public PhtSubscriptionStorage(
            string subscriptionPath,
            IMessageSerializer messageSerializer,
            IReflection reflection)
        {
            this.subscriptionPath = subscriptionPath;
            this.messageSerializer = messageSerializer;
            this.reflection = reflection;
            pht = new PersistentHashTable.PersistentHashTable(subscriptionPath);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (pht != null)
            {
                pht.Dispose();
                pht = null;
            }
        }

        #endregion

        #region IMessageModule Members

		void IMessageModule.Init(ITransport transport, IServiceBus bus)
        {
            transport.AdministrativeMessageArrived += HandleAdministrativeMessage;
        }

		void IMessageModule.Stop(ITransport transport, IServiceBus bus)
        {
            transport.AdministrativeMessageArrived -= HandleAdministrativeMessage;
        }

        #endregion

        #region ISubscriptionStorage Members

        public void Initialize()
        {
            logger.DebugFormat("Initializing msmq subscription storage on: {0}", subscriptionPath);
            pht.Initialize();

            pht.Batch(actions =>
            {
                var items = actions.GetItems(new GetItemsRequest
                {
                    Key = SubscriptionsKey
                });
                foreach (var item in items)
                {
                    object[] msgs;
                    try
                    {
                        msgs = messageSerializer.Deserialize(new MemoryStream(item.Value));
                    }
                    catch (Exception e)
                    {
                        throw new SubscriptionException("Could not deserialize message from subscription queue", e);
                    }

                    try
                    {
                    	currentlyLoadingPersistentData = true;
                        foreach (var msg in msgs)
                        {
                            HandleAdministrativeMessage(new CurrentMessageInformation
                            {
                                AllMessages = msgs,
                                Message = msg,
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        throw new SubscriptionException("Failed to process subscription records", e);
                    }
					finally
                    {
                    	currentlyLoadingPersistentData = false;
                    }
                }
                actions.Commit();
            });
        }

        public IEnumerable<Uri> GetSubscriptionsFor(Type type)
        {
            HashSet<Uri> subscriptionForType = null;
            subscriptions.Read(reader => reader.TryGetValue(type.FullName, out subscriptionForType));
            var subscriptionsFor = subscriptionForType ?? new HashSet<Uri>();

            List<Uri> instanceSubscriptions;
            remoteInstanceSubscriptions.TryGet(type.FullName, out instanceSubscriptions);

            subscriptionsFor.UnionWith(instanceSubscriptions);

            return subscriptionsFor;
        }

        public void RemoveLocalInstanceSubscription(IMessageConsumer consumer)
        {
            var messagesConsumes = reflection.GetMessagesConsumed(consumer);
            var changed = false;
            var list = new List<WeakReference>();

            localInstanceSubscriptions.Write(writer =>
            {
                foreach (var type in messagesConsumes)
                {
                    List<WeakReference> value;

                    if (writer.TryGetValue(type.FullName, out value) == false)
                        continue;
                    writer.Remove(type.FullName);
                    list.AddRange(value);
                }
            });

            foreach (var reference in list)
            {
                if (ReferenceEquals(reference.Target, consumer))
                    continue;

                changed = true;
            }
            if (changed)
                RaiseSubscriptionChanged();
        }

        public object[] GetInstanceSubscriptions(Type type)
        {
            List<WeakReference> value = null;

            localInstanceSubscriptions.Read(reader => reader.TryGetValue(type.FullName, out value));

            if (value == null)
                return new object[0];

            var liveInstances = value
                .Select(x => x.Target)
                .Where(x => x != null)
                .ToArray();

            if (liveInstances.Length != value.Count) //cleanup
            {
                localInstanceSubscriptions.Write(writer => value.RemoveAll(x => x.IsAlive == false));
            }

            return liveInstances;
        }

        public event Action SubscriptionChanged;

        public bool AddSubscription(string type, string endpoint)
        {
            var added = false;
            subscriptions.Write(writer =>
            {
                HashSet<Uri> subscriptionsForType;
                if (writer.TryGetValue(type, out subscriptionsForType) == false)
                {
                    subscriptionsForType = new HashSet<Uri>();
                    writer.Add(type, subscriptionsForType);
                }

                var uri = new Uri(endpoint);
                added = subscriptionsForType.Add(uri);

                logger.InfoFormat("Added subscription for {0} on {1}",
                                  type, uri);
            });

            RaiseSubscriptionChanged();
            return added;
        }

        public void RemoveSubscription(string type, string endpoint)
        {
            var uri = new Uri(endpoint);
            RemoveSubscriptionMessageFromPht(type, uri);

            subscriptions.Write(writer =>
            {
                HashSet<Uri> subscriptionsForType;

                if (writer.TryGetValue(type, out subscriptionsForType) == false)
                {
                    subscriptionsForType = new HashSet<Uri>();
                    writer.Add(type, subscriptionsForType);
                }

                subscriptionsForType.Remove(uri);

                logger.InfoFormat("Removed subscription for {0} on {1}",
                                  type, endpoint);
            });

            RaiseSubscriptionChanged();
        }

        public void AddLocalInstanceSubscription(IMessageConsumer consumer)
        {
            localInstanceSubscriptions.Write(writer =>
            {
                foreach (var type in reflection.GetMessagesConsumed(consumer))
                {
                    List<WeakReference> value;
                    if (writer.TryGetValue(type.FullName, out value) == false)
                    {
                        value = new List<WeakReference>();
                        writer.Add(type.FullName, value);
                    }
                    value.Add(new WeakReference(consumer));
                }
            });
            RaiseSubscriptionChanged();
        }

        #endregion

        private void AddMessageIdentifierForTracking(int messageId, string messageType, Uri uri)
        {
            subscriptionMessageIds.Write(writer =>
            {
                var key = new TypeAndUriKey {TypeName = messageType, Uri = uri};
                IList<int> value;
                if (writer.TryGetValue(key, out value) == false)
                {
                    value = new List<int>();
                    writer.Add(key, value);
                }

                value.Add(messageId);
            });
        }

        private void RemoveSubscriptionMessageFromPht(string type, Uri uri)
        {
            subscriptionMessageIds.Write(writer =>
            {
                var key = new TypeAndUriKey
                {
                    TypeName = type,
                    Uri = uri
                };
                IList<int> messageIds;
                if (writer.TryGetValue(key, out messageIds) == false)
                    return;

                pht.Batch(actions =>
                {
                    foreach (var msgId in messageIds)
                    {
                        actions.RemoveItem(new RemoveItemRequest
                        {
                            Id = msgId,
                            Key = SubscriptionsKey
                        });
                    }

                    actions.Commit();
                });
                writer.Remove(key);
            });
        }

        public bool HandleAdministrativeMessage(CurrentMessageInformation msgInfo)
        {
            var addSubscription = msgInfo.Message as AddSubscription;
            if (addSubscription != null)
            {
                return ConsumeAddSubscription(addSubscription);
            }
            var removeSubscription = msgInfo.Message as RemoveSubscription;
            if (removeSubscription != null)
            {
                return ConsumeRemoveSubscription(removeSubscription);
            }
            var addInstanceSubscription = msgInfo.Message as AddInstanceSubscription;
            if (addInstanceSubscription != null)
            {
                return ConsumeAddInstanceSubscription(addInstanceSubscription);
            }
            var removeInstanceSubscription = msgInfo.Message as RemoveInstanceSubscription;
            if (removeInstanceSubscription != null)
            {
                return ConsumeRemoveInstanceSubscription(removeInstanceSubscription);
            }
            return false;
        }

        public bool ConsumeRemoveInstanceSubscription(RemoveInstanceSubscription subscription)
        {
            int msgId;
            if (remoteInstanceSubscriptions.TryRemove(subscription.InstanceSubscriptionKey, out msgId))
            {
                pht.Batch(actions =>
                {
                    actions.RemoveItem(new RemoveItemRequest
                    {
                        Id = msgId,
                        Key = SubscriptionsKey
                    });

                    actions.Commit();
                });
                RaiseSubscriptionChanged();
            }
            return true;
        }

        public bool ConsumeAddInstanceSubscription(
            AddInstanceSubscription subscription)
        {
            pht.Batch(actions =>
            {
                var message = new MemoryStream();
                messageSerializer.Serialize(new[] {subscription}, message);
                var itemId = actions.AddItem(new AddItemRequest
                {
                    Key = SubscriptionsKey,
                    Data = message.ToArray()
                });

                remoteInstanceSubscriptions.Add(
                    subscription.InstanceSubscriptionKey,
                    subscription.Type,
                    new Uri(subscription.Endpoint),
                    itemId);

                actions.Commit();
            });

            RaiseSubscriptionChanged();
            return true;
        }

        public bool ConsumeRemoveSubscription(RemoveSubscription removeSubscription)
        {
            RemoveSubscription(removeSubscription.Type, removeSubscription.Endpoint.Uri.ToString());
            return true;
        }

        public bool ConsumeAddSubscription(AddSubscription addSubscription)
        {
            var newSubscription = AddSubscription(addSubscription.Type, addSubscription.Endpoint.Uri.ToString());

			if (newSubscription && currentlyLoadingPersistentData == false)
            {
                var itemId = 0;
                pht.Batch(actions =>
                {
                    var stream = new MemoryStream();
                    messageSerializer.Serialize(new[] {addSubscription}, stream);
                    itemId = actions.AddItem(new AddItemRequest
                    {
                        Key = SubscriptionsKey,
                        Data = stream.ToArray()
                    });

                    actions.Commit();
                });

                AddMessageIdentifierForTracking(
                    itemId,
                    addSubscription.Type,
                    addSubscription.Endpoint.Uri);

                return true;
            }

            return false;
        }

        private void RaiseSubscriptionChanged()
        {
            var copy = SubscriptionChanged;
            if (copy != null)
                copy();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<bitmap android:src="@drawable/st_ic_kt_menu" android:tint="@color/dashboard_kt_menu_color"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
.. currentmodule:: xray

#############
API reference
#############

This page provides an auto-generated summary of xray's API. For more details
and examples, refer to the relevant chapter in the main part of the
documentation.

Top-level functions
===================

.. autosummary::
   :toctree: generated/

   align
   concat
   set_options

Dataset
=======

Creating a dataset
------------------

.. autosummary::
   :toctree: generated/

   Dataset
   decode_cf

Attributes
----------

.. autosummary::
   :toctree: generated/

   Dataset.dims
   Dataset.data_vars
   Dataset.coords
   Dataset.attrs

Dictionary interface
--------------------

Datasets implement the mapping interface with keys given by variable names
and values given by ``DataArray`` objects.

.. autosummary::
   :toctree: generated/

   Dataset.__getitem__
   Dataset.__setitem__
   Dataset.__delitem__
   Dataset.update
   Dataset.iteritems
   Dataset.itervalues

Dataset contents
----------------

.. autosummary::
   :toctree: generated/

   Dataset.copy
   Dataset.assign
   Dataset.assign_coords
   Dataset.pipe
   Dataset.merge
   Dataset.rename
   Dataset.swap_dims
   Dataset.drop
   Dataset.set_coords
   Dataset.reset_coords

Comparisons
-----------

.. autosummary::
   :toctree: generated/

   Dataset.equals
   Dataset.identical
   Dataset.broadcast_equals

Indexing
--------

.. autosummary::
   :toctree: generated/

   Dataset.loc
   Dataset.isel
   Dataset.sel
   Dataset.isel_points
   Dataset.sel_points
   Dataset.squeeze
   Dataset.reindex
   Dataset.reindex_like

Computation
-----------

.. autosummary::
   :toctree: generated/

   Dataset.apply
   Dataset.reduce
   Dataset.groupby
   Dataset.resample
   Dataset.transpose
   Dataset.diff

**Aggregation**:
:py:attr:`~Dataset.all`
:py:attr:`~Dataset.any`
:py:attr:`~Dataset.argmax`
:py:attr:`~Dataset.argmin`
:py:attr:`~Dataset.max`
:py:attr:`~Dataset.mean`
:py:attr:`~Dataset.median`
:py:attr:`~Dataset.min`
:py:attr:`~Dataset.prod`
:py:attr:`~Dataset.sum`
:py:attr:`~Dataset.std`
:py:attr:`~Dataset.var`

**Missing values**:
:py:attr:`~Dataset.isnull`
:py:attr:`~Dataset.notnull`
:py:attr:`~Dataset.count`
:py:attr:`~Dataset.dropna`
:py:attr:`~Dataset.fillna`
:py:attr:`~Dataset.where`

**ndarray methods**:
:py:attr:`~Dataset.argsort`
:py:attr:`~Dataset.clip`
:py:attr:`~Dataset.conj`
:py:attr:`~Dataset.conjugate`
:py:attr:`~Dataset.imag`
:py:attr:`~Dataset.round`
:py:attr:`~Dataset.real`
:py:attr:`~Dataset.T`

**Grouped operations**:
:py:attr:`~core.groupby.DatasetGroupBy.assign`
:py:attr:`~core.groupby.DatasetGroupBy.assign_coords`
:py:attr:`~core.groupby.DatasetGroupBy.first`
:py:attr:`~core.groupby.DatasetGroupBy.last`
:py:attr:`~core.groupby.DatasetGroupBy.fillna`
:py:attr:`~core.groupby.DatasetGroupBy.where`

DataArray
=========

.. autosummary::
   :toctree: generated/

   DataArray

Attributes
----------

.. autosummary::
   :toctree: generated/

   DataArray.values
   DataArray.data
   DataArray.coords
   DataArray.dims
   DataArray.name
   DataArray.attrs
   DataArray.encoding

**ndarray attributes**:
:py:attr:`~DataArray.ndim`
:py:attr:`~DataArray.shape`
:py:attr:`~DataArray.size`
:py:attr:`~DataArray.dtype`

DataArray contents
------------------

.. autosummary::
   :toctree: generated/

   DataArray.assign_coords
   DataArray.rename
   DataArray.swap_dims
   DataArray.drop
   DataArray.reset_coords
   DataArray.copy

**ndarray methods**:
:py:attr:`~DataArray.astype`
:py:attr:`~DataArray.item`

Indexing
--------

.. autosummary::
   :toctree: generated/

   DataArray.__getitem__
   DataArray.__setitem__
   DataArray.loc
   DataArray.isel
   DataArray.sel
   DataArray.isel_points
   DataArray.sel_points
   DataArray.squeeze
   DataArray.reindex
   DataArray.reindex_like

Computation
-----------

.. autosummary::
   :toctree: generated/

   DataArray.reduce
   DataArray.groupby
   DataArray.resample
   DataArray.transpose
   DataArray.get_axis_num
   DataArray.diff

**Aggregation**:
:py:attr:`~DataArray.all`
:py:attr:`~DataArray.any`
:py:attr:`~DataArray.argmax`
:py:attr:`~DataArray.argmin`
:py:attr:`~DataArray.max`
:py:attr:`~DataArray.mean`
:py:attr:`~DataArray.median`
:py:attr:`~DataArray.min`
:py:attr:`~DataArray.prod`
:py:attr:`~DataArray.sum`
:py:attr:`~DataArray.std`
:py:attr:`~DataArray.var`

**Missing values**:
:py:attr:`~DataArray.isnull`
:py:attr:`~DataArray.notnull`
:py:attr:`~DataArray.count`
:py:attr:`~DataArray.dropna`
:py:attr:`~DataArray.fillna`
:py:attr:`~DataArray.where`

**ndarray methods**:
:py:attr:`~DataArray.argsort`
:py:attr:`~DataArray.clip`
:py:attr:`~DataArray.conj`
:py:attr:`~DataArray.conjugate`
:py:attr:`~DataArray.imag`
:py:attr:`~DataArray.searchsorted`
:py:attr:`~DataArray.round`
:py:attr:`~DataArray.real`
:py:attr:`~DataArray.T`

**Grouped operations**:
:py:attr:`~core.groupby.DataArrayGroupBy.assign_coords`
:py:attr:`~core.groupby.DataArrayGroupBy.first`
:py:attr:`~core.groupby.DataArrayGroupBy.last`
:py:attr:`~core.groupby.DataArrayGroupBy.fillna`
:py:attr:`~core.groupby.DataArrayGroupBy.where`

Comparisons
-----------

.. autosummary::
   :toctree: generated/

   DataArray.equals
   DataArray.identical
   DataArray.broadcast_equals

.. _api.ufuncs:

Universal functions
===================

This functions are copied from NumPy, but extended to work on NumPy arrays,
dask arrays and all xray objects. You can find them in the ``xray.ufuncs``
module:

:py:attr:`~ufuncs.angle`
:py:attr:`~ufuncs.arccos`
:py:attr:`~ufuncs.arccosh`
:py:attr:`~ufuncs.arcsin`
:py:attr:`~ufuncs.arcsinh`
:py:attr:`~ufuncs.arctan`
:py:attr:`~ufuncs.arctan2`
:py:attr:`~ufuncs.arctanh`
:py:attr:`~ufuncs.ceil`
:py:attr:`~ufuncs.conj`
:py:attr:`~ufuncs.copysign`
:py:attr:`~ufuncs.cos`
:py:attr:`~ufuncs.cosh`
:py:attr:`~ufuncs.deg2rad`
:py:attr:`~ufuncs.degrees`
:py:attr:`~ufuncs.exp`
:py:attr:`~ufuncs.expm1`
:py:attr:`~ufuncs.fabs`
:py:attr:`~ufuncs.fix`
:py:attr:`~ufuncs.floor`
:py:attr:`~ufuncs.fmax`
:py:attr:`~ufuncs.fmin`
:py:attr:`~ufuncs.fmod`
:py:attr:`~ufuncs.fmod`
:py:attr:`~ufuncs.frexp`
:py:attr:`~ufuncs.hypot`
:py:attr:`~ufuncs.imag`
:py:attr:`~ufuncs.iscomplex`
:py:attr:`~ufuncs.isfinite`
:py:attr:`~ufuncs.isinf`
:py:attr:`~ufuncs.isnan`
:py:attr:`~ufuncs.isreal`
:py:attr:`~ufuncs.ldexp`
:py:attr:`~ufuncs.log`
:py:attr:`~ufuncs.log10`
:py:attr:`~ufuncs.log1p`
:py:attr:`~ufuncs.log2`
:py:attr:`~ufuncs.logaddexp`
:py:attr:`~ufuncs.logaddexp2`
:py:attr:`~ufuncs.logical_and`
:py:attr:`~ufuncs.logical_not`
:py:attr:`~ufuncs.logical_or`
:py:attr:`~ufuncs.logical_xor`
:py:attr:`~ufuncs.maximum`
:py:attr:`~ufuncs.minimum`
:py:attr:`~ufuncs.nextafter`
:py:attr:`~ufuncs.rad2deg`
:py:attr:`~ufuncs.radians`
:py:attr:`~ufuncs.real`
:py:attr:`~ufuncs.rint`
:py:attr:`~ufuncs.sign`
:py:attr:`~ufuncs.signbit`
:py:attr:`~ufuncs.sin`
:py:attr:`~ufuncs.sinh`
:py:attr:`~ufuncs.sqrt`
:py:attr:`~ufuncs.square`
:py:attr:`~ufuncs.tan`
:py:attr:`~ufuncs.tanh`
:py:attr:`~ufuncs.trunc`

IO / Conversion
===============

Dataset methods
---------------

.. autosummary::
   :toctree: generated/

   open_dataset
   open_mfdataset
   Dataset.to_netcdf
   save_mfdataset
   Dataset.to_array
   Dataset.to_dataframe
   Dataset.from_dataframe
   Dataset.close
   Dataset.load
   Dataset.chunk

DataArray methods
-----------------

.. autosummary::
   :toctree: generated/

   DataArray.to_dataset
   DataArray.to_pandas
   DataArray.to_series
   DataArray.to_dataframe
   DataArray.to_index
   DataArray.to_masked_array
   DataArray.to_cdms2
   DataArray.from_series
   DataArray.from_cdms2
   DataArray.load
   DataArray.chunk

Backends (experimental)
-----------------------

These backends provide a low-level interface for lazily loading data from
external file-formats or protocols, and can be manually invoked to create
arguments for the ``from_store`` and ``dump_to_store`` Dataset methods.

.. autosummary::
   :toctree: generated/

   backends.NetCDF4DataStore
   backends.H5NetCDFStore
   backends.PydapDataStore
   backends.ScipyDataStore

Plotting
========

.. autosummary::
   :toctree: generated/

   plot.plot
   plot.contourf
   plot.contour
   plot.hist
   plot.imshow
   plot.line
   plot.pcolormesh
   plot.FacetGrid


text:
package com.christianbahl.conductor.dagger.sample.di;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;

/**
 * Created by cbahl on 12.03.17.
 */
@Scope @Retention(RetentionPolicy.RUNTIME) public @interface ScreenScope {
}


text:
package org.decimal4j.op.arith;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import org.decimal4j.api.Decimal;
import org.decimal4j.api.DecimalArithmetic;
import org.decimal4j.op.AbstractDecimalLongToDecimalTest;
import org.decimal4j.scale.ScaleMetrics;
import org.decimal4j.test.TestSettings;
import org.decimal4j.truncate.TruncationPolicy;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Unit test for {@link Decimal#divide(long)}, {@link Decimal#divide(long, RoundingMode)}
 * and {@link Decimal#divide(long, TruncationPolicy)}
 */
@RunWith(Parameterized.class)
public class DivideLongTest extends AbstractDecimalLongToDecimalTest {

	public DivideLongTest(ScaleMetrics sm, TruncationPolicy tp, DecimalArithmetic arithmetic) {
		super(sm, tp.getOverflowMode(), arithmetic);
	}

	@Parameters(name = "{index}: {0}, {1}")
	public static Iterable<Object[]> data() {
		final List<Object[]> data = new ArrayList<Object[]>();
		for (final ScaleMetrics s : TestSettings.SCALES) {
			for (final TruncationPolicy tp : TestSettings.POLICIES) {
				final DecimalArithmetic arith = s.getArithmetic(tp);
				data.add(new Object[] {s, tp, arith});
			}
		}
		return data;
	}

	@Override
	protected String operation() {
		return "/";
	}

	@Override
	protected BigDecimal expectedResult(BigDecimal a, long b) {
		return a.divide(toBigDecimal(b), mathContextLong128);
	}

	@Override
	protected <S extends ScaleMetrics> Decimal<S> actualResult(Decimal<S> a, long b) {
		if (isStandardTruncationPolicy() && RND.nextBoolean()) {
			return a.divide(b);
		}
		if (isUnchecked() && RND.nextBoolean()) {
			return a.divide(b, getRoundingMode());
		}
		return a.divide(b, getTruncationPolicy());
	}

}


text:
<!DOCTYPE html>

	<link rel="stylesheet" href="../../build/aui-skin-classic/css/aui-skin-classic-all-min.css" type="text/css" media="screen" />

Alloy - LoadingMask Demo


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

#include "chrome/browser/permissions/permission_context_base.h"

#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/permissions/permission_bubble_request_impl.h"
#include "chrome/browser/permissions/permission_context_uma_util.h"
#include "chrome/browser/permissions/permission_queue_controller.h"
#include "chrome/browser/permissions/permission_request_id.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
#include "chrome/common/pref_names.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/browser/website_settings_registry.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/origin_util.h"

PermissionContextBase::PermissionContextBase(
    Profile* profile,
    const ContentSettingsType permission_type)
    : profile_(profile),
      permission_type_(permission_type),
      weak_factory_(this) {
  permission_queue_controller_.reset(
      new PermissionQueueController(profile_, permission_type_));
}

PermissionContextBase::~PermissionContextBase() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

void PermissionContextBase::RequestPermission(
    content::WebContents* web_contents,
    const PermissionRequestID& id,
    const GURL& requesting_frame,
    bool user_gesture,
    const BrowserPermissionCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  DecidePermission(web_contents,
                   id,
                   requesting_frame.GetOrigin(),
                   web_contents->GetLastCommittedURL().GetOrigin(),
                   user_gesture,
                   callback);
}

ContentSetting PermissionContextBase::GetPermissionStatus(
    const GURL& requesting_origin,
    const GURL& embedding_origin) const {
  if (IsRestrictedToSecureOrigins() &&
      !content::IsOriginSecure(requesting_origin)) {
    return CONTENT_SETTING_BLOCK;
  }

  return HostContentSettingsMapFactory::GetForProfile(profile_)
      ->GetContentSetting(requesting_origin,
                          embedding_origin,
                          permission_type_,
                          std::string());
}

void PermissionContextBase::ResetPermission(
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
  HostContentSettingsMapFactory::GetForProfile(profile_)->SetContentSetting(
      ContentSettingsPattern::FromURLNoWildcard(requesting_origin),
      ContentSettingsPattern::FromURLNoWildcard(embedding_origin),
      permission_type_, std::string(), CONTENT_SETTING_DEFAULT);
}

void PermissionContextBase::CancelPermissionRequest(
    content::WebContents* web_contents,
    const PermissionRequestID& id) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (PermissionBubbleManager::Enabled()) {
    PermissionBubbleRequest* cancelling =
        pending_bubbles_.get(id.ToString());
    if (cancelling != NULL && web_contents != NULL &&
        PermissionBubbleManager::FromWebContents(web_contents) != NULL) {
      PermissionBubbleManager::FromWebContents(web_contents)->
          CancelRequest(cancelling);
    }
    return;
  }

  GetQueueController()->CancelInfoBarRequest(id);
}

void PermissionContextBase::DecidePermission(
    content::WebContents* web_contents,
    const PermissionRequestID& id,
    const GURL& requesting_origin,
    const GURL& embedding_origin,
    bool user_gesture,
    const BrowserPermissionCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!requesting_origin.is_valid() || !embedding_origin.is_valid()) {
    std::string type_name =
        content_settings::WebsiteSettingsRegistry::GetInstance()
            ->Get(permission_type_)
            ->name();

    DVLOG(1) << "Attempt to use " << type_name
             << " from an invalid URL: " << requesting_origin << ","
             << embedding_origin << " (" << type_name
             << " is not supported in popups)";
    NotifyPermissionSet(id, requesting_origin, embedding_origin, callback,
                        false /* persist */, CONTENT_SETTING_BLOCK);
    return;
  }

  if (IsRestrictedToSecureOrigins() &&
      !content::IsOriginSecure(requesting_origin)) {
    NotifyPermissionSet(id, requesting_origin, embedding_origin, callback,
                        false /* persist */, CONTENT_SETTING_BLOCK);
    return;
  }

  ContentSetting content_setting =
      HostContentSettingsMapFactory::GetForProfile(profile_)
          ->GetContentSettingAndMaybeUpdateLastUsage(
              requesting_origin, embedding_origin, permission_type_,
              std::string());

  if (content_setting == CONTENT_SETTING_ALLOW ||
      content_setting == CONTENT_SETTING_BLOCK) {
    NotifyPermissionSet(id, requesting_origin, embedding_origin, callback,
                        false /* persist */, content_setting);
    return;
  }

  PermissionContextUmaUtil::PermissionRequested(
      permission_type_, requesting_origin, embedding_origin, profile_);

  if (PermissionBubbleManager::Enabled()) {
    PermissionBubbleManager* bubble_manager =
        PermissionBubbleManager::FromWebContents(web_contents);
    DCHECK(bubble_manager);
    scoped_ptr<PermissionBubbleRequest> request_ptr(
        new PermissionBubbleRequestImpl(
            requesting_origin, user_gesture, permission_type_,
            profile_->GetPrefs()->GetString(prefs::kAcceptLanguages),
            base::Bind(&PermissionContextBase::PermissionDecided,
                       weak_factory_.GetWeakPtr(), id, requesting_origin,
                       embedding_origin, callback),
            base::Bind(&PermissionContextBase::CleanUpBubble,
                       weak_factory_.GetWeakPtr(), id)));
    PermissionBubbleRequest* request = request_ptr.get();

    bool inserted = pending_bubbles_.add(
        id.ToString(), request_ptr.Pass()).second;
    DCHECK(inserted) << "Duplicate id " << id.ToString();
    bubble_manager->AddRequest(request);
    return;
  }

  // TODO(gbillock): Delete this and the infobar delegate when
  // we're using only bubbles. crbug.com/337458
  GetQueueController()->CreateInfoBarRequest(
      id, requesting_origin, embedding_origin,
      base::Bind(&PermissionContextBase::PermissionDecided,
                 weak_factory_.GetWeakPtr(), id, requesting_origin,
                 embedding_origin, callback,
                 // the queue controller takes care of persisting the
                 // permission
                 false));
}

void PermissionContextBase::PermissionDecided(
    const PermissionRequestID& id,
    const GURL& requesting_origin,
    const GURL& embedding_origin,
    const BrowserPermissionCallback& callback,
    bool persist,
    ContentSetting content_setting) {
  // Infobar persistance and its related UMA is tracked on the infobar
  // controller directly.
  if (PermissionBubbleManager::Enabled()) {
    if (persist) {
      DCHECK(content_setting == CONTENT_SETTING_ALLOW ||
             content_setting == CONTENT_SETTING_BLOCK);
      if (content_setting == CONTENT_SETTING_ALLOW)
        PermissionContextUmaUtil::PermissionGranted(permission_type_,
                                                    requesting_origin);
      else
        PermissionContextUmaUtil::PermissionDenied(permission_type_,
                                                   requesting_origin);
    } else {
      DCHECK_EQ(content_setting, CONTENT_SETTING_DEFAULT);
      PermissionContextUmaUtil::PermissionDismissed(permission_type_,
                                                    requesting_origin);
    }
  }

  NotifyPermissionSet(id, requesting_origin, embedding_origin, callback,
                      persist, content_setting);
}

PermissionQueueController* PermissionContextBase::GetQueueController() {
  return permission_queue_controller_.get();
}

Profile* PermissionContextBase::profile() const {
  return profile_;
}

void PermissionContextBase::NotifyPermissionSet(
    const PermissionRequestID& id,
    const GURL& requesting_origin,
    const GURL& embedding_origin,
    const BrowserPermissionCallback& callback,
    bool persist,
    ContentSetting content_setting) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (persist)
    UpdateContentSetting(requesting_origin, embedding_origin, content_setting);

  UpdateTabContext(id, requesting_origin,
                   content_setting == CONTENT_SETTING_ALLOW);

  if (content_setting == CONTENT_SETTING_DEFAULT) {
    content_setting =
        HostContentSettingsMapFactory::GetForProfile(profile_)
            ->GetDefaultContentSetting(permission_type_, nullptr);
  }

  DCHECK_NE(content_setting, CONTENT_SETTING_DEFAULT);
  callback.Run(content_setting);
}

void PermissionContextBase::CleanUpBubble(const PermissionRequestID& id) {
  size_t success = pending_bubbles_.erase(id.ToString());
  DCHECK(success == 1) << "Missing request " << id.ToString();
}

void PermissionContextBase::UpdateContentSetting(
    const GURL& requesting_origin,
    const GURL& embedding_origin,
    ContentSetting content_setting) {
  DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin());
  DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin());
  DCHECK(content_setting == CONTENT_SETTING_ALLOW ||
         content_setting == CONTENT_SETTING_BLOCK);

  HostContentSettingsMapFactory::GetForProfile(profile_)->SetContentSetting(
      ContentSettingsPattern::FromURLNoWildcard(requesting_origin),
      ContentSettingsPattern::FromURLNoWildcard(embedding_origin),
      permission_type_, std::string(), content_setting);
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.spring.cloud.actuator.storage;

import org.springframework.boot.actuate.health.Status;

/**
 * Azure Storage actuator related constants.
 */
final class StorageHealthConstants {

    private StorageHealthConstants() {
    }

    static final String URL_FIELD = "URL";

    static final String NOT_EXISTING_CONTAINER = "spring-cloud-azure-not-existing-container";

    static final Status NOT_CONFIGURED_STATUS = new Status("Not configured");
}


text:
package org.innovateuk.ifs.finance.builder;

import org.innovateuk.ifs.BaseBuilder;
import org.innovateuk.ifs.finance.resource.cost.PersonnelCost;

import java.math.BigDecimal;
import java.util.List;
import java.util.function.BiConsumer;

import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.uniqueIds;

public class PersonnelCostBuilder extends BaseBuilder<PersonnelCost, PersonnelCostBuilder> {

    public static PersonnelCostBuilder newPersonnelCost() {
        return new PersonnelCostBuilder(emptyList()).with(uniqueIds());
    }

    public PersonnelCostBuilder withId(Long... value) {
        return withArraySetFieldByReflection("id", value);
    }

    public PersonnelCostBuilder withName(String... value) {
        return withArraySetFieldByReflection("name", value);
    }

    public PersonnelCostBuilder withDescription(String... value) {
        return withArraySetFieldByReflection("description", value);
    }

    public PersonnelCostBuilder withRole(String... value) {
        return withArraySetFieldByReflection("role", value);
    }

    public PersonnelCostBuilder withGrossEmployeeCost(BigDecimal... value) {
        return withArraySetFieldByReflection("grossEmployeeCost", value);
    }

    public PersonnelCostBuilder withLabourDays(Integer... value) {
        return withArraySetFieldByReflection("labourDays", value);
    }

    public PersonnelCostBuilder withRate(BigDecimal... value) {
        return withArraySetFieldByReflection("rate", value);
    }

    public PersonnelCostBuilder withTotal(BigDecimal... value) {
        return withArraySetFieldByReflection("total", value);
    }

    public PersonnelCostBuilder withThirdPartyOfgem(boolean... value) {
        return withArraySetFieldByReflection("thirdPartyOfgem", value);
    }

    private PersonnelCostBuilder(List<BiConsumer<Integer, PersonnelCost>> multiActions) {
        super(multiActions);
    }

    @Override
    protected PersonnelCostBuilder createNewBuilderWithActions(List<BiConsumer<Integer, PersonnelCost>> actions) {
        return new PersonnelCostBuilder(actions);
    }

    @Override
    protected PersonnelCost createInitial() {
        return newInstance(PersonnelCost.class);
    }
}


text:
<!--
  ~ Copyright 2016 Red Hat, Inc. and/or its affiliates
  ~ and other contributors as indicated by the @author tags.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="keycloak-default" transaction-type="RESOURCE_LOCAL">
        <class>org.keycloak.models.jpa.entities.ClientEntity</class>
        <class>org.keycloak.models.jpa.entities.CredentialEntity</class>
        <class>org.keycloak.models.jpa.entities.CredentialAttributeEntity</class>
        <class>org.keycloak.models.jpa.entities.RealmEntity</class>
        <class>org.keycloak.models.jpa.entities.RealmAttributeEntity</class>
        <class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class>
        <class>org.keycloak.models.jpa.entities.ComponentConfigEntity</class>
        <class>org.keycloak.models.jpa.entities.ComponentEntity</class>
        <class>org.keycloak.models.jpa.entities.UserFederationProviderEntity</class>
        <class>org.keycloak.models.jpa.entities.UserFederationMapperEntity</class>
        <class>org.keycloak.models.jpa.entities.RoleEntity</class>
        <class>org.keycloak.models.jpa.entities.FederatedIdentityEntity</class>
        <class>org.keycloak.models.jpa.entities.MigrationModelEntity</class>
        <class>org.keycloak.models.jpa.entities.UserEntity</class>
        <class>org.keycloak.models.jpa.entities.UserRequiredActionEntity</class>
        <class>org.keycloak.models.jpa.entities.UserAttributeEntity</class>
        <class>org.keycloak.models.jpa.entities.UserRoleMappingEntity</class>
        <class>org.keycloak.models.jpa.entities.IdentityProviderEntity</class>
        <class>org.keycloak.models.jpa.entities.IdentityProviderMapperEntity</class>
        <class>org.keycloak.models.jpa.entities.ClientIdentityProviderMappingEntity</class>
        <class>org.keycloak.models.jpa.entities.ProtocolMapperEntity</class>
        <class>org.keycloak.models.jpa.entities.UserConsentEntity</class>
        <class>org.keycloak.models.jpa.entities.UserConsentRoleEntity</class>
        <class>org.keycloak.models.jpa.entities.UserConsentProtocolMapperEntity</class>
        <class>org.keycloak.models.jpa.entities.AuthenticationFlowEntity</class>
        <class>org.keycloak.models.jpa.entities.AuthenticationExecutionEntity</class>
        <class>org.keycloak.models.jpa.entities.AuthenticatorConfigEntity</class>
        <class>org.keycloak.models.jpa.entities.RequiredActionProviderEntity</class>
        <class>org.keycloak.models.jpa.session.PersistentUserSessionEntity</class>
        <class>org.keycloak.models.jpa.session.PersistentClientSessionEntity</class>
        <class>org.keycloak.models.jpa.entities.GroupEntity</class>
        <class>org.keycloak.models.jpa.entities.GroupAttributeEntity</class>
        <class>org.keycloak.models.jpa.entities.GroupRoleMappingEntity</class>
        <class>org.keycloak.models.jpa.entities.UserGroupMembershipEntity</class>
        <class>org.keycloak.models.jpa.entities.ClientTemplateEntity</class>
        <class>org.keycloak.models.jpa.entities.TemplateScopeMappingEntity</class>

        <!-- JpaAuditProviders -->
        <class>org.keycloak.events.jpa.EventEntity</class>
        <class>org.keycloak.events.jpa.AdminEventEntity</class>

        <!-- Authorization -->
        <class>org.keycloak.authorization.jpa.entities.ResourceServerEntity</class>
        <class>org.keycloak.authorization.jpa.entities.ResourceEntity</class>
        <class>org.keycloak.authorization.jpa.entities.ScopeEntity</class>
        <class>org.keycloak.authorization.jpa.entities.PolicyEntity</class>

        <!-- User Federation Storage -->
        <class>org.keycloak.storage.jpa.entity.BrokerLinkEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUser</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserAttributeEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserConsentEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserConsentRoleEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserConsentProtocolMapperEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserCredentialEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserCredentialAttributeEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserGroupMembershipEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserRequiredActionEntity</class>
        <class>org.keycloak.storage.jpa.entity.FederatedUserRoleMappingEntity</class>

        <exclude-unlisted-classes>true</exclude-unlisted-classes>

        <properties>
            <property name="jboss.as.jpa.managed" value="false"/>
        </properties>
    </persistence-unit>
</persistence>


text:
<!DOCTYPE html>

    <title>Tomas Kral</title>

    <meta name="robots" content="noindex">
    <meta charset="utf-8" />
    <meta name="google-site-verification" content="VPA4Fd1cxgNmU-0JC-030ZnZEDV9g8uWoSnAKSBvyT0" />

				<link rel="alternate" hreflang="cs" href="/cs" />
				<link rel="alternate" hreflang="en" href="/en" />

				<link rel="alternate" hreflang="x-default" href="/en" />


text:
{% extends './base.html' %}
{% block htmlclasses %}{% parent %} about{% endblock %}{% block htmlid %}{% endblock %}
{% block metadesc %}{% parent %}{% endblock %}
{% block title %}{% parent %}{% endblock %}
{% block headcss %}
{% parent %}
{% endblock %}

{% block header %}{% endblock %}

{% block mainclass %}{% endblock %}

					{% block bodycontent %}

Your online resume

Get connected with recruiters, job boards and potential employers

										Your name

													<input tabindex="0" class="hidden" type="checkbox">
													Looking for work?

									Tell us a little about yourself, your mission and your goals. This is where we learn about you as a person.

Job Title

Your job title

Location

city

Phone

tel

Email

your@email.com

							Work History

											Previous job title

											June 2016

										Enter a description of your previous job and the skills you used.

						<button class="ui right floated icon button addHistory"></button>

							<button class="ui huge primary button addCV">Save my CV </button>

							Share

											With
											<input placeholder="Email address" type="email">

											<select class="ui dropdown groupId">

											</select>

Customise

											<input tabindex="0" class="hidden" type="checkbox" checked>
											Email

											<input tabindex="0" class="hidden" type="checkbox">
											Phone

											<input tabindex="0" class="hidden" type="checkbox" checked>
											Job Title

											<input tabindex="0" class="hidden" type="checkbox" checked>
											Summary

									Send

					{% endblock %}


text:
require 'travis'
require 'date'

config_path = ENV.fetch('TRAVIS_CONFIG_PATH') { File.expand_path('.travis', Dir.home) }
config = YAML.load_file(File.expand_path('config.yml', config_path))
access_token = config['endpoints'].values[0]['access_token']

Travis.access_token = access_token

$days_of_builds_to_consider = 5

puts "build, branch, state, started_at, duration"

def log_durations
  repository = Travis::Repository.find('GoogleChrome/lighthouse')
  repository.each_build do |build|
    # next unless Integer(build.number) < 8283

    next if build.started_at.nil?

    # quit paginating at some point.
    if build.started_at < Time.now.to_date.prev_day($days_of_builds_to_consider).to_time
      exit 0
    end

    build.jobs.each do |job|
      puts "#{job.number}, #{job.branch_info}, #{job.state}, #{job.started_at}, #{job.duration}"
    end
  end
end

log_durations


text:
package com.fimtra.datafission;

import java.rmi.Remote;
import java.util.List;
import java.util.Set;

import com.fimtra.tcpchannel.TcpChannel.FrameEncodingFormatEnum;

/**
 * A codec provides methods to decode and encode messages between {@link IPublisherContext} and
 * {@link IObserverContext} objects.
 *
 * @param <T>
 *            the type of data object the codec works with
 * @author Ramon Servadei
 */
public interface ICodec<T>
{
    public enum CommandEnum
    {
        NOOP, SHOW, SUBSCRIBE, UNSUBSCRIBE, RPC, IDENTIFY
    }

    /**
     * Interpret the command from the received data
     *
     * @param decodedMessage
     *            the decoded data for the command
     * @throws IllegalArgumentException
     *             if the command cannot be interpreted
     */
    CommandEnum getCommand(T decodedMessage);

    /**
     * Get the identity argument from the identity command
     *
     * @param decodedMessage
     *            the decoded data for the identity command
     * @return the identity for the connecting proxy context
     */
    String getIdentityArgumentFromDecodedMessage(T decodedMessage);

    /**
     * Get the names of the records to subscribe for in the command.
     *

     * Note: the first item is the permission token
     *
     * @param decodedMessage
     *            the decoded data for the subscribe command
     * @return the names of the records in the subscribe command, the first item in this list is
     *         the permission token for the subscribe operation
     * @see IObserverContext#addObserver(String, IRecordListener, String...)
     */
    List<String> getSubscribeArgumentsFromDecodedMessage(T decodedMessage);

    /**
     * Get the names of the records to unsubscribe for in the command
     *
     * @param decodedMessage
     *            the decoded data for the subscribe command
     * @return the names of the records in the unsubscribe command
     */
    List<String> getUnsubscribeArgumentsFromDecodedMessage(T decodedMessage);

    /**
     * @return the message byte[] to send that represents the atomic change
     */
    byte[] getTxMessageForAtomicChange(IRecordChange atomicChange);

    /**
     * @param data
     *            the byte[] of the data holding an atomic change
     * @return the atomic change read from the decoded message
     */
    IRecordChange getAtomicChangeFromRxMessage(byte[] data);

    /**
     * @return the message byte[] to send that represents an identity call (this identifies the
     *         connecting proxy to the context)
     */
    byte[] getTxMessageForIdentify(String proxyIdentity);

    /**
     * @param names
     *            the list of record names to subscribe for. Note: the first item is a
     *            permission token.
     *
     * @return the message byte[] to send that represents a subscribe for the named records
     * @see #getSubscribeArgumentsFromDecodedMessage(Object)
     */
    byte[] getTxMessageForSubscribe(String... names);

    /**
     * @return the message byte[] to send that represents an unsubscribe for the named records
     */
    byte[] getTxMessageForUnsubscribe(String... names);

    /**
     * Create an {@link IRecordChange} representing the RPC and encode into a byte[]
     *
     * @param rpcName
     *            the RPC name
     * @param args
     *            the RPC arguments
     * @param resultRecordName
     *            the record name for the RPC result
     * @return the byte[] for the RPC call and details
     * @see Remote for a description of the atomic change structure
     * @see #getRpcFromRxMessage(byte[])
     */
    byte[] getTxMessageForRpc(String rpcName, IValue[] args, String resultRecordName);

    /**
     * Resolve an {@link IRecordChange} representing an RPC from the decoded message
     *
     * @param decodedMessage
     *            the message to resolve the RPC from
     * @return an {@link IRecordChange} holding the RPC details
     * @see Remote for a description of the atomic change structure
     * @see #getAtomicChangeFromRxMessage(byte[])
     */
    IRecordChange getRpcFromRxMessage(T decodedMessage);

    /**
     * @return the message to send that holds all the record names
     */
    byte[] getTxMessageForShow(Set<String> recordNames);

    /**
     * Decode the byte[] into the data object type
     */
    T decode(byte[] rxMessage);

    /**
     * @return the frame encoding format for the wire protocol for this codec
     */
    FrameEncodingFormatEnum getFrameEncodingFormat();

    /**
     * @return a new instance of this codec
     */
    ICodec<T> newInstance();
}


text:
If you need to find the Xpath to the current node in an XML document, try the Backtrack-xpath gem.

Example:

    require 'backtrack-xpath'

    xml =<<XML
    <root>

        <n/><x1/><x2/>
        <records>

            <y color='blue'/><y2/>
            <records>
              <c><n/><records/></c>
            </records>

            <y color='red'/><y2/>
            <records>
              <c><n/><records/></c>
            </records>

        </records>

    </root>
    XML

    doc = Rexle.new xml
    node = doc.root.element '//y'
    puts BacktrackXPath.new(node).to_xpath #=> root/a/records/b/summary/y

Note: An id or class attribute will be used in the XPath to help identify the element if they exist in any of the elements.

gem backtrackxpath xpath html


text:
package ch.liquidmind.ripples.intf.logical.type.generics;

import java.util.Set;

import ch.liquidmind.ripples.intf.logical.type.Type;

public interface Wildcard extends GenericType
{
	public Set< Type > getLowerBounds();
	public Set< Type > getUpperBounds();
}


text:
<?php

namespace Arodiss\XlsBundle\Xls\Builder;

use Arodiss\XlsBundle\Xls\Writer\BufferedWriter;
use Arodiss\XlsBundle\Xls\Writer\WriterInterface;

class XlsBuilder
{

    /** @var \Arodiss\XlsBundle\Xls\Writer\WriterInterface */
    protected $writer;

    /**
     * @param WriterInterface $writer
     */
    public function __construct(WriterInterface $writer)
    {
        $this->writer = $writer;
    }

    /**
     * @param array $rows
     * @return string
     * @throws \Exception
     */
    public function buildXlsFromArray(array $rows)
    {
        if (0 === count($rows)) {
            throw new \Exception("Cannot create empty file");
        }
        $tmpFile = tempnam(sys_get_temp_dir(), "xls-build") . ".xlsx";
        $this->writer->createAndWrite($tmpFile, $rows);
        if ($this->writer instanceof BufferedWriter) {
            $this->writer->flush();
        }
        return $tmpFile;
    }
}


text:
namespace metrics {

namespace {

// The name of the log channel to query.
const wchar_t kChannelName[] = L"System";

// Event ids of system startup / shutdown events. These were obtained from
// inspection of the System log in Event Viewer on Windows 10:
//   - id 6005: "The Event log service was started."
//   - id 6006: "The Event log service was stopped."
//   - id 6008: "The previous system shutdown at <time> on <date> was
//               unexpected."
const uint16_t kIdSessionStart = 6005U;
const uint16_t kIdSessionEnd = 6006U;
const uint16_t kIdSessionEndUnclean = 6008U;

// An XPATH expression to query for system startup / shutdown events. The query
// is expected to retrieve exactly one event for each startup (kIdSessionStart)
// and one event for each shutdown (either kIdSessionEnd or
// kIdSessionEndUnclean).
const wchar_t kSessionEventsQuery[] =
    L"*[System[Provider[@Name='eventlog']"
    L" and (EventID=6005 or EventID=6006 or EventID=6008)]]";

// XPath expressions to attributes of interest.
const wchar_t kEventIdPath[] = L"Event/System/EventID";
const wchar_t kEventTimePath[] = L"Event/System/TimeCreated/@SystemTime";

// The timeout to use for calls to ::EvtNext.
const uint32_t kTimeoutMs = 5000;

base::Time ULLFileTimeToTime(ULONGLONG time_ulonglong) {
  // Copy low / high parts as FILETIME is not always 64bit aligned.
  ULARGE_INTEGER time;
  time.QuadPart = time_ulonglong;
  FILETIME ft;
  ft.dwLowDateTime = time.LowPart;
  ft.dwHighDateTime = time.HighPart;

  return base::Time::FromFileTime(ft);
}

}  // namespace

SystemSessionAnalyzer::SystemSessionAnalyzer(uint32_t max_session_cnt)
    : max_session_cnt_(max_session_cnt), sessions_queried_(0) {}

SystemSessionAnalyzer::~SystemSessionAnalyzer() {}

SystemSessionAnalyzer::ExtendedStatus
SystemSessionAnalyzer::GetExtendedFailureStatus() const {
  return extended_status_;
}

void SystemSessionAnalyzer::SetExtendedFailureStatus(
    ExtendedStatus new_status) {
  if (extended_status_ == ExtendedStatus::NO_FAILURE)
    extended_status_ = new_status;
}

bool SystemSessionAnalyzer::GetEventInfo(
    EVT_HANDLE context,
    EVT_HANDLE event,
    SystemSessionAnalyzer::EventInfo* info) {
  DCHECK(context);
  DCHECK(event);
  DCHECK(info);

  // Retrieve attributes of interest from the event. We expect the context to
  // specify the retrieval of two attributes (event id and event time), each
  // with a specific type.
  const DWORD kAttributeCnt = 2U;
  std::vector<EVT_VARIANT> buffer(kAttributeCnt);
  DWORD buffer_size = kAttributeCnt * sizeof(EVT_VARIANT);
  DWORD buffer_used = 0U;
  DWORD retrieved_attribute_cnt = 0U;
  if (!::EvtRender(context, event, EvtRenderEventValues, buffer_size,
                   buffer.data(), &buffer_used, &retrieved_attribute_cnt)) {
    SetExtendedFailureStatus(ExtendedStatus::RENDER_EVENT_FAILURE);
    DLOG(ERROR) << "Failed to render the event.";
    return false;
  }

  // Validate the count and types of the retrieved attributes.
  if (retrieved_attribute_cnt != kAttributeCnt) {
    SetExtendedFailureStatus(ExtendedStatus::ATTRIBUTE_CNT_MISMATCH);
    return false;
  }
  if (buffer[0].Type != EvtVarTypeUInt16) {
    SetExtendedFailureStatus(ExtendedStatus::EXPECTED_INT16_TYPE);
    return false;
  }
  if (buffer[1].Type != EvtVarTypeFileTime) {
    SetExtendedFailureStatus(ExtendedStatus::EXPECTED_FILETIME_TYPE);
    return false;
  }

  info->event_id = buffer[0].UInt16Val;
  info->event_time = ULLFileTimeToTime(buffer[1].FileTimeVal);

  return true;
}

SystemSessionAnalyzer::Status SystemSessionAnalyzer::IsSessionUnclean(
    base::Time timestamp) {
  if (!EnsureInitialized()) {
    // Insufficient events in the error log is a special-case with its own error
    // code so that a truncated system log doesn't cause failures.
    if (GetExtendedFailureStatus() == ExtendedStatus::EVENT_COUNT_MISMATCH)
      return INSUFFICIENT_DATA;
    return INITIALIZE_FAILED;
  }

  while (timestamp < coverage_start_ && sessions_queried_ < max_session_cnt_) {
    // Fetch the next session start and end events.
    std::vector<EventInfo> events;
    if (!FetchEvents(2U, &events) || events.size() != 2)
      return FETCH_EVENTS_FAILED;

    if (!ProcessSession(events[0], events[1]))
      return PROCESS_SESSION_FAILED;

    ++sessions_queried_;
  }

  if (timestamp < coverage_start_)
    return OUTSIDE_RANGE;

  // Get the first session starting after the timestamp.
  std::map<base::Time, base::TimeDelta>::const_iterator it =
      unclean_sessions_.upper_bound(timestamp);
  if (it == unclean_sessions_.begin())
    return CLEAN;  // No prior unclean session.

  // Get the previous session and see if it encompasses the timestamp.
  --it;
  bool is_spanned = (timestamp - it->first) <= it->second;
  return is_spanned ? UNCLEAN : CLEAN;
}

bool SystemSessionAnalyzer::FetchEvents(size_t requested_events,
                                        std::vector<EventInfo>* event_infos) {
  DCHECK(event_infos);

  if (!EnsureHandlesOpened())
    return false;

  DCHECK(query_handle_.get());

  // Retrieve events: 2 events per session, plus the current session's start.
  DWORD desired_event_cnt = requested_events;
  std::vector<EVT_HANDLE> events_raw(desired_event_cnt, nullptr);
  DWORD event_cnt = 0U;
  BOOL success = ::EvtNext(query_handle_.get(), desired_event_cnt,
                           events_raw.data(), kTimeoutMs, 0, &event_cnt);

  // Ensure handles get closed. The MSDN sample seems to imply handles may need
  // to be closed event in if EvtNext failed.
  std::vector<EvtHandle> events(desired_event_cnt);
  for (size_t i = 0; i < event_cnt; ++i)
    events[i].reset(events_raw[i]);

  if (!success) {
    SetExtendedFailureStatus(ExtendedStatus::RETRIEVE_EVENTS_FAILURE);
    DLOG(ERROR) << "Failed to retrieve events.";
    return false;
  }

  std::vector<EventInfo> event_infos_tmp;
  event_infos_tmp.reserve(event_cnt);

  EventInfo info = {};
  for (size_t i = 0; i < event_cnt; ++i) {
    if (!GetEventInfo(render_context_.get(), events[i].get(), &info))
      return false;
    event_infos_tmp.push_back(info);
  }

  event_infos->swap(event_infos_tmp);
  return true;
}

bool SystemSessionAnalyzer::EnsureInitialized() {
  if (!initialized_) {
    DCHECK(!init_success_);
    init_success_ = Initialize();
    initialized_ = true;
  }

  return init_success_;
}

bool SystemSessionAnalyzer::EnsureHandlesOpened() {
  // Create the event query.
  // Note: requesting events from newest to oldest.
  if (!query_handle_.get()) {
    query_handle_.reset(
        ::EvtQuery(nullptr, kChannelName, kSessionEventsQuery,
                   EvtQueryChannelPath | EvtQueryReverseDirection));
    if (!query_handle_.get()) {
      SetExtendedFailureStatus(ExtendedStatus::EVTQUERY_FAILED);
      DLOG(ERROR) << "Event query failed.";
      return false;
    }
  }

  if (!render_context_.get()) {
    // Create the render context for extracting information from the events.
    render_context_ = CreateRenderContext();
    if (!render_context_.get()) {
      SetExtendedFailureStatus(ExtendedStatus::CREATE_RENDER_CONTEXT_FAILURE);
      return false;
    }
  }

  return true;
}

bool SystemSessionAnalyzer::Initialize() {
  DCHECK(!initialized_);

  // Fetch the first (current) session start event and the first session,
  // comprising an end and a start event for a total of 3 events.
  std::vector<EventInfo> events;
  if (!FetchEvents(3U, &events)) {
    SetExtendedFailureStatus(ExtendedStatus::FETCH_EVENTS_FAILURE);
    return false;
  }

  // Validate that the initial event is what we expect.
  if (events.size() != 3) {
    SetExtendedFailureStatus(ExtendedStatus::EVENT_COUNT_MISMATCH);
    return false;
  }
  if (events[0].event_id != kIdSessionStart) {
    SetExtendedFailureStatus(ExtendedStatus::SESSION_START_MISMATCH);
    return false;
  }

  // Initialize the coverage start to allow detecting event time inversion.
  coverage_start_ = events[0].event_time;

  if (!ProcessSession(events[1], events[2]))
    return false;

  sessions_queried_ = 1;

  return true;
}

bool SystemSessionAnalyzer::ProcessSession(const EventInfo& end,
                                           const EventInfo& start) {
  // Validate the ordering of events (newest to oldest). The  expectation is a
  // (start / [unclean]shutdown) pair of events for each session.
  if (coverage_start_ < end.event_time) {
    SetExtendedFailureStatus(ExtendedStatus::COVERAGE_START_ORDER_FAILURE);
    return false;
  }
  if (end.event_time < start.event_time) {
    SetExtendedFailureStatus(ExtendedStatus::EVENT_ORDER_FAILURE);
    return false;
  }

  // Process a (start / shutdown) event pair, validating the types of events
  // and recording unclean sessions.
  if (start.event_id != kIdSessionStart) {
    SetExtendedFailureStatus(ExtendedStatus::UNEXPECTED_START_EVENT_TYPE);
    return false;  // Unexpected event type.
  }
  if (end.event_id != kIdSessionEnd && end.event_id != kIdSessionEndUnclean) {
    SetExtendedFailureStatus(ExtendedStatus::UNEXPECTED_END_EVENT_TYPE);
    return false;  // Unexpected event type.
  }

  if (end.event_id == kIdSessionEndUnclean) {
    unclean_sessions_.insert(
        std::make_pair(start.event_time, end.event_time - start.event_time));
  }

  coverage_start_ = start.event_time;

  return true;
}

SystemSessionAnalyzer::EvtHandle SystemSessionAnalyzer::CreateRenderContext() {
  LPCWSTR value_paths[] = {kEventIdPath, kEventTimePath};
  const DWORD kValueCnt = base::size(value_paths);

  EVT_HANDLE context = nullptr;
  context =
      ::EvtCreateRenderContext(kValueCnt, value_paths, EvtRenderContextValues);
  if (!context)
    DLOG(ERROR) << "Failed to create render context.";

  return EvtHandle(context);
}

}  // namespace metrics