text:
"""
Display the current window title with async update.

Uses asynchronous update via i3 IPC events.
Provides instant title update only when it required.

Configuration parameters:
    - always_show : do not hide the title when it can be already
                    visible (e.g. in tabbed layout), default: False.
    - empty_title : string that will be shown instead of the title when
                    the title is hidden, default: "" (empty string).
    - format : format of the title, default: "{title}".
    - max_width : maximum width of block (in symbols).
                  If the title is longer than `max_width`,
                  the title will be truncated to `max_width - 1`
                  first symbols with ellipsis appended. Default: 120.

Requires:
    - i3ipc (https://github.com/acrisci/i3ipc-python)

@author Anon1234 https://github.com/Anon1234
@license BSD
"""

from threading import Thread

import i3ipc

class Py3status:
    """
    """
    # available configuration parameters
    always_show = False
    empty_title = ""
    format = "{title}"
    max_width = 120

    def __init__(self):
        self.title = self.empty_title

        # we are listening to i3 events in a separate thread
        t = Thread(target=self._loop)
        t.daemon = True
        t.start()

    def _loop(self):
        def get_title(conn):
            tree = conn.get_tree()
            w = tree.find_focused()
            p = w.parent

            # dont show window title when the window already has means
            # to display it
            if not self.always_show and (
                    w.border == "normal" or w.type == "workspace" or
                    (p.layout in ("stacked", "tabbed") and len(p.nodes) > 1)):

                return self.empty_title

            else:
                title = w.name

                if len(title) > self.max_width:
                    title = title[:self.max_width - 1] + "…"

                return self.format.format(title=title)

        def update_title(conn, e):

            # catch only focused window title updates
            title_changed = hasattr(e, "container") and e.container.focused

            # check if we need to update title due to changes
            # in the workspace layout
            layout_changed = (hasattr(e, "binding") and
                              (e.binding.command.startswith("layout") or
                               e.binding.command.startswith("move container") or
                               e.binding.command.startswith("border")))

            if title_changed or layout_changed:
                self.title = get_title(conn)

        def clear_title(*args):
            self.title = self.empty_title

        conn = i3ipc.Connection()

        self.title = get_title(conn)  # set title on startup

        # The order of following callbacks is important!

        # clears the title on empty ws
        conn.on('workspace::focus', clear_title)

        # clears the title when the last window on ws was closed
        conn.on("window::close", clear_title)

        # listens for events which can trigger the title update
        conn.on("window::title", update_title)
        conn.on("window::focus", update_title)
        conn.on("binding", update_title)

        conn.main()  # run the event loop

    def window_title(self, i3s_output_list, i3s_config):
        resp = {
            'cached_until': 0,  # update ASAP
            'full_text': self.title,
        }

        for option in ('min_width', 'align', 'separator'):
            try:
                resp[option] = getattr(self, option)
            except AttributeError:
                continue

        return resp

if __name__ == "__main__":
    """
    Test this module by calling it directly.
    """
    from time import sleep
    x = Py3status()
    config = {
        'color_bad': '#FF0000',
        'color_degraded': '#FFFF00',
        'color_good': '#00FF00'
    }
    while True:
        print(x.window_title([], config))
        sleep(1)


text:
#if !NOFILEIO
using System;
using System.IO;

namespace ChainUtils.BitcoinCore
{
	public class BlockUndoStore : Store<StoredItem<BlockUndo>, BlockUndo>
	{
		public BlockUndoStore(string folder, Network network)
			: this(new DirectoryInfo(folder), network)
		{
		}
		public BlockUndoStore(DirectoryInfo folder, Network network)
			: base(folder, network)
		{
			FilePrefix = "rev";
			MaxFileSize = 0x1000000; // 16 MiB
		}
		protected override StoredItem<BlockUndo> CreateStoredItem(BlockUndo item, DiskBlockPos position)
		{
			var stored = new StoredItem<BlockUndo>(Network.Magic, item, position);
			stored.HasChecksum = true;
			if(item.CalculatedChecksum == null)
				throw new InvalidOperationException("A block undo should have an calculated checksum with ComputeChecksum");
			stored.Checksum = item.CalculatedChecksum;
			return stored;
		}

		protected override StoredItem<BlockUndo> ReadStoredItem(Stream stream, DiskBlockPos pos)
		{
			var item = new StoredItem<BlockUndo>(Network, pos);
			item.HasChecksum = true;
			item.ReadWrite(stream, false);
			item.Item.CalculatedChecksum = item.Checksum;
			return item;
		}
	}
}
#endif

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once( 'auth_chanw.php' );

use cascade_ws_AOHS      as aohs;
use cascade_ws_constants as c;
use cascade_ws_asset     as a;
use cascade_ws_property  as p;
use cascade_ws_utility   as u;
use cascade_ws_exception as e;

try
{
    $connector = $cascade->getAsset(
        a\TwitterConnector::TYPE, "017580c98b7f08ee707c11d62dc35154" )->dump();
    $ct1 = $cascade->getAsset( a\ContentType::TYPE, "1378b3e38b7f08ee1890c1e4df869132" );
    // RWD
    $ct2 = $cascade->getAsset( a\ContentType::TYPE, "5f4525208b7f08ee76b12c41beb6145a" );

    /*/
    $connector->addContentTypeLink(
        $cascade->getAsset( a\ContentType::TYPE, "1378b3e38b7f08ee1890c1e4df869132" ),
        "XML"
    )->edit() ->dump();
    /*/

    echo u\StringUtility::getCoalescedString( $connector->getAuth1() ), BR;
    echo u\StringUtility::getCoalescedString( $connector->getAuth2() ), BR;
    echo u\StringUtility::getCoalescedString( $connector->getUrl() ), BR;
    echo u\StringUtility::boolToString( $connector->getVerified() ), BR;
    echo u\StringUtility::getCoalescedString( $connector->getVerifiedDate() ), BR;
    echo u\StringUtility::boolToString(
        $connector->hasContentType( "_common_assets:RWD One Region" ) ), BR;
    //$connector->removeContentTypeLink( $ct );
    //u\DebugUtility::dump( $connector->getConnectorContentTypeLinks() );
    //u\DebugUtility::dump( $connector->getConnectorParameters() );

    $destination = $cascade->getAsset(
        a\Destination::TYPE, "0755e15e8b7f08ee3295aa6d6c19fbe2" );

    $connector->setDestination( $destination )->edit();

    echo u\ReflectionUtility::getClassDocumentation( "cascade_ws_asset\Connector" );
}
catch( \Exception $e )
{
    echo S_PRE . $e . E_PRE;
}
catch( \Error $er )
{
    echo S_PRE . $er . E_PRE;
}
?>


text:
class Reports::AssigneeReport < Reports::Report

  def self.report_type
    "assigned_to"
  end

  def field
    @field ||= "assigned_to_id"
  end

  def rows
    @rows ||= @project.members.collect { |m| m.user }.sort
  end

  def data
    @data ||= WorkPackage.by_assigned_to(@project)
  end

  def title
    @title ||= WorkPackage.human_attribute_name(:assigned_to)
  end

end


text:
require 'test_helper'

module AcceptableApi
  class AcceptanceTest < Test::Unit::TestCase
    include Rack::Test::Methods

    class Example
      attr_accessor :token
      private :token=, :token

      def initialize token
	self.token = token
      end

      def self.find token
	# Normally this would load the resource from the data store
	new token
      end

      def to_s
	"token #{token}"
      end
    end

    class ExampleResource
      include AcceptableApi::Controller

      def show
	Example.find params[:token]
      end
    end

    def app
      a = AcceptableApi::Builder.new
      a.register Example => 'application/vnd.acceptable-api.example-v1+txt' do |ex|
	'Ducks ' + ex.to_s
      end

      a.register Example => 'application/vnd.acceptable-api.example-v2+txt' do |ex|
	'Chickens ' + ex.to_s
      end

      a.expose 'AcceptableApi::AcceptanceTest::ExampleResource#show', at: '/example/:token', via: 'get'
      a.to_app
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?><!--
     Copyright (C) 2013 The Android Open Source Project

     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.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <!-- This outer linear layout protects the fixed dimensions of the dialog.
         The dimensions are not respected if this outer layout is not present. -->
    <LinearLayout
        android:layout_width="@dimen/recurrence_picker_width"
        android:layout_height="@dimen/recurrence_picker_height"
        android:background="@color/recurrence_picker_background"
        android:orientation="vertical"
        android:padding="0dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:descendantFocusability="beforeDescendants"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/bpWhite"
                    android:paddingBottom="4dip"
                    android:paddingLeft="12dip"
                    android:paddingRight="12dip"
                    android:paddingTop="12dip">

                    <Spinner
                        android:id="@+id/freqSpinner"
                        style="@style/TextAppearance.RecurrencePickerStyle"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight="1"
                        android:background="@drawable/spinner_background_holo_light"
                        android:dropDownSelector="@drawable/item_background_holo_light"
                        android:entries="@array/recurrence_freq"
                        android:gravity="left"
                        android:padding="0dp" />

                    <android.support.v7.widget.SwitchCompat
                        android:id="@+id/repeat_switch"
                        style="@style/Widget.Holo.Light.CompoundButton.Switch"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_marginLeft="4dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/options"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:measureAllChildren="true"
                    android:orientation="vertical"
                    android:paddingBottom="4dp"
                    android:paddingLeft="12dp"
                    android:paddingRight="12dp"
                    android:paddingTop="4dp">

                    <LinearLayout
                        android:id="@+id/intervalGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="start"
                        android:paddingLeft="4dp">

                        <TextView
                            android:id="@+id/intervalPreText"
                            style="@style/TextAppearance.RecurrencePickerStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" />

                        <EditText
                            android:id="@+id/interval"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:background="@drawable/edit_text_holo_light"
                            android:ems="2"
                            android:gravity="center_horizontal"
                            android:inputType="number"
                            android:maxLength="2"
                            android:paddingLeft="4dp"
                            android:paddingRight="4dp"
                            android:selectAllOnFocus="true"
                            android:singleLine="true"
                            android:textSize="15sp"/>

                        <TextView
                            android:id="@+id/intervalPostText"
                            style="@style/TextAppearance.RecurrencePickerStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" />
                    </LinearLayout>

                    <com.codetroopers.betterpickers.recurrencepicker.LinearLayoutWithMaxWidth
                        android:id="@+id/weekGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="4dp"
                        android:layout_marginRight="4dp"
                        android:layout_marginTop="8dp"
                        android:gravity="center_horizontal"
                        android:orientation="horizontal">

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />
                    </com.codetroopers.betterpickers.recurrencepicker.LinearLayoutWithMaxWidth>

                    <com.codetroopers.betterpickers.recurrencepicker.LinearLayoutWithMaxWidth
                        android:id="@+id/weekGroup2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="4dp"
                        android:layout_marginRight="4dp"
                        android:gravity="center_horizontal"
                        android:orientation="horizontal"
                        android:visibility="gone">

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton style="@style/RecurrenceDayOfWeekStyle" />

                        <com.codetroopers.betterpickers.recurrencepicker.WeekButton
                            style="@style/RecurrenceDayOfWeekStyle"
                            android:visibility="invisible" />
                    </com.codetroopers.betterpickers.recurrencepicker.LinearLayoutWithMaxWidth>

                    <RadioGroup
                        android:id="@+id/monthGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <RadioButton
                            android:id="@+id/repeatMonthlyByNthDayOfMonth"
                            style="@style/TextAppearance.RecurrencePickerStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/recurrence_month_pattern_by_day" />

                        <RadioButton
                            android:id="@+id/repeatMonthlyByNthDayOfTheWeek"
                            style="@style/TextAppearance.RecurrencePickerStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" />
                    </RadioGroup>

                    <LinearLayout
                        android:id="@+id/endGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="start"
                        android:orientation="horizontal"
                        android:paddingLeft="0dp">

                        <Spinner
                            android:id="@+id/endSpinner"
                            style="@style/TextAppearance.RecurrencePickerStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="-4dp"
                            android:layout_marginRight="8dp"
                            android:background="@drawable/spinner_background_holo_light"
                            android:dropDownSelector="@drawable/item_background_holo_light"
                            android:entries="@array/recurrence_freq"
                            android:gravity="left|center_vertical"
                            android:padding="0dp" />

                        <EditText
                            android:id="@+id/endCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_marginBottom="-3dp"
                            android:background="@drawable/edit_text_holo_light"
                            android:ems="3"
                            android:gravity="center_horizontal"
                            android:inputType="number"
                            android:maxLength="3"
                            android:selectAllOnFocus="true"
                            android:singleLine="true"
                            android:textSize="15sp" />

                        <TextView
                            android:id="@+id/postEndCount"
                            style="@style/TextAppearance.RecurrencePickerStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_marginBottom="-3dp"
                            android:gravity="bottom"
                            android:singleLine="true"
                            android:visibility="gone" />

                        <TextView
                            android:id="@+id/endDate"
                            style="@style/TextAppearance.EditEvent_SpinnerButton"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:layout_marginLeft="0dp"
                            android:layout_marginRight="0dp"
                            android:layout_marginTop="3dp"
                            android:background="@drawable/spinner_background_holo_light"
                            android:contentDescription="@string/acessibility_recurrence_choose_end_date_description"
                            android:gravity="center_horizontal|bottom"
                            android:minWidth="80dp"
                            android:paddingBottom="8dp"
                            android:paddingLeft="12dp"
                            android:paddingRight="16dp"
                            android:singleLine="true"
                            android:textColor="@color/recurrence_spinner_text_color"
                            android:textSize="15sp"
                            android:visibility="gone" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </ScrollView>

        <include layout="@layout/layout_ok_cancel_buttons" />
    </LinearLayout>
</LinearLayout>


text:
""" This containing a subclassed QGraphicsView that allows
zoom/pan/select inside the graphics view and supports PIP as well

QInteractiveGraphicsScene
QInteractiveGraphicsView
QPIPGraphicsView
"""
from vistrails.core import debug
from PyQt4 import QtCore, QtGui
from vistrails.gui.theme import CurrentTheme
from vistrails.core.configuration import get_vistrails_configuration
import vistrails.core.system
import math
from vistrails.gui.qt import qt_super
################################################################################

class QGraphicsItemInterface(object):
    """
    QGraphicsItem will override the default QGraphicsItem mouseRelease
    event to let it fires only 1 ItemSelectionChanged event. This is
    due to the clearSelection() in
    qgraphicsitem.cpp::QGrahpicsItem::mouseReleaseEvent

    """
    pass

class QGraphicsRubberBandItem(QtGui.QGraphicsRectItem):
    """
    QGraphicsRubberBandItem try to replace QRubberBand to have a
    unified look and feel on all platform. In the end, it mimics the
    Windows look. It is just a rectangle with a 50% transparency

    """
    def paint(self, painter, option, widget=None):
        """ paint(painter: QPainter, option: QStyleOptionGraphicsItem,
                  widget: QWidget) -> None
        Peform actual painting of the rubber band

        """
        painter.setOpacity(0.5)
        painter.fillRect(self.rect(),
                         CurrentTheme.SELECTION_BOX_BRUSH)
        painter.setOpacity(1.0)
        painter.setPen(CurrentTheme.SELECTION_BOX_PEN)
        painter.drawRect(self.rect())

class QInteractiveGraphicsScene(QtGui.QGraphicsScene):
    """
    QInteractiveGraphicsScene expands QGraphicsScene to allow panning
    freely over the view are

    """
    def __init__(self, parent=None):
        """ QInteractiveGraphicsScene(parent: QWidget)
                                      -> QInteractiveGraphicsScene
        Initialize the actual scene bounding rect
        """
        QtGui.QGraphicsScene.__init__(self, parent)
        self.sceneBoundingRect = QtCore.QRectF()
        self.multiSelecting = False

    def updateSceneBoundingRect(self, keep_square=False):
        """ updateSceneBoundingRect() -> None
        Compute the actual bounding rect of all shapes, then update
        the scene rect to be much wider for panning

        """
        self.sceneBoundingRect = QtCore.QRectF()
        for item in self.items():
            rect = item.sceneBoundingRect()
            self.sceneBoundingRect = self.sceneBoundingRect.united(rect)

        # Keep a minimum size
        minWDiff = 0
        minHDiff = 0
        min = CurrentTheme.BOUNDING_RECT_MINIMUM
        if self.sceneBoundingRect.width() < min:
            minWDiff = min-self.sceneBoundingRect.width()
        if self.sceneBoundingRect.height() < min:
            minHDiff = min-self.sceneBoundingRect.height()
        self.sceneBoundingRect.adjust(-minWDiff/2, -minHDiff/2,
                                       minWDiff/2, minHDiff/2)

        if keep_square:
            diff = abs(self.sceneBoundingRect.width()-
                       self.sceneBoundingRect.height())
            if self.sceneBoundingRect.width()<self.sceneBoundingRect.height():
                self.sceneBoundingRect.adjust(-diff/2, 0, diff/2, 0)
            else:
                self.sceneBoundingRect.adjust(0, -diff/2, 0, diff/2)
        panRect = self.sceneBoundingRect.adjusted(
            -self.sceneBoundingRect.width()*2,
            -self.sceneBoundingRect.height()*2,
            self.sceneBoundingRect.width()*2,
            self.sceneBoundingRect.height()*2)
        if panRect.width()<1e-6 and panRect.height()<1e-6:
            panRect = QtCore.QRectF(-1000,-1000,2000,2000)
        self.setSceneRect(panRect)

        # Reset cache
        for view in self.views():
            view.resetCachedContent()

    def fitToView(self, view, recompute_bounding_rect=False):
        """ fitToView(view: QGraphicsView,
                      recompute_bounding_rect=False) -> None
        Adjust view to fit and center the whole scene. If recompute_bounding_rect is
        False, does not recompute bounds, and instead uses previous one.

        """
        if recompute_bounding_rect:
            self.updateSceneBoundingRect()
        view.centerOn(self.sceneBoundingRect.center())
        view.fitInView(self.sceneBoundingRect, QtCore.Qt.KeepAspectRatio)

    def fitToAllViews(self, recompute_bounding_rect=False):
        """ fitToAllViews(recompute_bounding_rect=False) -> None
        Adjust all views using this scene to fit and center the whole scene

        if recompute_bounding_rect is False, uses previous bounding rect.

        """
        if recompute_bounding_rect:
            self.updateSceneBoundingRect()
        for view in self.views():
            self.fitToView(view, False)

    def clearItems(self):
        """ clearShapes() -> None
        Remove and delete all items belonging to this scene

        """
        self.removeItems(self.items())

    def removeItems(self, itemList):
        """ removeItems(itemList: sequence of [QGraphicsItem]) -> None
        Remove all items in itemList

        """
        for item in itemList:
            if item.scene():
                self.removeItem(item)

    def saveToPDF(self, filename):
        self.updateSceneBoundingRect(False)
        printer = QtGui.QPrinter()
        printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
        printer.setOutputFileName(filename)
        b_rect = self.sceneBoundingRect
        debug.debug("%sx%s" % (b_rect.width(), b_rect.height()))
        printer.setPaperSize(QtCore.QSizeF(b_rect.width(), b_rect.height()),
                             QtGui.QPrinter.Point)
        painter = QtGui.QPainter(printer)
        brush = self.backgroundBrush()
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(255,255,255)))
        self.render(painter, QtCore.QRectF(), b_rect)
        painter.end()
        self.setBackgroundBrush(brush)

    def saveToPNG(self, filename, width=None):
        try:
            self.updateSceneBoundingRect(False)
            b_rect = QtCore.QRectF(self.sceneBoundingRect)
            b_rect.setWidth(math.floor(b_rect.width()))
            b_rect.setHeight(math.floor(b_rect.height()))
            debug.debug("PNG bounding box %sx%s" % (b_rect.width(), b_rect.height()))
            pixmap = QtGui.QPixmap(QtCore.QSize(int(math.floor(b_rect.width())),
                                                int(math.floor(b_rect.height()))))
            debug.debug("PNG pixmap size: %s"%str(pixmap.size()))
            painter = QtGui.QPainter(pixmap)
            painter.setRenderHint(QtGui.QPainter.Antialiasing)
            brush = self.backgroundBrush()
            self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(255,255,255)))
            self.render(painter, QtCore.QRectF(), b_rect)
            painter.end()
            if width is not None:
                pixmap = pixmap.scaledToWidth(width, QtCore.Qt.SmoothTransformation)
            pixmap.save(filename)
            self.setBackgroundBrush(brush)
        except Exception, e:
            debug.critical("Exception saving to PNG", e)

class QInteractiveGraphicsView(QtGui.QGraphicsView):
    """
    QInteractiveGraphicsView is QGraphicsView with abilities to
    zoom/span with right/mid click

    """
    def __init__(self, parent=None):
        """ QInteractiveGraphicsView(parent: QWidget)
                                     -> QInteractiveGraphicsView
        Initialize the graphics view with interactive options

        """
        QtGui.QGraphicsView.__init__(self, parent)
        self.setInteractive(True)
#        self.setCacheMode(QtGui.QGraphicsView.CacheBackground)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
        self.setRenderHints (QtGui.QPainter.Antialiasing |
                             QtGui.QPainter.TextAntialiasing |
                             QtGui.QPainter.SmoothPixmapTransform)
        self.scaleMax = 2000
        self.scaleRatio = self.scaleMax/10
        self.scaleOffset = 700
        self.currentScale = self.scaleMax/2
        self.startScroll = (0,0)
        self.lastPos = QtCore.QPoint(0,0)
        self.pipScene = None
        self.pipFrame = None
        self.resetButton = None
        self.selectionBox = QGraphicsRubberBandItem(None)
        self.startSelectingPos = None
        self.setProperty('captureModifiers', 1)
        self.defaultCursorState = 0
        self.setCursorState(self.defaultCursorState)
        self.canSelectBackground = True
        self.canSelectRectangle = True

        if QtCore.QT_VERSION >= 0x40600:
            self.viewport().grabGesture(QtCore.Qt.PinchGesture)
        self.gestureStartScale = None

        conf = get_vistrails_configuration()
        conf.subscribe('showScrollbars', self.setScrollbarPolicy)
        self.setScrollbarPolicy('showScrollbars', conf.showScrollbars)

    def setScrollbarPolicy(self, field, value):
        if value:
            self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
            self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        else:
            self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
            self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

    def viewportEvent(self, event):
        if QtCore.QT_VERSION >= 0x40600 and event.type() == QtCore.QEvent.Gesture:
            pinch = event.gesture(QtCore.Qt.PinchGesture)
            if pinch:
                changeFlags = pinch.changeFlags()
                if changeFlags & QtGui.QPinchGesture.ScaleFactorChanged:
                    if self.gestureStartScale is None:
                        self.computeScale()
                        self.gestureStartScale = self.currentScale
                    newScale = self.gestureStartScale + self.scaleMax * \
                        math.log(pinch.property("scaleFactor"))/2
                    # Clamp the scale
                    if newScale<0: newScale = 0
                    if newScale>self.scaleMax: newScale = self.scaleMax
                    self.currentScale = newScale
                    self.updateMatrix()
                if pinch.state() == QtCore.Qt.GestureFinished:
                    self.gestureStartScale = None
                return True
        return QtGui.QGraphicsView.viewportEvent(self, event)

    def modifiersPressed(self, modifiers):
        """ modifiersPressed(modifiers: QtCore.Qt.KeyboardModifiers) -> None
        Notification when one of the modifier keys has been pressed

        """
        self.validateCursorState(modifiers)

    def modifiersReleased(self):
        """ modifiersReleased() -> None
        Notification when one of the modifier keys has been released

        """
        self.validateCursorState()

    def findCursorState(self, modifiers=None):
        """ findCursorState(modifiers: QtCore.Qt.KeyboardModifiers) -> None
        Check the keyboard modifiers and return the cursor state

        """
        if not self.isActiveWindow():
            return self.defaultCursorState
        if modifiers==None:
            modifiers = QtGui.QApplication.keyboardModifiers()
        shift = modifiers & QtCore.Qt.ShiftModifier
        alt = modifiers & QtCore.Qt.AltModifier
        meta = modifiers & QtCore.Qt.MetaModifier or (alt and shift)
        ctrl = modifiers & QtCore.Qt.ControlModifier
        if shift and (not alt) and (not ctrl) and (not meta):
            return 1
        elif meta and (not ctrl):
            return 2
        else:
            return self.defaultCursorState

    def validateCursorState(self, modifiers=None):
        """ validateCursorState(modifiers: QtCore.Qt.KeyboardModifiers) -> None
        Check the keyboard modifiers to change the cursor shape correspondingly

        """
        self.setCursorState(self.findCursorState(modifiers))

    def enterEvent(self, event):
        """ enterEvent(event: QEnterEvent) -> None
        Check the modifiers state when the mouse enter the
        canvas. Then update the mouse functionality appropriately

        """
        self.validateCursorState()
        return QtGui.QGraphicsView.enterEvent(self, event)
        # super(QInteractiveGraphicsView, self).enterEvent(event)

    def setCursorState(self, state):
        """ setCursorState(state: int) -> None
        Update the cursor shape

        Keyword arguments:
        state - 0: selecting (default)
                1: pan
                2: zoom
                3: panning

        """
        if state==0:
            self.viewport().setCursor(CurrentTheme.SELECT_CURSOR)
        elif state==1:
            self.viewport().setCursor(CurrentTheme.OPEN_HAND_CURSOR)
        elif state==2:
            self.viewport().setCursor(CurrentTheme.ZOOM_CURSOR)
        elif state==3:
            self.viewport().setCursor(CurrentTheme.CLOSE_HAND_CURSOR)

    def setDefaultCursorState(self, state):
        """ setDefaultCursorState(state: int) -> None
        Set the default cursor state when no modifier key is pressed

        """
        self.defaultCursorState = state
        self.validateCursorState()

    def translateButton(self, event):
        """ translateButton(event: QInputEvent) -> None
        Translate mouse button and modifiers into a virtual mouse button

        """
        if event.buttons() & QtCore.Qt.LeftButton:
            state = self.findCursorState(event.modifiers())
            state2Button = {0: QtCore.Qt.LeftButton,
                            1: QtCore.Qt.MidButton,
                            2: QtCore.Qt.RightButton}
            if state2Button.has_key(state):
                return state2Button[state]
        return event.buttons()

    def mousePressEvent(self, e):
        """ mousePressEvent(e: QMouseEvent) -> None
        Handle mouse click event, use Qt rubber band for left-click
        selection and prepare for zoom/pan on right/mid click

        """
        scenePos = self.mapToScene(e.pos())
        item = self.scene().itemAt(scenePos)
        buttons = self.translateButton(e)
        if buttons == QtCore.Qt.LeftButton:
            if item is None:
                if self.scene():
                    self.scene().multiSelecting = True
                    self.scene().addItem(self.selectionBox)
                    self.selectionBox.setZValue(1000)

                    self.startSelectingPos = self.mapToScene(e.pos())
                    rect = QtCore.QRectF(self.startSelectingPos,
                                         QtCore.QSizeF(0,0))
                    self.selectionBox.setRect(rect)
                    self.selectionBox.setVisible(self.canSelectRectangle)
            else:
                QtGui.QGraphicsView.mousePressEvent(self, e)
                # super(QInteractiveGraphicsView, self).mousePressEvent(e)
        else:
            if buttons & QtCore.Qt.RightButton:
                self.computeScale()
                if item is None:
                    self.setCursorState(2)
                else:
                    QtGui.QGraphicsView.mousePressEvent(self, e)
            elif buttons & QtCore.Qt.MidButton:
                self.setCursorState(3)
                self.computeScale()
                self.startScroll = (self.horizontalScrollBar().value(),
                                    self.verticalScrollBar().value())
            self.lastPos = QtCore.QPoint(QtGui.QCursor.pos())
            self.setDragMode(QtGui.QGraphicsView.NoDrag)

    def mouseMoveEvent(self, e):
        """ mouseMoveEvent(e: QMouseEvent) -> None
        Handle right click (zoom) and mid click (pan). This function
        uses QCursor globalPos instead of e.globalX() and e.globalY()
        because of their flaky values during transformation

        """
        self.setUpdatesEnabled(False)
        buttons = self.translateButton(e)
        if buttons == QtCore.Qt.LeftButton:
            if self.startSelectingPos:
                dis = self.mapToScene(e.pos())-self.startSelectingPos
                rect = QtCore.QRectF(self.startSelectingPos,
                                 QtCore.QSizeF(dis.x(), dis.y()))
                self.selectionBox.prepareGeometryChange()
                self.selectionBox.setRect(rect)
                self.selectModules()
            else:
                QtGui.QGraphicsView.mouseMoveEvent(self, e)
                # super(QInteractiveGraphicsView, self).mousePressEvent(e)
        elif self.lastPos:
            if buttons == QtCore.Qt.RightButton:
                globalPos = QtGui.QCursor.pos()

                # Set up new scale based on pixels moved
                newScale = self.currentScale + globalPos.y() - self.lastPos.y()

                # Clamp the scale
                if newScale<0: newScale = 0
                if newScale>self.scaleMax: newScale = self.scaleMax

                # Update the scale and transformation matrix
                self.currentScale = newScale
                self.updateMatrix()

                # Need to update last position
                self.lastPos = QtCore.QPoint(globalPos)

            elif buttons == QtCore.Qt.MidButton:
                globalPos = QtGui.QCursor.pos()

                # Just need to pan the scroll bar
                self.horizontalScrollBar().setValue(self.startScroll[0] -
                                                    globalPos.x() +
                                                    self.lastPos.x())
                self.verticalScrollBar().setValue(self.startScroll[1] -
                                                  globalPos.y() +
                                                  self.lastPos.y())
        else:
            self.validateCursorState(e.modifiers())
            QtGui.QGraphicsView.mouseMoveEvent(self, e)
        self.setUpdatesEnabled(True)

    def mouseReleaseEvent(self, e):
        """ mouseReleaseEvent(self, e: QMouseEvent) -> None
        Mark box selecting as off
        """
        if self.startSelectingPos:
            self.selectModules()
            self.startSelectingPos = None
            self.selectionBox.setVisible(False)
            self.scene().removeItem(self.selectionBox)
            self.scene().multiSelecting = False
        self.lastPos = None
        self.validateCursorState(e.modifiers())
        self.setUpdatesEnabled(True)
        QtGui.QGraphicsView.mouseReleaseEvent(self, e)
        # super(QInteractiveGraphicsView, self).mouseReleaseEvent(e)

    def mouseDoubleClickEvent(self, e):
        """ mouseDoubleClickEvent(self, e: QMouseEvent) -> None
        Try to avoid unselect if double-click on the background
        """
        if not self.canSelectBackground:
            return
        else:
            qt_super(QInteractiveGraphicsView, self).mouseDoubleClickEvent(e)

    def selectModules(self):
        """ selectModules() -> None
        Select all modules inside the self.selectionBox

        """
        if self.canSelectRectangle:
            br = self.selectionBox.sceneBoundingRect()
        else:
            br = QtCore.QRectF(self.startSelectingPos,
                              self.startSelectingPos)
        if not self.canSelectBackground:
            items = self.scene().items(br)
            if len(items)==0 or items==[self.selectionBox]:
                return
        path = QtGui.QPainterPath()
        path.addRect(br)
        self.scene().setSelectionArea(path)

    def updateMatrix(self):
        """ updateMatrix() -> None
        Update the view matrix with the current scale

        """
        matrix = QtGui.QMatrix()
        power = float(self.currentScale - self.scaleMax/2 - self.scaleOffset
                      )/self.scaleRatio
        scale = pow(2.0, power)
        matrix.scale(scale, scale)
        self.setMatrix(matrix)

    def computeScale(self):
        """ computeScale() -> None
        Compute the current scale based on the view matrix

        """
        self.currentScale = (math.log(self.matrix().m11(), 2.0)*
                             self.scaleRatio + self.scaleMax/2 +
                             self.scaleOffset)

    def setPIPScene(self, scene):
        """ setPIPScene(scene: QGraphicsScene) -> None
        Set the Picture-In-Picture scene fo the current GraphicsView
        to 'scene'

        """
        self.pipScene = scene

    def setPIPEnabled(self, enabled=True):
        """ setPIPEnabled(enabled: boolean) -> None
        Enable/Disable PIP view

        """
        if self.pipScene:
            if enabled:
                if self.pipFrame==None:
                    self.pipFrame = QPIPGraphicsView(self)
                    self.pipFrame.graphicsView.setScene(self.pipScene)
                    self.pipFrame.move(self.width(), 0)
                self.pipFrame.show()
                self.pipFrame.updateGeometry()
            elif self.pipFrame!=None:
                self.pipFrame.hide()

    def setQueryEnabled(self, enabled=True):
        """ setQueryEnabled(enabled: bool) -> None
        Enable/Disable the query reset button

        """
        if enabled:
            if not self.resetButton:
                self.resetButton = QResetQueryButton(self)
                self.connect(self.resetButton,
                             QtCore.SIGNAL('resetQuery()'),
                             self.resetQuery)
            self.resetButton.show()
            self.resetButton.updateGeometry()
        else:
            if self.resetButton:
                self.resetButton.hide()
            self.scene().update()

    def resetQuery(self):
        """ resetQuery() -> None
        pass the signal along

        """
        self.emit(QtCore.SIGNAL('resetQuery()'))

    def resizeEvent(self, event):
        """ resizeEvent(event: QResizeEvent) -> None
        Make sure the pip frame is inside the graphics view
        """
        if self.pipFrame:
            self.pipFrame.updateGeometry()
        if self.resetButton:
            self.resetButton.updateGeometry()
        return QtGui.QGraphicsView.resizeEvent(self, event)
        # super(QInteractiveGraphicsView, self).resizeEvent(event)

    def zoomToFit(self):
        self.scene().fitToView(self, True)
        self.computeScale()

    def zoomIn(self):
        self.setUpdatesEnabled(False)
        newScale = self.currentScale + 100.0

        # Clamp the scale
        if newScale<0: newScale = 0
        if newScale>self.scaleMax: newScale = self.scaleMax

        # Update the scale and transformation matrix
        self.currentScale = newScale
        self.updateMatrix()
        self.setUpdatesEnabled(True)

    def zoomOut(self):
        self.setUpdatesEnabled(False)
        newScale = self.currentScale - 100.0

        # Clamp the scale
        if newScale<0: newScale = 0
        if newScale>self.scaleMax: newScale = self.scaleMax

        # Update the scale and transformation matrix
        self.currentScale = newScale
        self.updateMatrix()
        self.setUpdatesEnabled(True)

    def sizeHint(self):
        """ sizeHint(self) -> QSize
        Return recommended size of the widget

        """
        return QtCore.QSize(512, 512)

    def save_pdf(self, filename=None):
        if filename is None:
            fileName = QtGui.QFileDialog.getSaveFileName(self.window(),
                "Save PDF...",
                vistrails.core.system.vistrails_file_directory(),
                "PDF files (*.pdf)")

            if not fileName:
                return None
            f = str(fileName)
        else:
            f = str(filename)

        self.scene().saveToPDF(f)

    # Workaround for border aliasing on OSX
    # However, it breaks things on Linux, because it
    # makes zooming _extremely_ slow, so we check it
    # before we run.
    if vistrails.core.system.systemType == 'Darwin':
        def setScene(self, scene):
            """ setScene(scene: QGraphicsScene) -> None
            Make sure the viewport background brush the same as the scene
            one. This is only neccessary on the Mac to work around Qt/Mac
            bug. We can remove this if any future release of Qt fixes
            this.

            """
            QtGui.QGraphicsView.setScene(self, scene)
            if self.scene():
                palette = QtGui.QPalette(self.viewport().palette())
                palette.setBrush(QtGui.QPalette.Base,
                                 self.scene().backgroundBrush())
                self.viewport().setPalette(palette)

class QPIPGraphicsView(QtGui.QWidget):
    """
    QPIPGraphicsView is a tool window contain a
    QInteractiveGraphicsView for PIP display

    """
    def __init__(self, parent=None):
        """ QPIPGraphicsView(parent: QWidget) -> QPIPGraphicsView
        Initialize a layout with some margin and a central widget
        """
        QtGui.QWidget.__init__(self, parent, QtCore.Qt.FramelessWindowHint)
        self.setMouseTracking(True)
        self.setAutoFillBackground(True)
        self.palette().setColor(QtGui.QPalette.Base,
                                CurrentTheme.PIP_FRAME_COLOR)
        self.setLayout(QtGui.QHBoxLayout(self))
        self.layout().setMargin(CurrentTheme.PIP_OUT_FRAME_WIDTH)
        self.graphicsView = QInteractiveGraphicsView()
        self.layout().addWidget(self.graphicsView)
        self.firstShow = True
        self.anchorCorner = [QtCore.Qt.AlignRight, QtCore.Qt.AlignTop]

    def sizeHint(self):
        """ sizeHint(self) -> QSize
        Return recommended size of the widget

        """
        return QtCore.QSize(*CurrentTheme.PIP_DEFAULT_SIZE)

    def mousePressEvent(self, e):
        """ mousePressEvent(e: QMouseEvent) -> None
        Capture mouse press event on the frame to move the widget

        """
        if e.buttons() & QtCore.Qt.LeftButton:
            self.resizing = False
            self.lastPos = QtCore.QPoint(e.globalX(), e.globalY())
            gvRect = self.graphicsView.geometry()
            if ((e.x()<gvRect.left() or e.x()>gvRect.right()) and
                (e.y()<gvRect.top() or e.y()>gvRect.bottom())):
                self.direction = [1,1]
                if e.x()<gvRect.left():
                    self.direction[0] = -1
                if e.y()<gvRect.top():
                    self.direction[1] = -1
                self.resizing = True

    def mouseMoveEvent(self, e):
        """ mouseMoveEvent(e: QMouseEvent) -> None
        Move widget as the mouse moving

        """
        if e.buttons() & QtCore.Qt.LeftButton:
            (dx, dy) = (e.globalX()-self.lastPos.x(),
                        e.globalY()-self.lastPos.y())
            parentGeometry = self.parent().geometry()
            newGeometry = QtCore.QRect(self.geometry())
            if self.resizing:
                if self.direction[0]==1:
                    if newGeometry.right()+dx>parentGeometry.width()-1:
                        dx = parentGeometry.width()-1-newGeometry.right()
                    newGeometry.adjust(0, 0, dx, 0)
                else:
                    if newGeometry.left()+dx<0:
                        dx = -newGeometry.left()
                    newGeometry.adjust(dx, 0, 0, 0)

                if self.direction[1]==1:
                    if newGeometry.bottom()+dy>parentGeometry.height()-1:
                        dy = parentGeometry.height()-1-newGeometry.bottom()
                    newGeometry.adjust(0, 0, 0, dy)
                else:
                    if newGeometry.top()+dy<0:
                        dy = -newGeometry.top()
                    newGeometry.adjust(0, dy, 0, 0)
            else:
                newGeometry.translate(dx, dy)
            if (newGeometry.left()>0 and
                newGeometry.right()<parentGeometry.width()-1):
                self.anchorCorner[0] = None
            if (newGeometry.top()>0 and
                newGeometry.bottom()<parentGeometry.height()-1):
                self.anchorCorner[1] = None
            self.updateGeometry(newGeometry)
            self.lastPos = QtCore.QPoint(e.globalX(), e.globalY())

    def updateGeometry(self, newGeometry=None):
        """ updateGeometry() -> None
        Make sure the widget is inside the parent graphics view

        """
        parentGeometry = self.parent().geometry()
        if newGeometry==None:
            newGeometry = QtCore.QRect(self.geometry())

        if self.anchorCorner[0]==None:
            if newGeometry.left()<0:
                newGeometry.moveLeft(0)
            if newGeometry.right()>=parentGeometry.width():
                newGeometry.moveRight(parentGeometry.width()-1)
            if newGeometry.left()==0:
                self.anchorCorner[0] = QtCore.Qt.AlignLeft
            if newGeometry.right()==parentGeometry.width()-1:
                self.anchorCorner[0] = QtCore.Qt.AlignRight
        else:
            if self.anchorCorner[0]==QtCore.Qt.AlignLeft:
                newGeometry.moveLeft(0)
            if self.anchorCorner[0]==QtCore.Qt.AlignRight:
                newGeometry.moveRight(parentGeometry.width()-1)

        if self.anchorCorner[1]==None:
            if newGeometry.top()<0:
                newGeometry.moveTop(0)
            if newGeometry.bottom()>=parentGeometry.height():
                newGeometry.moveBottom(parentGeometry.height()-1)
            if newGeometry.top()==0:
                self.anchorCorner[1] = QtCore.Qt.AlignTop
            if newGeometry.bottom()==parentGeometry.height()-1:
                self.anchorCorner[1] = QtCore.Qt.AlignBottom
        else:
            if self.anchorCorner[1]==QtCore.Qt.AlignTop:
                newGeometry.moveTop(0)
            if self.anchorCorner[1]==QtCore.Qt.AlignBottom:
                newGeometry.moveBottom(parentGeometry.height()-1)

        self.setGeometry(newGeometry)

    def showEvent(self, event):
        """ showEvent(event: QShowEvent) -> None
        Fit the scene to view for the show event only

        """
        if self.firstShow:
            self.firstShow = False
            self.graphicsView.scene().fitToView(self.graphicsView, True)
        return QtGui.QWidget.showEvent(self, event)
        # super(QPIPGraphicsView, self).showEvent(event)

    def enterEvent(self, event):
        """ enterEvent(event: QEnterEvent) -> None
        Show a larger frame when the mouse enter to facilitate
        resizing

        """
        self.layout().setMargin(CurrentTheme.PIP_IN_FRAME_WIDTH)

    def leaveEvent(self, event):
        """ leaveEvent(event: QLeaveEvent) -> None
        Show a smaller frame when the mouse exit the widget to get
        more view

        """
        self.layout().setMargin(CurrentTheme.PIP_OUT_FRAME_WIDTH)

class QResetQueryButton(QtGui.QLabel):
    """

    """
    def __init__(self, parent=None):
        QtGui.QLabel.__init__(self, parent)

        self.setText('Reset Query')
        self.setFrameStyle(QtGui.QFrame.StyledPanel)
        self.setFrameShadow(QtGui.QFrame.Raised)
        self.marginPad = 10

    def mousePressEvent(self, e):
        """ mousePressEvent(e: QMouseEvent) -> None
        Capture mouse press event on the frame to move the widget

        """
        if e.buttons() & QtCore.Qt.LeftButton:
            self.setFrameShadow(QtGui.QFrame.Sunken)

    def mouseReleaseEvent(self, e):
        self.setFrameShadow(QtGui.QFrame.Raised)
        self.emit(QtCore.SIGNAL('resetQuery()'))

    def updateGeometry(self):
        parentGeometry = self.parent().geometry()
        self.move(self.marginPad,
                  parentGeometry.height()-self.height()-self.marginPad)


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using Wyam.Modules.Razor.Microsoft.AspNet.Mvc.Rendering;
using Wyam.Modules.Razor.Microsoft.Framework.Internal;

namespace Wyam.Modules.Razor.Microsoft.AspNet.Mvc.Razor
{
    /// <summary>
    /// Default implementation of <see cref="IRazorViewEngine"/>.
    /// </summary>
    /// <remarks>
    /// For <c>ViewResults</c> returned from controllers, views should be located in <see cref="ViewLocationFormats"/>
    /// by default. For the controllers in an area, views should exist in <see cref="AreaViewLocationFormats"/>.
    /// </remarks>
    public class RazorViewEngine : IRazorViewEngine
    {
        private const string ViewExtension = ".cshtml";

        private static readonly IEnumerable<string> _viewLocationFormats = new[]
        {
            "/{0}",
            "/Shared/{0}",
            "/Views/{0}",
            "/Views/Shared/{0}"
        };

        private readonly IRazorPageFactory _pageFactory;
        private readonly IRazorViewFactory _viewFactory;

        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine" /> class.
        /// </summary>
        /// <param name="pageFactory">The page factory used for creating <see cref="IRazorPage"/> instances.</param>
        public RazorViewEngine(IRazorPageFactory pageFactory,
                               IRazorViewFactory viewFactory)
        {
            _pageFactory = pageFactory;
            _viewFactory = viewFactory;
        }

        /// <summary>
        /// Gets the locations where this instance of <see cref="RazorViewEngine"/> will search for views.
        /// </summary>
        /// <remarks>
        /// The locations of the views returned from controllers that do not belong to an area.
        /// Locations are composite format strings (see http://msdn.microsoft.com/en-us/library/txafckwd.aspx),
        /// which contains following indexes:
        /// {0} - Action Name
        /// {1} - Controller Name
        /// The values for these locations are case-sensitive on case-senstive file systems.
        /// For example, the view for the <c>Test</c> action of <c>HomeController</c> should be located at
        /// <c>/Views/Home/Test.cshtml</c>. Locations such as <c>/views/home/test.cshtml</c> would not be discovered
        /// </remarks>
        public virtual IEnumerable<string> ViewLocationFormats
        {
            get { return _viewLocationFormats; }
        }

        // Gets a view that acts like a normal file-based view, but uses the provided content
        public ViewEngineResult GetView([NotNull] ViewContext context,
                                         string viewName,
                                         Stream stream)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException("viewName");
            }

            var pageResult = GetRazorPageResult(context, viewName, isPartial: false, stream: stream);
            return CreateViewEngineResult(pageResult, _viewFactory, isPartial: false);
        }

        /// <inheritdoc />
        public ViewEngineResult FindView([NotNull] ViewContext context,
                                         string viewName)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException("viewName");
            }

            var pageResult = GetRazorPageResult(context, viewName, isPartial: false);
            return CreateViewEngineResult(pageResult, _viewFactory, isPartial: false);
        }

        /// <inheritdoc />
        public ViewEngineResult FindPartialView([NotNull] ViewContext context,
                                                string partialViewName)
        {
            if (string.IsNullOrEmpty(partialViewName))
            {
                throw new ArgumentException("partialViewName");
            }

            var pageResult = GetRazorPageResult(context, partialViewName, isPartial: true);
            return CreateViewEngineResult(pageResult, _viewFactory, isPartial: true);
        }

        /// <inheritdoc />
        public RazorPageResult FindPage([NotNull] ViewContext context,
                                        string pageName)
        {
            if (string.IsNullOrEmpty(pageName))
            {
                throw new ArgumentException("pageName");
            }

            return GetRazorPageResult(context, pageName, isPartial: true);
        }

        private RazorPageResult GetRazorPageResult(ViewContext context,
                                                   string pageName,
                                                   bool isPartial,
                                                   Stream stream = null)
        {
            if (!pageName.EndsWith(ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                pageName += ViewExtension;
            }
            if (IsApplicationRelativePath(pageName))
            {
                var applicationRelativePath = pageName;
                var page = _pageFactory.CreateInstance(applicationRelativePath, stream);
                if (page != null)
                {
                    return new RazorPageResult(pageName, page);
                }

                return new RazorPageResult(pageName, new[] { pageName });
            }
            else
            {
                return LocatePageFromViewLocations(context, pageName, isPartial);
            }
        }

        private RazorPageResult LocatePageFromViewLocations(ViewContext context,
                                                            string pageName,
                                                            bool isPartial)
        {
            // First search paths relative to the current view (and up the hierarchy)
            List<string> viewLocations = new List<string>();
            if (context.View != null && !string.IsNullOrWhiteSpace(context.View.Path))
            {
                string parentPath = Path.GetDirectoryName(context.View.Path).Replace('\\', '/');
                while (!string.IsNullOrWhiteSpace(parentPath) && parentPath != "/")
                {
                    viewLocations.AddRange(ViewLocationFormats.Select(x => parentPath + x));
                    parentPath = Path.GetDirectoryName(parentPath).Replace('\\', '/');
                }
            }

            // Now add the non-relative paths
            viewLocations.AddRange(ViewLocationFormats);

            // 3. Use the expanded locations to look up a page.
            var searchedLocations = new List<string>();
            foreach (var path in viewLocations)
            {
                var transformedPath = string.Format(CultureInfo.InvariantCulture,
                                                    path,
                                                    pageName);
                var page = _pageFactory.CreateInstance(transformedPath);
                if (page != null)
                {
                    return new RazorPageResult(pageName, page);
                }

                searchedLocations.Add(transformedPath);
            }

            // 3b. We did not find a page for any of the paths.
            return new RazorPageResult(pageName, searchedLocations);
        }

        private ViewEngineResult CreateViewEngineResult(RazorPageResult result,
                                                        IRazorViewFactory razorViewFactory,
                                                        bool isPartial)
        {
            if (result.SearchedLocations != null)
            {
                return ViewEngineResult.NotFound(result.Name, result.SearchedLocations);
            }

            var view = razorViewFactory.GetView(this, result.Page, isPartial);
            return ViewEngineResult.Found(result.Name, view);
        }

        private static bool IsApplicationRelativePath(string name)
        {
            Debug.Assert(!string.IsNullOrEmpty(name));
            return name[0] == '~' || name[0] == '/';
        }
    }
}


text:
<?php

interface Sabre_CalDAV_ISharedCalendar extends Sabre_CalDAV_ICalendar {

    /**
     * This method should return the url of the owners' copy of the shared
     * calendar.
     *
     * @return string
     */
    function getSharedUrl();

}


text:
<?php

class Plugin
{
    /**
     * hasCMsModule()
     * Checks if it has a CMS module following the path controller convention:
     *      app/plugins/[pluginName]/controllers/[pluginName]_cms_controller.php
     *
     * @param (string) $pluginName The plugin name to check.
     *
     * @return (boolean) TRUE if it has a CMS module. FALSE if not.
     */
    public static function hasCmsModule($pluginName)
    {
        if( CakePlugin::loaded($pluginName) )
        {
            if( is_file(CakePlugin::path($pluginName) . "/Controller/$pluginName" . "CmsController.php") )
            {
                return true;
            }
        }

        return false;
    }

    /**
     * loadPluginObject()
     * Loads and return an instance of the plugin configuration object.
     *
     * @param (string) $pluginName
     * @return ([pluginName]Plugin) Plugin object instance
     */
    public static function loadPluginObject($pluginName)
    {
        $className  = $pluginName . 'Plugin';
        $path       = CakePlugin::path($pluginName) . '/Config/plugin.php';

        $pluginObject = false;

        if( is_file($path) )
        {
            include_once($path);
            $pluginObject = new $className();
        }

        return $pluginObject;
    }

    /**
     * getPluginName()
     * Returns the display name for a given plugin
     *
     * @param (string) $plugin
     * @return (string) Plugin name
     *
     */
    public static function getPluginName($plugin)
    {
        $pluginObject = self::loadPluginObject($plugin);

        if(!empty($pluginObject))
        {
            return $pluginObject->getCmsModuleName();
        }
        else
        {
            return false;
        }
    }

    /**
     * getCmsModulesMenu()
     * Creates an array with all the CMS menu items retrieved from the installed plugins.
     *
     * @param (bool) $superAdmin. Indicates if a Super Admin is logged in.
     *
     * @return (array) The CMS menu array.
     */
    public static function getCmsModulesMenu( $superAdmin = false )
    {
        $modulesMenu = array();
        $installedPlugins = CakePlugin::loaded();

        // First load main menu.
        foreach($installedPlugins as $pluginName)
        {
            $pluginObject = self::loadPluginObject($pluginName);

            if($pluginObject && $pluginObject->showInBakeryMenu() && !$pluginObject->isCmsSubMenu())
            {
                if( $superAdmin || !$pluginObject->isRestricted() )
                {
                    $modulesMenu[] = array( 'plugin' => $pluginName,
                                            'name' => $pluginObject->getCmsModuleName(),
                                            'link' => '/bakery/' . Inflector::underscore($pluginName),
                                            'submenu' => array()
                    );
                }
            }
        }

        // Then searches for submenu
        foreach($installedPlugins as $pluginName)
        {
            $pluginObject = self::loadPluginObject($pluginName);

            if($pluginObject && $pluginObject->showInBakeryMenu() && $pluginObject->isCmsSubMenu())
            {
                if( $superAdmin || !$pluginObject->isRestricted() )
                {
                    for($i = 0; $i < count($modulesMenu); $i++)
                    {
                        if($modulesMenu[$i]['plugin'] == $pluginObject->getBakeryMenuFather())
                        {
                            $modulesMenu[$i]['submenu'][] = array(
                                                                'plugin' => $pluginName,
                                                                'name' => $pluginObject->getCmsModuleName(),
                                                                'link' => '/bakery/' . Inflector::underscore($pluginName),
                            );
                        }
                    }
                }
            }
        }

        // Returns the array
        return $modulesMenu;
    }
}


text:
package com.gs.fw.common.mithra.test.domain;

import java.sql.Timestamp;

public class NonAuditedBalance extends NonAuditedBalanceAbstract implements NonAuditedBalanceInterface
{

    public NonAuditedBalance(Timestamp businessDate)
    {
        super(businessDate);
    }
}


text:
package com.github.ltsopensource.nio;

import com.github.ltsopensource.core.json.JSON;
import com.github.ltsopensource.core.logger.Logger;
import com.github.ltsopensource.core.logger.LoggerFactory;
import com.github.ltsopensource.nio.channel.NioChannel;
import com.github.ltsopensource.nio.handler.IoFutureListener;
import com.github.ltsopensource.nio.handler.NioHandler;
import com.github.ltsopensource.nio.idle.IdleState;
import com.github.ltsopensource.remoting.ChannelHandlerListener;
import com.github.ltsopensource.remoting.Future;

/**
 * @author Robert HG (254963746@qq.com) on 2/3/16.
 */
public class EventHandler implements NioHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventHandler.class);

    @Override
    public void exceptionCaught(final NioChannel channel, Exception cause) {
        LOGGER.error("exceptionCaught - " + channel.remoteAddress(), cause);
        channel.close().addListener(new IoFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                LOGGER.info("closeChannel: close the connection to remote address[{}] result: {}", channel.remoteAddress(),
                        future.isSuccess());
            }
        });
    }

    @Override
    public void messageReceived(NioChannel channel, Object msg) throws Exception{
        LOGGER.info("messageReceived : " + channel.remoteAddress() + "  " + JSON.toJSONString(msg));
    }

    @Override
    public void channelConnected(NioChannel channel) {
        LOGGER.info("channelConnected - " + channel.remoteAddress());
    }

    @Override
    public void channelIdle(NioChannel channel, IdleState state) {

    }
}


text:
#include "i2400m.h"
#include <linux/etherdevice.h>
#include <linux/wimax/i2400m.h>
#include <linux/module.h>
#include <linux/moduleparam.h>

#define D_SUBMODULE driver
#include "debug-levels.h"

int i2400m_idle_mode_disabled;	/* 0 (idle mode enabled) by default */
module_param_named(idle_mode_disabled, i2400m_idle_mode_disabled, int, 0644);
MODULE_PARM_DESC(idle_mode_disabled,
		 "If true, the device will not enable idle mode negotiation "
		 "with the base station (when connected) to save power.");

int i2400m_rx_reorder_disabled;	/* 0 (rx reorder enabled) by default */
module_param_named(rx_reorder_disabled, i2400m_rx_reorder_disabled, int, 0644);
MODULE_PARM_DESC(rx_reorder_disabled,
		 "If true, RX reordering will be disabled.");

int i2400m_power_save_disabled;	/* 0 (power saving enabled) by default */
module_param_named(power_save_disabled, i2400m_power_save_disabled, int, 0644);
MODULE_PARM_DESC(power_save_disabled,
		 "If true, the driver will not tell the device to enter "
		 "power saving mode when it reports it is ready for it. "
		 "False by default (so the device is told to do power "
		 "saving).");

/**
 * i2400m_queue_work - schedule work on a i2400m's queue
 *
 * @i2400m: device descriptor
 *
 * @fn: function to run to execute work. It gets passed a 'struct
 *     work_struct' that is wrapped in a 'struct i2400m_work'. Once
 *     done, you have to (1) i2400m_put(i2400m_work->i2400m) and then
 *     (2) kfree(i2400m_work).
 *
 * @gfp_flags: GFP flags for memory allocation.
 *
 * @pl: pointer to a payload buffer that you want to pass to the _work
 *     function. Use this to pack (for example) a struct with extra
 *     arguments.
 *
 * @pl_size: size of the payload buffer.
 *
 * We do this quite often, so this just saves typing; allocate a
 * wrapper for a i2400m, get a ref to it, pack arguments and launch
 * the work.
 *
 * A usual workflow is:
 *
 * struct my_work_args {
 *         void *something;
 *         int whatever;
 * };
 * ...
 *
 * struct my_work_args my_args = {
 *         .something = FOO,
 *         .whaetever = BLAH
 * };
 * i2400m_queue_work(i2400m, 1, my_work_function, GFP_KERNEL,
 *                   &args, sizeof(args))
 *
 * And now the work function can unpack the arguments and call the
 * real function (or do the job itself):
 *
 * static
 * void my_work_fn((struct work_struct *ws)
 * {
 *         struct i2400m_work *iw =
 *	           container_of(ws, struct i2400m_work, ws);
 *	   struct my_work_args *my_args = (void *) iw->pl;
 *
 *	   my_work(iw->i2400m, my_args->something, my_args->whatevert);
 * }
 */
int i2400m_queue_work(struct i2400m *i2400m,
		      void (*fn)(struct work_struct *), gfp_t gfp_flags,
		      const void *pl, size_t pl_size)
{
	int result;
	struct i2400m_work *iw;

	BUG_ON(i2400m->work_queue == NULL);
	result = -ENOMEM;
	iw = kzalloc(sizeof(*iw) + pl_size, gfp_flags);
	if (iw == NULL)
		goto error_kzalloc;
	iw->i2400m = i2400m_get(i2400m);
	memcpy(iw->pl, pl, pl_size);
	INIT_WORK(&iw->ws, fn);
	result = queue_work(i2400m->work_queue, &iw->ws);
error_kzalloc:
	return result;
}
EXPORT_SYMBOL_GPL(i2400m_queue_work);

/*
 * Schedule i2400m's specific work on the system's queue.
 *
 * Used for a few cases where we really need it; otherwise, identical
 * to i2400m_queue_work().
 *
 * Returns < 0 errno code on error, 1 if ok.
 *
 * If it returns zero, something really bad happened, as it means the
 * works struct was already queued, but we have just allocated it, so
 * it should not happen.
 */
int i2400m_schedule_work(struct i2400m *i2400m,
			 void (*fn)(struct work_struct *), gfp_t gfp_flags)
{
	int result;
	struct i2400m_work *iw;

	result = -ENOMEM;
	iw = kzalloc(sizeof(*iw), gfp_flags);
	if (iw == NULL)
		goto error_kzalloc;
	iw->i2400m = i2400m_get(i2400m);
	INIT_WORK(&iw->ws, fn);
	result = schedule_work(&iw->ws);
	if (result == 0)
		result = -ENXIO;
error_kzalloc:
	return result;
}

/*
 * WiMAX stack operation: relay a message from user space
 *
 * @wimax_dev: device descriptor
 * @pipe_name: named pipe the message is for
 * @msg_buf: pointer to the message bytes
 * @msg_len: length of the buffer
 * @genl_info: passed by the generic netlink layer
 *
 * The WiMAX stack will call this function when a message was received
 * from user space.
 *
 * For the i2400m, this is an L3L4 message, as specified in
 * include/linux/wimax/i2400m.h, and thus prefixed with a 'struct
 * i2400m_l3l4_hdr'. Driver (and device) expect the messages to be
 * coded in Little Endian.
 *
 * This function just verifies that the header declaration and the
 * payload are consistent and then deals with it, either forwarding it
 * to the device or procesing it locally.
 *
 * In the i2400m, messages are basically commands that will carry an
 * ack, so we use i2400m_msg_to_dev() and then deliver the ack back to
 * user space. The rx.c code might intercept the response and use it
 * to update the driver's state, but then it will pass it on so it can
 * be relayed back to user space.
 *
 * Note that asynchronous events from the device are processed and
 * sent to user space in rx.c.
 */
static
int i2400m_op_msg_from_user(struct wimax_dev *wimax_dev,
			    const char *pipe_name,
			    const void *msg_buf, size_t msg_len,
			    const struct genl_info *genl_info)
{
	int result;
	struct i2400m *i2400m = wimax_dev_to_i2400m(wimax_dev);
	struct device *dev = i2400m_dev(i2400m);
	struct sk_buff *ack_skb;

	d_fnstart(4, dev, "(wimax_dev %p [i2400m %p] msg_buf %p "
		  "msg_len %zu genl_info %p)\n", wimax_dev, i2400m,
		  msg_buf, msg_len, genl_info);
	ack_skb = i2400m_msg_to_dev(i2400m, msg_buf, msg_len);
	result = PTR_ERR(ack_skb);
	if (IS_ERR(ack_skb))
		goto error_msg_to_dev;
	result = wimax_msg_send(&i2400m->wimax_dev, ack_skb);
error_msg_to_dev:
	d_fnend(4, dev, "(wimax_dev %p [i2400m %p] msg_buf %p msg_len %zu "
		"genl_info %p) = %d\n", wimax_dev, i2400m, msg_buf, msg_len,
		genl_info, result);
	return result;
}

/*
 * Context to wait for a reset to finalize
 */
struct i2400m_reset_ctx {
	struct completion completion;
	int result;
};

/*
 * WiMAX stack operation: reset a device
 *
 * @wimax_dev: device descriptor
 *
 * See the documentation for wimax_reset() and wimax_dev->op_reset for
 * the requirements of this function. The WiMAX stack guarantees
 * serialization on calls to this function.
 *
 * Do a warm reset on the device; if it fails, resort to a cold reset
 * and return -ENODEV. On successful warm reset, we need to block
 * until it is complete.
 *
 * The bus-driver implementation of reset takes care of falling back
 * to cold reset if warm fails.
 */
static
int i2400m_op_reset(struct wimax_dev *wimax_dev)
{
	int result;
	struct i2400m *i2400m = wimax_dev_to_i2400m(wimax_dev);
	struct device *dev = i2400m_dev(i2400m);
	struct i2400m_reset_ctx ctx = {
		.completion = COMPLETION_INITIALIZER_ONSTACK(ctx.completion),
		.result = 0,
	};

	d_fnstart(4, dev, "(wimax_dev %p)\n", wimax_dev);
	mutex_lock(&i2400m->init_mutex);
	i2400m->reset_ctx = &ctx;
	mutex_unlock(&i2400m->init_mutex);
	result = i2400m->bus_reset(i2400m, I2400M_RT_WARM);
	if (result < 0)
		goto out;
	result = wait_for_completion_timeout(&ctx.completion, 4*HZ);
	if (result == 0)
		result = -ETIMEDOUT;
	else if (result > 0)
		result = ctx.result;
	/* if result < 0, pass it on */
	mutex_lock(&i2400m->init_mutex);
	i2400m->reset_ctx = NULL;
	mutex_unlock(&i2400m->init_mutex);
out:
	d_fnend(4, dev, "(wimax_dev %p) = %d\n", wimax_dev, result);
	return result;
}

/*
 * Check the MAC address we got from boot mode is ok
 *
 * @i2400m: device descriptor
 *
 * Returns: 0 if ok, < 0 errno code on error.
 */
static
int i2400m_check_mac_addr(struct i2400m *i2400m)
{
	int result;
	struct device *dev = i2400m_dev(i2400m);
	struct sk_buff *skb;
	const struct i2400m_tlv_detailed_device_info *ddi;
	struct net_device *net_dev = i2400m->wimax_dev.net_dev;
	const unsigned char zeromac[ETH_ALEN] = { 0 };

	d_fnstart(3, dev, "(i2400m %p)\n", i2400m);
	skb = i2400m_get_device_info(i2400m);
	if (IS_ERR(skb)) {
		result = PTR_ERR(skb);
		dev_err(dev, "Cannot verify MAC address, error reading: %d\n",
			result);
		goto error;
	}
	/* Extract MAC addresss */
	ddi = (void *) skb->data;
	BUILD_BUG_ON(ETH_ALEN != sizeof(ddi->mac_address));
	d_printf(2, dev, "GET DEVICE INFO: mac addr "
		 "%02x:%02x:%02x:%02x:%02x:%02x\n",
		 ddi->mac_address[0], ddi->mac_address[1],
		 ddi->mac_address[2], ddi->mac_address[3],
		 ddi->mac_address[4], ddi->mac_address[5]);
	if (!memcmp(net_dev->perm_addr, ddi->mac_address,
		   sizeof(ddi->mac_address)))
		goto ok;
	dev_warn(dev, "warning: device reports a different MAC address "
		 "to that of boot mode's\n");
	dev_warn(dev, "device reports     %02x:%02x:%02x:%02x:%02x:%02x\n",
		 ddi->mac_address[0], ddi->mac_address[1],
		 ddi->mac_address[2], ddi->mac_address[3],
		 ddi->mac_address[4], ddi->mac_address[5]);
	dev_warn(dev, "boot mode reported %02x:%02x:%02x:%02x:%02x:%02x\n",
		 net_dev->perm_addr[0], net_dev->perm_addr[1],
		 net_dev->perm_addr[2], net_dev->perm_addr[3],
		 net_dev->perm_addr[4], net_dev->perm_addr[5]);
	if (!memcmp(zeromac, ddi->mac_address, sizeof(zeromac)))
		dev_err(dev, "device reports an invalid MAC address, "
			"not updating\n");
	else {
		dev_warn(dev, "updating MAC address\n");
		net_dev->addr_len = ETH_ALEN;
		memcpy(net_dev->perm_addr, ddi->mac_address, ETH_ALEN);
		memcpy(net_dev->dev_addr, ddi->mac_address, ETH_ALEN);
	}
ok:
	result = 0;
	kfree_skb(skb);
error:
	d_fnend(3, dev, "(i2400m %p) = %d\n", i2400m, result);
	return result;
}

/**
 * __i2400m_dev_start - Bring up driver communication with the device
 *
 * @i2400m: device descriptor
 * @flags: boot mode flags
 *
 * Returns: 0 if ok, < 0 errno code on error.
 *
 * Uploads firmware and brings up all the resources needed to be able
 * to communicate with the device.
 *
 * The workqueue has to be setup early, at least before RX handling
 * (it's only real user for now) so it can process reports as they
 * arrive. We also want to destroy it if we retry, to make sure it is
 * flushed...easier like this.
 *
 * TX needs to be setup before the bus-specific code (otherwise on
 * shutdown, the bus-tx code could try to access it).
 */
static
int __i2400m_dev_start(struct i2400m *i2400m, enum i2400m_bri flags)
{
	int result;
	struct wimax_dev *wimax_dev = &i2400m->wimax_dev;
	struct net_device *net_dev = wimax_dev->net_dev;
	struct device *dev = i2400m_dev(i2400m);
	int times = i2400m->bus_bm_retries;

	d_fnstart(3, dev, "(i2400m %p)\n", i2400m);
retry:
	result = i2400m_dev_bootstrap(i2400m, flags);
	if (result < 0) {
		dev_err(dev, "cannot bootstrap device: %d\n", result);
		goto error_bootstrap;
	}
	result = i2400m_tx_setup(i2400m);
	if (result < 0)
		goto error_tx_setup;
	result = i2400m_rx_setup(i2400m);
	if (result < 0)
		goto error_rx_setup;
	i2400m->work_queue = create_singlethread_workqueue(wimax_dev->name);
	if (i2400m->work_queue == NULL) {
		result = -ENOMEM;
		dev_err(dev, "cannot create workqueue\n");
		goto error_create_workqueue;
	}
	result = i2400m->bus_dev_start(i2400m);
	if (result < 0)
		goto error_bus_dev_start;
	result = i2400m_firmware_check(i2400m);	/* fw versions ok? */
	if (result < 0)
		goto error_fw_check;
	/* At this point is ok to send commands to the device */
	result = i2400m_check_mac_addr(i2400m);
	if (result < 0)
		goto error_check_mac_addr;
	i2400m->ready = 1;
	wimax_state_change(wimax_dev, WIMAX_ST_UNINITIALIZED);
	result = i2400m_dev_initialize(i2400m);
	if (result < 0)
		goto error_dev_initialize;
	/* At this point, reports will come for the device and set it
	 * to the right state if it is different than UNINITIALIZED */
	d_fnend(3, dev, "(net_dev %p [i2400m %p]) = %d\n",
		net_dev, i2400m, result);
	return result;

error_dev_initialize:
error_check_mac_addr:
error_fw_check:
	i2400m->bus_dev_stop(i2400m);
error_bus_dev_start:
	destroy_workqueue(i2400m->work_queue);
error_create_workqueue:
	i2400m_rx_release(i2400m);
error_rx_setup:
	i2400m_tx_release(i2400m);
error_tx_setup:
error_bootstrap:
	if (result == -EL3RST && times-- > 0) {
		flags = I2400M_BRI_SOFT|I2400M_BRI_MAC_REINIT;
		goto retry;
	}
	d_fnend(3, dev, "(net_dev %p [i2400m %p]) = %d\n",
		net_dev, i2400m, result);
	return result;
}

static
int i2400m_dev_start(struct i2400m *i2400m, enum i2400m_bri bm_flags)
{
	int result;
	mutex_lock(&i2400m->init_mutex);	/* Well, start the device */
	result = __i2400m_dev_start(i2400m, bm_flags);
	if (result >= 0)
		i2400m->updown = 1;
	mutex_unlock(&i2400m->init_mutex);
	return result;
}

/**
 * i2400m_dev_stop - Tear down driver communication with the device
 *
 * @i2400m: device descriptor
 *
 * Returns: 0 if ok, < 0 errno code on error.
 *
 * Releases all the resources allocated to communicate with the
 * device. Note we cannot destroy the workqueue earlier as until RX is
 * fully destroyed, it could still try to schedule jobs.
 */
static
void __i2400m_dev_stop(struct i2400m *i2400m)
{
	struct wimax_dev *wimax_dev = &i2400m->wimax_dev;
	struct device *dev = i2400m_dev(i2400m);

	d_fnstart(3, dev, "(i2400m %p)\n", i2400m);
	wimax_state_change(wimax_dev, __WIMAX_ST_QUIESCING);
	i2400m_dev_shutdown(i2400m);
	i2400m->ready = 0;
	i2400m->bus_dev_stop(i2400m);
	destroy_workqueue(i2400m->work_queue);
	i2400m_rx_release(i2400m);
	i2400m_tx_release(i2400m);
	wimax_state_change(wimax_dev, WIMAX_ST_DOWN);
	d_fnend(3, dev, "(i2400m %p) = 0\n", i2400m);
}

/*
 * Watch out -- we only need to stop if there is a need for it. The
 * device could have reset itself and failed to come up again (see
 * _i2400m_dev_reset_handle()).
 */
static
void i2400m_dev_stop(struct i2400m *i2400m)
{
	mutex_lock(&i2400m->init_mutex);
	if (i2400m->updown) {
		__i2400m_dev_stop(i2400m);
		i2400m->updown = 0;
	}
	mutex_unlock(&i2400m->init_mutex);
}

/*
 * The device has rebooted; fix up the device and the driver
 *
 * Tear down the driver communication with the device, reload the
 * firmware and reinitialize the communication with the device.
 *
 * If someone calls a reset when the device's firmware is down, in
 * theory we won't see it because we are not listening. However, just
 * in case, leave the code to handle it.
 *
 * If there is a reset context, use it; this means someone is waiting
 * for us to tell him when the reset operation is complete and the
 * device is ready to rock again.
 *
 * NOTE: if we are in the process of bringing up or down the
 *       communication with the device [running i2400m_dev_start() or
 *       _stop()], don't do anything, let it fail and handle it.
 *
 * This function is ran always in a thread context
 */
static
void __i2400m_dev_reset_handle(struct work_struct *ws)
{
	int result;
	struct i2400m_work *iw = container_of(ws, struct i2400m_work, ws);
	struct i2400m *i2400m = iw->i2400m;
	struct device *dev = i2400m_dev(i2400m);
	enum wimax_st wimax_state;
	struct i2400m_reset_ctx *ctx = i2400m->reset_ctx;

	d_fnstart(3, dev, "(ws %p i2400m %p)\n", ws, i2400m);
	result = 0;
	if (mutex_trylock(&i2400m->init_mutex) == 0) {
		/* We are still in i2400m_dev_start() [let it fail] or
		 * i2400m_dev_stop() [we are shutting down anyway, so
		 * ignore it] or we are resetting somewhere else. */
		dev_err(dev, "device rebooted\n");
		i2400m_msg_to_dev_cancel_wait(i2400m, -EL3RST);
		complete(&i2400m->msg_completion);
		goto out;
	}
	wimax_state = wimax_state_get(&i2400m->wimax_dev);
	if (wimax_state < WIMAX_ST_UNINITIALIZED) {
		dev_info(dev, "device rebooted: it is down, ignoring\n");
		goto out_unlock;	/* ifconfig up/down wasn't called */
	}
	dev_err(dev, "device rebooted: reinitializing driver\n");
	__i2400m_dev_stop(i2400m);
	i2400m->updown = 0;
	result = __i2400m_dev_start(i2400m,
				    I2400M_BRI_SOFT | I2400M_BRI_MAC_REINIT);
	if (result < 0) {
		dev_err(dev, "device reboot: cannot start the device: %d\n",
			result);
		result = i2400m->bus_reset(i2400m, I2400M_RT_BUS);
		if (result >= 0)
			result = -ENODEV;
	} else
		i2400m->updown = 1;
out_unlock:
	if (i2400m->reset_ctx) {
		ctx->result = result;
		complete(&ctx->completion);
	}
	mutex_unlock(&i2400m->init_mutex);
out:
	i2400m_put(i2400m);
	kfree(iw);
	d_fnend(3, dev, "(ws %p i2400m %p) = void\n", ws, i2400m);
	return;
}

/**
 * i2400m_dev_reset_handle - Handle a device's reset in a thread context
 *
 * Schedule a device reset handling out on a thread context, so it
 * is safe to call from atomic context. We can't use the i2400m's
 * queue as we are going to destroy it and reinitialize it as part of
 * the driver bringup/bringup process.
 *
 * See __i2400m_dev_reset_handle() for details; that takes care of
 * reinitializing the driver to handle the reset, calling into the
 * bus-specific functions ops as needed.
 */
int i2400m_dev_reset_handle(struct i2400m *i2400m)
{
	i2400m->boot_mode = 1;
	wmb();		/* Make sure i2400m_msg_to_dev() sees boot_mode */
	return i2400m_schedule_work(i2400m, __i2400m_dev_reset_handle,
				    GFP_ATOMIC);
}
EXPORT_SYMBOL_GPL(i2400m_dev_reset_handle);

/**
 * i2400m_setup - bus-generic setup function for the i2400m device
 *
 * @i2400m: device descriptor (bus-specific parts have been initialized)
 *
 * Returns: 0 if ok, < 0 errno code on error.
 *
 * Initializes the bus-generic parts of the i2400m driver; the
 * bus-specific parts have been initialized, function pointers filled
 * out by the bus-specific probe function.
 *
 * As well, this registers the WiMAX and net device nodes. Once this
 * function returns, the device is operative and has to be ready to
 * receive and send network traffic and WiMAX control operations.
 */
int i2400m_setup(struct i2400m *i2400m, enum i2400m_bri bm_flags)
{
	int result = -ENODEV;
	struct device *dev = i2400m_dev(i2400m);
	struct wimax_dev *wimax_dev = &i2400m->wimax_dev;
	struct net_device *net_dev = i2400m->wimax_dev.net_dev;

	d_fnstart(3, dev, "(i2400m %p)\n", i2400m);

	snprintf(wimax_dev->name, sizeof(wimax_dev->name),
		 "i2400m-%s:%s", dev->bus->name, dev_name(dev));

	i2400m->bm_cmd_buf = kzalloc(I2400M_BM_CMD_BUF_SIZE, GFP_KERNEL);
	if (i2400m->bm_cmd_buf == NULL) {
		dev_err(dev, "cannot allocate USB command buffer\n");
		goto error_bm_cmd_kzalloc;
	}
	i2400m->bm_ack_buf = kzalloc(I2400M_BM_ACK_BUF_SIZE, GFP_KERNEL);
	if (i2400m->bm_ack_buf == NULL) {
		dev_err(dev, "cannot allocate USB ack buffer\n");
		goto error_bm_ack_buf_kzalloc;
	}
	result = i2400m_bootrom_init(i2400m, bm_flags);
	if (result < 0) {
		dev_err(dev, "read mac addr: bootrom init "
			"failed: %d\n", result);
		goto error_bootrom_init;
	}
	result = i2400m_read_mac_addr(i2400m);
	if (result < 0)
		goto error_read_mac_addr;
	random_ether_addr(i2400m->src_mac_addr);

	result = register_netdev(net_dev);	/* Okey dokey, bring it up */
	if (result < 0) {
		dev_err(dev, "cannot register i2400m network device: %d\n",
			result);
		goto error_register_netdev;
	}
	netif_carrier_off(net_dev);

	result = i2400m_dev_start(i2400m, bm_flags);
	if (result < 0)
		goto error_dev_start;

	i2400m->wimax_dev.op_msg_from_user = i2400m_op_msg_from_user;
	i2400m->wimax_dev.op_rfkill_sw_toggle = i2400m_op_rfkill_sw_toggle;
	i2400m->wimax_dev.op_reset = i2400m_op_reset;
	result = wimax_dev_add(&i2400m->wimax_dev, net_dev);
	if (result < 0)
		goto error_wimax_dev_add;
	/* User space needs to do some init stuff */
	wimax_state_change(wimax_dev, WIMAX_ST_UNINITIALIZED);

	/* Now setup all that requires a registered net and wimax device. */
	result = sysfs_create_group(&net_dev->dev.kobj, &i2400m_dev_attr_group);
	if (result < 0) {
		dev_err(dev, "cannot setup i2400m's sysfs: %d\n", result);
		goto error_sysfs_setup;
	}
	result = i2400m_debugfs_add(i2400m);
	if (result < 0) {
		dev_err(dev, "cannot setup i2400m's debugfs: %d\n", result);
		goto error_debugfs_setup;
	}
	d_fnend(3, dev, "(i2400m %p) = %d\n", i2400m, result);
	return result;

error_debugfs_setup:
	sysfs_remove_group(&i2400m->wimax_dev.net_dev->dev.kobj,
			   &i2400m_dev_attr_group);
error_sysfs_setup:
	wimax_dev_rm(&i2400m->wimax_dev);
error_wimax_dev_add:
	i2400m_dev_stop(i2400m);
error_dev_start:
	unregister_netdev(net_dev);
error_register_netdev:
error_read_mac_addr:
error_bootrom_init:
	kfree(i2400m->bm_ack_buf);
error_bm_ack_buf_kzalloc:
	kfree(i2400m->bm_cmd_buf);
error_bm_cmd_kzalloc:
	d_fnend(3, dev, "(i2400m %p) = %d\n", i2400m, result);
	return result;
}
EXPORT_SYMBOL_GPL(i2400m_setup);

/**
 * i2400m_release - release the bus-generic driver resources
 *
 * Sends a disconnect message and undoes any setup done by i2400m_setup()
 */
void i2400m_release(struct i2400m *i2400m)
{
	struct device *dev = i2400m_dev(i2400m);

	d_fnstart(3, dev, "(i2400m %p)\n", i2400m);
	netif_stop_queue(i2400m->wimax_dev.net_dev);

	i2400m_debugfs_rm(i2400m);
	sysfs_remove_group(&i2400m->wimax_dev.net_dev->dev.kobj,
			   &i2400m_dev_attr_group);
	wimax_dev_rm(&i2400m->wimax_dev);
	i2400m_dev_stop(i2400m);
	unregister_netdev(i2400m->wimax_dev.net_dev);
	kfree(i2400m->bm_ack_buf);
	kfree(i2400m->bm_cmd_buf);
	d_fnend(3, dev, "(i2400m %p) = void\n", i2400m);
}
EXPORT_SYMBOL_GPL(i2400m_release);

/*
 * Debug levels control; see debug.h
 */
struct d_level D_LEVEL[] = {
	D_SUBMODULE_DEFINE(control),
	D_SUBMODULE_DEFINE(driver),
	D_SUBMODULE_DEFINE(debugfs),
	D_SUBMODULE_DEFINE(fw),
	D_SUBMODULE_DEFINE(netdev),
	D_SUBMODULE_DEFINE(rfkill),
	D_SUBMODULE_DEFINE(rx),
	D_SUBMODULE_DEFINE(tx),
};
size_t D_LEVEL_SIZE = ARRAY_SIZE(D_LEVEL);

static
int __init i2400m_driver_init(void)
{
	return 0;
}
module_init(i2400m_driver_init);

static
void __exit i2400m_driver_exit(void)
{
	/* for scheds i2400m_dev_reset_handle() */
	flush_scheduled_work();
	return;
}
module_exit(i2400m_driver_exit);

MODULE_AUTHOR("Intel Corporation <linux-wimax@intel.com>");
MODULE_DESCRIPTION("Intel 2400M WiMAX networking bus-generic driver");
MODULE_LICENSE("GPL");


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@drawable/abc_textfield_search_activated_mtrl_alpha"/>
    <item android:state_enabled="true" android:state_activated="true" android:drawable="@drawable/abc_textfield_search_activated_mtrl_alpha"/>
    <item android:state_enabled="true" android:drawable="@drawable/abc_textfield_search_default_mtrl_alpha"/>
    <item android:drawable="@drawable/abc_textfield_search_default_mtrl_alpha"/>
</selector>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package caillou.company.clonemanager.background.event;

/**
 *
 * @author pierre
 */
public class FileFullyHashedEvent extends FileTreatedEvent {

}


text:
This page explains how to play with GoBGP's MRT feature.

## Prerequisites

Assume you finished [Getting Started](https://github.com/osrg/gobgp/blob/master/docs/sources/getting-started.md).

## Contents
- [Configuration](#section0)
- [Dump MRT table v2 records](#section1)
    - [Dump neighbor's local table](#section1.1)
- [Inject routes from MRT table v2 records](#section2)

##  Configuration
You don't need any special configuration for MRT feature.
This page assume the configuration below.

```toml
[Global]
    [Global.GlobalConfig]
        As = 64512
        RouterId = "192.168.255.1"
[Neighbors]
    [[Neighbors.NeighborList]]
        [Neighbors.NeighborList.NeighborConfig]
        NeighborAddress = "10.0.0.1"
        PeerAs = 65001
```

## Dump MRT Table v2 Records

Instant dump can be done like below

```bash
$ gobgp mrt dump rib global
mrt dump: rib_ipv4_20150809_233952
$ ls -la rib*
rib_ipv4_20150809_233952
```

To dump ipv6 routes, type

```bash
$ gobgp mrt dump rib global -a ipv6
mrt dump: rib_ipv6_20150809_234012
```

If you want to dump periodically, specify dump interval (unit is second)
```bash
# dump hourly. this will block
$ gobgp mrt dump rib global $((60*60))
mrt dump: rib_ipv4_20150809_234438
...
```

You can change output directory by  `-o <outdir>` and filename format by `-f <format>`

```bash
# change the output directory and the filename of dumps
$ gobgp mrt dump rib global -o /dump/here -f mydailydump_{{.Y}}_{{.M}}_{{.D}} $((60*60*24))
mrt dump: /dump/here/rib_2015_08_09
...
```

Filename format is same as golang [text/template](http://golang.org/pkg/text/template/) package template.
Below is the supported variables you can use.

| value                 | meaning                                       |
|:---------------------:|:---------------------------------------------:|
| {{.Y}}                | Year (e.g. 2015)                              |
| {{.M}}                | Month (e.g. 08)                               |
| {{.D}}                | Day (e.g. 09)                                 |
| {{.H}}                | Hour (e.g. 23)                                |
| {{.Min}}              | Minute (e.g. 47)                              |
| {{.Sec}}              | Second (e.g. 10)                              |
| {{.Af}}               | Address Family ( `ipv4` \| `ipv6` \| `l2vpn`) |
| {{.NeighborAddress }} | Neighbor Address (e.g. 10.0.0.1)              |
| {{.Resource}}         | Resource ( `global` \| `local` )              |

###  Dump neighbor's local table
GoBGP supports multiple RIB for route server [feature](https://github.com/osrg/gobgp/blob/master/docs/sources/route-server.md).
GoBGP can also dump these tables which is local to neighbors

```bash
$ gobgp mrt dump rib neighbor 10.0.0.1 -o /dump/local $((60*60))
rpc error: code = 2 desc = "no local rib for 10.0.0.1"
```

Oops! Before trying this feature, you must enable route server feature.
Configuration is something like below.

```
$ cat gobgpd.conf
[Global]
    [Global.GlobalConfig]
        As = 64512
        RouterId = "192.168.255.1"
[Neighbors]
    [[Neighbors.NeighborList]]
        [Neighbors.NeighborList.NeighborConfig]
            NeighborAddress = "10.0.0.1"
            PeerAs = 65001
        [Neighbors.NeighborList.RouteServer]
            [Neighbors.NeighborList.RouteServer.RouteServerConfig]
            RouteServerClient = true
```

OK, let's try again.

```bash
$ gobgp mrt dump rib neighbor 10.0.0.1 -o /dump/local
mrt dump: /dump/local/rib_10.0.0.1_20150809_234543
```

##  Inject routes from MRT table v2 records
Route injection can be done by
```bash
$ gobgp mrt inject global <dumpfile> [<number of prefix to inject>]
```


text:
var should = require('should'),
    security = require('../../../../server/lib/security');

describe('Lib: Security - String', function () {
    describe('Safe String', function () {
        var options = {};

        it('should remove beginning and ending whitespace', function () {
            var result = security.string.safe(' stringwithspace ', options);
            result.should.equal('stringwithspace');
        });

        it('can handle null strings', function () {
            var result = security.string.safe(null);
            result.should.equal('');
        });

        it('should remove non ascii characters', function () {
            var result = security.string.safe('howtowin✓', options);
            result.should.equal('howtowin');
        });

        it('should replace spaces with dashes', function () {
            var result = security.string.safe('how to win', options);
            result.should.equal('how-to-win');
        });

        it('should replace most special characters with dashes', function () {
            var result = security.string.safe('a:b/c?d#e[f]g!h$i&j(k)l*m+n,o;{p}=q\\r%s<t>u|v^w~x£y"z@1.2`3', options);
            result.should.equal('a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-1-2-3');
        });

        it('should replace all of the html4 compat symbols in ascii except hyphen and underscore', function () {
            // note: This is missing the soft-hyphen char that isn't much-liked by linters/browsers/etc,
            // it passed the test before it was removed
            var result = security.string.safe('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿');
            result.should.equal('_-c-y-ss-c-a-r-deg-23up-1o-1-41-23-4');
        });

        it('should replace all of the foreign chars in ascii', function () {
            var result = security.string.safe('ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ');
            result.should.equal('aaaaaaaeceeeeiiiidnoooooxouuuuuthssaaaaaaaeceeeeiiiidnooooo-ouuuuythy');
        });

        it('should remove special characters at the beginning of a string', function () {
            var result = security.string.safe('.Not special', options);
            result.should.equal('not-special');
        });

        it('should remove apostrophes ', function () {
            var result = security.string.safe('how we shouldn\'t be', options);
            result.should.equal('how-we-shouldnt-be');
        });

        it('should convert to lowercase', function () {
            var result = security.string.safe('This has Upper Case', options);
            result.should.equal('this-has-upper-case');
        });

        it('should convert multiple dashes into a single dash', function () {
            var result = security.string.safe('This :) means everything', options);
            result.should.equal('this-means-everything');
        });

        it('should remove trailing dashes from the result', function () {
            var result = security.string.safe('This.', options);
            result.should.equal('this');
        });

        it('should handle pound signs', function () {
            var result = security.string.safe('WHOOPS! I spent all my £ again!', options);
            result.should.equal('whoops-i-spent-all-my-again');
        });

        it('should properly handle unicode punctuation conversion', function () {
            var result = security.string.safe('に間違いがないか、再度確認してください。再読み込みしてください。', options);
            result.should.equal('nijian-wei-iganaika-zai-du-que-ren-sitekudasai-zai-du-miip-misitekudasai');
        });

        it('should not lose or convert dashes if options are passed with truthy importing flag', function () {
            var result,
                options = {importing: true};
            result = security.string.safe('-slug-with-starting-ending-and---multiple-dashes-', options);
            result.should.equal('-slug-with-starting-ending-and---multiple-dashes-');
        });

        it('should still remove/convert invalid characters when passed options with truthy importing flag', function () {
            var result,
                options = {importing: true};
            result = security.string.safe('-slug-&with-✓-invalid-characters-に\'', options);
            result.should.equal('-slug--with--invalid-characters-ni');
        });
    });
});


text:
export const testAction = (action, payload, state, expectedMutations, done) => {
  let count = 0

  // mock commit
  const commit = (type, payload) => {
    const mutation = expectedMutations[count]

    try {
      expect(mutation.type).to.equal(type)
      if (payload) {
        expect(mutation.payload).to.deep.equal(payload)
      }
    } catch (error) {
      done(error)
    }

    count++
    if (count >= expectedMutations.length) {
      done()
    }
  }

  // call the action with mocked store and arguments
  action({ commit, state }, payload)

  // check if no mutations should have been dispatched
  if (expectedMutations.length === 0) {
    expect(count).to.equal(0)
    done()
  }
}


text:
//
//  PearlCCDebugLayer.h
//  Pearl
//
//  Created by Maarten Billemont on 06/07/09.
//  Copyright 2009 lhunath (Maarten Billemont). All rights reserved.
//

#import "cocos2d.h"

@interface PearlCCDebugLayer : CCLayer {

}

+ (instancetype)get;

@end