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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Microsoft.Tools.WindowsDevicePortal;
using static Microsoft.Tools.WindowsDevicePortal.DevicePortal;

namespace HoloLensCommander
{
    /// <summary>
    /// The view model for the DeviceMonitorControl object.
    /// </summary>
    partial class DeviceMonitorControlViewModel : INotifyPropertyChanged, IDisposable
    {
        /// <summary>
        /// Text labels describing the power connection state.
        /// </summary>
        private static readonly string OnAcPowerLabel = "";        // EBB2 (battery with plug)
        private static readonly string OnBatteryLabel = "";        // EBA7 (battery)

        /// <summary>
        /// Text labels describing the type of device.
        /// </summary>
        private static readonly string DeviceIsPCLabel = "";       // E7F4 (PC monitor)
        private static readonly string DeviceIsHoloLensLabel = "";  // no image
        private static readonly string DeviceIsUnknownLabel = "";  // F142 (question mark)

        /// <summary>
        /// Message to display when the heartbeat is lost.
        /// </summary>
        private static readonly string HeartbeatLostMessage = "Lost Connection to Device";

        /// <summary>
        /// The DeviceMonitor object responsible for communication with this device.
        /// </summary>
        private DeviceMonitor deviceMonitor;

        /// <summary>
        /// The DeviceMonitorControl object to which this view model is registered.
        /// </summary>
        private DeviceMonitorControl deviceMonitorControl;

        /// <summary>
        /// Indicates whether or not the monitor control was selected prior to loss of heartbeat.
        /// </summary>
        private bool oldIsSelected = false;

        /// <summary>
        /// Event that is notified when a property value has changed.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceMonitorControlViewModel" /> class.
        /// </summary>
        /// <param name="control">The DeviceMonitorControl to which this object is registered.</param>
        /// <param name="monitor">The DeviceMonitor responsible for communication with this device.</param>
        public DeviceMonitorControlViewModel(
            DeviceMonitorControl control,
            DeviceMonitor monitor)
        {
            this.deviceMonitorControl = control;

            this.RegisterCommands();

            this.deviceMonitor = monitor;
            this.deviceMonitor.HeartbeatLost += Device_HeartbeatLost;
            this.deviceMonitor.HeartbeatReceived += Device_HeartbeatReceived;
            this.deviceMonitor.AppInstallStatus += DeviceMonitor_AppInstallStatus;

            this.SetFilter();

            this.IsConnected = true;

            this.Address = deviceMonitor.Address;
            this.IsSelected = true;

        }

        /// <summary>
        /// Finalizer so that we are assured we clean up all encapsulated resources.
        /// </summary>
        /// <remarks>Call Dispose on this object to avoid running the finalizer.</remarks>
        DeviceMonitorControlViewModel()
        {
            this.Dispose();
        }

        /// <summary>
        /// Cleans up objects managed by the DeviceMonitorControlViewModel.
        /// </summary>
        /// <remarks>
        /// Failure to call this method will result in the object not being collected until
        /// finalization occurs.
        /// </remarks>
        public void Dispose()
        {
            this.deviceMonitor.HeartbeatLost -= Device_HeartbeatLost;
            this.deviceMonitor.HeartbeatReceived -= Device_HeartbeatReceived;
            this.deviceMonitor.AppInstallStatus -= DeviceMonitor_AppInstallStatus;
            this.deviceMonitor.Dispose();
            this.deviceMonitor = null;

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Closes all applications running on this device.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task CloseAllAppsAsync()
        {
            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    await this.deviceMonitor.TerminateAllApplicationsAsync();
                }
                catch(Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Failed to close one or more applications - {0}",
                        e.Message);
                }
            }
        }

        /// <summary>
        /// Queries the device for the names of all installed applications.
        /// </summary>
        /// <returns>List of application names.</returns>
        internal async Task<List<string>> GetInstalledAppNamesAsync()
        {
            List<string> appNames = new List<string>();

            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    AppPackages installedApps = await this.deviceMonitor.GetInstalledApplicationsAsync();
                    appNames = Utilities.GetAppNamesFromPackageInfo(
                        installedApps.Packages,
                        true);
                }
                catch
                {
                }
            }

            return appNames;
        }

        /// <summary>
        /// Downloads mixed reality files from the device.
        /// </summary>
        /// <param name="parentFolder">The parent folder which will contain the device specific folder.</param>
        /// <param name="deleteAfterDownload">Value indicating whether or not files are to be deleted
        /// from the device after they have been downloaded.</param>
        /// <returns>The name of the folder in to which the files were downloaded.</returns>
        internal async Task<string> GetMixedRealityFilesAsync(
            StorageFolder parentFolder,
            bool deleteAfterDownload)
        {
            string folderName = null;

            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    MrcFileList fileList = await this.deviceMonitor.GetMixedRealityFileListAsync();

                    if (fileList.Files.Count != 0)
                    {
                        // Create the folder for this device's files.
                        StorageFolder folder = await parentFolder.CreateFolderAsync(
                            (string.IsNullOrWhiteSpace(this.Name) ? this.Address : this.Name),
                            CreationCollisionOption.OpenIfExists);
                        folderName = folder.Name;

                        foreach (MrcFileInformation fileInfo in fileList.Files)
                        {
                            try
                            {
                                byte[] fileData = await this.deviceMonitor.GetMixedRealityFileAsync(fileInfo.FileName);

                                StorageFile file = await folder.CreateFileAsync(
                                    fileInfo.FileName,
                                    CreationCollisionOption.ReplaceExisting);

                                using (Stream stream = await file.OpenStreamForWriteAsync())
                                {
                                    await stream.WriteAsync(fileData, 0, fileData.Length);
                                    await stream.FlushAsync();
                                }

                                this.StatusMessage = string.Format(
                                    "{0} downloaded",
                                    fileInfo.FileName);

                                if (deleteAfterDownload)
                                {
                                    await this.deviceMonitor.DeleteMixedRealityFile(fileInfo.FileName);
                                }
                            }
                            catch(Exception e)
                            {
                                this.StatusMessage = string.Format(
                                    "Failed to download {0} - {1}",
                                    fileInfo.FileName,
                                    e.Message);
                            }
                        }
                    }
                }
                catch(Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Failed to get mixed reality files - {0}",
                        e.Message);
                }
            }

            return folderName;
        }

        /// <summary>
        /// Installs an application on this device.
        /// </summary>
        /// <param name="installFiles">Object describing the file(s) required to install an application.</param>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task InstallAppAsync(AppInstallFiles installFiles)
        {
            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    await this.deviceMonitor.InstallApplicationAsync(installFiles);

                    this.deviceMonitorControl.NotifyAppInstall();
                }
                catch(Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Failed to install {0} - {1}",
                        installFiles.AppPackageFile.Name,
                        e.Message);
                }
            }
        }

        /// <summary>
        /// Launches an applicaiton on this device.
        /// </summary>
        /// <param name="appName">The name of the application to launch.</param>
        /// <returns>The process identifier of the running application.</returns>
        internal async Task<int> LaunchAppAsync(string appName)
        {
            int processId = 0;

            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    string appId = null;
                    string packageName = null;

                    AppPackages installedApps = await this.deviceMonitor.GetInstalledApplicationsAsync();

                    foreach (PackageInfo packageInfo in installedApps.Packages)
                    {
                        if (appName == packageInfo.Name)
                        {
                            appId = packageInfo.AppId;
                            packageName = packageInfo.FullName;
                            break;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(appId) &&
                        !string.IsNullOrWhiteSpace(packageName))
                    {
                        processId = await this.deviceMonitor.LaunchApplicationAsync(
                            appId,
                            packageName);
                    }

                    Task t = new Task(
                        async () =>
                        {
                            await WatchProcess(processId,
                                appName,
                                2);
                        });
                    t.Start();
                }
                catch(Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Failed to launch {0} - {1}",
                        appName,
                        e.Message);
                }
            }

            return processId;
        }

        /// <summary>
        /// Launches the default web browser and connects to the Windows Device Portal on this devcie.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        private async Task LaunchDevicePortalAsync()
        {
            await Launcher.LaunchUriAsync(this.deviceMonitor.DevicePortalUri);
        }

        /// <summary>
        /// Displays the manage applications dialog.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        private async Task ManageAppsAsync()
        {
            ContentDialog dialog = new ManageAppsDialog(this.deviceMonitor, this.deviceMonitorControl);
            await dialog.ShowAsync();
        }

        /// <summary>
        /// Displays the mixed reality view dialog.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        private async Task MixedRealityViewAsync()
        {
            ContentDialog dialog = new MixedRealityViewDialog(this.deviceMonitor);
            await dialog.ShowAsync();
        }

        /// <summary>
        /// Reboots this device.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task RebootAsync()
        {
            if (this.IsConnected && this.IsSelected)
            {
                this.StatusMessage = "Rebooting";

                await this.deviceMonitor.RebootAsync();

                this.IsConnected = false;
            }
        }

        /// <summary>
        /// Displays the set IPD dialog.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task SetIpdAsync()
        {
            UserInformation userInfo = new UserInformation();
            float.TryParse(this.Ipd, out userInfo.Ipd);

            ContentDialog dialog = new SetIpdDialog(
                this.deviceMonitor.Address,
                userInfo);
            ContentDialogResult result = await dialog.ShowAsync().AsTask<ContentDialogResult>();;

            // Primary button == "Set"
            if (result == ContentDialogResult.Primary)
            {
                // Update the IPD on the device
                try
                {
                    await this.deviceMonitor.SetIpd(userInfo.Ipd);
                }
                catch (Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Unable to update the IPD - {0}",
                        e.Message);
                }
            }
        }

        /// <summary>
        /// Displays the device information dialog.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task ShowDeviceInfoAsync()
        {
            ContentDialog dialog = new DeviceInformationDialog(this.deviceMonitor);
            await dialog.ShowAsync().AsTask<ContentDialogResult>();
        }

        /// <summary>
        /// Shuts down this device.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task ShutdownAsync()
        {
            if (this.IsConnected && this.IsSelected)
            {
                this.StatusMessage = "Shutting down";

                await this.deviceMonitor.ShutdownAsync();

                this.IsConnected = false;
            }
        }

        /// <summary>
        /// Starts recording a mixed reality video on this device.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task StartMixedRealityRecordingAsync()
        {
            if (this.IsConnected && this.IsSelected)
            {
                this.StatusMessage = "Starting mixed reality recording";

                await this.deviceMonitor.StartMixedRealityRecordingAsync();
            }
        }

        /// <summary>
        /// Stops the mixed reality recording on this device.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task StopMixedRealityRecordingAsync()
        {
            if (this.IsConnected && this.IsSelected)
            {
                await this.deviceMonitor.StopMixedRealityRecordingAsync();

                this.StatusMessage = "Mixed reality recording stopped";
            }
        }

        /// <summary>
        /// Displays the tag device dialog.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        private async Task TagDeviceAsync()
        {
            TagInformation tagInfo = new TagInformation();
            tagInfo.Name = this.Name;

            ContentDialog dialog = new TagDeviceDialog(
                this.deviceMonitor.Address,
                tagInfo);
            ContentDialogResult result = await dialog.ShowAsync().AsTask<ContentDialogResult>();;

            // Primary button == "Ok"
            if (result == ContentDialogResult.Primary)
            {
                this.Name = tagInfo.Name;
                this.deviceMonitorControl.NotifyTagChanged();
            }
        }

        /// <summary>
        /// Unintalls an application on this device.
        /// </summary>
        /// <returns>Task object used for tracking method completion.</returns>
        internal async Task UninstallAppAsync(string appName)
        {
            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    AppPackages installedApps = await this.deviceMonitor.GetInstalledApplicationsAsync();

                    string packageName = Utilities.GetPackageNameFromAppName(
                        appName,
                        installedApps);

                    if (packageName == null)
                    {
                        throw new Exception(
                            string.Format("App ({0}) could not be found",
                            appName));
                    }

                    await this.deviceMonitor.UninstallApplicationAsync(packageName);

                    this.StatusMessage = "Uninstall complete";

                    this.deviceMonitorControl.NotifyAppUninstall();
                }
                catch (Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Failed to uninstall {0} - {1}",
                        appName,
                        e.Message);
                }
            }
        }

        /// <summary>
        /// Handles the ApplicationInstallStatus event.
        /// </summary>
        /// <param name="sender">The object which sent this event.</param>
        /// <param name="args">Event arguments.</param>
        private void DeviceMonitor_AppInstallStatus(
            DeviceMonitor sender,
            ApplicationInstallStatusEventArgs args)
        {
            this.StatusMessage = args.Message;
        }

        /// <summary>
        /// Handles the HeartbeatLost event.
        /// </summary>
        /// <param name="sender">The object which sent this event.</param>
        private void Device_HeartbeatLost(DeviceMonitor sender)
        {
            this.IsConnected = false;

            this.StatusMessage = HeartbeatLostMessage;

            // Handle whether or not we were previously selected
            if (!this.oldIsSelected &&
                this.IsSelected)
            {
                this.IsSelected = false;
                this.oldIsSelected = true;
            }

            // Update the heartbeat based UI
            this.PowerIndicator = OnBatteryLabel;
            this.BatteryLevel = "--";
            this.ThermalStatus = Visibility.Collapsed;
            this.Ipd = "--";
        }

        /// <summary>
        /// Handles the HeartbeatReceived event.
        /// </summary>
        /// <param name="sender">The object which sent this event.</param>
        private void Device_HeartbeatReceived(DeviceMonitor sender)
        {
            this.IsConnected = true;

            // Did we recover from a heartbeat loss?
            if (this.StatusMessage == HeartbeatLostMessage)
            {
                this.StatusMessage = "";
            }

            // Handle whether or not we were previously selected
            if (this.oldIsSelected &&
                !this.IsSelected)
            {
                this.IsSelected = true;
                this.oldIsSelected = false;
            }

            // Update the heartbeat based UI
            this.PowerIndicator = sender.BatteryState.IsOnAcPower ? OnAcPowerLabel : OnBatteryLabel;
            this.BatteryLevel = string.Format("{0}%", sender.BatteryState.Level.ToString("#.00"));
            this.ThermalStatus = (sender.ThermalStage == ThermalStages.Normal) ? Visibility.Collapsed : Visibility.Visible;
            this.Ipd = sender.Ipd.ToString();
        }

        /// <summary>
        /// Method used by WatchProcess to ensure that the status message update is performed on the ui thread.
        /// </summary>
        /// <param name="message">The message to display to the user.</param>
        private void MarshalStatusMessageUpdate(string message)
        {
            CoreDispatcher dispatcher = this.deviceMonitorControl.Dispatcher;
            if (!dispatcher.HasThreadAccess)
            {
                // Assigning the return value of RunAsync to a Task object to avoid
                // warning 4014 (call is not awaited).
                Task t = dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    () =>
                    {
                        this.MarshalStatusMessageUpdate(message);
                    }).AsTask();
                return;
            }

            this.StatusMessage = message;
        }

        /// <summary>
        /// Sends the PropertyChanged events to registered handlers.
        /// </summary>
        /// <param name="propertyName">The name of property that has changed.</param>
        private void NotifyPropertyChanged(string propertyName)
        {
            this.PropertyChanged?.Invoke(
                this,
                new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// Registers the commands supported by this object.
        /// </summary>
        private void RegisterCommands()
        {
            this.DisconnectCommand = new Command(
                (parameter) =>
                {
                    this.Disconnect();
                });

            this.SetIpdCommand = new Command(
                async (parameter) =>
                {
                    await this.SetIpdAsync();
                });

            this.SetTagCommand = new Command(
                async (parameter) =>
                {
                    await this.TagDeviceAsync();
                });

            this.ShowContextMenuCommand = new Command(
                async (parameter) =>
                {
                    await this.ShowContextMenuAsync(parameter);
                });
        }

        /// <summary>
        /// Determine the correct setting for the Filter property.
        /// </summary>
        private void SetFilter()
        {
            switch (this.deviceMonitor.Platform)
            {
                case DevicePortalPlatforms.HoloLens:
                    this.Filter = DeviceFilters.HoloLens;
                    this.DeviceTypeLabel = DeviceIsHoloLensLabel;
                    this.IpdVisibility = Visibility.Visible;
                    break;

                case DevicePortalPlatforms.Windows:
                    this.Filter = DeviceFilters.Desktop;
                    this.DeviceTypeLabel = DeviceIsPCLabel;
                    this.IpdVisibility = Visibility.Collapsed;
                    break;

                case DevicePortalPlatforms.VirtualMachine:
                    switch (this.deviceMonitor.DeviceFamily)
                    {
                        case "Windows.Desktop":
                            this.Filter = DeviceFilters.Desktop;
                            this.DeviceTypeLabel = DeviceIsPCLabel;
                            this.IpdVisibility = Visibility.Collapsed;
                            break;

                        case "Windows.Holographic":
                            this.Filter = DeviceFilters.HoloLens;
                            this.DeviceTypeLabel = DeviceIsHoloLensLabel;
                            this.IpdVisibility = Visibility.Visible;
                            break;

                        default:
                            Debug.Assert(false, "Virtual Machine: Unknown device family.");
                            this.Filter = DeviceFilters.None;
                            this.DeviceTypeLabel = DeviceIsUnknownLabel;
                            this.IpdVisibility = Visibility.Collapsed;
                            break;
                    }
                    break;

                default:
                    Debug.Assert(false, "Unknown device platform.");
                    this.Filter = DeviceFilters.None;
                    this.DeviceTypeLabel = DeviceIsUnknownLabel;
                    this.IpdVisibility = Visibility.Collapsed;
                    break;
            }
        }

        /// <summary>
        /// Monitors running processes and when the specified id is no longer running, update's the status message ui.
        /// </summary>
        /// <param name="processId">The process identifier to watch.</param>
        ///  <param name="appName">The name of the application associated with the process identifier.</param>
        /// <param name="waitSeconds">Time, in seconds, to wait between checking on the processes.</param>
        /// <returns>Task object used for tracking method completion.</returns>
        private async Task WatchProcess(
            int processId,
            string appName,
            float waitSeconds)
        {
            ManualResetEvent resetEvent = new ManualResetEvent(false);
            int waitTime = (int)(waitSeconds * 1000.0f);

            Timer timer = new Timer(
                WatchProcessCallback,
                resetEvent,
                Timeout.Infinite,
                Timeout.Infinite);

            RunningProcesses runningProcesses = null;
            bool processIsRunning = false;

            try
            {
                do
                {
                    MarshalStatusMessageUpdate(string.Format(
                        "Waiting for {0} to exit",
                        appName));

                    resetEvent.Reset();
                    timer.Change(0, waitTime);
                    resetEvent.WaitOne(waitTime * 2);   // Wait no longer than twice the specified time.
                    runningProcesses = await this.deviceMonitor.GetRunningProcessesAsync();
                    processIsRunning = runningProcesses.Contains(processId);
                }
                while(processIsRunning);

                    MarshalStatusMessageUpdate(string.Format(
                        "{0} has exited",
                        appName));
            }
            catch(Exception e)
            {
                MarshalStatusMessageUpdate(string.Format(
                    "Cannot determine the execution state of {0} - {1}",
                    appName,
                    e.Message));
            }

            timer.Change(
                Timeout.Infinite,
                Timeout.Infinite);
            timer.Dispose();
            timer = null;
        }

        /// <summary>
        /// Timer callback event used when watching a process.
        /// </summary>
        /// <param name="data">The manual reset event that is being waited upon.</param>
        private void WatchProcessCallback(object data)
        {
            ManualResetEvent resetEvent = data as ManualResetEvent;
            resetEvent.Set();
        }
    }
}


text:
The Identity service is regionless, so you do not need to specify a region when instantiating the service object. Although this was primarily based on Rackspace's implementation of Cloud Identity, it should also work for OpenStack Keystone.

## A note on object creation

Normally, when services are created the client handles authenticates automatically. But because Keystone/Identity is fundamental to the authentication process itself, it proves difficult to do this procedure as its normally done. For this reason, you have two options when creating the service object:

1: Use the client's factory method

```php
$identity = $client->identityService();
```

2: Authenticate manually

```php
use OpenCloud\Identity\Service as IdentityService;

$identity = IdentityService::factory($client);
$identity->getClient()->authenticate();
```

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Loupe.Extensibility.Client;
using Loupe.Extensibility.Data;

namespace Loupe.Extension.Export
{
    /// <summary>
    /// Core data and logic associated with exporting session data
    /// </summary>
    class MetricExportDefinition
    {
        private const string LogCategory = "SessionExport.Export";
        public HashSet<string> Applications { get; private set; }
        public HashSet<string> Metrics { get; private set; }
        private ExportAddInConfiguration Config { get; set; }
        private readonly IRepositoryContext _context;

        public MetricExportDefinition(IRepositoryContext context, ExportAddInConfiguration config)
        {
            _context = context;
            Config = config;
            Applications = new HashSet<string>();
            Metrics = new HashSet<string>();
        }

        /// <summary>
        /// Exports configured data for this session, if it is an application we care about
        /// </summary>
        public void Process(ISession session)
        {
            // Validate that we have work to do for the application that generated this session
            if (!Applications.Contains(session.Summary.FullApplicationName()))
                return;

            var metrics = session.MetricDefinitions.Where(md => Metrics.Contains(md.FullMetricName())).ToList();
            var metricFileCount = 0;
            foreach (var metric in metrics)
            {
                if (metric.SampleType == SampleType.Sampled)
                    ExportSampledMetric(session, metric, ref metricFileCount);
                else
                    ExportEventMetric(session, (IEventMetricDefinition)metric, ref metricFileCount);
            }
        }

        /// <summary>
        /// Export a CSV file for each instance of a sampled metric
        /// </summary>
        private void ExportSampledMetric(ISession session, IMetricDefinition metricDefinition, ref int metricFileCount)
        {
            if (metricDefinition.Metrics.Count == 1)
            {
                try
                {
                    using (
                        var writer = StreamCreator.CreateMetricStream(_context, Config, session, metricDefinition,
                            ref metricFileCount))
                    {
                        ExportSamples(writer, metricDefinition.Metrics[0]);
                    }
                }
                catch (Exception ex)
                {
                    _context.Log.RecordException(ex, LogCategory, true);
                }
            }
            else
            {
                foreach (var metric in metricDefinition.Metrics)
                {
                    try
                    {
                        using (
                            var writer = StreamCreator.CreateMetricInstanceStream(_context, Config, session, metric,
                                ref metricFileCount))
                        {
                            ExportSamples(writer, metric);
                        }
                    }
                    catch (Exception ex)
                    {
                        _context.Log.RecordException(ex, LogCategory, true);
                    }
                }
            }
        }

        /// <summary>
        /// ExportSamples is the shared logic for all sampled metric exports
        /// </summary>
        private void ExportSamples(StreamWriter writer, IMetric metric)
        {
            writer.Write("\"Sequence\",\"Timestamp\",\"{0}\"\r\n",
                string.IsNullOrEmpty(metric.InstanceName) ? "Value" : metric.InstanceName);

            foreach (var sample in metric.Samples)
            {
                writer.Write("{0},{1},{2}\r\n", sample.Sequence,sample.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"), sample.Value);
            }
        }

        /// <summary>
        /// Export a CSV file for each instance of am EventMetric
        /// </summary>
        private void ExportEventMetric(ISession session, IEventMetricDefinition metricDefinition, ref int metricFileCount)
        {
            if (metricDefinition.Metrics.Count == 1)
            {
                try
                {
                    using (
                        var writer = StreamCreator.CreateMetricStream(_context, Config, session, metricDefinition,
                            ref metricFileCount))
                    {
                        ExportEventSamples(writer, metricDefinition, metricDefinition.Metrics[0] as IEventMetric);
                    }
                }
                catch (Exception ex)
                {
                    _context.Log.RecordException(ex, LogCategory, true);
                }
            }
            else
            {
                foreach (var metric in metricDefinition.Metrics)
                {
                    try
                    {
                        using (
                            var writer = StreamCreator.CreateMetricInstanceStream(_context, Config, session, metric,
                                ref metricFileCount))
                        {
                            ExportEventSamples(writer, metricDefinition, metric as IEventMetric);
                        }
                    }
                    catch (Exception ex)
                    {
                        _context.Log.RecordException(ex, LogCategory, true);
                    }
                }
            }
        }

        /// <summary>
        /// ExportEvemtSamples is the shared logic for all event metric exports
        /// </summary>
        private void ExportEventSamples(StreamWriter writer, IEventMetricDefinition metricDefinition, IEventMetric metric)
        {
            writer.Write("\"Sequence\",\"Timestamp\"");
            foreach (var valueDefinition in metricDefinition.Values)
            {
                writer.Write(",\"{0}\"", valueDefinition.Caption);
            }
            writer.WriteLine();

            foreach (var sample in metric.Samples)
            {
                var eventSample = sample as IEventMetricSample;
                if (eventSample == null)
                    continue;

                writer.Write("{0},\"{1}\"", eventSample.Sequence, eventSample.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"));
                for (var i = 0; i < eventSample.Values.Count(); i++)
                {
                    writer.Write(",\"{0}\"", eventSample.Values[i]);
                }
                writer.WriteLine();
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>
Constant Field Values
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

All Classes

Constant Field Values

Contents

com.wesleyware.*

com.wesleyware.*

com.wesleyware.daowiz.gui.FieldTableModel

public static final int
COMMENTS
9

public static final int
FIELD_NAME
0

public static final int
FIELD_TYPE
2

public static final int
HAS_DEFAULT_VALUE
6

public static final int
IS_FK
8

public static final int
IS_NOT_NULL
5

public static final int
IS_PK
7

public static final int
SCALE
4

public static final int
SIZE
3

public static final int
VARIABLE_NAME
1

com.wesleyware.daowiz.gui.FieldTypes

public static final int
BIGINT
1

public static final int
BOOLEAN
2

public static final int
CHAR
3

public static final int
DATE
4

public static final int
DECIMAL
5

public static final int
DOUBLE
6

public static final int
FLOAT
7

public static final int
INT
8

public static final int
NUMERIC
9

public static final int
REAL
15

public static final int
SMALLINT
10

public static final int
TEXT
11

public static final int
TIME
12

public static final int
TIMESTAMP
13

public static final int
VARCHAR
14

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

All Classes


text:
using System;
using System.Runtime.Serialization;
using System.Windows.Forms;
using NLog;
using System.ComponentModel;
using Facebook;
using System.Collections.Generic;

namespace OdessaGUIProject.Other_Helpers
{
    internal class FacebookHelper
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        internal static bool LoginToFacebook()
        {
            const string appId = "228803620534906";
            string extendedPermissions = "publish_actions,email";

            var fbLoginDialog = new FacebookLoginDialog(appId, extendedPermissions);
            fbLoginDialog.ShowDialog();

            var facebookOAuthResult = fbLoginDialog.FacebookOAuthResult;

            if (facebookOAuthResult != null)
            {
                if (facebookOAuthResult.IsSuccess)
                {
                    Properties.Settings.Default.FacebookAccessToken = facebookOAuthResult.AccessToken;
                    Properties.Settings.Default.FacebookAccessTokenExpiration = facebookOAuthResult.Expires;
                    Properties.Settings.Default.Save();

                    Logger.Info("Logged in to Facebook with access token " + Properties.Settings.Default.FacebookAccessToken);
                    Logger.Info("Access token expires at " + Properties.Settings.Default.FacebookAccessTokenExpiration);

                    try
                    {
                        var captureEmailAddressWorker = new BackgroundWorker();
                        captureEmailAddressWorker.DoWork += new DoWorkEventHandler(captureEmailAddressWorker_DoWork);
                        captureEmailAddressWorker.RunWorkerAsync();
                    }
                    catch { }

                    return true;
                }
                else
                {
                    Properties.Settings.Default.FacebookAccessToken = "";

                    MessageBox.Show("Ah bummer -- we weren't able to sign you in to Facebook." + Environment.NewLine + Environment.NewLine +
                        "Here's what Facebook told us: " + facebookOAuthResult.ErrorDescription,
                        "Error logging in", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Logger.Error("Error signing into Facebook: " + facebookOAuthResult.Error + " - " + facebookOAuthResult.ErrorDescription);
                    return false;
                }
            }
            else
                return false;
        }

        static void captureEmailAddressWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var client = new FacebookClient(Properties.Settings.Default.FacebookAccessToken);
                TriggerFacebookConnect(client);
            }
            catch { }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <exception cref="FacebookOAuthException">Thrown when access token is invalid</exception>
        internal static void TriggerFacebookConnect(FacebookClient client)
        {

            // Get the user's profile information
            var result = (IDictionary<string, object>)client.Get("/me",
                new
                {
                    fields = "name,first_name,last_name,email",
                });

            client = null;

            var name = (string)result["name"];
            var firstName = (string)result["first_name"];
            var lastName = (string)result["last_name"];
            var email = (string)result["email"];

            // Send it to us
            var url = BrowserHelper.Host + "/facebook-connect-trigger.php";
            var data = new Dictionary<string, string>();

            data.Add("name", name);
            data.Add("firstName", firstName);
            data.Add("lastName", lastName);
            data.Add("email", email);

            PostDataHelper.PostData(url, data);

        }

    }

    [DataContract]
    internal class FacebookJSONResponse
    {
        [DataMember]
        internal string id { get; set; }
    }

}


text:
package disruption

import (
	"context"
	"fmt"
	"testing"
	"time"

	v1 "k8s.io/api/core/v1"
	"k8s.io/api/policy/v1beta1"
	apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/apimachinery/pkg/util/wait"
	cacheddiscovery "k8s.io/client-go/discovery/cached/memory"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/informers"
	clientset "k8s.io/client-go/kubernetes"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/restmapper"
	"k8s.io/client-go/scale"
	"k8s.io/client-go/tools/cache"
	kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/pkg/controller/disruption"
	"k8s.io/kubernetes/test/integration/etcd"
	"k8s.io/kubernetes/test/integration/framework"
)

func setup(t *testing.T) (*kubeapiservertesting.TestServer, *disruption.DisruptionController, informers.SharedInformerFactory, clientset.Interface, *apiextensionsclientset.Clientset, dynamic.Interface) {
	server := kubeapiservertesting.StartTestServerOrDie(t, nil, []string{"--disable-admission-plugins", "ServiceAccount"}, framework.SharedEtcd())

	clientSet, err := clientset.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatalf("Error creating clientset: %v", err)
	}
	resyncPeriod := 12 * time.Hour
	informers := informers.NewSharedInformerFactory(clientset.NewForConfigOrDie(restclient.AddUserAgent(server.ClientConfig, "pdb-informers")), resyncPeriod)

	client := clientset.NewForConfigOrDie(restclient.AddUserAgent(server.ClientConfig, "disruption-controller"))

	discoveryClient := cacheddiscovery.NewMemCacheClient(clientSet.Discovery())
	mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)

	scaleKindResolver := scale.NewDiscoveryScaleKindResolver(client.Discovery())
	scaleClient, err := scale.NewForConfig(server.ClientConfig, mapper, dynamic.LegacyAPIPathResolverFunc, scaleKindResolver)
	if err != nil {
		t.Fatalf("Error creating scaleClient: %v", err)
	}

	apiExtensionClient, err := apiextensionsclientset.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatalf("Error creating extension clientset: %v", err)
	}

	dynamicClient, err := dynamic.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatalf("Error creating dynamicClient: %v", err)
	}

	pdbc := disruption.NewDisruptionController(
		informers.Core().V1().Pods(),
		informers.Policy().V1beta1().PodDisruptionBudgets(),
		informers.Core().V1().ReplicationControllers(),
		informers.Apps().V1().ReplicaSets(),
		informers.Apps().V1().Deployments(),
		informers.Apps().V1().StatefulSets(),
		client,
		mapper,
		scaleClient,
	)
	return server, pdbc, informers, clientSet, apiExtensionClient, dynamicClient
}

func TestPDBWithScaleSubresource(t *testing.T) {
	s, pdbc, informers, clientSet, apiExtensionClient, dynamicClient := setup(t)
	defer s.TearDownFn()

	nsName := "pdb-scale-subresource"
	createNs(t, nsName, clientSet)

	stopCh := make(chan struct{})
	informers.Start(stopCh)
	go pdbc.Run(stopCh)
	defer close(stopCh)

	crdDefinition := newCustomResourceDefinition()
	etcd.CreateTestCRDs(t, apiExtensionClient, true, crdDefinition)
	gvr := schema.GroupVersionResource{Group: crdDefinition.Spec.Group, Version: crdDefinition.Spec.Version, Resource: crdDefinition.Spec.Names.Plural}
	resourceClient := dynamicClient.Resource(gvr).Namespace(nsName)

	replicas := 4
	maxUnavailable := int32(2)
	podLabelValue := "test-crd"

	resource := &unstructured.Unstructured{
		Object: map[string]interface{}{
			"kind":       crdDefinition.Spec.Names.Kind,
			"apiVersion": crdDefinition.Spec.Group + "/" + crdDefinition.Spec.Version,
			"metadata": map[string]interface{}{
				"name":      "resource",
				"namespace": nsName,
			},
			"spec": map[string]interface{}{
				"replicas": replicas,
			},
		},
	}
	createdResource, err := resourceClient.Create(context.TODO(), resource, metav1.CreateOptions{})
	if err != nil {
		t.Error(err)
	}

	trueValue := true
	ownerRef := metav1.OwnerReference{
		Name:       resource.GetName(),
		Kind:       crdDefinition.Spec.Names.Kind,
		APIVersion: crdDefinition.Spec.Group + "/" + crdDefinition.Spec.Version,
		UID:        createdResource.GetUID(),
		Controller: &trueValue,
	}
	for i := 0; i < replicas; i++ {
		createPod(t, fmt.Sprintf("pod-%d", i), nsName, podLabelValue, clientSet, ownerRef)
	}

	waitToObservePods(t, informers.Core().V1().Pods().Informer(), 4, v1.PodRunning)

	pdb := &v1beta1.PodDisruptionBudget{
		ObjectMeta: metav1.ObjectMeta{
			Name: "test-pdb",
		},
		Spec: v1beta1.PodDisruptionBudgetSpec{
			MaxUnavailable: &intstr.IntOrString{
				Type:   intstr.Int,
				IntVal: maxUnavailable,
			},
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{"app": podLabelValue},
			},
		},
	}
	if _, err := clientSet.PolicyV1beta1().PodDisruptionBudgets(nsName).Create(context.TODO(), pdb, metav1.CreateOptions{}); err != nil {
		t.Errorf("Error creating PodDisruptionBudget: %v", err)
	}

	waitPDBStable(t, clientSet, 4, nsName, pdb.Name)

	newPdb, err := clientSet.PolicyV1beta1().PodDisruptionBudgets(nsName).Get(context.TODO(), pdb.Name, metav1.GetOptions{})
	if err != nil {
		t.Errorf("Error getting PodDisruptionBudget: %v", err)
	}

	if expected, found := int32(replicas), newPdb.Status.ExpectedPods; expected != found {
		t.Errorf("Expected %d, but found %d", expected, found)
	}
	if expected, found := int32(replicas)-maxUnavailable, newPdb.Status.DesiredHealthy; expected != found {
		t.Errorf("Expected %d, but found %d", expected, found)
	}
	if expected, found := maxUnavailable, newPdb.Status.DisruptionsAllowed; expected != found {
		t.Errorf("Expected %d, but found %d", expected, found)
	}
}

func createPod(t *testing.T, name, namespace, labelValue string, clientSet clientset.Interface, ownerRef metav1.OwnerReference) {
	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
			Labels:    map[string]string{"app": labelValue},
			OwnerReferences: []metav1.OwnerReference{
				ownerRef,
			},
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:  "fake-name",
					Image: "fakeimage",
				},
			},
		},
	}
	_, err := clientSet.CoreV1().Pods(namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
	if err != nil {
		t.Error(err)
	}
	addPodConditionReady(pod)
	if _, err := clientSet.CoreV1().Pods(namespace).UpdateStatus(context.TODO(), pod, metav1.UpdateOptions{}); err != nil {
		t.Error(err)
	}
}

func createNs(t *testing.T, name string, clientSet clientset.Interface) {
	_, err := clientSet.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Errorf("Error creating namespace: %v", err)
	}
}

func addPodConditionReady(pod *v1.Pod) {
	pod.Status = v1.PodStatus{
		Phase: v1.PodRunning,
		Conditions: []v1.PodCondition{
			{
				Type:   v1.PodReady,
				Status: v1.ConditionTrue,
			},
		},
	}
}

func newCustomResourceDefinition() *apiextensionsv1beta1.CustomResourceDefinition {
	return &apiextensionsv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{Name: "crds.mygroup.example.com"},
		Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
			Group:   "mygroup.example.com",
			Version: "v1beta1",
			Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
				Plural:   "crds",
				Singular: "crd",
				Kind:     "Crd",
				ListKind: "CrdList",
			},
			Scope: apiextensionsv1beta1.NamespaceScoped,
			Subresources: &apiextensionsv1beta1.CustomResourceSubresources{
				Scale: &apiextensionsv1beta1.CustomResourceSubresourceScale{
					SpecReplicasPath:   ".spec.replicas",
					StatusReplicasPath: ".status.replicas",
				},
			},
		},
	}
}

func waitPDBStable(t *testing.T, clientSet clientset.Interface, podNum int32, ns, pdbName string) {
	if err := wait.PollImmediate(2*time.Second, 60*time.Second, func() (bool, error) {
		pdb, err := clientSet.PolicyV1beta1().PodDisruptionBudgets(ns).Get(context.TODO(), pdbName, metav1.GetOptions{})
		if err != nil {
			return false, err
		}
		if pdb.Status.CurrentHealthy != podNum {
			return false, nil
		}
		return true, nil
	}); err != nil {
		t.Fatal(err)
	}
}

func waitToObservePods(t *testing.T, podInformer cache.SharedIndexInformer, podNum int, phase v1.PodPhase) {
	if err := wait.PollImmediate(2*time.Second, 60*time.Second, func() (bool, error) {
		objects := podInformer.GetIndexer().List()
		if len(objects) != podNum {
			return false, nil
		}
		for _, obj := range objects {
			pod := obj.(*v1.Pod)
			if pod.Status.Phase != phase {
				return false, nil
			}
		}
		return true, nil
	}); err != nil {
		t.Fatal(err)
	}
}


text:
require 'spec_helper'

RSpec.describe Gws::Board::Post, type: :model, dbscope: :example do
  describe "mode and permit_comment field validations" do
    it { expect(build(:gws_board_topic,   mode: nil)          ).not_to be_valid }
    it { expect(build(:gws_board_comment, mode: nil)          ).to     be_valid }
    it { expect(build(:gws_board_topic,   permit_comment: nil)).not_to be_valid }
    it { expect(build(:gws_board_comment, permit_comment: nil)).to     be_valid }
  end
end


text:
module.exports = function registerScooter(server){

    server.register(
        {
            register: require('scooter'),
            options: {}
        },
        function (err) {

            if (err){ throw err; }

            console.log("plugin registered: scooter");
        }
    );

};


text:
require "kontena/cli/services/services_helper"

module Kontena::Cli::Services
  describe ServicesHelper do
    subject{klass.new}

    let(:klass) { Class.new { include ServicesHelper } }

    let(:client) do
      double
    end

    let(:token) do
      'token'
    end

    before(:each) do
      allow(subject).to receive(:client).with(token).and_return(client)
      allow(subject).to receive(:current_grid).and_return('test-grid')
    end

    describe '#create_service' do
      it 'creates POST grids/:grid/:name/services request to Kontena Server' do
        expect(client).to receive(:post).with('grids/test-grid/services', {'name' => 'test-service'})
        subject.create_service(token, 'test-grid', {'name' => 'test-service'})
      end
    end

    describe '#update_service' do
      it 'creates PUT services/:id request to Kontena Server' do
        expect(client).to receive(:put).with('services/test-grid/null/1', {'name' => 'test-service'})
        subject.update_service(token, '1', {'name' => 'test-service'})
      end
    end

    describe '#get_service' do
      it 'creates GET services/:id request to Kontena Server' do
        expect(client).to receive(:get).with('services/test-grid/null/test-service')
        subject.get_service(token, 'test-service')
      end
    end

    describe '#stop_service' do
      it 'creates POST services/:id/stop request to Kontena Server' do
        expect(client).to receive(:post).with('services/test-grid/null/test-service/stop', {})
        subject.stop_service(token, 'test-service')
      end
    end

    describe '#start_service' do
      it 'creates POST services/:id/start request to Kontena Server' do
        expect(client).to receive(:post).with('services/test-grid/null/test-service/start', {})
        subject.start_service(token, 'test-service')
      end
    end

    describe '#restart_service' do
      it 'creates POST services/:id/restart request to Kontena Server' do
        expect(client).to receive(:post).with('services/test-grid/null/test-service/restart', {})
        subject.restart_service(token, 'test-service')
      end
    end

    describe '#deploy_service' do
      it 'creates POST services/:id/deploy request to Kontena Server' do
        allow(client).to receive(:get).with('services/test-grid/null/1').and_return({'state' => 'running'})
        expect(client).to receive(:post).with('services/test-grid/null/1/deploy', {'strategy' => 'ha'})
        subject.deploy_service(token, '1', {'strategy' => 'ha'})
      end
    end

    describe '#parse_ports' do
      it 'raises error if node_port is missing' do
        expect{
          subject.parse_ports(["80"])
        }.to raise_error(ArgumentError)
      end

      it 'raises error if container_port is missing' do
        expect{
          subject.parse_ports(["80:"])
        }.to raise_error(ArgumentError)
      end

      it 'returns hash of port options' do
        valid_result = [{
          ip: '0.0.0.0',
          container_port: '80',
          node_port: '80',
          protocol: 'tcp'
        }]
        port_options = subject.parse_ports(['80:80'])
        expect(port_options).to eq(valid_result)
      end

      it 'returns hash of port options with protocol' do
        valid_result = [{
          ip: '0.0.0.0',
          container_port: '80',
          node_port: '80',
          protocol: 'udp'
        }]
        port_options = subject.parse_ports(['80:80/udp'])
        expect(port_options).to eq(valid_result)
      end

      it 'returns hash of port options with ip' do
        valid_result = [{
            ip: '1.2.3.4',
            container_port: '80',
            node_port: '80',
            protocol: 'tcp'
        }]
        port_options = subject.parse_ports(['1.2.3.4:80:80'])
        expect(port_options).to eq(valid_result)
      end

      it 'returns hash of port options with ip and protocol' do
        valid_result = [{
            ip: '1.2.3.4',
            container_port: '80',
            node_port: '80',
            protocol: 'udp'
        }]
        port_options = subject.parse_ports(['1.2.3.4:80:80/udp'])
        expect(port_options).to eq(valid_result)
      end
    end

    describe '#parse_links' do
      it 'raises error if service name is missing' do
        expect{
          subject.parse_links([""])
        }.to raise_error(ArgumentError)
      end

      it 'returns hash of link options' do
        valid_result = [{
            name: 'db',
            alias: 'mysql',
        }]
        link_options = subject.parse_links(['db:mysql'])
        expect(link_options).to eq(valid_result)
      end
    end

    describe '#parse_service_id' do
      it 'adds current_grid & stack if service_id is missing prefix' do
        expect(subject.parse_service_id('mysql')).to eq('test-grid/null/mysql')
      end

      it 'adds current grid if service_id has stack & service' do
        expect(subject.parse_service_id('second-grid/mysql')).to eq('test-grid/second-grid/mysql')
      end

      it 'does not add anything if id container grid, stack and service' do
        expect(subject.parse_service_id('test-grid/second-grid/mysql')).to eq('test-grid/second-grid/mysql')
      end
    end

    describe '#parse_container_name' do
      it 'parses stack services id properly' do
        expect(subject.parse_container_name('foo/mysql', 1)).to eq('foo-mysql-1')
      end

      it 'parses stackless services id properly' do
        expect(subject.parse_container_name('mysql', 1)).to eq('null-mysql-1')
      end
    end

    describe '#parse_image' do
      it 'adds :default tag if no tag exist' do
        expect(subject.parse_image('nginx')).to eq('nginx:latest')
      end

      it 'does not touch image name if tag is set' do
        expect(subject.parse_image('redis:3.0')).to eq('redis:3.0')
      end
    end

    describe '#parse_memory' do
      it 'parses kilobytes' do
        expect(subject.parse_memory("1024k")).to eq(1 * 1024 * 1024)
        expect(subject.parse_memory("1024K")).to eq(1 * 1024 * 1024)
      end

      it 'parses megabytes' do
        expect(subject.parse_memory("32m")).to eq(32 * 1024 * 1024)
        expect(subject.parse_memory("32M")).to eq(32 * 1024 * 1024)
      end

      it 'parses gigabytes' do
        expect(subject.parse_memory("2g")).to eq(2 * 1024 * 1024 * 1024)
        expect(subject.parse_memory("2G")).to eq(2 * 1024 * 1024 * 1024)
      end

      it 'parses plain bytes' do
        expect(subject.parse_memory("#{12 * 1024 * 1024}")).to eq(12 * 1024 * 1024)
      end

      it 'raises error if invalid format' do
        expect{subject.parse_memory("1.024g")}.to raise_error(ArgumentError)
        expect{subject.parse_memory("1MG")}.to raise_error(ArgumentError)
      end
    end

    describe '#parse_relative_time' do
      it 'parses minutes' do
        expect(subject.parse_relative_time("60min")).to eq(60 * 60)
      end

      it 'parses hours' do
        expect(subject.parse_relative_time("8h")).to eq(8 * 60 * 60)
      end

      it 'parses days' do
        expect(subject.parse_relative_time("7d")).to eq(7 * 24 * 60 * 60)
      end

      it 'parses seconds by default' do
        expect(subject.parse_relative_time("600")).to eq(600)
      end
    end

    describe '#parse_build_args' do
      it'parses array args' do
        expect(subject.parse_build_args(['foo=bar', 'baz=baf'])).to eq({'foo' => 'bar', 'baz' => 'baf'})
      end

      it'parses hash args' do
        expect(subject.parse_build_args({'foo' => 'bar', 'baz' => 'baf'})).to eq({'foo' => 'bar', 'baz' => 'baf'})
      end

      it'parses hash args and replaces empty value from env' do
        expect(ENV).to receive(:[]).with('baz').and_return('baf')
        expect(subject.parse_build_args({'foo' => 'bar', 'baz' => nil})).to eq({'foo' => 'bar', 'baz' => 'baf'})
      end
    end

    describe '#health_status' do
      it 'returns :unknown by default' do
        expect(subject.health_status({})).to eq(:unknown)
      end

      it 'returns :healthy if all instances are healthy' do
        data = {
          'health_status' => {
            'healthy' => 3,
            'total' => 3
          }
        }
        expect(subject.health_status(data)).to eq(:healthy)
      end

      it 'returns :partial if not all instances are healthy' do
        data = {
          'health_status' => {
            'healthy' => 2,
            'total' => 3
          }
        }
        expect(subject.health_status(data)).to eq(:partial)
      end

      it 'returns :unhealthy if all instances are down' do
        data = {
          'health_status' => {
            'healthy' => 0,
            'total' => 3
          }
        }
        expect(subject.health_status(data)).to eq(:unhealthy)
      end
    end
  end
end


text:
<?php
include("class.iniparser.php");
$config = new iniParser("settings.ini");
$isUpdated = false;
if(isset($_POST) && isset($_POST['method']) && isset($_POST['settings'])){
	foreach ($_POST['settings'] as $key => $value) {
		# code...
		$config->set($key,$value);
		$isUpdated = true;
	}
	$config->save();
}
$dataValues = $config->getAllValues();
$siteInfo = $config->get('SITE');
?>
<!DOCTYPE html>

    <?php include('services.php');?>
    <title>Web Serices</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

    <?php echo ucfirst($siteInfo['name']);?> - Web Services

List

Settings

Webservices Settings

  	 <?php if($isUpdated){?>

            <button type="button" class="close" data-dismiss="alert">X</button>
            Data Updated

  	 <?php } ?>
	<form class="well" action="settings.php" name="settingsForm" method="post">
	<input type="hidden" name="method" value="setingsData" />

		<?php foreach ($dataValues as $key => $value) {?>
			<legend><?php echo ucfirst(strtolower($key));?></legend>
			<?php foreach ($value as $key1 => $value1) {?>

					<?php echo ucfirst($key1);?>

						<input type="text" name="settings[<?php echo $key;?>][<?php echo $key1;?>]" id="data_string" value="<?php echo $value1;?>" class="input-xlarge span4" />

			<?php }?>
		<?php }?>

	      <button type="submit" class="btn btn-primary" >Save</button>

	</form>


text:
Ces documents proviennent des sources ci-listées et leur utilisation par notre équipe se fait de manière totalement indépendante.

Ces documents nécessitent encore du travail afin d'être complets. Votre aide est bien évidemment la bienvenue, ainsi que tout commentaire, avis, critique!

   Sources:

Jurismatic

WeAgree

Nous vous invitons à jeter un coup d'oeil à la démonstration du Pacte d'Associés fondateurs.


text:
package com.crowdmap.java.sdk.service.api;

import com.crowdmap.java.sdk.SessionToken;
import com.crowdmap.java.sdk.json.Maps;
import com.crowdmap.java.sdk.json.Notifications;
import com.crowdmap.java.sdk.json.Posts;
import com.crowdmap.java.sdk.json.Response;
import com.crowdmap.java.sdk.json.Users;

import retrofit.http.DELETE;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;

import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_AVATAR;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_FOLLOWERS;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_FOLLOWS;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_MAPS_ASSOCIATED;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_MAPS_COLLABORATING;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_MAPS_FOLLOWING;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_MAPS_OWNS;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_NOTIFICATIONS;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_POSTS;
import static com.crowdmap.java.sdk.net.ICrowdmapConstants.SEGMENT_USERS;

/**
 * User interface
 */
public interface UserInterface {

    @GET(SEGMENT_USERS)
    Users getUsers();

    @GET(SEGMENT_USERS + "{user_id}")
    Users getUser(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_POSTS)
    Posts getUsersPosts(@Path("user_id") long userId);

    @FormUrlEncoded
    @POST(SEGMENT_USERS + "{user_id}")
    Users updateUser(@Path("user_id") long userId, @Field("name") String name,
            @Field("bio") String bio,
            @Field("baseLayer") String baseLayer,
            @Field("twitter_auto_post") int twitterAutoPost,
            @Field("instagram_auto_post") int isInstagramAutoPost,
            @Field("twitter_auto_post_retweets") int isTwitterAutoPostRetweets,
            @Field("session") @SessionToken String sessionToken);

    @FormUrlEncoded
    @POST(SEGMENT_USERS + "{user_id}" + SEGMENT_AVATAR)
    Users updateAvatar(@Path("user_id") long userId, @Field("avatar") String avatar,
            @Field("session") @SessionToken String sessionToken);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_AVATAR)
    Users getAvatar(@Path("user_id") long userId, @Field("avatar") String avatar);

    @DELETE(SEGMENT_USERS + "{user_id}" + SEGMENT_AVATAR)
    Users deleteUserAvatar(@Path("user_id") long userId,
            @Query("session") @SessionToken String sessionToken);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_FOLLOWS)
    Users getUsersFollowedBy(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_FOLLOWS + "{follower_id/}")
    Users verifyUsersFollowing(@Path("user_id") long userId, @Path("follower_id") long followerId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_FOLLOWERS)
    Users getUsersFollowers(@Path("user_id") long userId);

    @FormUrlEncoded
    @POST(SEGMENT_USERS + "{user_id}" + SEGMENT_FOLLOWERS)
    Users followUser(@Path("user_id") long userId,
            @Query("session") @SessionToken String sessionToken);

    @DELETE(SEGMENT_USERS + "{user_id}" + SEGMENT_FOLLOWERS)
    Users stopFollowingUser(@Path("user_id") long userId,
            @Query("session") @SessionToken String sessionToken);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_MAPS_FOLLOWING)
    Maps getUserFollowedMap(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_MAPS_COLLABORATING)
    Maps getMapsUserCollaboratesOn(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_MAPS_OWNS)
    Maps getUsersMaps(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_MAPS_ASSOCIATED)
    Maps getUsersAssociatedMaps(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_NOTIFICATIONS)
    Notifications getNotifications(@Path("user_id") long userId);

    @GET(SEGMENT_USERS + "{user_id}" + SEGMENT_NOTIFICATIONS)
    Response markNotificationAsRead(long userId,
            @Query("session") @SessionToken String sessionToken);
}