text:
<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<link rel="import" href="../../components/polymer/polymer.html">

<polymer-element name="x-abstract-editor" attributes="value">
  <script>
    Polymer('x-abstract-editor', {
      value: '',
      meta: null,
      workingValue: null,
      valueChanged: function() {
        this.workingValue = this.value;
      },
      commit: function() {
        this.value = this.format(this.workingValue);
        // it's critical to have an event from the editor UI so we know when
        // a user has changed a value, vs some other form of alteration
        // for the same reason, we float our own changed event
        this.fire('editor-value-changed');
      },
      format: function(value) {
        return value;
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-string-editor" extends="x-abstract-editor">
  <template>
    <style>
      :host {
        display: inline-block;
        width: 95%;
      }
      input {
        border: 1px solid #e4e4e4;
        border-top-color: #cecece;
        color: #333;
        background: #fff;
        padding: 9px 8px;
        margin: 0;
        width: 100%;
        font: inherit;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        /* -webkit-user-select: all;
        -moz-user-select: all;
        user-select: all; */
      }
      input:focus {
        outline: 1px solid #448afd;
      }
      input:invalid {
        outline: 1px solid #d84437;
      }
      input:active {
        background: #ededed;
      }
    </style>
    <input id="input" type="{{type}}" value="{{workingValue}}" autocapitalize="off"
      autocorrect="off" on-change="{{commit}}">
  </template>
  <script>
    Polymer('x-string-editor', {
      type: 'text',
      focus: function() {
        this.$.input.focus();
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-number-editor" extends="x-string-editor">
<script>
    Polymer('x-number-editor', {
      format: function(value) {
        return Number(value);
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-color-editor" extends="x-string-editor">
  <script>
    Polymer('x-color-editor', {
      type: 'color',
      ready: function() {
        // TODO(sjmiles): box-sizing: border-box doesn't play nice with color inputs
        // TODO(sjmiles): is there a way to effect these styles via stylesheet?
        this.$.input.style.boxSizing = 'content-box';
        this.$.input.style.width = '95%';
        this.$.input.style.padding = '5px';
        // TODO(dfreedm): Workaround for http://crbug.com/234801, colorpicker
        // does not update swatch when in shadowdom because of focus issues
        this.$.input.tabindex = -1;
      },
      valueChanged: function() {
        this.workingValue = toHex(this.value);
      },
      format: function(value) {
        return toHex(value);
      }
    });
    function toHex(color) {
      if (!color || color.substr(0, 1) === "#") {
        return color;
      }
      var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color);
      if (nums) {
        var r = parseInt(nums[2], 10).toString(16),
            g = parseInt(nums[3], 10).toString(16),
            b = parseInt(nums[4], 10).toString(16);
        return "#"+ (
          (r.length == 1 ? r + "0" : r) +
          (g.length == 1 ? g + "0" : g) +
          (b.length == 1 ? b + "0" : b)
        );
      }
    }
  </script>
</polymer-element>

<polymer-element name="x-boolean-editor" extends="x-abstract-editor">
  <template>
    <style>
      input {
        font: inherit;
      }
    </style>
    <input id="input" type="checkbox" checked="{{workingValue}}" on-change="{{inputChange}}">
  </template>
  <script>
    Polymer('x-boolean-editor', {
      inputChange: function(event) {
        this.workingValue = event.target.checked;
        this.commit();
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-select-editor" extends="x-abstract-editor" attributes="options">
  <template>
    <style>
      :host {
        display: inline-block;
        width: 95%;
        position: relative;
      }
      select {
        margin-left: 0;
        margin-right: 0;
        width: 100%;
        font: inherit;
        -webkit-user-select: all;
        -moz-user-select: all;
        user-select: all;
      }
    </style>
    <select id="select" on-change="{{selectChange}}"></select>
  </template>
  <script>
    // TODO(sorvell): Template repeat functions specially inside a select
    // by using <option template repeat="{{options}}">{{}}</option>
    // However, this creates an extra space in the select; see
    // due to https://github.com/toolkitchen/mdv/issues/56.
    // For that reason, we're manually iterating these nodes.
    Polymer('x-select-editor', {
      metaChanged: function() {
        this.options = this.meta.options || [];
        // allow template to generate options before setting value
        this.asyncMethod(function() {
          this.$.select.value = this.workingValue;
        });
      },
      optionsChanged: function() {
        this.$.select.value = this.workingValue;
        this.$.select.textContent = '';
        this.options.forEach(function(o) {
          var option = document.createElement('option');
          option.textContent = o;
          this.$.select.appendChild(option);
        }, this);
        /*
        this.asyncMethod(function() {
          if (this.workingValue !== this.$.select.value) {
            this.selectChange();
          }
        });
        */
      },
      selectChange: function() {
        this.workingValue = this.$.select.value;
        this.commit();
      },
      focus: function() {
        this.$.select.focus();
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-text-editor" extends="x-abstract-editor">
  <template>
    <style>
      textarea {
        padding: 6px;
        margin: 0;
        width: 95%;
        /* -webkit-user-select: all;
        -moz-user-select: all;
        user-select: all; */
        overflow: auto;
        vertical-align: middle;
      }
    </style>
    <textarea id="input" on-change="{{commit}}" rows="10"></textarea>
  </template>
  <script>
    Polymer('x-text-editor', {
      workingValueChanged: function() {
        this.$.input.textContent = this.workingValue;
      },
      commit: function() {
        this.workingValue = this.$.input.value;
        this.super();
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-json-editor" extends="x-text-editor">
  <template>
    <shadow></shadow>
  </template>
  <script>
    Polymer('x-json-editor', {
      workingValueChanged: function() {
        this.$.input.textContent = JSON.stringify(this.workingValue);
      },
      format: function(value) {
        return JSON.parse(this.workingValue);
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-range-editor" extends="x-abstract-editor" attributes="min max step defaultValue">
  <template>
    <style>
      :host {
        display: inline-block;
        width: 95%;
        position: relative;
      }
      input {
        padding: 7px 6px 8px;
        margin: 0;
        width: 95%;
        box-sizing: border-box;
        vertical-align: middle;
        -webkit-user-select: all;
        -moz-user-select: all;
        user-select: all;
      }
    </style>
    <input id="input" type="range" value="{{workingValue}}" min="{{min}}" max="{{max}}" step="{{step}}" on-change="{{commit}}">
  </template>
  <script>
    Polymer('x-range-editor', {
      min: 0,
      max: 1,
      step: 0.1,
      defaultValue: 0,
      metaChanged: function() {
        if (this.meta) {
          this.min = this.meta.min;
          this.max = this.meta.max;
          this.step = this.meta.step;
          this.defaultValue = this.meta.defaultvalue;
        }
      },
      defaultValueChanged: function() {
        if (this.workingValue === null || this.workingValue === '') {
          this.workingValue = this.defaultValue || this.min || 0;
        }
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-speech-editor" extends="x-string-editor">
  <script>
    Polymer('x-speech-editor', {
      ready: function() {
        this.$.input.setAttribute('x-webkit-speech');
      }
    });
  </script>
</polymer-element>

<polymer-element name="x-compound-editor" extends="x-abstract-editor">
  <template>
    <x-string-editor style="width: 90px;"></x-string-editor>
    <x-select-editor style="width: 70px;" options="{{options}}"></x-select-editor>
    <x-range-editor style="width: 100px;"></x-range-editor>
  </template>
  <script>
    Polymer('x-compound-editor', {
      options: ['px', 'pt', '%', 'em', 'rem', '']
    });
  </script>
</polymer-element>

<polymer-element name="x-classname-editor" extends="x-string-editor">
  <script>
  (function() {
    Polymer('x-classname-editor', {
      blackList: ['selected-element'],
      valueChanged: function() {
        this.blackListed = [];
        var v = this.value || '';
        for (var i=0, p; (p = this.blackList[i]); i++) {
          if (v.indexOf(p) >= 0) {
            v = v.replace(p, '');
            this.blackListed.push(p);
          }
        }
        this.workingValue = stripWhiteSpace(v);
      },
      format: function(value) {
        value = value + ' ' + this.blackListed.join(' ');
        return stripWhiteSpace(value);
      }
    });

    function stripWhiteSpace(value) {
      return (value || '').replace(/[\s]+/g, ' ').trim();
    }

  })();
  </script>
</polymer-element>


text:
/*!
** \file    /Source/Win32Lib.h
** \brief   Win32Lib abstracts operating systems objects.
******************************************************************************/
#pragma once

const size_t MaxExtLength   = _MAX_EXT;
const size_t MaxFNameLength = _MAX_FNAME;
const size_t MaxPathLength  = _MAX_PATH;

redpajama_set_name: RedPajamaGithub


text:
#ifndef OVR_CRC32_h
#define OVR_CRC32_h

#include "OVR_Types.h"

namespace OVR {

//-----------------------------------------------------------------------------------
// ***** CRC-32

// Polynomial used and algorithm details are proprietary to our sensor board
uint32_t CRC32_Calculate(const void* data, int bytes, uint32_t prevCRC = 0);

} // namespace OVR

#endif


text:
/* -*- C++ -*- */

/****************************************************************************
** Copyright (c) 2001-2014
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/

#ifndef FIX_SESSIONSETTINGS_H
#define FIX_SESSIONSETTINGS_H

#ifdef _MSC_VER
#pragma warning( disable : 4503 4355 4786 4290 )
#endif

#include "Dictionary.h"
#include "SessionID.h"
#include "Exceptions.h"
#include <map>
#include <set>

namespace FIX
{
const char BEGINSTRING[] = "BeginString";
const char SENDERCOMPID[] = "SenderCompID";
const char TARGETCOMPID[] = "TargetCompID";
const char SESSION_QUALIFIER[] = "SessionQualifier";
const char DEFAULT_APPLVERID[] = "DefaultApplVerID";
const char CONNECTION_TYPE[] = "ConnectionType";
const char USE_DATA_DICTIONARY[] = "UseDataDictionary";
const char SEND_RESETSEQNUMFLAG[] = "SendResetSeqNumFlag";
const char SEND_REDUNDANT_RESENDREQUESTS[] = "SendRedundantResendRequests";
const char DATA_DICTIONARY[] = "DataDictionary";
const char TRANSPORT_DATA_DICTIONARY[] = "TransportDataDictionary";
const char APP_DATA_DICTIONARY[] = "AppDataDictionary";
const char USE_LOCAL_TIME[] = "UseLocalTime";
const char START_TIME[] = "StartTime";
const char END_TIME[] = "EndTime";
const char START_DAY[] = "StartDay";
const char END_DAY[] = "EndDay";
const char LOGON_TIME[] = "LogonTime";
const char LOGOUT_TIME[] = "LogoutTime";
const char LOGON_DAY[] = "LogonDay";
const char LOGOUT_DAY[] = "LogoutDay";
const char CHECK_COMPID[] = "CheckCompID";
const char CHECK_LATENCY[] = "CheckLatency";
const char MAX_LATENCY[] = "MaxLatency";
const char HEARTBTINT[] = "HeartBtInt";
const char SOCKET_ACCEPT_PORT[] = "SocketAcceptPort";
const char SOCKET_REUSE_ADDRESS[] = "SocketReuseAddress";
const char SOCKET_CONNECT_HOST[] = "SocketConnectHost";
const char SOCKET_CONNECT_PORT[] = "SocketConnectPort";
const char SOCKET_NODELAY[] = "SocketNodelay";
const char SOCKET_SEND_BUFFER_SIZE[] = "SendBufferSize";
const char SOCKET_RECEIVE_BUFFER_SIZE[] = "ReceiveBufferSize";
const char RECONNECT_INTERVAL[] = "ReconnectInterval";
const char VALIDATE_LENGTH_AND_CHECKSUM[] = "ValidateLengthAndChecksum";
const char VALIDATE_FIELDS_OUT_OF_ORDER[] = "ValidateFieldsOutOfOrder";
const char VALIDATE_FIELDS_HAVE_VALUES[] = "ValidateFieldsHaveValues";
const char VALIDATE_USER_DEFINED_FIELDS[] = "ValidateUserDefinedFields";
const char LOGON_TIMEOUT[] = "LogonTimeout";
const char LOGOUT_TIMEOUT[] = "LogoutTimeout";
const char FILE_STORE_PATH[] = "FileStorePath";
const char MYSQL_STORE_USECONNECTIONPOOL[] = "MySQLStoreUseConnectionPool";
const char MYSQL_STORE_DATABASE[] = "MySQLStoreDatabase";
const char MYSQL_STORE_USER[] = "MySQLStoreUser";
const char MYSQL_STORE_PASSWORD[] = "MySQLStorePassword";
const char MYSQL_STORE_HOST[] = "MySQLStoreHost";
const char MYSQL_STORE_PORT[] = "MySQLStorePort";
const char POSTGRESQL_STORE_USECONNECTIONPOOL[] = "PostgreSQLStoreUseConnectionPool";
const char POSTGRESQL_STORE_DATABASE[] = "PostgreSQLStoreDatabase";
const char POSTGRESQL_STORE_USER[] = "PostgreSQLStoreUser";
const char POSTGRESQL_STORE_PASSWORD[] = "PostgreSQLStorePassword";
const char POSTGRESQL_STORE_HOST[] = "PostgreSQLStoreHost";
const char POSTGRESQL_STORE_PORT[] = "PostgreSQLStorePort";
const char ODBC_STORE_USER[] = "OdbcStoreUser";
const char ODBC_STORE_PASSWORD[] = "OdbcStorePassword";
const char ODBC_STORE_CONNECTION_STRING[] = "OdbcStoreConnectionString";
const char FILE_LOG_PATH[] = "FileLogPath";
const char FILE_LOG_BACKUP_PATH[] = "FileLogBackupPath";
const char SCREEN_LOG_SHOW_INCOMING[] = "ScreenLogShowIncoming";
const char SCREEN_LOG_SHOW_OUTGOING[] = "ScreenLogShowOutgoing";
const char SCREEN_LOG_SHOW_EVENTS[] = "ScreenLogShowEvents";
const char MYSQL_LOG_USECONNECTIONPOOL[] = "MySQLLogUseConnectionPool";
const char MYSQL_LOG_DATABASE[] = "MySQLLogDatabase";
const char MYSQL_LOG_USER[] = "MySQLLogUser";
const char MYSQL_LOG_PASSWORD[] = "MySQLLogPassword";
const char MYSQL_LOG_HOST[] = "MySQLLogHost";
const char MYSQL_LOG_PORT[] = "MySQLLogPort";
const char MYSQL_LOG_INCOMING_TABLE[] = "MySQLLogIncomingTable";
const char MYSQL_LOG_OUTGOING_TABLE[] = "MySQLLogOutgoingTable";
const char MYSQL_LOG_EVENT_TABLE[] = "MySQLLogEventTable";
const char POSTGRESQL_LOG_USECONNECTIONPOOL[] = "PostgreSQLLogUseConnectionPool";
const char POSTGRESQL_LOG_DATABASE[] = "PostgreSQLLogDatabase";
const char POSTGRESQL_LOG_USER[] = "PostgreSQLLogUser";
const char POSTGRESQL_LOG_PASSWORD[] = "PostgreSQLLogPassword";
const char POSTGRESQL_LOG_HOST[] = "PostgreSQLLogHost";
const char POSTGRESQL_LOG_PORT[] = "PostgreSQLLogPort";
const char POSTGRESQL_LOG_INCOMING_TABLE[] = "PostgreSQLLogIncomingTable";
const char POSTGRESQL_LOG_OUTGOING_TABLE[] = "PostgreSQLLogOutgoingTable";
const char POSTGRESQL_LOG_EVENT_TABLE[] = "PostgreSQLLogEventTable";
const char ODBC_LOG_USER[] = "OdbcLogUser";
const char ODBC_LOG_PASSWORD[] = "OdbcLogPassword";
const char ODBC_LOG_CONNECTION_STRING[] = "OdbcLogConnectionString";
const char ODBC_LOG_INCOMING_TABLE[] = "OdbcLogIncomingTable";
const char ODBC_LOG_OUTGOING_TABLE[] = "OdbcLogOutgoingTable";
const char ODBC_LOG_EVENT_TABLE[] = "OdbcLogEventTable";
const char RESET_ON_LOGON[] = "ResetOnLogon";
const char RESET_ON_LOGOUT[] = "ResetOnLogout";
const char RESET_ON_DISCONNECT[] = "ResetOnDisconnect";
const char REFRESH_ON_LOGON[] = "RefreshOnLogon";
const char MILLISECONDS_IN_TIMESTAMP[] = "MillisecondsInTimeStamp";
const char HTTP_ACCEPT_PORT[] = "HttpAcceptPort";
const char PERSIST_MESSAGES[] = "PersistMessages";

/// Container for setting dictionaries mapped to sessions.
class SessionSettings
{
public:
  SessionSettings() {}
  SessionSettings( std::istream& stream ) throw( ConfigError );
  SessionSettings( const std::string& file ) throw( ConfigError );

  /// Check if session setings are present
  const bool has( const SessionID& ) const;

  /// Get a dictionary for a session.
  const Dictionary& get( const SessionID& ) const throw( ConfigError );
  /// Set a dictionary for a session
  void set( const SessionID&, Dictionary ) throw( ConfigError );

  /// Get global default settings
  const Dictionary& get() const { return m_defaults; }
  /// Set global default settings
  void set( const Dictionary& defaults ) throw( ConfigError );

  /// Number of session settings
  size_t size() const { return m_settings.size(); }

  typedef std::map < SessionID, Dictionary > Dictionaries;
  std::set < SessionID > getSessions() const;

private:
  void validate( const Dictionary& ) const throw( ConfigError );

  Dictionaries m_settings;
  Dictionary m_defaults;

  friend std::ostream& operator<<( std::ostream&, const SessionSettings& );
};
/*! @} */

std::istream& operator>>( std::istream&, SessionSettings& )
throw( ConfigError );
std::ostream& operator<<( std::ostream&, const SessionSettings& );
}

#endif //FIX_SESSIONSETTINGS_H


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;

static public class VHUI
{
    #region Constants
    static readonly Color DefaultTextColor = new Color(0.196f, 0.196f, 0.196f, 1);
    //static readonly Color DefaultPanelColor = new Color(1, 1, 1, 100f / 255f);
    #endregion

    #region Functions
    static public Canvas CreateCanvas(string canvasName, int sortingOrder)
    {
        return CreateCanvas(canvasName, null, sortingOrder, RenderMode.ScreenSpaceOverlay);
    }

    static public Canvas CreateCanvas(string canvasName, GameObject parent, int sortingOrder)
    {
        return CreateCanvas(canvasName, parent, sortingOrder, RenderMode.ScreenSpaceOverlay);
    }

    static public Canvas CreateCanvas(string canvasName, int sortingOrder, RenderMode renderMode)
    {
        return CreateCanvas(canvasName, null, sortingOrder, RenderMode.ScreenSpaceOverlay);
    }

    static public Canvas CreateCanvas(string canvasName, GameObject parent, int sortingOrder, RenderMode renderMode)
    {
        GameObject canvasGO = new GameObject("Canvas", new System.Type[] { typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster), typeof(CanvasGroup) } );
        canvasGO.name = canvasName;
        if (parent != null)
            canvasGO.transform.SetParent(parent.transform);

        Canvas canvas = canvasGO.GetComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        canvas.sortingOrder = sortingOrder;

        // need an event system too if there isn't one
        if (GameObject.FindObjectOfType<EventSystem>() == null)
        {
            EventSystem eventSystem = GameObject.Instantiate(Resources.Load<EventSystem>("vhAssetsEventSystem"));
            eventSystem.name = eventSystem.name.Replace("(Clone)", "");
        }

        return canvas;
    }

    static public Image CreateImage(string goName, Transform parent)
    {
        return CreateImage(goName, parent, null);
    }

    static public Image CreateImage(string goName, Transform parent, Sprite sprite)
    {
        Image image = GameObject.Instantiate(Resources.Load<Image>("vhAssetsImage"));
        image.transform.SetParent(parent);
        image.name = goName;
        if (sprite != null)
        {
            image.sprite = sprite;
        }
        return image;
    }

    static public Text CreateText(string goName, Transform parent, string text)
    {
        return CreateText(goName, parent, text, DefaultTextColor);
    }

    static public Text CreateText(string goName, Transform parent, string text, Color textColor)
    {
        Text t = GameObject.Instantiate<Text>((Resources.Load<Text>("vhAssetsText")));
        t.name = goName;
        //t.fontSize = 14;
        t.transform.SetParent(parent);
        t.color = textColor;
        t.text = text;
        return t;
    }

    static public Text CreateLayoutText(string goName, Transform parent, string text, Color textColor, float screenPctWidth, float screenPctHeight)
    {
        Text t = CreateText(goName, parent, text, textColor);
        LayoutElement layout = t.gameObject.AddComponent<LayoutElement>();
        SetPreferredLayout(layout, screenPctWidth, screenPctHeight);
        return t;
    }

    static public void SetPreferredLayout(LayoutElement layout, float screenPctWidth, float screenPctHeight)
    {
        layout.preferredWidth = screenPctWidth * Screen.width;
        layout.preferredHeight = screenPctHeight * Screen.height;
    }

    static public InputField CreateInputField(string goName, Transform parent, UnityEngine.Events.UnityAction<string> onEndEditCallback)
    {
        InputField field = GameObject.Instantiate(Resources.Load<InputField>("vhAssetsInputField"));
        field.name = goName;
        field.transform.SetParent(parent);
        if (onEndEditCallback != null)
        {
            field.onEndEdit.AddListener(onEndEditCallback);
        }
        return field;
    }

    static public Button CreateButton(string goName, Transform parent, UnityEngine.Events.UnityAction onClickCallback, string text)
    {
        Button button = GameObject.Instantiate(Resources.Load<Button>("vhAssetsButton"));
        button.name = goName;
        button.transform.SetParent(parent);
        button.GetComponentInChildren<Text>().text = text;
        if (onClickCallback != null)
        {
            button.onClick.AddListener(onClickCallback);
        }
        return button;
    }

    /// <summary>
    /// Creates a button with a Layout Element component.
    /// </summary>
    /// <returns>The layout button.</returns>
    /// <param name="goName">Go name.</param>
    /// <param name="parent">Parent.</param>
    /// <param name="onClickCallback">On click callback.</param>
    /// <param name="text">Text.</param>
    /// <param name="screenPctWidth">Used with Screen.width to calculate preferred Width</param>
    /// <param name="screenPctHeight">Used with Screen.width to calculate preferred Height</param>
    static public Button CreateLayoutButton(string goName, Transform parent, UnityEngine.Events.UnityAction onClickCallback, string text, float screenPctWidth, float screenPctHeight)
    {
        Button button = CreateButton(goName, parent, onClickCallback, text);
        LayoutElement layout = button.gameObject.AddComponent<LayoutElement>();
        layout.preferredWidth = screenPctWidth * Screen.width;
        layout.preferredHeight = screenPctHeight * Screen.height;
        return button;
    }

    static public Toggle CreateToggle(string goName, Transform parent, UnityEngine.Events.UnityAction<bool> onValueChangedCallback, string text, bool isChecked)
    {
        Toggle toggle = GameObject.Instantiate(Resources.Load<Toggle>("vhAssetsToggle"));
        toggle.name = goName;
        toggle.transform.SetParent(parent);
        toggle.isOn = isChecked;
        toggle.GetComponentInChildren<Text>().text = text;
        if (onValueChangedCallback != null)
        {
            toggle.onValueChanged.AddListener(onValueChangedCallback);
        }
        return toggle;
    }

    static public Toggle CreateLayoutToggle(string goName, Transform parent, UnityEngine.Events.UnityAction<bool> onValueChangedCallback,
        string text, bool isChecked, float screenPctWidth, float screenPctHeight)
    {
        Toggle toggle = CreateToggle(goName, parent, onValueChangedCallback, text, isChecked);
        LayoutElement layout = toggle.gameObject.AddComponent<LayoutElement>();
        layout.preferredWidth = screenPctWidth * Screen.width;
        layout.preferredHeight = screenPctHeight * Screen.height;
        return toggle;
    }

    static public Dropdown CreateDropdown(string goName, Transform parent, UnityEngine.Events.UnityAction<int> onValueChangedCallback, List<string> options)
    {
        Dropdown dropdown = GameObject.Instantiate(Resources.Load<Dropdown>("vhAssetsDropdown"));
        dropdown.name = goName;
        dropdown.transform.SetParent(parent);
        if (onValueChangedCallback != null)
        {
            dropdown.onValueChanged.AddListener(onValueChangedCallback);
        }

        if (options != null)
        {
            dropdown.AddOptions(options);
        }
        return dropdown;
    }

    static public Scrollbar CreateScrollbar(string goName, Transform parent, UnityEngine.Events.UnityAction<float> onValueChangedCallback, float val)
    {
        Scrollbar scrollbar = GameObject.Instantiate(Resources.Load<Scrollbar>("vhAssetsScrollbar"));
        scrollbar.name = goName;
        scrollbar.transform.SetParent(parent);
        scrollbar.value = val;
        if (onValueChangedCallback != null)
        {
            scrollbar.onValueChanged.AddListener(onValueChangedCallback);
        }
        return scrollbar;
    }

    static public Slider CreateSlider(string goName, Transform parent, UnityEngine.Events.UnityAction<float> onValueChangedCallback, float val)
    {
        Slider slider = GameObject.Instantiate(Resources.Load<Slider>("vhAssetsSlider"));
        slider.name = goName;
        slider.transform.SetParent(parent);
        slider.value = val;
        if (onValueChangedCallback != null)
        {
            slider.onValueChanged.AddListener(onValueChangedCallback);
        }
        return slider;
    }

    static public RawImage CreateRawImage(string goName, Transform parent, Texture texture)
    {
        RawImage rawImage = GameObject.Instantiate(Resources.Load<RawImage>("vhAssetsRawImage"));
        rawImage.name = goName;
        rawImage.transform.SetParent(parent);
        rawImage.texture = texture;
        return rawImage;
    }

    static public ScrollRect CreateScrollRect(string goName, Transform parent, bool useContentSizeFitter)
    {
        ScrollRect scrollRect = GameObject.Instantiate(Resources.Load<ScrollRect>("vhAssetsScrollView"));
        scrollRect.name = goName;
        scrollRect.transform.SetParent(parent);
        if (useContentSizeFitter)
        {
            GameObject contentGO = VHUtils.FindChildRecursive(scrollRect.gameObject, "Content");
            contentGO.AddComponent<ContentSizeFitter>();
        }
        return scrollRect;
        /*Image image = CreateImage(goName, parent);
        GameObject go = image.gameObject;
        ScrollRect scrollRect = go.AddComponent<ScrollRect>();

        GameObject viewportGO = new GameObject("View Port", new System.Type[] { typeof(Mask), typeof(Image) });
        Image viewportImage = viewportGO.GetComponent<Image>();//CreateImage("View Port", scrollRect.transform);
        viewportGO.transform.SetParent(scrollRect.transform);
        viewportGO.GetComponent<Mask>().showMaskGraphic = false;
        //viewportGO.GetComponent<Mask>().enabled = false;
        viewportGO.GetComponent<RectTransform>().pivot = new Vector2(0, 1);
        //viewportImage.gameObject.AddComponent<Mask>().showMaskGraphic = false;

        StretchToParent(viewportImage.GetComponent<RectTransform>());

        GameObject contentGO = new GameObject("Content");
        contentGO.transform.SetParent(viewportImage.transform);
        if (useContentSizeFitter)
        {
            contentGO.AddComponent<ContentSizeFitter>();
        }

        scrollRect.content = contentGO.GetComponent<RectTransform>();
        scrollRect.content.pivot = new Vector2(0, 1);
        scrollRect.viewport = viewportImage.GetComponent<RectTransform>();

        RectTransform contentRect = contentGO.GetComponent<RectTransform>();
        StretchToParent(contentRect);
        SetAnchors(contentRect, 0, 1, 1, 1);

        scrollRect.horizontalScrollbar = CreateScrollbar("Scrollbar Horizontal", scrollRect.transform, Scrollbar.Direction.LeftToRight);
        scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
        scrollRect.horizontalScrollbarSpacing = -3;

        RectTransform horizontalRect = scrollRect.horizontalScrollbar.GetComponent<RectTransform>();
        horizontalRect.pivot = Vector2.zero;
        SetAnchors(horizontalRect, 0, 0, 1, 0);
        horizontalRect.sizeDelta = new Vector2(17, 20);

        scrollRect.verticalScrollbar = CreateScrollbar("Scrollbar Vertical", scrollRect.transform, Scrollbar.Direction.BottomToTop);
        scrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
        scrollRect.verticalScrollbarSpacing = -3;

        RectTransform verticalRect = scrollRect.verticalScrollbar.GetComponent<RectTransform>();
        verticalRect.pivot = Vector2.one;
        SetAnchors(verticalRect, 1, 0, 1, 1);
        verticalRect.sizeDelta = new Vector2(20, 17);

        return scrollRect;*/
    }

    public static Scrollbar CreateScrollbar(string goName, Transform parent, Scrollbar.Direction direction)
    {
        Scrollbar scrollbar = GameObject.Instantiate(Resources.Load<Scrollbar>("vhAssetsScrollbar"));
        scrollbar.transform.SetParent(parent);
        return scrollbar;

        /*Image image = CreateImage(goName, parent);
        Scrollbar scrollbar = image.gameObject.AddComponent<Scrollbar>();
        image.color = DefaultPanelColor;

        scrollbar.direction = direction;
        GameObject slidingArea = new GameObject("Sliding Area", new System.Type[] { typeof(RectTransform) } );
        slidingArea.transform.SetParent(scrollbar.transform);
        StretchToParent(slidingArea.GetComponent<RectTransform>());
        slidingArea.GetComponent<RectTransform>().sizeDelta = new Vector2(-20, -20);

        //Object o = Resources.Load("UI/Skin/UISprite");

        Image handle = CreateImage("Handle", slidingArea.transform);
        RectTransform handleRect = handle.GetComponent<RectTransform>();
        //StretchToParent(handleRect);
        handleRect.sizeDelta = new Vector2(20, 20);

        scrollbar.handleRect = handleRect;
        return scrollbar;*/
    }

    public static T CreateLayoutGroup<T>(string goName, Transform parent) where T : LayoutGroup
    {
        return CreateLayoutGroup<T>(goName, parent, new RectOffset(), TextAnchor.UpperLeft);
    }

    public static T CreateLayoutGroup<T>(string goName, Transform parent, RectOffset padding, TextAnchor childAlignment) where T : LayoutGroup
    {
        GameObject go = new GameObject(goName, new System.Type[] { typeof(RectTransform), typeof(T) } );
        go.transform.SetParent(parent);
        T group = go.GetComponent<T>();
        group.padding = padding;
        group.childAlignment = childAlignment;
        return group;
    }

    static public void StretchToParent(RectTransform rectTransform)
    {
        StretchToParent(rectTransform, 0, 0, 0, 0);
    }

    static public void StretchToParent(RectTransform rectTransform, float leftInset, float bottomInset, float rightInset, float topInset)
    {
        rectTransform.anchorMin = Vector2.zero;
        rectTransform.anchorMax = Vector2.one;
        SetInset(rectTransform, leftInset, bottomInset, rightInset, topInset);
    }

    public static void SetAnchors(RectTransform rectTransform, float minX, float minY, float maxX, float maxY)
    {
        rectTransform.anchorMin = new Vector2(minX, minY);
        rectTransform.anchorMax = new Vector2(maxX, maxY);
    }

    public static void SetInset(RectTransform rectTransform, float leftInset, float bottomInset, float rightInset, float topInset)
    {
        rectTransform.offsetMin = new Vector2(leftInset, bottomInset);
        rectTransform.offsetMax = new Vector2(rightInset, topInset);
    }

    static public void FadeAlpha(this Text text, float fadeTime, float startAlpha, float targetAlpha)
    {
        text.StartCoroutine(FadeAlphaInternal(text, fadeTime, startAlpha, targetAlpha));
    }

    static IEnumerator FadeAlphaInternal(Text text, float fadeTime, float startAlpha, float targetAlpha)
    {
        float t = 0;
        Color holder = text.color;

        while (t < fadeTime)
        {
            holder.a = Mathf.SmoothStep(startAlpha, targetAlpha, t / fadeTime);
            text.color = holder;
            yield return new WaitForEndOfFrame();
            t += Time.deltaTime;
            //Debug.Log(holder.a);
        }
    }

    static public void FadeAlphaInOut(this Text text, float totalFadeTime, float startRampTime, float endRampTime)
    {
        // fades text in for startRampTime, fades text out for endRampTime, over a total of totalFadeTime
        if (text.gameObject.activeSelf)
        {
            text.StartCoroutine(FadeAlphaInOutInternal(text, totalFadeTime, startRampTime, endRampTime));
        }
    }

    static IEnumerator FadeAlphaInOutInternal(Text text, float totalFadeTime, float startRampTime, float endRampTime)
    {
        const float startAlpha = 0;
        const float midAlpha = 1;
        const float endAlpha = 0;

        float startTime = Time.time;
        float startEndTime = (startTime + totalFadeTime) - endRampTime;  // time we need to start fading out
        float curTime = Time.time;
        Color color = text.color;

        while (curTime < startTime + totalFadeTime)
        {
            if (curTime < startTime + startRampTime)  // fade in
                color.a = Mathf.Lerp(startAlpha, midAlpha, (curTime - startTime) / startRampTime);
            else if (curTime > startEndTime)  // fade out
                color.a = Mathf.Lerp(midAlpha, endAlpha, (curTime - startEndTime) / endRampTime);
            else
                color.a = midAlpha;

            text.color = color;

            //Debug.Log(string.Format("{0} {1} {2} {3} {4} {5}", curTime, startTime, startTime + fadeTime, startTime + startRampTime, startEndTime, color.a));

            yield return new WaitForEndOfFrame();
            curTime = Time.time;
        }

        text.color = new Color(text.color.r, text.color.g, text.color.b, 0);
    }

    public static int CalculateTextWidth(this Text text)
    {
        return CalculateTextWidth(text.text, text.font, text.fontSize);
    }

    public static int CalculateTextWidth(string text, Font font, int fontSize)
    {
        int totalLength = 0;
        CharacterInfo characterInfo = new CharacterInfo();

        char[] arr = text.ToCharArray();

        foreach (char c in arr)
        {
            font.GetCharacterInfo(c, out characterInfo, fontSize);

            totalLength += characterInfo.advance;
        }

        return totalLength;
    }

    /// <summary>
    /// Inserts the breaks based on the number of pixels specified in the breakInterval
    /// </summary>
    /// <param name="text">Text.</param>
    /// <param name="breakInterval">Number of pixels before a newline is inserted</param>
    public static void InsertBreaks(this Text text, int breakIntervalPixels)
    {
        text.text = InsertBreaks(text.text, text.font, text.fontSize, breakIntervalPixels);
    }

    public static string InsertBreaks(string text, Font font, int fontSize, int breakIntervalPixels)
    {
        int length = 0;
        Font myFont = font;
        CharacterInfo characterInfo = new CharacterInfo();
        text = text.Replace("\r\n", "\n");

        for (int i = 0; i < text.Length; i++)
        {
            char c = text[i];
            if (c == '\n')
            {
                length = 0;
                continue;
            }

            myFont.GetCharacterInfo(c, out characterInfo, fontSize);
            length += characterInfo.advance;

            if (length > breakIntervalPixels)
            {
                length = 0;
                text = text.Insert(i, "\n");
                i++;
            }
        }
        return text;
    }

    public static int CalculateNumTextLines(this Text text)
    {
        int msgWidth = text.CalculateTextWidth();
        return Mathf.Max(1, Mathf.CeilToInt((float)msgWidth / (float)Screen.width));
    }
    #endregion
}


text:
import time
from google.cloud import logging
from google.gax.errors import RetryError

'''
So we are seeing cases on the UDU sever where the Google default credentials expire every
hour, and are useless for about five minutes. If you try to log something, you get a nasty
RetryError. If we get one, try to recover:
'''

class Safe_Logger(object):
    def __init__(self, log_point):
        self.log_point = log_point
        self.logging_client = logging.Client()
        self.logger = self.logging_client.logger(log_point)

    def log_text(self, text, severity='INFO'):
        sending = True
        try_count = 10
        while sending and try_count > 0:
            try:
                self.logger.log_text(text, severity=severity)
                sending = False
            except RetryError:
                time.sleep(2)
                self.logging_client = logging.Client()
                self.logger = self.logging_client.logger(self.log_point)
                try_count -= 1


text:
from __future__ import absolute_import

from __future__ import unicode_literals
from .http import parse_quoted_string, parse_token

import logging

from six import StringIO
from six.moves import range

# Make sure a NullHandler is available
# This was added in Python 2.7/3.2
try:
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

l = logging.getLogger(__name__)
l.addHandler(NullHandler())

_LWS=[chr(9), ' ', '\r', '\n']
_ILLEGAL_TOKEN_CHARACTERS = (
    [chr(n) for n in range(0-31)] + # control characters
    [chr(127)] + # DEL
    ['(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' '] +
    [chr(9)]) # horizontal tab

class State(object):
    def character(self, c):
        return self.consume(c)

    def close(self):
        return self.eof()

    def eof(self):
        raise ValueError('EOF not permitted in this state.')

    '''
    Return False to keep the current state, or True to pop it
    '''
    def consume(c):
        raise Execption('Unimplemented')

class ParentState(State):
    def __init__(self):
        super(State, self).__init__()
        self.child = None

    def close(self):
        if self.child:
            return self.handle_child_return(self.child.close())
        else:
            return self.eof()

    def push_child(self, child, c=None):
        self.child = child
        if c is not None:
            return self.send_to_child(c)
        else:
            return False

    def send_to_child(self, c):
        return self.handle_child_return(self.child.character(c))

    def handle_child_return(self, returned_value):
        if returned_value:
            child = self.child
            self.child = None
            return self.child_complete(child)
        return False

    '''
    Return False to keep the current state, or True to pop it.
    '''
    def child_complete(self, child):
        return False

    def character(self, c):
        if self.child:
            return self.send_to_child(c)
        else:
            return self.consume(c)

    def consume(self, c):
        return False

class EscapedCharacterState(State):
    def __init__(self, io):
        super(EscapedCharacterState, self).__init__()
        self.io = io

    def consume(self, c):
        self.io.write(c)
        return True

class KeyTrailingWhitespaceState(State):
    def consume(self, c):
        if c in _LWS:
            return False
        elif c == '=':
            return True
        else:
            raise ValueError("Expected whitespace or '='")

class ValueLeadingWhitespaceState(ParentState):
    def __init__(self, io):
        super(ValueLeadingWhitespaceState, self).__init__()
        self.io = io

    def consume(self, c):
        if c in _LWS:
            return False
        elif c == '"':
            return self.push_child(QuotedValueState(self.io))
        elif c in _ILLEGAL_TOKEN_CHARACTERS:
            raise ValueError('The character %r is not a legal token character' % c)
        else:
            self.io.write(c)
            return self.push_child(UnquotedValueState(self.io))

    def child_complete(self, child):
        return True

class ValueTrailingWhitespaceState(State):
    def eof(self):
        return True

    def consume(self, c):
        if c in _LWS:
            return False
        elif c == ',':
            return True
        else:
            raise ValueError("Expected whitespace, ',', or EOF")

class BaseQuotedState(ParentState):
    def __init__(self, io):
        super(BaseQuotedState, self).__init__()
        self.key_io = io

    def consume(self, c):
        if c == '\\':
            return self.push_child(EscapedCharacterState(self.key_io))
        elif c == '"':
            return self.push_child(self.TrailingWhitespaceState())
        else:
            self.key_io.write(c)
            return False

    def child_complete(self, child):
        if type(child) == EscapedCharacterState:
            return False
        elif type(child) == self.TrailingWhitespaceState:
            return True

class BaseUnquotedState(ParentState):
    def __init__(self, io):
        super(BaseUnquotedState, self).__init__()
        self.io = io

    def consume(self, c):
        if c == self.terminating_character:
            return True
        elif c in _LWS:
            return self.push_child(self.TrailingWhitespaceState())
        elif c in _ILLEGAL_TOKEN_CHARACTERS:
            raise ValueError('The character %r is not a legal token character' % c)
        else:
            self.io.write(c)
            return False

    def child_complete(self, child):
        # type(child) == self.TrailingWhitespaceState
        return True

class QuotedKeyState(BaseQuotedState):
    TrailingWhitespaceState = KeyTrailingWhitespaceState

class QuotedValueState(BaseQuotedState):
    TrailingWhitespaceState = ValueTrailingWhitespaceState

class UnquotedKeyState(BaseUnquotedState):
    TrailingWhitespaceState = KeyTrailingWhitespaceState
    terminating_character = '='

class UnquotedValueState(BaseUnquotedState):
    TrailingWhitespaceState = ValueTrailingWhitespaceState
    terminating_character  = ','

    def eof(self):
        return True

class NewPartState(ParentState):
    def __init__(self, parts):
        super(NewPartState, self).__init__()
        self.parts = parts
        self.key_io = StringIO()
        self.value_io = StringIO()

    def consume(self, c):
        if c in _LWS:
            return False
        elif c == '"':
            return self.push_child(QuotedKeyState(self.key_io))
        elif c in _ILLEGAL_TOKEN_CHARACTERS:
            raise ValueError('The character %r is not a legal token character' % c)
        else:
            self.key_io.write(c)
            return self.push_child(UnquotedKeyState(self.key_io))

    def child_complete(self, child):
        if type(child) in [QuotedKeyState, UnquotedKeyState]:
            return self.push_child(ValueLeadingWhitespaceState(self.value_io))
        else:
            self.parts[self.key_io.getvalue()] = self.value_io.getvalue()
            return True

class FoundationState(ParentState):
    def __init__(self, defaults):
        super(FoundationState, self).__init__()
        self.parts = defaults.copy()

    def result(self):
        return self.parts

    def consume(self, c):
        return self.push_child(NewPartState(self.parts), c)

def parse_parts(parts_string, defaults={}):
    state_machine = FoundationState(defaults)
    index = 0
    try:
        for c in parts_string:
            state_machine.character(c)
            index += 1
        state_machine.close()
        return state_machine.result()
    except ValueError as e:
        annotated_parts_string = "%s[%s]%s" % (parts_string[0:index],
                                               index < len(parts_string) and parts_string[index] or '',
                                               index + 1 < len(parts_string) and parts_string[index+1:] or '')
        l.exception("Failed to parse the Digest string "
                    "(offending character is in []): %r" % annotated_parts_string)
        return None

def format_parts(**kwargs):
    return ", ".join(['%s="%s"' % (k, v) for (k, v) in kwargs.items()])


text:
/* SCP UART module registers */

#ifndef __CROS_EC_UART_REGS_H
#define __CROS_EC_UART_REGS_H

#include "registers.h"

/* Chip specific function for setting UART pinmux. */
void uart_init_pinmux(void);

/* DLAB (Divisor Latch Access Bit) == 0 */

/* (Read) receiver buffer register */
#define UART_RBR(n) UART_REG(n, 0)
/* (Write) transmitter holding register */
#define UART_THR(n) UART_REG(n, 0)
/* (Write) interrupt enable register */
#define UART_IER(n) UART_REG(n, 1)
#define UART_IER_RDI BIT(0) /* received data */
#define UART_IER_THRI BIT(1) /* THR empty */
#define UART_IER_RLSI BIT(2) /* receiver LSR change */
#define UART_IER_MSI BIT(3) /* MSR change */
/* (Read) interrupt identification register */
#define UART_IIR(n) UART_REG(n, 2)
#define UART_IIR_ID_MASK 0x0e
#define UART_IIR_MSI 0x00 /* modem status change */
#define UART_IIR_NO_INT 0x01 /* no int pending */
#define UART_IIR_THRI 0x02 /* THR empty */
#define UART_IIR_RDI 0x04 /* received data available */
#define UART_IIR_RLSI 0x06 /* line status change */
/* (Write) FIFO control register */
#define UART_FCR(n) UART_REG(n, 2)
#define UART_FCR_ENABLE_FIFO BIT(0) /* enable FIFO */
#define UART_FCR_CLEAR_RCVR BIT(1) /* clear receive FIFO */
#define UART_FCR_CLEAR_XMIT BIT(2) /* clear transmit FIFO */
#define UART_FCR_DMA_SELECT BIT(3) /* select DMA mode */
/* (Write) line control register */
#define UART_LCR(n) UART_REG(n, 3)
#define UART_LCR_WLEN5 0 /* word length 5 bits */
#define UART_LCR_WLEN6 1
#define UART_LCR_WLEN7 2
#define UART_LCR_WLEN8 3
#define UART_LCR_STOP BIT(2) /* stop bits: 1bit, 2bits */
#define UART_LCR_PARITY BIT(3) /* parity enable */
#define UART_LCR_EPAR BIT(4) /* even parity */
#define UART_LCR_SPAR BIT(5) /* stick parity */
#define UART_LCR_SBC BIT(6) /* set break control */
#define UART_LCR_DLAB BIT(7) /* divisor latch access */
/* (Write) modem control register */
#define UART_MCR(n) UART_REG(n, 4)
/* (Read) line status register */
#define UART_LSR(n) UART_REG(n, 5)
#define UART_LSR_DR BIT(0) /* data ready */
#define UART_LSR_OE BIT(1) /* overrun error */
#define UART_LSR_PE BIT(2) /* parity error */
#define UART_LSR_FE BIT(3) /* frame error */
#define UART_LSR_BI BIT(4) /* break interrupt */
#define UART_LSR_THRE BIT(5) /* THR empty */
#define UART_LSR_TEMT BIT(6) /* THR empty, line idle */
#define UART_LSR_FIFOE BIT(7) /* FIFO error */
/* (Read) modem status register */
#define UART_MSR(n) UART_REG(n, 6)
/* (Read/Write) scratch register */
#define UART_SCR(n) UART_REG(n, 7)

/* DLAB == 1 */

/* (Write) divisor latch */
#define UART_DLL(n) UART_REG(n, 0)
#define UART_DLH(n) UART_REG(n, 1)

/* MTK extension */
#define UART_HIGHSPEED(n) UART_REG(n, 9)

#endif /* __CROS_EC_UART_REGS_H */


text:
package org.kie.spring.jbpm;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;

import java.util.Arrays;
import java.util.Collection;

import org.drools.core.impl.EnvironmentFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.manager.Context;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.kie.spring.persistence.KieSpringTransactionManager;
import org.kie.spring.persistence.KieSpringTransactionManagerFactory;
import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;

@RunWith(Parameterized.class)
public class KieSpringTransactionManagerFactoryTest extends AbstractJbpmSpringParameterizedTest {

    @Parameterized.Parameters(name = "{index}: {0}")
    public static Collection<Object[]> contextPath() {
        Object[][] data = new Object[][]{
                {JTA_EMF_SINGLETON_PATH, ProcessInstanceIdContext.get()}
        };
        return Arrays.asList(data);
    }

    public KieSpringTransactionManagerFactoryTest(String contextPath,
                                                  Context<?> runtimeManagerContext) {
        super(contextPath,
              runtimeManagerContext);
    }

    @Test
    public void testTransactionManagerSet() throws Exception {
        Object txManager = context.getBean("jbpmTxManager");
        assertNotNull(txManager);
        assertTrue(txManager instanceof JtaTransactionManager);

        JtaTransactionManager jtaManager = (JtaTransactionManager) txManager;

        Environment env = EnvironmentFactory.newEnvironment();
        env.set(EnvironmentName.TRANSACTION_MANAGER,
                jtaManager);
        KieSpringTransactionManagerFactory factory = new KieSpringTransactionManagerFactory();
        Object springTxManager = factory.newTransactionManager(env);
        assertNotNull(springTxManager);
        assertTrue(springTxManager instanceof KieSpringTransactionManager);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testTransactionManagerNotSet() throws Exception {
        Object txManager = context.getBean("jbpmTxManager");
        assertNotNull(txManager);
        assertTrue(txManager instanceof JtaTransactionManager);

        JtaTransactionManager jtaManager = (JtaTransactionManager) txManager;

        Environment env = EnvironmentFactory.newEnvironment();
        KieSpringTransactionManagerFactory factory = new KieSpringTransactionManagerFactory();
        Object springTxManager = factory.newTransactionManager(env);
    }

    @Test
    public void testGlobalTransactionManagerSet() throws Exception {
        Object txManager = context.getBean("jbpmTxManager");
        assertNotNull(txManager);
        assertTrue(txManager instanceof JtaTransactionManager);
        KieSpringTransactionManagerFactory factory = new KieSpringTransactionManagerFactory();
        factory.setGlobalTransactionManager((AbstractPlatformTransactionManager) txManager);
        Object springTxManager = factory.newTransactionManager();
        assertNotNull(springTxManager);
        assertTrue(springTxManager instanceof KieSpringTransactionManager);
    }

    @Test(expected = RuntimeException.class)
    public void testGlobalTransactionManagerNotSet() throws Exception {
        KieSpringTransactionManagerFactory factory = new KieSpringTransactionManagerFactory();

        Object springTxManager = factory.newTransactionManager();
    }
}


text:
package org.apache.deltaspike.test.core.api.config.propertyconfigsource;

import javax.inject.Inject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Collections;

import org.apache.deltaspike.core.api.config.ConfigResolver;
import org.apache.deltaspike.core.impl.config.PropertyFileConfigSource;
import org.junit.Assert;
import org.junit.Test;

public class BaseTestConfigProperty
{
    protected final static String CONFIG_FILE_NAME = "myconfig.properties";
    protected static final String CONFIG_VALUE = "deltaspike.dynamic.reloadable.config.value";

    @Inject
    private MyBean myBean;

    @Test
    public void testInjectConfig()
    {
        Assert.assertEquals("psAwareStringValue", myBean.getStringConfig());
        Assert.assertEquals("DEFAULT", myBean.getStringConfigWithDefault());
        Assert.assertEquals("stringValue", myBean.getStringConfigWithoutProjectStage());
        Assert.assertEquals("parameterizedPsAwareStringValue", myBean.getStringConfigParameterized());

        Assert.assertEquals(false, myBean.getBooleanConfig());
        Assert.assertEquals(MyBean.class, myBean.getClassConfig());
        Assert.assertEquals(5, myBean.getIntConfig());
        Assert.assertEquals(8589934592l, myBean.getLongConfig());
        Assert.assertEquals(-1.1f, myBean.getFloatConfig(), 0);
        Assert.assertEquals(4e40, myBean.getDoubleConfig(), 0);
    }

    @Test
    public void testDynamicReload() throws Exception
    {
        File prop = File.createTempFile("deltaspike-test", ".properties");
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(prop)))
        {
            bw.write(CONFIG_VALUE + "=1\ndeltaspike_reload=1\n");
            bw.flush();
        }
        prop.deleteOnExit();

        final PropertyFileConfigSource dynamicReloadConfigSource = new PropertyFileConfigSource(prop.toURI().toURL());
        ConfigResolver.addConfigSources(Collections.singletonList(dynamicReloadConfigSource));

        Assert.assertEquals("1", ConfigResolver.getPropertyValue(CONFIG_VALUE));

        // we need to take care of file system granularity
        Thread.sleep(2100L);

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(prop)))
        {
            bw.write(CONFIG_VALUE + "=2\ndeltaspike_reload=1\n");
            bw.flush();
        }

        Assert.assertEquals("2", ConfigResolver.getPropertyValue(CONFIG_VALUE));
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Photography</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Graphic Design">
    <link rel="canonical" href="www.frnkdnny.com/projects/2014/07/14/photography-image/">

    <link rel="stylesheet" href="/style.css">

    <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Portfolio

                        About

                        Contact

              Dragon Divas // Web Design

              SimShows // Identity

              728 Outdoor // Product Design

              Beast Mode // Photomanipulation

              Spirit Of Duluth // Branding

              Photography // Lookbook

              Edmonton Rush // Web Design

              US Pond Hockey Championships // Apparel

About

Hey there! My name is Frank Denney. I am a Digital Designer and Photographer from South Korea, raised on a farm in Iowa, currently residing in Minneapolis, MN. I believe in strategy, sweating the details, and more than anything else I believe in making people happy. Over the past decade my main focus has been in sports design working on web and mobile user interfaces, brand identities, bicycles, snowboards, apparel and digital art. I've also had the opportunity to build brands and meaningful visual solutions for a wide variety of other great technology startups, established businesses, and mass retailers as well. In my spare time I enjoy exploring the city on my bike, behind a camera lens, and alongside my girlfriend. I love meeting new people, let's chat!

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

Dragon Divas

Web Design

I was proud to volunteer in the 2014 Overnight Website Challenge, a 24-hour hackathon creating websites for non-profit organizations who may not otherwise have the money to afford. My team was paired with the Dragon Divas, a group of breast-cancer surviving women striving to demonstrate a full and active life following diagnosis through dragon boat racing. I was Lead Designer and Art Director on the project where our contributions to the finished site helped establish an online presence for these strong women.

            ![Test Image](/img/portfolio/dragondivas-detail1.jpg)
![Test Image](/img/portfolio/dragondivas-detail2.jpg)
![Test Image](/img/portfolio/dragondivas-detail3.jpg)
![Test Image](/img/portfolio/dragondivas-detail4.jpg)
![Test Image](/img/portfolio/dragondivas-detail5.jpg)
![Test Image](/img/portfolio/dragondivas-detail6.jpg)
![Test Image](/img/portfolio/dragondivas-detail7.jpg)

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

SimShows

Identity

Sound in Motion is the leading event promotion group in Minneapolis, MN. These guys are legendary in the Twin Cities area, bringing all the biggest EDM shows to life from Deadmau5, Skrillex, Tiesto, David Guetta, and many more.The logo was created to express the coming together of community, culture, and fans who bring the overall experience of Twin Cities Music scene to the top. A concise, geometric and recognizable mark representing the lifestyle, the crowds, and the people coming together as one.

            ![Test Image](/img/portfolio/simshows-detail1.jpg)
![Test Image](/img/portfolio/simshows-detail2.jpg)
![Test Image](/img/portfolio/simshows-detail3.jpg)
![Test Image](/img/portfolio/simshows-detail4.jpg)
![Test Image](/img/portfolio/simshows-detail5.jpg)
![Test Image](/img/portfolio/simshows-detail6.jpg)
![Test Image](/img/portfolio/simshows-detail7.jpg)

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

728 Outdoor

Product Design

I was approached by 728 with the opportunity to contract work on branding, apparel, and product design for a new snowboard brand based out of Fort Collins, Colorado. 728 Outdoor specializes in unique and dynamic snowboards with a bamboo twist for riders who strive to distinguish and elevate their style of riding.

            ![Test Image](/img/portfolio/728-detail1.jpg)
![Test Image](/img/portfolio/728-detail2.jpg)
![Test Image](/img/portfolio/728-detail3.jpg)
![Test Image](/img/portfolio/728-detail4.jpg)
![Test Image](/img/portfolio/728-detail5.jpg)
![Test Image](/img/portfolio/728-detail6.jpg)
![Test Image](/img/portfolio/728-detail7.jpg)
![Test Image](/img/portfolio/728-detail8.jpg)
![Test Image](/img/portfolio/728-detail9.jpg)

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

Beast Mode

Photomanipulation

Beast mode was a personal project of one of my favorite NFL players, Marshawn Lynch a.k.a. Beast Mode. Photo credit AP Photo/Elaine Thompson

            ![Test Image](/img/portfolio/beastmode-detail1.jpg)
![Test Image](/img/portfolio/beastmode-detail2.jpg)
![Test Image](/img/portfolio/beastmode-detail3.jpg)
![Test Image](/img/portfolio/beastmode-detail4.jpg)
![Test Image](/img/portfolio/beastmode-detail5.gif)

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

Spirit Of Duluth

Branding

The Spirit of Duluth Hockey Tournament has helped developed Minnesota's youth for almost forty years. I was part of a small team who volunteered to rebrand and rebuild their website to help give them a facelift pro-bono to help them establish an online presence. The goal of the branding project was to modernize their look while maintaining their strong tradition and heritage. The website design goals were simple, to make a beautiful looking site with very little upkeep on their end. During the tournament our team headed north to Duluth to help run their tournament and show them how to use the tools we created for them.

            ![Test Image](/img/portfolio/spirit-detail1.jpg)
![Test Image](/img/portfolio/spirit-detail2.jpg)
![Test Image](/img/portfolio/spirit-detail3.jpg)
![Test Image](/img/portfolio/spirit-detail4.jpg)
![Test Image](/img/portfolio/spirit-detail5.jpg)
![Test Image](/img/portfolio/spirit-detail6.jpg)
![Test Image](/img/portfolio/spirit-detail7.jpg)
![Test Image](/img/portfolio/spirit-detail8.jpg)
![Test Image](/img/portfolio/spirit-detail9.jpg)
![Test Image](/img/portfolio/spirit-detail10.jpg)
![Test Image](/img/portfolio/spirit-detail11.jpg)
![Test Image](/img/portfolio/spirit.gif)
            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

Photography

Lookbook

I rarely leave home without my camera and love capturing the world around me. Over the past 5 years I've had the opportunity of shooting with wonderful people across a variety of different portraits, weddings, and sporting events.

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

Edmonton Rush

Web Design

The Rush Lacrosse team has gained a reputation in the National Lacrosse League for their edge and high impact play. I was approached by their marketing team to help reinforce their brand image through their website and give them a major facelift. The goal was to build high-impact visuals with a sense of legendary photo treatments. The website was a huge improvement from the digital tools they had in the past. It was awesome partnering with such a great team, building onto a brand with such and introducing them to an online solution for their organization.

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>

US Pond Hockey Championships

Apparel

Over the past 2 years I've had the pleasure of designing the apparel line for the nation's largest outdoor pond hockey tournament. Every year hockey lovers put on their skates and take to the ice to play hockey the way nature intended. In addition, I have also loved capturing the passion and love for the game as the official event photographer.

            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close</button>


text:
A powershell wrapper for RedditSharp

### Install Instructions

Download the project, compile it.

Copy the "Redditsharp" directory to your local modules folder

```powershell
Copy-Item -Recurse -Path RedditSharp -Destination $env:USERPROFILE\Documents\WindowsPowerShell\modules
```

### Using RedditSharp.PowerShell

Examples

```powershell
# get some comments
Import-Module RedditSharp

Start-RedditSession -User "myuser" -Password "password" -ClientId "11111111" -Secret "2222222" -RedirectUri "http://localhost"

$subreddit = Get-Subreddit -Name "example"

$hot = $subreddit.Hot | Select -First 100

# process hot queue
$hot | ForEach-Object {
   $item = $_
   if ($item.Title -contains "something bad") {

      # reply as moderator
      New-Comment -Target $item -Body "this is something bad" | Invoke-ModeratorAction -Action Distinguish -DistinguishType Moderator

      # remove and flair the post
      Invoke-ModeratorAction -Action Remove -Target $item
      Invoke-ModeratorAction -Action Flair -FlairText "Off Topic" -FlairCss = "offTopicCssClass"

   }
}
```

#### Cmdlets

**Get-Comment**

-Subreddit example
-Id a1s2d3 (or t1_a1s2d3)
-Uri http://www.reddit.com/r/spacepope/foo

---

**New-Comment**

-Target VotableThing (Accepts value from pipeline)

-Body "this is example comment text"

-Distinguish Moderator

---

**Edit-Comment**

-Target Comment (Accepts value from pipeline)

-Body "this is the new body"

---

**Get-Post**

-Subreddit example

-Id 1q2w3e (or t3_1q2w3e)

---

**New-Post**
-Subreddit example (Accepts Value from pipeline)

-Title "this is a post title"

-Content string or Uri

---

**Edit-Post**

-Target (Accepts value from pipeline)

-Body "new text/markdown of body"

**Get-Subreddit**

-Name example

---

**Start-RedditSession**

-UserName johndoe

-Password 12345

-ClientId aaaaaaaaaa

-Secret bbbbbbbbbbbbbbbbbbbbbbb

-RedirectUri http://localhost

---

Invoke-ModeratorAction -Action -Target ]


text:
<?php
namespace EnableMediaReplace;
use \EnableMediaReplace\emrFile as File;
use EnableMediaReplace\ShortPixelLogger\ShortPixelLogger as Log;
use EnableMediaReplace\Notices\NoticeController as Notices;

class Replacer
{
  protected $post_id;

  // everything source is the attachment being replaced
  protected $sourceFile; // File Object
  protected $source_post; // wpPost;
  protected $source_is_image;
  protected $source_metadata;
  protected $source_url;

  // everything target is what will be. This is set when the image is replace, the result. Used for replacing.
  protected $targetFile;
  protected $targetName;
  protected $target_metadata;
  protected $target_url;

  protected $target_location = false; // option for replacing to another target location

  protected $replaceMode = 1; // replace if nothing is set
  protected $timeMode = 1;
  protected $datetime = null;

  protected $ThumbnailUpdater; // class

  const MODE_REPLACE = 1;
  const MODE_SEARCHREPLACE = 2;

  const TIME_UPDATEALL = 1; // replace the date
  const TIME_UPDATEMODIFIED = 2; // keep the date, update only modified
  const TIME_CUSTOM = 3; // custom time entry

  public function __construct($post_id)
  {
      $this->post_id = $post_id;

      if (function_exists('wp_get_original_image_path')) // WP 5.3+
      {
          $source_file = wp_get_original_image_path($post_id);
          if ($source_file === false) // if it's not an image, returns false, use the old way.
            $source_file = trim(get_attached_file($post_id, apply_filters( 'emr_unfiltered_get_attached_file', true )));
      }
      else
        $source_file = trim(get_attached_file($post_id, apply_filters( 'emr_unfiltered_get_attached_file', true )));

      Log::addDebug('SourceFile ' . $source_file);
      $this->sourceFile = new File($source_file);

      $this->source_post = get_post($post_id);
      $this->source_is_image = wp_attachment_is('image', $this->source_post);
      $this->source_metadata = wp_get_attachment_metadata( $post_id );

      if (function_exists('wp_get_original_image_url')) // WP 5.3+
      {
        $source_url = wp_get_original_image_url($post_id);
        if ($source_url === false)  // not an image, or borked, try the old way
          $source_url = wp_get_attachment_url($post_id);

        $this->source_url = $source_url;
      }
      else
        $this->source_url = wp_get_attachment_url($post_id);
    //  $this->ThumbnailUpdater = new \ThumbnailUpdater($post_id);
      //$this->ThumbnailUpdater->setOldMetadata($this->source_metadata);
  }

  public function setMode($mode)
  {
    $this->replaceMode = $mode;
  }

  public function setTimeMode($mode, $datetime = 0)
  {
    if ($datetime == 0)
      $datetime = current_time('mysql');

    $this->datetime = $datetime;
    $this->timeMode = $mode;
  }

  /** Replace the sourceFile with a target
  * @param $file String Full Path to the Replacement File. This will usually be an uploaded file in /tmp/
  * @param $fileName String The fileName of the uploaded file. This will be used if sourcefile is not to be overwritten.
  * @throws RunTimeException  Can throw exception if something went wrong with the files.
  */
  public function replaceWith($file, $fileName)
  {
      global $wpdb;
      //$this->targetFile = new File($file);
      $this->targetName = $fileName;
      //$this->targetFile = new File($file); // this will point to /tmp!

      $targetFile = $this->getTargetFile();

      if (is_null($targetFile))
      {
        return null;
      //  $ex = __('Target File could not be set. The source file might not be there. In case of search and replace, a filter might prevent this', "enable-media-replace");
      //  throw new \RuntimeException($ex);
      }

      $targetFileObj = new File($targetFile);
      $result = $targetFileObj->checkAndCreateFolder();
      if ($result === false)
        Log::addError('Directory creation for targetFile failed');

      $this->removeCurrent(); // tries to remove the current files.

      /* @todo See if wp_handle_sideload / wp_handle_upload can be more securely used for this */
      $result_moved = move_uploaded_file($file,$targetFile);

      if (false === $result_moved)
      {
        $ex = sprintf( esc_html__('The uploaded file could not be moved to %1$s. This is most likely an issue with permissions, or upload failed.', "enable-media-replace"), $targetFile );
        throw new \RuntimeException($ex);
      }

      // init targetFile.
      $this->targetFile = new File($targetFile);

      if ($this->sourceFile->getPermissions() > 0)
        chmod( $targetFile, $this->sourceFile->getPermissions() ); // restore permissions
      else {
        Log::addWarn('Setting permissions failed');
      }

      // update the file attached. This is required for wp_get_attachment_url to work.
      update_attached_file($this->post_id, $this->targetFile->getFullFilePath() );
      $this->target_url = wp_get_attachment_url($this->post_id);

      // Run the filter, so other plugins can hook if needed.
      $filtered = apply_filters( 'wp_handle_upload', array(
          'file' => $this->targetFile->getFullFilePath(),
          'url'  => $this->target_url,
          'type' => $this->targetFile->getFileMime(),
      ), 'sideload');

      // check if file changed during filter. Set changed to attached file meta properly.
      if (isset($filtered['file']) && $filtered['file'] != $this->targetFile->getFullFilePath() )
      {
        update_attached_file($this->post_id, $filtered['file'] );
        $this->targetFile = new File($filtered['file']);  // handle as a new file
        Log::addInfo('WP_Handle_upload filter returned different file', $filtered);
      }

      $metadata = wp_generate_attachment_metadata( $this->post_id, $this->targetFile->getFullFilePath() );
      wp_update_attachment_metadata( $this->post_id, $metadata );
      $this->target_metadata = $metadata;

      /** If author is different from replacer, note this */
      $author_id = get_post_meta($this->post_id, '_emr_replace_author', true);

      if ( intval($this->source_post->post_author) !== get_current_user_id())
      {

         update_post_meta($this->post_id, '_emr_replace_author', get_current_user_id());
      }
      elseif ($author_id)
      {

        delete_post_meta($this->post_id, '_emr_replace_author');
      }

      if ($this->replaceMode == self::MODE_SEARCHREPLACE)
      {
         // Write new image title.
         $title = $this->getNewTitle();
         $update_ar = array('ID' => $this->post_id);
         $update_ar['post_title'] = $title;
         $update_ar['post_name'] = sanitize_title($title);
    //     $update_ar['guid'] = wp_get_attachment_url($this->post_id);
         $update_ar['post_mime_type'] = $this->targetFile->getFileMime();
         $post_id = \wp_update_post($update_ar, true);

         // update post doesn't update GUID on updates.
         $wpdb->update( $wpdb->posts, array( 'guid' =>  $this->target_url), array('ID' => $this->post_id) );
         //enable-media-replace-upload-done

         // @todo Replace this one with proper Notices:addError;
         if (is_wp_error($post_id))
         {
          $errors = $post_id->get_error_messages();
         foreach ($errors as $error) {
             echo $error;
          }
         }

      }  // SEARCH REPLACE MODE

      $args = array(
          'thumbnails_only' => ($this->replaceMode == self::MODE_SEARCHREPLACE) ? false : true,
      );

      // Search Replace will also update thumbnails.
      $this->doSearchReplace($args);

      /*if(wp_attachment_is_image($this->post_id))
      {
        $this->ThumbnailUpdater->setNewMetadata($this->target_metadata);
        $result = $this->ThumbnailUpdater->updateThumbnails();
        if (false === $result)
          Log::addWarn('Thumbnail Updater returned false');
      }*/

      // if all set and done, update the date.
      // This must be done after wp_update_posts
      $this->updateDate(); // updates the date.

      // Give the caching a kick. Off pending specifics.
      $cache_args = array(
        'flush_mode' => 'post',
        'post_id' => $this->post_id,
      );

      $cache = new emrCache();
      $cache->flushCache($cache_args);

      do_action("enable-media-replace-upload-done", $this->target_url, $this->source_url);

      return true;
  }

  protected function getNewTitle()
  {
    // get basename without extension
    $title = basename($this->targetFile->getFileName(), '.' . $this->targetFile->getFileExtension());
    $meta = $this->target_metadata;

    if (isset($meta['image_meta']))
    {
      if (isset($meta['image_meta']['title']))
      {
          if (strlen($meta['image_meta']['title']) > 0)
          {
             $title = $meta['image_meta']['title'];
          }
      }
    }

    // Thanks Jonas Lundman   (http://wordpress.org/support/topic/add-filter-hook-suggestion-to)
    $title = apply_filters( 'enable_media_replace_title', $title );

    return $title;
  }

  /** Gets the source file after processing. Returns a file */
  public function getSourceFile()
  {
     return $this->sourceFile;
  }

  public function setNewTargetLocation($new_rel_location)
  {
      $uploadDir = wp_upload_dir();
      $newPath = trailingslashit($uploadDir['basedir']) . $new_rel_location;

      if (! is_dir($newPath))
      {
        Notices::addError(__('Specificed new directory does not exist. Path must be a relative path from the upload directory and exist', 'enable-media-replace'));
        return false;
      }
      $this->target_location = trailingslashit($newPath);
      return true;
  }

  /** Returns a full target path to place to new file. Including the file name!  **/
  protected function getTargetFile()
  {
    $targetPath = null;
    if ($this->replaceMode == self::MODE_REPLACE)
    {
      $targetFile = $this->sourceFile->getFullFilePath(); // overwrite source
    }
    elseif ($this->replaceMode == self::MODE_SEARCHREPLACE)
    {
        $path = $this->sourceFile->getFilePath();
        if ($this->target_location) // Replace to another path.
        {
           $otherTarget = new File($this->target_location . $this->targetName);
           if ($otherTarget->exists())
           {
              Notices::addError(__('In specificied directory there is already a file with the same name. Can\'t replace.', 'enable-media-replace'));
              return null;
           }
           $path = $this->target_location; // if all went well.
        }
        $unique = wp_unique_filename($path, $this->targetName);

        $new_filename = apply_filters( 'emr_unique_filename', $unique, $path, $this->post_id );
        $targetFile = trailingslashit($path) . $new_filename;
    }
    if (is_dir($targetFile)) // this indicates an error with the source.
    {
        Log::addWarn('TargetFile is directory ' . $targetFile );
        $upload_dir = wp_upload_dir();
        if (isset($upload_dir['path']))
        {
          $targetFile = trailingslashit($upload_dir['path']) . wp_unique_filename($targetFile, $this->targetName);
        }
        else {
          $err = __('EMR could not establish a proper destination for replacement', 'enable-media-replace');
          Notices::addError($err);
          Log::addError($err);
        //  throw new \RuntimeException($err);
        //  exit($err); // fallback
          return null;
        }
    }

    return $targetFile;
  }

  /** Tries to remove all of the old image, without touching the metadata in database
  *  This might fail on certain files, but this is not an indication of success ( remove might fail, but overwrite can still work)
  */
  protected function removeCurrent()
  {
    $meta = \wp_get_attachment_metadata( $this->post_id );
    $backup_sizes = get_post_meta( $this->post_id, '_wp_attachment_backup_sizes', true );

    // this must be -scaled if that exists, since wp_delete_attachment_files checks for original_files but doesn't recheck if scaled is included since that the one 'that exists' in WP . $this->source_file replaces original image, not the -scaled one.
    $file = get_attached_file($this->post_id);
    $result = \wp_delete_attachment_files($this->post_id, $meta, $backup_sizes, $file );

  }

  /** Handle new dates for the replacement */
  protected function updateDate()
  {
    global $wpdb;
    $post_date = $this->datetime;
    $post_date_gmt = get_gmt_from_date($post_date);

    $update_ar = array('ID' => $this->post_id);
    if ($this->timeMode == static::TIME_UPDATEALL || $this->timeMode == static::TIME_CUSTOM)
    {
      $update_ar['post_date'] = $post_date;
      $update_ar['post_date_gmt'] = $post_date_gmt;
    }
    else {
      //$update_ar['post_date'] = 'post_date';
    //  $update_ar['post_date_gmt'] = 'post_date_gmt';
    }
    $update_ar['post_modified'] = $post_date;
    $update_ar['post_modified_gmt'] = $post_date_gmt;

    $updated = $wpdb->update( $wpdb->posts, $update_ar , array('ID' => $this->post_id) );

    wp_cache_delete($this->post_id, 'posts');

  }

  protected function doSearchReplace($args = array())
  {
    $defaults = array(
        'thumbnails_only' => false,
    );

    $args = wp_parse_args($args, $defaults);

    global $wpdb;

     // Search-and-replace filename in post database
     // @todo Check this with scaled images.
 		$current_base_url = parse_url($this->source_url, PHP_URL_PATH);// emr_get_match_url( $this->source_url);
    $current_base_url = str_replace('.' . pathinfo($current_base_url, PATHINFO_EXTENSION), '', $current_base_url);

    /** Fail-safe if base_url is a whole directory, don't go search/replace */
    if (is_dir($current_base_url))
    {
      Log::addError('Search Replace tried to replace to directory - ' . $current_base_url);
      Notices::addError(__('Fail Safe :: Source Location seems to be a directory.', 'enable-media-replace'));
      return;
    }

    if (strlen(trim($current_base_url)) == 0)
    {
      Log::addError('Current Base URL emtpy - ' . $current_base_url);
      Notices::addError(__('Fail Safe :: Source Location returned empty string. Not replacing content','enable-media-replace'));
      return;
    }

    //$search_files = $this->getFilesFromMetadata($this->source_metadata);
    //$replace_files = $this->getFilesFromMetadata($this->target_metadata);
  //  $arr = $this->getRelativeURLS();

    /*$search_urls  = emr_get_file_urls( $this->source_url, $this->source_metadata );
    $replace_urls = emr_get_file_urls( $this->target_url, $this->target_metadata );
    $replace_urls = array_values(emr_normalize_file_urls( $search_urls, $replace_urls ));*/

    // get relurls of both source and target.
    $urls = $this->getRelativeURLS();

    if ($args['thumbnails_only'])
    {
      foreach($urls as $side => $data)
      {
        if (isset($data['base']))
        {
          unset($urls[$side]['base']);
        }
        if (isset($data['file']))
        {
          unset($urls[$side]['file']);
        }
      }
    }

    $search_urls = $urls['source'];
    $replace_urls = $urls['target'];

    /* If the replacement is much larger than the source, there can be more thumbnails. This leads to disbalance in the search/replace arrays.
      Remove those from the equation. If the size doesn't exist in the source, it shouldn't be in use either */
    foreach($replace_urls as $size => $url)
    {
      if (! isset($search_urls[$size]))
      {
        Log::addDebug('Dropping size ' . $size . ' - not found in source urls');
        unset($replace_urls[$size]);
      }
    }

    /* If on the other hand, some sizes are available in source, but not in target, try to replace them with something closeby.  */
    foreach($search_urls as $size => $url)
    {
        if (! isset($replace_urls[$size]))
        {
           $closest = $this->findNearestSize($size);
           if ($closest)
           {
              $sourceUrl = $search_urls[$size];
              $baseurl = trailingslashit(str_replace(wp_basename($sourceUrl), '', $sourceUrl));
              Log::addDebug('Nearest size of source ' . $size . ' for target is ' . $closest);
              $replace_urls[$size] = $baseurl . $closest;
           }
           else
           {
             Log::addDebug('Unset size ' . $size . ' - no closest found in source');
           }
        }
    }

    /* If source and target are the same, remove them from replace. This happens when replacing a file with same name, and +/- same dimensions generated.

    After previous loops, for every search there should be a replace size.
    */
    foreach($search_urls as $size => $url)
    {
        $replace_url = $replace_urls[$size];
        if ($url == $replace_url) // if source and target as the same, no need for replacing.
        {
          unset($search_urls[$size]);
          unset($replace_urls[$size]);
        }
    }

    // If the two sides are disbalanced, the str_replace part will cause everything that has an empty replace counterpart to replace it with empty. Unwanted.
    if (count($search_urls) !== count($replace_urls))
    {

      Log::addError('Unbalanced Replace Arrays, aborting', array($search_urls, $replace_urls, count($search_urls), count($replace_urls) ));
      Notices::addError(__('There was an issue with updating your image URLS: Search and replace have different amount of values. Aborting updating thumbnails', 'enable-media-replace'));
      return;
    }

    Log::addDebug('Doing meta search and replace -', array($search_urls, $replace_urls) );
    Log::addDebug('Searching with BaseuRL' . $current_base_url);

    /* Search and replace in WP_POSTS */
    // Removed $wpdb->remove_placeholder_escape from here, not compatible with WP 4.8
 		$posts_sql = $wpdb->prepare(
 			"SELECT ID, post_content FROM $wpdb->posts WHERE post_status = 'publish' AND post_content LIKE %s;",
 			'%' . $current_base_url . '%');

    // json encodes it all differently. Catch json-like encoded urls
    //$json_url = str_replace('/', '\/', ltrim($current_base_url, '/') );

    $postmeta_sql = 'SELECT meta_id, post_id, meta_key, meta_value FROM ' . $wpdb->postmeta . '
        WHERE post_id in (SELECT ID from '. $wpdb->posts . ' where post_status = "publish") AND meta_value like %s';
    $postmeta_sql = $wpdb->prepare($postmeta_sql, '%' . $current_base_url . '%');

    // This is a desparate solution. Can't find anyway for wpdb->prepare not the add extra slashes to the query, which messes up the query.
//    $postmeta_sql = str_replace('[JSON_URL]', $json_url, $postmeta_sql);

    $rsmeta = $wpdb->get_results($postmeta_sql, ARRAY_A);

 		$rs = $wpdb->get_results( $posts_sql, ARRAY_A );

 		$number_of_updates = 0;

    Log::addDebug('Queries', array($postmeta_sql, $posts_sql));
    Log::addDebug('Queries found '  . count($rs) . ' post rows and ' . count($rsmeta) . ' meta rows');

 		if ( ! empty( $rs ) ) {
 			foreach ( $rs AS $rows ) {
 				$number_of_updates = $number_of_updates + 1;
 				// replace old URLs with new URLs.
 				$post_content = $rows["post_content"];
 				//$post_content = str_replace( $search_urls, $replace_urls, $post_content );

        $post_id = $rows['ID'];
        $post_ar = array('ID' => $post_id);
        $post_ar['post_content'] = $this->replaceContent($post_content, $search_urls, $replace_urls);

        if ($post_ar['post_content'] !== $post_content)
        {
          $result = wp_update_post($post_ar);
          if (is_wp_error($result))
          {
            Notice::addError('Something went wrong while replacing' .  $result->get_error_message() );
            Log::addError('WP-Error during post update', $result);
          }
        }

 			}
    }
    if (! empty($rsmeta))
    {
      foreach ($rsmeta as $row)
      {
        $number_of_updates++;
        $content = $row['meta_value'];
        $meta_key = $row['meta_key'];
        $post_id = $row['post_id'];
        $content = $this->replaceContent($content, $search_urls, $replace_urls); //str_replace($search_urls, $replace_urls, $content);

        update_post_meta($post_id, $meta_key, $content);
    //    $sql = $wpdb->prepare('UPDATE ' . $wpdb->postmeta . ' SET meta_value = %s WHERE meta_id = %d', $content, $row['meta_id'] );
    //    $wpdb->query($sql);
      }
    }

  } // doSearchReplace

  private function replaceContent($content, $search, $replace)
  {
    //$is_serial = false;
    $content = maybe_unserialize($content);
    $isJson = $this->isJSON($content);

    if ($isJson)
    {
      Log::addDebug('Found JSON Content');
      $content = json_decode($content);
    }

    if (is_string($content))  // let's check the normal one first.
    {
      $content = str_replace($search, $replace, $content);
    }
    elseif (is_wp_error($content)) // seen this.
    {
       //return $content;  // do nothing.
    }
    elseif (is_array($content) ) // array metadata and such.
    {
      foreach($content as $index => $value)
      {
        $content[$index] = $this->replaceContent($value, $search, $replace); //str_replace($value, $search, $replace);
      }
      //return $content;
    }
    elseif(is_object($content)) // metadata objects, they exist.
    {
      foreach($content as $key => $value)
      {
        $content->{$key} = $this->replaceContent($value, $search, $replace); //str_replace($value, $search, $replace);
      }
      //return $content;
    }

    if ($isJson) // convert back to JSON, if this was JSON. Different than serialize which does WP automatically.
    {
      Log::addDebug('Value was found to be JSON, encoding');
      // wp-slash -> WP does stripslashes_deep which destroys JSON
      $content = wp_slash(json_encode($content, JSON_UNESCAPED_SLASHES));
      Log::addDebug('Content returning', array($content));
    }

    return $content;
  }

  private function getFilesFromMetadata($meta)
  {
        $fileArray = array();
        if (isset($meta['file']))
          $fileArray['file'] = $meta['file'];

        if (isset($meta['sizes']))
        {
          foreach($meta['sizes'] as $name => $data)
          {
            if (isset($data['file']))
            {
              $fileArray[$name] = $data['file'];
            }
          }
        }
      return $fileArray;
  }

  /* Check if given content is JSON format. */
  private function isJSON($content)
  {
      if (is_array($content) || is_object($content))
        return false; // can never be.

      $json = json_decode($content);
      return $json && $json != $content;
  }

  // Get REL Urls of both source and target.
  private function getRelativeURLS()
  {
      $dataArray = array(
          'source' => array('url' => $this->source_url, 'metadata' => $this->getFilesFromMetadata($this->source_metadata) ),
          'target' => array('url' => $this->target_url, 'metadata' => $this->getFilesFromMetadata($this->target_metadata) ),
      );

    //  Log::addDebug('Source Metadata', $this->source_metadata);
  //    Log::addDebug('Target Metadata', $this->target_metadata);

      $result = array();

      foreach($dataArray as $index => $item)
      {
          $result[$index] = array();
          $metadata = $item['metadata'];

          $baseurl = parse_url($item['url'], PHP_URL_PATH);
          $result[$index]['base'] = $baseurl;  // this is the relpath of the mainfile.
          $baseurl = trailingslashit(str_replace( wp_basename($item['url']), '', $baseurl)); // get the relpath of main file.

          foreach($metadata as $name => $filename)
          {
              $result[$index][$name] =  $baseurl . wp_basename($filename); // filename can have a path like 19/08 etc.
          }

      }
  //    Log::addDebug('Relative URLS', $result);
      return $result;
  }

  /** FindNearestsize
  * This works on the assumption that when the exact image size name is not available, find the nearest width with the smallest possible difference to impact the site the least.
  */
  private function findNearestSize($sizeName)
  {

      $old_width = $this->source_metadata['sizes'][$sizeName]['width']; // the width from size not in new image
      $new_width = $this->target_metadata['width']; // default check - the width of the main image

      $diff = abs($old_width - $new_width);
    //  $closest_file = str_replace($this->relPath, '', $this->newMeta['file']);
      $closest_file = wp_basename($this->target_metadata['file']); // mainfile as default

      foreach($this->target_metadata['sizes'] as $sizeName => $data)
      {
          $thisdiff = abs($old_width - $data['width']);

          if ( $thisdiff  < $diff )
          {
              $closest_file = $data['file'];
              if(is_array($closest_file)) { $closest_file = $closest_file[0];} // HelpScout case 709692915
              if(!empty($closest_file)) {
                  $diff = $thisdiff;
                  $found_metasize = true;
              }
          }
      }

      if(empty($closest_file)) return false;

      return $closest_file;
      //$oldFile = $oldData['file'];
      //if(is_array($oldFile)) { $oldFile = $oldFile[0];} // HelpScout case 709692915
      /*if(empty($oldFile)) {
          return false; //make sure we don't replace in this case as we will break the URLs for all the images in the folder.
      } */
    //  $this->convertArray[] = array('imageFrom' => $this->relPath .  $oldFile, 'imageTo' => $this->relPath . $closest_file);

  }

} // class