text:
//*****************************************************************************
//
//  File:       ColorPickerPropertiesProvider.cs
//
//  Contents:   Definition for color picker properties provider
//
//*****************************************************************************

using System;
using System.Drawing;
using RibbonLib.Interop;

namespace RibbonLib.Controls.Properties
{
    /// <summary>
    /// Definition for color picker properties provider interface
    /// </summary>
    public interface IColorPickerPropertiesProvider
    {
        /// <summary>
        /// Automatic color label property
        /// </summary>
        string AutomaticColorLabel { get; set; }

        /// <summary>
        /// Color property
        /// </summary>
        Color Color { get; set; }

        /// <summary>
        /// Color type property
        /// </summary>
        SwatchColorType ColorType { get; set; }

        /// <summary>
        /// More colors label property
        /// </summary>
        string MoreColorsLabel { get; set; }

        /// <summary>
        /// No color label property
        /// </summary>
        string NoColorLabel { get; set; }

        /// <summary>
        /// Recent colors category label property
        /// </summary>
        string RecentColorsCategoryLabel { get; set; }

        /// <summary>
        /// Standard colors property
        /// </summary>
        Color[] StandardColors { get; set; }

        /// <summary>
        /// Standard colors category label property
        /// </summary>
        string StandardColorsCategoryLabel { get; set; }

        /// <summary>
        /// Standard colors tooltips property
        /// </summary>
        string[] StandardColorsTooltips { get; set; }

        /// <summary>
        /// Theme colors property
        /// </summary>
        Color[] ThemeColors { get; set; }

        /// <summary>
        /// Theme colors category label property
        /// </summary>
        string ThemeColorsCategoryLabel { get; set; }

        /// <summary>
        /// Theme colors tooltips property
        /// </summary>
        string[] ThemeColorsTooltips { get; set; }
    }

    /// <summary>
    /// Implementation of IColorPickerPropertiesProvider
    /// </summary>
    public class ColorPickerPropertiesProvider : BasePropertiesProvider, IColorPickerPropertiesProvider
    {
        /// <summary>
        /// ColorPickerPropertiesProvider ctor
        /// </summary>
        /// <param name="ribbon">parent ribbon</param>
        /// <param name="commandId">ribbon control command id</param>
        public ColorPickerPropertiesProvider(Ribbon ribbon, uint commandId)
            : base(ribbon, commandId)
        {
            // add supported properties
            _supportedProperties.Add(RibbonProperties.AutomaticColorLabel);
            _supportedProperties.Add(RibbonProperties.Color);
            _supportedProperties.Add(RibbonProperties.ColorType);
            _supportedProperties.Add(RibbonProperties.MoreColorsLabel);
            _supportedProperties.Add(RibbonProperties.NoColorLabel);
            _supportedProperties.Add(RibbonProperties.RecentColorsCategoryLabel);
            _supportedProperties.Add(RibbonProperties.StandardColors);
            _supportedProperties.Add(RibbonProperties.StandardColorsCategoryLabel);
            _supportedProperties.Add(RibbonProperties.StandardColorsTooltips);
            _supportedProperties.Add(RibbonProperties.ThemeColors);
            _supportedProperties.Add(RibbonProperties.ThemeColorsCategoryLabel);
            _supportedProperties.Add(RibbonProperties.ThemeColorsTooltips);
        }

        private string _automaticColorLabel;
        private Color? _color;
        private SwatchColorType? _colorType;
        private string _moreColorsLabel;
        private string _noColorLabel;
        private string _recentColorsCategoryLabel;
        private Color[] _standardColors;
        private string _standardColorsCategoryLabel;
        private string[] _standardColorsTooltips;
        private Color[] _themeColors;
        private string _themeColorsCategoryLabel;
        private string[] _themeColorsTooltips;

        /// <summary>
        /// Handles IUICommandHandler.UpdateProperty function for the supported properties
        /// </summary>
        /// <param name="key">The Property Key to update</param>
        /// <param name="currentValue">A pointer to the current value for key. This parameter can be NULL</param>
        /// <param name="newValue">When this method returns, contains a pointer to the new value for key</param>
        /// <returns>Returns S_OK if successful, or an error value otherwise</returns>
        public override HRESULT UpdateProperty(ref PropertyKey key, PropVariantRef currentValue, ref PropVariant newValue)
        {
            if (key == RibbonProperties.AutomaticColorLabel)
            {
                if (_automaticColorLabel != null)
                {
                    newValue.SetString(_automaticColorLabel);
                }
            }
            else if (key == RibbonProperties.Color)
            {
                if (_color.HasValue)
                {
                    newValue.SetUInt((uint)ColorTranslator.ToWin32(_color.Value));
                }
            }
            else if (key == RibbonProperties.ColorType)
            {
                if (_colorType.HasValue)
                {
                    newValue.SetUInt((uint)_colorType.Value);
                }
            }
            else if (key == RibbonProperties.MoreColorsLabel)
            {
                if (_moreColorsLabel != null)
                {
                    newValue.SetString(_moreColorsLabel);
                }
            }
            else if (key == RibbonProperties.NoColorLabel)
            {
                if (_noColorLabel != null)
                {
                    newValue.SetString(_noColorLabel);
                }
            }
            else if (key == RibbonProperties.RecentColorsCategoryLabel)
            {
                if (_recentColorsCategoryLabel != null)
                {
                    newValue.SetString(_recentColorsCategoryLabel);
                }
            }
            else if (key == RibbonProperties.StandardColors)
            {
                if (_standardColors != null)
                {
                    int[] intStandardColors = Array.ConvertAll<Color, int>(_standardColors, new Converter<Color, int>(ColorTranslator.ToWin32));
                    uint[] uintStandardColors = Array.ConvertAll<int, uint>(intStandardColors, new Converter<int, uint>(Convert.ToUInt32));
                    newValue.SetUIntVector(uintStandardColors);
                }
            }
            else if (key == RibbonProperties.StandardColorsCategoryLabel)
            {
                if (_standardColorsCategoryLabel != null)
                {
                    newValue.SetString(_standardColorsCategoryLabel);
                }
            }
            else if (key == RibbonProperties.StandardColorsTooltips)
            {
                if (_standardColorsTooltips != null)
                {
                    newValue.SetStringVector(_standardColorsTooltips);
                }
            }
            else if (key == RibbonProperties.ThemeColors)
            {
                if (_themeColors != null)
                {
                    int[] intThemeColors = Array.ConvertAll<Color, int>(_themeColors, new Converter<Color, int>(ColorTranslator.ToWin32));
                    uint[] uintThemeColors = Array.ConvertAll<int, uint>(intThemeColors, new Converter<int, uint>(Convert.ToUInt32));
                    newValue.SetUIntVector(uintThemeColors);
                }
            }
            else if (key == RibbonProperties.ThemeColorsCategoryLabel)
            {
                if (_themeColorsCategoryLabel != null)
                {
                    newValue.SetString(_themeColorsCategoryLabel);
                }
            }
            else if (key == RibbonProperties.ThemeColorsTooltips)
            {
                if (_themeColorsTooltips != null)
                {
                    newValue.SetStringVector(_themeColorsTooltips);
                }
            }

            return HRESULT.S_OK;
        }

        #region IColorPickerPropertiesProvider Members

        /// <summary>
        /// Automatic color label property
        /// </summary>
        public string AutomaticColorLabel
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant automaticColorLabel;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.AutomaticColorLabel, out automaticColorLabel);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string)automaticColorLabel.Value;
                    }
                }

                return _automaticColorLabel;
            }
            set
            {
                _automaticColorLabel = value;
                if (_ribbon.Initalized)
                {
                    PropVariant automaticColorLabel;
                    if ((_automaticColorLabel == null) || (_automaticColorLabel.Trim() == string.Empty))
                    {
                        automaticColorLabel = PropVariant.Empty;
                    }
                    else
                    {
                        automaticColorLabel = PropVariant.FromObject(_automaticColorLabel);
                    }
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.AutomaticColorLabel, ref automaticColorLabel);
                }
            }
        }

        /// <summary>
        /// Color property
        /// </summary>
        public Color Color
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant color;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.Color, out color);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return ColorTranslator.FromWin32((int)(uint)color.Value);
                    }
                }

                return _color.GetValueOrDefault();
            }
            set
            {
                _color = value;
                if (_ribbon.Initalized)
                {
                    PropVariant color = PropVariant.FromObject((uint)ColorTranslator.ToWin32(value));
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.Color, ref color);
                }
            }
        }

        /// <summary>
        /// Color type property
        /// </summary>
        public SwatchColorType ColorType
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant colorType;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.ColorType, out colorType);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (SwatchColorType)colorType.Value;
                    }
                }

                return _colorType.GetValueOrDefault();
            }
            set
            {
                _colorType = value;
                if (_ribbon.Initalized)
                {
                    PropVariant colorType = PropVariant.FromObject((uint)value);
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.ColorType, ref colorType);
                }
            }
        }

        /// <summary>
        /// More colors label property
        /// </summary>
        public string MoreColorsLabel
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant moreColorsLabel;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.MoreColorsLabel, out moreColorsLabel);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string)moreColorsLabel.Value;
                    }
                }

                return _moreColorsLabel;
            }
            set
            {
                _moreColorsLabel = value;
                if (_ribbon.Initalized)
                {
                    PropVariant moreColorsLabel;
                    if ((_moreColorsLabel == null) || (_moreColorsLabel.Trim() == string.Empty))
                    {
                        moreColorsLabel = PropVariant.Empty;
                    }
                    else
                    {
                        moreColorsLabel = PropVariant.FromObject(_moreColorsLabel);
                    }
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.MoreColorsLabel, ref moreColorsLabel);
                }
            }
        }

        /// <summary>
        /// No color label property
        /// </summary>
        public string NoColorLabel
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant noColorLabel;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.NoColorLabel, out noColorLabel);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string)noColorLabel.Value;
                    }
                }

                return _noColorLabel;
            }
            set
            {
                _noColorLabel = value;
                if (_ribbon.Initalized)
                {
                    PropVariant noColorLabel;
                    if ((_noColorLabel == null) || (_noColorLabel.Trim() == string.Empty))
                    {
                        noColorLabel = PropVariant.Empty;
                    }
                    else
                    {
                        noColorLabel = PropVariant.FromObject(_noColorLabel);
                    }
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.NoColorLabel, ref noColorLabel);
                }
            }
        }

        /// <summary>
        /// Recent colors category label property
        /// </summary>
        public string RecentColorsCategoryLabel
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant recentColorsCategoryLabel;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.RecentColorsCategoryLabel, out recentColorsCategoryLabel);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string)recentColorsCategoryLabel.Value;
                    }
                }

                return _recentColorsCategoryLabel;
            }
            set
            {
                _recentColorsCategoryLabel = value;
                if (_ribbon.Initalized)
                {
                    PropVariant recentColorsCategoryLabel;
                    if ((_recentColorsCategoryLabel == null) || (_recentColorsCategoryLabel.Trim() == string.Empty))
                    {
                        recentColorsCategoryLabel = PropVariant.Empty;
                    }
                    else
                    {
                        recentColorsCategoryLabel = PropVariant.FromObject(_recentColorsCategoryLabel);
                    }
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.RecentColorsCategoryLabel, ref recentColorsCategoryLabel);
                }
            }
        }

        /// <summary>
        /// Standard colors property
        /// </summary>
        public Color[] StandardColors
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant standardColors;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.StandardColors, out standardColors);
                    if (NativeMethods.Succeeded(hr))
                    {
                        uint[] uintStandardColors = (uint[])standardColors.Value;
                        int[] intStandardColors = Array.ConvertAll<uint, int>(uintStandardColors, new Converter<uint, int>(Convert.ToInt32));
                        Color[] colorStandardColors = Array.ConvertAll<int, Color>(intStandardColors, new Converter<int, Color>(ColorTranslator.FromWin32));
                        return colorStandardColors;
                    }
                }

                return _standardColors;
            }
            set
            {
                _standardColors = value;
                if (_ribbon.Initalized)
                {
                    int[] intStandardColors = Array.ConvertAll<Color, int>(_standardColors, new Converter<Color, int>(ColorTranslator.ToWin32));
                    uint[] uintStandardColors = Array.ConvertAll<int, uint>(intStandardColors, new Converter<int, uint>(Convert.ToUInt32));

                    PropVariant standardColors = PropVariant.FromObject(uintStandardColors);
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.StandardColors, ref standardColors);
                }
            }
        }

        /// <summary>
        /// Standard colors category label property
        /// </summary>
        public string StandardColorsCategoryLabel
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant standardColorsCategoryLabel;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.StandardColorsCategoryLabel, out standardColorsCategoryLabel);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string)standardColorsCategoryLabel.Value;
                    }
                }

                return _standardColorsCategoryLabel;
            }
            set
            {
                _standardColorsCategoryLabel = value;
                if (_ribbon.Initalized)
                {
                    PropVariant standardColorsCategoryLabel;
                    if ((_standardColorsCategoryLabel == null) || (_standardColorsCategoryLabel.Trim() == string.Empty))
                    {
                        standardColorsCategoryLabel = PropVariant.Empty;
                    }
                    else
                    {
                        standardColorsCategoryLabel = PropVariant.FromObject(_standardColorsCategoryLabel);
                    }
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.StandardColorsCategoryLabel, ref standardColorsCategoryLabel);
                }
            }
        }

        /// <summary>
        /// Standard colors tooltips property
        /// </summary>
        public string[] StandardColorsTooltips
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant standardColorsTooltips;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.StandardColorsTooltips, out standardColorsTooltips);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string[])standardColorsTooltips.Value;
                    }
                }

                return _standardColorsTooltips;
            }
            set
            {
                _standardColorsTooltips = value;
                if (_ribbon.Initalized)
                {
                    PropVariant standardColorsTooltips = PropVariant.FromObject(value);
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.StandardColorsTooltips, ref standardColorsTooltips);
                }
            }
        }

        /// <summary>
        /// Theme colors property
        /// </summary>
        public Color[] ThemeColors
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant themeColors;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.ThemeColors, out themeColors);
                    if (NativeMethods.Succeeded(hr))
                    {
                        uint[] uintThemeColors = (uint[])themeColors.Value;
                        int[] intThemeColors = Array.ConvertAll<uint, int>(uintThemeColors, new Converter<uint, int>(Convert.ToInt32));
                        Color[] colorThemeColors = Array.ConvertAll<int, Color>(intThemeColors, new Converter<int, Color>(ColorTranslator.FromWin32));
                        return colorThemeColors;
                    }
                }

                return _themeColors;
            }
            set
            {
                _themeColors = value;
                if (_ribbon.Initalized)
                {
                    int[] intThemeColors = Array.ConvertAll<Color, int>(_themeColors, new Converter<Color, int>(ColorTranslator.ToWin32));
                    uint[] uintThemeColors = Array.ConvertAll<int, uint>(intThemeColors, new Converter<int, uint>(Convert.ToUInt32));

                    PropVariant themeColors = PropVariant.FromObject(uintThemeColors);
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.ThemeColors, ref themeColors);
                }
            }
        }

        /// <summary>
        /// Theme colors category label property
        /// </summary>
        public string ThemeColorsCategoryLabel
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant themeColorsCategoryLabel;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.ThemeColorsCategoryLabel, out themeColorsCategoryLabel);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string)themeColorsCategoryLabel.Value;
                    }
                }

                return _themeColorsCategoryLabel;
            }
            set
            {
                _themeColorsCategoryLabel = value;
                if (_ribbon.Initalized)
                {
                    PropVariant themeColorsCategoryLabel;
                    if ((_themeColorsCategoryLabel == null) || (_themeColorsCategoryLabel.Trim() == string.Empty))
                    {
                        themeColorsCategoryLabel = PropVariant.Empty;
                    }
                    else
                    {
                        themeColorsCategoryLabel = PropVariant.FromObject(_themeColorsCategoryLabel);
                    }
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.ThemeColorsCategoryLabel, ref themeColorsCategoryLabel);
                }
            }
        }

        /// <summary>
        /// Theme colors tooltips property
        /// </summary>
        public string[] ThemeColorsTooltips
        {
            get
            {
                if (_ribbon.Initalized)
                {
                    PropVariant themeColorsTooltips;
                    HRESULT hr = _ribbon.Framework.GetUICommandProperty(_commandID, ref RibbonProperties.ThemeColorsTooltips, out themeColorsTooltips);
                    if (NativeMethods.Succeeded(hr))
                    {
                        return (string[])themeColorsTooltips.Value;
                    }
                }

                return _themeColorsTooltips;
            }
            set
            {
                _themeColorsTooltips = value;
                if (_ribbon.Initalized)
                {
                    PropVariant themeColorsTooltips = PropVariant.FromObject(value);
                    HRESULT hr = _ribbon.Framework.SetUICommandProperty(_commandID, ref RibbonProperties.ThemeColorsTooltips, ref themeColorsTooltips);
                }
            }
        }

        #endregion
    }
}


text:
package com.coveros.selenified;

import com.coveros.selenified.Browser.BrowserName;
import com.coveros.selenified.exceptions.InvalidBrowserException;
import com.coveros.selenified.exceptions.InvalidBrowserOptionsException;
import com.coveros.selenified.exceptions.InvalidProxyException;
import com.coveros.selenified.utilities.Property;
import com.coveros.selenified.utilities.Sauce;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.opera.OperaOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;

import static com.coveros.selenified.utilities.Property.HEADLESS;
import static com.coveros.selenified.utilities.Reporter.ENABLED_LOGS;

/**
 * Assists with Selenified class in setting up proxy, hub, and browser details
 *
 * @author Max Saperstone
 * @version 3.3.1
 * @lastupdate 3/29/2019
 */
public class Capabilities {

    private Browser browser;
    private int instance = 0;
    private DesiredCapabilities desiredCapabilities;

    /**
     * A constructor which sets up the browser, and default desiredCapabilities, based on the browser, and information
     * passed in from the command line
     */
    public Capabilities(Browser browser) throws InvalidBrowserException, InvalidProxyException {
        if (browser == null) {
            throw new InvalidBrowserException("A valid browser was not provided");
        }
        this.browser = browser;
        this.desiredCapabilities = new DesiredCapabilities();
        setDesiredCapabilities();
    }

    private void setDesiredCapabilities() throws InvalidProxyException {
        if (browser.getName() == BrowserName.NONE) {
            return;
        }
        //clean up console logging
        java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.SEVERE);
        System.setProperty("webdriver." + browser.getName().toString().toLowerCase() + ".silentOutput", "true");
        //turn on browser logging
        LoggingPreferences logPrefs = new LoggingPreferences();
        for (String logType : ENABLED_LOGS) {
            logPrefs.enable(logType, Level.ALL);
        }
        this.desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
        // by default, accept insecure sites - there are some exceptions for browsers
        this.desiredCapabilities.setAcceptInsecureCerts(true);
        // setup our browser name based on the enum provided - there are a few special cases
        this.desiredCapabilities.setBrowserName(browser.getName().toString().toLowerCase());
        // the default platform is any, unless the browser is platform specific - this can be overridden
        switch (browser.getName()) {
            case INTERNETEXPLORER:
                this.desiredCapabilities.setBrowserName("internet explorer");
                this.desiredCapabilities.setPlatform(Platform.WINDOWS);
                this.desiredCapabilities.setAcceptInsecureCerts(false);
                break;
            case EDGE:
                this.desiredCapabilities.setBrowserName("MicrosoftEdge");
                this.desiredCapabilities.setPlatform(Platform.WIN10);
                break;
            case SAFARI:
                this.desiredCapabilities.setPlatform(Platform.MOJAVE);
                // Safari 12 doesn't support setAcceptInsecureCerts, and there is no current workaround
                if ("12".equals(browser.getVersion()) || browser.getVersion() == null) {
                    this.desiredCapabilities.setAcceptInsecureCerts(false);
                }
                break;
            default:
                this.desiredCapabilities.setPlatform(Platform.ANY);
        }
        if (browser.getPlatform() != null) {
            this.desiredCapabilities.setPlatform(browser.getPlatform());
        }
        // the default version is empty - this can be overridden
        this.desiredCapabilities.setVersion("");
        if (browser.getVersion() != null) {
            this.desiredCapabilities.setVersion(browser.getVersion());
        }
        // only include the screen resolution is in width x height format
        if (browser.getScreensize() != null && browser.getScreensize().matches("(\\d+)x(\\d+)")) {
            this.desiredCapabilities.setCapability("screenResolution", browser.getScreensize());
        }
        // always enable javascript, accept certs, and start with a clean session
        this.desiredCapabilities.setJavascriptEnabled(true);
        this.desiredCapabilities.setCapability("ensureCleanSession", true);
        // setup additional non-browser capabilities
        setupProxy();
        Sauce.setupSauceCapabilities(desiredCapabilities);
    }

    /**
     * returns the classes defined desired desiredCapabilities
     *
     * @return DesiredCapabilities
     */
    public DesiredCapabilities getDesiredCapabilities() {
        return desiredCapabilities;
    }

    /**
     * returns the classes defined all browser details
     *
     * @return Browser - the browser with details
     */
    public Browser getBrowser() {
        return browser;
    }

    /**
     * Sets the instances of the test running. This references the invocation count from TestNG, allowing looping, and
     * specifies which test run this is
     *
     * @param instance - the number instance of the test being run, to track capabilities
     */
    void setInstance(int instance) {
        this.instance = instance;
    }

    /**
     * Retrieves the instance of the test running. This references the invocation count from TestNG, allowing looping,
     * and specifies which test run this is
     *
     * @return Integer
     */
    public int getInstance() {
        return instance;
    }

    /**
     * Obtains the set system values for the proxy, and adds them to the desired
     * desiredCapabilities
     */
    public void setupProxy() throws InvalidProxyException {
        // are we running through a proxy
        if (Property.isProxySet()) {
            // set the proxy information
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(Property.getProxy());
            desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
        }
    }

    /**
     * this creates the webdriver object, which will be used to interact with
     * for all browser web tests
     *
     * @return WebDriver: the driver to interact with for the test
     */
    public WebDriver setupDriver() throws InvalidBrowserException {
        WebDriver driver;
        // check the browser
        switch (browser.getName()) {
            case HTMLUNIT:
                System.getProperties().put("org.apache.commons.logging.simplelog.defaultlog", "fatal");
                java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
                java.util.logging.Logger.getLogger("org.apache.http").setLevel(Level.OFF);
                driver = new HtmlUnitDriver(desiredCapabilities);
                break;
            case FIREFOX:
                WebDriverManager.firefoxdriver().forceCache().setup();
                FirefoxOptions firefoxOptions = new FirefoxOptions(desiredCapabilities);
                firefoxOptions.addArguments(getBrowserOptions());
                if (Property.runHeadless()) {
                    firefoxOptions.setHeadless(true);
                }
                driver = new FirefoxDriver(firefoxOptions);
                break;
            case CHROME:
                WebDriverManager.chromedriver().forceCache().setup();
                ChromeOptions chromeOptions = new ChromeOptions();
                chromeOptions = chromeOptions.merge(desiredCapabilities);
                chromeOptions.addArguments(getBrowserOptions());
                if (Property.runHeadless()) {
                    chromeOptions.setHeadless(true);
                }
                driver = new ChromeDriver(chromeOptions);
                break;
            case INTERNETEXPLORER:
                WebDriverManager.iedriver().forceCache().setup();
                InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions(desiredCapabilities);
                driver = new InternetExplorerDriver(internetExplorerOptions);
                break;
            case EDGE:
                WebDriverManager.edgedriver().forceCache().setup();
                EdgeOptions edgeOptions = new EdgeOptions();
                edgeOptions = edgeOptions.merge(desiredCapabilities);
                driver = new EdgeDriver(edgeOptions);
                break;
            case SAFARI:
                SafariOptions safariOptions = new SafariOptions(desiredCapabilities);
                driver = new SafariDriver(safariOptions);
                break;
            case OPERA:
                WebDriverManager.operadriver().forceCache().setup();
                OperaOptions operaOptions = new OperaOptions();
                operaOptions = operaOptions.merge(desiredCapabilities);
                driver = new OperaDriver(operaOptions);
                break;
            case PHANTOMJS:
                WebDriverManager.phantomjs().forceCache().setup();
                driver = new PhantomJSDriver(desiredCapabilities);
                break;
            // if the browser is not listed, throw an error
            default:
                throw new InvalidBrowserException(
                        "The selected browser " + browser.getName() + " is not an applicable choice");
        }
        return driver;
    }

    private List<String> getBrowserOptions() throws InvalidBrowserOptionsException {
        ArrayList<String> browserOptions = new ArrayList<>();
        if (Property.areOptionsSet()) {
            browserOptions = new ArrayList(Arrays.asList(Property.getOptions().split("\\s*,\\s*")));
        }
        if (browser.getName() == BrowserName.CHROME && browserOptions.contains("--headless")) {
            browserOptions.remove("--headless");
            System.setProperty(HEADLESS, "true");
        }
        if (browser.getName() == BrowserName.FIREFOX && browserOptions.contains("-headless")) {
            browserOptions.remove("-headless");
            System.setProperty(HEADLESS, "true");
        }
        return browserOptions;
    }

    /**
     * If additional capabilities are provided in the test case, add them in
     *
     * @param extraCapabilities any additional parameters to set for selenium
     */
    public void addExtraCapabilities(DesiredCapabilities extraCapabilities) {
        if (extraCapabilities != null && browser.getName() != BrowserName.NONE) {
            for (String capabilityName : extraCapabilities.getCapabilityNames()) {
                desiredCapabilities.setCapability(capabilityName, extraCapabilities.getCapability(capabilityName));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Next: Renaming Files, Previous: Symbolic Links, Up: File System Interface   [Contents][Index]

14.6 Deleting Files

You can delete a file with unlink or remove.

Deletion actually deletes a file name.  If this is the file’s only name,
then the file is deleted as well.  If the file has other remaining names
(see Hard Links), it remains accessible under those names.

Function: int unlink (const char *<var>filename</var>)

Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

The unlink function deletes the file name <var>filename</var>.  If
this is a file’s sole name, the file itself is also deleted.  (Actually,
if any process has the file open when this happens, deletion is
postponed until all processes have closed the file.)

The function unlink is declared in the header file <samp>unistd.h</samp>.

This function returns 0 on successful completion, and -1
on error.  In addition to the usual file name errors
(see File Name Errors), the following errno error conditions are
defined for this function:

EACCES

Write permission is denied for the directory from which the file is to be
removed, or the directory has the sticky bit set and you do not own the file.

EBUSY

This error indicates that the file is being used by the system in such a
way that it can’t be unlinked.  For example, you might see this error if
the file name specifies the root directory or a mount point for a file
system.

ENOENT

The file name to be deleted doesn’t exist.

EPERM

On some systems unlink cannot be used to delete the name of a
directory, or at least can only be used this way by a privileged user.
To avoid such problems, use rmdir to delete directories.  (On
GNU/Linux and GNU/Hurd systems unlink can never delete the name of a directory.)

EROFS

The directory containing the file name to be deleted is on a read-only
file system and can’t be modified.

Function: int rmdir (const char *<var>filename</var>)

Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

The rmdir function deletes a directory.  The directory must be
empty before it can be removed; in other words, it can only contain
entries for <samp>.</samp> and <samp>..</samp>.

In most other respects, rmdir behaves like unlink.  There
are two additional errno error conditions defined for
rmdir:

ENOTEMPTY

EEXIST

The directory to be deleted is not empty.

These two error codes are synonymous; some systems use one, and some use
the other.  GNU/Linux and GNU/Hurd systems always use ENOTEMPTY.

The prototype for this function is declared in the header file
<samp>unistd.h</samp>.

Function: int remove (const char *<var>filename</var>)

Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

This is the ISO C function to remove a file.  It works like
unlink for files and like rmdir for directories.
remove is declared in <samp>stdio.h</samp>.

Next: Renaming Files, Previous: Symbolic Links, Up: File System Interface   [Contents][Index]


text:
package org.jasig.portal.io.xml;

import org.springframework.oxm.Marshaller;

/**
 * Defines a class that can export a specific type of portal data
 *
 *
 * @author Eric Dalquist
 * @version $Revision$
 */
public interface IDataExporter<T> {
    /**
     * @return The type descriptor for the
     */
    public IPortalDataType getPortalDataType();

    /**
     * @return All of the available data for this type
     */
    public Iterable<? extends IPortalData> getPortalData();

    /**
     * Return portal data to export, if no data exists for the id null should be returned.
     */
    public T exportData(String id);

    /**
     * Return a safe file name. Safe is defined as not containing characters that are invalid or difficult to
     * type on common file systems or names that are reserved on common file systems.
     */
    public String getFileName(T data);

    /**
     * @return The Marshaller to use the convert the data to XML
     */
    public Marshaller getMarshaller();
}


text:
module Middleman
  # Current Version
  # @return [String]
  VERSION = '4.1.2'.freeze unless const_defined?(:VERSION)
end


text:
/*
 * Init
 */

$.index.open();

//This creates a global reference to the tab
Alloy.Globals.tabChapters = $.tabChapters;

$.table.setData(Alloy.Globals.radiologyDB.chapters());

// Open new window with list of sections
	function sectionsWindow(event){
		var addWindow = Alloy.createController("sectionsList", {title: event.row.title}).getView();
		Alloy.Globals.tabChapters.open( addWindow );

		//The following works to add a new Window which allows to get down to subsections, but loses reversal
			//addWindow.open();
	};


text:
<?php

namespace Apigee\Edge\Api\Management\Entity;

/**
 * Interface CompanyAppInterface.
 */
interface CompanyAppInterface extends AppInterface
{
    /**
     * @return string
     */
    public function getCompanyName(): ?string;
}


text:
package org.fastcatsearch.ir;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.fastcatsearch.datasource.reader.AbstractDataSourceReader;
import org.fastcatsearch.datasource.reader.DataSourceReader;
import org.fastcatsearch.datasource.reader.DefaultDataSourceReaderFactory;
import org.fastcatsearch.ir.analysis.AnalyzerPoolManager;
import org.fastcatsearch.ir.common.IRException;
import org.fastcatsearch.ir.common.IndexingType;
import org.fastcatsearch.ir.config.CollectionContext;
import org.fastcatsearch.ir.config.CollectionIndexStatus.IndexStatus;
import org.fastcatsearch.ir.config.DataInfo.RevisionInfo;
import org.fastcatsearch.ir.config.DataInfo.SegmentInfo;
import org.fastcatsearch.ir.config.DataSourceConfig;
import org.fastcatsearch.ir.settings.SchemaSetting;
import org.fastcatsearch.job.indexing.IndexingStopException;

/**
 * 컬렉션의 전체색인을 수행하는 indexer.
 * */
public class CollectionFullIndexer extends AbstractCollectionIndexer {

	public CollectionFullIndexer(CollectionContext collectionContext, AnalyzerPoolManager analyzerPoolManager) throws IRException {
		super(collectionContext, analyzerPoolManager);

		init(collectionContext.schema());
	}

	@Override
	protected DataSourceReader createDataSourceReader(File filePath, SchemaSetting schemaSetting) throws IRException{
		DataSourceConfig dataSourceConfig = collectionContext.dataSourceConfig();

		return DefaultDataSourceReaderFactory.createFullIndexingSourceReader(super.collectionContext.collectionId(),filePath, schemaSetting, dataSourceConfig);
	}

	@Override
	protected void prepare() throws IRException {
		workingSegmentInfo = new SegmentInfo();

		// data 디렉토리를 변경한다.
		int newDataSequence = collectionContext.nextDataSequence();

		// 디렉토리 초기화.
		File indexDataDir = collectionContext.collectionFilePaths().dataPaths().indexDirFile(newDataSequence);
		try {
			//FileUtils.deleteDirectory(indexDataDir);
			if(indexDataDir.exists()) {
				FileUtils.forceDelete(indexDataDir);
			}
		} catch (IOException e) {
			throw new IRException(e);
		}

		collectionContext.clearDataInfoAndStatus();
		indexDataDir.mkdirs();
	}

	@Override
	protected boolean done(RevisionInfo revisionInfo, IndexStatus indexStatus) throws IRException, IndexingStopException {
		int insertCount = revisionInfo.getInsertCount();

		if (insertCount > 0 && !stopRequested) {
			//이미 동일한 revinfo이므로 재셋팅필요없다.
			//workingSegmentInfo.updateRevision(revisionInfo);

			//update index#/info.xml file
			//addindexing의 updateCollection대신 호출.
			collectionContext.addSegmentInfo(workingSegmentInfo);
			//update status.xml file
			collectionContext.updateCollectionStatus(IndexingType.FULL, revisionInfo, startTime, System.currentTimeMillis());
			collectionContext.indexStatus().setFullIndexStatus(indexStatus);
			return true;
		}else{
			if(!stopRequested){
				logger.info("[{}] Indexing Canceled due to no documents.", collectionContext.collectionId());
				throw new IndexingStopException(collectionContext.collectionId()+" Indexing Canceled due to no documents.");
			}else{
				logger.info("[{}] Indexing Canceled due to Stop Requested!", collectionContext.collectionId());
				throw new IndexingStopException(collectionContext.collectionId()+" Indexing Canceled due to Stop Requested");
			}
		}

	}
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_INTERPOLATED_TRANSFORM_OPERATION_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_INTERPOLATED_TRANSFORM_OPERATION_H_

#include "third_party/blink/renderer/platform/transforms/transform_operation.h"
#include "third_party/blink/renderer/platform/transforms/transform_operations.h"

namespace blink {

// This class is an implementation detail for deferred interpolations.
class PLATFORM_EXPORT InterpolatedTransformOperation final
    : public TransformOperation {
 public:
  static scoped_refptr<InterpolatedTransformOperation> Create(
      const TransformOperations& from,
      const TransformOperations& to,
      int starting_index,
      double progress) {
    return base::AdoptRef(
        new InterpolatedTransformOperation(from, to, starting_index, progress));
  }

  bool CanBlendWith(const TransformOperation& other) const override {
    return IsSameType(other);
  }

 private:
  OperationType GetType() const override { return kInterpolated; }

  bool operator==(const TransformOperation&) const override;
  void Apply(TransformationMatrix&,
             const FloatSize& border_box_size) const override;

  scoped_refptr<TransformOperation> Accumulate(
      const TransformOperation&) override {
    NOTREACHED();
    return this;
  }

  scoped_refptr<TransformOperation> Blend(
      const TransformOperation* from,
      double progress,
      bool blend_to_identity = false) override;
  scoped_refptr<TransformOperation> Zoom(double factor) final {
    return Create(from_.Zoom(factor), to_.Zoom(factor), starting_index_,
                  progress_);
  }

  bool PreservesAxisAlignment() const final {
    return from_.PreservesAxisAlignment() && to_.PreservesAxisAlignment();
  }

  bool DependsOnBoxSize() const override {
    return from_.DependsOnBoxSize() || to_.DependsOnBoxSize();
  }

  InterpolatedTransformOperation(const TransformOperations& from,
                                 const TransformOperations& to,
                                 int starting_index,
                                 double progress)
      : from_(from),
        to_(to),
        starting_index_(starting_index),
        progress_(progress) {}

  const TransformOperations from_;
  const TransformOperations to_;
  // Number of operations to skip from the start of each list. By spec,
  // pairwise interpolations are performed for compatible operations at the
  // start of the list and matrix interpolation for the remainder.
  int starting_index_;
  double progress_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_INTERPOLATED_TRANSFORM_OPERATION_H_


text:
from collections import namedtuple

from ..tool import extends, producer
from .. import types, tool, error

from . import ast

# typechecking is implemented as a method on ast nodes, which should
# yield (self, type) prior to returning inferred type, if any.

# this way we can easily collect every inferred type for each node in
# an ast for later use. use the @producer decorator to wrap yielding
# automatically, and yield from sub-nodes typechecks.

literal = {
    bool: types.boolean,
    int: types.integer,
    float: types.real,
    str: types.string,
    type(None): types.unit,
}

@extends(ast.Lit)
@producer
def typecheck(self, state):
    '''literals'''

    # just look it up in literal table
    return literal[ type(self.value) ]

@extends(ast.Var)
@producer
def typecheck(self, state):
    '''variables'''

    try:
        # instantiate polytype with fresh variables
        poly = state[self.name]
        mono = state.instantiate(poly)

        return mono

    except error.UnboundVariable as e:
        raise error.Type('unbound variable "{0}"'.format(e.name))

@extends(ast.Fix)
@producer
def typecheck(self, state):
    '''fixpoint combinator'''
    a = state.fresh()
    return (a >> a) >> a

@extends(ast.Let)
@producer
def typecheck(self, state):
    '''let bindings'''

    value = self.value

    # recursive functions by default
    if type(value) is ast.Abs:
        value = self.fix()

    value_mono = yield from value.typecheck(state)
    value_poly = state.generalize(value_mono)

    with state.scope():

        if self.name != ast.Var.wildcard:
            state[self.name] = value_poly

        body_type = yield from self.body.typecheck(state)

        # TODO outer scope ?
        return body_type

@extends(ast.App)
@producer
def typecheck(self, st):
    '''function applications'''

    # infer type for func/args
    func_type = yield from self.func.typecheck(st)

    # seems like python is unable to express this as a list
    # comprehension :-/
    args_type = []

    for a in self.args:
        t = yield from a.typecheck(st)
        args_type.append(t)

    args_type = args_type or [types.unit]

    result_type = st.fresh()

    # total function type
    app_type = result_type

    for a in reversed(args_type):
        app_type = a >> app_type

    # unification happens here
    types.unify(st.uf, func_type, app_type)

    return result_type

@extends(ast.Abs)
@producer
def typecheck(self, state, constraint = None):
    '''function definitions'''

    with state.scope():
        # fresh vars for argument types, unit for nullary
        args_type = [ state.fresh() for a in self.args ] or [types.unit]

        # sometimes it is desirable to pre-unify some argument types,
        # which we do using constraint callback
        if constraint:
            constraint(args_type)

        # build sub-context
        for a, ta in zip(self.args, args_type):

            if a != ast.Var.wildcard: # skip wildcards/unit
                state[a] = types.Scheme(ta)

        body_type = yield from self.body.typecheck(state)

        # total function type
        res = body_type

        for a in reversed(args_type):
            res = a >> res

        # TODO outer scope?
        return res


text:
@echo Off
set key=%1
if "%key%" == "" (
   set key="Empty"
)
mkdir Output
mkdir Packages
.\Sources\.nuget\nuget.exe restore .\Sources\Taijutsu.sln
%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild Build\Taijutsu.proj /p:NugetKey=%key% /v:M /fl /flp:LogFile=Output\msbuild.log;Verbosity=Normal /nr:false


text:
require 'torch'
require 'nn'
require 'optim'
require 'gnuplot'

month = torch.range(1,10)
price = torch.Tensor{28993,29110,29436,30791,33384,36762,39900,39972,40230,40146}

model = nn.Sequential()
model:add(nn.MulConstant(0.1))
model:add(nn.Linear(1,3))
model:add(nn.Sigmoid())
model:add(nn.Linear(3,3))
model:add(nn.Sigmoid())
model:add(nn.Linear(3,1))
model:add(nn.MulConstant(50000))
criterion = nn.MSECriterion()

month_train = month:reshape(10,1)
price_train = price:reshape(10,1)

gnuplot.figure()

w, dl_dw = model:getParameters()

feval = function(w_new)
   if w ~= w_new then w:copy(w_new) end
    dl_dw:zero()

    price_predict = model:forward(month_train)
    loss = criterion:forward(price_predict, price_train)
    model:backward(month_train, criterion:backward(price_predict, price_train))
    return loss, dl_dw
end

params = {
   learningRate = 1e-2
}

for i=1,3000 do
   optim.rprop(feval, w, params)

   if i%10==0 then
      gnuplot.plot({month, price}, {month_train:reshape(10), price_predict:reshape(10)})
   end
end

month_predict = torch.range(1,12)
local price_predict = model:forward(month_predict:reshape(12,1))
print(price_predict)

gnuplot.pngfigure('plot.png')
gnuplot.plot({month, price}, {month_predict, price_predict})
gnuplot.plotflush()


text:
package com.github.ionsys.star.model;

import org.springframework.stereotype.Component;

/**
 * @author Ian 'Txuritan' Cronkright
 */
@SuppressWarnings("unused")
@Component
public class TagModel {
    private String type;

    private String content;

    public TagModel() {

    }

    public TagModel(String type, String content) {
        this.type = type;
        this.content = content;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}


text:
using System.Linq;
using ClearScript.Manager.Http.Helpers;
using ClearScript.Manager.Http.Packages;
using ClearScript.Manager.Loaders;
using Microsoft.ClearScript;
using NUnit.Framework;
using Should;

namespace ClearScript.Manager.Http.Test
{
    [TestFixture]
    public class WhenMakingHttpCall
    {
        [SetUp]
        public void Setup()
        {
            RequireManager.ClearPackages();
        }

        [Test]
        public async void Basic_Http_Get_Succeeds()
        {
            var subject = new TestObject();
            var manager = new RuntimeManager(new ManualManagerSettings{ScriptTimeoutMilliSeconds = 0});

            PackageHelpers.RegisterRequestPackages();

            manager.AddConsoleReference = true;
            var options = new ExecutionOptions();
            options.HostObjects.Add(new HostObject {Name = "subject", Target = subject});

            var scriptAwaiter = new ScriptAwaiter();
            options.HostObjects.Add(new HostObject { Name = "scriptAwaiter", Target = scriptAwaiter });

            var code = "var request = require('request');" +
                       "request({url: 'http://api.icndb.com/jokes/random/1', json: true}," +
                       " function (error, response, body) {subject.StatusCode = response.statusCode; subject.Response = response; scriptAwaiter.Callback();});";

            await manager.ExecuteAsync("testScript", code, options);
            await scriptAwaiter.T;

            subject.StatusCode.ShouldEqual(200);
        }

        [Test]
        public async void Basic_Http_Get_Body_Is_Retrieved()
        {
            var subject = new TestObject();
            var manager = new RuntimeManager(new ManualManagerSettings { ScriptTimeoutMilliSeconds = 0 });

            PackageHelpers.RegisterRequestPackages();

            manager.AddConsoleReference = true;
            var options = new ExecutionOptions();
            options.HostObjects.Add(new HostObject { Name = "subject", Target = subject });

            var scriptAwaiter = new ScriptAwaiter();
            options.HostObjects.Add(new HostObject { Name = "scriptAwaiter", Target = scriptAwaiter });

            var code = "var request = require('request');" +
                       "request({url: 'http://api.icndb.com/jokes/random/1', json: true}," +
                       " function (error, response, body) {subject.Response = response; subject.Body = body; subject.Joke = body.value[0].joke; scriptAwaiter.Callback();});";

            await manager.ExecuteAsync("testScript", code, options);
            await scriptAwaiter.T;

            subject.Joke.ShouldNotBeNull();
        }

        [Test]
        public async void Basic_Http_Get_Headers_Are_Retrieved()
        {
            var subject = new TestObject();
            var manager = new RuntimeManager(new ManualManagerSettings { ScriptTimeoutMilliSeconds = 0 });

            PackageHelpers.RegisterRequestPackages();

            manager.AddConsoleReference = true;
            var options = new ExecutionOptions();
            options.HostObjects.Add(new HostObject { Name = "subject", Target = subject });

            var scriptAwaiter = new ScriptAwaiter();
            options.HostObjects.Add(new HostObject { Name = "scriptAwaiter", Target = scriptAwaiter });

            var code = "var request = require('request');" +
                       "request({url: 'http://api.icndb.com/jokes/random/1', json: true}," +
                       " function (error, response, body) {subject.Response = response; subject.Headers = response.headers; scriptAwaiter.Callback();});";

            await manager.ExecuteAsync("testScript", code, options);
            await scriptAwaiter.T;

            subject.Headers.Count().ShouldBeGreaterThan(0);
        }

        public class TestObject
        {
            private string _name = "Name";

            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }

            public string Server { get; set; }

            public int StatusCode { get; set; }

            public string Joke { get; set; }

            public object Response { get; set; }

            public object Body { get; set; }

            public PropertyBag Headers { get; set; }

            public int Count { get; set; }
        }

    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>SecucardConnectSDK: SCPaymentCustomer Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

SecucardConnectSDK

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Properties |
List of all members

SCPaymentCustomer Class Reference

Inheritance diagram for SCPaymentCustomer:

  <map id="SCPaymentCustomer_map" name="SCPaymentCustomer_map">
<area href="interface_s_c_secu_object.html" alt="SCSecuObject" shape="rect" coords="77,56,221,80"/>
</map>

Properties

SCGeneralMerchant * 	merchant

SCPaymentContract * 	contact

NSDate * 	created

NSDate * 	updated

SCPaymentContract * 	contract

 Properties inherited from SCSecuObject

NSString * 	id

Additional Inherited Members

 Class Methods inherited from SCSecuObject

(NSString *) 	+ object

(NSDateFormatter *) 	+ dateFormatter

(NSDateFormatter *) 	+ dateShortFormatter

The documentation for this class was generated from the following file:

Pod/Classes/Model/Payment/SCPaymentCustomer.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
package junitdemo;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

import org.junit.*;

public class JUnitDemoJavaFailedTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println(Thread.currentThread() + " - setUpBeforeClass()");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println(Thread.currentThread() + " - tearDownAfterClass()");
    }

    @Before
    public void setUp() throws Exception {
        System.out.println(Thread.currentThread() + " - setUp()");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println(Thread.currentThread() + " - tearDown()");
    }

    List<String> mylist = Arrays.asList("123", "456");

    @Test
    public void testFailedFeature() {
        mylist = Arrays.asList("abc", "def", "ghi");
        System.out.println(mylist);
        assertEquals(5, mylist.size());
    }

	@Ignore("Test is ignored as a demonstration")
    @Test
    public void testIgnoreFeature() {
        System.out.println(mylist);
        assertEquals(2, mylist.size());
    }

}


text:
/*

 CEColorPanelController.m

 CotEditor
 http://coteditor.com

 Created by 1024jp on 2014-04-22.

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

 © 2014-2015 1024jp

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 */

#import "CEColorCodePanelController.h"
#import "CEDocument.h"
#import "NSColor+WFColorCode.h"
#import "Constants.h"

@interface CEColorCodePanelController ()

@property (nonatomic, nullable) IBOutlet NSView *accessoryView;
@property (nonatomic, nullable) NSColor *color;
@property (nonatomic, nullable) NSString *colorCode;

@end

#pragma mark -

@implementation CEColorCodePanelController

#pragma mark Singleton

// ------------------------------------------------------
/// return singleton instance
+ (nonnull instancetype)sharedController
// ------------------------------------------------------
{
    static dispatch_once_t onceToken;
    static id shared = nil;

    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    });

    return shared;
}

#pragma mark NSWindowPanel Methods

// ------------------------------------------------------
/// initialize
- (nonnull instancetype)init
// ------------------------------------------------------
{
    self = [super init];
    if (self) {
        [[NSBundle mainBundle] loadNibNamed:@"ColorCodePanelAccessory" owner:self topLevelObjects:nil];
    }
    return self;
}

#pragma mark Public Methods

// ------------------------------------------------------
/// set color to color panel from color code
- (void)setColorWithCode:(nullable NSString *)colorCode
// ------------------------------------------------------
{
    colorCode = [colorCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if ([colorCode length] == 0) {
        return;
    }

    WFColorCodeType codeType;
    NSColor *color = [NSColor colorWithColorCode:colorCode codeType:&codeType];

    if (color) {
        [[NSUserDefaults standardUserDefaults] setInteger:codeType forKey:CEDefaultColorCodeTypeKey];
        [(NSColorPanel *)[self window] setColor:color];
        return;
    }
    NSBeep();
}

#pragma mark Delegate

//=======================================================
// NSWindowDelegate  < NSColorPanel
//=======================================================

// ------------------------------------------------------
/// panel will close
- (void)windowWillClose:(nonnull NSNotification *)notification
// ------------------------------------------------------
{
    NSColorPanel *colorPanel = (NSColorPanel *)[self window];
    [[self window] setDelegate:nil];
    [colorPanel setAccessoryView:nil];
    [colorPanel setShowsAlpha:NO];
}

#pragma mark Action Messages

// ------------------------------------------------------
/// on show color panel
- (void)showWindow:(nullable id)sender
// ------------------------------------------------------
{
    // setup the shared color panel
    NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel];
    [colorPanel setAccessoryView:[self accessoryView]];
    [colorPanel setShowsAlpha:YES];
    [colorPanel setStyleMask:[colorPanel styleMask] & ~NSResizableWindowMask];
    [colorPanel setRestorable:NO];

    [colorPanel setDelegate:self];
    [colorPanel setAction:@selector(selectColor:)];
    [colorPanel setTarget:self];

    [self setWindow:colorPanel];
    [self setColor:[colorPanel color]];
    [self updateCode:self];

    [colorPanel orderFront:self];
}

// ------------------------------------------------------
/// insert color code to the selection of the frontmost document
- (IBAction)insertCodeToDocument:(nullable id)sender
// ------------------------------------------------------
{
    NSTextView *textView = [[[self documentWindowController] editor] focusedTextView];

    if ([textView shouldChangeTextInRange:[textView selectedRange] replacementString:[self colorCode]]) {
        [textView replaceCharactersInRange:[textView selectedRange] withString:[self colorCode]];
        [[textView undoManager] setActionName:NSLocalizedString(@"Insert Color Code", nil)];
        [textView didChangeText];
        [textView scrollRangeToVisible:[textView selectedRange]];
    }
}

// ------------------------------------------------------
/// a new color was selected on the panel
- (IBAction)selectColor:(nullable id)sender
// ------------------------------------------------------
{
    [self setColor:[sender color]];
    [self updateCode:sender];
}

// ------------------------------------------------------
/// set color from the color code field in the panel
- (IBAction)applayColorCode:(nullable id)sender
// ------------------------------------------------------
{
    [self setColorWithCode:[self colorCode]];
}

// ------------------------------------------------------
/// update color code in the field
- (IBAction)updateCode:(nullable id)sender
// ------------------------------------------------------
{
    WFColorCodeType codeType = [[NSUserDefaults standardUserDefaults] integerForKey:CEDefaultColorCodeTypeKey];
    NSString *code = [[[self color] colorUsingColorSpaceName:NSCalibratedRGBColorSpace] colorCodeWithType:codeType];

    // keep lettercase if current Hex code is uppercase
    if ((codeType == WFColorCodeHex || codeType == WFColorCodeShortHex) &&
        [[self colorCode] rangeOfString:@"^#[0-9A-F]{1,6}$" options:NSRegularExpressionSearch].location != NSNotFound) {
        code = [code uppercaseString];
    }

    [self setColorCode:code];
}

@end


text: Generating Asp.Net models and controllers based on OpenAPI (swagger 2.0) spec


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\Constraint;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 */
final class LessThan extends Constraint
{
    private float|int $value;

    public function __construct(float|int $value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return 'is less than ' . $this->exporter()->export($this->value);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     */
    protected function matches(mixed $other): bool
    {
        return $this->value > $other;
    }
}


text:
cask 'macdown' do
  version '0.7.1'
  sha256 '4b26fb70b399cd998f226a78f81cd74348da19a8953aca80169fd7d00667496c'

  # github.com/MacDownApp/macdown was verified as official when first introduced to the cask
  url "https://github.com/MacDownApp/macdown/releases/download/v#{version}/MacDown.app.zip"
  appcast 'https://macdown.uranusjr.com/sparkle/macdown/stable/appcast.xml',
          checkpoint: '0f66f2a2ec60b25ce7b15cf153db4245badf0c1252196e2bfda8a9d401767789'
  name 'MacDown'
  homepage 'https://macdown.uranusjr.com/'

  auto_updates true
  depends_on macos: '>= :mountain_lion'

  app 'MacDown.app'
  binary "#{appdir}/MacDown.app/Contents/SharedSupport/bin/macdown"

  zap delete: [
                '~/Library/Application Support/MacDown',
                '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.uranusjr.macdown.sfl',
                '~/Library/Caches/com.uranusjr.macdown',
                '~/Library/Cookies/com.uranusjr.macdown.binarycookies',
                '~/Library/Preferences/com.uranusjr.macdown.plist',
                '~/Library/Saved Application State/com.uranusjr.macdown.savedState',
                '~/Library/WebKit/com.uranusjr.macdown',
              ]
end


text:
using System;
using System.IO;
using System.Linq;
using SqlNotebookScript.Core;
using SqlNotebookScript.Utils;

namespace SqlNotebookScript.Interpreter;

public sealed class ImportXlsStmtRunner
{
    private readonly Notebook _notebook;
    private readonly ScriptEnv _env;
    private readonly ScriptRunner _runner;
    private readonly Ast.ImportXlsStmt _stmt;

    private readonly string _filePath;
    private readonly object _whichSheet; // 1-based number or string name

    // option values
    private readonly int _firstRowIndex = 0; // 0-based index
    private readonly int? _lastRowIndex = null; // 0-based index
    private readonly int _firstColumnIndex = 0; // 0-based index
    private readonly int? _lastColumnIndex = null; // 0-based index
    private readonly bool _headerRow = true;
    private readonly bool _truncateExistingTable = false;
    private readonly bool _temporaryTable = false;
    private readonly bool _stopAtFirstBlankRow = true;
    private readonly IfConversionFails _ifConversionFails = IfConversionFails.ImportAsText;
    private readonly BlankValuesOption _blankValuesMethod = BlankValuesOption.Null;

    public static void Run(Notebook notebook, ScriptEnv env, ScriptRunner runner, Ast.ImportXlsStmt stmt)
    {
        var importer = new ImportXlsStmtRunner(notebook, env, runner, stmt);
        SqlUtil.WithTransaction(notebook, importer.Import);
    }

    private ImportXlsStmtRunner(Notebook notebook, ScriptEnv env, ScriptRunner runner, Ast.ImportXlsStmt stmt)
    {
        _notebook = notebook;
        _env = env;
        _runner = runner;
        _stmt = stmt;

        _filePath = _runner.EvaluateExpr<string>(_stmt.FilenameExpr, _env);
        if (!File.Exists(_filePath))
        {
            throw new Exception($"The specified XLS/XLSX file was not found: \"{_filePath}\"");
        }

        if (_stmt.WhichSheetExpr != null)
        {
            _whichSheet = _runner.EvaluateExpr(_stmt.WhichSheetExpr, _env);
        }

        int? index;
        foreach (var option in _stmt.OptionsList.GetOptionKeys())
        {
            switch (option)
            {
                case "FIRST_ROW":
                    _firstRowIndex = _stmt.OptionsList.GetOptionInt(option, _runner, _env, 1, minValue: 1) - 1;
                    break;

                case "LAST_ROW":
                    var lastRowNum = _stmt.OptionsList.GetOptionInt(option, _runner, _env, 0, minValue: 0);
                    if (lastRowNum == 0)
                    {
                        _lastRowIndex = null;
                    }
                    else
                    {
                        _lastRowIndex = lastRowNum - 1;
                    }
                    break;

                case "FIRST_COLUMN":
                    index = XlsUtil.ColumnRefToIndex(_stmt.OptionsList.GetOption<object>(option, _runner, _env, null));
                    if (index.HasValue)
                    {
                        _firstColumnIndex = index.Value;
                    }
                    else
                    {
                        throw new Exception($"The {option} option must be a valid column number or string.");
                    }
                    break;

                case "LAST_COLUMN":
                    var lastColumnValue = _stmt.OptionsList.GetOption<object>(option, _runner, _env, null);
                    if (lastColumnValue is long b && b == 0)
                    {
                        _lastColumnIndex = null;
                        break;
                    }
                    index = XlsUtil.ColumnRefToIndex(lastColumnValue);
                    if (index.HasValue)
                    {
                        _lastColumnIndex = index.Value;
                    }
                    else
                    {
                        throw new Exception($"The {option} option must be a valid column number or string.");
                    }
                    break;

                case "HEADER_ROW":
                    _headerRow = _stmt.OptionsList.GetOptionBool(option, _runner, _env, true);
                    break;

                case "TRUNCATE_EXISTING_TABLE":
                    _truncateExistingTable = _stmt.OptionsList.GetOptionBool(option, _runner, _env, false);
                    break;

                case "TEMPORARY_TABLE":
                    _temporaryTable = _stmt.OptionsList.GetOptionBool(option, _runner, _env, false);
                    break;

                case "IF_CONVERSION_FAILS":
                    _ifConversionFails = (IfConversionFails)
                        _stmt.OptionsList.GetOptionLong(option, _runner, _env, 1, minValue: 1, maxValue: 3);
                    break;

                case "STOP_AT_FIRST_BLANK_ROW":
                    _stopAtFirstBlankRow = _stmt.OptionsList.GetOptionBool(option, _runner, _env, true);
                    break;

                case "BLANK_VALUES":
                    _blankValuesMethod = (BlankValuesOption)
                        _stmt.OptionsList.GetOptionLong(option, _runner, _env, 2, minValue: 1, maxValue: 3);
                    break;

                default:
                    throw new Exception($"\"{option}\" is not a recognized option name.");
            }
        }
    }

    private void Import()
    {
        XlsUtil.WithWorkbook(
            _filePath,
            workbook =>
            {
                workbook.SeekToWorksheet(GetSheetIndex(workbook));
                var rows = workbook.ReadSheet(_firstRowIndex, _lastRowIndex, _firstColumnIndex, _lastColumnIndex);

                SqlUtil.Import(
                    srcColNames: XlsUtil.ReadColumnNames(rows, _headerRow),
                    dataRows: rows.Skip(_headerRow ? 1 : 0),
                    importTable: _stmt.ImportTable,
                    temporaryTable: _temporaryTable,
                    truncateExistingTable: _truncateExistingTable,
                    stopAtFirstBlankRow: _stopAtFirstBlankRow,
                    ifConversionFails: _ifConversionFails,
                    blankValuesMethod: _blankValuesMethod,
                    notebook: _notebook,
                    runner: _runner,
                    env: _env
                );
            }
        );
    }

    private int GetSheetIndex(XlsUtil.IWorkbook workbook)
    {
        var whichSheet = _whichSheet ?? 1; // 1-based number or name string
        if (whichSheet is int || whichSheet is long)
        {
            var whichSheetNum = Convert.ToInt32(whichSheet);
            if (whichSheetNum < 1)
            {
                throw new Exception($"The worksheet number must be at least 1.");
            }
            return whichSheetNum - 1;
        }
        else if (whichSheet is string name)
        {
            var names = workbook.ReadWorksheetNames();
            var index = names.IndexOf(name);
            if (index == -1)
            {
                throw new Exception($"The worksheet \"{name}\" was not found.");
            }
            else
            {
                return index;
            }
        }
        else
        {
            throw new Exception($"The \"which-sheet\" argument must be a number or a string.");
        }
    }
}


text:
* Fixed "Error 404" ([#8](https://github.com/githubjeka/angular-yii2/issues/8))
* Update vendors ([#4](https://github.com/AngularYii2/angularyii2.github.io/pull/4)).


text:
layout: page
weight: 70
title: Underused Mail Setting Retirement
group: account-management
navigation:
  show: false
seo:
  title: Underused Mail Setting Retirement
  keywords:
  override:
  description: This page explains the changes to Twilio SendGrid mail settings coming in Q1 2020
---

As we continuously modernize our email delivery infrastructure, we have sunset some sparsely used features in order to improve efficiency.

    Mail Setting
    Recommended Action

    Plain Content is an option within SendGrid Mail Settings that disables the automatic conversion of plain text emails to HTML.
    If you would like to maintain open and click tracking, you must send HTML. Otherwise, you can continue sending plain text emails without open and click tracking.

    Gravatar third party integration.
    Due to low adoption among customers we decided to sunset this feature.

    Sections is a form of mail merge where sections of an email content can be customized by recipient.
    We recommend using Twilio SendGrid transactional templates with handlebars syntax through our v3 API.

    BCC automatically BCCs an email address for every email sent.
    We recommend identifying bcc as a personalization in each API call.

    Spam Checker is an option within SendGrid Mail Settings that checks outbound messages for spam content.
    We recommend using  Email Testing to maximize your deliverability.

    Drop feature is a test feature that goes through the processing of mail, but just drops it without delivering in the end.
    We have a Sandbox Mode feature which allows you to send a test email to ensure that your request body is formatted correctly without delivering the email to any of your recipients.	 h

    Sendwithus third party Integration
    We recommend using Twilio SendGrid Marketing Campaigns.

   DomainKey is an old feature for signing emails which has been deprecated by email industry.
Users should utilize DKIM which is the new standard for signing emails.


text:
#ifndef WEBRTC_MODULES_REMOTE_BITRATE_ESTIMATOR_REMOTE_BITRATE_ESTIMATOR_UNITTEST_HELPER_H_
#define WEBRTC_MODULES_REMOTE_BITRATE_ESTIMATOR_REMOTE_BITRATE_ESTIMATOR_UNITTEST_HELPER_H_

#include <list>
#include <map>
#include <utility>

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/system_wrappers/interface/clock.h"

namespace webrtc {
namespace testing {

class TestBitrateObserver : public RemoteBitrateObserver {
 public:
  TestBitrateObserver() : updated_(false), latest_bitrate_(0) {}
  virtual ~TestBitrateObserver() {}

  void OnReceiveBitrateChanged(const std::vector<unsigned int>& ssrcs,
                               unsigned int bitrate) override;

  void Reset() { updated_ = false; }

  bool updated() const { return updated_; }

  unsigned int latest_bitrate() const { return latest_bitrate_; }

 private:
  bool updated_;
  unsigned int latest_bitrate_;
};

class RtpStream {
 public:
  struct RtpPacket {
    int64_t send_time;
    int64_t arrival_time;
    uint32_t rtp_timestamp;
    size_t size;
    unsigned int ssrc;
  };

  struct RtcpPacket {
    uint32_t ntp_secs;
    uint32_t ntp_frac;
    uint32_t timestamp;
    unsigned int ssrc;
  };

  typedef std::list<RtpPacket*> PacketList;

  enum { kSendSideOffsetUs = 1000000 };

  RtpStream(int fps, int bitrate_bps, unsigned int ssrc, unsigned int frequency,
      uint32_t timestamp_offset, int64_t rtcp_receive_time);
  void set_rtp_timestamp_offset(uint32_t offset);

  // Generates a new frame for this stream. If called too soon after the
  // previous frame, no frame will be generated. The frame is split into
  // packets.
  int64_t GenerateFrame(int64_t time_now_us, PacketList* packets);

  // The send-side time when the next frame can be generated.
  double next_rtp_time() const;

  // Generates an RTCP packet.
  RtcpPacket* Rtcp(int64_t time_now_us);

  void set_bitrate_bps(int bitrate_bps);

  int bitrate_bps() const;

  unsigned int ssrc() const;

  static bool Compare(const std::pair<unsigned int, RtpStream*>& left,
                      const std::pair<unsigned int, RtpStream*>& right);

 private:
  enum { kRtcpIntervalUs = 1000000 };

  int fps_;
  int bitrate_bps_;
  unsigned int ssrc_;
  unsigned int frequency_;
  int64_t next_rtp_time_;
  int64_t next_rtcp_time_;
  uint32_t rtp_timestamp_offset_;
  const double kNtpFracPerMs;

  RTC_DISALLOW_COPY_AND_ASSIGN(RtpStream);
};

class StreamGenerator {
 public:
  typedef std::list<RtpStream::RtcpPacket*> RtcpList;

  StreamGenerator(int capacity, double time_now);

  ~StreamGenerator();

  // Add a new stream.
  void AddStream(RtpStream* stream);

  // Set the link capacity.
  void set_capacity_bps(int capacity_bps);

  // Divides |bitrate_bps| among all streams. The allocated bitrate per stream
  // is decided by the initial allocation ratios.
  void SetBitrateBps(int bitrate_bps);

  // Set the RTP timestamp offset for the stream identified by |ssrc|.
  void set_rtp_timestamp_offset(unsigned int ssrc, uint32_t offset);

  // TODO(holmer): Break out the channel simulation part from this class to make
  // it possible to simulate different types of channels.
  int64_t GenerateFrame(RtpStream::PacketList* packets, int64_t time_now_us);

 private:
  typedef std::map<unsigned int, RtpStream*> StreamMap;

  // Capacity of the simulated channel in bits per second.
  int capacity_;
  // The time when the last packet arrived.
  int64_t prev_arrival_time_us_;
  // All streams being transmitted on this simulated channel.
  StreamMap streams_;

  RTC_DISALLOW_COPY_AND_ASSIGN(StreamGenerator);
};
}  // namespace testing

class RemoteBitrateEstimatorTest : public ::testing::Test {
 public:
  RemoteBitrateEstimatorTest();
  virtual ~RemoteBitrateEstimatorTest();

 protected:
  virtual void SetUp() = 0;

  void AddDefaultStream();

  // Helper to convert some time format to resolution used in absolute send time
  // header extension, rounded upwards. |t| is the time to convert, in some
  // resolution. |denom| is the value to divide |t| by to get whole seconds,
  // e.g. |denom| = 1000 if |t| is in milliseconds.
  static uint32_t AbsSendTime(int64_t t, int64_t denom);

  // Helper to add two absolute send time values and keep it less than 1<<24.
  static uint32_t AddAbsSendTime(uint32_t t1, uint32_t t2);

  // Helper to create a WebRtcRTPHeader containing the relevant data for the
  // estimator (all other fields are cleared) and call IncomingPacket on the
  // estimator.
  void IncomingPacket(uint32_t ssrc,
                      size_t payload_size,
                      int64_t arrival_time,
                      uint32_t rtp_timestamp,
                      uint32_t absolute_send_time,
                      bool was_paced);

  // Generates a frame of packets belonging to a stream at a given bitrate and
  // with a given ssrc. The stream is pushed through a very simple simulated
  // network, and is then given to the receive-side bandwidth estimator.
  // Returns true if an over-use was seen, false otherwise.
  // The StreamGenerator::updated() should be used to check for any changes in
  // target bitrate after the call to this function.
  bool GenerateAndProcessFrame(unsigned int ssrc, unsigned int bitrate_bps);

  // Run the bandwidth estimator with a stream of |number_of_frames| frames, or
  // until it reaches |target_bitrate|.
  // Can for instance be used to run the estimator for some time to get it
  // into a steady state.
  unsigned int SteadyStateRun(unsigned int ssrc,
                              int number_of_frames,
                              unsigned int start_bitrate,
                              unsigned int min_bitrate,
                              unsigned int max_bitrate,
                              unsigned int target_bitrate);

  void TestTimestampGroupingTestHelper();

  void TestGetStatsHelper();

  void TestWrappingHelper(int silence_time_s);

  void InitialBehaviorTestHelper(unsigned int expected_converge_bitrate);
  void RateIncreaseReorderingTestHelper(unsigned int expected_bitrate);
  void RateIncreaseRtpTimestampsTestHelper(int expected_iterations);
  void CapacityDropTestHelper(int number_of_streams,
                              bool wrap_time_stamp,
                              unsigned int expected_bitrate_drop_delta);

  static const unsigned int kDefaultSsrc;
  static const int kArrivalTimeClockOffsetMs = 60000;

  SimulatedClock clock_;  // Time at the receiver.
  rtc::scoped_ptr<testing::TestBitrateObserver> bitrate_observer_;
  rtc::scoped_ptr<RemoteBitrateEstimator> bitrate_estimator_;
  rtc::scoped_ptr<testing::StreamGenerator> stream_generator_;

  RTC_DISALLOW_COPY_AND_ASSIGN(RemoteBitrateEstimatorTest);
};
}  // namespace webrtc

#endif  // WEBRTC_MODULES_REMOTE_BITRATE_ESTIMATOR_REMOTE_BITRATE_ESTIMATOR_UNITTEST_HELPER_H_


text:
A [bouzuya/cars][] counter for qiita items.

## Installation

```
$ npm install --save bouzuya/cars-counter-qiita-items
```

## Configuration

```
$ export QIITA_TOKEN='...'
```

## License

[MIT](LICENSE)

## Author

[bouzuya][user] <[m@bouzuya.net][email]> ([http://bouzuya.net][url])

[user]: https://github.com/bouzuya
[email]: mailto:m@bouzuya.net
[url]: http://bouzuya.net
[bouzuya/cars]: https://github.com/bouzuya/cars


text:
namespace Microsoft.Azure.Management.VideoAnalyzer.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// A collection of Operation items.
    /// </summary>
    public partial class OperationCollection
    {
        /// <summary>
        /// Initializes a new instance of the OperationCollection class.
        /// </summary>
        public OperationCollection()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the OperationCollection class.
        /// </summary>
        /// <param name="value">A collection of Operation items.</param>
        public OperationCollection(IList<Operation> value = default(IList<Operation>))
        {
            Value = value;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets a collection of Operation items.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public IList<Operation> Value { get; set; }

    }
}


text:
import logging

from model_utils import Choices

from django.apps import apps
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import JSONField
from django.db import connection
from django.db import models
from django.db import transaction
from django.utils import timezone
from django.utils.translation import ugettext as _

from share.models.fuzzycount import FuzzyCountManager
from share.models import NormalizedData
from share.util import IDObfuscator

__all__ = ('Change', 'ChangeSet', )
logger = logging.getLogger(__name__)

class ChangeSetManager(FuzzyCountManager):

    def from_graph(self, graph, normalized_data_id):
        if all(n.is_skippable for n in graph.nodes):
            logger.debug('No changes detected in {!r}, skipping.'.format(graph))
            return None

        cs = ChangeSet(normalized_data_id=normalized_data_id)
        cs.save()

        Change.objects.bulk_create(filter(None, [Change.objects.from_node(node, cs, save=False) for node in graph.nodes]))

        return cs

class ChangeManager(FuzzyCountManager):

    def from_node(self, node, change_set, save=True):
        if node.is_skippable:
            logger.debug('No changes detected in {!r}, skipping.'.format(node))
            return None
        if not hasattr(node.model, 'VersionModel'):
            # Non-ShareObjects (e.g. Subject) cannot be changed.
            # Shouldn't reach this point...
            logger.warn('Change node {!r} targets immutable model {}, skipping.'.format(node, node.model))
            return None

        attrs = {
            'node_id': node.id,
            'change': node.change,
            'change_set': change_set,
            'model_type': ContentType.objects.get_for_model(node.model, for_concrete_model=False),
            'target_type': ContentType.objects.get_for_model(node.model, for_concrete_model=True),
            'target_version_type': ContentType.objects.get_for_model(node.model.VersionModel, for_concrete_model=True),
        }

        if node.is_merge:
            attrs['type'] = Change.TYPE.merge
        elif not node.instance:
            attrs['type'] = Change.TYPE.create
        else:
            attrs['type'] = Change.TYPE.update
            attrs['target_id'] = node.instance.pk
            attrs['target_version_id'] = node.instance.version.pk

        change = Change(**attrs)

        if save:
            change.save()

        return change

class ChangeSet(models.Model):
    STATUS = Choices((0, 'pending', _('pending')), (1, 'accepted', _('accepted')), (2, 'rejected', _('rejected')))

    objects = ChangeSetManager()

    status = models.IntegerField(choices=STATUS, default=STATUS.pending)
    submitted_at = models.DateTimeField(auto_now_add=True)
    normalized_data = models.ForeignKey(NormalizedData)

    _changes_cache = []

    def accept(self, save=True):
        ret = []
        with transaction.atomic():
            self._changes_cache = list(self.changes.all())
            for c in self._changes_cache:
                ret.append(c.accept(save=save))
            self.status = ChangeSet.STATUS.accepted
            if save:
                self.save()
        return ret

    def _resolve_ref(self, ref):
        model = apps.get_model('share', model_name=ref['@type'])
        ct = ContentType.objects.get_for_model(model, for_concrete_model=True)
        try:
            if ref['@id'].startswith('_:'):
                return next(
                    change.target
                    for change in self._changes_cache
                    if change.target_type == ct
                    and change.node_id == ref['@id']
                    and change.target
                )
            return model._meta.concrete_model.objects.get(pk=IDObfuscator.decode_id(ref['@id']))
        except (StopIteration, model.DoesNotExist) as ex:
            raise Exception('Could not resolve reference {}'.format(ref)) from ex

    def __repr__(self):
        return '<{}({}, {}, {} changes)>'.format(self.__class__.__name__, self.STATUS[self.status].upper(), self.normalized_data.source, self.changes.count())

class Change(models.Model):
    TYPE = Choices((0, 'create', _('create')), (1, 'merge', _('merge')), (2, 'update', _('update')))

    objects = ChangeManager()

    change = JSONField()
    node_id = models.TextField()

    type = models.IntegerField(choices=TYPE, editable=False)
    # The non-concrete type that this change has made
    model_type = models.ForeignKey(ContentType, related_name='+', db_index=False)

    target_id = models.PositiveIntegerField(null=True)
    target = GenericForeignKey('target_type', 'target_id')
    target_type = models.ForeignKey(ContentType, related_name='target_%(class)s')

    target_version_type = models.ForeignKey(ContentType, related_name='target_version_%(class)s', db_index=False)
    target_version_id = models.PositiveIntegerField(null=True, db_index=False)
    target_version = GenericForeignKey('target_version_type', 'target_version_id')

    change_set = models.ForeignKey(ChangeSet, related_name='changes')

    class Meta:
        ordering = ('pk', )

    def accept(self, save=True):
        # Little bit of blind faith here that all requirements have been accepted
        assert self.change_set.status == ChangeSet.STATUS.pending, 'Cannot accept a change with status {}'.format(self.change_set.status)
        logger.debug('Accepting change node ({}, {})'.format(ContentType.objects.get_for_id(self.model_type_id), self.node_id))
        ret = self._accept(save)

        if save:
            # Psuedo hack, sources.add(...) tries to do some safety checks.
            # Don't do that. We have a database. That is its job. Let it do its job.
            through_meta = ret._meta.get_field('sources').rel.through._meta

            with connection.cursor() as cursor:
                cursor.execute('''
                    INSERT INTO "{0}"
                        ("{1}", "{2}")
                    VALUES
                        (%s, %s)
                    ON CONFLICT DO NOTHING;
                '''.format(
                    through_meta.db_table,
                    through_meta.get_field(ret._meta.concrete_model._meta.model_name).column,
                    through_meta.get_field('shareuser').column,
                ), (ret.pk, self.change_set.normalized_data.source_id))

            self.save()
        else:
            logger.warning('Calling accept with save=False will not update the sources field')

        return ret

    def _accept(self, save):
        if self.type == Change.TYPE.create:
            return self._create(save=save)
        if self.type == Change.TYPE.update:
            return self._update(save=save)
        return self._merge(save=save)

    def _create(self, save=True):
        resolved_change = self._resolve_change()
        inst = ContentType.objects.get_for_id(self.model_type_id).model_class()(change=self, **resolved_change)
        if save:
            inst.save()
        self.target = inst
        return inst

    def _update(self, save=True):
        self.target.change = self

        new_type = self.change.pop('@type', None)
        if new_type:
            self.target.recast('share.{}'.format(new_type))

        self.target.__dict__.update(self._resolve_change())
        if save:
            self.target.save()
        return self.target

    def _merge(self, save=True):
        from share.models.base import ShareObject
        assert save is True, 'Cannot perform merge without saving'

        change = self._resolve_change()
        # Find all fields that reference this model
        fields = [
            field.field for field in
            self.target_type.model_class()._meta.get_fields()
            if field.is_relation
            and not field.many_to_many
            and field.remote_field
            and issubclass(field.remote_field.model, ShareObject)
            and hasattr(field, 'field')
        ]

        # NOTE: Date is pinned up here to ensure its the same for all changed rows
        date_modified = timezone.now()

        for field in fields:
            # Update all rows in "from"
            # Updates the change, the field in question, the version pin of the field in question
            # and date_modified must be manually updated
            field.model.objects.select_for_update().filter(**{
                field.name + '__in': change['from']
            }).update(**{
                'change': self,
                field.name: change['into'],
                field.name + '_version': change['into'].version,
                'date_modified': date_modified,
            })

        # Finally point all from rows' same_as and
        # same_as_version to the canonical model.
        type(change['into']).objects.select_for_update().filter(
            pk__in=[i.pk for i in change['from']]
        ).update(
            change=self,
            same_as=change['into'],
            same_as_version=change['into'].version,
            date_modified=date_modified,
        )

        return change['into']

    def _resolve_change(self):
        change = {}
        for k, v in self.change.items():
            if k == 'extra':
                if not v:
                    continue
                if self.target and self.target.extra:
                    change[k] = self.target.extra
                else:
                    from share.models.base import ExtraData
                    change[k] = ExtraData()
                change[k].change = self
                change[k].data.update({self.change_set.normalized_data.source.username: v})
                change[k].save()
                change[k + '_version_id'] = change[k].version_id
            elif isinstance(v, dict):
                inst = self.change_set._resolve_ref(v)
                change[k] = inst
                try:
                    change[k + '_version_id'] = inst.version_id
                except AttributeError:
                    # this isn't a ShareObject, no worries
                    pass
            elif isinstance(v, list):
                change[k] = [self.change_set._resolve_ref(r) for r in v]
            else:
                change[k] = v
        return change