Deletes the user.

## SYNTAX

### ClientObject (Default)
```
Remove-SPClientUser [-ClientContext <ClientContext>] [-ClientObject] <User>
```

### Identity
```
Remove-SPClientUser [-ClientContext <ClientContext>] -Identity <Int32>
```

### Name
```
Remove-SPClientUser [-ClientContext <ClientContext>] -Name <String>
```

### Email
```
Remove-SPClientUser [-ClientContext <ClientContext>] -Email <String>
```

## DESCRIPTION
The Remove-SPClientUser function removes the user from the site.
If the user could not be found, throws exception.

## EXAMPLES

### -------------------------- Example 1 --------------------------
```
Remove-SPClientUser $user
```

### -------------------------- Example 2 --------------------------
```
Remove-SPClientUser -Identity 7
```

### -------------------------- Example 3 --------------------------
```
Remove-SPClientUser -Name "i:0#.f|membership|admin@example.com"
```

### -------------------------- Example 4 --------------------------
```
Remove-SPClientUser -Email "admin@example.com"
```

## PARAMETERS

### -ClientContext
Indicates the client context.
If not specified, uses a default context.

```yaml
Type: ClientContext
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: $SPClient.ClientContext
Accept pipeline input: False
Accept wildcard characters: False
```

### -ClientObject
Indicates the user to delete.

```yaml
Type: User
Parameter Sets: ClientObject
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -Identity
Indicates the user ID.

```yaml
Type: Int32
Parameter Sets: Identity
Aliases: Id

Required: True
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
Indicates the user login name.

```yaml
Type: String
Parameter Sets: Name
Aliases: LoginName

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Email
Indicates the user E-mail.

```yaml
Type: String
Parameter Sets: Email
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

## INPUTS

### None or Microsoft.SharePoint.Client.User

## OUTPUTS

### None

## NOTES

## RELATED LINKS

[https://github.com/karamem0/SPClient/blob/master/doc/Remove-SPClientUser.md](https://github.com/karamem0/SPClient/blob/master/doc/Remove-SPClientUser.md)


#ifndef ScrollingTreeNode_h
#define ScrollingTreeNode_h

#if ENABLE(THREADED_SCROLLING)

#include "IntRect.h"
#include "ScrollTypes.h"
#include "ScrollingCoordinator.h"
#include <wtf/PassOwnPtr.h>

namespace WebCore {

class ScrollingTreeNode {
public:
    explicit ScrollingTreeNode(ScrollingTree*);
    virtual ~ScrollingTreeNode();

    virtual void update(ScrollingStateNode*) = 0;

    ScrollingNodeID scrollingNodeID() const { return m_nodeID; }
    void setScrollingNodeID(ScrollingNodeID nodeID) { m_nodeID = nodeID; }

    ScrollingTreeNode* parent() const { return m_parent; }
    void setParent(ScrollingTreeNode* parent) { m_parent = parent; }

    void appendChild(PassOwnPtr<ScrollingTreeNode>);
    void removeChild(ScrollingTreeNode*);

protected:
    ScrollingTree* scrollingTree() const { return m_scrollingTree; }

private:
    ScrollingTree* m_scrollingTree;

    ScrollingNodeID m_nodeID;

    ScrollingTreeNode* m_parent;
    OwnPtr<Vector<OwnPtr<ScrollingTreeNode> > > m_children;
};

} // namespace WebCore

#endif // ENABLE(THREADED_SCROLLING)

#endif // ScrollingTreeNode_h


	jQuery(document).ready(function() {
	jQuery(function(){
		//Registration form validation
		jQuery('#registration_form').validate();
	});
});


"""
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

from __future__ import absolute_import

import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler

class SentryHandler(BaseSentryHandler):
    def __init__(self):
        logging.Handler.__init__(self)

    def _get_client(self):
        from raven.contrib.django.models import client

        return client

    client = property(_get_client)

    def _emit(self, record):
        from raven.contrib.django.middleware import SentryLogMiddleware

        # Fetch the request from a threadlocal variable, if available
        request = getattr(record, 'request', getattr(SentryLogMiddleware.thread, 'request', None))

        return super(SentryHandler, self)._emit(record, request=request)


require 'unit_spec_helper'

describe Rpush::Client::ActiveRecord::Apns::App do
  it_behaves_like 'Rpush::Client::Apns::App'
  it_behaves_like 'Rpush::Client::ActiveRecord::App'
end if active_record?


import React, { Component } from 'react';
import PropTypes from 'prop-types';

import classNames from 'classnames';

import '../../assets/scss/SimpleBanner.css';

class SimpleBannerComponent extends Component {
  static propTypes = {
    classNameBanner: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    classNameBannerTitle: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    classNameBannerTitleUpperText: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    classNameBannerTitleLowerText: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    upperText: PropTypes.string,
    lowerText: PropTypes.string,
  };

  static defaultProps = {
    classNameBanner: '',
    classNameBannerTitle: '',
    classNameBannerTitleUpperText: '',
    classNameBannerTitleLowerText: '',
    upperText: '',
    lowerText: '',
  };

  render() {
    const {
      classNameBanner,
      classNameBannerTitle,
      classNameBannerTitleUpperText,
      classNameBannerTitleLowerText,
      upperText,
      lowerText,
    } = this.props;

    const cls = {
      banner: classNames('simple-banner', classNameBanner),
      bannerOverlay: 'simple-banner__overlay',
      bannerTitle: classNames('simple-banner__title', classNameBannerTitle),
      bannerTitleTextLight: classNames('simple-banner__title__text simple-banner__title__text--light animated fadeInUp', classNameBannerTitleUpperText),
      bannerSmallTitleText: classNames('simple-banner__title__text simple-banner__title__text--small animated fadeInDown', classNameBannerTitleLowerText),
    };

    return (

          {upperText}
          {lowerText}

    )
  }
}

export default SimpleBannerComponent;


<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavadocGenerationManager">
    <option name="OUTPUT_DIRECTORY" value="$USER_HOME$/Desktop" />
    <option name="OPTION_SCOPE" value="protected" />
    <option name="OPTION_HIERARCHY" value="true" />
    <option name="OPTION_NAVIGATOR" value="true" />
    <option name="OPTION_INDEX" value="true" />
    <option name="OPTION_SEPARATE_INDEX" value="true" />
    <option name="OPTION_DOCUMENT_TAG_USE" value="true" />
    <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="true" />
    <option name="OPTION_DOCUMENT_TAG_VERSION" value="true" />
    <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
    <option name="OPTION_DEPRECATED_LIST" value="true" />
    <option name="OTHER_OPTIONS" />
    <option name="HEAP_SIZE" />
    <option name="LOCALE" />
    <option name="OPEN_IN_BROWSER" value="true" />
    <option name="OPTION_INCLUDE_LIBS" value="false" />
  </component>
  <component name="ProjectKey">
    <option name="state" value="project://e79810c8-c5c8-43b1-b19c-90c1f4095425" />
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


namespace sync_file_system {
namespace drive {

namespace {

const base::FilePath::CharType kV0FormatPathPrefix[] =
    FILE_PATH_LITERAL("drive/");
const char kWapiFileIdPrefix[] = "file:";
const char kWapiFolderIdPrefix[] = "folder:";

std::string RemovePrefix(const std::string& str, const std::string& prefix) {
  if (StartsWithASCII(str, prefix, true))
    return std::string(str.begin() + prefix.size(), str.end());
  return str;
}

}  // namespace

bool ParseV0FormatFileSystemURL(const GURL& url,
                                GURL* origin,
                                base::FilePath* path) {
  fileapi::FileSystemType mount_type;
  base::FilePath virtual_path;

  if (!fileapi::FileSystemURL::ParseFileSystemSchemeURL(
          url, origin, &mount_type, &virtual_path) ||
      mount_type != fileapi::kFileSystemTypeExternal) {
    NOTREACHED() << "Failed to parse filesystem scheme URL " << url.spec();
    return false;
  }

  base::FilePath::StringType prefix =
      base::FilePath(kV0FormatPathPrefix).NormalizePathSeparators().value();
  if (virtual_path.value().substr(0, prefix.size()) != prefix)
    return false;

  *path = base::FilePath(virtual_path.value().substr(prefix.size()));
  return true;
}

std::string AddWapiFilePrefix(const std::string& resource_id) {
  DCHECK(!StartsWithASCII(resource_id, kWapiFileIdPrefix, true));
  DCHECK(!StartsWithASCII(resource_id, kWapiFolderIdPrefix, true));

  if (resource_id.empty() ||
      StartsWithASCII(resource_id, kWapiFileIdPrefix, true) ||
      StartsWithASCII(resource_id, kWapiFolderIdPrefix, true))
    return resource_id;
  return kWapiFileIdPrefix + resource_id;
}

std::string AddWapiFolderPrefix(const std::string& resource_id) {
  DCHECK(!StartsWithASCII(resource_id, kWapiFileIdPrefix, true));
  DCHECK(!StartsWithASCII(resource_id, kWapiFolderIdPrefix, true));

  if (resource_id.empty() ||
      StartsWithASCII(resource_id, kWapiFileIdPrefix, true) ||
      StartsWithASCII(resource_id, kWapiFolderIdPrefix, true))
    return resource_id;
  return kWapiFolderIdPrefix + resource_id;
}

std::string AddWapiIdPrefix(const std::string& resource_id,
                            DriveMetadata_ResourceType type) {
  switch (type) {
    case DriveMetadata_ResourceType_RESOURCE_TYPE_FILE:
      return AddWapiFilePrefix(resource_id);
    case DriveMetadata_ResourceType_RESOURCE_TYPE_FOLDER:
      return AddWapiFolderPrefix(resource_id);
  }
  NOTREACHED();
  return resource_id;
}

std::string RemoveWapiIdPrefix(const std::string& resource_id) {
  if (StartsWithASCII(resource_id, kWapiFileIdPrefix, true))
    return RemovePrefix(resource_id, kWapiFileIdPrefix);
  if (StartsWithASCII(resource_id, kWapiFolderIdPrefix, true))
    return RemovePrefix(resource_id, kWapiFolderIdPrefix);
  return resource_id;
}

SyncStatusCode MigrateDatabaseFromV0ToV1(leveldb::DB* db) {
  // Version 0 database format:
  //   key: "CHANGE_STAMP"
  //   value: <Largest Changestamp>
  //
  //   key: "SYNC_ROOT_DIR"
  //   value: <Resource ID of the sync root directory>
  //
  //   key: "METADATA: " +
  //        <FileSystemURL serialized by SerializeSyncableFileSystemURL>
  //   value: <Serialized DriveMetadata>
  //
  //   key: "BSYNC_ORIGIN: " + <URL string of a batch sync origin>
  //   value: <Resource ID of the drive directory for the origin>
  //
  //   key: "ISYNC_ORIGIN: " + <URL string of a incremental sync origin>
  //   value: <Resource ID of the drive directory for the origin>
  //
  // Version 1 database format (changed keys/fields are marked with '*'):
  // * key: "VERSION" (new)
  // * value: 1
  //
  //   key: "CHANGE_STAMP"
  //   value: <Largest Changestamp>
  //
  //   key: "SYNC_ROOT_DIR"
  //   value: <Resource ID of the sync root directory>
  //
  // * key: "METADATA: " + <Origin and URL> (changed)
  // * value: <Serialized DriveMetadata>
  //
  //   key: "BSYNC_ORIGIN: " + <URL string of a batch sync origin>
  //   value: <Resource ID of the drive directory for the origin>
  //
  //   key: "ISYNC_ORIGIN: " + <URL string of a incremental sync origin>
  //   value: <Resource ID of the drive directory for the origin>
  //
  //   key: "DISABLED_ORIGIN: " + <URL string of a disabled origin>
  //   value: <Resource ID of the drive directory for the origin>

  const char kDatabaseVersionKey[] = "VERSION";
  const char kDriveMetadataKeyPrefix[] = "METADATA: ";
  const char kMetadataKeySeparator = ' ';

  leveldb::WriteBatch write_batch;
  write_batch.Put(kDatabaseVersionKey, "1");

  scoped_ptr<leveldb::Iterator> itr(db->NewIterator(leveldb::ReadOptions()));
  for (itr->Seek(kDriveMetadataKeyPrefix); itr->Valid(); itr->Next()) {
    std::string key = itr->key().ToString();
    if (!StartsWithASCII(key, kDriveMetadataKeyPrefix, true))
      break;
    std::string serialized_url(RemovePrefix(key, kDriveMetadataKeyPrefix));

    GURL origin;
    base::FilePath path;
    bool success = ParseV0FormatFileSystemURL(
        GURL(serialized_url), &origin, &path);
    DCHECK(success) << serialized_url;
    std::string new_key = kDriveMetadataKeyPrefix + origin.spec() +
        kMetadataKeySeparator + path.AsUTF8Unsafe();

    write_batch.Put(new_key, itr->value());
    write_batch.Delete(key);
  }

  return LevelDBStatusToSyncStatusCode(
      db->Write(leveldb::WriteOptions(), &write_batch));
}

SyncStatusCode MigrateDatabaseFromV1ToV2(leveldb::DB* db) {
  // Strips prefix of WAPI resource ID, and discards batch sync origins.
  // (i.e. "file:xxxx" => "xxxx", "folder:yyyy" => "yyyy")
  //
  // Version 2 database format (changed keys/fields are marked with '*'):
  //   key: "VERSION"
  // * value: 2
  //
  //   key: "CHANGE_STAMP"
  //   value: <Largest Changestamp>
  //
  //   key: "SYNC_ROOT_DIR"
  // * value: <Resource ID of the sync root directory> (striped)
  //
  //   key: "METADATA: " + <Origin and URL>
  // * value: <Serialized DriveMetadata> (stripped)
  //
  // * key: "BSYNC_ORIGIN: " + <URL string of a batch sync origin> (deleted)
  // * value: <Resource ID of the drive directory for the origin> (deleted)
  //
  //   key: "ISYNC_ORIGIN: " + <URL string of a incremental sync origin>
  // * value: <Resource ID of the drive directory for the origin> (stripped)
  //
  //   key: "DISABLED_ORIGIN: " + <URL string of a disabled origin>
  // * value: <Resource ID of the drive directory for the origin> (stripped)

  const char kDatabaseVersionKey[] = "VERSION";
  const char kSyncRootDirectoryKey[] = "SYNC_ROOT_DIR";
  const char kDriveMetadataKeyPrefix[] = "METADATA: ";
  const char kDriveBatchSyncOriginKeyPrefix[] = "BSYNC_ORIGIN: ";
  const char kDriveIncrementalSyncOriginKeyPrefix[] = "ISYNC_ORIGIN: ";
  const char kDriveDisabledOriginKeyPrefix[] = "DISABLED_ORIGIN: ";

  leveldb::WriteBatch write_batch;
  write_batch.Put(kDatabaseVersionKey, "2");

  scoped_ptr<leveldb::Iterator> itr(db->NewIterator(leveldb::ReadOptions()));
  for (itr->SeekToFirst(); itr->Valid(); itr->Next()) {
    std::string key = itr->key().ToString();

    // Strip resource id for the sync root directory.
    if (StartsWithASCII(key, kSyncRootDirectoryKey, true)) {
      write_batch.Put(key, RemoveWapiIdPrefix(itr->value().ToString()));
      continue;
    }

    // Strip resource ids in the drive metadata.
    if (StartsWithASCII(key, kDriveMetadataKeyPrefix, true)) {
      DriveMetadata metadata;
      bool success = metadata.ParseFromString(itr->value().ToString());
      DCHECK(success);

      metadata.set_resource_id(RemoveWapiIdPrefix(metadata.resource_id()));
      std::string metadata_string;
      metadata.SerializeToString(&metadata_string);

      write_batch.Put(key, metadata_string);
      continue;
    }

    // Deprecate legacy batch sync origin entries that are no longer needed.
    if (StartsWithASCII(key, kDriveBatchSyncOriginKeyPrefix, true)) {
      write_batch.Delete(key);
      continue;
    }

    // Strip resource ids of the incremental sync origins.
    if (StartsWithASCII(key, kDriveIncrementalSyncOriginKeyPrefix, true)) {
      write_batch.Put(key, RemoveWapiIdPrefix(itr->value().ToString()));
      continue;
    }

    // Strip resource ids of the disabled sync origins.
    if (StartsWithASCII(key, kDriveDisabledOriginKeyPrefix, true)) {
      write_batch.Put(key, RemoveWapiIdPrefix(itr->value().ToString()));
      continue;
    }
  }

  return LevelDBStatusToSyncStatusCode(
      db->Write(leveldb::WriteOptions(), &write_batch));
}

}  // namespace drive
}  // namespace sync_file_system


// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Management.BackupServices.Models;
using MBS = Microsoft.Azure.Management.BackupServices;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.Azure.Commands.AzureBackup.Properties;
using Microsoft.Azure.Commands.AzureBackup.Models;
using Microsoft.Azure.Commands.AzureBackup.Helpers;
using Microsoft.Azure.Management.BackupServices;

namespace Microsoft.Azure.Commands.AzureBackup.Cmdlets
{
    /// <summary>
    /// Enables reregistration of a machine container
    /// </summary>
    [Cmdlet(VerbsLifecycle.Enable, "AzureRMBackupContainerReregistration")]
    public class EnableAzureRMBackupContainerReregistration : AzureBackupContainerCmdletBase
    {
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                AzureBackupContainerType containerType = (AzureBackupContainerType)Enum.Parse(typeof(AzureBackupContainerType), Container.ContainerType);
                switch (containerType)
                {
                    case AzureBackupContainerType.Windows:
                    case AzureBackupContainerType.SCDPM:
                        AzureBackupClient.EnableMachineContainerReregistration(Container.ResourceGroupName, Container.ResourceName, Container.Id);
                        break;
                    default:
                        throw new ArgumentException(Resources.CannotEnableRegistration);
                }
            });
        }
    }
}


class WDTypedResult;

//
// Result types for WebDataService.
//
typedef enum {
  BOOL_RESULT = 1,               // WDResult<bool>
  KEYWORDS_RESULT,               // WDResult<WDKeywordsResult>
  INT64_RESULT,                  // WDResult<int64_t>
#if defined(OS_WIN)              //
  PASSWORD_IE7_RESULT,           // WDResult<IE7PasswordInfo>
#endif                           //
  WEB_APP_IMAGES,                // WDResult<WDAppImagesResult>
  TOKEN_RESULT,                  // WDResult<TokenResult>
  AUTOFILL_VALUE_RESULT,         // WDResult<std::vector<AutofillEntry>>
  AUTOFILL_CLEANUP_RESULT,       // WDResult<size_t>
  AUTOFILL_CHANGES,              // WDResult<std::vector<AutofillChange>>
  AUTOFILL_PROFILE_RESULT,       // WDResult<AutofillProfile>
  AUTOFILL_PROFILES_RESULT,      // WDResult<std::vector<
                                 //     std::unique_ptr<AutofillProfile>>>
  AUTOFILL_CLOUDTOKEN_RESULT,    // WDResult<std::vector<std::unique_ptr<
                                 //     CreditCardCloudTokenData>>>
  AUTOFILL_CREDITCARD_RESULT,    // WDResult<CreditCard>
  AUTOFILL_CREDITCARDS_RESULT,   // WDResult<std::vector<
                                 //     std::unique_ptr<CreditCard>>>
  AUTOFILL_CUSTOMERDATA_RESULT,  // WDResult<std::unique_ptr<
                                 //     PaymentsCustomerData>>
  AUTOFILL_UPI_RESULT,           // WDResult<std::string>
#if !defined(OS_IOS)             //
  PAYMENT_WEB_APP_MANIFEST,      // WDResult<std::vector<
                                 //     mojom::WebAppManifestSectionPtr>>
  PAYMENT_METHOD_MANIFEST,       // WDResult<std::vector<std::string>>
#endif
} WDResultType;

//
// The top level class for a result.
//
class WEBDATA_EXPORT WDTypedResult {
 public:
  virtual ~WDTypedResult() {}

  // Return the result type.
  WDResultType GetType() const { return type_; }

 protected:
  explicit WDTypedResult(WDResultType type) : type_(type) {}

 private:
  WDResultType type_;
  DISALLOW_COPY_AND_ASSIGN(WDTypedResult);
};

// A result containing one specific pointer or literal value.
template <class T>
class WDResult : public WDTypedResult {
 public:
  WDResult(WDResultType type, const T& v) : WDTypedResult(type), value_(v) {}
  WDResult(WDResultType type, T&& v)
      : WDTypedResult(type), value_(std::move(v)) {}

  ~WDResult() override {}

  // Return a single value result.
  const T& GetValue() const { return value_; }
  T GetValue() { return std::move(value_); }

 private:
  T value_;

  DISALLOW_COPY_AND_ASSIGN(WDResult);
};

#endif  // COMPONENTS_WEBDATA_COMMON_WEB_DATA_RESULTS_H_


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.river.api.io (River-Internet vtrunk API Documentation)</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.river.api.io

Interfaces

AtomicSerial.ReadObject

Classes

AtomicExternal.Factory

AtomicMarshalInputStream

AtomicMarshalOutputStream

AtomicSerial.Factory

AtomicSerial.GetArg

DeSerializationPermission

UnsuportedOperationException

Valid

Enums

AtomicMarshalInputStream.Reference

Exceptions

AtomicException

Annotation Types

AtomicExternal

AtomicSerial

AtomicSerial.ReadInput

Serializer


angular
    .module("avaliacao", ['ui.router', 'ui.bootstrap'])
    .config(["$stateProvider", '$urlRouterProvider', "$locationProvider", routes]);

function routes($stateProvider, $urlRouterProvider, $locationProvider) {
    $urlRouterProvider.otherwise('/');
   /*
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false

    });
    */
    $stateProvider
        .state('home', {
            url: '/',
            templateUrl: 'templates/home.html'
        })
        .state('Login', {
            url: '/Login',
            templateUrl: 'templates/Login.html'
        });
}


import './index';

import sinon from 'sinon';
import { expect } from 'chai';
import { $, $$ } from 'common-sk/modules/dom';
import fetchMock from 'fetch-mock';

import { GetTasksResponse } from '../json';
import {
  singleResultCanDelete, singleResultNoDelete, resultSetOneItem, resultSetTwoItems,
} from './test_data';
import {
  eventPromise,
  setUpElementUnderTest,
} from '../../../infra-sk/modules/test_util';

describe('task-queue-sk', () => {
  const newInstance = setUpElementUnderTest('task-queue-sk');
  fetchMock.config.overwriteRoutes = false;

  const loadTable = async () => {
    const event = eventPromise('end-task');
    const taskTableSk = newInstance();
    await event;
    return taskTableSk;
  };
  const loadTableWithReplies = async (replies: GetTasksResponse[]) => {
    const kNumTaskQueries = 16;
    const replyCount = replies.length;
    expect(replyCount).to.be.most(kNumTaskQueries);
    for (let i = 0; i < replyCount; ++i) {
      fetchMock.postOnce('begin:/_/get_', replies[i]);
    }
    fetchMock.post('begin:/_/get_', 200, { repeat: kNumTaskQueries - replyCount });

    return loadTable();
  };

  afterEach(() => {
    //  Check all mock fetches called at least once and reset.
    expect(fetchMock.done()).to.be.true;
    fetchMock.reset();
    sinon.restore();
  });

  it('shows table entries', async () => {
    // Return some results for 2 of the 16 task queries.
    const table = await loadTableWithReplies([resultSetOneItem, resultSetTwoItems]);

    // (3 items) * 6 columns
    expect($('td', table).length).to.equal(18);
  });

  it('delete option shown', async () => {
    const table = await loadTableWithReplies([singleResultCanDelete]);

    expect($$('delete-icon-sk', table)).to.have.property('hidden', false);
  });

  it('delete option hidden', async () => {
    const table = await loadTableWithReplies([singleResultNoDelete]);

    expect($$('delete-icon-sk', table)).to.have.property('hidden', true);
  });

  it('delete flow works', async () => {
    const table = await loadTableWithReplies([singleResultCanDelete]);

    sinon.stub(window, 'confirm').returns(true);
    sinon.stub(window, 'alert');
    fetchMock.postOnce((url, options) => url.startsWith('/_/delete_') && options.body === JSON.stringify({ id: 1 }), 200);
    ($$('delete-icon-sk', table) as HTMLElement).click();
  });

  it('task details works', async () => {
    const table = await loadTableWithReplies([resultSetOneItem]);

    expect($$('.dialog-background', table)!.classList.value).to.include('hidden');
    expect($$('.dialog-background', table)!.classList.value).to.include('hidden');
    ($$('.details', table) as HTMLElement).click();

    expect($$('.dialog-background', table)!.classList.value).to.not.include('hidden');
  });
});


#pragma once
#ifndef EL_READ_ASCII_HPP
#define EL_READ_ASCII_HPP

namespace El {
namespace read {

template<typename T>
inline void
Ascii( Matrix<T>& A, const string filename )
{
    DEBUG_ONLY(CSE cse("read::Ascii"))
    std::ifstream file( filename.c_str() );
    if( !file.is_open() )
        RuntimeError("Could not open ",filename);

    // Walk through the file once to both count the number of rows and
    // columns and to ensure that the number of columns is consistent
    Int height=0, width=0;
    string line;
    while( std::getline( file, line ) )
    {
        std::stringstream lineStream( line );
        Int numCols=0;
        T value;
        while( lineStream >> value ) ++numCols;
        if( numCols != 0 )
        {
            if( numCols != width && width != 0 )
                LogicError("Inconsistent number of columns");
            else
                width = numCols;
            ++height;
        }
    }
    file.clear();
    file.seekg(0,file.beg);

    // Resize the matrix and then read it
    A.Resize( height, width );
    Int i=0;
    while( std::getline( file, line ) )
    {
        std::stringstream lineStream( line );
        Int j=0;
        T value;
        while( lineStream >> value )
        {
            A.Set( i, j, value );
            ++j;
        }
        ++i;
    }
}

template<typename T>
inline void
Ascii( AbstractDistMatrix<T>& A, const string filename )
{
    DEBUG_ONLY(CSE cse("read::Ascii"))
    std::ifstream file( filename.c_str() );
    if( !file.is_open() )
        RuntimeError("Could not open ",filename);

    // Walk through the file once to both count the number of rows and
    // columns and to ensure that the number of columns is consistent
    Int height=0, width=0;
    string line;
    while( std::getline( file, line ) )
    {
        std::stringstream lineStream( line );
        Int numCols=0;
        T value;
        while( lineStream >> value ) ++numCols;
        if( numCols != 0 )
        {
            if( numCols != width && width != 0 )
                LogicError("Inconsistent number of columns");
            else
                width = numCols;
            ++height;
        }
    }
    file.clear();
    file.seekg(0,file.beg);

    // Resize the matrix and then read in our local portion
    A.Resize( height, width );
    Int i=0;
    while( std::getline( file, line ) )
    {
        std::stringstream lineStream( line );
        Int j=0;
        T value;
        while( lineStream >> value )
        {
            A.Set( i, j, value );
            ++j;
        }
        ++i;
    }
}

template<typename T>
inline void
Ascii( AbstractBlockDistMatrix<T>& A, const string filename )
{
    DEBUG_ONLY(CSE cse("read::Ascii"))
    std::ifstream file( filename.c_str() );
    if( !file.is_open() )
        RuntimeError("Could not open ",filename);

    // Walk through the file once to both count the number of rows and
    // columns and to ensure that the number of columns is consistent
    Int height=0, width=0;
    string line;
    while( std::getline( file, line ) )
    {
        std::stringstream lineStream( line );
        Int numCols=0;
        T value;
        while( lineStream >> value ) ++numCols;
        if( numCols != 0 )
        {
            if( numCols != width && width != 0 )
                LogicError("Inconsistent number of columns");
            else
                width = numCols;
            ++height;
        }
    }
    file.clear();
    file.seekg(0,file.beg);

    // Resize the matrix and then read in our local portion
    A.Resize( height, width );
    Int i=0;
    while( std::getline( file, line ) )
    {
        std::stringstream lineStream( line );
        Int j=0;
        T value;
        while( lineStream >> value )
        {
            A.Set( i, j, value );
            ++j;
        }
        ++i;
    }
}

} // namespace read
} // namespace El

#endif // ifndef EL_READ_ASCII_HPP


<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>opam-website: Not compatible</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / released

8.5.0 / opam-website - 1.2.1

            « Up

              opam-website

                1.2.1
                Not compatible

 (2020-06-25 03:38:52 UTC)

Context

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-num            base        Num library distributed with the OCaml compiler
base-threads        base
base-unix           base
camlp5              7.12        Preprocessor-pretty-printer of OCaml
conf-findutils      1           Virtual package relying on findutils
coq                 8.5.0       Formal proof management system.
num                 0           The Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.05.0      The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0      Official 4.05.0 release
ocaml-config        1           OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "dev@clarus.me"
homepage: "https://github.com/clarus/coq-opam-website"
dev-repo: "git+https://github.com/clarus/coq-opam-website.git"
bug-reports: "https://github.com/clarus/coq-opam-website/issues"
authors: ["Guillaume Claret"]
license: "MIT"
build: [
  ["./configure.sh"]
  [make "-j%{jobs}%"]
  ["sh" "-c" "cd extraction && make"]
]
depends: [
  "ocaml"
  "coq" {>= "8.4pl4"}
  "coq-io" {>= "3.1.0"}
  "coq-io-exception" {>= "1.0.0"}
  "coq-io-system" {>= "2.3.0"}
  "coq-list-string" {>= "2.1.0"}
]
synopsis: "Generation of a Coq website for OPAM: http://coq.io/opam/ "
url {
  src: "https://github.com/coq-io/opam-website/archive/1.2.1.tar.gz"
  checksum: "md5=8456933fe4380095c46240546fb2bad1"
}

Lint

Command

true

Return code

0

Dry install

Dry install with the current Coq version:

Command

opam install -y --show-action coq-opam-website.1.2.1 coq.8.5.0

Return code

5120

Output

[NOTE] Package coq is already installed (current version is 8.5.0).
The following dependencies couldn't be met:
  - coq-opam-website -> coq-io-exception -> coq < 8.5~ -> ocaml < 4.03.0
      base of this switch (use `--unlock-base' to force)
No solution found, exiting

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

opam remove -y coq; opam install -y --show-action --unlock-base coq-opam-website.1.2.1

Return code

0

Install dependencies

Command

true

Return code

0

Duration

0 s

Install

Command

true

Return code

0

Duration

0 s

Installation size

No files were installed.

Uninstall

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub. © Guillaume Claret.


#include "unix/guts.h"
#include "Application.h"
#include "Clipboard.h"
#include "Icon.h"

#define WIN PComponent(application)-> handle

#define CF_NAME(x)   (guts. clipboard_formats[(x)*3])
#define CF_TYPE(x)   (guts. clipboard_formats[(x)*3+1])
#define CF_FORMAT(x) (guts. clipboard_formats[(x)*3+2])
#define CF_ASSIGN(i,a,b,c) CF_NAME(i)=(a);CF_TYPE(i)=(b);CF_FORMAT(i)=((Atom)c)
#define CF_32        (sizeof(long)*8)        /* 32-bit properties are hacky */

Bool
prima_init_clipboard_subsystem(char * error_buf)
{
   guts. clipboards = hash_create();

   if ( !(guts. clipboard_formats = malloc( cfCOUNT * 3 * sizeof(Atom)))) {
      sprintf( error_buf, "No memory");
      return false;
   }
   guts. clipboard_formats_count = cfCOUNT;
#if (cfText != 0) || (cfBitmap != 1) || (cfUTF8 != 2)
#error broken clipboard type formats
#endif

   CF_ASSIGN(cfText, XA_STRING, XA_STRING, 8);
   CF_ASSIGN(cfUTF8, UTF8_STRING, UTF8_STRING, 8);
   CF_ASSIGN(cfBitmap, XA_PIXMAP, XA_PIXMAP, CF_32);
   CF_ASSIGN(cfTargets, CF_TARGETS, XA_ATOM, CF_32);

   /* XXX - bitmaps and indexed pixmaps may have the associated colormap or pixel values
   CF_ASSIGN(cfPalette, XA_COLORMAP, XA_ATOM, CF_32);
   CF_ASSIGN(cfForeground, CF_FOREGROUND, CF_PIXEL, CF_32);
   CF_ASSIGN(cfBackground, CF_BACKGROUND, CF_PIXEL, CF_32);
   */

   guts. clipboard_event_timeout = 2000;
   return true;
}

PList
apc_get_standard_clipboards( void)
{
   PList l = plist_create( 3, 1);
   if (!l) return nil;
   list_add( l, (Handle)duplicate_string( "Primary"));
   list_add( l, (Handle)duplicate_string( "Secondary"));
   list_add( l, (Handle)duplicate_string( "Clipboard"));
   return l;
}

Bool
apc_clipboard_create( Handle self)
{
   PClipboard c = (PClipboard)self;
   char *name, *x;
   DEFCC;

   XX-> selection = None;

   name = x = duplicate_string( c-> name);
   while (*x) {
      *x = toupper(*x);
      x++;
   }
   XX-> selection = XInternAtom( DISP, name, false);
   free( name);

   if ( hash_fetch( guts.clipboards, &XX->selection, sizeof(XX->selection))) {
      warn("This clipboard is already present");
      return false;
   }

   if ( !( XX-> internal = malloc( sizeof( ClipboardDataItem) * cfCOUNT))) {
      warn("Not enough memory");
      return false;
   }
   if ( !( XX-> external = malloc( sizeof( ClipboardDataItem) * cfCOUNT))) {
      free( XX-> internal);
      warn("Not enough memory");
      return false;
   }
   bzero( XX-> internal, sizeof( ClipboardDataItem) * cfCOUNT);
   bzero( XX-> external, sizeof( ClipboardDataItem) * cfCOUNT);

   hash_store( guts.clipboards, &XX->selection, sizeof(XX->selection), (void*)self);

   return true;
}

static void
clipboard_free_data( void * data, int size, Handle id)
{
   if ( size <= 0) {
      if ( size == 0 && data != nil) free( data);
      return;
   }
   if ( id == cfBitmap) {
      int i;
      Pixmap * p = (Pixmap*) data;
      for ( i = 0; i < size/sizeof(Pixmap); i++, p++)
         if ( *p)
            XFreePixmap( DISP, *p);
   }
   free( data);
}

/*
   each clipboard type can be represented by a set of
   X properties pairs, where each is X name and X type.
   get_typename() returns such pairs by the index.
 */
static Atom
get_typename( Handle id, int index, Atom * type)
{
   if ( type) *type = None;
   switch ( id) {
   case cfUTF8:
      if ( index > 1) return None;
      if ( index == 0) {
         if ( type) *type = CF_TYPE(id);
         return CF_NAME(id);
      } else {
         if ( type) *type = UTF8_MIME;
         return UTF8_MIME;
      }
   case cfBitmap:
      if ( index > 1) return None;
      if ( index == 0) {
         if ( type) *type = CF_TYPE(id);
	 return CF_NAME(id);
      } else {
         if ( type) *type = XA_BITMAP;
	 return XA_BITMAP;
      }
   case cfTargets:
      if ( index > 1) return None;
      if ( index == 0) {
         if ( type) *type = CF_TYPE(id);
         return CF_NAME(id);
      } else {
         if ( type) *type = CF_TARGETS;
         return CF_NAME(id);
      }
   }
   if ( index > 0) return None;
   if ( type) *type = CF_TYPE(id);
   return CF_NAME(id);
}

static void
clipboard_kill_item( PClipboardDataItem item, Handle id)
{
   item += id;
   clipboard_free_data( item-> data, item-> size, id);
   item-> data = nil;
   item-> size = 0;
   item-> name = get_typename( id, 0, nil);
}

/*
   Deletes a transfer record from pending xfer chain.
 */
static void
delete_xfer( PClipboardSysData cc, ClipboardXfer * xfer)
{
   ClipboardXferKey key;
   CLIPBOARD_XFER_KEY( key, xfer-> requestor, xfer-> property);
   if ( guts. clipboard_xfers) {
      IV refcnt;
      hash_delete( guts. clipboard_xfers, key, sizeof( key), false);
      refcnt = PTR2IV( hash_fetch( guts. clipboard_xfers, &xfer-> requestor, sizeof(XWindow)));
      if ( --refcnt == 0) {
         XSelectInput( DISP, xfer-> requestor, 0);
         hash_delete( guts. clipboard_xfers, &xfer-> requestor, sizeof(XWindow), false);
      } else {
         if ( refcnt < 0) refcnt = 0;
         hash_store( guts. clipboard_xfers, &xfer-> requestor, sizeof(XWindow), INT2PTR(void*, refcnt));
      }
   }
   if ( cc-> xfers)
      list_delete( cc-> xfers, ( Handle) xfer);
   if ( xfer-> data_detached && xfer-> data_master)
      clipboard_free_data( xfer-> data, xfer-> size, xfer-> id);
   free( xfer);
}

Bool
apc_clipboard_destroy( Handle self)
{
   DEFCC;
   int i;

   if (XX-> selection == None) return true;

   if ( XX-> xfers) {
      for ( i = 0; i < XX-> xfers-> count; i++)
         delete_xfer( XX, ( ClipboardXfer*) XX-> xfers-> items[i]);
      plist_destroy( XX-> xfers);
   }

   for ( i = 0; i < guts. clipboard_formats_count; i++) {
      if ( XX-> external) clipboard_kill_item( XX-> external, i);
      if ( XX-> internal) clipboard_kill_item( XX-> internal, i);
   }

   free( XX-> external);
   free( XX-> internal);
   hash_delete( guts.clipboards, &XX->selection, sizeof(XX->selection), false);

   XX-> selection = None;
   return true;
}

Bool
apc_clipboard_open( Handle self)
{
   DEFCC;
   if ( XX-> opened) return false;
   XX-> opened = true;

   if ( !XX-> inside_event) XX-> need_write = false;

   return true;
}

Bool
apc_clipboard_close( Handle self)
{
   DEFCC;
   if ( !XX-> opened) return false;
   XX-> opened = false;

   /* check if UTF8 is present and Text is not, and downgrade */
   if ( XX-> need_write &&
	XX-> internal[cfUTF8]. size > 0 &&
	XX-> internal[cfText]. size == 0) {
      Byte * src = XX-> internal[cfUTF8]. data;
      int len    = utf8_length( src, src + XX-> internal[cfUTF8]. size);
      if (( XX-> internal[cfText]. data = malloc( len))) {
	  STRLEN charlen;
	  U8 *dst;
	  dst = XX-> internal[cfText]. data;
          XX-> internal[cfText]. size = len;
	  while ( len--) {
             register UV u =
#if PERL_PATCHLEVEL >= 16
	     utf8_to_uvchr_buf( src, src + XX-> internal[cfUTF8]. size, &charlen);
#else
	     utf8_to_uvchr( src, &charlen)
#endif
	     ;
	     *(dst++) = ( u < 0x7f) ? u : '?'; /* XXX employ $LANG and iconv() */
	     src += charlen;
	  }
      }
   }

   if ( !XX-> inside_event) {
      int i;
      for ( i = 0; i < guts. clipboard_formats_count; i++)
         clipboard_kill_item( XX-> external, i);
      if ( XX-> need_write)
         if ( XGetSelectionOwner( DISP, XX-> selection) != WIN)
            XSetSelectionOwner( DISP, XX-> selection, WIN, CurrentTime);
   }

   return true;
}

/*
   Detaches data for pending transfers from XX, so eventual changes
   to XX->internal would not affect them. detach_xfers() should be
   called before clipboard_kill_item(XX-> internal), otherwise
   there's a chance of coredump.
 */
static void
detach_xfers( PClipboardSysData XX, Handle id, Bool clear_original_data)
{
   int i, got_master = 0, got_anything = 0;
   if ( !XX-> xfers) return;
   for ( i = 0; i < XX-> xfers-> count; i++) {
      ClipboardXfer * x = ( ClipboardXfer *) XX-> xfers-> items[i];
      if ( x-> data_detached || x-> id != id) continue;
      got_anything = 1;
      if ( !got_master) {
         x-> data_master = true;
         got_master = 1;
      }
      x-> data_detached = true;
   }
   if ( got_anything && clear_original_data) {
      XX-> internal[id]. data = nil;
      XX-> internal[id]. size = 0;
      XX-> internal[id]. name = get_typename( id, 0, nil);
   }
}

Bool
apc_clipboard_clear( Handle self)
{
   DEFCC;
   int i;

   for ( i = 0; i < guts. clipboard_formats_count; i++) {
      detach_xfers( XX, i, true);
      clipboard_kill_item( XX-> internal, i);
      clipboard_kill_item( XX-> external, i);
   }

   if ( XX-> inside_event) {
     XX-> need_write = true;
   } else {
     XWindow owner = XGetSelectionOwner( DISP, XX-> selection);
     XX-> need_write = false;
     if ( owner != None && owner != WIN)
        XSetSelectionOwner( DISP, XX-> selection, None, CurrentTime);
   }

   return true;
}

typedef struct {
   Atom selection;
   long mask;
} SelectionProcData;

#define SELECTION_NOTIFY_MASK 1
#define PROPERTY_NOTIFY_MASK  2

static int
selection_filter( Display * disp, XEvent * ev, SelectionProcData * data)
{
   switch ( ev-> type) {
   case PropertyNotify:
      return (data-> mask & PROPERTY_NOTIFY_MASK) && (data-> selection == ev-> xproperty. atom);
   case SelectionRequest:
   case SelectionClear:
   case MappingNotify:
      return true;
   case SelectionNotify:
      return (data-> mask & SELECTION_NOTIFY_MASK) && (data-> selection == ev-> xselection. selection);
   case ClientMessage:
      if ( ev-> xclient. window == WIN ||
           ev-> xclient. window == guts. root ||
           ev-> xclient. window == None) return true;
      if ( hash_fetch( guts.windows, (void*)&ev-> xclient. window,
           sizeof(ev-> xclient. window))) return false;
      return true;
   }
   return false;
}

#define CFDATA_NONE            0
#define CFDATA_NOT_ACQUIRED  (-1)
#define CFDATA_ERROR         (-2)

#define RPS_OK       0
#define RPS_PARTIAL  1
#define RPS_NODATA   2
#define RPS_ERROR    3

static int
read_property( Atom property, Atom * type, int * format,
               unsigned long * size, unsigned char ** data)
{
   int ret = ( *size > 0) ? RPS_PARTIAL : RPS_ERROR;
   unsigned char * prop, *a1;
   unsigned long n, left, offs = 0, new_size, big_offs = *size;

   XCHECKPOINT;
   Cdebug("clipboard: read_property: %s\n", XGetAtomName(DISP, property));
   while ( 1) {
      if ( XGetWindowProperty( DISP, WIN, property,
          offs, guts. limits. request_length - 4, false,
          AnyPropertyType,
          type, format, &n, &left, &prop) != Success) {
         XDeleteProperty( DISP, WIN, property);
	 Cdebug("clipboard:fail\n");
         return ret;
      }
      XCHECKPOINT;
      Cdebug("clipboard: type=0x%x(%s) fmt=%d n=%d left=%d\n",
	     *type, XGetAtomName(DISP,*type), *format, n, left);

      if ( *format == 32) *format = CF_32;

      if ( *type == 0 ) return RPS_NODATA;

      new_size = n * *format / 8;

      if ( new_size > 0) {
         if ( !( a1 = realloc( *data, big_offs + offs * 4 + new_size))) {
            warn("Not enough memory: %ld bytes\n", offs * 4 + new_size);
            XDeleteProperty( DISP, WIN, property);
            XFree( prop);
            return ret;
         }
         *data = a1;
         memcpy( *data + big_offs + offs * 4, prop, new_size);
         *size = big_offs + (offs * 4) + new_size;
         if ( *size > INT_MAX) *size = INT_MAX;
         offs += new_size / 4;
         ret = RPS_PARTIAL;
      }
      XFree( prop);
      if ( left <= 0 || *size == INT_MAX || n * *format == 0) break;
   }

   XDeleteProperty( DISP, WIN, property);
   XCHECKPOINT;

   return RPS_OK;
}

static Bool
query_datum( Handle self, Handle id, Atom query_target, Atom query_type)
{
   DEFCC;
   XEvent ev;
   Atom type;
   int format, rps;
   SelectionProcData spd;
   unsigned long size = 0, incr = 0, old_size, delay;
   unsigned char * data;
   struct timeval start_time, timeout;

   /* init */
   if ( query_target == None) return false;
   data = malloc(0);
   XX-> external[id]. size = CFDATA_ERROR;
   gettimeofday( &start_time, nil);
   XCHECKPOINT;
   Cdebug("clipboard:convert %s from %08x\n", XGetAtomName( DISP, query_target), WIN);
   XDeleteProperty( DISP, WIN, XX-> selection);
   XConvertSelection( DISP, XX-> selection, query_target, XX-> selection, WIN, guts. last_time);
   XFlush( DISP);
   XCHECKPOINT;

   /* wait for SelectionNotify */
   spd. selection = XX-> selection;
   spd. mask = SELECTION_NOTIFY_MASK;
   while ( 1) {
      XIfEvent( DISP, &ev, (XIfEventProcType)selection_filter, (char*)&spd);
      if ( ev. type != SelectionNotify) {
         prima_handle_event( &ev, nil);
         continue;
      }
      if ( ev. xselection. property == None) goto FAIL;
      Cdebug("clipboard:read SelectionNotify  %s %s\n",
             XGetAtomName(DISP, ev. xselection. property),
             XGetAtomName(DISP, ev. xselection. target));
      gettimeofday( &timeout, nil);
      delay = 2 * (( timeout. tv_sec - start_time. tv_sec) * 1000 +
                   ( timeout. tv_usec - start_time. tv_usec) / 1000) + guts. clipboard_event_timeout;
      start_time = timeout;
      if ( read_property( ev. xselection. property, &type, &format, &size, &data) > RPS_PARTIAL)
         goto FAIL;
      XFlush( DISP);
      break;
   }
   XCHECKPOINT;

   if ( type != XA_INCR) { /* ordinary, single-property selection */
      if ( format != CF_FORMAT(id) || type != query_type) {
	 if ( format != CF_FORMAT(id))
	    Cdebug("clipboard: id=%d: formats mismatch: got %d, want %d\n", id, format, CF_FORMAT(id));
	 if ( type != query_type)
	    Cdebug("clipboard: id=%d: types mismatch: got %s, want %s\n", id,
		   XGetAtomName(DISP,type), XGetAtomName(DISP,query_type));
	 return false;
      }
      XX-> external[id]. size = size;
      XX-> external[id]. data = data;
      XX-> external[id]. name = query_target;
      return true;
   }

   /* setup INCR */
   if ( format != CF_32 || size < 4) goto FAIL;
   incr = (unsigned long) *(( Atom*) data);
   if ( incr == 0) goto FAIL;
   size = 0;
   spd. mask = PROPERTY_NOTIFY_MASK;

   while ( 1) {
      /* wait for PropertyNotify */
      while ( XCheckIfEvent( DISP, &ev, (XIfEventProcType)selection_filter, (char*)&spd) == False) {
         gettimeofday( &timeout, nil);
         if ((( timeout. tv_sec - start_time. tv_sec) * 1000 +
              ( timeout. tv_usec - start_time. tv_usec) / 1000) > delay)
              goto END_LOOP;
      }
      if ( ev. type != PropertyNotify) {
         prima_handle_event( &ev, nil);
         continue;
      }
      if ( ev. xproperty. state != PropertyNewValue) continue;
      start_time = timeout;
      old_size = size;

      rps = read_property( ev. xproperty. atom, &type, &format, &size, &data);
      XFlush( DISP);
      if ( rps == RPS_NODATA) continue;
      if ( rps == RPS_ERROR) goto FAIL;
      if ( format != CF_FORMAT(id) || type != CF_TYPE(id)) return false;
      if ( size > incr ||                       /* read all in INCR */
           rps == RPS_PARTIAL ||                /* failed somewhere */
           ( size == incr && old_size == size)  /* wait for empty PropertyNotify otherwise */
           ) break;
   }
END_LOOP:
   XCHECKPOINT;

   XX-> external[id]. size   = size;
   XX-> external[id]. data   = data;
   XX-> external[id]. name   = query_target;
   return true;

FAIL:
   XCHECKPOINT;
   free( data);
   return false;
}

static Bool
query_data( Handle self, Handle id)
{
   Atom name, type;
   int index = 0;
   while (( name = get_typename( id, index++, &type)) != None) {
      if ( query_datum( self, id, name, type)) return true;
   }
   return false;
}

static Atom
find_atoms( Atom * data, int length, int id)
{
   int i, index = 0;
   Atom name;

   while (( name = get_typename( id, index++, nil)) != None) {
      for ( i = 0; i < length / sizeof(Atom); i++) {
         if ( data[i] == name)
            return name;
      }
   }
   return None;
}

Bool
apc_clipboard_has_format( Handle self, Handle id)
{
   DEFCC;
   if ( id < 0 || id >= guts. clipboard_formats_count) return false;

   if ( XX-> inside_event) {
      return XX-> internal[id]. size > 0 || XX-> external[id]. size > 0;
   } else {
      if ( XX-> internal[id]. size > 0) return true;

      if ( XX-> external[cfTargets]. size == 0) {
         /* read TARGETS, which as array of ATOMs */
         query_data( self, cfTargets);

         if ( XX-> external[cfTargets].size > 0) {
            int i, size = XX-> external[cfTargets].size;
            Atom * data = ( Atom*)(XX-> external[cfTargets]. data);
            Atom ret;

            Cdebug("clipboard targets:");
            for ( i = 0; i < size/4; i++)
               Cdebug("%s\n", XGetAtomName( DISP, data[i]));

            /* find our index for TARGETS[i], assign CFDATA_NOT_ACQUIRED to it */
            for ( i = 0; i < guts. clipboard_formats_count; i++) {
               if ( i == cfTargets) continue;
               ret = find_atoms( data, size, i);
               if ( ret != None && (
                      XX-> external[i]. size == 0 ||
                      XX-> external[i]. size == CFDATA_ERROR
                    )
                  ) {
                   XX-> external[i]. size = CFDATA_NOT_ACQUIRED;
                   XX-> external[i]. name = ret;
                }
            }

            if ( XX-> external[id]. size == 0 ||
                 XX-> external[id]. size == CFDATA_ERROR)
               return false;
         }
      }

      if ( XX-> external[id]. size > 0 ||
           XX-> external[id]. size == CFDATA_NOT_ACQUIRED)
         return true;

      if ( XX-> external[id]. size == CFDATA_ERROR)
         return false;

      /* selection owner does not support TARGETS, so peek */
      if ( XX-> external[cfTargets]. size == 0 && XX-> internal[id]. size == 0)
         return query_data( self, id);
   }
   return false;
}

Bool
apc_clipboard_get_data( Handle self, Handle id, PClipboardDataRec c)
{
   DEFCC;
   STRLEN size;
   unsigned char * data;
   Atom name;

   if ( id < 0 || id >= guts. clipboard_formats_count) return false;

   if ( !XX-> inside_event) {
      if ( XX-> internal[id]. size == 0) {
         if ( XX-> external[id]. size == CFDATA_NOT_ACQUIRED) {
            if ( !query_data( self, id)) return false;
         }
         if ( XX-> external[id]. size == CFDATA_ERROR) return false;
      }
   }
   if ( XX-> internal[id]. size == CFDATA_ERROR) return false;

   if ( XX-> internal[id]. size > 0) {
      size = XX-> internal[id]. size;
      data = XX-> internal[id]. data;
      name = XX-> internal[id]. name;
   } else {
      size = XX-> external[id]. size;
      data = XX-> external[id]. data;
      name = XX-> external[id]. name;
   }
   if ( size == 0 || data == nil) return false;

   switch ( id) {
   case cfBitmap: {
      Handle img = c-> image;
      XWindow foo;
      Pixmap px = *(( Pixmap*)( data));
      unsigned int dummy, x, y, d;
      int bar;

      if ( !XGetGeometry( DISP, px, &foo, &bar, &bar, &x, &y, &dummy, &d))
         return false;
      CImage( img)-> create_empty( img, x, y, ( d == 1) ? imBW : guts. qdepth);
      if ( !prima_std_query_image( img, px)) return false;
      break;}
   case cfText:
   case cfUTF8: {
      void * ret = malloc( size);
      if ( !ret) {
         warn("Not enough memory: %d bytes\n", (int)size);
         return false;
      }
      memcpy( ret, data, size);
      c-> data   = ret;
      c-> length = size;
      break;}
   default: {
      void * ret = malloc( size);
      if ( !ret) {
         warn("Not enough memory: %d bytes\n", (int)size);
         return false;
      }
      memcpy( ret, data, size);
      c-> data = ( Byte * ) ret;
      c-> length = size;
      break;}
   }
   return true;
}

Bool
apc_clipboard_set_data( Handle self, Handle id, PClipboardDataRec c)
{
   DEFCC;
   if ( id < 0 || id >= guts. clipboard_formats_count) return false;

   if ( id >= cfTargets && id < cfCOUNT ) return false;
   detach_xfers( XX, id, true);
   clipboard_kill_item( XX-> internal, id);

   switch ( id) {
   case cfBitmap: {
      Pixmap px = prima_std_pixmap( c-> image, CACHE_LOW_RES);
      if ( px) {
         if ( !( XX-> internal[cfBitmap]. data = malloc( sizeof( px)))) {
            XFreePixmap( DISP, px);
            return false;
         }
         XX-> internal[cfBitmap]. size = sizeof(px);
         memcpy( XX-> internal[cfBitmap]. data, &px, sizeof(px));
      } else
         return false;
      break;}
   default:
      if ( !( XX-> internal[id]. data = malloc( c-> length)))
         return false;
      XX-> internal[id]. size = c-> length;
      memcpy( XX-> internal[id]. data, c-> data, c-> length);
      break;
   }
   XX-> need_write = true;
   return true;
}

static Bool
expand_clipboards( Handle self, int keyLen, void * key, void * dummy)
{
   DEFCC;
   PClipboardDataItem f;

   if ( !( f = realloc( XX-> internal,
      sizeof( ClipboardDataItem) * guts. clipboard_formats_count))) {
      guts. clipboard_formats_count--;
      return true;
   }
   f[ guts. clipboard_formats_count-1].size = 0;
   f[ guts. clipboard_formats_count-1].data = nil;
   f[ guts. clipboard_formats_count-1].name = CF_NAME(guts. clipboard_formats_count-1);
   XX-> internal = f;
   if ( !( f = realloc( XX-> external,
      sizeof( ClipboardDataItem) * guts. clipboard_formats_count))) {
      guts. clipboard_formats_count--;
      return true;
   }
   f[ guts. clipboard_formats_count-1].size = 0;
   f[ guts. clipboard_formats_count-1].data = nil;
   f[ guts. clipboard_formats_count-1].name = CF_NAME(guts. clipboard_formats_count-1);
   XX-> external = f;
   return false;
}

Handle
apc_clipboard_register_format( Handle self, const char* format)
{
   int i;
   Atom x = XInternAtom( DISP, format, false);
   Atom *f;

   for ( i = 0; i < guts. clipboard_formats_count; i++) {
      if ( x == CF_NAME(i))
         return i;
   }

   if ( !( f = realloc( guts. clipboard_formats,
      sizeof( Atom) * 3 * ( guts. clipboard_formats_count + 1))))
      return false;

   guts. clipboard_formats = f;
   CF_ASSIGN( guts. clipboard_formats_count, x, x, 8);
   guts. clipboard_formats_count++;

   if ( hash_first_that( guts. clipboards, (void*)expand_clipboards, nil, nil, nil))
      return -1;

   return guts. clipboard_formats_count - 1;
}

Bool
apc_clipboard_deregister_format( Handle self, Handle id)
{
   return true;
}

ApiHandle
apc_clipboard_get_handle( Handle self)
{
  return C(self)-> selection;
}

static Bool
delete_xfers( Handle self, int keyLen, void * key, XWindow * window)
{
   DEFCC;
   if ( XX-> xfers) {
      int i;
      for ( i = 0; i < XX-> xfers-> count; i++)
         delete_xfer( XX, ( ClipboardXfer*) XX-> xfers-> items[i]);
   }
   hash_delete( guts. clipboard_xfers, window, sizeof( XWindow), false);
   return false;
}

void
prima_handle_selection_event( XEvent *ev, XWindow win, Handle self)
{
   XCHECKPOINT;
   switch ( ev-> type) {
   case SelectionRequest: {
      XEvent xe;
      int i, id = -1;
      Atom prop   = ev-> xselectionrequest. property,
           target = ev-> xselectionrequest. target;
      self = ( Handle) hash_fetch( guts. clipboards, &ev-> xselectionrequest. selection, sizeof( Atom));

      guts. last_time = ev-> xselectionrequest. time;
      xe. type      = SelectionNotify;
      xe. xselection. send_event = true;
      xe. xselection. serial    = ev-> xselectionrequest. serial;
      xe. xselection. display   = ev-> xselectionrequest. display;
      xe. xselection. requestor = ev-> xselectionrequest. requestor;
      xe. xselection. selection = ev-> xselectionrequest. selection;
      xe. xselection. target    = target;
      xe. xselection. property  = None;
      xe. xselection. time      = ev-> xselectionrequest. time;

      Cdebug("from %08x %s at %s\n", ev-> xselectionrequest. requestor,
             XGetAtomName( DISP, ev-> xselectionrequest. target),
             XGetAtomName( DISP, ev-> xselectionrequest. property)
             );

      if ( self) {
         PClipboardSysData CC = C(self);
         Bool event = CC-> inside_event;
         int format, utf8_mime = 0;

         for ( i = 0; i < guts. clipboard_formats_count; i++) {
            if ( xe. xselection. target == CC-> internal[i]. name) {
               id = i;
               break;
            } else if ( i == cfUTF8 && xe. xselection. target == UTF8_MIME) {
               id = i;
               utf8_mime = 1;
               break;
            }
         }
         if ( id < 0) goto SEND_EMPTY;
         for ( i = 0; i < guts. clipboard_formats_count; i++)
            clipboard_kill_item( CC-> external, i);

         CC-> target = xe. xselection. target;
         CC-> need_write = false;

         CC-> inside_event = true;
         /* XXX cmSelection */
         CC-> inside_event = event;

         format = CF_FORMAT(id);
         target = CF_TYPE( id);
         if ( utf8_mime) target = UTF8_MIME;

         if ( id == cfTargets) {
            int count = 0, have_utf8 = 0;
            Atom * ci;
            for ( i = 0; i < guts. clipboard_formats_count; i++) {
               if ( i != cfTargets && CC-> internal[i]. size > 0) {
                  count++;
		  if ( i == cfUTF8) {
		     count++;
		     have_utf8 = 1;
		  }
	       }
	    }
            detach_xfers( CC, cfTargets, true);
            clipboard_kill_item( CC-> internal, cfTargets);
            if (( CC-> internal[cfTargets]. data = malloc( count * sizeof( Atom)))) {
               CC-> internal[cfTargets]. size = count * sizeof( Atom);
               ci = (Atom*)CC-> internal[cfTargets]. data;
               for ( i = 0; i < guts. clipboard_formats_count; i++)
                  if ( i != cfTargets && CC-> internal[i]. size > 0)
                     *(ci++) = CF_NAME(i);
               if ( have_utf8)
		  *(ci++) = UTF8_MIME;
            }
         }

         if ( CC-> internal[id]. size > 0) {
            Atom incr;
            int mode = PropModeReplace;
            unsigned char * data = CC-> internal[id]. data;
            unsigned long size = CC-> internal[id]. size * 8 / format;
            if ( CC-> internal[id]. size > guts. limits. request_length - 4) {
               int ok = 0;
               int reqlen = guts. limits. request_length - 4;
               /* INCR */
               if ( !guts. clipboard_xfers)
                  guts. clipboard_xfers = hash_create();
               if ( !CC-> xfers)
                  CC-> xfers = plist_create( 1, 1);
               if ( CC-> xfers && guts. clipboard_xfers) {
                  ClipboardXfer * x = malloc( sizeof( ClipboardXfer));
                  if ( x) {
                     IV refcnt;
                     ClipboardXferKey key;

                     bzero( x, sizeof( ClipboardXfer));
                     list_add( CC-> xfers, ( Handle) x);
                     x-> size = CC-> internal[id]. size;
                     x-> data = CC-> internal[id]. data;
                     x-> blocks = ( x-> size / reqlen ) + ( x-> size % reqlen) ? 1 : 0;
                     x-> requestor = xe. xselection. requestor;
                     x-> property  = prop;
                     x-> target    = xe. xselection. target;
                     x-> self      = self;
                     x-> format    = format;
                     x-> id        = id;
                     gettimeofday( &x-> time, nil);

                     CLIPBOARD_XFER_KEY( key, x-> requestor, x-> property);
                     hash_store( guts. clipboard_xfers, key, sizeof(key), (void*) x);
                     refcnt = PTR2IV( hash_fetch( guts. clipboard_xfers, &x-> requestor, sizeof( XWindow)));
                     if ( refcnt++ == 0)
                        XSelectInput( DISP, x-> requestor, PropertyChangeMask|StructureNotifyMask);
                     hash_store( guts. clipboard_xfers, &x-> requestor, sizeof(XWindow), INT2PTR( void*, refcnt));

                     format = CF_32;
                     size = 1;
                     incr = ( Atom) CC-> internal[id]. size;
                     data = ( unsigned char*) &incr;
                     ok = 1;
                     target = XA_INCR;
                     Cdebug("clpboard: init INCR for %08x %d\n", x-> requestor, x-> property);
                  }
               }
               if ( !ok) size = reqlen;
            }

            if ( format == CF_32) format = 32;
            XChangeProperty(
               xe. xselection. display,
               xe. xselection. requestor,
               prop, target, format, mode, data, size);
            Cdebug("clipboard: store prop %s\n", XGetAtomName( DISP, prop));
            xe. xselection. property = prop;
         }

         /* content of PIXMAP or BITMAP is seemingly gets invalidated
            after the selection transfer, unlike the string data format */
         if ( id == cfBitmap) {
            bzero( CC-> internal[id].data, CC-> internal[id].size);
            bzero( CC-> external[id].data, CC-> external[id].size);
            clipboard_kill_item( CC-> internal, id);
            clipboard_kill_item( CC-> external, id);
         }
      }
SEND_EMPTY:
      XSendEvent( xe.xselection.display, xe.xselection.requestor, false, 0, &xe);
      XFlush( DISP);
      Cdebug("clipboard:id %d, SelectionNotify to %08x , %s %s\n", id, xe.xselection.requestor,
         XGetAtomName( DISP, xe. xselection. property),
         XGetAtomName( DISP, xe. xselection. target));
   } break;
   case SelectionClear:
      guts. last_time = ev-> xselectionclear. time;
      if ( XGetSelectionOwner( DISP, ev-> xselectionclear. selection) != WIN) {
         Handle c = ( Handle) hash_fetch( guts. clipboards,
                                          &ev-> xselectionclear. selection, sizeof( Atom));
         guts. last_time = ev-> xselectionclear. time;
         if (c) {
            int i;
            C(c)-> selection_owner = nilHandle;
            for ( i = 0; i < guts. clipboard_formats_count; i++) {
               detach_xfers( C(c), i, true);
               clipboard_kill_item( C(c)-> external, i);
               clipboard_kill_item( C(c)-> internal, i);
            }
         }
      }
      break;
   case PropertyNotify:
      if ( ev-> xproperty. state == PropertyDelete) {
         unsigned long offs, size, reqlen = guts. limits. request_length - 4, format;
         ClipboardXfer * x = ( ClipboardXfer *) self;
         PClipboardSysData CC = C(x-> self);
         offs = x-> offset * reqlen;
         if ( offs >= x-> size) { /* clear termination */
            size = 0;
            offs = 0;
         } else {
            size = x-> size - offs;
            if ( size > reqlen) size = reqlen;
         }
         Cdebug("clipboard: put %d %d in %08x %d\n", x-> offset, size, x-> requestor, x-> property);
         if ( x-> format > 8)  size /= 2;
         if ( x-> format > 16) size /= 2;
	 format = ( x-> format == CF_32) ? 32 : x-> format;
         XChangeProperty( DISP, x-> requestor, x-> property, x-> target,
            format, PropModeReplace,
            x-> data + offs, size);
         XFlush( DISP);
         x-> offset++;
         if ( size == 0) delete_xfer( CC, x);
      }
      break;
   case DestroyNotify:
      Cdebug("clipboard: destroy xfers at %08x\n", ev-> xdestroywindow. window);
      hash_first_that( guts. clipboards, (void*)delete_xfers, (void*) &ev-> xdestroywindow. window, nil, nil);
      XFlush( DISP);
      break;
   }
   XCHECKPOINT;
}


package scaleio

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"k8s.io/klog/v2"
	"k8s.io/mount-utils"
	utilstrings "k8s.io/utils/strings"

	api "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	meta "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/uuid"
	volumehelpers "k8s.io/cloud-provider/volume/helpers"
	"k8s.io/kubernetes/pkg/volume"
	"k8s.io/kubernetes/pkg/volume/util"
)

type sioVolume struct {
	sioMgr          *sioMgr
	plugin          *sioPlugin
	pod             *api.Pod
	podUID          types.UID
	spec            *volume.Spec
	secretName      string
	secretNamespace string
	volSpecName     string
	volName         string
	readOnly        bool
	fsType          string
	options         volume.VolumeOptions
	configData      map[string]string

	volume.MetricsNil
}

const (
	minimumVolumeSizeGiB = 8
)

// *******************
// volume.Volume Impl
var _ volume.Volume = &sioVolume{}

// GetPath returns the path where the volume will be mounted.
func (v *sioVolume) GetPath() string {
	return v.plugin.host.GetPodVolumeDir(
		v.podUID,
		utilstrings.EscapeQualifiedName(sioPluginName),
		v.volSpecName)
}

// *************
// Mounter Impl
// *************
var _ volume.Mounter = &sioVolume{}

// CanMount checks to verify that the volume can be mounted prior to Setup.
// A nil error indicates that the volume is ready for mounitnig.
func (v *sioVolume) CanMount() error {
	return nil
}

func (v *sioVolume) SetUp(mounterArgs volume.MounterArgs) error {
	return v.SetUpAt(v.GetPath(), mounterArgs)
}

// SetUp bind mounts the disk global mount to the volume path.
func (v *sioVolume) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
	v.plugin.volumeMtx.LockKey(v.volSpecName)
	defer v.plugin.volumeMtx.UnlockKey(v.volSpecName)

	klog.V(4).Info(log("setting up volume for PV.spec %s", v.volSpecName))
	if err := v.setSioMgr(); err != nil {
		klog.Error(log("setup failed to create scalio manager: %v", err))
		return err
	}

	mounter := v.plugin.host.GetMounter(v.plugin.GetPluginName())
	notDevMnt, err := mounter.IsLikelyNotMountPoint(dir)
	if err != nil && !os.IsNotExist(err) {
		klog.Error(log("IsLikelyNotMountPoint test failed for dir %v", dir))
		return err
	}
	if !notDevMnt {
		klog.V(4).Info(log("skipping setup, dir %s already a mount point", v.volName))
		return nil
	}

	// should multiple-mapping be enabled
	enableMultiMaps := false
	isROM := false
	if v.spec.PersistentVolume != nil {
		ams := v.spec.PersistentVolume.Spec.AccessModes
		for _, am := range ams {
			if am == api.ReadOnlyMany {
				enableMultiMaps = true
				isROM = true
			}
		}
	}
	klog.V(4).Info(log("multiple mapping enabled = %v", enableMultiMaps))

	volName := v.volName
	devicePath, err := v.sioMgr.AttachVolume(volName, enableMultiMaps)
	if err != nil {
		klog.Error(log("setup of volume %v:  %v", v.volSpecName, err))
		return err
	}
	options := []string{}
	switch {
	default:
		options = append(options, "rw")
	case isROM && !v.readOnly:
		options = append(options, "rw")
	case isROM:
		options = append(options, "ro")
	case v.readOnly:
		options = append(options, "ro")
	}

	klog.V(4).Info(log("mounting device  %s -> %s", devicePath, dir))
	if err := os.MkdirAll(dir, 0750); err != nil {
		klog.Error(log("failed to create dir %#v:  %v", dir, err))
		return err
	}
	klog.V(4).Info(log("setup created mount point directory %s", dir))

	diskMounter := util.NewSafeFormatAndMountFromHost(v.plugin.GetPluginName(), v.plugin.host)
	err = diskMounter.FormatAndMount(devicePath, dir, v.fsType, options)

	if err != nil {
		klog.Error(log("mount operation failed during setup: %v", err))
		if err := os.Remove(dir); err != nil && !os.IsNotExist(err) {
			klog.Error(log("failed to remove dir %s during a failed mount at setup: %v", dir, err))
			return err
		}
		return err
	}

	if !v.readOnly && mounterArgs.FsGroup != nil {
		klog.V(4).Info(log("applying  value FSGroup ownership"))
		volume.SetVolumeOwnership(v, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(v.plugin.GetPluginName()))
	}

	klog.V(4).Info(log("successfully setup PV %s: volume %s mapped as %s mounted at %s", v.volSpecName, v.volName, devicePath, dir))
	return nil
}

func (v *sioVolume) GetAttributes() volume.Attributes {
	return volume.Attributes{
		ReadOnly:        v.readOnly,
		Managed:         !v.readOnly,
		SupportsSELinux: true,
	}
}

// **********************
// volume.Unmounter Impl
// *********************
var _ volume.Unmounter = &sioVolume{}

// TearDownAt unmounts the bind mount
func (v *sioVolume) TearDown() error {
	return v.TearDownAt(v.GetPath())
}

// TearDown unmounts  and remove the volume
func (v *sioVolume) TearDownAt(dir string) error {
	v.plugin.volumeMtx.LockKey(v.volSpecName)
	defer v.plugin.volumeMtx.UnlockKey(v.volSpecName)

	mounter := v.plugin.host.GetMounter(v.plugin.GetPluginName())
	dev, _, err := mount.GetDeviceNameFromMount(mounter, dir)
	if err != nil {
		klog.Errorf(log("failed to get reference count for volume: %s", dir))
		return err
	}

	klog.V(4).Info(log("attempting to unmount %s", dir))
	if err := mount.CleanupMountPoint(dir, mounter, false); err != nil {
		klog.Error(log("teardown failed while unmounting dir %s: %v ", dir, err))
		return err
	}
	klog.V(4).Info(log("dir %s unmounted successfully", dir))

	// detach/unmap
	kvh, ok := v.plugin.host.(volume.KubeletVolumeHost)
	if !ok {
		return fmt.Errorf("plugin volume host does not implement KubeletVolumeHost interface")
	}
	hu := kvh.GetHostUtil()
	deviceBusy, err := hu.DeviceOpened(dev)
	if err != nil {
		klog.Error(log("teardown unable to get status for device %s: %v", dev, err))
		return err
	}

	// Detach volume from node:
	// use "last attempt wins" strategy to detach volume from node
	// only allow volume to detach when it is not busy (not being used by other pods)
	if !deviceBusy {
		klog.V(4).Info(log("teardown is attempting to detach/unmap volume for PV %s", v.volSpecName))
		if err := v.resetSioMgr(); err != nil {
			klog.Error(log("teardown failed, unable to reset scalio mgr: %v", err))
		}
		volName := v.volName
		if err := v.sioMgr.DetachVolume(volName); err != nil {
			klog.Warning(log("warning: detaching failed for volume %s:  %v", volName, err))
			return nil
		}
		klog.V(4).Infof(log("teardown of volume %v detached successfully", volName))
	}
	return nil
}

// ********************
// volume.Deleter Impl
// ********************
var _ volume.Deleter = &sioVolume{}

func (v *sioVolume) Delete() error {
	klog.V(4).Info(log("deleting pvc %s", v.volSpecName))

	if err := v.setSioMgrFromSpec(); err != nil {
		klog.Error(log("delete failed while setting sio manager: %v", err))
		return err
	}

	err := v.sioMgr.DeleteVolume(v.volName)
	if err != nil {
		klog.Error(log("failed to delete volume %s: %v", v.volName, err))
		return err
	}

	klog.V(4).Info(log("successfully deleted PV %s with volume %s", v.volSpecName, v.volName))
	return nil
}

// ************************
// volume.Provisioner Impl
// ************************
var _ volume.Provisioner = &sioVolume{}

func (v *sioVolume) Provision(selectedNode *api.Node, allowedTopologies []api.TopologySelectorTerm) (*api.PersistentVolume, error) {
	klog.V(4).Info(log("attempting to dynamically provision pvc %v", v.options.PVC.Name))

	if !util.AccessModesContainedInAll(v.plugin.GetAccessModes(), v.options.PVC.Spec.AccessModes) {
		return nil, fmt.Errorf("invalid AccessModes %v: only AccessModes %v are supported", v.options.PVC.Spec.AccessModes, v.plugin.GetAccessModes())
	}

	if util.CheckPersistentVolumeClaimModeBlock(v.options.PVC) {
		return nil, fmt.Errorf("%s does not support block volume provisioning", v.plugin.GetPluginName())
	}

	// setup volume attrributes
	genName := v.generateName("k8svol", 11)

	capacity := v.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)]

	volSizeGiB, err := volumehelpers.RoundUpToGiB(capacity)
	if err != nil {
		return nil, err
	}

	if volSizeGiB < minimumVolumeSizeGiB {
		volSizeGiB = minimumVolumeSizeGiB
		klog.V(4).Info(log("capacity less than 8Gi found, adjusted to %dGi", volSizeGiB))

	}

	// create sio manager
	if err := v.setSioMgrFromConfig(); err != nil {
		klog.Error(log("provision failed while setting up sio mgr: %v", err))
		return nil, err
	}

	// create volume
	volName := genName
	vol, err := v.sioMgr.CreateVolume(volName, volSizeGiB)
	if err != nil {
		klog.Error(log("provision failed while creating volume: %v", err))
		return nil, err
	}

	// prepare data for pv
	v.configData[confKey.volumeName] = volName
	sslEnabled, err := strconv.ParseBool(v.configData[confKey.sslEnabled])
	if err != nil {
		klog.Warning(log("failed to parse parameter sslEnabled, setting to false"))
		sslEnabled = false
	}
	readOnly, err := strconv.ParseBool(v.configData[confKey.readOnly])
	if err != nil {
		klog.Warning(log("failed to parse parameter readOnly, setting it to false"))
		readOnly = false
	}

	// describe created pv
	pvName := genName
	pv := &api.PersistentVolume{
		ObjectMeta: meta.ObjectMeta{
			Name:      pvName,
			Namespace: v.options.PVC.Namespace,
			Labels:    map[string]string{},
			Annotations: map[string]string{
				util.VolumeDynamicallyCreatedByKey: "scaleio-dynamic-provisioner",
			},
		},
		Spec: api.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: v.options.PersistentVolumeReclaimPolicy,
			AccessModes:                   v.options.PVC.Spec.AccessModes,
			Capacity: api.ResourceList{
				api.ResourceName(api.ResourceStorage): resource.MustParse(
					fmt.Sprintf("%dGi", volSizeGiB),
				),
			},
			PersistentVolumeSource: api.PersistentVolumeSource{
				ScaleIO: &api.ScaleIOPersistentVolumeSource{
					Gateway:          v.configData[confKey.gateway],
					SSLEnabled:       sslEnabled,
					SecretRef:        &api.SecretReference{Name: v.secretName, Namespace: v.secretNamespace},
					System:           v.configData[confKey.system],
					ProtectionDomain: v.configData[confKey.protectionDomain],
					StoragePool:      v.configData[confKey.storagePool],
					StorageMode:      v.configData[confKey.storageMode],
					VolumeName:       volName,
					FSType:           v.configData[confKey.fsType],
					ReadOnly:         readOnly,
				},
			},
		},
	}
	if len(v.options.PVC.Spec.AccessModes) == 0 {
		pv.Spec.AccessModes = v.plugin.GetAccessModes()
	}

	klog.V(4).Info(log("provisioner created pv %v and volume %s successfully", pvName, vol.Name))
	return pv, nil
}

// setSioMgr creates scaleio mgr from cached config data if found
// otherwise, setups new config data and create mgr
func (v *sioVolume) setSioMgr() error {
	klog.V(4).Info(log("setting up sio mgr for spec  %s", v.volSpecName))
	podDir := v.plugin.host.GetPodPluginDir(v.podUID, sioPluginName)
	configName := filepath.Join(podDir, sioConfigFileName)
	if v.sioMgr == nil {
		configData, err := loadConfig(configName) // try to load config if exist
		if err != nil {
			if !os.IsNotExist(err) {
				klog.Error(log("failed to load config %s : %v", configName, err))
				return err
			}
			klog.V(4).Info(log("previous config file not found, creating new one"))
			// prepare config data
			configData = make(map[string]string)
			mapVolumeSpec(configData, v.spec)

			// additional config data
			configData[confKey.secretNamespace] = v.secretNamespace
			configData[confKey.secretName] = v.secretName
			configData[confKey.volSpecName] = v.volSpecName

			if err := validateConfigs(configData); err != nil {
				klog.Error(log("config setup failed: %s", err))
				return err
			}

			// persist config
			if err := saveConfig(configName, configData); err != nil {
				klog.Error(log("failed to save config data: %v", err))
				return err
			}
		}
		// merge in secret
		if err := attachSecret(v.plugin, v.secretNamespace, configData); err != nil {
			klog.Error(log("failed to load secret: %v", err))
			return err
		}

		// merge in Sdc Guid label value
		if err := attachSdcGUID(v.plugin, configData); err != nil {
			klog.Error(log("failed to retrieve sdc guid: %v", err))
			return err
		}
		mgr, err := newSioMgr(configData, v.plugin.host, v.plugin.host.GetExec(v.plugin.GetPluginName()))

		if err != nil {
			klog.Error(log("failed to reset sio manager: %v", err))
			return err
		}

		v.sioMgr = mgr
	}
	return nil
}

// resetSioMgr creates scaleio manager from existing (cached) config data
func (v *sioVolume) resetSioMgr() error {
	podDir := v.plugin.host.GetPodPluginDir(v.podUID, sioPluginName)
	configName := filepath.Join(podDir, sioConfigFileName)
	if v.sioMgr == nil {
		// load config data from disk
		configData, err := loadConfig(configName)
		if err != nil {
			klog.Error(log("failed to load config data: %v", err))
			return err
		}
		v.secretName = configData[confKey.secretName]
		v.secretNamespace = configData[confKey.secretNamespace]
		v.volName = configData[confKey.volumeName]
		v.volSpecName = configData[confKey.volSpecName]

		// attach secret
		if err := attachSecret(v.plugin, v.secretNamespace, configData); err != nil {
			klog.Error(log("failed to load secret: %v", err))
			return err
		}

		// merge in Sdc Guid label value
		if err := attachSdcGUID(v.plugin, configData); err != nil {
			klog.Error(log("failed to retrieve sdc guid: %v", err))
			return err
		}
		mgr, err := newSioMgr(configData, v.plugin.host, v.plugin.host.GetExec(v.plugin.GetPluginName()))

		if err != nil {
			klog.Error(log("failed to reset scaleio mgr: %v", err))
			return err
		}
		v.sioMgr = mgr
	}
	return nil
}

// setSioFromConfig sets up scaleio mgr from an available config data map
// designed to be called from dynamic provisioner
func (v *sioVolume) setSioMgrFromConfig() error {
	klog.V(4).Info(log("setting scaleio mgr from available config"))
	if v.sioMgr == nil {
		applyConfigDefaults(v.configData)

		v.configData[confKey.volSpecName] = v.volSpecName

		if err := validateConfigs(v.configData); err != nil {
			klog.Error(log("config data setup failed: %s", err))
			return err
		}

		// copy config and attach secret
		data := map[string]string{}
		for k, v := range v.configData {
			data[k] = v
		}

		if err := attachSecret(v.plugin, v.secretNamespace, data); err != nil {
			klog.Error(log("failed to load secret: %v", err))
			return err
		}
		mgr, err := newSioMgr(data, v.plugin.host, v.plugin.host.GetExec(v.plugin.GetPluginName()))

		if err != nil {
			klog.Error(log("failed while setting scaleio mgr from config: %v", err))
			return err
		}
		v.sioMgr = mgr
	}
	return nil
}

// setSioMgrFromSpec sets the scaleio manager from a spec object.
// The spec may be complete or incomplete depending on lifecycle phase.
func (v *sioVolume) setSioMgrFromSpec() error {
	klog.V(4).Info(log("setting sio manager from spec"))
	if v.sioMgr == nil {
		// get config data form spec volume source
		configData := map[string]string{}
		mapVolumeSpec(configData, v.spec)

		// additional config
		configData[confKey.secretNamespace] = v.secretNamespace
		configData[confKey.secretName] = v.secretName
		configData[confKey.volSpecName] = v.volSpecName

		if err := validateConfigs(configData); err != nil {
			klog.Error(log("config setup failed: %s", err))
			return err
		}

		// attach secret object to config data
		if err := attachSecret(v.plugin, v.secretNamespace, configData); err != nil {
			klog.Error(log("failed to load secret: %v", err))
			return err
		}
		mgr, err := newSioMgr(configData, v.plugin.host, v.plugin.host.GetExec(v.plugin.GetPluginName()))

		if err != nil {
			klog.Error(log("failed to reset sio manager: %v", err))
			return err
		}
		v.sioMgr = mgr
	}
	return nil
}

func (v *sioVolume) generateName(prefix string, size int) string {
	return fmt.Sprintf("%s-%s", prefix, strings.Replace(string(uuid.NewUUID()), "-", "", -1)[0:size])
}


extern "Java"
{
  namespace javax
  {
    namespace security
    {
      namespace auth
      {
        namespace login
        {
            class FailedLoginException;
        }
      }
    }
  }
}

class javax::security::auth::login::FailedLoginException : public ::javax::security::auth::login::LoginException
{

public:
  FailedLoginException();
  FailedLoginException(::java::lang::String *);
private:
  static const jlong serialVersionUID = 802556922354616286LL;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_security_auth_login_FailedLoginException__


package uk.co.real_logic.aeron.common;

import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

interface NetworkInterfaceShim
{
    Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException;
    List<InterfaceAddress> getInterfaceAddresses(NetworkInterface ifc);
    boolean isLoopback(NetworkInterface ifc) throws SocketException;

    NetworkInterfaceShim DEFAULT = new NetworkInterfaceShim()
    {
        public Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException
        {
            return NetworkInterface.getNetworkInterfaces();
        }

        public List<InterfaceAddress> getInterfaceAddresses(final NetworkInterface ifc)
        {
            return ifc.getInterfaceAddresses();
        }

        public boolean isLoopback(final NetworkInterface ifc) throws SocketException
        {
            return ifc.isLoopback();
        }
    };
}


// Copyright (c) 2013 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 "content/browser/indexed_db/leveldb/leveldb_database.h"

#include <cerrno>

#include "base/basictypes.h"
#include "base/files/file.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "content/browser/indexed_db/indexed_db_class_factory.h"
#include "content/browser/indexed_db/leveldb/leveldb_comparator.h"
#include "content/browser/indexed_db/leveldb/leveldb_iterator_impl.h"
#include "content/browser/indexed_db/leveldb/leveldb_write_batch.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/env_idb.h"
#include "third_party/leveldatabase/src/helpers/memenv/memenv.h"
#include "third_party/leveldatabase/src/include/leveldb/db.h"
#include "third_party/leveldatabase/src/include/leveldb/env.h"
#include "third_party/leveldatabase/src/include/leveldb/filter_policy.h"
#include "third_party/leveldatabase/src/include/leveldb/slice.h"

using base::StringPiece;

namespace content {

// Forcing flushes to disk at the end of a transaction guarantees that the
// data hit disk, but drastically impacts throughput when the filesystem is
// busy with background compactions. Not syncing trades off reliability for
// performance. Note that background compactions which move data from the
// log to SSTs are always done with reliable writes.
//
// Sync writes are necessary on Windows for quota calculations; POSIX
// calculates file sizes correctly even when not synced to disk.
#if defined(OS_WIN)
static const bool kSyncWrites = true;
#else
// TODO(dgrogan): Either remove the #if block or change this back to false.
// See http://crbug.com/338385.
static const bool kSyncWrites = true;
#endif

static leveldb::Slice MakeSlice(const StringPiece& s) {
  return leveldb::Slice(s.begin(), s.size());
}

static StringPiece MakeStringPiece(const leveldb::Slice& s) {
  return StringPiece(s.data(), s.size());
}

LevelDBDatabase::ComparatorAdapter::ComparatorAdapter(
    const LevelDBComparator* comparator)
    : comparator_(comparator) {}

int LevelDBDatabase::ComparatorAdapter::Compare(const leveldb::Slice& a,
                                                const leveldb::Slice& b) const {
  return comparator_->Compare(MakeStringPiece(a), MakeStringPiece(b));
}

const char* LevelDBDatabase::ComparatorAdapter::Name() const {
  return comparator_->Name();
}

// TODO(jsbell): Support the methods below in the future.
void LevelDBDatabase::ComparatorAdapter::FindShortestSeparator(
    std::string* start,
    const leveldb::Slice& limit) const {}

void LevelDBDatabase::ComparatorAdapter::FindShortSuccessor(
    std::string* key) const {}

LevelDBSnapshot::LevelDBSnapshot(LevelDBDatabase* db)
    : db_(db->db_.get()), snapshot_(db_->GetSnapshot()) {}

LevelDBSnapshot::~LevelDBSnapshot() { db_->ReleaseSnapshot(snapshot_); }

LevelDBDatabase::LevelDBDatabase() {}

LevelDBDatabase::~LevelDBDatabase() {
  // db_'s destructor uses comparator_adapter_; order of deletion is important.
  db_.reset();
  comparator_adapter_.reset();
  env_.reset();
}

static leveldb::Status OpenDB(
    leveldb::Comparator* comparator,
    leveldb::Env* env,
    const base::FilePath& path,
    leveldb::DB** db,
    scoped_ptr<const leveldb::FilterPolicy>* filter_policy) {
  filter_policy->reset(leveldb::NewBloomFilterPolicy(10));
  leveldb::Options options;
  options.comparator = comparator;
  options.create_if_missing = true;
  options.paranoid_checks = true;
  options.filter_policy = filter_policy->get();
  options.reuse_logs = true;
  options.compression = leveldb::kSnappyCompression;

  // For info about the troubles we've run into with this parameter, see:
  // https://code.google.com/p/chromium/issues/detail?id=227313#c11
  options.max_open_files = 80;
  options.env = env;

  // ChromiumEnv assumes UTF8, converts back to FilePath before using.
  leveldb::Status s = leveldb::DB::Open(options, path.AsUTF8Unsafe(), db);

  return s;
}

leveldb::Status LevelDBDatabase::Destroy(const base::FilePath& file_name) {
  leveldb::Options options;
  options.env = leveldb::IDBEnv();
  // ChromiumEnv assumes UTF8, converts back to FilePath before using.
  return leveldb::DestroyDB(file_name.AsUTF8Unsafe(), options);
}

namespace {
class LockImpl : public LevelDBLock {
 public:
  explicit LockImpl(leveldb::Env* env, leveldb::FileLock* lock)
      : env_(env), lock_(lock) {}
  ~LockImpl() override { env_->UnlockFile(lock_); }

 private:
  leveldb::Env* env_;
  leveldb::FileLock* lock_;

  DISALLOW_COPY_AND_ASSIGN(LockImpl);
};
}  // namespace

scoped_ptr<LevelDBLock> LevelDBDatabase::LockForTesting(
    const base::FilePath& file_name) {
  leveldb::Env* env = leveldb::IDBEnv();
  base::FilePath lock_path = file_name.AppendASCII("LOCK");
  leveldb::FileLock* lock = NULL;
  leveldb::Status status = env->LockFile(lock_path.AsUTF8Unsafe(), &lock);
  if (!status.ok())
    return scoped_ptr<LevelDBLock>();
  DCHECK(lock);
  return scoped_ptr<LevelDBLock>(new LockImpl(env, lock));
}

static int CheckFreeSpace(const char* const type,
                          const base::FilePath& file_name) {
  std::string name =
      std::string("WebCore.IndexedDB.LevelDB.Open") + type + "FreeDiskSpace";
  int64 free_disk_space_in_k_bytes =
      base::SysInfo::AmountOfFreeDiskSpace(file_name) / 1024;
  if (free_disk_space_in_k_bytes < 0) {
    base::Histogram::FactoryGet(
        "WebCore.IndexedDB.LevelDB.FreeDiskSpaceFailure",
        1,
        2 /*boundary*/,
        2 /*boundary*/ + 1,
        base::HistogramBase::kUmaTargetedHistogramFlag)->Add(1 /*sample*/);
    return -1;
  }
  int clamped_disk_space_k_bytes = free_disk_space_in_k_bytes > INT_MAX
                                       ? INT_MAX
                                       : free_disk_space_in_k_bytes;
  const uint64 histogram_max = static_cast<uint64>(1e9);
  static_assert(histogram_max <= INT_MAX, "histogram_max too big");
  base::Histogram::FactoryGet(name,
                              1,
                              histogram_max,
                              11 /*buckets*/,
                              base::HistogramBase::kUmaTargetedHistogramFlag)
      ->Add(clamped_disk_space_k_bytes);
  return clamped_disk_space_k_bytes;
}

static void ParseAndHistogramIOErrorDetails(const std::string& histogram_name,
                                            const leveldb::Status& s) {
  leveldb_env::MethodID method;
  base::File::Error error = base::File::FILE_OK;
  leveldb_env::ErrorParsingResult result =
      leveldb_env::ParseMethodAndError(s, &method, &error);
  if (result == leveldb_env::NONE)
    return;
  std::string method_histogram_name(histogram_name);
  method_histogram_name.append(".EnvMethod");
  base::LinearHistogram::FactoryGet(
      method_histogram_name,
      1,
      leveldb_env::kNumEntries,
      leveldb_env::kNumEntries + 1,
      base::HistogramBase::kUmaTargetedHistogramFlag)->Add(method);

  std::string error_histogram_name(histogram_name);

  if (result == leveldb_env::METHOD_AND_PFE) {
    DCHECK_LT(error, 0);
    error_histogram_name.append(std::string(".PFE.") +
                                leveldb_env::MethodIDToString(method));
    base::LinearHistogram::FactoryGet(
        error_histogram_name,
        1,
        -base::File::FILE_ERROR_MAX,
        -base::File::FILE_ERROR_MAX + 1,
        base::HistogramBase::kUmaTargetedHistogramFlag)->Add(-error);
  }
}

static void ParseAndHistogramCorruptionDetails(
    const std::string& histogram_name,
    const leveldb::Status& status) {
  int error = leveldb_env::GetCorruptionCode(status);
  DCHECK_GE(error, 0);
  std::string corruption_histogram_name(histogram_name);
  corruption_histogram_name.append(".Corruption");
  const int kNumPatterns = leveldb_env::GetNumCorruptionCodes();
  base::LinearHistogram::FactoryGet(
      corruption_histogram_name,
      1,
      kNumPatterns,
      kNumPatterns + 1,
      base::HistogramBase::kUmaTargetedHistogramFlag)->Add(error);
}

static void HistogramLevelDBError(const std::string& histogram_name,
                                  const leveldb::Status& s) {
  if (s.ok()) {
    NOTREACHED();
    return;
  }
  enum {
    LEVEL_DB_NOT_FOUND,
    LEVEL_DB_CORRUPTION,
    LEVEL_DB_IO_ERROR,
    LEVEL_DB_OTHER,
    LEVEL_DB_MAX_ERROR
  };
  int leveldb_error = LEVEL_DB_OTHER;
  if (s.IsNotFound())
    leveldb_error = LEVEL_DB_NOT_FOUND;
  else if (s.IsCorruption())
    leveldb_error = LEVEL_DB_CORRUPTION;
  else if (s.IsIOError())
    leveldb_error = LEVEL_DB_IO_ERROR;
  base::Histogram::FactoryGet(histogram_name,
                              1,
                              LEVEL_DB_MAX_ERROR,
                              LEVEL_DB_MAX_ERROR + 1,
                              base::HistogramBase::kUmaTargetedHistogramFlag)
      ->Add(leveldb_error);
  if (s.IsIOError())
    ParseAndHistogramIOErrorDetails(histogram_name, s);
  else
    ParseAndHistogramCorruptionDetails(histogram_name, s);
}

leveldb::Status LevelDBDatabase::Open(const base::FilePath& file_name,
                                      const LevelDBComparator* comparator,
                                      scoped_ptr<LevelDBDatabase>* result,
                                      bool* is_disk_full) {
  base::TimeTicks begin_time = base::TimeTicks::Now();

  scoped_ptr<ComparatorAdapter> comparator_adapter(
      new ComparatorAdapter(comparator));

  leveldb::DB* db;
  scoped_ptr<const leveldb::FilterPolicy> filter_policy;
  const leveldb::Status s = OpenDB(comparator_adapter.get(),
                                   leveldb::IDBEnv(),
                                   file_name,
                                   &db,
                                   &filter_policy);

  if (!s.ok()) {
    HistogramLevelDBError("WebCore.IndexedDB.LevelDBOpenErrors", s);
    int free_space_k_bytes = CheckFreeSpace("Failure", file_name);
    // Disks with <100k of free space almost never succeed in opening a
    // leveldb database.
    if (is_disk_full)
      *is_disk_full = free_space_k_bytes >= 0 && free_space_k_bytes < 100;

    LOG(ERROR) << "Failed to open LevelDB database from "
               << file_name.AsUTF8Unsafe() << "," << s.ToString();
    return s;
  }

  UMA_HISTOGRAM_MEDIUM_TIMES("WebCore.IndexedDB.LevelDB.OpenTime",
                             base::TimeTicks::Now() - begin_time);

  CheckFreeSpace("Success", file_name);

  (*result).reset(new LevelDBDatabase);
  (*result)->db_ = make_scoped_ptr(db);
  (*result)->comparator_adapter_ = comparator_adapter.Pass();
  (*result)->comparator_ = comparator;
  (*result)->filter_policy_ = filter_policy.Pass();

  return s;
}

scoped_ptr<LevelDBDatabase> LevelDBDatabase::OpenInMemory(
    const LevelDBComparator* comparator) {
  scoped_ptr<ComparatorAdapter> comparator_adapter(
      new ComparatorAdapter(comparator));
  scoped_ptr<leveldb::Env> in_memory_env(leveldb::NewMemEnv(leveldb::IDBEnv()));

  leveldb::DB* db;
  scoped_ptr<const leveldb::FilterPolicy> filter_policy;
  const leveldb::Status s = OpenDB(comparator_adapter.get(),
                                   in_memory_env.get(),
                                   base::FilePath(),
                                   &db,
                                   &filter_policy);

  if (!s.ok()) {
    LOG(ERROR) << "Failed to open in-memory LevelDB database: " << s.ToString();
    return scoped_ptr<LevelDBDatabase>();
  }

  scoped_ptr<LevelDBDatabase> result(new LevelDBDatabase);
  result->env_ = in_memory_env.Pass();
  result->db_ = make_scoped_ptr(db);
  result->comparator_adapter_ = comparator_adapter.Pass();
  result->comparator_ = comparator;
  result->filter_policy_ = filter_policy.Pass();

  return result.Pass();
}

leveldb::Status LevelDBDatabase::Put(const StringPiece& key,
                                     std::string* value) {
  base::TimeTicks begin_time = base::TimeTicks::Now();

  leveldb::WriteOptions write_options;
  write_options.sync = kSyncWrites;

  const leveldb::Status s =
      db_->Put(write_options, MakeSlice(key), MakeSlice(*value));
  if (!s.ok())
    LOG(ERROR) << "LevelDB put failed: " << s.ToString();
  else
    UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.PutTime",
                        base::TimeTicks::Now() - begin_time);
  return s;
}

leveldb::Status LevelDBDatabase::Remove(const StringPiece& key) {
  leveldb::WriteOptions write_options;
  write_options.sync = kSyncWrites;

  const leveldb::Status s = db_->Delete(write_options, MakeSlice(key));
  if (!s.IsNotFound())
    LOG(ERROR) << "LevelDB remove failed: " << s.ToString();
  return s;
}

leveldb::Status LevelDBDatabase::Get(const StringPiece& key,
                                     std::string* value,
                                     bool* found,
                                     const LevelDBSnapshot* snapshot) {
  *found = false;
  leveldb::ReadOptions read_options;
  read_options.verify_checksums = true;  // TODO(jsbell): Disable this if the
                                         // performance impact is too great.
  read_options.snapshot = snapshot ? snapshot->snapshot_ : 0;

  const leveldb::Status s = db_->Get(read_options, MakeSlice(key), value);
  if (s.ok()) {
    *found = true;
    return s;
  }
  if (s.IsNotFound())
    return leveldb::Status::OK();
  HistogramLevelDBError("WebCore.IndexedDB.LevelDBReadErrors", s);
  LOG(ERROR) << "LevelDB get failed: " << s.ToString();
  return s;
}

leveldb::Status LevelDBDatabase::Write(const LevelDBWriteBatch& write_batch) {
  base::TimeTicks begin_time = base::TimeTicks::Now();
  leveldb::WriteOptions write_options;
  write_options.sync = kSyncWrites;

  const leveldb::Status s =
      db_->Write(write_options, write_batch.write_batch_.get());
  if (!s.ok()) {
    HistogramLevelDBError("WebCore.IndexedDB.LevelDBWriteErrors", s);
    LOG(ERROR) << "LevelDB write failed: " << s.ToString();
  } else {
    UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.WriteTime",
                        base::TimeTicks::Now() - begin_time);
  }
  return s;
}

scoped_ptr<LevelDBIterator> LevelDBDatabase::CreateIterator(
    const LevelDBSnapshot* snapshot) {
  leveldb::ReadOptions read_options;
  read_options.verify_checksums = true;  // TODO(jsbell): Disable this if the
                                         // performance impact is too great.
  read_options.snapshot = snapshot ? snapshot->snapshot_ : 0;

  scoped_ptr<leveldb::Iterator> i(db_->NewIterator(read_options));
  return scoped_ptr<LevelDBIterator>(
      IndexedDBClassFactory::Get()->CreateIteratorImpl(i.Pass()));
}

const LevelDBComparator* LevelDBDatabase::Comparator() const {
  return comparator_;
}

void LevelDBDatabase::Compact(const base::StringPiece& start,
                              const base::StringPiece& stop) {
  const leveldb::Slice start_slice = MakeSlice(start);
  const leveldb::Slice stop_slice = MakeSlice(stop);
  // NULL batch means just wait for earlier writes to be done
  db_->Write(leveldb::WriteOptions(), NULL);
  db_->CompactRange(&start_slice, &stop_slice);
}

void LevelDBDatabase::CompactAll() { db_->CompactRange(NULL, NULL); }

}  // namespace content


/**
 * \file
 *         Protects against replay attacks by comparing with the last
 *         unicast or broadcast frame counter of the sender.
 * \author
 *         Konrad Krentz <konrad.krentz@gmail.com>
 */

/**
 * \addtogroup llsec802154
 * @{
 */

#include <net/l2_buf.h>

#include "contiki/llsec/anti-replay.h"
#include "contiki/packetbuf.h"

/* This node's current frame counter value */
static uint32_t counter;

/*---------------------------------------------------------------------------*/
void
anti_replay_set_counter(struct net_buf *buf)
{
  frame802154_frame_counter_t reordered_counter;

  reordered_counter.u32 = LLSEC802154_HTONL(++counter);

  packetbuf_set_attr(buf, PACKETBUF_ATTR_FRAME_COUNTER_BYTES_0_1, reordered_counter.u16[0]);
  packetbuf_set_attr(buf, PACKETBUF_ATTR_FRAME_COUNTER_BYTES_2_3, reordered_counter.u16[1]);
}
/*---------------------------------------------------------------------------*/
uint32_t
anti_replay_get_counter(struct net_buf *buf)
{
  frame802154_frame_counter_t disordered_counter;

  disordered_counter.u16[0] = packetbuf_attr(buf, PACKETBUF_ATTR_FRAME_COUNTER_BYTES_0_1);
  disordered_counter.u16[1] = packetbuf_attr(buf, PACKETBUF_ATTR_FRAME_COUNTER_BYTES_2_3);

  return LLSEC802154_HTONL(disordered_counter.u32);
}
/*---------------------------------------------------------------------------*/
void
anti_replay_init_info(struct net_buf *buf, struct anti_replay_info *info)
{
  info->last_broadcast_counter
      = info->last_unicast_counter
      = anti_replay_get_counter(buf);
}
/*---------------------------------------------------------------------------*/
int
anti_replay_was_replayed(struct net_buf *buf, struct anti_replay_info *info)
{
  uint32_t received_counter;

  received_counter = anti_replay_get_counter(buf);

  if(packetbuf_holds_broadcast(buf)) {
    /* broadcast */
    if(received_counter <= info->last_broadcast_counter) {
      return 1;
    } else {
      info->last_broadcast_counter = received_counter;
      return 0;
    }
  } else {
    /* unicast */
    if(received_counter <= info->last_unicast_counter) {
      return 1;
    } else {
      info->last_unicast_counter = received_counter;
      return 0;
    }
  }
}
/*---------------------------------------------------------------------------*/

/** @} */