text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using WiremockUI.Languages;

namespace WiremockUI
{
    public partial class SimpleEditor : IBaseEditor
    {
        #region Search
        private int indexOfSearchText;
        private int start;
        private int searchPanelHeight;
        private int replacePanelHeight;
        #endregion

        private Stack<Func<object>> undoStack = new Stack<Func<object>>();
        private Stack<Func<object>> redoStack = new Stack<Func<object>>();
        private bool enableOptions;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsEdited { get; set; }

        [DefaultValue(true)]
        public bool EnableSearch { get; set; }

        [DefaultValue(true)]
        public bool EnableFormatters { get; set; }

        [DefaultValue(true)]
        public bool EnableHistory { get; set; }

        [DefaultValue(true)]
        public bool EnableOptions
        {
            get => enableOptions;
            set
            {
                this.enableOptions = value;
                if (value)
                    txtContent.ContextMenuStrip = EditorUtils.GetMenuOptions(this);
                else
                    txtContent.ContextMenuStrip = null;
            }
        }

        [DefaultValue(false)]
        public bool EnableReplace
        {
            get
            {
                return pnlReplace.Visible;
            }
            set
            {
                var down = Properties.Resources.arrow_down;
                var up = Properties.Resources.arrow_up;
                pnlReplace.Visible = value;

                if (value)
                {
                    this.imgToggleReplace.Image = up;
                    this.pnlSearch.Height = this.replacePanelHeight;
                }
                else
                {
                    this.imgToggleReplace.Image = down;
                    this.pnlSearch.Height = this.searchPanelHeight;
                }
            }
        }

        public new ContextMenuStrip ContextMenuStrip
        {
            get => txtContent.ContextMenuStrip;
            set => txtContent.ContextMenuStrip = value;
        }

        #region RithTextBox Wrapper

        [Localizable(true)]
        [RefreshProperties(RefreshProperties.All)]
        [DefaultValue("")]
        public string TextValue
        {
            get => txtContent.Text;
            set => txtContent.Text = value;
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int SelectionStart
        {
            get => txtContent.SelectionStart;
            set => txtContent.SelectionStart = value;
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int SelectionLength
        {
            get => txtContent.SelectionLength;
            set => txtContent.SelectionLength = value;
        }

        [DefaultValue(RichTextBoxScrollBars.Both)]
        [Localizable(true)]
        public RichTextBoxScrollBars ScrollBars
        {
            get => txtContent.ScrollBars;
            set => txtContent.ScrollBars = value;
        }

        [DefaultValue(false)]
        public bool ShowSelectionMargin
        {
            get => txtContent.ShowSelectionMargin;
            set => txtContent.ShowSelectionMargin = value;
        }

        [DefaultValue(false)]
        public bool HideSelection
        {
            get => txtContent.HideSelection;
            set => txtContent.HideSelection = value;
        }

        [Browsable(false)]
        public int TextLength
        {
            get => txtContent.TextLength;
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Color SelectionColor
        {
            get => txtContent.SelectionColor;
            set => txtContent.SelectionColor = value;
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Font SelectionFont
        {
            get => txtContent.SelectionFont;
            set => txtContent.SelectionFont = value;
        }

        [Browsable(false)]
        [DefaultValue("")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string SelectedText
        {
            get => txtContent.SelectedText;
            set => txtContent.SelectedText = value;
        }

        [DefaultValue(true)]
        public bool AcceptsTab
        {
            get => txtContent.AcceptsTab;
            set => txtContent.AcceptsTab = value;
        }

        [DefaultValue(true)]
        public bool Multiline
        {
            get => txtContent.Multiline;
            set => txtContent.Multiline = value;
        }

        [DefaultValue(0)]
        public int MaxLength
        {
            get => txtContent.MaxLength;
            set => txtContent.MaxLength = value;
        }

        [DefaultValue(false)]
        public bool DetectUrls
        {
            get => txtContent.DetectUrls;
            set => txtContent.DetectUrls = value;
        }

        [DefaultValue(true)]
        [Localizable(true)]
        public bool WordWrap
        {
            get => txtContent.WordWrap;
            set => txtContent.WordWrap = value;
        }

        [DefaultValue(false)]
        [RefreshProperties(RefreshProperties.Repaint)]
        public bool ReadOnly
        {
            get => txtContent.ReadOnly;
            set => txtContent.ReadOnly = value;
        }

        [DefaultValue(BorderStyle.Fixed3D)]
        public new BorderStyle BorderStyle
        {
            get => txtContent.BorderStyle;
            set
            {
                txtContent.BorderStyle = value;
            }
        }

        #endregion

        public SimpleEditor()
        {
            InitializeComponent();

            this.searchPanelHeight = this.pnlSearch.Height - this.pnlReplace.Height;
            this.replacePanelHeight = this.pnlSearch.Height;

            AcceptsTab = true;
            Multiline = true;
            MaxLength = 0;
            DetectUrls = false;
            HideSelection = false;
            EnableHistory = true;
            EnableOptions = true;
            EnableSearch = true;
            EnableFormatters = true;
            EnableReplace = false;

            this.txtSearchValue.Multiline = false;
            this.btnSearch.Text = Resource.btnSearch;
            this.btnReplace.Text = Resource.btnReplace;
            this.btnReplaceAll.Text = Resource.btnReplaceAll;
            this.pnlSearch.BackColor = Color.FromArgb(207, 214, 229);
        }

        private void txtContent_KeyDown(object sender, KeyEventArgs e)
        {
            var spaces = "    ";
            var keyCanWrite = EditorUtils.KeyIsWritable(e.KeyCode);

            //if (e.KeyCode == Keys.ControlKey && ModifierKeys == Keys.Control) { }
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            {
                ((RichTextBox)sender).SelectAll();
                e.Handled = true;
            }
            else if (e.Modifiers == Keys.None && e.KeyCode == Keys.Tab)
            {
                if (txtContent.ReadOnly)
                    return;

                e.SuppressKeyPress = true;
                var posFinal = txtContent.SelectionStart + spaces.Length;
                txtContent.Text = txtContent.Text.Insert(txtContent.SelectionStart, spaces);
                txtContent.SelectionStart = posFinal;
            }
            else if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.Tab)
            {
                if (txtContent.ReadOnly)
                    return;

                e.SuppressKeyPress = true;

                var posStart = txtContent.SelectionStart - spaces.Length;
                var posEnd = txtContent.SelectionStart - 1;

                if (posStart < 0)
                    return;

                var c = 0;
                for (var i = posStart; i <= posEnd; i++)
                {
                    if (txtContent.Text[i] == ' ')
                        c++;
                }

                if (c == spaces.Length)
                {
                    txtContent.Text = txtContent.Text.Remove(posStart, spaces.Length);
                    txtContent.SelectionStart = posStart;
                }
            }
            else if (EnableSearch && e.Modifiers == Keys.Control && e.KeyCode == Keys.F)
            {
                OpenSearch();
            }
            else if (EnableHistory && e.Modifiers == Keys.Control && e.KeyCode == Keys.Z)
            {
                Undo();
            }
            else if (EnableHistory && e.Modifiers == Keys.Control && e.KeyCode == Keys.Y)
            {
                Redo();
            }
            else if (EnableHistory && keyCanWrite)
            {
                redoStack.Clear();
                StackPush(sender, undoStack);
            }

            if (keyCanWrite)
                IsEdited = true;

            OnKeyDown(e);
        }

        private void StackPush(object sender, Stack<Func<object>> stack)
        {
            var textBox = (RichTextBox)sender;
            var tBT = GetText(textBox, textBox.Text, textBox.SelectionStart);
            stack.Push(tBT);
        }

        private Func<RichTextBox> GetText(RichTextBox textBox, string text, int sel)
        {
            return () =>
            {
                textBox.Text = text;
                textBox.SelectionStart = sel;
                return textBox;
            };
        }

        public void ScrollToCaret()
        {
            txtContent.ScrollToCaret();
        }

        public void Clear()
        {
            txtContent.Clear();
        }

        #region Search

        private void OpenSearch()
        {
            pnlSearch.Visible = !pnlSearch.Visible;
            txtContent.DeselectAll();
            txtSearchValue.Focus();
        }

        private void Search(string replaceText = null)
        {
            int startindex = 0;

            if (txtSearchValue.Text.Length > 0)
            {
                startindex = FindMyText(txtSearchValue.Text.Trim(), start, txtContent.Text.Length);

                if (startindex == -1 && start >= 0) // Not found string and not searching from beginning
                {
                    // Wrap search
                    // int oldStart = start;
                    start = 0;
                    startindex = FindMyText(txtSearchValue.Text.Trim(), start, txtContent.Text.Length);
                }
            }

            // If string was found in the RichTextBox, highlight it
            if (startindex >= 0)
            {
                int endindex = txtSearchValue.Text.Length;
                txtContent.Select(startindex, endindex);

                start = startindex + endindex;
            }
        }

        public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
        {
            // Unselect the previously searched string
            if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
            {
                txtContent.DeselectAll();
            }

            // Set the return value to -1 by default.
            int retVal = -1;

            // A valid starting index should be specified.
            // if indexOfSearchText = -1, the end of search
            if (searchStart >= 0 && indexOfSearchText >= 0)
            {
                // A valid ending index
                if (searchEnd > searchStart || searchEnd == -1)
                {
                    // Find the position of search string in RichTextBox
                    indexOfSearchText = txtContent.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
                    // Determine whether the text was found in richTextBox1.
                    if (indexOfSearchText != -1)
                    {
                        // Return the index to the specified search text.
                        retVal = indexOfSearchText;
                    }
                    else
                    {
                        start = 0;
                        indexOfSearchText = 0;
                    }
                }
            }
            return retVal;
        }

        private void CloseSearch()
        {
            pnlSearch.Visible = false;
            txtContent.DeselectAll();
            EnableReplace = false;
        }

        private void ReplaceAll(string word, string replacement)
        {
            int i = 0;
            int n = 0;
            int a = replacement.Length - word.Length;
            foreach (Match m in Regex.Matches(this.txtContent.Text, word))
            {
                this.txtContent.Select(m.Index + i, word.Length);
                i += a;
                this.txtContent.SelectedText = replacement;
                n++;
            }

            if (i > 0)
                start = 0;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            if (this.SelectedText == this.txtSearchValue.Text)
            {
                this.SelectedText = this.txtReplaceText.Text;
                start = 0;
            }
            else
            {
                Search();
            }
        }

        private void btnReplaceAll_Click(object sender, EventArgs e)
        {
            //this.txtContent.Text = this.txtContent.Text.Replace(this.txtSearchValue.Text, this.txtReplaceText.Text);
            ReplaceAll(this.txtSearchValue.Text, this.txtReplaceText.Text);
        }

        private void txtSearchValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                Search();
        }

        private void imgClose_Click(object sender, EventArgs e)
        {
            CloseSearch();
        }

        private void imgToggleReplace_Click(object sender, EventArgs e)
        {
            EnableReplace = !EnableReplace;
        }

        #endregion

        #region IEditorBase

        public void SelectAll()
        {
            txtContent.SelectAll();
        }

        public void Redo()
        {
            if (redoStack.Count > 0)
            {
                StackPush(txtContent, undoStack);
                redoStack.Pop()();
            }
        }

        public void Undo()
        {
            if (undoStack.Count > 0)
            {
                StackPush(txtContent, redoStack);
                undoStack.Pop()();
            }
        }

        public void Paste()
        {
            txtContent.Paste();
        }

        public void Cut()
        {
            txtContent.Cut();
        }

        public void Copy()
        {
            txtContent.Copy();
        }

        public void ShowReplaceDialog()
        {
            OpenSearch();
        }

        #endregion
    }
}


text:
<?php

namespace Widgets\Form;

class DateTime extends Field{

	public function __construct($options = array()){

		$this->template = 'datetime';

		parent::__construct($options);

	}

}

redpajama_set_name: RedPajamaGithub


text:
require 'nokogiri'
require 'json'
require 'open-uri'

module Cinch
  module Plugins
    class Csgo
      include Cinch::Plugin

      match /(csgo) (.+)/
      match /(help csgo)$/, method: :help

      def execute(m, prefix, csgo, user)
        page = Nokogiri::XML(open("http://steamcommunity.com/id/#{user}/?xml=1"))
        return m.reply "invalid user bru" if page.text == "The specified profile could not be found."
        steamID64 = page.xpath("//steamID64").text
        steamGet = open("http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=#{ENV['STEAM_KEY']}&steamid=#{steamID64}").read
        result = JSON.parse(steamGet)

        total_k, total_d, hs, hit, fired, wins, rounds = 0, 0, 0, 0, 0, 0, 0
        result['playerstats']['stats'].each do |item|
          total_k += item['value'].to_f if item['name'] == 'total_kills'
          total_d += item['value'].to_f if item['name'] == 'total_deaths'
          hs      += item['value'].to_f if item['name'] == 'total_kills_headshot'
          hit     += item['value'].to_f if item['name'] == 'total_shots_hit'
          fired   += item['value'].to_f if item['name'] == 'total_shots_fired'
          wins    += item['value'].to_f if item['name'] == 'total_wins'
          rounds  += item['value'].to_f if item['name'] == 'total_rounds_played'
        end

        kd_ratio = (total_k / total_d).round(2)
        hs_ratio = ((hs / total_k) * 100).round(0)
        accuracy = ((hit / fired) * 100).round(0)
        win_ratio = ((wins / rounds) * 100).round(0)

        m.reply "K/D: #{kd_ratio} | HS: #{hs_ratio}% | ACC: #{accuracy}% | WIN: #{win_ratio}%"
      end

      def help(m)
        m.reply 'Returns K/D ratio, hs percentage, accuracy, and win percentage for specified public Steam username'
      end

    end
  end
end


text:
package microsoft.exchange.webservices.data;

/**
 * Represents a collection of OccurrenceInfo objects.
 */
@EditorBrowsable(state = EditorBrowsableState.Never)
public final class OccurrenceInfoCollection extends
    ComplexPropertyCollection<OccurrenceInfo> {

  /**
   * Initializes a new instance of the <see cref="OccurrenceInfoCollection"/>
   * class.
   */
  protected OccurrenceInfoCollection() {
  }

  /**
   * Creates the complex property.
   *
   * @param xmlElementName Name of the XML element
   * @return OccuranceInfo instance
   */
  @Override
  protected OccurrenceInfo createComplexProperty(String xmlElementName) {
    if (xmlElementName.equals(XmlElementNames.Occurrence)) {
      return new OccurrenceInfo();
    } else {
      return null;
    }
  }

  /**
   * Gets the name of the collection item XML element.
   *
   * @param complexProperty The complex property.
   * @return XML element name.
   */
  @Override
  protected String getCollectionItemXmlElementName(
      OccurrenceInfo complexProperty) {
    return XmlElementNames.Occurrence;
  }

}


text:
import React from 'react';
import { View, ActivityIndicator } from 'react-native';
import Colors from '../../../native-base-theme/variables/commonColor';

const Loading = () => (
  <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
    <ActivityIndicator size="large" color={Colors.brandPrimary} />
  </View>
);

export default Loading;


text:
FROM openjdk:8

COPY target/finapp-1.0-SNAPSHOT-jar-with-dependencies.jar /app/finapp.jar

EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/finapp.jar"]


text:
package com.project.hotel.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ProgressBar;

import com.project.hotel.R;

public class ProgressDialogFragment extends DialogFragment {
    public static final String TAG = ProgressDialogFragment.class.getSimpleName();

    // Note: only the system can call this constructor by reflection.
    public ProgressDialogFragment() {
    }

    public static ProgressDialogFragment getInstance() {
        ProgressDialogFragment fragment = new ProgressDialogFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_progress, null, false);
        ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progress);
        progressBar.getIndeterminateDrawable().setColorFilter(getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
        return view;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                // Disable Back key and Search key
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                    case KeyEvent.KEYCODE_SEARCH:
                        return true;
                    default:
                        return false;
                }
            }
        });
        return dialog;
    }
}


text:
#ifndef VR_SEURAT_IMAGE_IMAGE_UTIL_H_
#define VR_SEURAT_IMAGE_IMAGE_UTIL_H_

#include <utility>

#include "ion/gfx/image.h"
#include "seurat/base/color.h"
#include "seurat/base/ion_util_no_gl.h"
#include "seurat/image/image.h"

namespace seurat {
namespace image {

// Maps a seurat image type to the corresponding 8-bit integer pixel type and
// ion image format.
template <typename ImageType>
struct ConvertImageTraits {};

template <>
struct ConvertImageTraits<image::Image1f> {
  using IntPixelType = base::Color1ui8;
  static constexpr ion::gfx::Image::Format kIonFormat =
      ion::gfx::Image::Format::kAlpha;
};

template <>
struct ConvertImageTraits<image::Image3f> {
  using IntPixelType = base::Color3ui8;
  static constexpr ion::gfx::Image::Format kIonFormat =
      ion::gfx::Image::Format::kRgb888;
};

template <>
struct ConvertImageTraits<image::Image4f> {
  using IntPixelType = base::Color4ui8;
  static constexpr ion::gfx::Image::Format kIonFormat =
      ion::gfx::Image::Format::kRgba8888;
};

// Converts a floating-point Image to the corresponding 8 bits per channel ion
// image format.
template <typename ImageType>
ion::gfx::ImagePtr ConvertSeuratImageToIonImage(const ImageType& simage) {
  using IntPixelType = typename ConvertImageTraits<ImageType>::IntPixelType;
  ion::gfx::ImagePtr img =
      base::CreateImage(ConvertImageTraits<ImageType>::kIonFormat,
                        {simage.Width(), simage.Height()});
  const auto data_container = img->GetData();
  IntPixelType* data = data_container->GetMutableData<IntPixelType>();
  for (int y = 0; y < simage.Height(); ++y) {
    for (int x = 0; x < simage.Width(); ++x) {
      data[y * simage.Width() + x] = simage.At(x, y).AsColorUI8();
    }
  }
  return img;
}

// Converts an 8-bit Image to an ion image in rgba8888 format.
ion::gfx::ImagePtr ConvertSeuratImageToIonImage(const Image4ui8& simage);

// Converts an Ion Image to a Seurat Image.  This templated function is only
// specialized for the supported destination formats.
template <typename ReturnImageType>
ReturnImageType ConvertIonImageToSeuratImage(
    const ion::gfx::ImagePtr& ion_image);

// Returns true if |image| is opaque relative to the |alpha_threshold|.
bool IsOpaque(const Image4f& image, float alpha_threshold);

}  // namespace image
}  // namespace seurat

#endif  // VR_SEURAT_IMAGE_IMAGE_UTIL_H_


text:
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.runtime;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.devtools.build.lib.bugreport.BugReporter;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link MemoryPressureListener}. */
@RunWith(JUnit4.class)
public final class MemoryPressureListenerTest {
  private interface NotificationBean extends GarbageCollectorMXBean, NotificationEmitter {}

  private static final String TENURED_SPACE_NAME = "CMS Old Gen";
  private final NotificationBean mockBean = mock(NotificationBean.class);
  private final NotificationBean mockUselessBean = mock(NotificationBean.class);
  private final BugReporter bugReporter = mock(BugReporter.class);
  private final EventBus eventBus = new EventBus();
  private final RetainedHeapLimiter retainedHeapLimiter = RetainedHeapLimiter.create(bugReporter);
  private final List<MemoryPressureEvent> events = new ArrayList<>();

  @Before
  public void initMocks() {
    when(mockBean.getMemoryPoolNames())
        .thenReturn(new String[] {"not tenured", TENURED_SPACE_NAME});
    when(mockUselessBean.getMemoryPoolNames()).thenReturn(new String[] {"assistant", "adjunct"});
  }

  @Before
  public void registerSubscriber() {
    eventBus.register(
        new Object() {
          @Subscribe
          public void handle(MemoryPressureEvent event) {
            events.add(event);
          }
        });
  }

  @Test
  public void findBeans() {
    assertThat(
        MemoryPressureListener.findTenuredCollectorBeans(
            ImmutableList.of(mockUselessBean, mockBean)))
        .containsExactly(mockBean);
  }

  @Test
  public void createFromBeans_returnsNullIfNoTenuredSpaceBean() {
    assertThat(
            MemoryPressureListener.createFromBeans(
                ImmutableList.of(mockUselessBean), retainedHeapLimiter))
        .isNull();
  }

  @Test
  public void simple() {
    MemoryPressureListener underTest =
        MemoryPressureListener.createFromBeans(
            ImmutableList.of(mockUselessBean, mockBean), retainedHeapLimiter);
    underTest.setEventBus(eventBus);
    verify(mockBean).addNotificationListener(underTest, null, null);
    verify(mockUselessBean, never()).addNotificationListener(any(), any(), any());

    GcInfo mockGcInfo = mock(GcInfo.class);
    String nonTenuredSpaceName = "nope";
    MemoryUsage mockMemoryUsageForNonTenuredSpace = mock(MemoryUsage.class);
    MemoryUsage mockMemoryUsageForTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForTenuredSpace.getUsed()).thenReturn(42L);
    when(mockMemoryUsageForTenuredSpace.getMax()).thenReturn(100L);
    when(mockGcInfo.getMemoryUsageAfterGc())
        .thenReturn(
            ImmutableMap.of(
                nonTenuredSpaceName,
                mockMemoryUsageForNonTenuredSpace,
                TENURED_SPACE_NAME,
                mockMemoryUsageForTenuredSpace));

    Notification notification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    notification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "non-manual", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(notification, null);

    assertThat(events)
        .containsExactly(
            MemoryPressureEvent.newBuilder()
                .setWasManualGc(false)
                .setTenuredSpaceUsedBytes(42L)
                .setTenuredSpaceMaxBytes(100L)
                .build());
  }

  @Test
  public void nullEventBus_doNotPublishEvent() {
    MemoryPressureListener underTest =
        MemoryPressureListener.createFromBeans(
            ImmutableList.of(mockUselessBean, mockBean), retainedHeapLimiter);
    verify(mockBean).addNotificationListener(underTest, null, null);
    verify(mockUselessBean, never()).addNotificationListener(any(), any(), any());

    GcInfo mockGcInfo = mock(GcInfo.class);
    String nonTenuredSpaceName = "nope";
    MemoryUsage mockMemoryUsageForNonTenuredSpace = mock(MemoryUsage.class);
    MemoryUsage mockMemoryUsageForTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForTenuredSpace.getUsed()).thenReturn(42L);
    when(mockMemoryUsageForTenuredSpace.getMax()).thenReturn(100L);
    when(mockGcInfo.getMemoryUsageAfterGc())
        .thenReturn(
            ImmutableMap.of(
                nonTenuredSpaceName,
                mockMemoryUsageForNonTenuredSpace,
                TENURED_SPACE_NAME,
                mockMemoryUsageForTenuredSpace));

    Notification notification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    notification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "non-manual", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(notification, null);

    assertThat(events).isEmpty();
  }

  @Test
  public void manualGc() {
    MemoryPressureListener underTest =
        MemoryPressureListener.createFromBeans(ImmutableList.of(mockBean), retainedHeapLimiter);
    underTest.setEventBus(eventBus);
    verify(mockBean).addNotificationListener(underTest, null, null);

    GcInfo mockGcInfo = mock(GcInfo.class);
    MemoryUsage mockMemoryUsageForTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForTenuredSpace.getUsed()).thenReturn(42L);
    when(mockMemoryUsageForTenuredSpace.getMax()).thenReturn(100L);
    when(mockGcInfo.getMemoryUsageAfterGc())
        .thenReturn(ImmutableMap.of(TENURED_SPACE_NAME, mockMemoryUsageForTenuredSpace));

    Notification notification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    notification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "System.gc()", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(notification, null);

    assertThat(events)
        .containsExactly(
            MemoryPressureEvent.newBuilder()
                .setWasManualGc(true)
                .setTenuredSpaceUsedBytes(42L)
                .setTenuredSpaceMaxBytes(100L)
                .build());
  }

  @Test
  public void doesntInvokeHandlerWhenTenuredSpaceMaxSizeIsZero() {
    MemoryPressureListener underTest =
        MemoryPressureListener.createFromBeans(ImmutableList.of(mockBean), retainedHeapLimiter);
    underTest.setEventBus(eventBus);
    verify(mockBean).addNotificationListener(underTest, null, null);

    GcInfo mockGcInfo = mock(GcInfo.class);
    MemoryUsage mockMemoryUsageForTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForTenuredSpace.getUsed()).thenReturn(42L);
    when(mockMemoryUsageForTenuredSpace.getMax()).thenReturn(0L);
    when(mockGcInfo.getMemoryUsageAfterGc())
        .thenReturn(ImmutableMap.of(TENURED_SPACE_NAME, mockMemoryUsageForTenuredSpace));

    Notification notification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    notification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "non-manual", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(notification, null);

    assertThat(events).isEmpty();
  }

  @Test
  public void findsTenuredSpaceWithNonZeroMaxSize() {
    NotificationBean anotherMockBean = mock(NotificationBean.class);
    String anotherTenuredSpaceName = "G1 Old Gen";
    when(anotherMockBean.getMemoryPoolNames()).thenReturn(new String[] {anotherTenuredSpaceName});

    MemoryPressureListener underTest =
        MemoryPressureListener.createFromBeans(
            ImmutableList.of(mockBean, anotherMockBean), retainedHeapLimiter);
    underTest.setEventBus(eventBus);
    verify(mockBean).addNotificationListener(underTest, null, null);
    verify(anotherMockBean).addNotificationListener(underTest, null, null);

    GcInfo mockGcInfo = mock(GcInfo.class);
    MemoryUsage mockMemoryUsageForTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForTenuredSpace.getUsed()).thenReturn(1L);
    when(mockMemoryUsageForTenuredSpace.getMax()).thenReturn(0L);
    MemoryUsage mockMemoryUsageForAnotherTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForAnotherTenuredSpace.getUsed()).thenReturn(2L);
    when(mockMemoryUsageForAnotherTenuredSpace.getMax()).thenReturn(3L);
    when(mockGcInfo.getMemoryUsageAfterGc())
        .thenReturn(
            ImmutableMap.of(
                TENURED_SPACE_NAME,
                mockMemoryUsageForTenuredSpace,
                anotherTenuredSpaceName,
                mockMemoryUsageForAnotherTenuredSpace));

    Notification notification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    notification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "non-manual", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(notification, null);

    assertThat(events)
        .containsExactly(
            MemoryPressureEvent.newBuilder()
                .setWasManualGc(false)
                .setTenuredSpaceUsedBytes(2L)
                .setTenuredSpaceMaxBytes(3L)
                .build());
  }

  @Test
  public void retainedHeapLimiter_aboveThreshold_handleCrash() {
    MemoryPressureListener underTest =
        MemoryPressureListener.createFromBeans(
            ImmutableList.of(mockUselessBean, mockBean), retainedHeapLimiter);
    underTest.setEventBus(eventBus);
    verify(mockBean).addNotificationListener(underTest, null, null);
    verify(mockUselessBean, never()).addNotificationListener(any(), any(), any());

    GcInfo mockGcInfo = mock(GcInfo.class);
    String nonTenuredSpaceName = "nope";
    MemoryUsage mockMemoryUsageForNonTenuredSpace = mock(MemoryUsage.class);
    MemoryUsage mockMemoryUsageForTenuredSpace = mock(MemoryUsage.class);
    when(mockMemoryUsageForTenuredSpace.getUsed()).thenReturn(101L);
    when(mockMemoryUsageForTenuredSpace.getMax()).thenReturn(100L);
    when(mockGcInfo.getMemoryUsageAfterGc())
        .thenReturn(
            ImmutableMap.of(
                nonTenuredSpaceName,
                mockMemoryUsageForNonTenuredSpace,
                TENURED_SPACE_NAME,
                mockMemoryUsageForTenuredSpace));

    MemoryPressureEvent event =
        MemoryPressureEvent.newBuilder()
            .setWasManualGc(false)
            .setTenuredSpaceUsedBytes(101L)
            .setTenuredSpaceMaxBytes(100L)
            .build();
    Notification notification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    notification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "non-manual", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(notification, null);

    assertThat(events).containsExactly(event);

    MemoryPressureEvent manualGcEvent =
        MemoryPressureEvent.newBuilder()
            .setWasManualGc(true)
            .setTenuredSpaceUsedBytes(101L)
            .setTenuredSpaceMaxBytes(100L)
            .build();
    Notification manualGCNotification =
        new Notification(
            GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION, "test", 123);
    manualGCNotification.setUserData(
        new GarbageCollectionNotificationInfo("gcName", "gcAction", "System.gc()", mockGcInfo)
            .toCompositeData(null));
    underTest.handleNotification(manualGCNotification, null);

    verify(bugReporter).handleCrash(any(), any());
    assertThat(events).containsExactly(event, manualGcEvent);
  }
}


text:
.. _plugins:

Plugins
=======

Plugins contains checks that sauna can run to determine the health of the system. Sauna will
periodically run the checks contained in active plugins and forward the results to active
:ref:`consumers <consumers>`.

Plugins can either be core ones shipped with sauna, or :ref:`your own plugins <custom>` for
monitoring the specific parts of your system.

.. todo:: Find a way to automatically document core plugins. For now you can find the list of core
          `plugins on GitHub <https://github.com/NicolasLM/sauna/tree/master/sauna/plugins/ext>`_.


text:
var TwinTron=require("./twintron");

module.exports=TwinTron;


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="12dp"
    android:height="12dp"
    android:viewportWidth="12"
    android:viewportHeight="12">
  <path
      android:pathData="M5.999,0l6,6l-6,6l-6,-6z"
      android:strokeWidth="1"
      android:fillColor="@color/tooltipBackground"
      android:fillType="evenOdd"
      android:strokeColor="#00000000"/>
</vector>


text:
> This page is part of the [App Framework Documentation](../DOCUMENTATION.md)

<br />

Before you start to work with App Framework, you need to install some free available softare.

## Atom

First of all, you need a code editor. We really recommend Atom, which is open source, supports correct syntax highlighting and is available for macOS, Windows and Linux.

1. Download from [Atom.io](https://atom.io/) the right installer for your operating system
2. Install Atom and open it afterwards
3. Select the *Welcome* tab, disable the checkbox *Show welcome guide when opening Atom* and close the tab
4. Select the *Telemetry Consent* tab and decide whether you want to send statistics or not to Atom
5. Open from the top menu *File > Settings* and select in the left menu *Install*
6. Search for package `language-vue-component` and click on *install*
7. Search for package `linter-eslint` and click on *install*
8. Search for package `editorconfig` and click on *install*
9. Close the settings tab and Atom itself

## Node.js

To run the App Framework scripts and the development server, you need to install [Node.js](https://nodejs.org/), which is available for macOS, Windows and Linux and is free of charge. You can install it with the default settings.

## Xcode

[Xcode](https://developer.apple.com/xcode/) is optional. You need it, if you want to publish your application to the Apple App Store. You can install Xcode only to macOS machines, like iMac or macBook. You can download Xcode free of charge from the macOS App Store.

## Android Studio

Android Studio is optional. You need it, if you want to publish your application to the Google Play Store. It is available free of charge for macOS, Windows and Linux.

To ensure you install Android Studio and its SDK properly, please read the [official installation guide](https://developer.android.com/studio/install.html).

### On Linux

Please take care to unpack Android Studio to one of the following locations to ensure that App Framework will find the *studio.sh* file:

- /bin/android-studio/bin/studio.sh
- /opt/android-studio/bin/studio.sh
- /usr/bin/android-studio/bin/studio.sh
- /usr/local/android-studio/bin/studio.sh
- /usr/local/bin/android-studio/bin/studio.sh

## GitHub desktop client

The GitHub desktop client is optional. We recommend it as a Git client, because GitHub is great for collaboration or as a backup for your own code. The desktop client is available for macOS and Windows and is free of charge.

1. Create an account on [GitHub.com](https://github.com/join)
2. Download from [GitHub.com](https://desktop.github.com/) the right installer for your operating system
3. Install the GitHub desktop client and log in with your credentials
4. Configure your user name and a email address under which you will commit to GitHub
5. Close the GitHub desktop client

## Reboot

At the end of the installation process, you should reboot your computer.


text:
  <button class="close-button" aria-label="Close menu" type="button" data-close>
    ×
  </button>

      Learn

About Foundation

Tutorials

Classes

Case Studies

Brands

      Develop

Frameworks

Foundation for Sites

Foundation for Email

Foundation for Apps

Develop

HTML Templates

Resources

Building Blocks

Yeti Launch

Contribute

Upload

      Support

Support Channels

Premium Support

Foundation Forum

FAQs

      Docs

Sites Docs

Apps Docs

Email Docs

Getting Started

  <button class="close-button" aria-label="Close menu" type="button" data-close>
    ×
  </button>

Foundation

Dot

ZURB

Com

Slash

Sites


text:
package gps

import (
	"log"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/golang/dep/internal/fs"
	"github.com/pkg/errors"
)

// PruneOptions represents the pruning options used to write the dependecy tree.
type PruneOptions uint8

const (
	// PruneNestedVendorDirs indicates if nested vendor directories should be pruned.
	PruneNestedVendorDirs PruneOptions = 1 << iota
	// PruneUnusedPackages indicates if unused Go packages should be pruned.
	PruneUnusedPackages
	// PruneNonGoFiles indicates if non-Go files should be pruned.
	// Files matching licenseFilePrefixes and legalFileSubstrings are kept in
	// an attempt to comply with legal requirements.
	PruneNonGoFiles
	// PruneGoTestFiles indicates if Go test files should be pruned.
	PruneGoTestFiles
)

// PruneOptionSet represents trinary distinctions for each of the types of
// prune rules (as expressed via PruneOptions): nested vendor directories,
// unused packages, non-go files, and go test files.
//
// The three-way distinction is between "none", "true", and "false", represented
// by uint8 values of 0, 1, and 2, respectively.
//
// This trinary distinction is necessary in order to record, with full fidelity,
// a cascading tree of pruning values, as expressed in CascadingPruneOptions; a
// simple boolean cannot delineate between "false" and "none".
type PruneOptionSet struct {
	NestedVendor   uint8
	UnusedPackages uint8
	NonGoFiles     uint8
	GoTests        uint8
}

// CascadingPruneOptions is a set of rules for pruning a dependency tree.
//
// The DefaultOptions are the global default pruning rules, expressed as a
// single PruneOptions bitfield. These global rules will cascade down to
// individual project rules, unless superseded.
type CascadingPruneOptions struct {
	DefaultOptions    PruneOptions
	PerProjectOptions map[ProjectRoot]PruneOptionSet
}

// PruneOptionsFor returns the PruneOptions bits for the given project,
// indicating which pruning rules should be applied to the project's code.
//
// It computes the cascade from default to project-specific options (if any) on
// the fly.
func (o CascadingPruneOptions) PruneOptionsFor(pr ProjectRoot) PruneOptions {
	po, has := o.PerProjectOptions[pr]
	if !has {
		return o.DefaultOptions
	}

	ops := o.DefaultOptions
	if po.NestedVendor != 0 {
		if po.NestedVendor == 1 {
			ops |= PruneNestedVendorDirs
		} else {
			ops &^= PruneNestedVendorDirs
		}
	}

	if po.UnusedPackages != 0 {
		if po.UnusedPackages == 1 {
			ops |= PruneUnusedPackages
		} else {
			ops &^= PruneUnusedPackages
		}
	}

	if po.NonGoFiles != 0 {
		if po.NonGoFiles == 1 {
			ops |= PruneNonGoFiles
		} else {
			ops &^= PruneNonGoFiles
		}
	}

	if po.GoTests != 0 {
		if po.GoTests == 1 {
			ops |= PruneGoTestFiles
		} else {
			ops &^= PruneGoTestFiles
		}
	}

	return ops
}

func defaultCascadingPruneOptions() CascadingPruneOptions {
	return CascadingPruneOptions{
		DefaultOptions:    PruneNestedVendorDirs,
		PerProjectOptions: map[ProjectRoot]PruneOptionSet{},
	}
}

var (
	// licenseFilePrefixes is a list of name prefixes for license files.
	licenseFilePrefixes = []string{
		"license",
		"licence",
		"copying",
		"unlicense",
		"copyright",
		"copyleft",
	}
	// legalFileSubstrings contains substrings that are likey part of a legal
	// declaration file.
	legalFileSubstrings = []string{
		"authors",
		"contributors",
		"legal",
		"notice",
		"disclaimer",
		"patent",
		"third-party",
		"thirdparty",
	}
)

// PruneProject remove excess files according to the options passed, from
// the lp directory in baseDir.
func PruneProject(baseDir string, lp LockedProject, options PruneOptions, logger *log.Logger) error {
	fsState, err := deriveFilesystemState(baseDir)

	if err != nil {
		return errors.Wrap(err, "could not derive filesystem state")
	}

	if (options & PruneNestedVendorDirs) != 0 {
		if err := pruneVendorDirs(fsState); err != nil {
			return errors.Wrapf(err, "failed to prune nested vendor directories")
		}
	}

	if (options & PruneUnusedPackages) != 0 {
		if _, err := pruneUnusedPackages(lp, fsState); err != nil {
			return errors.Wrap(err, "failed to prune unused packages")
		}
	}

	if (options & PruneNonGoFiles) != 0 {
		if err := pruneNonGoFiles(fsState); err != nil {
			return errors.Wrap(err, "failed to prune non-Go files")
		}
	}

	if (options & PruneGoTestFiles) != 0 {
		if err := pruneGoTestFiles(fsState); err != nil {
			return errors.Wrap(err, "failed to prune Go test files")
		}
	}

	if err := deleteEmptyDirs(fsState); err != nil {
		return errors.Wrap(err, "could not delete empty dirs")
	}

	return nil
}

// pruneVendorDirs deletes all nested vendor directories within baseDir.
func pruneVendorDirs(fsState filesystemState) error {
	for _, dir := range fsState.dirs {
		if filepath.Base(dir) == "vendor" {
			err := os.RemoveAll(filepath.Join(fsState.root, dir))
			if err != nil && !os.IsNotExist(err) {
				return err
			}
		}
	}

	for _, link := range fsState.links {
		if filepath.Base(link.path) == "vendor" {
			err := os.Remove(filepath.Join(fsState.root, link.path))
			if err != nil && !os.IsNotExist(err) {
				return err
			}
		}
	}

	return nil
}

// pruneUnusedPackages deletes unimported packages found in fsState.
// Determining whether packages are imported or not is based on the passed LockedProject.
func pruneUnusedPackages(lp LockedProject, fsState filesystemState) (map[string]interface{}, error) {
	unusedPackages := calculateUnusedPackages(lp, fsState)
	toDelete := collectUnusedPackagesFiles(fsState, unusedPackages)

	for _, path := range toDelete {
		if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
			return nil, err
		}
	}

	return unusedPackages, nil
}

// calculateUnusedPackages generates a list of unused packages in lp.
func calculateUnusedPackages(lp LockedProject, fsState filesystemState) map[string]interface{} {
	unused := make(map[string]interface{})
	imported := make(map[string]interface{})

	for _, pkg := range lp.Packages() {
		imported[pkg] = nil
	}

	// Add the root package if it's not imported.
	if _, ok := imported["."]; !ok {
		unused["."] = nil
	}

	for _, dirPath := range fsState.dirs {
		pkg := filepath.ToSlash(dirPath)

		if _, ok := imported[pkg]; !ok {
			unused[pkg] = nil
		}
	}

	return unused
}

// collectUnusedPackagesFiles returns a slice of all files in the unused
// packages based on fsState.
func collectUnusedPackagesFiles(fsState filesystemState, unusedPackages map[string]interface{}) []string {
	// TODO(ibrasho): is this useful?
	files := make([]string, 0, len(unusedPackages))

	for _, path := range fsState.files {
		// Keep perserved files.
		if isPreservedFile(filepath.Base(path)) {
			continue
		}

		pkg := filepath.ToSlash(filepath.Dir(path))

		if _, ok := unusedPackages[pkg]; ok {
			files = append(files, filepath.Join(fsState.root, path))
		}
	}

	return files
}

// pruneNonGoFiles delete all non-Go files existing in fsState.
//
// Files matching licenseFilePrefixes and legalFileSubstrings are not pruned.
func pruneNonGoFiles(fsState filesystemState) error {
	toDelete := make([]string, 0, len(fsState.files)/4)

	for _, path := range fsState.files {
		ext := fileExt(path)

		// Refer to: https://github.com/golang/go/blob/release-branch.go1.9/src/go/build/build.go#L750
		switch ext {
		case ".go":
			continue
		case ".c":
			continue
		case ".cc", ".cpp", ".cxx":
			continue
		case ".m":
			continue
		case ".h", ".hh", ".hpp", ".hxx":
			continue
		case ".f", ".F", ".for", ".f90":
			continue
		case ".s":
			continue
		case ".S":
			continue
		case ".swig":
			continue
		case ".swigcxx":
			continue
		case ".syso":
			continue
		}

		// Ignore perserved files.
		if isPreservedFile(filepath.Base(path)) {
			continue
		}

		toDelete = append(toDelete, filepath.Join(fsState.root, path))
	}

	for _, path := range toDelete {
		if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
			return err
		}
	}

	return nil
}

// isPreservedFile checks if the file name indicates that the file should be
// preserved based on licenseFilePrefixes or legalFileSubstrings.
func isPreservedFile(name string) bool {
	name = strings.ToLower(name)

	for _, prefix := range licenseFilePrefixes {
		if strings.HasPrefix(name, prefix) {
			return true
		}
	}

	for _, substring := range legalFileSubstrings {
		if strings.Contains(name, substring) {
			return true
		}
	}

	return false
}

// pruneGoTestFiles deletes all Go test files (*_test.go) in fsState.
func pruneGoTestFiles(fsState filesystemState) error {
	toDelete := make([]string, 0, len(fsState.files)/2)

	for _, path := range fsState.files {
		if strings.HasSuffix(path, "_test.go") {
			toDelete = append(toDelete, filepath.Join(fsState.root, path))
		}
	}

	for _, path := range toDelete {
		if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
			return err
		}
	}

	return nil
}

func deleteEmptyDirs(fsState filesystemState) error {
	sort.Sort(sort.Reverse(sort.StringSlice(fsState.dirs)))

	for _, dir := range fsState.dirs {
		path := filepath.Join(fsState.root, dir)

		notEmpty, err := fs.IsNonEmptyDir(path)
		if err != nil {
			return err
		}

		if !notEmpty {
			if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
				return err
			}
		}
	}

	return nil
}

func fileExt(name string) string {
	i := strings.LastIndex(name, ".")
	if i < 0 {
		return ""
	}
	return name[i:]
}


text:
import ddt
import mock
import six

from rally import consts as rally_consts
from rally.plugins.openstack.context.manila import consts
from rally.plugins.openstack.context.manila import manila_security_services
from tests.unit import test

CONTEXT_NAME = consts.SECURITY_SERVICES_CONTEXT_NAME

@ddt.ddt
class SecurityServicesTestCase(test.ScenarioTestCase):
    TENANTS_AMOUNT = 3
    USERS_PER_TENANT = 4
    SECURITY_SERVICES = [
        {"security_service_type": ss_type,
         "dns_ip": "fake_dns_ip_%s" % ss_type,
         "server": "fake_server_%s" % ss_type,
         "domain": "fake_domain_%s" % ss_type,
         "user": "fake_user_%s" % ss_type,
         "password": "fake_password_%s" % ss_type}
        for ss_type in ("ldap", "kerberos", "active_directory")
    ]

    def _get_context(self, security_services=None, networks_per_tenant=2,
                     neutron_network_provider=True):
        if security_services is None:
            security_services = self.SECURITY_SERVICES
        tenants = {}
        for t_id in range(self.TENANTS_AMOUNT):
            tenants[six.text_type(t_id)] = {"name": six.text_type(t_id)}
            tenants[six.text_type(t_id)]["networks"] = []
            for i in range(networks_per_tenant):
                network = {"id": "fake_net_id_%s" % i}
                if neutron_network_provider:
                    network["subnets"] = ["fake_subnet_id_of_net_%s" % i]
                else:
                    network["cidr"] = "101.0.5.0/24"
                tenants[six.text_type(t_id)]["networks"].append(network)
        users = []
        for t_id in tenants.keys():
            for i in range(self.USERS_PER_TENANT):
                users.append({"id": i, "tenant_id": t_id, "endpoint": "fake"})
        context = {
            "config": {
                "users": {
                    "tenants": self.TENANTS_AMOUNT,
                    "users_per_tenant": self.USERS_PER_TENANT,
                },
                CONTEXT_NAME: {
                    "security_services": security_services,
                },
            },
            "admin": {
                "endpoint": mock.MagicMock(),
            },
            "task": mock.MagicMock(),
            "users": users,
            "tenants": tenants,
        }
        return context

    def test_init(self):
        context = {
            "task": mock.MagicMock(),
            "config": {
                CONTEXT_NAME: {"foo": "bar"},
                "not_manila": {"not_manila_key": "not_manila_value"},
            }
        }

        inst = manila_security_services.SecurityServices(context)

        self.assertEqual(inst.config.get("foo"), "bar")
        self.assertFalse(inst.config.get("security_services"))
        self.assertIn(
            rally_consts.JSON_SCHEMA, inst.CONFIG_SCHEMA.get("$schema"))
        self.assertEqual(False, inst.CONFIG_SCHEMA.get("additionalProperties"))
        self.assertEqual("object", inst.CONFIG_SCHEMA.get("type"))
        props = inst.CONFIG_SCHEMA.get("properties", {})
        self.assertEqual({"type": "array"}, props.get("security_services"))
        self.assertEqual(445, inst.get_order())
        self.assertEqual(CONTEXT_NAME, inst.get_name())

    @mock.patch.object(manila_security_services.manila_utils, "ManilaScenario")
    @ddt.data(True, False)
    def test_setup_security_services_set(self, neutron_network_provider,
                                         mock_manila_scenario):
        ctxt = self._get_context(
            neutron_network_provider=neutron_network_provider)
        inst = manila_security_services.SecurityServices(ctxt)

        inst.setup()

        self.assertEqual(
            self.TENANTS_AMOUNT, mock_manila_scenario.call_count)
        self.assertEqual(
            mock_manila_scenario.call_args_list,
            [mock.call({
                "task": inst.task,
                "config": {"api_versions": []},
                "user": user})
             for user in inst.context["users"] if user["id"] == 0]
        )
        mock_create_security_service = (
            mock_manila_scenario.return_value._create_security_service)
        expected_calls = []
        for ss in self.SECURITY_SERVICES:
            expected_calls.extend([mock.call(**ss), mock.call().to_dict()])
        mock_create_security_service.assert_has_calls(expected_calls)
        self.assertEqual(
            self.TENANTS_AMOUNT * len(self.SECURITY_SERVICES),
            mock_create_security_service.call_count)
        self.assertEqual(
            self.TENANTS_AMOUNT,
            len(inst.context["config"][CONTEXT_NAME]["security_services"]))
        for tenant in inst.context["tenants"]:
            self.assertEqual(
                self.TENANTS_AMOUNT,
                len(inst.context["tenants"][tenant][CONTEXT_NAME][
                    "security_services"])
            )

    @mock.patch.object(manila_security_services.manila_utils, "ManilaScenario")
    def test_setup_security_services_not_set(self, mock_manila_scenario):
        ctxt = self._get_context(security_services=[])
        inst = manila_security_services.SecurityServices(ctxt)

        inst.setup()

        self.assertFalse(mock_manila_scenario.called)
        self.assertFalse(
            mock_manila_scenario.return_value._create_security_service.called)
        self.assertIn(CONTEXT_NAME, inst.context["config"])
        self.assertIn(
            "security_services", inst.context["config"][CONTEXT_NAME])
        self.assertEqual(
            0,
            len(inst.context["config"][CONTEXT_NAME]["security_services"]))
        for tenant in inst.context["tenants"]:
            self.assertEqual(
                0,
                len(inst.context["tenants"][tenant][CONTEXT_NAME][
                    "security_services"])
            )

    @mock.patch.object(manila_security_services, "resource_manager")
    def test_cleanup_security_services_enabled(self, mock_resource_manager):
        ctxt = self._get_context()
        inst = manila_security_services.SecurityServices(ctxt)

        inst.cleanup()

        mock_resource_manager.cleanup.assert_called_once_with(
            names=["manila.security_services"], users=ctxt["users"])


text:
using System;
using System.Globalization;

namespace ArkNet.Utils
{

    public class NumberFormat
    {
        protected readonly CultureInfo locale;

        //private int maximumIntegerDigits;
        //private int minimumIntegerDigits;
        //private int maximumFractionDigits;
        //private int minimumFractionDigits;

        public NumberFormat(CultureInfo locale)
        {
            this.locale = locale;
        }

        public virtual string Format(object number)
        {
            string format = GetNumberFormat();

            if (number is int)
            {
                return ((int)number).ToString(format, locale);
            }
            else if (number is long)
            {
                return ((long)number).ToString(format, locale);
            }
            else if (number is short)
            {
                return ((short)number).ToString(format, locale);
            }
            else if (number is float)
            {
                return ((float)number).ToString(format, locale);
            }
            else if (number is double)
            {
                return ((double)number).ToString(format, locale);
            }
            else if (number is decimal)
            {
                return ((decimal)number).ToString(format, locale);
            }

            throw new ArgumentException("Cannot format given object as a Number");
        }

        public virtual string Format(double number)
        {
            string format = GetNumberFormat();
            return number.ToString(format, locale);
        }

        public virtual string Format(long number)
        {
            string format = GetNumberFormat();
            return number.ToString(format, locale);
        }

        protected virtual string GetNumberFormat()
        {
            return null;
        }

        public virtual /*Number*/ object Parse(string source)
        {
            return decimal.Parse(source, locale);
        }

        public override string ToString()
        {
            return base.ToString() + " - " + GetNumberFormat() + " - " + locale.ToString();
        }

        // LUCENENET TODO: Add additional functionality to edit the NumberFormatInfo
        // properties, which provides somewhat similar functionality to the below Java
        // getters and setters.

        //public virtual int MaximumIntegerDigits
        //{
        //    get { return this.maximumIntegerDigits; }
        //}

        //public virtual void SetMaximumIntegerDigits(int newValue)
        //{
        //    this.maximumIntegerDigits = Math.Max(0, newValue);
        //    if (maximumIntegerDigits < minimumIntegerDigits)
        //    {
        //        minimumIntegerDigits = maximumIntegerDigits;
        //    }
        //}

        //public virtual int MinimumIntegerDigits
        //{
        //    get { return this.minimumIntegerDigits; }
        //}

        //public virtual void SetMinimumIntegerDigits(int newValue)
        //{
        //    this.minimumIntegerDigits = Math.Max(0, newValue);
        //    if (minimumIntegerDigits > maximumIntegerDigits)
        //    {
        //        maximumIntegerDigits = minimumIntegerDigits;
        //    }
        //}

        //public virtual int MaximumFractionDigits
        //{
        //    get { return this.maximumFractionDigits; }
        //}

        //public virtual void SetMaximumFractionDigits(int newValue)
        //{
        //    maximumFractionDigits = Math.Max(0, newValue);
        //    if (maximumFractionDigits < minimumFractionDigits)
        //    {
        //        minimumFractionDigits = maximumFractionDigits;
        //    }
        //}

        //public virtual int MinimumFractionDigits
        //{
        //    get { return this.minimumFractionDigits; }
        //}

        //public void SetMinimumFractionDigits(int newValue)
        //{
        //    minimumFractionDigits = Math.Max(0, newValue);
        //    if (maximumFractionDigits < minimumFractionDigits)
        //    {
        //        maximumFractionDigits = minimumFractionDigits;
        //    }
        //}
    }
}


text:
******************************************
Submitting to the OSEHRA Technical Journal
******************************************

Substantial code contributions such as new VistA modules or a major refactoring
of the existing code base require a submission to the OSEHRA Technical Journal
(OTJ). OTJ submissions allow for a more thorough description of the submitted
code.  It also allows community members to download, use, try, and maintain the
submitted code prior to, and independently of, its progress through the OSEHRA
Certification Process.

For submissions that are not expected to go through the OSEHRA Certification
Process, there is no minimum set of objects.  We recommend that a technical
document, such as a Business Requirements Document or Software Design Document,
accompany the submission.

For those submissions that are expected to be part of the OSEHRA Certification
Process, OSEHRA requires a minimum set of objects in order to proceed through
the evaluation:

1.  The code for the submission.  This code **must** be released under the
    `Apache 2.0`_ license in order to be considered for OSEHRA Certification.

2.  The tests for the submission.  Since OSEHRA Level 1 certification is
    reserved for legacy VA code, all new submissions are required to have
    tests. Ideally, the tests would execute using the OSEHRA Code Testing
    framework. But OSEHRA will also accept a description of any additional
    functional tests that should be carried out manually to fully test the
    system.

3.  A Technical Article that describes the functional goals of the submission,
    the use of the submission and any additional details that may help a user
    of the software and for the subsequent developers who will maintain the
    codebase.

    Technical Articles are expected to follow the style of a technical report,
    with particular focus on providing guidance for the future use and
    maintenance of the new code contribution.

Once the submission is ready, go to the OTJ and click on ``New Publication`` as
shown in Figure 1.

.. figure::
   http://code.osehra.org/content/named/SHA1/7246bd-selectNewPublication.png
   :align: center
   :alt:  OTJ Main page with New Publication highlighted

Figure 1 - OSEHRA Technical Journal home page with the "New Publication" button
indicated by the  arrow.

The submission process will walk the submitter through the required steps of
the submission process, including:

* Choosing an OTJ Issue to submit to.
* Agreeing to the open source license for the Technical Article
* Filling in the contact and general information of the submission

  * The fields marked with a star ``*`` are required for submission.

.. figure::
   http://code.osehra.org/content/named/SHA1/0f35c6-submissionInformation.png
   :align: center
   :alt:  OTJ information page for submission

Figure 2 - OSEHRA Technical Journal "Manage Submission" page

Once the information is entered, click ``Next`` at the bottom of the page to
proceed to the second page of the OTJ Submission process.

This next page is the hub where all of the objects for the submission are
uploaded to the OSEHRA Technical Journal.  The minimum set of files for a
complete submission are those mentioned above.  This page also allows for the
submission of auxiliary files. These additional files could consist of:

  * Other supporting documents, such as a major technique paper or
    additional design documentation
  * Testing Data
  * An optional developer specific logo

The upload of each file is done by selecting the proper upload type from the
dropdown menu, selecting the proper file from the local system, and then
uploading it to the OTJ.  For an upload with multiple files or directories
within the desired content: use an archival tool, such as zip or tar.zip, to
combine the files into a single archive to upload.

.. figure::
   http://code.osehra.org/content/named/SHA1/fa2f4c-submissionUpload.png
   :align: center
   :alt:  OTJ upload page with possible selections shown

Figure 3 - OSEHRA Technical Journal "Manage Files" page with selection menu expanded

**Note:** If the code is in a publicly-available Git repository, the submitter
can submit a link to the repository and the OTJ will generate a zip file from
the ``master`` branch of the given repository. Selecting the
``Github repository`` option from the upload type will prompt the user for a
URL pointing to the repository.

At the end of the process the article and code is uploaded to the OTJ and,
after approval by an OTJ Administrator, becomes available for download,
review, comments, and eventual placement onto the OSEHRA Priority Queue.

Create A New Revision
---------------------

It is possible to add a new revision to an existing submission. New revisions
can be created as needed, and may be used for bug fixes or new features. Note
that if a submission has gone through the OSEHRA certification process, any new
revisions will need to be recertified.

To create a new revision, go to the OTJ site, log in and select the article
that to be modified. Once the article submission page is loaded, the current
revision is displayed under ``Information`` on the right of the page. Use the
drop-down box to navigate between revisions.

To create a new revision, click on the ``New Revision`` link (Figure 4).

.. figure::
   http://code.osehra.org/content/named/SHA1/39c87d-newRevision.png
   :align: center
   :alt:  OTJ Change current revision or add a new revision

Figure 4 - OSEHRA Technical Journal article submission page

The submission process for a new revision is similar to creating a new
submission, as described in the beginning of this document. Most fields on the
``Manage Submission`` page will be populated with information from the previous
revision. The one exception is the ``Revision Notes`` field. Submitters should
use this field to describe why a new revision has been created and what has
changed since the previous revision. This information will be displayed on the
article submission page and will help users to ensure that they are selecting
the correct revision.

After the ``Revision Notes`` are entered and other fields are updated as
needed, click ``Next`` to proceed to the ``Manage Files`` page. As in the
original submission, select one or more files to upload and agree to the
appropriate licensing questions. Finally, select whether or not to send a
notification email and click ``Publish``.

.. _`Apache 2.0`: http://www.apache.org/licenses/LICENSE-2.0


text:
using System;
using System.Collections.Generic;
using System.Text;
#if FRB_XNA || WINDOWS_PHONE || SILVERLIGHT || MONODROID
using Microsoft.Xna.Framework;
//using System.Windows.Forms;
using Keys = Microsoft.Xna.Framework.Input.Keys;
#elif FRB_MDX
using Microsoft.DirectX;
using Keys = Microsoft.DirectX.DirectInput.Key;
#endif

namespace FlatRedBall.Gui
{
    public class Vector3Display : Window, IInputReceiver
    {
        #region Fields

        TextDisplay mXDisplay;
        TextDisplay mYDisplay;
        TextDisplay mZDisplay;
        TextDisplay mWDisplay;

        UpDown mXUpDown;
        UpDown mYUpDown;
        UpDown mZUpDown;
        UpDown mWUpDown;

        int mNumberOfComponents = 3;

        List<Keys> mIgnoredKeys = new List<Keys>();

        #endregion

        #region Properties

        public Vector2 BeforeChangeVector2Value
        {
            get { return new Vector2(mXUpDown.BeforeChangeValue, mYUpDown.BeforeChangeValue); }
        }

        public Vector3 BeforeChangeVector3Value
        {
            get { return new Vector3(mXUpDown.BeforeChangeValue, mYUpDown.BeforeChangeValue, mZUpDown.BeforeChangeValue); }
        }

        public List<Keys> IgnoredKeys
        {
            get { return mIgnoredKeys; }
        }

        public bool IsUserEditingWindow
        {
            get
            {
                return mCursor.WindowPushed == mXUpDown.UpDownButton ||
                    mCursor.WindowPushed == mYUpDown.UpDownButton ||
                    mCursor.WindowPushed == mZUpDown.UpDownButton ||
                    mCursor.WindowPushed == mWUpDown.UpDownButton;
            }
        }

        private UpDown LastVisibleUpDown
        {
            get
            {
                if (mWUpDown.Visible)
                {
                    return mWUpDown;
                }
                else if (mZUpDown.Visible)
                {
                    return mZUpDown;
                }
                else if (mYUpDown.Visible)
                {
                    return mYUpDown;
                }
                else if (mXUpDown.Visible)
                {
                    return mXUpDown;
                }
                else
                {
                    return null;
                }
            }
        }
        public int NumberOfComponents
        {
            get { return mNumberOfComponents; }
            set
            {

                mNumberOfComponents = value;

                #region Set the visibility of the components

                mXDisplay.Visible = mNumberOfComponents > 0;
                mXUpDown.Visible = mXDisplay.Visible;

                mYDisplay.Visible = mNumberOfComponents > 1;
                mYUpDown.Visible = mYDisplay.Visible;

                mZDisplay.Visible = mNumberOfComponents > 2;
                mZUpDown.Visible = mZDisplay.Visible;

                mWDisplay.Visible = mNumberOfComponents > 3;
                mWUpDown.Visible = mWDisplay.Visible;
                #endregion

                ScaleY = .5f + mNumberOfComponents;

                float border = .5f;

                mXUpDown.Y = border + 1;
                mYUpDown.Y = border + 3;
                mZUpDown.Y = border + 5;
                mWUpDown.Y = border + 7;

                mXDisplay.Y = mXUpDown.Y;
                mYDisplay.Y = mYUpDown.Y;
                mZDisplay.Y = mZUpDown.Y;
                mWDisplay.Y = mWUpDown.Y;

                if (mWUpDown.Visible)
                {
                    mZUpDown.NextInTabSequence = mWUpDown;
                }

                if (mZUpDown.Visible)
                {
                    mYUpDown.NextInTabSequence = mZUpDown;
                }

                if (mYUpDown.Visible)
                {
                    mXUpDown.NextInTabSequence = mYUpDown;
                }

            }
        }

        public float Sensitivity
        {
            get { return mXUpDown.Sensitivity; }
            set
            {
                if (mXUpDown != null)
                    mXUpDown.Sensitivity = value;
                if (mYUpDown != null)
                    mYUpDown.Sensitivity = value;
                if (mZUpDown != null)
                    mZUpDown.Sensitivity = value;
                if (mWUpDown != null)
                    mWUpDown.Sensitivity = value;
            }
        }

        public Vector2 Vector2Value
        {
            get { return new Vector2(mXUpDown.CurrentValue, mYUpDown.CurrentValue); }
            set
            {
                mXUpDown.CurrentValue = value.X;
                mYUpDown.CurrentValue = value.Y;

                if (!mCursor.IsOn(mXUpDown as IWindow))
                {
                    mXUpDown.ForceUpdateBeforeChangedValue();
                }
                if (!mCursor.IsOn(mYUpDown as IWindow))
                {
                    mYUpDown.ForceUpdateBeforeChangedValue();
                }
                if (!mCursor.IsOn(mZUpDown as IWindow))
                {
                    mZUpDown.ForceUpdateBeforeChangedValue();
                }
                if (!mCursor.IsOn(mWUpDown as IWindow))
                {
                    mWUpDown.ForceUpdateBeforeChangedValue();
                }

            }
        }

        public Vector3 Vector3Value
        {
            get { return new Vector3(mXUpDown.CurrentValue, mYUpDown.CurrentValue, mZUpDown.CurrentValue); }
            set
            {
                mXUpDown.CurrentValue = value.X;
                mYUpDown.CurrentValue = value.Y;
                mZUpDown.CurrentValue = value.Z;

                if (!mCursor.IsOn(mXUpDown as IWindow))
                {
                    mXUpDown.ForceUpdateBeforeChangedValue();
                }
                if (!mCursor.IsOn(mYUpDown as IWindow))
                {
                    mYUpDown.ForceUpdateBeforeChangedValue();
                }
                if (!mCursor.IsOn(mZUpDown as IWindow))
                {
                    mZUpDown.ForceUpdateBeforeChangedValue();
                }
                if (!mCursor.IsOn(mWUpDown as IWindow))
                {
                    mWUpDown.ForceUpdateBeforeChangedValue();
                }

            }
        }

        #endregion

        #region Events

        public GuiMessage ValueChanged;
        public GuiMessage AfterValueChanged;

        #endregion

        #region Event and Delegate Methods

        // July 10, 2011
        // These two methods
        // were previously not
        // implemented - the FocusUpdate
        // and GainFocus events were not being
        // used.  I implemented them.  Hopefully
        // this doesn't cause issues if the engine
        // raises these events...but I think it should
        // be okay.
        void OnFocusUpdateInternal(IInputReceiver inputReceiver)
        {
            if (this.FocusUpdate != null)
            {
                this.FocusUpdate(this);
            }
        }
        void OnGainFocusInternal(Window callingWindow)
        {
            if (this.GainFocus != null)
            {
                this.GainFocus(this);
            }
        }

        private void OnValueChanged(Window callingWindow)
        {
            if (ValueChanged != null)
            {
                ValueChanged(this);
            }
        }

        private void OnAfterValueChanged(Window callingWindow)
        {
            if(AfterValueChanged != null)
            {
                AfterValueChanged(this);
            }

            // The UpDown's BeforeChangeValue is only
            // set when the user pushes on the UpDown.
            // That means that if the user changes the X,
            // then Y, then Z, the BeforeChange value on all
            // three will remain the exact same.  This forces
            // the BeforeChangeValue to be accurate so it can be
            // used in the BeforeChangeVector3Value property.
            //mXUpDown.ForceUpdateBeforeChangedValue();
            //mYUpDown.ForceUpdateBeforeChangedValue();
            //mZUpDown.ForceUpdateBeforeChangedValue();
            //mWUpDown.ForceUpdateBeforeChangedValue();
        }

        private void ComponentLosingFocus(Window callingWindow)
        {
            base.OnLosingFocus();
        }

        #endregion

        #region Methods

        public Vector3Display(Cursor cursor)
            : base(cursor)
        {
            float border = .5f;
            this.ScaleX = 6f;
            this.ScaleY = 3.5f;

            #region Create the UpDowns and set their static properties

            mXUpDown = new UpDown(mCursor);
            AddWindow(mXUpDown);

            mYUpDown = new UpDown(mCursor);
            AddWindow(mYUpDown);

            mZUpDown = new UpDown(mCursor);
            AddWindow(mZUpDown);

            mWUpDown = new UpDown(mCursor);
            AddWindow(mWUpDown);

            mXUpDown.Y = border + 1;
            mYUpDown.Y = border + 3;
            mZUpDown.Y = border + 5;
            mWUpDown.Y = border + 7;

            mXUpDown.ValueChanged += OnValueChanged;
            mYUpDown.ValueChanged += OnValueChanged;
            mZUpDown.ValueChanged += OnValueChanged;
            mWUpDown.ValueChanged += OnValueChanged;

            mXUpDown.LosingFocus += ComponentLosingFocus;
            mYUpDown.LosingFocus += ComponentLosingFocus;
            mZUpDown.LosingFocus += ComponentLosingFocus;
            mWUpDown.LosingFocus += ComponentLosingFocus;

            mXUpDown.AfterValueChanged += OnAfterValueChanged;
            mYUpDown.AfterValueChanged += OnAfterValueChanged;
            mZUpDown.AfterValueChanged += OnAfterValueChanged;
            mWUpDown.AfterValueChanged += OnAfterValueChanged;

            mXUpDown.FocusUpdate += OnFocusUpdateInternal;
            mYUpDown.FocusUpdate += OnFocusUpdateInternal;
            mZUpDown.FocusUpdate += OnFocusUpdateInternal;
            mWUpDown.FocusUpdate += OnFocusUpdateInternal;

            mXUpDown.GainFocus += OnGainFocusInternal;
            mYUpDown.GainFocus += OnGainFocusInternal;
            mZUpDown.GainFocus += OnGainFocusInternal;
            mWUpDown.GainFocus += OnGainFocusInternal;

            #endregion

            #region Create the TextDisplays and set their static properties
            mXDisplay = new TextDisplay(mCursor);
            AddWindow(mXDisplay);

            mYDisplay = new TextDisplay(mCursor);
            AddWindow(mYDisplay);

            mZDisplay = new TextDisplay(mCursor);
            AddWindow(mZDisplay);

            mWDisplay = new TextDisplay(mCursor);
            AddWindow(mWDisplay);

            mXDisplay.Text = "X:";
            mYDisplay.Text = "Y:";
            mZDisplay.Text = "Z:";
            mWDisplay.Text = "W:";

            mXDisplay.X = 0f;
            mYDisplay.X = 0f;
            mZDisplay.X = 0f;
            mWDisplay.X = 0f;

            mXDisplay.Y = mXUpDown.Y;
            mYDisplay.Y = mYUpDown.Y;
            mZDisplay.Y = mZUpDown.Y;
            mWDisplay.Y = mWUpDown.Y;

            #endregion

            float spaceForDisplay = 1;

            #region Set the UpDown ScaleX values

            mXUpDown.ScaleX = this.ScaleX - border - spaceForDisplay;
            mYUpDown.ScaleX = this.ScaleX - border - spaceForDisplay;
            mZUpDown.ScaleX = this.ScaleX - border - spaceForDisplay;
            mWUpDown.ScaleX = this.ScaleX - border - spaceForDisplay;

            #endregion

            mXUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX;
            mYUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX;
            mZUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX;
            mWUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX;

            NumberOfComponents = 3;
        }

        #endregion

        #region IInputReceiver Members

        public bool TakingInput
        {
            get { return mXUpDown.TakingInput; }
        }

        public IInputReceiver NextInTabSequence
        {
            get
            {
                UpDown lastUpDown = LastVisibleUpDown;

                if (lastUpDown != null)
                {
                    return lastUpDown.NextInTabSequence;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                UpDown lastUpDown = LastVisibleUpDown;

                if (lastUpDown != null)
                {
                    lastUpDown.NextInTabSequence = value;
                }
            }
        }

        public event GuiMessage GainFocus;

        public event FocusUpdateDelegate FocusUpdate;

        public void OnFocusUpdate()
        {
            throw new InvalidOperationException("Vector3 should never have its OnFocusUpdate called");
        }

        public void OnGainFocus()
        {
            FlatRedBall.Input.InputManager.ReceivingInput = mXUpDown;
        }

        public void LoseFocus()
        {
            // do nothing
        }

        public void ReceiveInput()
        {
            throw new InvalidOperationException("Vector3 should never have its ReceiveInput called");
        }

        #endregion
    }
}


text:
package net.oschina.app.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import net.oschina.app.R;
import net.oschina.app.base.ListBaseAdapter;
import net.oschina.app.bean.Active;
import net.oschina.app.bean.Active.ObjectReply;
import net.oschina.app.emoji.InputHelper;
import net.oschina.app.ui.OSCPhotosActivity;
import net.oschina.app.util.BitmapHelper;
import net.oschina.app.util.ImageUtils;
import net.oschina.app.util.PlatfromUtil;
import net.oschina.app.util.StringUtils;
import net.oschina.app.util.UIHelper;
import net.oschina.app.widget.AvatarView;
import net.oschina.app.widget.MyLinkMovementMethod;
import net.oschina.app.widget.MyURLSpan;
import net.oschina.app.widget.TweetTextView;

import org.kymjs.kjframe.Core;
import org.kymjs.kjframe.bitmap.BitmapCallBack;
import org.kymjs.kjframe.utils.DensityUtils;

import butterknife.ButterKnife;
import butterknife.Bind;

public class ActiveAdapter extends ListBaseAdapter {
    private final static String AT_HOST_PRE = "http://my.oschina.net";
    private final static String MAIN_HOST = "http://www.oschina.net";

    public ActiveAdapter() {
    }

    private Bitmap recordBitmap;
    private int rectSize;

    private void initRecordImg(Context cxt) {
        recordBitmap = BitmapFactory.decodeResource(cxt.getResources(),
                R.mipmap.audio3);
        recordBitmap = ImageUtils.zoomBitmap(recordBitmap,
                DensityUtils.dip2px(cxt, 20f), DensityUtils.dip2px(cxt, 20f));
    }

    private void initImageSize(Context cxt) {
        if (cxt != null && rectSize == 0) {
            rectSize = (int) cxt.getResources().getDimension(R.dimen.space_100);
        } else {
            rectSize = 300;
        }
    }

    @Override
    @SuppressLint("InflateParams")
    protected View getRealView(int position, View convertView,
                               final ViewGroup parent) {
        ViewHolder vh;
        initImageSize(parent.getContext());
        if (convertView == null || convertView.getTag() == null) {
            convertView = getLayoutInflater(parent.getContext()).inflate(
                    R.layout.list_cell_active, null);
            vh = new ViewHolder(convertView);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        final Active item = (Active) mDatas.get(position);

        vh.name.setText(item.getAuthor());

        vh.action.setText(UIHelper.parseActiveAction(item.getObjectType(),
                item.getObjectCatalog(), item.getObjectTitle()));

        if (TextUtils.isEmpty(item.getMessage())) {
            vh.body.setVisibility(View.GONE);
        } else {
            vh.body.setMovementMethod(MyLinkMovementMethod.a());
            vh.body.setFocusable(false);
            vh.body.setDispatchToParent(true);
            vh.body.setLongClickable(false);

            Spanned span = Html.fromHtml(modifyPath(item.getMessage()));

            if (!StringUtils.isEmpty(item.getTweetattach())) {
                if (recordBitmap == null) {
                    initRecordImg(parent.getContext());
                }
                ImageSpan recordImg = new ImageSpan(parent.getContext(),
                        recordBitmap);
                SpannableString str = new SpannableString("c");
                str.setSpan(recordImg, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                vh.body.setText(str);
                span = InputHelper.displayEmoji(parent.getContext()
                        .getResources(), span);
                vh.body.append(span);
            } else {
                span = InputHelper.displayEmoji(parent.getContext()
                        .getResources(), span);
                vh.body.setText(span);
            }
            MyURLSpan.parseLinkText(vh.body, span);
        }

        ObjectReply reply = item.getObjectReply();
        if (reply != null) {
            vh.reply.setMovementMethod(MyLinkMovementMethod.a());
            vh.reply.setFocusable(false);
            vh.reply.setDispatchToParent(true);
            vh.reply.setLongClickable(false);
            Spanned span = UIHelper.parseActiveReply(reply.objectName,
                    reply.objectBody);
            vh.reply.setText(span);//
            MyURLSpan.parseLinkText(vh.reply, span);
            vh.lyReply.setVisibility(TextView.VISIBLE);
        } else {
            vh.reply.setText("");
            vh.lyReply.setVisibility(TextView.GONE);
        }

        vh.time.setText(StringUtils.formatSomeAgo(item.getPubDate()));

        PlatfromUtil.setPlatFromString(vh.from, item.getAppClient());

        vh.commentCount.setText(item.getCommentCount() + "");

        vh.avatar.setUserInfo(item.getAuthorId(), item.getAuthor());
        vh.avatar.setAvatarUrl(item.getPortrait());

        if (!TextUtils.isEmpty(item.getTweetimage())) {
            setTweetImage(parent, vh, item);
        } else {
            vh.pic.setVisibility(View.GONE);
            vh.pic.setImageBitmap(null);
        }

        return convertView;
    }

    /**
     * 动态设置图片显示样式
     */
    private void setTweetImage(final ViewGroup parent, final ViewHolder vh,
                               final Active item) {
        vh.pic.setVisibility(View.VISIBLE);

        new Core.Builder().url(item.getTweetimage()).view(vh.pic).loadBitmapRes(R.drawable
                .pic_bg).size(rectSize, rectSize).bitmapCallBack(new BitmapCallBack() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                super.onSuccess(bitmap);
                if (bitmap != null) {
                    bitmap = BitmapHelper.scaleWithXY(bitmap, rectSize / bitmap.getHeight());
                    vh.pic.setImageBitmap(bitmap);
                }
            }
        }).doTask();

        vh.pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OSCPhotosActivity.showImagePreview(parent.getContext(), getOriginalUrl(item.getTweetimage()));
            }
        });
    }

    private String modifyPath(String message) {
        message = message.replaceAll("(<a[^>]+href=\")/([\\S]+)\"", "$1"
                + AT_HOST_PRE + "/$2\"");
        message = message.replaceAll(
                "(<a[^>]+href=\")http://m.oschina.net([\\S]+)\"", "$1"
                        + MAIN_HOST + "$2\"");
        return message;
    }

    private String getOriginalUrl(String url) {
        return url.replaceAll("_thumb", "");
    }

    static class ViewHolder {
        @Bind(R.id.tv_name)
        TextView name;
        @Bind(R.id.tv_from)
        TextView from;
        @Bind(R.id.tv_time)
        TextView time;
        @Bind(R.id.tv_action)
        TextView action;
        @Bind(R.id.tv_action_name)
        TextView actionName;
        @Bind(R.id.tv_comment_count)
        TextView commentCount;
        @Bind(R.id.tv_body)
        TweetTextView body;
        @Bind(R.id.tv_reply)
        TweetTextView reply;
        @Bind(R.id.iv_pic)
        ImageView pic;
        @Bind(R.id.ly_reply)
        View lyReply;
        @Bind(R.id.iv_avatar)
        AvatarView avatar;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}


text:
/* eslint-disable react/prop-types, no-mixed-operators, react/jsx-space-before-closing, spaced-comment, arrow-body-style, react/jsx-first-prop-new-line, react/jsx-indent-props, quotes, react/jsx-closing-bracket-location, react/jsx-wrap-multilines */
import React from 'react';
import _ from 'lodash';
import styles from './styles.css';

function getStyles(classRefs) {
  const classes = [];
  classRefs.split(' ').forEach((className) => {
    classes.push(styles[className]);
  });
  return classes.join(' ');
}

function getYPosition(max, height, chartHeight, value) {
  return (height - (chartHeight / max) * value) - 40;
}

function getXPosition(index, block) {
  return (index * block);
}

function getHoverPath(index, data, block, max, height, chartHeight) {
  const dataSet = _.clone(data).slice(0, index + 1);
  const Y = _.map(dataSet, (item, i) => {
    return `${getXPosition(i, block)} ${getYPosition(max, height, chartHeight, item)}`;
  });
  return `M${Y.join(',')}`;
}

function LineChart(props) {
  let mainContent =  data not available ;
  let data = [];
  let startingYear = (new Date()).getFullYear();
  let midYear = startingYear;
  let endYear = startingYear;

  if (props.data !== 'no data') {
    if (typeof props.data[0] === 'object') {
      props.data.forEach((item) => {
        data.push(item.value);
      });
      startingYear = props.data[0].period;
      midYear = props.data[Math.ceil((data.length - 1) / 2)].period;
      endYear = props.data[data.length - 1].period;
    } else {
      data = props.data;
      midYear = Math.ceil(startingYear + data.length / 2);
      endYear = startingYear + data.length;
    }
    const width = window.innerWidth - 40;
    const height = 200;
    const chartHeight = height - 80;
    const max = _.max(data);
    const block = width / (data.length - 1);
    const labelOffset = 36;

    const Y = _.map(data, (item, index) => {
      return `${getXPosition(index, block)} ${getYPosition(max, height, chartHeight, item)}`;
    });

    const path = `M${Y.join(',')}`;

    mainContent = (

        <svg width={width}
             height={height}
             xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="GRAD">
              <stop stopColor="rgb(11, 241, 210)"/>
              <stop offset="100%" stopColor="rgb(79, 210,244)"/>
            </linearGradient>
          </defs>
          <filter id="dropshadow" height="150%">
            <feGaussianBlur result="blurOut" in="SourceAlpha" stdDeviation="3"/>
            <feOffset dx="0" dy="4" result="offsetblur"/>
            <feMerge>
              <feMergeNode/>
              <feMergeNode in="SourceGraphic"/>
            </feMerge>
          </filter>
          <path className={styles.line} d={path}/>

          {data.map((value, index) => {
            return (<g className={styles.value} key={index}>
              <circle className={styles.point_ghost} cx={index * block}
                      cy={getYPosition(max, height, chartHeight, value)}
                      r={20}
              />
              <path className={getStyles("line_hover")} d={getHoverPath(index, data, block, max, height, chartHeight)} stroke="url(#GRAD)"
                    strokeLinecap="round"/>
              <g className={styles.tooltip}
                 transform={`translate(${((index * block) - 53)}, ${(getYPosition(max, height, chartHeight, value) - 60)})`}>
                <circle cx="50"
                        cy="60"
                        r="24"
                        fill="rgba(255, 255, 255, 0.2)"
                />
                <circle className={styles.point_dot} cx="50"
                        cy="60"
                        r="14"
                />
                <rect x="0"
                      y="0"
                      width="100"
                      height="40"
                      rx="3" ry="3"
                      className={styles.label_container}
                      style={{ filter: "url(#dropshadow)" }}
                />
                <text className={styles.label} x="5" y="16">
                  {/*{`R$ ${_.round(value, 2)}`}*/}
                  R$ {value.toLocaleString(props.locale, { minimumFractionDigits: 2 })}
                </text>
                <text className={styles.label} x="5" y="32">
                  {`${startingYear + index}`}
                </text>
              </g>
            </g>);
          })}
          <text className={getStyles("xLabel")} x={10} y={height - 10}>{startingYear}</text>
          <text className={getStyles("xLabel")} x={width / 2 - labelOffset / 2}
                y={height - 10}>{midYear}</text>
          <text className={getStyles("xLabel")} x={width - labelOffset}
                y={height - 10}>{endYear}</text>
        </svg>

);
  }

  return (

      { mainContent }

  );
}

LineChart.propTypes = {
  locale: React.PropTypes.string,
  data: React.PropTypes.oneOfType([
    React.PropTypes.array,
    React.PropTypes.string,
  ]),
};

export default LineChart;


text:
import DataNode from './data/Node'
import EventEmitter from '../util/EventEmitter'

/**
  Base node type for document nodes.

  @example

  The following example shows how a new node type is defined.

  ```js
  class Todo extends TextBlock {}
  Todo.schema = {
    type: 'todo',
    content: 'text',
    done: { type: 'bool', default: false }
  }
  ```

  The following data types are supported:

  - `string` bare metal string data type
  - `text` a string that carries annotations
  - `number` numeric values
  - `bool` boolean values
  - `id` a node id referencing another node in the document
*/
class DocumentNode extends DataNode {

  /**
    @param {Document} doc A document instance
    @param {object} node properties
  */
  constructor(doc, props) {
    super(props)
    // being less strict here allows us to create a detached node
    // which can be useful for testing
    // if (!doc) throw new Error('Document instance is mandatory.')
    this.document = doc
  }

  /**
    Get the Document instance.

    @returns {Document}
  */
  getDocument() {
    return this.document
  }

  /**
    Whether this node has a parent.

    `parent` is a built-in property for implementing nested nodes.

    @returns {Boolean}
  */
  hasParent() {
    return Boolean(this.parent)
  }

  /**
    @returns {DocumentNode} the parent node
  */
  getParent() {
    return this.document.get(this.parent)
  }

  /**
    Get the root node.

    The root node is the last ancestor returned
    by a sequence of `getParent()` calls.

    @returns {DocumentNode}
  */
  getRoot() {
    let node = this
    while(node.parent) {
      node = node.parent
    }
    return node
  }

  /**
    Checks whether this node has children.

    @returns {Boolean} default: false
  */
  hasChildren() {
    return false
  }

  /**
    Get the index of a given child.

    @returns {Number} default: -1
  */
  getChildIndex(child) { // eslint-disable-line
    return -1
  }

  /**
    Get a child node at a given position.

    @returns {DocumentNode} default: null
  */
  getChildAt(idx) { // eslint-disable-line
    return null
  }

  /**
    Get the number of children nodes.

    @returns {Number} default: 0
  */
  getChildCount() {
    return 0
  }

  // TODO: should this really be here?
  // volatile property necessary to render highlighted node differently
  // TODO: We should get this out here
  setHighlighted(highlighted, scope) {
    if (this.highlighted !== highlighted) {
      this.highlightedScope = scope
      this.highlighted = highlighted
      this.emit('highlighted', highlighted)
    }
  }

  // Experimental: we are working on a simpler API replacing the
  // rather inconvenient EventProxy API.
  on(eventName, handler, ctx) {
    var match = _matchPropertyEvent(eventName)
    if (match) {
      var propertyName = match[1]
      if (this.constructor.schema[propertyName]) {
        var doc = this.getDocument()
        doc.getEventProxy('path')
          .on([this.id, propertyName], handler, ctx)
      }
    }
    EventEmitter.prototype.on.apply(this, arguments)
  }

  off(ctx, eventName, handler) {
    var doc = this.getDocument()
    var match = false
    if (!eventName) {
      doc.getEventProxy('path').off(ctx)
    } else {
      match = _matchPropertyEvent(eventName)
    }
    if (match) {
      var propertyName = match[1]
      doc.getEventProxy('path')
        .off(ctx, [this.id, propertyName], handler)
    }
    EventEmitter.prototype.off.apply(this, arguments)
  }

  _onPropertyChange(propertyName) {
    var args = [propertyName + ':changed']
      .concat(Array.prototype.slice.call(arguments, 1))
    this.emit.apply(this, args)
  }

  // Node categories
  // --------------------

  /**
    @returns {Boolean} true if node is a block node (e.g. Paragraph, Figure, List, Table)
  */
  isBlock() {
    return Boolean(this.constructor.isBlock)
  }

  /**
    @returns {Boolean} true if node is a text node (e.g. Paragraph, Codebock)
  */
  isText() {
    return Boolean(this.constructor.isText)
  }

  /**
    @returns {Boolean} true if node is an inline node (e.g. Citation)
  */
  isInline() {
    return Boolean(this.constructor.isInline)
  }

  isList() {
    return Boolean(this.constructor.isList)
  }

}

DocumentNode.prototype._isDocumentNode = true

/**
  Declares a node to be treated as block-type node.

  BlockNodes are considers the direct descendant of `Container` nodes.
  @type {Boolean} default: false
*/
DocumentNode.isBlock = false

/**
  Declares a node to be treated as text-ish node.

  @type {Boolean} default: false
*/
DocumentNode.isText = false

/**
  Declares a node to be treated as {@link model/PropertyAnnotation}.

  @type {Boolean} default: false
*/
DocumentNode.isPropertyAnnotation = false

/**
  Declares a node to be treated as {@link model/ContainerAnnotation}.

  @type {Boolean} default: false
*/
DocumentNode.isContainerAnnotation = false

/**
  Declares a node to be treated as {@link model/InlineNode}.

  @type {Boolean} default: false
*/
DocumentNode.isInline = false

function _matchPropertyEvent(eventName) {
  return /([a-zA-Z_0-9]+):changed/.exec(eventName)
}

export default DocumentNode


text:
MetaModule Construction Kit
===========================

(to be written)