text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Azure.Devices.Api.Test
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Common;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;

    [TestClass]
    public class DeviceAuthenticationTests
    {
        const string IotHubName = "acme";

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        public async Task DeviceAuthenticationGoodAuthConfigTest1()
        {
            var deviceGoodAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = new X509Thumbprint()
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceGoodAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceGoodAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        public async Task DeviceAuthenticationGoodAuthConfigTest2()
        {
            var deviceGoodAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceGoodAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceGoodAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        public async Task DeviceAuthenticationGoodAuthConfigTest3()
        {
            var deviceGoodAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = null
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceGoodAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceGoodAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        public async Task DeviceAuthenticationGoodAuthConfigTest4()
        {
            var deviceGoodAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = null,
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceGoodAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceGoodAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        public async Task DeviceAuthenticationGoodAuthConfigTest5()
        {
            var deviceGoodAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = null
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceGoodAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceGoodAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        public async Task DeviceAuthenticationGoodAuthConfigTest6()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = "781BC9694ADEB8929D4F7FE4B9A3A6DE58B07952"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof (ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest1()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest2()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = null,
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest3()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = null
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest4()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = null
                    },
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest5()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = null,
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest6()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = null,
                        SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                    },
                    X509Thumbprint = null
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadAuthConfigTest7()
        {
            var deviceBadAuthConfig = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
                        SecondaryKey = null
                    },
                    X509Thumbprint = null
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadAuthConfig);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest1()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = null,
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B079"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest2()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F74B9A3A6DE58B0790B",
                        SecondaryThumbprint = null
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest3()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F74B9A3A",
                        SecondaryThumbprint = "8929D4F74B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest4()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F74B9A3A",
                        SecondaryThumbprint = null
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest5()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = null,
                        SecondaryThumbprint = "8929D4F74B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest6()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B",
                        SecondaryThumbprint = "8929D4F74B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [TestCategory("Auth")]
        [ExpectedException(typeof(ArgumentException))]
        public async Task DeviceAuthenticationBadThumbprintTest7()
        {
            var deviceBadThumbprint = new Device("123")
            {
                ConnectionState = DeviceConnectionState.Connected,
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = null,
                    X509Thumbprint = new X509Thumbprint()
                    {
                        PrimaryThumbprint = "921BC9694ADEB8929D4F74B9A3A",
                        SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B"
                    }
                }
            };

            var restOpMock = new Mock<IHttpClientHelper>();
            restOpMock.Setup(
                restOp =>
                    restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(),
                        It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(),
                        It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadThumbprint);
            var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName);
            await registryManager.AddDeviceAsync(deviceBadThumbprint);
        }
    }
}


text:
/* $Id: xpidf.h 3553 2011-05-05 06:14:19Z nanang $ */
/*
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef __PJSIP_SIMPLE_XPIDF_H__
#define __PJSIP_SIMPLE_XPIDF_H__

/**
 * @file xpidf.h
 * @brief XPIDF/Presence Information Data Format
 */
#include <VialerPJSIP/pjsip-simple/types.h>
#include <VialerPJSIP/pjlib-util/xml.h>

PJ_BEGIN_DECL

/**
 * @defgroup PJSIP_SIMPLE_XPIDF XPIDF/Presence Information Data Format
 * @ingroup PJSIP_SIMPLE
 * @brief Support for XPIDF/Presence Information Data Format
 * @{
 *
 * This is an old presence data format as described in:
 * draft-rosenberg-impp-pidf-00.txt.
 *
 * We won't support this format extensively here, as it seems there's not
 * too many implementations support this anymore, as it shouldn't.
 */

/** Type definitions for XPIDF root document. */
typedef pj_xml_node pjxpidf_pres;

/**
 * Create a new XPIDF document.
 *
 * @param pool	    Pool.
 * @param uri	    URI to set in the XPIDF document.
 *
 * @return	    XPIDF document.
 */
PJ_DECL(pjxpidf_pres*) pjxpidf_create(pj_pool_t *pool, const pj_str_t *uri);

/**
 * Parse XPIDF document.
 *
 * @param pool	    Pool.
 * @param text	    Input text.
 * @param len	    Length of input text.
 *
 * @return	    XPIDF document.
 */
PJ_DECL(pjxpidf_pres*) pjxpidf_parse(pj_pool_t *pool, char *text, pj_size_t len);

/**
 * Print XPIDF document.
 *
 * @param pres	    The XPIDF document to print.
 * @param text	    Buffer to place the output.
 * @param len	    Length of the buffer.
 *
 * @return	    The length printed.
 */
PJ_DECL(int) pjxpidf_print( pjxpidf_pres *pres, char *text, pj_size_t len);

/**
 * Get URI in the XPIDF document
 *
 * @param pres	    XPIDF document
 *
 * @return	    The URI, or an empty string.
 */
PJ_DECL(pj_str_t*) pjxpidf_get_uri(pjxpidf_pres *pres);

/**
 * Set the URI of the XPIDF document.
 *
 * @param pool	    Pool.
 * @param pres	    The XPIDF document.
 * @param uri	    URI to set in the XPIDF document.
 *
 * @return	    Zero on success.
 */
PJ_DECL(pj_status_t) pjxpidf_set_uri(pj_pool_t *pool, pjxpidf_pres *pres,
				     const pj_str_t *uri);

/**
 * Get presence status in the XPIDF document.
 *
 * @param pres	    XPIDF document.
 *
 * @return	    True to indicate the contact is online.
 */
PJ_DECL(pj_bool_t) pjxpidf_get_status(pjxpidf_pres *pres);

/**
 * Set presence status in the XPIDF document.
 *
 * @param pres	    XPIDF document.
 * @param status    Status to set, True for online, False for offline.
 *
 * @return	    Zero on success.
 */
PJ_DECL(pj_status_t) pjxpidf_set_status(pjxpidf_pres *pres, pj_bool_t status);

/**
 * @}
 */

PJ_END_DECL

#endif	/* __PJSIP_SIMPLE_XPIDF_H__ */

redpajama_set_name: RedPajamaGithub


text:
title: "Usage with a Pre-Built Distribution"
weight: 20

menu:
  main:
    identifier: "rest-api-overview-distro-use"
    parent: "rest-api-overview"

---

The REST API is included in Camunda's pre-built distributions.
It can be accessed via the context `/engine-rest` and uses the engines provided by the class `BpmPlatform`.

The default process engine is available out of the box by accessing `/engine-rest/engine/default/{rest-methods}`
or simply `/engine-rest/{rest-methods}`. Any other shared (i.e., it is globally visible) process engine that is created later is available through `/engine-rest/engine/{name}/{rest-methods}` without any further context.

Authentication is deactivated by default, but can be activated as described in the [Authentication]({{< relref "reference/rest/overview/authentication.md" >}}) section.


text:
from django.http import HttpResponseRedirect
from django.conf import settings
from django_openid.consumer import SessionConsumer
from django.contrib import messages

from bundestagger.account.auth import login, logout

class BundesOpenidConsumer(SessionConsumer):
    session_key = 'openid'
    openid_required_message = 'Gib eine OpenID ein'
    xri_disabled_message = 'i-names werden nicht unterstützt'
    openid_invalid_message = 'Die OpenID ist nicht gültig'
    request_cancelled_message = 'Die Anfrage wurde abgebrochen'
    message_loggedin = "Erfolgreich eingeloggt"
    message_loggedout = "Erfolgreich ausgeloggt"
    failure_message = 'Fehler: %s'
    setup_needed_message = 'Setup benötigt'
    sign_next_param = False
    salt_next = '07n98kpajapd290?(H"N=)(czar3)' # Adds extra saltiness to the ?next= salt
    xri_enabled = False
    on_complete_url = None
    trust_root = settings.SITE_DOMAIN # If None, full URL to endpoint is used
    logo_path = None # Path to the OpenID logo, as used by the login view

    def show_error(self, request, message, exception=None):
        messages.error(request, message)
        return HttpResponseRedirect("/")

    def show_message(self, request, title, message):
        messages.info(request, message)
        return HttpResponseRedirect("/")

    def on_success(self, request, identity_url, openid_response):
        messages.info(request, self.message_loggedin)
        login(request, identity_url)
        return super(BundesOpenidConsumer,self).on_success(request, identity_url, openid_response)

    def do_logout(self, request):
        logout(request)
        response =  super(BundesOpenidConsumer,self).do_logout(request)
        messages.info(request, self.message_loggedout)
        return response


text:
package com.github.benmanes.caffeine.cache.testing;

import static java.util.Objects.requireNonNull;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.util.concurrent.ForwardingExecutorService;
import com.google.common.util.concurrent.Uninterruptibles;

/**
 * An executor that retains metrics regarding the execution history.
 *
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class TrackingExecutor extends ForwardingExecutorService {
  private static final CountDownLatch ZERO = new CountDownLatch(0);

  private final ExecutorService delegate;
  private final AtomicInteger submitted;
  private final AtomicInteger completed;
  private final AtomicInteger failed;

  private volatile CountDownLatch latch;

  public TrackingExecutor(ExecutorService executor) {
    delegate = requireNonNull(executor);
    submitted = new AtomicInteger();
    completed = new AtomicInteger();
    failed = new AtomicInteger();
    latch = ZERO;
  }

  @Override
  public void execute(Runnable command) {
    try {
      submitted.incrementAndGet();
      delegate.execute(() -> {
        Uninterruptibles.awaitUninterruptibly(latch);
        try {
          command.run();
        } catch (Throwable t) {
          failed.incrementAndGet();
          throw t;
        } finally {
          completed.incrementAndGet();
        }
      });
    } catch (Throwable t) {
      completed.incrementAndGet();
      failed.incrementAndGet();
      throw t;
    }
  }

  public int submitted() {
    return submitted.get();
  }

  public int completed() {
    return completed.get();
  }

  public int failed() {
    return failed.get();
  }

  public void pause() {
    latch = new CountDownLatch(1);
  }

  public void resume() {
    latch.countDown();
  }

  @Override
  public ExecutorService delegate() {
    return delegate;
  }
}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Get modular with Python functions)
[#]: via: (https://opensource.com/article/19/7/get-modular-python-functions)
[#]: author: (Seth Kenlon https://opensource.com/users/seth/users/xd-deng/users/nhuntwalker/users/don-watkins)

Get modular with Python functions
======
Minimize your coding workload by using Python functions for repeating
tasks.
![OpenStack source code \(Python\) in VIM][1]

Are you confused by fancy programming terms like functions, classes, methods, libraries, and modules? Do you struggle with the scope of variables? Whether you're a self-taught programmer or a formally trained code monkey, the modularity of code can be confusing. But classes and libraries encourage modular code, and modular code can mean building up a collection of multipurpose code blocks that you can use across many projects to reduce your coding workload. In other words, if you follow along with this article's study of [Python][2] functions, you'll find ways to work smarter, and working smarter means working less.

This article assumes enough Python familiarity to write and run a simple script. If you haven't used Python, read my [intro to Python][3] article first.

### Functions

Functions are an important step toward modularity because they are formalized methods of repetition. If there is a task that needs to be done again and again in your program, you can group the code into a function and call the function as often as you need it. This way, you only have to write the code once, but you can use it as often as you like.

Here is an example of a simple function:

```
#!/usr/bin/env python3

import time

def Timer():
        print("Time is " + str(time.time() ) )
```

Create a folder called **mymodularity** and save the function code as **timestamp.py**.

In addition to this function, create a file called **__init__.py** in the **mymodularity** directory. You can do this in a file manager or a Bash shell:

```
`$ touch mymodularity/__init__.py`
```

You have now created your own Python library (a "module," in Python lingo) in your Python package called **mymodularity**. It's not a very useful module, because all it does is import the **time** module and print a timestamp, but it's a start.

To use your function, treat it just like any other Python module. Here's a small application that tests the accuracy of Python's **sleep()** function, using your **mymodularity** package for support. Save this file as **sleeptest.py** _outside_ the **mymodularity** directory (if you put this _into_ **mymodularity**, then it becomes a module in your package, and you don't want that).

```
#!/usr/bin/env python3

import time
from mymodularity import timestamp

print("Testing Python sleep()...")

# modularity
timestamp.Timer()
time.sleep(3)
timestamp.Timer()
```

In this simple script, you are calling your **timestamp** module from your **mymodularity** package (twice). When you import a module from a package, the usual syntax is to import the module you want from the package and then use the _module name + a dot + the name of the function you want to call_ (e.g., **timestamp.Timer()**).

You're calling your **Timer()** function twice, so if your **timestamp** module were more complicated than this simple example, you'd be saving yourself quite a lot of repeated code.

Save the file and run it:

```
$ python3 ./sleeptest.py
Testing Python sleep()...
Time is 1560711266.1526039
Time is 1560711269.1557732
```

According to your test, the sleep function in Python is pretty accurate: after three seconds of sleep, the timestamp was successfully and correctly incremented by three, with a little variance in microseconds.

The structure of a Python library might seem confusing, but it's not magic. Python is _programmed_ to treat a folder full of Python code accompanied by an **__init__.py** file as a package, and it's programmed to look for available modules in its current directory _first_. This is why the statement **from mymodularity import timestamp** works: Python looks in the current directory for a folder called **mymodularity**, then looks for a **timestamp** file ending in **.py**.

What you have done in this example is functionally the same as this less modular version:

```
#!/usr/bin/env python3

import time
from mymodularity import timestamp

print("Testing Python sleep()...")

# no modularity
print("Time is " + str(time.time() ) )
time.sleep(3)
print("Time is " + str(time.time() ) )
```

For a simple example like this, there's not really a reason you wouldn't write your sleep test that way, but the best part about writing your own module is that your code is generic so you can reuse it for other projects.

You can make the code more generic by passing information into the function when you call it. For instance, suppose you want to use your module to test not the _computer's_ sleep function, but a _user's_ sleep function. Change your **timestamp** code so it accepts an incoming variable called **msg**, which will be a string of text controlling how the **timestamp** is presented each time it is called:

```
#!/usr/bin/env python3

import time

# updated code
def Timer(msg):
    print(str(msg) + str(time.time() ) )
```

Now your function is more abstract than before. It still prints a timestamp, but what it prints for the user is undefined. That means you need to define it when calling the function.

The **msg** parameter your **Timer** function accepts is arbitrarily named. You could call the parameter **m** or **message** or **text** or anything that makes sense to you. The important thing is that when the **timestamp.Timer** function is called, it accepts some text as its input, places whatever it receives into a variable, and uses the variable to accomplish its task.

Here's a new application to test the user's ability to sense the passage of time correctly:

```
#!/usr/bin/env python3

from mymodularity import timestamp

print("Press the RETURN key. Count to 3, and press RETURN again.")

input()
timestamp.Timer("Started timer at ")

print("Count to 3...")

input()
timestamp.Timer("You slept until ")
```

Save your new application as **response.py** and run it:

```
$ python3 ./response.py
Press the RETURN key. Count to 3, and press RETURN again.

Started timer at 1560714482.3772075
Count to 3...

You slept until 1560714484.1628013
```

### Functions and required parameters

The new version of your timestamp module now _requires_ a **msg** parameter. That's significant because your first application is broken because it doesn't pass a string to the **timestamp.Timer** function:

```
$ python3 ./sleeptest.py
Testing Python sleep()...
Traceback (most recent call last):
  File "./sleeptest.py", line 8, in <module>
    timestamp.Timer()
TypeError: Timer() missing 1 required positional argument: 'msg'
```

Can you fix your **sleeptest.py** application so it runs correctly with the updated version of your module?

### Variables and functions

By design, functions limit the scope of variables. In other words, if a variable is created within a function, that variable is available to _only_ that function. If you try to use a variable that appears in a function outside the function, an error occurs.

Here's a modification of the **response.py** application, with an attempt to print the **msg** variable from the **timestamp.Timer()** function:

```
#!/usr/bin/env python3

from mymodularity import timestamp

print("Press the RETURN key. Count to 3, and press RETURN again.")

input()
timestamp.Timer("Started timer at ")

print("Count to 3...")

input()
timestamp.Timer("You slept for ")

print(msg)
```

Try running it to see the error:

```
$ python3 ./response.py
Press the RETURN key. Count to 3, and press RETURN again.

Started timer at 1560719527.7862902
Count to 3...

You slept for 1560719528.135406
Traceback (most recent call last):
  File "./response.py", line 15, in <module>
    print(msg)
NameError: name 'msg' is not defined
```

The application returns a **NameError** message because **msg** is not defined. This might seem confusing because you wrote code that defined **msg**, but you have greater insight into your code than Python does. Code that calls a function, whether the function appears within the same file or if it's packaged up as a module, doesn't know what happens inside the function. A function independently performs its calculations and returns what it has been programmed to return. Any variables involved are _local_ only: they exist only within the function and only as long as it takes the function to accomplish its purpose.

#### Return statements

If your application needs information contained only in a function, use a **return** statement to have the function provide meaningful data after it runs.

They say time is money, so modify your timestamp function to allow for an imaginary charging system:

```
#!/usr/bin/env python3

import time

def Timer(msg):
    print(str(msg) + str(time.time() ) )
    charge = .02
    return charge
```

The **timestamp** module now charges two cents for each call, but most importantly, it returns the amount charged each time it is called.

Here's a demonstration of how a return statement can be used:

```
#!/usr/bin/env python3

from mymodularity import timestamp

print("Press RETURN for the time (costs 2 cents).")
print("Press Q RETURN to quit.")

total = 0

while True:
    kbd = input()
    if kbd.lower() == "q":
        print("You owe $" + str(total) )
        exit()
    else:
        charge = timestamp.Timer("Time is ")
        total = total+charge
```

In this sample code, the variable **charge** is assigned as the endpoint for the **timestamp.Timer()** function, so it receives whatever the function returns. In this case, the function returns a number, so a new variable called **total** is used to keep track of how many changes have been made. When the application receives the signal to quit, it prints the total charges:

```
$ python3 ./charge.py
Press RETURN for the time (costs 2 cents).
Press Q RETURN to quit.

Time is 1560722430.345412

Time is 1560722430.933996

Time is 1560722434.6027434

Time is 1560722438.612629

Time is 1560722439.3649364
q
You owe $0.1
```

#### Inline functions

Functions don't have to be created in separate files. If you're just writing a short script specific to one task, it may make more sense to just write your functions in the same file. The only difference is that you don't have to import your own module, but otherwise the function works the same way. Here's the latest iteration of the time test application as one file:

```
#!/usr/bin/env python3

import time

total = 0

def Timer(msg):
    print(str(msg) + str(time.time() ) )
    charge = .02
    return charge

print("Press RETURN for the time (costs 2 cents).")
print("Press Q RETURN to quit.")

while True:
    kbd = input()
    if kbd.lower() == "q":
        print("You owe $" + str(total) )
        exit()
    else:
        charge = Timer("Time is ")
        total = total+charge
```

It has no external dependencies (the **time** module is included in the Python distribution), and produces the same results as the modular version. The advantage is that everything is located in one file, and the disadvantage is that you cannot use the **Timer()** function in some other script you are writing unless you copy and paste it manually.

#### Global variables

A variable created outside a function has nothing limiting its scope, so it is considered a _global_ variable.

An example of a global variable is the **total** variable in the **charge.py** example used to track current charges. The running total is created outside any function, so it is bound to the application rather than to a specific function.

A function within the application has access to your global variable, but to get the variable into your imported module, you must send it there the same way you send your **msg** variable.

Global variables are convenient because they seem to be available whenever and wherever you need them, but it can be difficult to keep track of their scope and to know which ones are still hanging around in system memory long after they're no longer needed (although Python generally has very good garbage collection).

Global variables are important, though, because not all variables can be local to a function or class. That's easy now that you know how to send variables to functions and get values back.

### Wrapping up functions

You've learned a lot about functions, so start putting them into your scripts—if not as separate modules, then as blocks of code you don't have to write multiple times within one script. In the next article in this series, I'll get into Python classes.

--------------------------------------------------------------------------------

via: https://opensource.com/article/19/7/get-modular-python-functions

作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/seth/users/xd-deng/users/nhuntwalker/users/don-watkins
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/openstack_python_vim_1.jpg?itok=lHQK5zpm (OpenStack source code (Python) in VIM)
[2]: https://www.python.org/
[3]: https://opensource.com/article/17/10/python-101


text:
package org.assertj.core.error;

import org.assertj.core.util.VisibleForTesting;

import java.io.File;
import java.nio.file.Path;

/**
 * Creates an error message indicating that an assertion that verifies that a {@link File} or {@link Path} does not
 * exist failed.
 *
 * @author Yvonne Wang
 * @author Francis Galiegue
 */
public class ShouldNotExist extends BasicErrorMessageFactory {

  @VisibleForTesting
  public static final String PATH_SHOULD_NOT_EXIST = "%nExpecting path:%n  <%s>%nnot to exist";
  @VisibleForTesting
  public static final String FILE_SHOULD_NOT_EXIST = "%nExpecting file:%n  <%s>%nnot to exist";
  @VisibleForTesting
  public static final String PATH_SHOULD_NOT_EXIST_NO_FOLLOW_LINKS = "%nExpecting path:%n  <%s>%nnot to exist (symbolic links were not followed).";

  /**
   * Creates a new <code>{@link ShouldNotExist}</code>.
   *
   * @param actual the actual value in the failed assertion.
   * @return the created {@code ErrorMessageFactory}.
   */
  public static ErrorMessageFactory shouldNotExist(File actual) {
	return new ShouldNotExist(actual);
  }

  public static ErrorMessageFactory shouldNotExist(final Path actual) {
	return new ShouldNotExist(actual);
  }

  public static ErrorMessageFactory shouldExistNoFollowLinks(final Path actual) {
	return new ShouldNotExist(actual);
  }

  private ShouldNotExist(File actual) {
	super(FILE_SHOULD_NOT_EXIST, actual);
  }

  private ShouldNotExist(final Path actual) {
	super(PATH_SHOULD_NOT_EXIST, actual);
  }

  private ShouldNotExist(final Path actual, boolean followLinks) {
	super(followLinks ? PATH_SHOULD_NOT_EXIST : PATH_SHOULD_NOT_EXIST_NO_FOLLOW_LINKS, actual);
  }
}


text:
package com.bv.eidss;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.bv.eidss.data.EidssDatabase;

public class RegionsProvider  extends ContentProvider{

    static final String PROVIDER_NAME = "com.bv.eidss.regionsprovider";
    static final String URL = "content://" + PROVIDER_NAME + "/regions";
    public static final Uri CONTENT_URI = Uri.parse(URL);
    public static final String NAME = "name";

    static final int REGIONS = 1;
    static final int REGION_ID = 2;

    static final UriMatcher uriMatcher;
    static{
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "regions", REGIONS);
        uriMatcher.addURI(PROVIDER_NAME, "regions/#", REGION_ID);
    }

        private SQLiteDatabase db;

        @Override
        public boolean onCreate() {
            /*EidssDatabase mDb = new EidssDatabase(getContext());
            db = mDb.getReadableDatabase();
            return (db == null)? false:true;*/
            return true;
        }

        @Override
        public Uri insert(Uri uri, ContentValues values) {
            throw new SQLException("Failed to add a record into " + uri);
        }

        @Override
        public Cursor query(Uri uri, String[] projection, String selection,
                            String[] selectionArgs, String sortOrder) {
            if (db == null) {
                EidssDatabase mDb = new EidssDatabase(getContext());
                db = mDb.getReadableDatabase();
            }
            switch (uriMatcher.match(uri)) {
                case REGIONS:
                    return db.rawQuery(EidssDatabase.select_sql_regions, selectionArgs);
                case REGION_ID:
                    return db.rawQuery(EidssDatabase.select_sql_region, selectionArgs);
                default:
                    throw new IllegalArgumentException("Wrong URI: " + uri);
            }
        }

        @Override
        public int delete(Uri uri, String selection, String[] selectionArgs) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        @Override
        public int update(Uri uri, ContentValues values, String selection,
                          String[] selectionArgs) {
            throw new IllegalArgumentException("Unknown URI " + uri );
        }

        @Override
        public String getType(Uri uri) {
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
}


text:
<?php

function get_user_signon()
{
    return null;
}


text:
using System;
namespace Pattern4.Proxy
{
    public class Program
    {
        public static void Main()
        {
            // Working with BankAccount class
            IBankAccount account = new BankAccount();
            Console.WriteLine(account.GetCurrentBalance()); //0
            account.Deposit(1234.67m);
            account.Withdraw(10000.00m);
            Console.WriteLine(account.GetCurrentBalance()); // -8765.33 => Unproper behavior

            //Working with BankAccountProxy class
            IBankAccount proxyAccount = new BankAccountProxy("Ivan Petrov", "very secret password");
            Console.WriteLine(proxyAccount.GetCurrentBalance()); //0

            proxyAccount.Deposit(5m); // Minimum deposite amount is 10 units
            proxyAccount.Deposit(10001m); //Maximum deposite amount is 10 000 units
            Console.WriteLine(proxyAccount.GetCurrentBalance()); // 0

            proxyAccount.Withdraw(100m); // The Ballance of your account is 0

            proxyAccount.Deposit(1234.56m);
            proxyAccount.Withdraw(1000.00m);
            Console.WriteLine(proxyAccount.GetCurrentBalance()); // 234.56

            proxyAccount.Withdraw(234.57m); // Your Balance is too low for this withdraw
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace EliteJournalReader.Events
{
    //When written: at startup, when loading from main menu
    //Parameters:
    //•	Inventory: array of cargo, with Name and Count for each
    public class CargoTransferEvent : JournalEvent<CargoEvent.CargoEventArgs>
    {
        public CargoTransferEvent() : base("CargoTransfer") { }

        public class CargoTransferEventArgs : JournalEventArgs
        {
            public CargoTransfer[] Transfers { get; set; }
        }
    }
}


text:
imdb-scraping-node
==================

Scrapes some of the imdb pages for a given imdb id.


text:
module.exports = {
  path: `${process.cwd()}/build`,
  publicPath: "/public",
};


text:
// Written by Gil Tene of Azul Systems, and released to the public domain,
// as explained at http://creativecommons.org/publicdomain/zero/1.0/
//
// Ported to .NET by Iulian Margarintescu under the same license and terms as the java version
// Java Version repo: https://github.com/HdrHistogram/HdrHistogram
// Latest ported version is available in the Java submodule in the root of the repo
using System;

namespace HdrHistogram
{
    /// <summary>
    /// Used for iterating through histogram values.
    /// </summary>
    internal abstract class AbstractHistogramIterator : Iterator<HistogramIterationValue>
    {
        protected AbstractHistogram histogram;
        protected long savedHistogramTotalRawCount;

        protected int currentIndex;
        protected long currentValueAtIndex;

        protected long nextValueAtIndex;

        long prevValueIteratedTo;
        long totalCountToPrevIndex;

        protected long totalCountToCurrentIndex;
        long totalValueToCurrentIndex;

        protected long arrayTotalCount;
        protected long countAtThisValue;

        private bool freshSubBucket;
        internal readonly HistogramIterationValue currentIterationValue = new HistogramIterationValue();

        private double integerToDoubleValueConversionRatio;

        protected void resetIterator(AbstractHistogram histogram)
        {
            this.histogram = histogram;
            this.savedHistogramTotalRawCount = histogram.getTotalCount();
            this.arrayTotalCount = histogram.getTotalCount();
            this.integerToDoubleValueConversionRatio = histogram.integerToDoubleValueConversionRatio;
            this.currentIndex = 0;
            this.currentValueAtIndex = 0;
            this.nextValueAtIndex = 1 << histogram.unitMagnitude;
            this.prevValueIteratedTo = 0;
            this.totalCountToPrevIndex = 0;
            this.totalCountToCurrentIndex = 0;
            this.totalValueToCurrentIndex = 0;
            this.countAtThisValue = 0;
            this.freshSubBucket = true;
            currentIterationValue.reset();
        }

        /**
         * Returns true if the iteration has more elements. (In other words, returns true if next would return an
         * element rather than throwing an exception.)
         *
         * @return true if the iterator has more elements.
         */

        public override bool hasNext()
        {
            if (histogram.getTotalCount() != savedHistogramTotalRawCount)
            {
                throw new InvalidOperationException("ConcurrentModificationException");
            }
            return (totalCountToCurrentIndex < arrayTotalCount);
        }

        /**
         * Returns the next element in the iteration.
         *
         * @return the {@link HistogramIterationValue} associated with the next element in the iteration.
         */

        public override HistogramIterationValue next()
        {
            // Move through the sub buckets and buckets until we hit the next reporting level:
            while (!exhaustedSubBuckets())
            {
                countAtThisValue = histogram.getCountAtIndex(currentIndex);
                if (freshSubBucket)
                { // Don't add unless we've incremented since last bucket...
                    totalCountToCurrentIndex += countAtThisValue;
                    totalValueToCurrentIndex += countAtThisValue * histogram.highestEquivalentValue(currentValueAtIndex);
                    freshSubBucket = false;
                }
                if (reachedIterationLevel())
                {
                    long valueIteratedTo = getValueIteratedTo();
                    currentIterationValue.set(valueIteratedTo, prevValueIteratedTo, countAtThisValue,
                            (totalCountToCurrentIndex - totalCountToPrevIndex), totalCountToCurrentIndex,
                            totalValueToCurrentIndex, ((100.0 * totalCountToCurrentIndex) / arrayTotalCount),
                            getPercentileIteratedTo(), integerToDoubleValueConversionRatio);
                    prevValueIteratedTo = valueIteratedTo;
                    totalCountToPrevIndex = totalCountToCurrentIndex;
                    // move the next iteration level forward:
                    incrementIterationLevel();
                    if (histogram.getTotalCount() != savedHistogramTotalRawCount)
                    {
                        throw new InvalidOperationException("ConcurrentModificationException");
                    }
                    return currentIterationValue;
                }
                incrementSubBucket();
            }
            // Should not reach here. But possible for overflowed histograms under certain conditions
            throw new IndexOutOfRangeException();
        }

        protected abstract void incrementIterationLevel();

        protected abstract bool reachedIterationLevel();

        double getPercentileIteratedTo()
        {
            return (100.0 * this.totalCountToCurrentIndex) / arrayTotalCount;
        }

        long getValueIteratedTo()
        {
            return histogram.highestEquivalentValue(currentValueAtIndex);
        }

        private bool exhaustedSubBuckets()
        {
            return (currentIndex >= histogram.countsArrayLength);
        }

        void incrementSubBucket()
        {
            freshSubBucket = true;
            // Take on the next index:
            currentIndex++;
            currentValueAtIndex = histogram.ValueFromIndex(currentIndex);
            // Figure out the value at the next index (used by some iterators):
            nextValueAtIndex = histogram.ValueFromIndex(currentIndex + 1);
        }

    }

}


text:
rm -rf wc_output
mkdir wc_output

PYTHONPATH=src python -m main


text:
"""Unit test module for Encounter API and model"""

import json
import os
import time

import dateutil
from flask_webtest import SessionScope

from portal.extensions import db
from portal.models.encounter import Encounter
from portal.models.organization import Organization
from portal.models.role import ROLE
from portal.models.user import INVITE_PREFIX
from tests import TEST_USER_ID, TestCase

class TestEncounter(TestCase):

    def test_encounter_from_fhir(self):
        with open(os.path.join(os.path.dirname(__file__),
                               'encounter-example.json'), 'r') as fhir_data:
            data = json.load(fhir_data)

        enc = Encounter.from_fhir(data)
        assert enc.status == 'finished'
        assert enc.auth_method == 'password_authenticated'
        assert enc.start_time == dateutil.parser.parse("2013-05-05")

    def test_encounter_as_fhir(self):
        enc = Encounter(status='planned', auth_method='url_authenticated',
                        user_id=TEST_USER_ID,
                        start_time=dateutil.parser.parse("2013-07-07"))
        data = enc.as_fhir()
        # confirm we can store
        with SessionScope(db):
            db.session.add(enc)
            db.session.commit()
        enc = db.session.merge(enc)
        assert enc.status == data['status']
        assert enc.auth_method == data['auth_method']

    def test_encounter_on_login(self):
        self.login()
        assert len(self.test_user.encounters) == 1
        assert (self.test_user.current_encounter().auth_method
                == 'password_authenticated')

    def test_encounter_after_logout(self):
        self.login()
        time.sleep(0.1)
        self.login()  # generate a second encounter - should reuse the first
        self.client.get('/logout', follow_redirects=True)
        assert len(self.test_user.encounters) == 1
        assert all(e.status == 'finished' for e in self.test_user.encounters)
        # as we generate failsafe on missing, confirm that's the type returned
        assert self.test_user.current_encounter().auth_method == 'failsafe'

    def test_service_encounter_on_login(self):
        service_user = self.add_service_user()
        self.login(user_id=service_user.id)
        assert (service_user.current_encounter().auth_method
                == 'service_token_authenticated')

    def test_login_as(self):
        self.bless_with_basics()
        self.promote_user(role_name=ROLE.WRITE_ONLY.value)
        self.test_user = db.session.merge(self.test_user)
        consented_org = self.test_user.valid_consents[0].organization_id
        staff_user = self.add_user(username='staff@example.com')
        staff_user.organizations.append(Organization.query.get(consented_org))
        self.promote_user(user=staff_user, role_name=ROLE.STAFF.value)
        staff_user = db.session.merge(staff_user)
        self.login(user_id=staff_user.id)
        assert staff_user.current_encounter(generate_failsafe_if_missing=False)

        # Switch to test_user using login_as, test the encounter
        self.test_user = db.session.merge(self.test_user)
        response = self.client.get('/login-as/{}'.format(TEST_USER_ID))
        assert response.status_code == 302  # sent to next_after_login
        assert (self.test_user.current_encounter().auth_method
                == 'staff_authenticated')
        assert self.test_user._email.startswith(INVITE_PREFIX)

    def test_login_as_bogus(self):
        self.bless_with_basics(make_patient=False)
        self.promote_user(role_name=ROLE.STAFF.value)
        self.test_user = db.session.merge(self.test_user)
        consented_org = self.test_user.valid_consents[0].organization_id
        staff_user = self.add_user(username='staff@example.com')
        staff_user.organizations.append(Organization.query.get(consented_org))
        self.promote_user(user=staff_user, role_name=ROLE.ADMIN.value)
        self.promote_user(user=staff_user, role_name=ROLE.STAFF.value)
        staff_user = db.session.merge(staff_user)
        self.login(user_id=staff_user.id)
        assert staff_user.current_encounter(generate_failsafe_if_missing=False)

        # Switch to test_user using login_as, test the encounter
        self.test_user = db.session.merge(self.test_user)
        response = self.client.get('/login-as/{}'.format(TEST_USER_ID))
        # should return 401 as test user isn't a patient or partner
        assert response.status_code == 401
        assert self.test_user.current_encounter().auth_method == 'failsafe'
        assert staff_user.current_encounter(generate_failsafe_if_missing=False)

    def test_failsafe(self):
        self.bless_with_basics()
        self.promote_user(role_name=ROLE.WRITE_ONLY.value)
        self.test_user = db.session.merge(self.test_user)
        consented_org = self.test_user.valid_consents[0].organization_id
        staff_user = self.add_user(username='staff@example.com')
        staff_user.organizations.append(Organization.query.get(consented_org))
        self.promote_user(user=staff_user, role_name=ROLE.STAFF.value)
        staff_user = db.session.merge(staff_user)
        self.login(user_id=staff_user.id)
        assert staff_user.current_encounter(generate_failsafe_if_missing=False)

        # Switch to test_user using login_as, test the encounter
        self.test_user = db.session.merge(self.test_user)
        response = self.client.get('/login-as/{}'.format(TEST_USER_ID))
        assert response.status_code == 302  # sent to next_after_login
        assert (self.test_user.current_encounter().auth_method
                == 'staff_authenticated')
        assert self.test_user._email.startswith(INVITE_PREFIX)

        # Blow away test user's current encounter, and confirm a failsafe
        # comes to life
        e = Encounter.query.filter(Encounter.user_id == TEST_USER_ID).one()
        db.session.delete(e)

        self.test_user = db.session.merge(self.test_user)
        encounter = self.test_user.current_encounter()
        assert encounter.auth_method == 'failsafe'
        assert encounter.status == 'in-progress'


text:
layout: post
title: "New camera"
author: mark_kim
modified:
date:   2015-09-27 15:30
tags: []
---

New nonlinear zoom for the camera. Woot.


text:
cadnano\.strandset\.removestrandcmd module
==========================================

.. automodule:: cadnano.strandset.removestrandcmd
    :members:
    :undoc-members:
    :show-inheritance:


text:
// Package k8sdeps provides kustomize factory with k8s dependencies
package k8sdeps

import (
	"sigs.k8s.io/kustomize/k8sdeps/kunstruct"
	"sigs.k8s.io/kustomize/k8sdeps/transformer"
	"sigs.k8s.io/kustomize/k8sdeps/validator"
	"sigs.k8s.io/kustomize/pkg/factory"
)

// NewFactory creates an instance of KustFactory using k8sdeps factories
func NewFactory() *factory.KustFactory {
	return factory.NewKustFactory(
		kunstruct.NewKunstructuredFactoryImpl(),
		validator.NewKustValidator(),
		transformer.NewFactoryImpl(),
	)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright (C) 2006-2020 the original author or authors.

    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

        https://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.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>spotbugs-maven-plugin.it</groupId>
    <artifactId>common</artifactId>
    <version>testing</version>
    <relativePath>../common.xml</relativePath>
  </parent>
  <artifactId>threshold-experimental</artifactId>
  <name>threshold-experimental</name>
  <packaging>jar</packaging>
  <reporting>
    <excludeDefaults>true</excludeDefaults>
    <plugins>
      <plugin>
        <groupId>com.github.spotbugs</groupId>
        <artifactId>spotbugs-maven-plugin</artifactId>
        <configuration>
          <threshold>Exp</threshold>
          <spotbugsXmlOutput>true</spotbugsXmlOutput>
          <xmlOutput>true</xmlOutput>
          <relaxed>true</relaxed>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>


text:
// <copyright file="Versicherungsart.cs" company="DATALINE GmbH & Co. KG">
// Copyright (c) DATALINE GmbH & Co. KG. All rights reserved.
// </copyright>

namespace SocialInsurance.Germany.Messages.Pocos.AAG
{
    /// <summary>
    /// Art der Versicherung
    /// </summary>
    public enum Versicherungsart
    {
        /// <summary>
        /// In der GKV versichert
        /// </summary>
        GKV = 0,

        /// <summary>
        /// Privat versichert
        /// </summary>
        Privat,

        /// <summary>
        /// LKK-versichert
        /// </summary>
        LKK,

        /// <summary>
        /// Geringfügige Beschaeftigung
        /// </summary>
        GeringfuegigeBeschaeftigung,
    }
}


text:
import app from '../../forum/app';
import Modal from '../../common/components/Modal';
import Button from '../../common/components/Button';

/**
 * The `ChangePasswordModal` component shows a modal dialog which allows the
 * user to send themself a password reset email.
 */
export default class ChangePasswordModal extends Modal {
  className() {
    return 'ChangePasswordModal Modal--small';
  }

  title() {
    return app.translator.trans('core.forum.change_password.title');
  }

  content() {
    return (

{app.translator.trans('core.forum.change_password.text')}

            {Button.component(
              {
                className: 'Button Button--primary Button--block',
                type: 'submit',
                loading: this.loading,
              },
              app.translator.trans('core.forum.change_password.send_button')
            )}

    );
  }

  onsubmit(e) {
    e.preventDefault();

    this.loading = true;

    app
      .request({
        method: 'POST',
        url: app.forum.attribute('apiUrl') + '/forgot',
        body: { email: app.session.user.email() },
      })
      .then(this.hide.bind(this), this.loaded.bind(this));
  }
}


text:
    <meta charset="UTF-8">
    <title>Cosmodrom</title>

    <link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="codemirror.css">
    <link rel="stylesheet" href="night.css">

<textarea id="inp"></textarea>

    <button id="button" type="button">C</button>


text:
<?php
/**
 * Created by PhpStorm.
 * Date: 7/21/17
 */

namespace OK\Tests;
use OK\Credentials\CashCredentials;
use OK\Credentials\Environment\DevelopmentEnvironment;
use OK\Environment;
use OK\Credentials\OKTicketCredentials;
use OK\Credentials\OpenCredentials;
use OK\Credentials\TicketCredentials;

/**
 * Class ClientTest. Contains instantiated client object
 */
abstract class ServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var CashCredentials
     */
    protected $cashCredentials;

    /**
     * @var OpenCredentials
     */
    protected $openCredentials;

    /**
     * @var TicketCredentials
     */
    protected $ticketCredentials;

    /**
     * @var OKTicketCredentials
     */
    protected $okticketCredentials;

    /**
     * @var string
     */
    protected $userToken = "294f27a9-4ab6-4848-b75e-a0ccf00f6799";

    protected $env;

    public function setUp() {
        parent::setUp();

        $this->env = new DevelopmentEnvironment();

        $this->openCredentials = new OpenCredentials("", getenv("KEY_OPEN"), $this->env);
        $this->cashCredentials = new CashCredentials("", getenv("KEY_CASH"), $this->env);
        $this->ticketCredentials = new TicketCredentials("", getenv("KEY_TICKET"), $this->env);
        $this->okticketCredentials = new OKTicketCredentials("", getenv("KEY_TICKET"), $this->env);
    }

}


text:
layout: slide
title: The First Crusade
theme: white
transition: slide
tags: teaching hidden
---

The First Crusade

Jeffrey C. Witt (Loyola University Maryland) | @jeffreycwitt

The Council of Clermont: The Call of Pope Urban II - November 1095

Question:
      How does Pope Urban Speech recall or reference the many causes leading up to Crusade?

Military Reform

"He saw that faith of Christianity was being destroyed ot excess by everybody..." (Peters, p. 49, n. 2)

"Now, let those, who until recently existed as plunderers, be soldiers of Christ..." (Peters, p. 53, n. 7)

Church Reform

"Especially establish ecclesiastical affairs, firm in their own right..." (p. 51, n. 9)

"Uphold the Church in its own ranks altogether free from all secular power..." (p. 51, n. 10)

Byzantine Call for Help Against the Turks

"He heard, too, that the interior regions of romania [anatolia], where the Turks ruled over the Christians, had been perniciously subjected in a savage attack..." (Peters, p. 49, n. 3)

Seljuk Turks become a dominant force in Anatolia in 11th Century.

1071 Battle of Manzikert is decisive for Turkish Control of Anatolia

1075 Seljuk Turks occupy Jerusalem (see SHMA, p. 163)

1095 Council of Piacenza, Alexius calls for assistance (See SHMA, p. 181)

Maps of the First Crusade

Departure from the West - Summer 1096

Arrival Constantinople - May 14th 1097

Siege at Nicea - May 14 to June 18th, 1097

    "Far from aiding the Eastern Empire, they hastened its disintegration.
    They also revealed the continuing inability of Latin Christians
    to understand Greek Christians, and they hardened the schism between them."
     - Walker, Williston, History of the Christian Church, 1985, p. 290:

Battle of Dorylaeum - July 1, 1097

Baldwin and Edessa - February 20, 1098

Siege at Antioch - October 20, 1097

Siege and Conquest of Jerusalem - June 13 to July 15, 1099

Reflection

Reflection


text:
<?xml version="1.0"?>
<stores>
  <store>
    <name>users</name>
    <persistence>bdb</persistence>
    <routing>client</routing>
    <replication-factor>2</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>2</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>java-serialization</type>
    </value-serializer>
  </store>
  <store>
    <name>veggies</name>
    <persistence>bdb</persistence>
    <routing>client</routing>
    <replication-factor>2</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>2</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>json</type>
      <schema-info version="1">"int32"</schema-info>
      <schema-info version="2">"int32"</schema-info>
    </value-serializer>
  </store>
   <store>
    <name>test-replication-memory</name>
    <persistence>memory</persistence>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
  </store>
  <store>
    <name>test-recovery-data</name>
    <persistence>memory</persistence>
    <routing>client</routing>
    <replication-factor>2</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>2</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
  </store>
    <store>
    <name>test-replication-persistent</name>
    <persistence>bdb</persistence>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>java-serialization</type>
    </value-serializer>
  </store>
  <store>
    <name>test-readrepair-memory</name>
    <persistence>memory</persistence>
    <routing>client</routing>
    <replication-factor>2</replication-factor>
    <required-reads>2</required-reads>
    <required-writes>2</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
  </store>
  <store>
    <name>test-readonly-fetchfiles</name>
    <persistence>read-only</persistence>
    <routing>client</routing>
    <replication-factor>2</replication-factor>
    <required-reads>2</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
  </store>
  <store>
    <name>test-readonly-versions</name>
    <persistence>read-only</persistence>
    <routing>client</routing>
    <replication-factor>2</replication-factor>
    <required-reads>2</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
  </store>
  <store>
    <name>test-consistent</name>
    <persistence>memory</persistence>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <preferred-reads>1</preferred-reads>
    <required-reads>1</required-reads>
    <preferred-writes>1</preferred-writes>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
    <hinted-handoff-strategy>consistent-handoff</hinted-handoff-strategy>
  </store>
  <store>
    <name>test-to-all</name>
    <persistence>memory</persistence>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <preferred-reads>1</preferred-reads>
    <required-reads>1</required-reads>
    <preferred-writes>1</preferred-writes>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
    <hinted-handoff-strategy>all-handoff</hinted-handoff-strategy>
  </store>
  <store>
    <name>test-consistent-with-pref-list</name>
    <persistence>memory</persistence>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <preferred-reads>1</preferred-reads>
    <required-reads>1</required-reads>
    <preferred-writes>1</preferred-writes>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
      <schema-info>UTF-8</schema-info>
    </value-serializer>
    <hinted-handoff-strategy>all-handoff</hinted-handoff-strategy>
    <hint-preflist-size>10</hint-preflist-size>
  </store>
</stores>


text:
cask 'supercollider' do
  version '3.9.3'
  sha256 '84cdad611aca022ff218aff46e92021a334c5bb8e6ac3dbbe0051fe7f57bae07'

  # github.com/supercollider/supercollider was verified as official when first introduced to the cask
  url "https://github.com/supercollider/supercollider/releases/download/Version-#{version}/SuperCollider-#{version}-macOS.zip"
  appcast 'https://github.com/supercollider/supercollider/releases.atom',
          checkpoint: '72ee8bd7b4c3325c616a0eca42db28464b46904434215af74addfcad5f2a19f0'
  name 'SuperCollider'
  homepage 'https://supercollider.github.io/'

  app 'SuperCollider/SuperCollider.app'
end


text:
#ifndef DG_SETTINGS_H
#define DG_SETTINGS_H

#include <glib-object.h>

G_BEGIN_DECLS

#define DG_SETTINGS_TYPE     (dg_settings_get_type ())
#define DG_SETTINGS(obj)     (G_TYPE_CHECK_INSTANCE_CAST ((obj), DG_SETTINGS_TYPE, DgSettings))
#define DG_IS_SETTINGS(obj)  (G_TYPE_CHECK_INSTANCE_TYPE ((obj), DG_SETTINGS_TYPE))

typedef struct _DgSettingsClass DgSettingsClass;
typedef struct _DgSettings      DgSettings;

struct _DgSettingsClass {
  GObjectClass parent_class;
};

struct _DgSettings {
  GObject parent;
};

GType dg_settings_get_type (void);

void dg_settings__get_property__ (GObject      *object,
                                  guint         prop_id,
                                  GValue       *value,
                                  GParamSpec   *pspec);
void dg_settings__set_property__ (GObject      *object,
                                  guint         prop_id,
                                  const GValue *value,
                                  GParamSpec   *pspec);
void dg_settings__constructed__  (GObject      *object);

#define DG_SETTING__FLAG \
  (1 << G_PARAM_USER_SHIFT)
#define DG_SETTING_FLAGS \
  (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | DG_SETTING__FLAG)

#define DG_SETTINGS_BOOLEAN(_name, _nick, _desc, _default)         \
  g_object_class_install_property (G_OBJECT_CLASS (klass),          \
                                   ++klass->prop_id,                 \
                                   g_param_spec_boolean ((_name),     \
                                                         (_nick),      \
                                                         (_desc),       \
                                                         (_default),     \
                                                         DG_SETTING_FLAGS))

#define DG_SETTINGS_STRING(_name, _nick, _desc, _default)         \
  g_object_class_install_property (G_OBJECT_CLASS (klass),         \
                                   ++klass->prop_id,                \
                                   g_param_spec_string ((_name),     \
                                                        (_nick),      \
                                                        (_desc),       \
                                                        (_default),     \
                                                        DG_SETTING_FLAGS))

#define DG_SETTINGS_UINT_RANGE(_name, _nick, _desc, _default, _min, _max) \
    g_object_class_install_property (G_OBJECT_CLASS (klass),              \
                                     ++klass->prop_id,                    \
                                     g_param_spec_uint ((_name),          \
                                                        (_nick),          \
                                                        (_desc),          \
                                                        (_min),           \
                                                        (_max),           \
                                                        (_default),       \
                                                        DG_SETTING_FLAGS))

#define DG_SETTINGS_UINT(_name, _nick, _desc, _default) \
    DG_SETTINGS_UINT_RANGE ((_name), (_nick), (_desc), (_default), 0, G_MAXUINT)

#define DG_SETTINGS_CLASS_DECLARE(_T, _t)                               \
  typedef struct _ ## _T ## Class _T ## Class;                          \
  typedef struct _ ## _T _T;                                            \
  GType _t ## _get_type (void);                                         \
  static inline _T* _t ## _new(const gchar *path, gboolean monitor) {   \
    return g_object_new (_t ## _get_type(), "settings-path", path,      \
                         "settings-monitoring-enabled", monitor, NULL); }

#define DG_SETTINGS_CLASS_DEFINE(_T, _t)                                    \
  struct _ ## _T ## Class { DgSettingsClass parent_class; guint prop_id; }; \
  struct _ ## _T { DgSettings parent; };                                    \
  static void _t ## _init (_T *object) { }                                  \
  G_DEFINE_TYPE (_T, _t, DG_SETTINGS_TYPE)                                  \
  static void _t ## _class_init (_T ## Class *klass) {                      \
    G_OBJECT_CLASS (klass)->get_property = dg_settings__get_property__;     \
    G_OBJECT_CLASS (klass)->set_property = dg_settings__set_property__;     \
    G_OBJECT_CLASS (klass)->constructed  = dg_settings__constructed__;
#define DG_SETTINGS_CLASS_END }

G_END_DECLS

#endif /* !DG_SETTINGS_H */


text:
<?php

namespace Bemoove\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * BaseUser
 *
 * @ORM\MappedSuperclass()
 * @UniqueEntity(fields={"email"}, message = "The email already exists.")
 */
class BaseUser implements UserInterface
{
    /**
     * @var int
     *
     * @Groups({"booking_with_user"})
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @Groups({"booking_with_user"})
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email(
     *     message = "The email '{{ value }}' is not a valid email."
     * )
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="roles", type="string", length=255)
     */
    private $roles;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=255)
     */
    private $password;

    /**
     * @var string
     *
     * @ORM\Column(name="salt", type="string", length=255)
     */
    private $salt;

    /**
     * @var string
     *
     * @Groups({"booking_with_user"})
     * @ORM\Column(name="Username", type="string", length=255)
     */
    private $username;

    public function __construct() {
        // De base, on va attribuer au nouveau utilisateur, le rôle « ROLE_USER »
        $this->setRoles(array("ROLE_USER"));

        // Chaque utilisateur va se voir attribuer une clé permettant
        // de saler son mot de passe. Cela n'est pas obligatoire,
        // on pourrait mettre $salt à null
        if(empty($this->salt)) {
            $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
        }
    }
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;
        $this->setUsername($this->email);

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set roles
     *
     * @param array||string $roles
     *
     * @return User
     */
    public function setRoles($roles)
    {
        if (!is_array($roles) && is_string($roles)) {
            $roles = array($roles);
        }
        $this->roles = serialize($roles);

        return $this;
    }

    /**
     * Get roles
     *
     * @return string
     */
    public function getRoles()
    {
        return unserialize($this->roles);
    }

    /**
     * Add roles
     *
     * @return string
     */
    public function addRoles($roles)
    {
        $arr_roles = $this->getRoles();
        $arr_roles[] = $roles;
        $arr_roles = array_unique($arr_roles);
        sort($arr_roles);
        $this->setRoles($arr_roles);

        return unserialize($this->roles);
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set salt
     *
     * @param string $salt
     *
     * @return User
     */
    public function setSalt($salt)
    {
        $this->salt = $salt;

        return $this;
    }

    /**
     * Get salt
     *
     * @return string
     */
    public function getSalt()
    {
        return $this->salt;
    }

    /**
     * Set username
     *
     * @param string $username
     *
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    public function eraseCredentials() {

    }
}


text:
#ifndef _COMMON_CMDS_H
#define _COMMON_CMDS_H
#include "u_hash_map_structs.h"
#include "u_memmgr.h"

int parse_env_line(memmgr **mm, char *one_var, char **name, char **value);

void set_env_opts(memmgr **mm, job_data **env_attr, char **envp);

void calloc_or_fail(memmgr **mm, char **dest, int alloc_size, const char *err_msg);

int parse_variable_list(memmgr **mm, job_data **dest_hash, job_data *user_env, int var_type, int op_type, char *the_list);

#endif /* _COMMON_CMDS_H */


text:
import argparse
import messagebird
from messagebird.voice_webhook import VoiceCreateWebhookRequest

parser = argparse.ArgumentParser()
parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True)
parser.add_argument('--url', help='url for the webhook', type=str, required=True)
parser.add_argument('--title', help='title for the webhook', type=str)
parser.add_argument('--token', help='token for the webhook', type=str)
args = vars(parser.parse_args())

try:
    client = messagebird.Client(args['accessKey'])

    create_webhook_request = VoiceCreateWebhookRequest(url=args['url'], title=args['title'], token=args['token'])
    webhook = client.voice_create_webhook(create_webhook_request)

    # Print the object information.
    print('\nThe following information was returned as a Voice Webhook object:\n')
    print('  id                 : {}'.format(webhook.id))
    print('  token              : {}'.format(webhook.token))
    print('  url                : {}'.format(webhook.url))
    print('  createdAt          : {}'.format(webhook.createdAt))
    print('  updatedAt          : {}'.format(webhook.updatedAt))

except messagebird.client.ErrorException as e:
    print('An error occured while creating a Voice Webhook object:')

    for error in e.errors:
        print('  code        : {}'.format(error.code))
        print('  description : {}'.format(error.description))
        print('  parameter   : {}\n'.format(error.parameter))


text:
layout: page
title: Orb Air Dinner
date: 2016-05-24
author: Eric Abbott
tags: weekly links, java
status: published
summary: Vestibulum ante ipsum primis in faucibus orci luctus et ultrices.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/27/2017
  endDate: 10/29/2017
  ctyhocn: HOUCYHX
  groupCode: OAD
published: true
---
Vivamus aliquet augue at dui euismod sollicitudin. Cras varius massa iaculis dolor fermentum dapibus. Nam mauris nisi, finibus quis faucibus eu, euismod sit amet erat. Sed et iaculis ante. Morbi at tincidunt lectus. Duis bibendum libero ut urna laoreet mollis. Aenean egestas vehicula placerat.
Pellentesque diam mi, dictum ac velit faucibus, rutrum posuere magna. Quisque turpis odio, cursus et mollis sit amet, consequat quis risus. Maecenas facilisis egestas nunc, vel pharetra tellus venenatis a. Nullam tincidunt nibh nisi, in ultrices ipsum mattis placerat. Suspendisse molestie, elit non tincidunt varius, velit mauris malesuada ex, ut feugiat diam sapien sed diam. Nulla porta, nisi tempus vehicula dictum, dolor dui suscipit mi, porta feugiat felis justo vitae eros. Nam fermentum, ex et iaculis molestie, sapien lacus porta quam, sed mollis libero nunc ut lectus. Vivamus ultrices ornare risus ac sagittis. Maecenas sed consectetur tellus, congue consectetur lectus. Phasellus ultricies, ipsum vel aliquet tristique, mauris libero fringilla odio, nec lacinia purus mi ac nunc.

* Curabitur tempus dui vitae ex dapibus porta
* Fusce vitae velit a massa tempus pretium ac et tortor
* Curabitur suscipit augue non sem posuere lobortis
* Vivamus et magna vitae felis consequat vestibulum non ac nunc.

Cras lectus odio, ullamcorper nec bibendum ultrices, facilisis sed urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed tempus accumsan mollis. Donec pulvinar justo in lectus semper hendrerit. Aenean a eleifend lectus. Aenean luctus vestibulum consequat. Quisque quam elit, commodo sed ultricies eu, suscipit et augue. Ut vel pretium lorem, accumsan luctus lorem. In a placerat tortor, et congue augue.