text:
The `simple-storage` module lets you easily and persistently store data across
Firefox restarts.  If you're familiar with [DOM storage][] on the Web, it's
kind of like that, but for add-ons.

[DOM storage]: https://developer.mozilla.org/en/DOM/Storage

The simple storage module exports an object called `storage` that is persistent
and private to your add-on.  It's a normal JavaScript object, and you can treat
it as you would any other.

To store a value, just assign it to a property on `storage`:

    var ss = require("sdk/simple-storage");
    ss.storage.myArray = [1, 1, 2, 3, 5, 8, 13];
    ss.storage.myBoolean = true;
    ss.storage.myNull = null;
    ss.storage.myNumber = 3.1337;
    ss.storage.myObject = { a: "foo", b: { c: true }, d: null };
    ss.storage.myString = "O frabjous day!";

You can store array, boolean, number, object, null, and string values.
If you'd like to store other types of values, you'll first have to convert
them to strings or another one of these types.

Be careful to set properties on the `storage` object and not the module itself:

    // This is no good!
    var ss = require("sdk/simple-storage");
    ss.foo = "I will not be saved! :(";

Simple Storage and "cfx run"
----------------------------
The simple storage module stores its data in your profile.
Because `cfx run` by default uses a fresh profile each time it runs,
simple storage won't work with add-ons executed using `cfx run` - that
is, stored data will not persist from one run to the next.

The easiest solution to this problem is to use the
[`--profiledir` option to `cfx run`](dev-guide/cfx-tool.html#profiledir).

If you use this method, you must end your debugging session by
quitting Firefox normally, not by cancelling the shell command.
If you don't close Firefox normally, then simple storage will
not be notified that the session is finished, and will not write
your data to the backing store.

Constructing Arrays
-------------------
Be careful to construct array objects conditionally in your code, or you may
zero them each time the construction code runs. For example, this add-on
tries to store the URLs of pages the user visits:

var ss = require("sdk/simple-storage");
ss.storage.pages = [];

require("sdk/tabs").on("ready", function(tab) {
  ss.storage.pages.push(tab.url);
});

var widget = require("sdk/widget").Widget({
  id: "log_history",
  label: "Log History",
  width: 30,
  content: "Log",
  onClick: function() {
    console.log(ss.storage.pages);
  }
});

But this isn't going to work, because it empties the array each time the
add-on runs (for example, each time Firefox is started). Line 2 needs
to be made conditional, so the array is only constructed if it does
not already exist:

if (!ss.storage.pages)
  ss.storage.pages = [];

Deleting Data
-------------
You can delete properties using the `delete` operator. Here's an add-on
that adds three widgets to write, read, and delete a value:

var widgets = require("sdk/widget");
var ss = require("sdk/simple-storage");

var widget = widgets.Widget({
  id: "write",
  label: "Write",
  width: 50,
  content: "Write",
  onClick: function() {
    ss.storage.value = 1;
    console.log("Setting value");
  }
});

var widget = widgets.Widget({
  id: "read",
  label: "Read",
  width: 50,
  content: "Read",
  onClick: function() {
    console.log(ss.storage.value);
  }
});

var widget = widgets.Widget({
  id: "delete",
  label: "Delete",
  width: 50,
  content: "Delete",
  onClick: function() {
    delete ss.storage.value;
    console.log("Deleting value");
  }
});

If you run it, you'll see that after clicking "Read" after clicking
"Delete" gives you the expected output:

info: undefined

Quotas
------
The simple storage available to your add-on is limited.  Currently this limit is
about five megabytes (5,242,880 bytes).  You can choose to be notified when you
go over quota, and you should respond by reducing the amount of data in storage.
If the user quits the application while you are over quota, all data stored
since the last time you were under quota will not be persisted.  You should not
let that happen.

To listen for quota notifications, register a listener for the `"OverQuota"`
event.  It will be called when your storage goes over quota.

    function myOnOverQuotaListener() {
      console.log("Uh oh.");
    }
    ss.on("OverQuota", myOnOverQuotaListener);

Listeners can also be removed:

    ss.removeListener("OverQuota", myOnOverQuotaListener);

To find out how much of your quota you're using, check the module's `quotaUsage`
property.  It indicates the percentage of quota your storage occupies.  If
you're within your quota, it's a number from 0 to 1, inclusive, and if you're
over, it's a number greater than 1.

Therefore, when you're notified that you're over quota, respond by removing
storage until your `quotaUsage` is less than or equal to 1.  Which particular
data you remove is up to you.  For example:

    ss.storage.myList = [ /* some long array */ ];
    ss.on("OverQuota", function () {
      while (ss.quotaUsage > 1)
        ss.storage.myList.pop();
    });

Private Browsing
----------------
If your storage is related to your users' Web history, personal information, or
other sensitive data, your add-on should respect
[private browsing](http://support.mozilla.com/en-US/kb/Private+Browsing).

To read about how to opt into private browsing mode and how to use the
SDK to avoid storing user data associated with private windows, refer to the
documentation for the
[`private-browsing` module](modules/sdk/private-browsing.html).

<api name="storage">
@property {object}
  A persistent object private to your add-on.  Properties with array, boolean,
  number, object, null, and string values will be persisted.
</api>

<api name="quotaUsage">
@property {number}
  A number in the range [0, Infinity) that indicates the percentage of quota
  occupied by storage.  A value in the range [0, 1] indicates that the storage
  is within quota.  A value greater than 1 indicates that the storage exceeds
  quota.
</api>

<api name="OverQuota">
@event
The module emits this event when your add-on's storage goes over its quota.
</api>


text:
export interface WrapGroupDimension {
	childWidth: number;
	childHeight: number;
	items: any[];
}

redpajama_set_name: RedPajamaGithub


text:
namespace Google.Cloud.Dialogflow.V2Beta1.Snippets
{
    // [START dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_async]
    using Google.Cloud.Dialogflow.V2Beta1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedKnowledgeBasesClientSnippets
    {
        /// <summary>Snippet for GetKnowledgeBaseAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task GetKnowledgeBaseRequestObjectAsync()
        {
            // Create client
            KnowledgeBasesClient knowledgeBasesClient = await KnowledgeBasesClient.CreateAsync();
            // Initialize request argument(s)
            GetKnowledgeBaseRequest request = new GetKnowledgeBaseRequest
            {
                KnowledgeBaseName = KnowledgeBaseName.FromProjectKnowledgeBase("[PROJECT]", "[KNOWLEDGE_BASE]"),
            };
            // Make the request
            KnowledgeBase response = await knowledgeBasesClient.GetKnowledgeBaseAsync(request);
        }
    }
    // [END dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_async]
}


text:
select DepositGroup from WizzardDeposits
group by DepositGroup
having avg(MagicWandSize) = (
select min(AverageSizes) as MinimalAverageSize from (
select avg(MagicWandSize) as AverageSizes from WizzardDeposits
group by DepositGroup) as WandSizeTable
)


text:
<?php

namespace Catalog\OrderBundle\Controller\Order;

use Admingenerated\CatalogOrderBundle\BaseOrderController\EditController as BaseEditController;

/**
 * EditController
 */
class EditController extends BaseEditController
{
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Database.Neo4j.Relationship where

import Database.Neo4j.Node
import qualified Data.HashMap.Lazy as Map
import Database.Neo4j.Types
import Database.Neo4j.Internal
import Network.HTTP
import Network.URI
import Data.Aeson
import Data.ByteString.Class
import Text.Printf
import qualified Data.Attoparsec as Attoparsec
import Control.Monad
import qualified Data.Vector as V

getRelationshipFromHTTPResult client result = case result of
    Right response -> case rspCode response of
        (2, 0, 0) -> let body = rspBody response in
            case Attoparsec.parse json body of
                Attoparsec.Done _ o ->
                    case relationshipAttributesFromParsedResponse o of
                    Just attrs  -> mkRelationshipFromAttributes client attrs
                    Nothing     -> return $
                        Left "Couldn't pull relationship attributes"
                _            -> return $ Left
                    ("Couldn't parse response as JSON. Response : " ++
                                        (show response))
        (2, 0, 1) -> case pullReturnedSelfURI $ rspBody response of
            Just selfURI -> getRelationship client selfURI
            _            -> return $ Left "no url returned :o"
        _ -> return $
            Left ("Relationship wasn't returned in response. " ++
                (show response))
    Left err -> return $ Left $ show err

data RelationshipRetrievalType = RetrieveAll | RetrieveIncoming | RetrieveOutgoing | RetrieveTyped String deriving (Eq)

-- | Create a relationship between two nodes. You must specify a name/relationship type
createRelationship :: Client -> Node -> Node -> String -> Properties -> IO (Either String Relationship)
createRelationship client n@(Node from _) m@(Node to _) name properties =
    clientGuard client [from, to] $ do
        let uri = from `appendToPath` "relationships"
        let request = buildPost uri $ toStrictByteString $ encode $
                    object [("to", toJSON $ show to), ("type", toJSON name)]
        r <- getRelationshipFromHTTPResult client =<< simpleHTTP request
        case (properties, r) of
            ([], _)            -> return r
            (_, Right relationship) ->
                updateRelationshipProperties client relationship properties
            (_, Left err)           -> return $ Left err

getRelationship :: Client -> URI -> IO (Either String Relationship)
getRelationship client uri = clientGuard client [uri] $ do
    let request = mkRequest GET uri
    (getRelationshipFromHTTPResult client) =<< simpleHTTP request

-- | Update the properties of a relationship
updateRelationshipProperties :: Client -> Relationship -> Properties -> IO (Either String Relationship)
updateRelationshipProperties client r ps =
    clientGuard client [(relationshipURI r)] $ do
        let uri = (relationshipURI r) `appendToPath` "properties"
        let request = buildPut uri (toStrictByteString $ encode $ object ps)
        result <- simpleHTTP request
        case result of
            Right response -> case rspCode response of
                (2, 0, 4) -> getRelationship defaultClient (relationshipURI r)
                _         -> return $ Left ("Couldn't update relationship. "
                                ++ (show response))

deleteRelationship :: Client -> Relationship -> IO (Either String ())
deleteRelationship client (Relationship uri _ _ _ _) =
    clientGuard client [uri] $ delete "Relationship" uri

relationshipAttributesFromParsedResponse (Object o) = do
    start <- (parseURI <=< fromJSON') =<< Map.lookup "start" o
    end <- (parseURI <=< fromJSON') =<< Map.lookup "end" o
    self <- (parseURI <=< fromJSON') =<< Map.lookup "self" o
    name <- fromJSON' =<< Map.lookup "type" o
    props <- (fmap Map.toList . fromJSON') =<< Map.lookup "data" o
    return (self, start, end, name, props)
relationshipAttributesFromParsedResponse _ = Nothing

mkRelationshipFromAttributes client (self, start, end, name, props) = do
    x <- getNode client start
    y <- getNode client end
    case (x, y) of
        (Right x', Right y')   ->
            return $ Right $ Relationship self x' y' name props
        (Left err, Right _)    ->
            return $ Left $ printf "%s: %s" (show start) (show err)
        (Right _, Left err)    ->
            return $ Left $ printf "%s: %s" (show end) (show err)
        (Left err1, Left err2) ->
            return $ Left $ printf "%s: %s" (show (start, end))
                                            (show (err1, err2))

-- | Get all the relationships of a given type for a node.
getRelationships :: Client -> RelationshipRetrievalType -> Node -> IO (Either String [Relationship])
getRelationships client rrType (Node nodeURI _) = do
    let uri = nodeURI `appendToPath` "relationships" `appendToPath`
            case rrType of
                RetrieveAll ->  "all"
                RetrieveIncoming -> "in"
                RetrieveOutgoing -> "out"
                RetrieveTyped relType -> "all/" ++ relType
    result <- simpleHTTP $ mkRequest GET uri
    let relationshipResult = case result of
            Right response -> case rspCode response of
                (2, 0, 0) -> let body = rspBody response in
                    case Attoparsec.parse json body of
                        Attoparsec.Done _ (Array v) -> Right $ mapM
                            (relationshipAttributesFromParsedResponse)
                                (V.toList v)
                        _ -> Left ("Couldn't parse response " ++
                                (show response))
                _ -> Left $ show response
            Left err -> Left $ show err
    case relationshipResult of
        Right (Just xs) -> fmap sequence $
            mapM (mkRelationshipFromAttributes client) xs
        Right _ -> return $ Left $
            printf "Couldn't extract data from relationship response %s" $
                    show relationshipResult
        Left err -> return $ Left $ show err

incomingRelationships client = getRelationships client RetrieveIncoming
outgoingRelationships client = getRelationships client RetrieveOutgoing
allRelationships client = getRelationships client RetrieveAll


text:
package volumefakes

import (
	"context"
	"io"
	"sync"

	"github.com/concourse/baggageclaim/volume"
)

type FakeRepository struct {
	CreateVolumeStub        func(context.Context, string, volume.Strategy, volume.Properties, bool) (volume.Volume, error)
	createVolumeMutex       sync.RWMutex
	createVolumeArgsForCall []struct {
		arg1 context.Context
		arg2 string
		arg3 volume.Strategy
		arg4 volume.Properties
		arg5 bool
	}
	createVolumeReturns struct {
		result1 volume.Volume
		result2 error
	}
	createVolumeReturnsOnCall map[int]struct {
		result1 volume.Volume
		result2 error
	}
	DestroyVolumeStub        func(context.Context, string) error
	destroyVolumeMutex       sync.RWMutex
	destroyVolumeArgsForCall []struct {
		arg1 context.Context
		arg2 string
	}
	destroyVolumeReturns struct {
		result1 error
	}
	destroyVolumeReturnsOnCall map[int]struct {
		result1 error
	}
	DestroyVolumeAndDescendantsStub        func(context.Context, string) error
	destroyVolumeAndDescendantsMutex       sync.RWMutex
	destroyVolumeAndDescendantsArgsForCall []struct {
		arg1 context.Context
		arg2 string
	}
	destroyVolumeAndDescendantsReturns struct {
		result1 error
	}
	destroyVolumeAndDescendantsReturnsOnCall map[int]struct {
		result1 error
	}
	GetPrivilegedStub        func(context.Context, string) (bool, error)
	getPrivilegedMutex       sync.RWMutex
	getPrivilegedArgsForCall []struct {
		arg1 context.Context
		arg2 string
	}
	getPrivilegedReturns struct {
		result1 bool
		result2 error
	}
	getPrivilegedReturnsOnCall map[int]struct {
		result1 bool
		result2 error
	}
	GetVolumeStub        func(context.Context, string) (volume.Volume, bool, error)
	getVolumeMutex       sync.RWMutex
	getVolumeArgsForCall []struct {
		arg1 context.Context
		arg2 string
	}
	getVolumeReturns struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}
	getVolumeReturnsOnCall map[int]struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}
	ListVolumesStub        func(context.Context, volume.Properties) (volume.Volumes, []string, error)
	listVolumesMutex       sync.RWMutex
	listVolumesArgsForCall []struct {
		arg1 context.Context
		arg2 volume.Properties
	}
	listVolumesReturns struct {
		result1 volume.Volumes
		result2 []string
		result3 error
	}
	listVolumesReturnsOnCall map[int]struct {
		result1 volume.Volumes
		result2 []string
		result3 error
	}
	SetPrivilegedStub        func(context.Context, string, bool) error
	setPrivilegedMutex       sync.RWMutex
	setPrivilegedArgsForCall []struct {
		arg1 context.Context
		arg2 string
		arg3 bool
	}
	setPrivilegedReturns struct {
		result1 error
	}
	setPrivilegedReturnsOnCall map[int]struct {
		result1 error
	}
	SetPropertyStub        func(context.Context, string, string, string) error
	setPropertyMutex       sync.RWMutex
	setPropertyArgsForCall []struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
	}
	setPropertyReturns struct {
		result1 error
	}
	setPropertyReturnsOnCall map[int]struct {
		result1 error
	}
	StreamInStub        func(context.Context, string, string, string, io.Reader) (bool, error)
	streamInMutex       sync.RWMutex
	streamInArgsForCall []struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
		arg5 io.Reader
	}
	streamInReturns struct {
		result1 bool
		result2 error
	}
	streamInReturnsOnCall map[int]struct {
		result1 bool
		result2 error
	}
	StreamOutStub        func(context.Context, string, string, string, io.Writer) error
	streamOutMutex       sync.RWMutex
	streamOutArgsForCall []struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
		arg5 io.Writer
	}
	streamOutReturns struct {
		result1 error
	}
	streamOutReturnsOnCall map[int]struct {
		result1 error
	}
	StreamP2pOutStub        func(context.Context, string, string, string, string) error
	streamP2pOutMutex       sync.RWMutex
	streamP2pOutArgsForCall []struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
		arg5 string
	}
	streamP2pOutReturns struct {
		result1 error
	}
	streamP2pOutReturnsOnCall map[int]struct {
		result1 error
	}
	VolumeParentStub        func(context.Context, string) (volume.Volume, bool, error)
	volumeParentMutex       sync.RWMutex
	volumeParentArgsForCall []struct {
		arg1 context.Context
		arg2 string
	}
	volumeParentReturns struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}
	volumeParentReturnsOnCall map[int]struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeRepository) CreateVolume(arg1 context.Context, arg2 string, arg3 volume.Strategy, arg4 volume.Properties, arg5 bool) (volume.Volume, error) {
	fake.createVolumeMutex.Lock()
	ret, specificReturn := fake.createVolumeReturnsOnCall[len(fake.createVolumeArgsForCall)]
	fake.createVolumeArgsForCall = append(fake.createVolumeArgsForCall, struct {
		arg1 context.Context
		arg2 string
		arg3 volume.Strategy
		arg4 volume.Properties
		arg5 bool
	}{arg1, arg2, arg3, arg4, arg5})
	fake.recordInvocation("CreateVolume", []interface{}{arg1, arg2, arg3, arg4, arg5})
	fake.createVolumeMutex.Unlock()
	if fake.CreateVolumeStub != nil {
		return fake.CreateVolumeStub(arg1, arg2, arg3, arg4, arg5)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.createVolumeReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeRepository) CreateVolumeCallCount() int {
	fake.createVolumeMutex.RLock()
	defer fake.createVolumeMutex.RUnlock()
	return len(fake.createVolumeArgsForCall)
}

func (fake *FakeRepository) CreateVolumeCalls(stub func(context.Context, string, volume.Strategy, volume.Properties, bool) (volume.Volume, error)) {
	fake.createVolumeMutex.Lock()
	defer fake.createVolumeMutex.Unlock()
	fake.CreateVolumeStub = stub
}

func (fake *FakeRepository) CreateVolumeArgsForCall(i int) (context.Context, string, volume.Strategy, volume.Properties, bool) {
	fake.createVolumeMutex.RLock()
	defer fake.createVolumeMutex.RUnlock()
	argsForCall := fake.createVolumeArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5
}

func (fake *FakeRepository) CreateVolumeReturns(result1 volume.Volume, result2 error) {
	fake.createVolumeMutex.Lock()
	defer fake.createVolumeMutex.Unlock()
	fake.CreateVolumeStub = nil
	fake.createVolumeReturns = struct {
		result1 volume.Volume
		result2 error
	}{result1, result2}
}

func (fake *FakeRepository) CreateVolumeReturnsOnCall(i int, result1 volume.Volume, result2 error) {
	fake.createVolumeMutex.Lock()
	defer fake.createVolumeMutex.Unlock()
	fake.CreateVolumeStub = nil
	if fake.createVolumeReturnsOnCall == nil {
		fake.createVolumeReturnsOnCall = make(map[int]struct {
			result1 volume.Volume
			result2 error
		})
	}
	fake.createVolumeReturnsOnCall[i] = struct {
		result1 volume.Volume
		result2 error
	}{result1, result2}
}

func (fake *FakeRepository) DestroyVolume(arg1 context.Context, arg2 string) error {
	fake.destroyVolumeMutex.Lock()
	ret, specificReturn := fake.destroyVolumeReturnsOnCall[len(fake.destroyVolumeArgsForCall)]
	fake.destroyVolumeArgsForCall = append(fake.destroyVolumeArgsForCall, struct {
		arg1 context.Context
		arg2 string
	}{arg1, arg2})
	fake.recordInvocation("DestroyVolume", []interface{}{arg1, arg2})
	fake.destroyVolumeMutex.Unlock()
	if fake.DestroyVolumeStub != nil {
		return fake.DestroyVolumeStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.destroyVolumeReturns
	return fakeReturns.result1
}

func (fake *FakeRepository) DestroyVolumeCallCount() int {
	fake.destroyVolumeMutex.RLock()
	defer fake.destroyVolumeMutex.RUnlock()
	return len(fake.destroyVolumeArgsForCall)
}

func (fake *FakeRepository) DestroyVolumeCalls(stub func(context.Context, string) error) {
	fake.destroyVolumeMutex.Lock()
	defer fake.destroyVolumeMutex.Unlock()
	fake.DestroyVolumeStub = stub
}

func (fake *FakeRepository) DestroyVolumeArgsForCall(i int) (context.Context, string) {
	fake.destroyVolumeMutex.RLock()
	defer fake.destroyVolumeMutex.RUnlock()
	argsForCall := fake.destroyVolumeArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeRepository) DestroyVolumeReturns(result1 error) {
	fake.destroyVolumeMutex.Lock()
	defer fake.destroyVolumeMutex.Unlock()
	fake.DestroyVolumeStub = nil
	fake.destroyVolumeReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) DestroyVolumeReturnsOnCall(i int, result1 error) {
	fake.destroyVolumeMutex.Lock()
	defer fake.destroyVolumeMutex.Unlock()
	fake.DestroyVolumeStub = nil
	if fake.destroyVolumeReturnsOnCall == nil {
		fake.destroyVolumeReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.destroyVolumeReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) DestroyVolumeAndDescendants(arg1 context.Context, arg2 string) error {
	fake.destroyVolumeAndDescendantsMutex.Lock()
	ret, specificReturn := fake.destroyVolumeAndDescendantsReturnsOnCall[len(fake.destroyVolumeAndDescendantsArgsForCall)]
	fake.destroyVolumeAndDescendantsArgsForCall = append(fake.destroyVolumeAndDescendantsArgsForCall, struct {
		arg1 context.Context
		arg2 string
	}{arg1, arg2})
	fake.recordInvocation("DestroyVolumeAndDescendants", []interface{}{arg1, arg2})
	fake.destroyVolumeAndDescendantsMutex.Unlock()
	if fake.DestroyVolumeAndDescendantsStub != nil {
		return fake.DestroyVolumeAndDescendantsStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.destroyVolumeAndDescendantsReturns
	return fakeReturns.result1
}

func (fake *FakeRepository) DestroyVolumeAndDescendantsCallCount() int {
	fake.destroyVolumeAndDescendantsMutex.RLock()
	defer fake.destroyVolumeAndDescendantsMutex.RUnlock()
	return len(fake.destroyVolumeAndDescendantsArgsForCall)
}

func (fake *FakeRepository) DestroyVolumeAndDescendantsCalls(stub func(context.Context, string) error) {
	fake.destroyVolumeAndDescendantsMutex.Lock()
	defer fake.destroyVolumeAndDescendantsMutex.Unlock()
	fake.DestroyVolumeAndDescendantsStub = stub
}

func (fake *FakeRepository) DestroyVolumeAndDescendantsArgsForCall(i int) (context.Context, string) {
	fake.destroyVolumeAndDescendantsMutex.RLock()
	defer fake.destroyVolumeAndDescendantsMutex.RUnlock()
	argsForCall := fake.destroyVolumeAndDescendantsArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeRepository) DestroyVolumeAndDescendantsReturns(result1 error) {
	fake.destroyVolumeAndDescendantsMutex.Lock()
	defer fake.destroyVolumeAndDescendantsMutex.Unlock()
	fake.DestroyVolumeAndDescendantsStub = nil
	fake.destroyVolumeAndDescendantsReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) DestroyVolumeAndDescendantsReturnsOnCall(i int, result1 error) {
	fake.destroyVolumeAndDescendantsMutex.Lock()
	defer fake.destroyVolumeAndDescendantsMutex.Unlock()
	fake.DestroyVolumeAndDescendantsStub = nil
	if fake.destroyVolumeAndDescendantsReturnsOnCall == nil {
		fake.destroyVolumeAndDescendantsReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.destroyVolumeAndDescendantsReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) GetPrivileged(arg1 context.Context, arg2 string) (bool, error) {
	fake.getPrivilegedMutex.Lock()
	ret, specificReturn := fake.getPrivilegedReturnsOnCall[len(fake.getPrivilegedArgsForCall)]
	fake.getPrivilegedArgsForCall = append(fake.getPrivilegedArgsForCall, struct {
		arg1 context.Context
		arg2 string
	}{arg1, arg2})
	fake.recordInvocation("GetPrivileged", []interface{}{arg1, arg2})
	fake.getPrivilegedMutex.Unlock()
	if fake.GetPrivilegedStub != nil {
		return fake.GetPrivilegedStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.getPrivilegedReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeRepository) GetPrivilegedCallCount() int {
	fake.getPrivilegedMutex.RLock()
	defer fake.getPrivilegedMutex.RUnlock()
	return len(fake.getPrivilegedArgsForCall)
}

func (fake *FakeRepository) GetPrivilegedCalls(stub func(context.Context, string) (bool, error)) {
	fake.getPrivilegedMutex.Lock()
	defer fake.getPrivilegedMutex.Unlock()
	fake.GetPrivilegedStub = stub
}

func (fake *FakeRepository) GetPrivilegedArgsForCall(i int) (context.Context, string) {
	fake.getPrivilegedMutex.RLock()
	defer fake.getPrivilegedMutex.RUnlock()
	argsForCall := fake.getPrivilegedArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeRepository) GetPrivilegedReturns(result1 bool, result2 error) {
	fake.getPrivilegedMutex.Lock()
	defer fake.getPrivilegedMutex.Unlock()
	fake.GetPrivilegedStub = nil
	fake.getPrivilegedReturns = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeRepository) GetPrivilegedReturnsOnCall(i int, result1 bool, result2 error) {
	fake.getPrivilegedMutex.Lock()
	defer fake.getPrivilegedMutex.Unlock()
	fake.GetPrivilegedStub = nil
	if fake.getPrivilegedReturnsOnCall == nil {
		fake.getPrivilegedReturnsOnCall = make(map[int]struct {
			result1 bool
			result2 error
		})
	}
	fake.getPrivilegedReturnsOnCall[i] = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeRepository) GetVolume(arg1 context.Context, arg2 string) (volume.Volume, bool, error) {
	fake.getVolumeMutex.Lock()
	ret, specificReturn := fake.getVolumeReturnsOnCall[len(fake.getVolumeArgsForCall)]
	fake.getVolumeArgsForCall = append(fake.getVolumeArgsForCall, struct {
		arg1 context.Context
		arg2 string
	}{arg1, arg2})
	fake.recordInvocation("GetVolume", []interface{}{arg1, arg2})
	fake.getVolumeMutex.Unlock()
	if fake.GetVolumeStub != nil {
		return fake.GetVolumeStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2, ret.result3
	}
	fakeReturns := fake.getVolumeReturns
	return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
}

func (fake *FakeRepository) GetVolumeCallCount() int {
	fake.getVolumeMutex.RLock()
	defer fake.getVolumeMutex.RUnlock()
	return len(fake.getVolumeArgsForCall)
}

func (fake *FakeRepository) GetVolumeCalls(stub func(context.Context, string) (volume.Volume, bool, error)) {
	fake.getVolumeMutex.Lock()
	defer fake.getVolumeMutex.Unlock()
	fake.GetVolumeStub = stub
}

func (fake *FakeRepository) GetVolumeArgsForCall(i int) (context.Context, string) {
	fake.getVolumeMutex.RLock()
	defer fake.getVolumeMutex.RUnlock()
	argsForCall := fake.getVolumeArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeRepository) GetVolumeReturns(result1 volume.Volume, result2 bool, result3 error) {
	fake.getVolumeMutex.Lock()
	defer fake.getVolumeMutex.Unlock()
	fake.GetVolumeStub = nil
	fake.getVolumeReturns = struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeRepository) GetVolumeReturnsOnCall(i int, result1 volume.Volume, result2 bool, result3 error) {
	fake.getVolumeMutex.Lock()
	defer fake.getVolumeMutex.Unlock()
	fake.GetVolumeStub = nil
	if fake.getVolumeReturnsOnCall == nil {
		fake.getVolumeReturnsOnCall = make(map[int]struct {
			result1 volume.Volume
			result2 bool
			result3 error
		})
	}
	fake.getVolumeReturnsOnCall[i] = struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeRepository) ListVolumes(arg1 context.Context, arg2 volume.Properties) (volume.Volumes, []string, error) {
	fake.listVolumesMutex.Lock()
	ret, specificReturn := fake.listVolumesReturnsOnCall[len(fake.listVolumesArgsForCall)]
	fake.listVolumesArgsForCall = append(fake.listVolumesArgsForCall, struct {
		arg1 context.Context
		arg2 volume.Properties
	}{arg1, arg2})
	fake.recordInvocation("ListVolumes", []interface{}{arg1, arg2})
	fake.listVolumesMutex.Unlock()
	if fake.ListVolumesStub != nil {
		return fake.ListVolumesStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2, ret.result3
	}
	fakeReturns := fake.listVolumesReturns
	return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
}

func (fake *FakeRepository) ListVolumesCallCount() int {
	fake.listVolumesMutex.RLock()
	defer fake.listVolumesMutex.RUnlock()
	return len(fake.listVolumesArgsForCall)
}

func (fake *FakeRepository) ListVolumesCalls(stub func(context.Context, volume.Properties) (volume.Volumes, []string, error)) {
	fake.listVolumesMutex.Lock()
	defer fake.listVolumesMutex.Unlock()
	fake.ListVolumesStub = stub
}

func (fake *FakeRepository) ListVolumesArgsForCall(i int) (context.Context, volume.Properties) {
	fake.listVolumesMutex.RLock()
	defer fake.listVolumesMutex.RUnlock()
	argsForCall := fake.listVolumesArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeRepository) ListVolumesReturns(result1 volume.Volumes, result2 []string, result3 error) {
	fake.listVolumesMutex.Lock()
	defer fake.listVolumesMutex.Unlock()
	fake.ListVolumesStub = nil
	fake.listVolumesReturns = struct {
		result1 volume.Volumes
		result2 []string
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeRepository) ListVolumesReturnsOnCall(i int, result1 volume.Volumes, result2 []string, result3 error) {
	fake.listVolumesMutex.Lock()
	defer fake.listVolumesMutex.Unlock()
	fake.ListVolumesStub = nil
	if fake.listVolumesReturnsOnCall == nil {
		fake.listVolumesReturnsOnCall = make(map[int]struct {
			result1 volume.Volumes
			result2 []string
			result3 error
		})
	}
	fake.listVolumesReturnsOnCall[i] = struct {
		result1 volume.Volumes
		result2 []string
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeRepository) SetPrivileged(arg1 context.Context, arg2 string, arg3 bool) error {
	fake.setPrivilegedMutex.Lock()
	ret, specificReturn := fake.setPrivilegedReturnsOnCall[len(fake.setPrivilegedArgsForCall)]
	fake.setPrivilegedArgsForCall = append(fake.setPrivilegedArgsForCall, struct {
		arg1 context.Context
		arg2 string
		arg3 bool
	}{arg1, arg2, arg3})
	fake.recordInvocation("SetPrivileged", []interface{}{arg1, arg2, arg3})
	fake.setPrivilegedMutex.Unlock()
	if fake.SetPrivilegedStub != nil {
		return fake.SetPrivilegedStub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.setPrivilegedReturns
	return fakeReturns.result1
}

func (fake *FakeRepository) SetPrivilegedCallCount() int {
	fake.setPrivilegedMutex.RLock()
	defer fake.setPrivilegedMutex.RUnlock()
	return len(fake.setPrivilegedArgsForCall)
}

func (fake *FakeRepository) SetPrivilegedCalls(stub func(context.Context, string, bool) error) {
	fake.setPrivilegedMutex.Lock()
	defer fake.setPrivilegedMutex.Unlock()
	fake.SetPrivilegedStub = stub
}

func (fake *FakeRepository) SetPrivilegedArgsForCall(i int) (context.Context, string, bool) {
	fake.setPrivilegedMutex.RLock()
	defer fake.setPrivilegedMutex.RUnlock()
	argsForCall := fake.setPrivilegedArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeRepository) SetPrivilegedReturns(result1 error) {
	fake.setPrivilegedMutex.Lock()
	defer fake.setPrivilegedMutex.Unlock()
	fake.SetPrivilegedStub = nil
	fake.setPrivilegedReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) SetPrivilegedReturnsOnCall(i int, result1 error) {
	fake.setPrivilegedMutex.Lock()
	defer fake.setPrivilegedMutex.Unlock()
	fake.SetPrivilegedStub = nil
	if fake.setPrivilegedReturnsOnCall == nil {
		fake.setPrivilegedReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.setPrivilegedReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) SetProperty(arg1 context.Context, arg2 string, arg3 string, arg4 string) error {
	fake.setPropertyMutex.Lock()
	ret, specificReturn := fake.setPropertyReturnsOnCall[len(fake.setPropertyArgsForCall)]
	fake.setPropertyArgsForCall = append(fake.setPropertyArgsForCall, struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
	}{arg1, arg2, arg3, arg4})
	fake.recordInvocation("SetProperty", []interface{}{arg1, arg2, arg3, arg4})
	fake.setPropertyMutex.Unlock()
	if fake.SetPropertyStub != nil {
		return fake.SetPropertyStub(arg1, arg2, arg3, arg4)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.setPropertyReturns
	return fakeReturns.result1
}

func (fake *FakeRepository) SetPropertyCallCount() int {
	fake.setPropertyMutex.RLock()
	defer fake.setPropertyMutex.RUnlock()
	return len(fake.setPropertyArgsForCall)
}

func (fake *FakeRepository) SetPropertyCalls(stub func(context.Context, string, string, string) error) {
	fake.setPropertyMutex.Lock()
	defer fake.setPropertyMutex.Unlock()
	fake.SetPropertyStub = stub
}

func (fake *FakeRepository) SetPropertyArgsForCall(i int) (context.Context, string, string, string) {
	fake.setPropertyMutex.RLock()
	defer fake.setPropertyMutex.RUnlock()
	argsForCall := fake.setPropertyArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}

func (fake *FakeRepository) SetPropertyReturns(result1 error) {
	fake.setPropertyMutex.Lock()
	defer fake.setPropertyMutex.Unlock()
	fake.SetPropertyStub = nil
	fake.setPropertyReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) SetPropertyReturnsOnCall(i int, result1 error) {
	fake.setPropertyMutex.Lock()
	defer fake.setPropertyMutex.Unlock()
	fake.SetPropertyStub = nil
	if fake.setPropertyReturnsOnCall == nil {
		fake.setPropertyReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.setPropertyReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) StreamIn(arg1 context.Context, arg2 string, arg3 string, arg4 string, arg5 io.Reader) (bool, error) {
	fake.streamInMutex.Lock()
	ret, specificReturn := fake.streamInReturnsOnCall[len(fake.streamInArgsForCall)]
	fake.streamInArgsForCall = append(fake.streamInArgsForCall, struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
		arg5 io.Reader
	}{arg1, arg2, arg3, arg4, arg5})
	fake.recordInvocation("StreamIn", []interface{}{arg1, arg2, arg3, arg4, arg5})
	fake.streamInMutex.Unlock()
	if fake.StreamInStub != nil {
		return fake.StreamInStub(arg1, arg2, arg3, arg4, arg5)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.streamInReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeRepository) StreamInCallCount() int {
	fake.streamInMutex.RLock()
	defer fake.streamInMutex.RUnlock()
	return len(fake.streamInArgsForCall)
}

func (fake *FakeRepository) StreamInCalls(stub func(context.Context, string, string, string, io.Reader) (bool, error)) {
	fake.streamInMutex.Lock()
	defer fake.streamInMutex.Unlock()
	fake.StreamInStub = stub
}

func (fake *FakeRepository) StreamInArgsForCall(i int) (context.Context, string, string, string, io.Reader) {
	fake.streamInMutex.RLock()
	defer fake.streamInMutex.RUnlock()
	argsForCall := fake.streamInArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5
}

func (fake *FakeRepository) StreamInReturns(result1 bool, result2 error) {
	fake.streamInMutex.Lock()
	defer fake.streamInMutex.Unlock()
	fake.StreamInStub = nil
	fake.streamInReturns = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeRepository) StreamInReturnsOnCall(i int, result1 bool, result2 error) {
	fake.streamInMutex.Lock()
	defer fake.streamInMutex.Unlock()
	fake.StreamInStub = nil
	if fake.streamInReturnsOnCall == nil {
		fake.streamInReturnsOnCall = make(map[int]struct {
			result1 bool
			result2 error
		})
	}
	fake.streamInReturnsOnCall[i] = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeRepository) StreamOut(arg1 context.Context, arg2 string, arg3 string, arg4 string, arg5 io.Writer) error {
	fake.streamOutMutex.Lock()
	ret, specificReturn := fake.streamOutReturnsOnCall[len(fake.streamOutArgsForCall)]
	fake.streamOutArgsForCall = append(fake.streamOutArgsForCall, struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
		arg5 io.Writer
	}{arg1, arg2, arg3, arg4, arg5})
	fake.recordInvocation("StreamOut", []interface{}{arg1, arg2, arg3, arg4, arg5})
	fake.streamOutMutex.Unlock()
	if fake.StreamOutStub != nil {
		return fake.StreamOutStub(arg1, arg2, arg3, arg4, arg5)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.streamOutReturns
	return fakeReturns.result1
}

func (fake *FakeRepository) StreamOutCallCount() int {
	fake.streamOutMutex.RLock()
	defer fake.streamOutMutex.RUnlock()
	return len(fake.streamOutArgsForCall)
}

func (fake *FakeRepository) StreamOutCalls(stub func(context.Context, string, string, string, io.Writer) error) {
	fake.streamOutMutex.Lock()
	defer fake.streamOutMutex.Unlock()
	fake.StreamOutStub = stub
}

func (fake *FakeRepository) StreamOutArgsForCall(i int) (context.Context, string, string, string, io.Writer) {
	fake.streamOutMutex.RLock()
	defer fake.streamOutMutex.RUnlock()
	argsForCall := fake.streamOutArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5
}

func (fake *FakeRepository) StreamOutReturns(result1 error) {
	fake.streamOutMutex.Lock()
	defer fake.streamOutMutex.Unlock()
	fake.StreamOutStub = nil
	fake.streamOutReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) StreamOutReturnsOnCall(i int, result1 error) {
	fake.streamOutMutex.Lock()
	defer fake.streamOutMutex.Unlock()
	fake.StreamOutStub = nil
	if fake.streamOutReturnsOnCall == nil {
		fake.streamOutReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.streamOutReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) StreamP2pOut(arg1 context.Context, arg2 string, arg3 string, arg4 string, arg5 string) error {
	fake.streamP2pOutMutex.Lock()
	ret, specificReturn := fake.streamP2pOutReturnsOnCall[len(fake.streamP2pOutArgsForCall)]
	fake.streamP2pOutArgsForCall = append(fake.streamP2pOutArgsForCall, struct {
		arg1 context.Context
		arg2 string
		arg3 string
		arg4 string
		arg5 string
	}{arg1, arg2, arg3, arg4, arg5})
	fake.recordInvocation("StreamP2pOut", []interface{}{arg1, arg2, arg3, arg4, arg5})
	fake.streamP2pOutMutex.Unlock()
	if fake.StreamP2pOutStub != nil {
		return fake.StreamP2pOutStub(arg1, arg2, arg3, arg4, arg5)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.streamP2pOutReturns
	return fakeReturns.result1
}

func (fake *FakeRepository) StreamP2pOutCallCount() int {
	fake.streamP2pOutMutex.RLock()
	defer fake.streamP2pOutMutex.RUnlock()
	return len(fake.streamP2pOutArgsForCall)
}

func (fake *FakeRepository) StreamP2pOutCalls(stub func(context.Context, string, string, string, string) error) {
	fake.streamP2pOutMutex.Lock()
	defer fake.streamP2pOutMutex.Unlock()
	fake.StreamP2pOutStub = stub
}

func (fake *FakeRepository) StreamP2pOutArgsForCall(i int) (context.Context, string, string, string, string) {
	fake.streamP2pOutMutex.RLock()
	defer fake.streamP2pOutMutex.RUnlock()
	argsForCall := fake.streamP2pOutArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5
}

func (fake *FakeRepository) StreamP2pOutReturns(result1 error) {
	fake.streamP2pOutMutex.Lock()
	defer fake.streamP2pOutMutex.Unlock()
	fake.StreamP2pOutStub = nil
	fake.streamP2pOutReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) StreamP2pOutReturnsOnCall(i int, result1 error) {
	fake.streamP2pOutMutex.Lock()
	defer fake.streamP2pOutMutex.Unlock()
	fake.StreamP2pOutStub = nil
	if fake.streamP2pOutReturnsOnCall == nil {
		fake.streamP2pOutReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.streamP2pOutReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeRepository) VolumeParent(arg1 context.Context, arg2 string) (volume.Volume, bool, error) {
	fake.volumeParentMutex.Lock()
	ret, specificReturn := fake.volumeParentReturnsOnCall[len(fake.volumeParentArgsForCall)]
	fake.volumeParentArgsForCall = append(fake.volumeParentArgsForCall, struct {
		arg1 context.Context
		arg2 string
	}{arg1, arg2})
	fake.recordInvocation("VolumeParent", []interface{}{arg1, arg2})
	fake.volumeParentMutex.Unlock()
	if fake.VolumeParentStub != nil {
		return fake.VolumeParentStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2, ret.result3
	}
	fakeReturns := fake.volumeParentReturns
	return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
}

func (fake *FakeRepository) VolumeParentCallCount() int {
	fake.volumeParentMutex.RLock()
	defer fake.volumeParentMutex.RUnlock()
	return len(fake.volumeParentArgsForCall)
}

func (fake *FakeRepository) VolumeParentCalls(stub func(context.Context, string) (volume.Volume, bool, error)) {
	fake.volumeParentMutex.Lock()
	defer fake.volumeParentMutex.Unlock()
	fake.VolumeParentStub = stub
}

func (fake *FakeRepository) VolumeParentArgsForCall(i int) (context.Context, string) {
	fake.volumeParentMutex.RLock()
	defer fake.volumeParentMutex.RUnlock()
	argsForCall := fake.volumeParentArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeRepository) VolumeParentReturns(result1 volume.Volume, result2 bool, result3 error) {
	fake.volumeParentMutex.Lock()
	defer fake.volumeParentMutex.Unlock()
	fake.VolumeParentStub = nil
	fake.volumeParentReturns = struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeRepository) VolumeParentReturnsOnCall(i int, result1 volume.Volume, result2 bool, result3 error) {
	fake.volumeParentMutex.Lock()
	defer fake.volumeParentMutex.Unlock()
	fake.VolumeParentStub = nil
	if fake.volumeParentReturnsOnCall == nil {
		fake.volumeParentReturnsOnCall = make(map[int]struct {
			result1 volume.Volume
			result2 bool
			result3 error
		})
	}
	fake.volumeParentReturnsOnCall[i] = struct {
		result1 volume.Volume
		result2 bool
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeRepository) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.createVolumeMutex.RLock()
	defer fake.createVolumeMutex.RUnlock()
	fake.destroyVolumeMutex.RLock()
	defer fake.destroyVolumeMutex.RUnlock()
	fake.destroyVolumeAndDescendantsMutex.RLock()
	defer fake.destroyVolumeAndDescendantsMutex.RUnlock()
	fake.getPrivilegedMutex.RLock()
	defer fake.getPrivilegedMutex.RUnlock()
	fake.getVolumeMutex.RLock()
	defer fake.getVolumeMutex.RUnlock()
	fake.listVolumesMutex.RLock()
	defer fake.listVolumesMutex.RUnlock()
	fake.setPrivilegedMutex.RLock()
	defer fake.setPrivilegedMutex.RUnlock()
	fake.setPropertyMutex.RLock()
	defer fake.setPropertyMutex.RUnlock()
	fake.streamInMutex.RLock()
	defer fake.streamInMutex.RUnlock()
	fake.streamOutMutex.RLock()
	defer fake.streamOutMutex.RUnlock()
	fake.streamP2pOutMutex.RLock()
	defer fake.streamP2pOutMutex.RUnlock()
	fake.volumeParentMutex.RLock()
	defer fake.volumeParentMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeRepository) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ volume.Repository = new(FakeRepository)


text:
unless User.where(:email => 'dan.elbert@gmail.com').exists?
  dan = User.new({:email => "dan.elbert@gmail.com", :name => "Dan", :username => 'dan', :password => "qwerty", :password_confirmation => "qwerty", :is_admin => true})
  dan.save!
end

unless User.where(:email => 'dungeon@system.com').exists?
  system = User.new({:email => "dungeon@system.com", :name => "System", password_digest: 'totally invalid', :is_admin => true, auth_token: SecureRandom.uuid})
  system.save!(validate: false)
end

Dir[Rails.root.join('db', 'seed_data', 'background_images', '*')].each do |file|
  name = File.basename file
  unless BackgroundImage.where(filename: name).exists?
    i = BackgroundImage.create!({filename: name, data: File.binread(file)})
    i.process!(true)
  end
end


text:
import { AzureSQLServer } from '@waldur/azure/common/types';
import { Tooltip } from '@waldur/core/Tooltip';
import { formatFilesize } from '@waldur/core/utils';
import { withTranslation } from '@waldur/i18n';
import { Field, ResourceSummaryProps } from '@waldur/resource/summary';
import { UserPassword } from '@waldur/resource/UserPassword';

import { PureAzureResourceSummary } from '../AzureResourceSummary';

const ValueWithTooltip = ({ value, tooltip }) => (
  <>
    <Tooltip id="compute-generation" label={tooltip}>
      <i className="fa fa-question-circle" />
    </Tooltip>{' '}
    {value}
  </>
);

const PureAzureSQLServerSummary = (
  props: ResourceSummaryProps<AzureSQLServer>,
) => {
  const { translate, resource } = props;
  return (
    <>
      <PureAzureResourceSummary {...props} />
      {resource.fqdn && (
        <Field label={translate('Connection details')}>
          {`psql --host=${resource.fqdn} --port=5432 --username=${resource.username}@${resource.name} --dbname=postgres`}
        </Field>
      )}
      <Field label={translate('Password')}>
        <UserPassword password={resource.password} />
      </Field>
      <Field label={translate('Pricing tier')}>
        <ValueWithTooltip
          value="Basic"
          tooltip="Workloads that require light compute and I/O performance. Examples include servers used for development or testing or small-scale infrequently used applications."
        />
      </Field>
      <Field label={translate('Compute generation')}>
        <ValueWithTooltip
          value="5 Gen"
          tooltip="CPUs are based on Intel E5-2673 v4 (Broadwell) 2.3-GHz processors."
        />
      </Field>
      <Field label={translate('Storage size')}>
        {formatFilesize(resource.storage_mb || 5120)}
      </Field>
      <Field label={translate('vCores')}>1</Field>
      <Field label={translate('Memory per vCore')}>2 GB</Field>
      <Field label={translate('Storage type')}>Azure Standard Storage</Field>
    </>
  );
};

export const AzureSQLServerSummary = withTranslation(PureAzureSQLServerSummary);


text:
import atexit
from time import sleep

from django.core.management import BaseCommand

from django_jsx.server.template_server import TemplateServer

class Command(BaseCommand):
    def __init__(self):
        super().__init__()

        self.server = TemplateServer()

    def handle(self, *args, **options):
        atexit.register(self.server.terminate)
        self.server.start()

        while True: sleep(1)


text:
package org.xwalk.embedded.api.asyncsample.basic;
import org.xwalk.embedded.api.asyncsample.R;

import android.app.Activity;
import org.xwalk.core.XWalkInitializer;
import org.xwalk.core.XWalkPreferences;
import org.xwalk.core.XWalkView;

import android.app.AlertDialog;
import android.os.Bundle;

public class XWalkViewWithSetZOrderOnTopAsync extends Activity implements XWalkInitializer.XWalkInitListener {
    private XWalkView mXWalkView;
    private XWalkInitializer mXWalkInitializer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mXWalkInitializer = new XWalkInitializer(this, this);
        mXWalkInitializer.initAsync();
    }

    @Override
    public final void onXWalkInitStarted() {
        // It's okay to do nothing
    }

    @Override
    public final void onXWalkInitCancelled() {
        // It's okay to do nothing
    }

    @Override
    public final void onXWalkInitFailed() {
        // Do crash or logging or anything else in order to let the tester know if this method get called
    }

    @Override
    public final void onXWalkInitCompleted() {

        setContentView(R.layout.xwview_transparent_layout);
        StringBuffer mess = new StringBuffer();
        mess.append("Test Purpose: \n\n")
        .append("Check XWalkView's transparent feature whether display the view under the webview.\n\n")
        .append("Expected Result:\n\n")
        .append("Test passes if you can see button view & blue imageview");
        new  AlertDialog.Builder(this)
        .setTitle("Info" )
        .setMessage(mess.toString())
        .setPositiveButton("confirm" ,  null )
        .show();
        mXWalkView = (XWalkView) findViewById(R.id.xwalkview_transparent);
        mXWalkView.setZOrderOnTop(true);
        mXWalkView.setBackgroundColor(0);
        mXWalkView.load("http://www.baidu.com/", null);
    }

}


text:
// Copyright (c) 2008-2022, Hazelcast, Inc. All Rights Reserved.
//
// 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.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Hazelcast.Testing;
using NUnit.Framework;

namespace Hazelcast.Tests.Networking
{
    [TestFixture]
    public class ReproduceDotNetIssues : HazelcastTestBase
    {
        // these tests reproduce issue https://github.com/dotnet/runtime/issues/61411
        //
        // this issue breaks the APM (Asynchronous Programming Model, based upon Begin+End and callbacks) in
        // .NET 6 - prior to .NET 6 they were implementing TAP (Task-based Asynchronous Pattern, based on
        // async calls)on top of APM and in .NET 6 they now switched to implementing APM on top of TAP, as
        // async becomes the recommended approach - but with some issues - essentially leaving an underlying
        // task hidden and non-awaited/awaitable - which means its exceptions are bubbled as unobserved - and
        // this is bad for the health of the overall process.
        //
        // for this reason we cannot continue using APM (which we used for historical reasons) with .NET 6
        // and have to switch to TAP (which is OK for all .NET versions) -> SocketExtensions is updated to
        // use TAP for all .NET versions.

        [Test]
        [Timeout(20_000)]
        public async Task ReproduceIssue61411()
        {
            var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
            var socket = new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(endpoint);
            socket.Listen(10);
            var okToDispose = new TaskCompletionSource<object>();
            var calledBack = false;
            var caughtObjectDisposedException = false;
            var caughtOtherException = false;
            socket.BeginAccept(asyncResult =>
            {
                try
                {
                    var s = (Socket)asyncResult.AsyncState;
                    var accepted = s.EndAccept(asyncResult);
                }
                catch (ObjectDisposedException)
                {
                    Console.WriteLine("caught ObjectDisposedException");
                    caughtObjectDisposedException = true;

                    // this (reflection) would be the only way in .NET 6 to observe the exception
                    /*
                    try
                    {
                        var taskField = asyncResult.GetType().GetField("_task", BindingFlags.NonPublic | BindingFlags.Instance);
                        var task = (Task<Socket>)taskField.GetValue(asyncResult);
                        task.GetAwaiter().GetResult();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("caught! " + e);
                        caughtAsyncResultException = true;
                    }
                    */
                }
                catch (Exception e)
                {
                    Console.WriteLine("caught " + e);
                    caughtOtherException = true;
                }
                calledBack = true;
                okToDispose.TrySetResult(null);
            }, socket);

            await Task.Delay(1000);

            // invalid - SocketException: cannot shutdown a socket that was not connected
            //socket.Shutdown(SocketShutdown.Both);

            // useless - Close does Dispose immediately
            //socket.Close();

            //await okToDispose.Task; // if we dispose before the callback, EndAccept cannot run

            // callback hasn't run yet
            Assert.That(!calledBack);

            // dispose the socket
            socket.Dispose();

            // callback eventually runs
            await AssertEx.SucceedsEventually(() => Assert.That(calledBack), 2000, 100);

            // and here is the issue we are reproducing:
            Assert.That(caughtObjectDisposedException); // EndAccept throws because the socket has been disposed = expected
            Assert.That(!caughtOtherException); // and nothing else

            var e = GetUnobservedExceptions();

#if NET6_0_OR_GREATER
            // .NET 6 has 1 unobserved exception
            Assert.That(e.Count, Is.EqualTo(1));
            ClearUnobservedExceptions(); // don't fail the test
#else
            // anything before .NET 6 is safe
            Assert.That(e.Count, Is.Zero);
#endif
        }

        [Test]
        [Timeout(20_000)]
        public async Task AsyncHasNoIssue()
        {
            var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
            var socket = new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(endpoint);
            socket.Listen(10);

            var e = new SocketAsyncEventArgs
            {
                UserToken = null // could be used to pass a user state
            };
            e.Completed += (sender, args) =>
            {
                var socket2 = args.AcceptSocket; // the new socket for the accepted connection
            };
            var pending = socket.AcceptAsync(e);
            Assert.That(pending, Is.True);

            await Task.Delay(1000);

            // here, we can dispose the socket and everything will go down without leaving an unobserved
            // exception (this test class inherits from HazelcastTestBase which detects unobserved exceptions
            // on teardown).
            socket.Dispose();
        }
    }
}


text:
package org.apache.cassandra.cql3.statements;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.cassandra.auth.Permission;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.cql3.*;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.transport.messages.ResultMessage;

import static org.apache.cassandra.thrift.ThriftValidation.validateColumnFamily;

public class AlterTableStatement extends SchemaAlteringStatement
{
    public static enum Type
    {
        ADD, ALTER, DROP, OPTS, RENAME
    }

    public final Type oType;
    public final CQL3Type.Raw validator;
    public final ColumnIdentifier columnName;
    private final CFPropDefs cfProps;
    private final Map<ColumnIdentifier, ColumnIdentifier> renames;
    private final boolean isStatic; // Only for ALTER ADD

    public AlterTableStatement(CFName name,
                               Type type,
                               ColumnIdentifier columnName,
                               CQL3Type.Raw validator,
                               CFPropDefs cfProps,
                               Map<ColumnIdentifier, ColumnIdentifier> renames,
                               boolean isStatic)
    {
        super(name);
        this.oType = type;
        this.columnName = columnName;
        this.validator = validator; // used only for ADD/ALTER commands
        this.cfProps = cfProps;
        this.renames = renames;
        this.isStatic = isStatic;
    }

    public void checkAccess(ClientState state) throws UnauthorizedException, InvalidRequestException
    {
        state.hasColumnFamilyAccess(keyspace(), columnFamily(), Permission.ALTER);
    }

    public void validate(ClientState state)
    {
        // validated in announceMigration()
    }

    public void announceMigration() throws RequestValidationException
    {
        CFMetaData meta = validateColumnFamily(keyspace(), columnFamily());
        CFMetaData cfm = meta.copy();

        CQL3Type validator = this.validator == null ? null : this.validator.prepare(keyspace());

        ColumnDefinition def = columnName == null ? null : cfm.getColumnDefinition(columnName);
        switch (oType)
        {
            case ADD:
                if (cfm.comparator.isDense())
                    throw new InvalidRequestException("Cannot add new column to a COMPACT STORAGE table");
                if (isStatic && !cfm.comparator.isCompound())
                    throw new InvalidRequestException("Static columns are not allowed in COMPACT STORAGE tables");
                if (def != null)
                {
                    switch (def.kind)
                    {
                        case PARTITION_KEY:
                        case CLUSTERING_COLUMN:
                            throw new InvalidRequestException(String.format("Invalid column name %s because it conflicts with a PRIMARY KEY part", columnName));
                        default:
                            throw new InvalidRequestException(String.format("Invalid column name %s because it conflicts with an existing column", columnName));
                    }
                }

                AbstractType<?> type = validator.getType();
                if (type instanceof CollectionType)
                {
                    if (!cfm.comparator.supportCollections())
                        throw new InvalidRequestException("Cannot use collection types with non-composite PRIMARY KEY");
                    if (cfm.isSuper())
                        throw new InvalidRequestException("Cannot use collection types with Super column family");

                    cfm.comparator = cfm.comparator.addOrUpdateCollection(columnName, (CollectionType)type);
                }

                Integer componentIndex = cfm.comparator.isCompound() ? cfm.comparator.clusteringPrefixSize() : null;
                cfm.addColumnDefinition(isStatic
                                        ? ColumnDefinition.staticDef(cfm, columnName.bytes, type, componentIndex)
                                        : ColumnDefinition.regularDef(cfm, columnName.bytes, type, componentIndex));
                break;

            case ALTER:
                if (def == null)
                    throw new InvalidRequestException(String.format("Cell %s was not found in table %s", columnName, columnFamily()));

                switch (def.kind)
                {
                    case PARTITION_KEY:
                        AbstractType<?> newType = validator.getType();
                        if (newType instanceof CounterColumnType)
                            throw new InvalidRequestException(String.format("counter type is not supported for PRIMARY KEY part %s", columnName));
                        if (cfm.getKeyValidator() instanceof CompositeType)
                        {
                            List<AbstractType<?>> oldTypes = ((CompositeType) cfm.getKeyValidator()).types;
                            if (!newType.isValueCompatibleWith(oldTypes.get(def.position())))
                                throw new ConfigurationException(String.format("Cannot change %s from type %s to type %s: types are incompatible.",
                                                                               columnName,
                                                                               oldTypes.get(def.position()).asCQL3Type(),
                                                                               validator));

                            List<AbstractType<?>> newTypes = new ArrayList<AbstractType<?>>(oldTypes);
                            newTypes.set(def.position(), newType);
                            cfm.keyValidator(CompositeType.getInstance(newTypes));
                        }
                        else
                        {
                            if (!newType.isValueCompatibleWith(cfm.getKeyValidator()))
                                throw new ConfigurationException(String.format("Cannot change %s from type %s to type %s: types are incompatible.",
                                                                               columnName,
                                                                               cfm.getKeyValidator().asCQL3Type(),
                                                                               validator));
                            cfm.keyValidator(newType);
                        }
                        break;
                    case CLUSTERING_COLUMN:
                        AbstractType<?> oldType = cfm.comparator.subtype(def.position());
                        // Note that CFMetaData.validateCompatibility already validate the change we're about to do. However, the error message it
                        // sends is a bit cryptic for a CQL3 user, so validating here for a sake of returning a better error message
                        // Do note that we need isCompatibleWith here, not just isValueCompatibleWith.
                        if (!validator.getType().isCompatibleWith(oldType))
                            throw new ConfigurationException(String.format("Cannot change %s from type %s to type %s: types are not order-compatible.",
                                                                           columnName,
                                                                           oldType.asCQL3Type(),
                                                                           validator));

                        cfm.comparator = cfm.comparator.setSubtype(def.position(), validator.getType());
                        break;
                    case COMPACT_VALUE:
                        // See below
                        if (!validator.getType().isValueCompatibleWith(cfm.getDefaultValidator()))
                            throw new ConfigurationException(String.format("Cannot change %s from type %s to type %s: types are incompatible.",
                                                                           columnName,
                                                                           cfm.getDefaultValidator().asCQL3Type(),
                                                                           validator));
                        cfm.defaultValidator(validator.getType());
                        break;
                    case REGULAR:
                    case STATIC:
                        // Thrift allows to change a column validator so CFMetaData.validateCompatibility will let it slide
                        // if we change to an incompatible type (contrarily to the comparator case). But we don't want to
                        // allow it for CQL3 (see #5882) so validating it explicitly here. We only care about value compatibility
                        // though since we won't compare values (except when there is an index, but that is validated by
                        // ColumnDefinition already).
                        if (!validator.getType().isValueCompatibleWith(def.type))
                            throw new ConfigurationException(String.format("Cannot change %s from type %s to type %s: types are incompatible.",
                                                                           columnName,
                                                                           def.type.asCQL3Type(),
                                                                           validator));

                        // For collections, if we alter the type, we need to update the comparator too since it includes
                        // the type too (note that isValueCompatibleWith above has validated that the need type don't really
                        // change the underlying sorting order, but we still don't want to have a discrepancy between the type
                        // in the comparator and the one in the ColumnDefinition as that would be dodgy).
                        if (validator.getType() instanceof CollectionType)
                            cfm.comparator = cfm.comparator.addOrUpdateCollection(def.name, (CollectionType)validator.getType());

                        break;
                }
                // In any case, we update the column definition
                cfm.addOrReplaceColumnDefinition(def.withNewType(validator.getType()));
                break;

            case DROP:
                if (!cfm.isCQL3Table())
                    throw new InvalidRequestException("Cannot drop columns from a non-CQL3 table");
                if (def == null)
                    throw new InvalidRequestException(String.format("Column %s was not found in table %s", columnName, columnFamily()));

                switch (def.kind)
                {
                    case PARTITION_KEY:
                    case CLUSTERING_COLUMN:
                        throw new InvalidRequestException(String.format("Cannot drop PRIMARY KEY part %s", columnName));
                    case REGULAR:
                    case STATIC:
                        ColumnDefinition toDelete = null;
                        for (ColumnDefinition columnDef : cfm.regularAndStaticColumns())
                        {
                            if (columnDef.name.equals(columnName))
                                toDelete = columnDef;
                        }
                        assert toDelete != null;
                        cfm.removeColumnDefinition(toDelete);
                        cfm.recordColumnDrop(toDelete);
                        break;
                }
                break;
            case OPTS:
                if (cfProps == null)
                    throw new InvalidRequestException(String.format("ALTER COLUMNFAMILY WITH invoked, but no parameters found"));

                cfProps.validate();
                cfProps.applyToCFMetadata(cfm);
                break;
            case RENAME:
                for (Map.Entry<ColumnIdentifier, ColumnIdentifier> entry : renames.entrySet())
                    cfm.renameColumn(entry.getKey(), entry.getValue());
                break;
        }

        MigrationManager.announceColumnFamilyUpdate(cfm, false);
    }

    public String toString()
    {
        return String.format("AlterTableStatement(name=%s, type=%s, column=%s, validator=%s)",
                             cfName,
                             oType,
                             columnName,
                             validator);
    }

    public ResultMessage.SchemaChange.Change changeType()
    {
        return ResultMessage.SchemaChange.Change.UPDATED;
    }
}


text:
const $util = require('./../helper/util'),
    axios = require('axios'),
    secretConf = require("./../config/secret"),
    sha1 = require('sha1')

const getAccessToken = () => {
    return new Promise((resolve, reject) => {
        const baseUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&'
        const appid = secretConf.appid
        const secret = secretConf.secret
        const requestUrl = baseUrl + `appid=${appid}&secret=${secret}`
        console.log('Current getAccessToken requestUrl is: ', requestUrl)
        return axios.get(requestUrl).then((result) => {
            resolve(result.data)
        }).catch(err => {
            console.log("Opps, Axios Error Occurred !" + err)
            resolve({})
        })
    })
}

const getWechatTicket = (params) => {
    return new Promise((resolve, reject) => {
        const baseUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?&type=jsapi'
        const requestUrl = baseUrl + `&access_token=${params.access_token}`
        console.log('Current requestUrl is: ', requestUrl)
        return axios.get(requestUrl).then((res) => {
            resolve(res.data)
        }).catch(err => {
            console.log("Opps, Axios Error Occurred !" + err)
            resolve({})
        })
    })
}

exports.getWechatApiSignature = async(ctx, next) => {
    const url = ctx.request.query.url
    const requestParam = await getAccessToken()
    const result = await getWechatTicket(requestParam)
    const noncestr = $util.generateRandomStr(16)
    const timestamp = (new Date()).getTime()
    const signatureFields = [
        `jsapi_ticket=${result.ticket}`,
        `noncestr=${noncestr}`,
        `timestamp=${timestamp}`,
        `url=${url}`
    ]
    const signatureStr = signatureFields.join('&')
    console.log('💯 Current SignatureStr Is: ', signatureStr)
    const signature = sha1(signatureStr)

    return  $util.sendSuccess(ctx, {
        appId: secretConf.appid,
        timestamp: timestamp,
        nonceStr: noncestr,
        signature: signature
    })
}

exports.crawlLinksInfo = async(ctx, next) => {
    let options = ctx.request.query
    try {
      return await $util.getWebPageInfo(options.url).then(result => {
        $util.sendSuccess(ctx, result)
      })
    } catch (error) {
        ctx.status = 500
        ctx.body = 'Opps, Something Error :' + error
    }
}


text:
// <copyright file="StringExtensionsTest.cs" company="Logikfabrik">
//   Copyright (c) 2016 anton(at)logikfabrik.se. Licensed under the MIT license.
// </copyright>

namespace Logikfabrik.Umbraco.Jet.Test.Extensions
{
    using Jet.Extensions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class StringExtensionsTest : TestBase
    {
        [TestMethod]
        public void CanGetAliasFor1LetterLowercaseWord()
        {
            Assert.AreEqual("u", "u".Alias());
        }

        [TestMethod]
        public void CanGetAliasFor1LetterUppercaseWord()
        {
            Assert.AreEqual("u", "U".Alias());
        }

        [TestMethod]
        public void CanGetAliasForWordWithValidCharacters()
        {
            Assert.AreEqual("abc123", "abc123".Alias());
        }

        [TestMethod]
        public void CanGetAliasForWordWithInvalidCharacters()
        {
            Assert.AreEqual("abc", "abc;:_".Alias());
        }

        [TestMethod]
        public void CanGetAliasForNullWord()
        {
            Assert.IsNull(((string)null).Alias());
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockTraderRI.Modules.Watch.Services;
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;
using System.ComponentModel.Composition;

namespace StockTraderRI.Modules.Watch.AddWatch
{
    [Export(typeof(AddWatchViewModel))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class AddWatchViewModel : BindableBase
    {
        private string stockSymbol;
        private IWatchListService watchListService;

        [ImportingConstructor]
        public AddWatchViewModel(IWatchListService watchListService)
        {
            if (watchListService == null)
            {
                throw new ArgumentNullException("watchListService");
            }

            this.watchListService = watchListService;
        }

        public string StockSymbol
        {
            get { return stockSymbol; }
            set
            {
                SetProperty(ref stockSymbol, value);
            }
        }

        public ICommand AddWatchCommand { get { return this.watchListService.AddWatchCommand; } }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace ODataValidator.Rule
{
    #region Namespaces
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using Newtonsoft.Json.Linq;
    using ODataValidator.Rule.Helper;
    using ODataValidator.RuleEngine;
    using ODataValidator.RuleEngine.Common;
    #endregion

    /// <summary>
    /// Extension rule to verify v3 and v4 Json light individual property:
    /// A property that is of complex type are represented as a complex value.
    /// </summary>
    [Export(typeof(ExtensionRule))]
    public class IndividualPropertyCore4204 : ExtensionRule
    {
        /// <summary>
        /// Gets Category property
        /// </summary>
        public override string Category
        {
            get
            {
                return "core";
            }
        }

        /// <summary>
        /// Gets rule name
        /// </summary>
        public override string Name
        {
            get
            {
                return "IndividualProperty.Core.4204";
            }
        }

        /// <summary>
        /// Gets rule description
        /// </summary>
        public override string Description
        {
            get
            {
                return @"In individual property, a property that is of complex type are represented as a complex value.";
            }
        }

        /// <summary>
        /// Gets rule specification in OData document
        /// </summary>
        public override string V4SpecificationSection
        {
            get
            {
                return "11";
            }
        }

        /// <summary>
        /// Gets the version.
        /// </summary>
        public override ODataVersion? Version
        {
            get
            {
                return ODataVersion.V3_V4;
            }
        }

        /// <summary>
        /// Gets location of help information of the rule
        /// </summary>
        public override string HelpLink
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the error message for validation failure
        /// </summary>
        public override string ErrorMessage
        {
            get
            {
                return this.Description;
            }
        }

        /// <summary>
        /// Gets the requirement level.
        /// </summary>
        public override RequirementLevel RequirementLevel
        {
            get
            {
                return RequirementLevel.Must;
            }
        }

        /// <summary>
        /// Gets the payload type to which the rule applies.
        /// </summary>
        public override PayloadType? PayloadType
        {
            get
            {
                return RuleEngine.PayloadType.IndividualProperty;
            }
        }

        /// <summary>
        /// Gets the payload format to which the rule applies.
        /// </summary>
        public override PayloadFormat? PayloadFormat
        {
            get
            {
                return RuleEngine.PayloadFormat.JsonLight;
            }
        }

        /// <summary>
        /// Gets the RequireMetadata property to which the rule applies.
        /// </summary>
        public override bool? RequireMetadata
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets the IsOfflineContext property to which the rule applies.
        /// </summary>
        public override bool? IsOfflineContext
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;
            string propertyType = string.Empty;
            string formatLiteral = string.Empty;
            List<string> complexTypeValues = new List<string>();

            JObject jo;
            context.ResponsePayload.TryToJObject(out jo);
            string contextUrl = string.Empty;

            if (jo[Constants.OdataV4JsonIdentity] == null)
            {
                passed = false;
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);

                return passed;
            }
            else
            {
                // Use the XPath query language to access the metadata document and get all Namespace and alias values.
                string xpath = @"//*[local-name()='DataServices']/*[local-name()='Schema']";
                XElement metadata = XElement.Parse(context.MetadataDocument);
                var schemaElement = metadata.XPathSelectElement(xpath, ODataNamespaceManager.Instance);
                string nameSpace = schemaElement.GetAttributeValue("Namespace");
                string alias = schemaElement.GetAttributeValue("Alias");

                complexTypeValues = MetadataHelper.GetAllComplexNameFromMetadata(context.MetadataDocument);

                contextUrl = jo[Constants.OdataV4JsonIdentity].Value<string>().StripOffDoubleQuotes();
                string[] feedSegment = contextUrl.Remove(0, contextUrl.IndexOf(Constants.JsonFeedIdentity) + Constants.JsonFeedIdentity.Length).Split('/');
                string entitySetName = feedSegment[0].Split('(')[0];
                string entityTypeName = XmlHelper.GetEntityTypeShortName(entitySetName, context.MetadataDocument);
                var normalProperties = MetadataHelper.GetAllPropertiesOfEntity(context.MetadataDocument, entityTypeName, MatchPropertyType.Normal);

                Dictionary<string, string> propertyNameAndComplexTypeName = new Dictionary<string, string>();

                foreach (XElement xe in normalProperties)
                {
                    if ((!string.IsNullOrEmpty(nameSpace) && xe.GetAttributeValue("Type").StartsWith(nameSpace))
                        || (!string.IsNullOrEmpty(alias) && xe.GetAttributeValue("Type").StartsWith(alias)))
                    {
                        string typeShortName = xe.GetAttributeValue("Type").Remove(0, xe.GetAttributeValue("Type").LastIndexOf('.') + 1);

                        if (complexTypeValues.Contains(typeShortName))
                        {
                            propertyNameAndComplexTypeName.Add(xe.GetAttributeValue("Name"), typeShortName);
                        }
                    }
                }

                 string propertyName = feedSegment[1];

                 if (propertyNameAndComplexTypeName.ContainsKey(propertyName))
                 {
                     List<string> propertiesOfComplexType = MetadataHelper.GetAllPropertiesNamesOfComplexType(context.MetadataDocument, propertyNameAndComplexTypeName[propertyName]);

                     foreach (JProperty jp in jo.Children())
                     {
                         if (!JsonSchemaHelper.IsAnnotation(jp.Name))
                         {
                             if (propertiesOfComplexType.Contains(jp.Name))
                             {
                                 passed = true;
                             }
                             else
                             {
                                 passed = false;
                                 info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                                 break;
                             }
                         }
                     }
                 }
            }

            return passed;
        }
    }
}


text:
/* eslint-disable no-undef */
(function (window) {
  const toggleGlueAvailable = () => {
    document.getElementById("glueImg").src = "/assets/connected.svg";
    document.getElementById("glueSpan").textContent = "Connected";
  };

  const logger = (function logger() {
    function log(type, options) {
      const message = typeof options === "string" ? options : options.message;
      const logTime =
        options != null && options.logTime === false ? false : true;

      const item = document.createElement("li");
      const itemDot = document.createElement("span");
      const div = document.createElement("div");

      div.classList = "align-items-center d-flex flex-grow-1";
      itemDot.style.width = "10px";
      itemDot.style.height = "10px";
      itemDot.style.minWidth = "10px";
      itemDot.style.minHeight = "10px";
      itemDot.classList = "bg-success d-inline-block mr-2 rounded-circle";
      itemDot.classList.add(`bg-${type}`);

      div.append(itemDot);
      div.append(message);

      item.classList =
        "d-flex justify-content-between align-items-center border-top py-1";

      item.append(div);

      if (logTime) {
        const timeSpan = document.createElement("span");
        timeSpan.textContent = `${formatTime(new Date())} `;
        timeSpan.classList = "badge badge-pill";
        item.append(timeSpan);
      }

      document.getElementById("logs-list").prepend(item);
    }

    return {
      info(options) {
        log("", options);
      },
      error(options) {
        log("danger", options);
      },
      clear() {
        const element = document.getElementById("logs-list");
        if (element) {
          element.innerHTML = "";
        }
      }
    };
  })();

  const setDocumentTitle = title => {
    document.title = title;
  };

  const displayAppName = text => {
    const el = document.getElementById("appNameHeading");
    if (el) {
      el.textContent = text;
    }
  };

  const formatTime = date => {
    if (date instanceof Date) {
      return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}.${date.getMilliseconds()}`;
    } else {
      return "";
    }
  };

  /*
    elementId - Default value "clearLogsBtn".
   */
  const clearLogsHandler = elementId => {
    elementId = typeof elementId === "string" ? elementId : "clearLogsBtn";
    const element = document.getElementById(elementId);
    if (element) {
      element.addEventListener("click", logger.clear);
    }
  };

  const renderChannels = async (
    channelNames,
    myChannel,
    onJoinClicked,
    onLeaveClicked
  ) => {
    if (myChannel) {
      try {
        const colorOfMyChannel = (await glue.channels.get(myChannel)).meta
          .color;
        document.body.style.background = colorOfMyChannel;
      } catch (error) {
        const message = `Failed to get the context of my channel "${myChannel}"!`
        console.error(message);
        logger.error(message);
      }
    } else {
      document.body.style.background = "#fff";
    }

    const channelsListElement = document.getElementById("channelsList");
    channelsListElement.innerHTML = "";

    channelNames.forEach(channelName => {
      const rowElement = document.createElement("div");
      rowElement.classList = "row mt-2";

      const channelNameElement = document.createElement("div");
      channelNameElement.classList = "align-self-center pl-3 w-25";
      channelNameElement.textContent = channelName;

      const joinLeaveButtonWrapperElement = document.createElement("div");
      joinLeaveButtonWrapperElement.classList = "d-flex pl-sm-2";

      if (channelName === myChannel) {
        const leaveButtonElement = document.createElement("button");
        leaveButtonElement.classList =
          "btn btn-primary btn-sm border border-dark text-nowrap w-40";
        leaveButtonElement.textContent = "Leave";
        leaveButtonElement.onclick = onLeaveClicked;
        joinLeaveButtonWrapperElement.appendChild(leaveButtonElement);
      } else {
        const joinButtonElement = document.createElement("button");
        joinButtonElement.classList = "btn btn-primary btn-sm border border-dark text-nowrap w-40";
        joinButtonElement.textContent = "Join";
        joinButtonElement.onclick = () => onJoinClicked(channelName);
        joinLeaveButtonWrapperElement.appendChild(joinButtonElement);
      }

      rowElement.appendChild(channelNameElement);
      rowElement.appendChild(joinLeaveButtonWrapperElement);

      channelsListElement.appendChild(rowElement);
    });
  };

  window.logger = logger;
  window.toggleGlueAvailable = toggleGlueAvailable;
  window.setDocumentTitle = setDocumentTitle;
  window.displayAppName = displayAppName;
  window.formatTime = formatTime;
  window.clearLogsHandler = clearLogsHandler;
  window.renderChannels = renderChannels;
})(window || {});


text:
class CreateDeferrals < ActiveRecord::Migration[5.1]
  def self.up
    create_table :deferrals do |t|
      t.date :approval_date
      t.string :obs
      t.references :enrollment
      t.references :deferral_type

      t.timestamps
    end
  end

  def self.down
    drop_table :deferrals
  end
end


text:
require 'rails_helper'

describe SuggestionsController do

  let(:user) { FactoryGirl.create(:user, email: Faker::Internet.email) }
  let(:suggestion) { FactoryGirl.create(:suggestion, user: user) }

  describe "GET #new" do

    it "renders the form for suggestions" do
      get :new

      expect(response).to render_template(:new)
    end
  end

  describe "POST #create" do

    context "with an authenticated user" do

      before(:each) do
        sign_in user
      end

      context "with a suggestion that can be saved" do
        it "creates a suggestion" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description"}

          expect(assigns(:suggestion).description).to eq "this is a suggestion description"
        end

        it "updates the suggestion flash message appropriately" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description"}

          expect(flash[:success]).to eq "You've successfully shared your suggestion. Click here to see all of your contributions."
        end

        it "redirects to the correct path for this suggestion" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description"}

          expect(response).to redirect_to("/")
        end
      end

      context "with a suggestion that cannot be saved" do

        it "renders the new page" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description", link: 'ftp://google.com'}

          expect(response).to render_template(:new)
        end
      end
    end

    context "with an unauthenticated user" do

      before(:each) do
        sign_out user
      end

      context "with a suggestion that can be saved" do

        it "caches the suggestion" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description"}

          expect(session[:object]).to_not be_nil
        end

        it "redirects to the correct path" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description"}

          expect(response).to redirect_to("/preview?class_name=suggestion")
        end
      end

      context "with an suggestion that cannot be saved" do
        it "renders the new page" do
          post :create, suggestion: {title: "this is a suggestion title", description: "this is a suggestion description", link: 'ftp://google.com'}

          expect(response).to render_template(:new)
        end
      end
    end
  end

  describe "PATCH #update" do

    before(:each) do
      sign_in user
    end

    context "when the update is successful" do

      it "updates the suggestion" do
        request.env['HTTP_REFERER'] = "http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags"
        patch :update, id: suggestion.id, suggestion: { description: "suggestion description update" }

        expect(assigns(:suggestion).description).to eq "suggestion description update"
      end

      it "updates the flash message" do
        request.env['HTTP_REFERER'] = "http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags"
        patch :update, id: suggestion.id, suggestion: {description: "suggestion description update"}

        expect(flash[:success]).to eq "You've successfully updated your suggestion. Click here to see all of your contributions."
      end

      it "redirects to the correct path after update" do
        request.env['HTTP_REFERER'] = '/'
        patch :update, id: suggestion.id, suggestion: { description: "suggestion description update" }

        expect(response).to redirect_to "/"
      end
    end

    context "when update is unsuccessful" do

      it "renders the edit page if the update was unsuccessful" do
        patch :update, id: suggestion.id, suggestion: { description: "suggestion description update", link: 'ftp://google.com' }

        expect(response).to render_template(:edit)
      end
    end
  end

  describe "DELETE #destroy" do

    let(:other_user) { FactoryGirl.create(:user, email: 'evil_user@malicious.com') }

    context "the suggestion user and logged in user are the same" do

      before(:each) do
        request.env['HTTP_REFERER'] = "http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags"
        sign_in user
      end

      it "soft deletes the suggestion" do
        delete :destroy, id: suggestion.id
        expect(assigns(:suggestion).destroyed_at).to_not be_nil
      end

      it 'does not *actually* destroy the entity' do
        delete :destroy, id: suggestion.id
        expect(assigns(:suggestion).destroyed?).to eq false
      end

      it "updates the flash message for delete" do
        delete :destroy, id: suggestion.id
        expect(flash[:success]).to eq "You've successfully deleted your suggestion. Click here to see all of your contributions."
      end

      it "redirects to the correct path for suggestions" do
        delete :destroy, id: suggestion.id
        expect(response).to redirect_to("/")
      end
    end

    context "if the suggestion user and the logged in user are NOT the same" do

      before(:each) do
        request.env['HTTP_REFERER'] = "http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags"
        sign_out user
        sign_in other_user
      end

      it "does not soft delete the suggestion that doesn't belong to the user" do
        delete :destroy, id: suggestion.id
        expect(assigns(:suggestion).destroyed_at).to be_nil
      end
    end
  end

  describe "PUT #like" do

    context "when the user is logged in" do

      before(:each) do
        sign_in user
      end

      it "updates the like status of the suggestion" do
        put :like, id: suggestion.id, vote_weight: 1

        expect(assigns(:suggestion).cached_votes_up).to eq 1
        expect(assigns(:suggestion).get_upvotes(vote_weight: 1, vote_scope: 'rating').length).to eq 1
      end

      it "renders the vote.js.erb file" do
        put :like, id: suggestion.id, format: :js

        expect(response).to render_template :like
      end

      it "redirects if not rendering JavaScript" do
        put :like, id: suggestion.id

        expect(response).to redirect_to("/")
      end
    end

    context "when the user is not logged in" do

      before(:each) do
        sign_out user
      end

      it "caches the like" do
        put :like, id: suggestion.id, vote_weight: 2

        expect(session[:like]).to_not be_nil
      end
    end
  end

  describe "PUT #unlike" do

    context "when the user is logged in" do

      before(:each) do
        sign_in user
        suggestion.liked_by(user, vote_scope: "rating", vote_weight: 3)
      end

      it "updates the like status of the suggestion" do
        put :unlike, id: suggestion.id, vote_weight: 3

        expect(assigns(:suggestion).cached_votes_up).to eq 0
        expect(assigns(:suggestion).get_upvotes(vote_scope: 'rating', vote_weight: 3).length).to eq 0
      end

      it "renders the unlike.js.erb file" do
        put :unlike, id: suggestion.id, format: :js

        expect(response).to render_template :unlike
      end

      it "redirects if not rendering JavaScript" do
        put :unlike, id: suggestion.id

        expect(response).to redirect_to("/")
      end

    end
  end

end