text:
A replacement for Logger that offers more robust handling of log rotation.

The built-in logger supports log rotation on a daily, weekly or monthly basis,
but not with more fine-grained control. Birling will allow rotation by hour,
by day, or by an arbitrary amount of time expressed in seconds.

Additionally, Birling will automatically remove old log files. These can be
pruned off by age, by retaining a minimum number of them, or a combination of
both.

## Example

The interface is very similar to the [built in logger](http://rubygems.org/gems/logger)
facility that ships with Ruby:

```ruby
logger = Birling::Logger.new('test.log')

logger.info("Application starting up.")
logger.debug("application_init()")
```

A short-hand method is available:

```ruby
logger = Birling.open('test.log')
```

Log rotation parameters are quite flexible. For example, to retain a maximum
of ten hourly logs:

```ruby
logger = Birling.open(
  'test.log',
  period: :hourly,
  retain_count: 10
)
```

Alternatively the retention period can be expressed in terms of time where
log files that could have been created by this logger which are older than
that period will be removed:

```ruby
logger = Birling.open(
  'test.log',
  period: :hourly,
  retain_period: 10 * 3600
)
```

The format of the resulting log-file can be adjusted by supplying a formatter.
Several arguments passed to the formatter's `call` method, so a `lambda`, a
`module` or an object instance could be used for this purpose.

Example:

```ruby
logger = Birling.open(
  'test.log',
  formatter: -> (severity, time, program, message) { "#{time}> #{message}\n" }
)
```

Note that the formatter is responsible for introducing any line-feeds into
the resulting output stream. This gives the formatter complete control over
what is written to the log.

## Limitations

The log rotation feature, for reasons that should be obvious, will not work
on loggers that are created with an existing file-handle. For example, when
using `STDOUT` the logger will not rotate.

## Copyright

Copyright (c) 2011-2019 Scott Tadman, PostageApp Ltd.


text:
package weixin.util.weixin;

import org.apache.commons.codec.digest.DigestUtils;
import org.jetbrains.annotations.Nullable;
import weixin.util.weixin.platform.wx.WeixinMessage;
import weixin.util.weixin.platform.wx.WeixinUtils;
import weixin.util.weixin.platform.wx.rewrite.Conf;
import weixin.util.weixin.platform.wx.rewrite.RewrittenUrl;
import weixin.util.weixin.platform.wx.rewrite.UrlRewriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * weixin robot servlet
 *
 * @author linux_china
 */
public class WexinRobotServlet extends HttpServlet {
    /**
     * token
     */
    private String token;
    /**
     * pass code,用于调试,不执行签名检查
     */
    private String passCode;
    /**
     * url rewriter
     */
    private UrlRewriter urlRewriter;

    /**
     * init config
     *
     * @param config servlet config
     * @throws javax.servlet.ServletException servlet exception
     */
    public void init(ServletConfig config) throws ServletException {
        this.token = config.getInitParameter("token");
        this.passCode = config.getInitParameter("passCode");
        String confFile = config.getInitParameter("confFile");
        try {
            Conf conf = new Conf(config.getServletContext(), confFile);
            this.urlRewriter = new UrlRewriter(conf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 微信公共平台认证接口
     *
     * @param request  http servlet request
     * @param response http servlet response
     * @throws javax.servlet.ServletException servlet exception
     * @throws java.io.IOException      io exception
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String echostr = request.getParameter("echostr");
        response.setContentType("text/plain; charset=UTF-8");
        PrintWriter out = response.getWriter();
//        if (checkSignature(request.getQueryString(), getToken())) {
//            out.print(echostr);
//        } else {
//            out.print("false");
//        }
        out.print(echostr);
        out.flush();
    }

    /**
     * 微信消息接收接口
     *
     * @param request  http servlet request
     * @param response http servlet response
     * @throws javax.servlet.ServletException servlet exception
     * @throws java.io.IOException      io exception
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //validate signature
        boolean valid = checkSignature(request.getQueryString(), getToken());
        if (valid) {
            try {
                WeixinMessage wxMsg = WeixinUtils.parseXML(request.getInputStream());
                System.out.println("");
                doMessage(wxMsg, request, response);
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } finally {
                WeixinMessageContext.clear();
            }
        } else {
            send400(response);
        }
    }

    /**
     * 处理 weixin message
     *
     * @param wxMsg    weixin message
     * @param request  http servlet request
     * @param response http servlet response
     * @throws Exception exception
     */
    public void doMessage(WeixinMessage wxMsg, HttpServletRequest request, HttpServletResponse response) throws Exception {
        WeixinMessageContext.setWeixinMessage(wxMsg);
        WeixinMessageContext.setQueryString(request.getQueryString());
        response.setContentType("text/xml; charset=UTF-8");
        request.setAttribute("wxMsg", wxMsg);
        RewrittenUrl rewrittenUrl = urlRewriter.processRequest(wxMsg, request, response);
        if (rewrittenUrl != null) {
            rewrittenUrl.doRewrite(request, response);
        }
    }

    /**
     * 验证签名
     *
     * @param queryString query string
     * @return valid mark
     */
    public boolean checkSignature(String queryString, @Nullable String token) {
        if (token == null || token.isEmpty() || queryString == null) return false;
        //pass code check
        if (passCode != null && queryString.contains(passCode)) return true;
        Map<String, String> params = new HashMap<String, String>();
        for (String pair : queryString.split("&")) {
            String[] temp = pair.split("=", 2);
            params.put(temp[0], temp[1]);
        }
        List<String> elements = new ArrayList<String>();
        elements.add(params.get("timestamp"));
        elements.add(params.get("nonce"));
        elements.add(token);
        Collections.sort(elements);
        StringBuilder seed = new StringBuilder();
        for (String link : elements) {
            seed.append(link);
        }
        return DigestUtils.sha1Hex(seed.toString()).equals(params.get("signature"));
    }

    /**
     * get weixin call back token
     *
     * @return token
     */
    @Nullable
    protected String getToken() {
        return this.token;
    }

    /**
     * get query   from query string
     *
     * @param request http servlet request
     * @return query object
     */
    protected Map<String, String> getQuery(HttpServletRequest request) {
        String queryString = request.getQueryString();
        if (queryString == null || !queryString.contains("=")) {
            return Collections.emptyMap();
        }
        Map<String, String> query = new HashMap<String, String>();
        for (String pair : queryString.split("&")) {
            String[] parts = pair.split("=", 2);
            if (parts.length == 2 && !parts[1].isEmpty()) {
                query.put(parts[0], parts[1]);
            }
        }
        return query;
    }

    /**
     * send 400(bad request) response
     *
     * @param response response
     */
    public void send400(HttpServletResponse response) {
        try {
            response.sendError(400);
        } catch (Exception ignore) {

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.huawei.esdk.demo.gen;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="cameraCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "cameraCode"
})
@XmlRootElement(name = "stopPlatformRecord")
public class StopPlatformRecord {

    @XmlElement(required = true)
    protected String cameraCode;

    /**
     * Gets the value of the cameraCode property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCameraCode() {
        return cameraCode;
    }

    /**
     * Sets the value of the cameraCode property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCameraCode(String value) {
        this.cameraCode = value;
    }

}


text:
[![Version](https://img.shields.io/cocoapods/v/Gallery.svg?style=flat)](http://cocoadocs.org/docsets/Gallery)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![License](https://img.shields.io/cocoapods/l/Gallery.svg?style=flat)](http://cocoadocs.org/docsets/Gallery)
[![Platform](https://img.shields.io/cocoapods/p/Gallery.svg?style=flat)](http://cocoadocs.org/docsets/Gallery)
![Swift](https://img.shields.io/badge/%20in-swift%204.0-orange.svg)

## Description

We all love image pickers, don't we? You may already know of [ImagePicker](https://github.com/hyperoslo/ImagePicker), the all in one solution for capturing pictures and selecting images. Well, it has a sibling too, called `Gallery`. Based on the same engine that powers ImagePicker, Gallery has a clearer flow based on albums and focuses on the use case of selecting video. If this suits your need, give it a try 😉

`Gallery` has 3 tabs with easy navigation through swipe gesture

- Images: select albums and images. Handle selection with hightlighted numbers so your users don't forget the order
- Camera: your photographer skill goes here
- Videos: display all videos and select. For now the use case is to select one video at a time

And, it has zero dependencies 😎

## Usage

### Presenting

`GalleryController` is the main entry point, just instantiate and give it the delegate

```swift
let gallery = GalleryController()
gallery.delegate = self
present(gallery, animated: true, completion: nil)
```

The content controller is not loaded until the users navigate to, which offers a much faster experience.

### Delegate

The `GalleryControllerDelegate` requires you to implement some delegate methods in order to interact with the picker

```swift
func galleryController(_ controller: GalleryController, didSelectImages images: [UIImage])
func galleryController(_ controller: GalleryController, didSelectVideo video: Video)
func galleryController(_ controller: GalleryController, requestLightbox images: [UIImage])
func galleryControllerDidCancel(_ controller: GalleryController)
```

The lightbox delegate method is your chance to display selected images. If you're looking for a nice solution, here is the [Lightbox](https://github.com/hyperoslo/Lightbox) that we use and love

### Permission

`Gallery` handles permissions for you. It checks and askes for photo and camera usage permissions at first launch. As of iOS 10, we need to explicitly declare usage descriptions in plist files

```xml
<key>NSCameraUsageDescription</key>
<string>This app requires access to camera</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to photo library</string>
```

### Configuration

There are lots of customization points in `Config` structs. For example

```swift
Config.Permission.image = UIImage(named: ImageList.Gallery.cameraIcon)
Config.Font.Text.bold = UIFont(name: FontList.OpenSans.bold, size: 14)!
Config.Camera.recordLocation = true
```

### Video Editor

`Galery` cares more about video with its editing functionalities. We have `VideoEditor` and `AdvancedVideoEditor` to trim, resize, scale and define quality of the selected video

```swift
func galleryController(_ controller: GalleryController, didSelectVideo video: Video) {
  controller.dismiss(animated: true, completion: nil)

  let editor = VideoEditor()
  editor.edit(video: video) { (editedVideo: Video?, tempPath: URL?) in
    DispatchQueue.main.async {
      if let tempPath = tempPath {
        let controller = AVPlayerViewController()
        controller.player = AVPlayer(url: tempPath)

        self.present(controller, animated: true, completion: nil)
      }
    }
  }
}
```

With the `Video` object, you can `fetchPlayerItem`, `fetchAVAsset` and `fetchThumbnail` as well

And, of course, you have the ability to customize it

```swift
Config.VideoEditor.maximumDuration = 30
Config.VideoEditor.savesEditedVideoToLibrary = true
```

## Installation

**Gallery** is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'Gallery'
```

**Gallery** is also available through [Carthage](https://github.com/Carthage/Carthage).
To install just write into your Cartfile:

```ruby
github "hyperoslo/Gallery"
```

**Gallery** can also be installed manually. Just download and drop `Sources` folders in your project.

## Author

Hyper Interaktiv AS, ios@hyper.no

## Contributing

We would love you to contribute to **Gallery**, check the [CONTRIBUTING](https://github.com/hyperoslo/Gallery/blob/master/CONTRIBUTING.md) file for more info.

## License

**Gallery** is available under the MIT license. See the [LICENSE](https://github.com/hyperoslo/Gallery/blob/master/LICENSE.md) file for more info.


text:
module.exports = function($, window, errorHandler) {
    var Multigraph = require('../../core/multigraph.js')($),
        Point = require('../../math/point.js');

    if (typeof(Multigraph.registerTouchEvents)==="function") { return Multigraph; }

    Multigraph.respondsTo("registerTouchEvents", function (target) {
        var touchStarted           = false,
            dragStarted            = false,
            pinchZoomStarted       = false,
            pinchZoomDetermined    = false,
            pinchZoomInitialDeltas = {},
            pinchZoomDeterminedTimeout,
            previoustoucha, previoustouchb,
            base,
            multigraph = this,
            $target = $(target);

        var touchLocationToGraphCoords = function (touch) {
            return new Point((touch.pageX - $target.offset().left) - multigraph.graphs().at(0).x0(),
                             $target.height() - (touch.pageY - $target.offset().top) - multigraph.graphs().at(0).y0());
        };

        var handleTouchStart = function (jqueryEvent) {
            var e = jqueryEvent.originalEvent;
            e.preventDefault();

            if (e.touches.length === 1) {
                base = touchLocationToGraphCoords(e.touches[0]);
            }
            previoustoucha = touchLocationToGraphCoords(e.touches[0]);

            // one finger drag
            if (e.touches.length === 1) {
                dragStarted = true;
            } else {
                dragStarted = false;
            }

            // pinch zoom
            if (e.touches.length === 2) {
                pinchZoomStarted = true;
                pinchZoomDetermined = false;
                previoustouchb = touchLocationToGraphCoords(e.touches[1]);
            } else {
                pinchZoomStarted = false;
                pinchZoomDetermined = false;
            }

            touchStarted = false;
            multigraph.graphs().at(0).doDragDone();
        };

        var handleTouchMove = function (jqueryEvent) {
            var e = jqueryEvent.originalEvent;
            e.preventDefault();

            // one finger drag
            if (e.touches.length === 1 && dragStarted === true) {
                handleDrag(e);
            }
            // pinch zoom
            if (e.touches.length === 2 && pinchZoomStarted === true) {
                handlePinchZoom(e);
            }
        };

        var handleTouchEnd = function (jqueryEvent) {
            var e = jqueryEvent.originalEvent;
            e.preventDefault();

            // one finger drag
            if (e.touches.length === 1) {
                dragStarted = true;
            } else {
                dragStarted = false;
            }

            // pinch zoom
            if (e.touches.length === 2) {
                pinchZoomStarted = true;
                pinchZoomDetermined = false;
            } else {
                pinchZoomStarted = false;
                pinchZoomDetermined = false;
            }

            touchStarted = false;
            multigraph.graphs().at(0).doDragDone();
        };

        var handleTouchLeave = function (jqueryEvent) {
            jqueryEvent.originalEvent.preventDefault();

            dragStarted = false;
            pinchZoomStarted = false;
            pinchZoomDetermined = false;
            touchStarted = false;

            multigraph.graphs().at(0).doDragDone();
        };

        var handleDrag = function (e) {
            var touchLoc = touchLocationToGraphCoords(e.touches[0]),
                dx = touchLoc.x() - previoustoucha.x(),
                dy = touchLoc.y() - previoustoucha.y();
            if (multigraph.graphs().size() > 0) {
                if (!touchStarted) {
                    multigraph.graphs().at(0).doDragReset();
                }
                multigraph.graphs().at(0).doDrag(multigraph, base.x(), base.y(), dx, dy, false);
            }
            touchStarted = true;
            previoustoucha = touchLoc;
        };

        var handlePinchZoom = function (e) {
            var a = touchLocationToGraphCoords(e.touches[0]),
                b = touchLocationToGraphCoords(e.touches[1]),
                basex = (a.x() + b.x()) / 2,
                basey = (a.y() + b.y()) / 2,
                dx = calculateAbsoluteDistance(a.x(), b.x()) - calculateAbsoluteDistance(previoustoucha.x(), previoustouchb.x()),
                dy = calculateAbsoluteDistance(a.y(), b.y()) - calculateAbsoluteDistance(previoustoucha.y(), previoustouchb.y());

            if (multigraph.graphs().size() > 0) {
                if (!touchStarted) {
                    multigraph.graphs().at(0).doDragReset();
                }
                if (pinchZoomDetermined === true) {
                    multigraph.graphs().at(0).doDrag(multigraph, basex, basey, dx, dy, true);
                }
            }
            touchStarted = true;

            // two finger scroll
            var cx = ((a.x() - previoustoucha.x()) + (b.x() - previoustouchb.x())) / 2,
                cy = ((a.y() - previoustoucha.y()) + (b.y() - previoustouchb.y())) / 2;
            if (pinchZoomDetermined === true) {
                multigraph.graphs().at(0).doDrag(multigraph, basex, basey, cx, cy, false);
            }

            if (pinchZoomDetermined === false) {
                if (pinchZoomInitialDeltas.base === undefined) {
                    pinchZoomInitialDeltas.base = {};
                    pinchZoomInitialDeltas.base.x = basex;
                    pinchZoomInitialDeltas.base.y = basey;
                }
                if (pinchZoomInitialDeltas.zoomDeltas === undefined) {
                    pinchZoomInitialDeltas.zoomDeltas = {
                        "dx"     : 0,
                        "dy"     : 0,
                        "totalx" : 0,
                        "totaly" : 0
                    };
                }
                if (pinchZoomInitialDeltas.panDeltas === undefined) {
                    pinchZoomInitialDeltas.panDeltas = {
                        "dx" : 0,
                        "dy" : 0
                    };
                }

                pinchZoomInitialDeltas.zoomDeltas.dx += dx;
                pinchZoomInitialDeltas.zoomDeltas.dy += dy;
                pinchZoomInitialDeltas.panDeltas.dx += cx;
                pinchZoomInitialDeltas.panDeltas.dy += cy;

                pinchZoomInitialDeltas.zoomDeltas.totalx += Math.abs(dx);
                pinchZoomInitialDeltas.zoomDeltas.totaly += Math.abs(dy);

                if (pinchZoomDeterminedTimeout === undefined) {
                    pinchZoomDeterminedTimeout = setTimeout(function () {
                        var basex = pinchZoomInitialDeltas.base.x,
                            basey = pinchZoomInitialDeltas.base.y,
                            dx = pinchZoomInitialDeltas.zoomDeltas.dx,
                            dy = pinchZoomInitialDeltas.zoomDeltas.dy,
                            cx = pinchZoomInitialDeltas.panDeltas.dx,
                            cy = pinchZoomInitialDeltas.panDeltas.dy;

                        multigraph.graphs().at(0).doDragReset();

                        multigraph.graphs().at(0).doFirstPinchZoom(multigraph, basex, basey, dx, dy, pinchZoomInitialDeltas.zoomDeltas.totalx, pinchZoomInitialDeltas.zoomDeltas.totaly);
                        multigraph.graphs().at(0).doDrag(multigraph, basex, basey, cx, cy, false);

                        pinchZoomInitialDeltas = {};
                        pinchZoomDetermined = true;
                        clearTimeout(pinchZoomDeterminedTimeout);
                        pinchZoomDeterminedTimeout = undefined;
                    }, 60);
                }
            }

            previoustoucha = a;
            previoustouchb = b;

        };

        var calculateAbsoluteDistance = function (a, b) {
            return Math.abs(a - b);
        };

        $target.on("touchstart", handleTouchStart);
        $target.on("touchmove", handleTouchMove);
        $target.on("touchend", handleTouchEnd);
        $target.on("touchleave", handleTouchLeave);

    });

    return Multigraph;
};


text:
//
//  GTLMirrorMenuItem.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Google Mirror API (mirror/v1)
// Description:
//   API for interacting with Glass users via the timeline.
// Documentation:
//   https://developers.google.com/glass
// Classes:
//   GTLMirrorMenuItem (0 custom class methods, 5 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLMirrorMenuValue;

// ----------------------------------------------------------------------------
//
//   GTLMirrorMenuItem
//

// A custom menu item that can be presented to the user by a timeline item.

@interface GTLMirrorMenuItem : GTLObject

// Controls the behavior when the user picks the menu option. Allowed values
// are:
// - CUSTOM - Custom action set by the service. When the user selects this
// menuItem, the API triggers a notification to your callbackUrl with the
// userActions.type set to CUSTOM and the userActions.payload set to the ID of
// this menu item. This is the default value.
// - Built-in actions:
// - REPLY - Initiate a reply to the timeline item using the voice recording UI.
// The creator attribute must be set in the timeline item for this menu to be
// available.
// - REPLY_ALL - Same behavior as REPLY. The original timeline item's recipients
// will be added to the reply item.
// - DELETE - Delete the timeline item.
// - SHARE - Share the timeline item with the available contacts.
// - READ_ALOUD - Read the timeline item's speakableText aloud; if this field is
// not set, read the text field; if none of those fields are set, this menu item
// is ignored.
// - VOICE_CALL - Initiate a phone call using the timeline item's
// creator.phone_number attribute as recipient.
// - NAVIGATE - Navigate to the timeline item's location.
// - TOGGLE_PINNED - Toggle the isPinned state of the timeline item.
// - OPEN_URI - Open the payload of the menu item in the browser.
// - PLAY_VIDEO - Open the payload of the menu item in the Glass video player.
@property (copy) NSString *action;

// The ID for this menu item. This is generated by the application and is
// treated as an opaque token.
// identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
@property (copy) NSString *identifier;

// A generic payload whose meaning changes depending on this MenuItem's action.
// - When the action is OPEN_URI, the payload is the URL of the website to view.
// - When the action is PLAY_VIDEO, the payload is the streaming URL of the
// video
@property (copy) NSString *payload;

// If set to true on a CUSTOM menu item, that item will be removed from the menu
// after it is selected.
@property (retain) NSNumber *removeWhenSelected;  // boolValue

// For CUSTOM items, a list of values controlling the appearance of the menu
// item in each of its states. A value for the DEFAULT state must be provided.
// If the PENDING or CONFIRMED states are missing, they will not be shown.
@property (retain) NSArray *values;  // of GTLMirrorMenuValue

@end


text:
from pyprint.Printer import Printer

from coalib.output.printers.LOG_LEVEL import LOG_LEVEL
from coalib.output.printers.LogPrinter import LogPrinterMixin
from coalib.processes.communication.LogMessage import LogMessage

class ListLogPrinter(Printer, LogPrinterMixin):
    """
    A ListLogPrinter is a log printer which collects all LogMessages to a list
    so that the logs can be used at a later time.
    """

    def __init__(self,
                 log_level=LOG_LEVEL.WARNING,
                 timestamp_format='%X'):
        Printer.__init__(self)
        self.log_level = log_level

        self.logs = []

    def log_message(self, log_message, **kwargs):
        if not isinstance(log_message, LogMessage):
            raise TypeError('log_message should be of type LogMessage.')

        if log_message.log_level < self.log_level:
            return

        self.logs.append(log_message)

    def _print(self, output, **kwargs):
        self.info(output, **kwargs)


text:
Start-Transcript

<#
$enableScriptBlockLoggingValue = Get-ItemPropertyValue -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Name "EnableScriptBlockLogging" -ErrorAction SilentlyContinue
if ($enableScriptBlockLoggingValue)
{
    Write-Output "EnableScriptBlockLoggingValue: $enableScriptBlockLoggingValue"
}
else
{
    Write-Output "EnableScriptBlockLoggingValue registry entry does not exist"
    $scriptBlockLoggingKey = Get-Item -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -ErrorAction SilentlyContinue
    if ((Test-Path -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging') -eq $false)
    {
        # Create ScriptBlockLogging key if it does not exist
        New-Item -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Force
    }
    New-ItemProperty -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Name "EnableScriptBlockLogging" -PropertyType 'DWord' -Value 1 -Force
}
#>

'This is "no cmdlet" output'
Write-Debug 'This is Write-Debug output'
Write-Error 'This is Write-Error output'
Write-Host 'This is Write-Host output'
Write-Information 'This is Write-Information output'
Write-Output 'This is Write-Output output'
Write-Progress 'This is Write-Progress output'
Write-Warning 'This is Write-Warning output'
Write-Verbose 'This is Write-Verbose output'

#exit 1
Stop-Transcript

<#
New-Item -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Force
New-ItemProperty -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Name "EnableScriptBlockLogging" -PropertyType 'DWord' -Value 1 -Force
New-ItemProperty -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Name "EnableScriptBlockLogging" -PropertyType 'DWord' -Value 0 -Force
Get-Item -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' #-ErrorAction SilentlyContinue
Get-ItemPropertyValue -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Name "EnableScriptBlockLogging" -ErrorAction SilentlyContinue
Remove-ItemProperty -Path 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' -Name "EnableScriptBlockLogging"
#>


text:
package com.gentics.mesh.util;

import static com.gentics.mesh.core.rest.error.Errors.error;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;

import java.security.MessageDigest;

import io.reactivex.Flowable;
import io.reactivex.Single;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

/**
 * Set of utility methods for file handling.
 */
public final class FileUtils {

	private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

	protected static final char[] hexArray = "0123456789abcdef".toCharArray();

	private FileUtils() {
	}

	/**
	 * Generate a SHA 512 checksum from the given buffer flow and return a hex encoded hash as a string.
	 *
	 * @param stream
	 * @return Hashing result
	 */
	public static Single<String> hash(Flowable<Buffer> stream) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-512");
			return stream.reduce(md, (digest, buffer) -> {
				digest.update(buffer.getBytes());
				return digest;
			}).map(MessageDigest::digest).map(FileUtils::bytesToHex);
		} catch (Exception e) {
			log.error("Error while hashing data", e);
			return Single.error(error(INTERNAL_SERVER_ERROR, "node_error_upload_failed", e));
		}
	}

	/**
	 * Generate a SHA 512 checksum from the data in the given buffer and asynchronously return the hex encoded hash as a string.
	 *
	 * @param buffer
	 * @return Observable returning the SHA 512 checksum
	 */
	public static Single<String> hash(Buffer buffer) {
		return hash(Flowable.just(buffer));
	}

	/**
	 * Convert the byte array to a hex formatted string.
	 *
	 * @param bytes
	 * @return
	 */
	public static String bytesToHex(byte[] bytes) {
		char[] hexChars = new char[bytes.length * 2];
		for (int j = 0; j < bytes.length; j++) {
			int v = bytes[j] & 0xFF;
			hexChars[j * 2] = hexArray[v >>> 4];
			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
		}
		return new String(hexChars);
	}
}


text:
package com.pxh.cook.app.bean;

import java.util.Properties;

/**
 * Created by Administrator on 17/10/21.
 */

public class MailSenderBean {
    // 发送邮件的服务器的IP和端口
    private String mailServerHost;
    private String mailServerPort = "25";
    // 邮件发送者的地址
    private String fromAddress;
    // 邮件接收者的地址
    private String toAddress;
    // 登陆邮件发送服务器的用户名和密码
    private String userName;
    private String password;
    // 是否需要身份验证
    private boolean validate = false;
    // 邮件主题
    private String subject;
    // 邮件的文本内容
    private String content;
    // 邮件附件的文件名
    private String[] attachFileNames;

    /**
     * 获得邮件会话属性
     */
    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }

    public String getMailServerHost() {
        return mailServerHost;
    }

    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }

    public String getMailServerPort() {
        return mailServerPort;
    }

    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

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

    public String[] getAttachFileNames() {
        return attachFileNames;
    }

    public void setAttachFileNames(String[] attachFileNames) {
        this.attachFileNames = attachFileNames;
    }
}


text:
package org.wso2.appserver.integration.common.utils;

import org.apache.axis2.AxisFault;
import org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver;
import org.apache.axis2.rpc.receivers.RPCMessageReceiver;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMNamespace;
import org.springframework.context.ApplicationContext;
import org.wso2.appserver.integration.common.clients.SpringServiceUploaderClient;
import org.wso2.carbon.springservices.ui.GenericApplicationContextUtil;
import org.wso2.carbon.springservices.ui.SpringBeansData;
import org.wso2.carbon.utils.ArchiveManipulator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.activation.FileDataSource;
import javax.activation.DataHandler;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;

public class SpringServiceMaker {

    private static final Log log = LogFactory.getLog(SpringServiceMaker.class);

    private static final String SPRING_CONTEXT_SUPPLIER = "org.wso2.carbon.springservices.GenericApplicationContextSupplier";

    public SpringServiceMaker() {
    }

    public SpringBeansData getSpringBeanNames(String springContextFilePath,
                                              String springBeanFilePath,
                                              ClassLoader bundleClassLoader) throws AxisFault {

        SpringBeansData data = new SpringBeansData();
        File urlFile = new File(springBeanFilePath);

        ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
        ClassLoader urlCl;
        try {
            URL url = urlFile.toURL();
            urlCl = URLClassLoader.newInstance(new URL[]{url}, bundleClassLoader);

            // Save the class loader so that you can restore it later
            Thread.currentThread()
                    .setContextClassLoader(urlCl);

            ApplicationContext aCtx = GenericApplicationContextUtil
                    .getSpringApplicationContext(springContextFilePath,
                            springBeanFilePath);
            String[] beanDefintions = aCtx.getBeanDefinitionNames();
            data.setBeans(beanDefintions);
        } catch (Exception e) {
            String msg = "Spring cannot load spring beans";
            handleException(msg, e);
        } finally {
            Thread.currentThread().setContextClassLoader(prevCl);
        }
        return data;
    }

    public void createAndUploadSpringBean(String springContextFilePath, String springBeanFilePath,
                                          String sessionCookie, String backendURL)
            throws Exception {
        SpringBeansData data = getSpringBeanNames(springContextFilePath, springBeanFilePath, this.getClass().getClassLoader());
        String beanClasses[] = data.getBeans();

        if (springBeanFilePath == null) {
            String msg = "spring.non.existent.file";
            log.warn(msg);
            throw new AxisFault(msg);
        }

        int endIndex = springBeanFilePath.lastIndexOf(File.separator);
        String filePath = springBeanFilePath.substring(0, endIndex);
        String archiveFileName = springBeanFilePath.substring(endIndex);
        archiveFileName = archiveFileName.substring(1, archiveFileName
                .lastIndexOf("."));

        ArchiveManipulator archiveManipulator = new ArchiveManipulator();

        // ----------------- Unzip the file ------------------------------------
        String unzippeDir = filePath + File.separator + "springTemp";
        File unzipped = new File(unzippeDir);
        unzipped.mkdirs();

        try {
            archiveManipulator.extract(springBeanFilePath, unzippeDir);
        } catch (IOException e) {
            String msg = "spring.cannot.extract.archive";
            handleException(msg, e);
        }

        // TODO copy the spring xml
        String springContextRelLocation = "spring/context.xml";
        try {
            File springContextRelDir = new File(unzippeDir + File.separator
                    + "spring");
            springContextRelDir.mkdirs();
            File absFile = new File(springContextRelDir, "context.xml");
            if (!absFile.exists()) {
                absFile.createNewFile();
            }
            File file = new File(springContextFilePath);
            FileInputStream in = new FileInputStream(file);
            FileOutputStream out = new FileOutputStream(absFile);
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();

        } catch (FileNotFoundException e) {
            throw AxisFault.makeFault(e);
        } catch (IOException e) {
            throw AxisFault.makeFault(e);
        }

        // ---- Generate the services.xml and place it in META-INF -----
        File file = new File(unzippeDir + File.separator + "META-INF"
                + File.separator + "services.xml");
        file.mkdirs();

        try {
            File absoluteFile = file.getAbsoluteFile();

            if (absoluteFile.exists()) {
                absoluteFile.delete();
            }

            absoluteFile.createNewFile();

            OutputStream os = new FileOutputStream(file);
            OMElement servicesXML = createServicesXMLFromSpringBeans(
                    beanClasses, springContextRelLocation);
            servicesXML.build();
            servicesXML.serialize(os);
        } catch (Exception e) {
            String msg = "spring.cannot.write.services.xml";
            handleException(msg, e);
        }

        // ----------------- Create the AAR ------------------------------------
        // These are the files to include in the ZIP file
        String outAARFilename = filePath + File.separator + archiveFileName
                + ".aar";

        try {
            archiveManipulator.archiveDir(outAARFilename, unzipped.getPath());
        } catch (IOException e) {
            String msg = "Spring cannot create new aar archive";
            handleException(msg, e);
        }

        File fileToUpload = new File(outAARFilename);

        FileDataSource fileDataSource = new FileDataSource(fileToUpload);
        DataHandler dataHandler = new DataHandler(fileDataSource);

        try {
            SpringServiceUploaderClient uploaderClient =
                    new SpringServiceUploaderClient(backendURL, sessionCookie);
            uploaderClient.uploadSpringServiceFile(archiveFileName + ".aar", dataHandler);
        } catch (Exception e) {
            String msg = "spring.unable.to.upload";
            handleException(msg, e);
        }

    }

    private OMElement createServicesXMLFromSpringBeans(String[] springBeans,
                                                       String springContextLocation) {
        OMFactory factory = OMAbstractFactory.getOMFactory();
        OMNamespace emptyNS = factory.createOMNamespace("", "");
        OMElement serviceGroupEle = factory.createOMElement("serviceGroup", "",
                "");

        for (String serviceBeanName : springBeans) {
            OMElement serviceEle = factory.createOMElement("service", "", "");

            OMElement schemaEle = factory.createOMElement("schema", "", "");
            schemaEle.addAttribute(factory.createOMAttribute(
                    "elementFormDefaultQualified", emptyNS, "false"));

            serviceEle.addAttribute(factory.createOMAttribute("name", emptyNS,
                    serviceBeanName));

            OMElement msgReceiversEle = factory.createOMElement(
                    "messageReceivers", "", "");
            OMElement msgReceiverEle1 = factory.createOMElement(
                    "messageReceiver", "", "");
            msgReceiverEle1.addAttribute("mep",
                    "http://www.w3.org/ns/wsdl/in-only", emptyNS);
            msgReceiverEle1.addAttribute("class",
                    RPCInOnlyMessageReceiver.class.getName(), emptyNS);

            OMElement msgReceiverEle2 = factory.createOMElement(
                    "messageReceiver", "", "");
            msgReceiverEle2.addAttribute("mep",
                    "http://www.w3.org/ns/wsdl/in-out", emptyNS);
            msgReceiverEle2.addAttribute("class", RPCMessageReceiver.class
                    .getName(), emptyNS);
            msgReceiversEle.addChild(msgReceiverEle1);
            msgReceiversEle.addChild(msgReceiverEle2);

            OMElement parameterEleServiceObjectSupplier = factory
                    .createOMElement("parameter", "", "");
            parameterEleServiceObjectSupplier.addAttribute("locked", "true",
                    emptyNS);
            parameterEleServiceObjectSupplier.addAttribute("name",
                    "ServiceObjectSupplier", emptyNS);
            parameterEleServiceObjectSupplier
                    .setText(SpringServiceMaker.SPRING_CONTEXT_SUPPLIER);

            OMElement parameterEleSpringBeanName = factory.createOMElement(
                    "parameter", "", "");
            parameterEleSpringBeanName.addAttribute("locked", "true", emptyNS);
            parameterEleSpringBeanName.addAttribute("name", "SpringBeanName",
                    emptyNS);
            parameterEleSpringBeanName.setText(serviceBeanName);

            OMElement parameterEleSpringContextLocation = factory
                    .createOMElement("parameter", "", "");
            parameterEleSpringContextLocation.addAttribute("locked", "true",
                    emptyNS);
            parameterEleSpringContextLocation.addAttribute("name",
                    "SpringContextLocation", emptyNS);
            parameterEleSpringContextLocation.setText(springContextLocation);

            OMElement paramEleserviceType = factory.createOMElement("parameter", "", "");
            paramEleserviceType.addAttribute("name", "serviceType", emptyNS);
            paramEleserviceType.setText("spring");

            serviceEle.addChild(schemaEle);
            serviceEle.addChild(msgReceiversEle);
            serviceEle.addChild(parameterEleServiceObjectSupplier);
            serviceEle.addChild(parameterEleSpringBeanName);
            serviceEle.addChild(parameterEleSpringContextLocation);
            serviceEle.addChild(paramEleserviceType);
            serviceGroupEle.addChild(serviceEle);
        }
        return serviceGroupEle;
    }

    private void handleException(String msg, Exception e) throws AxisFault {
        log.error(msg, e);
        throw new AxisFault(msg, e);
    }
}


text:
  <!-- JavaScript -->
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="<?php echo SITE_URL; ?>/resources/js/bootstrap.js"></script>

    <!-- Page Specific Plugins -->

	 <script src="<?php echo SITE_URL; ?>/resources/js/custom_js.js"></script>

  </body>
</html>


text:
namespace vtrc { namespace common { namespace defaults {

    vtrc::rpc::session_options session_options( )
    {
        rpc::session_options res;
        res.set_max_active_calls  ( 5 );
        res.set_max_message_length( 65536 );
        res.set_max_stack_size    ( 16 );
        res.set_read_buffer_size  ( 4096 );
        res.set_init_timeout      ( 10000 ); // milliseconds
        return res;
    }

    vtrc::rpc::options method_options( )
    {
        vtrc::rpc::options res;
        res.set_timeout( 30000000 ); // microseconds
        res.set_wait( true );
        res.set_accept_callbacks( true );
        return res;
    }

    vtrc::rpc::unit_options unit_options( )
    {
        vtrc::rpc::unit_options res;
        res.set_wait( true );
        res.set_accept_callbacks( true );
        res.set_accept_response( true );
        return res;
    }

}}}


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

<TITLE>
G-Index
</TITLE>

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

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E G H I L M P R S T U W

G

generateWordlist(String) -
Method in class iitb.cfilt.cpost.lexicon.Wordlist

get(String) -
Static method in class iitb.cfilt.cpost.ConfigReader

getCategory(String) -
Method in class iitb.cfilt.cpost.lexicon.Wordlist

getCategory() -
Method in class iitb.cfilt.cpost.lexicon.WordProperties

getCategory() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleResult

getDepth() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getLogString() -
Static method in class iitb.cfilt.cpost.logger.Logger

getParadigm() -
Method in class iitb.cfilt.cpost.lexicon.WordProperties

getParadigm() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getParadigm() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleResult

getPenultimateDeletion() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getPenultimateInsertion() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getPriority() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getRegularRootForm(String) -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleReader

getRoot() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleResult

getSpellingVariations(String) -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleReader

getStemmedOutputs() -
Method in class iitb.cfilt.cpost.stemmer.StemmedToken

getSuffixList() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleResult

getSuffixSize() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleResult

getToken() -
Method in class iitb.cfilt.cpost.stemmer.StemmedToken

getUltimateDeletion() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getUltimateDeletion() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleResult

getUltimateInsertion() -
Method in class iitb.cfilt.cpost.stemmer.StemmerRule

getUniqueSuffix(LinkedList<String>) -
Method in class iitb.cfilt.cpost.stemmer.StemmerRuleReader

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E G H I L M P R S T U W


text:
<?php

namespace Coral\SiteBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Coral\SiteBundle\DependencyInjection\CoralSiteExtension;
use Coral\SiteBundle\DependencyInjection\FilterCompilerPass;

/**
 * Coral Site Bundle
 *
 * @codeCoverageIgnore
 */
class CoralSiteBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->registerExtension(new CoralSiteExtension());

        $container->addCompilerPass(new FilterCompilerPass);
    }
}


text:
package cn.aage.robot.web;

import cn.aage.robot.service.CookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by shonve on 2016/10/21.
 */
@Controller
@RequestMapping("/cook")
public class CookController {

    @Autowired
    private CookService cookService;

    @RequestMapping(value = "/cook", method = {RequestMethod.POST, RequestMethod.GET})
    public void cook(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        String name = request.getParameter("name");
        name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        cookService.saveCook(name, 0);
    }

    @RequestMapping(value = "/label", method = {RequestMethod.POST, RequestMethod.GET})
    public void label(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        cookService.saveStyle1(0);

    }

    @RequestMapping(value = "/arrange", method = {RequestMethod.POST, RequestMethod.GET})
    public void arrange(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        cookService.arrange();

    }

    @RequestMapping(value = "/del", method = {RequestMethod.POST, RequestMethod.GET})
    public void del(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        cookService.del();

    }
}


text:
using System;
using System.Security.Cryptography;

namespace Tamir.SharpSsh.jsch.jce
{
    /* -*-mode:java; c-basic-offset:2; -*- */
    /*
	Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	  1. Redistributions of source code must retain the above copyright notice,
		 this list of conditions and the following disclaimer.

	  2. Redistributions in binary form must reproduce the above copyright
		 notice, this list of conditions and the following disclaimer in
		 the documentation and/or other materials provided with the distribution.

	  3. The names of the authors may not be used to endorse or promote products
		 derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
	FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
	INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
	OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
	EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	*/

    public class AES128CBC : Cipher
    {
        private int mode;
        private const int ivsize = 16;
        private const int bsize = 16;
        private RijndaelManaged rijndael;
        private ICryptoTransform cipher;

        public override int getIVSize()
        {
            return ivsize;
        }

        public override int getBlockSize()
        {
            return bsize;
        }

        public override void init(int mode, byte[] key, byte[] iv)
        {
            this.mode = mode;
            rijndael = new RijndaelManaged();
            rijndael.Mode = CipherMode.CBC;
            rijndael.Padding = PaddingMode.None;
            //String pad="NoPadding";
            byte[] tmp;
            if (iv.Length > ivsize)
            {
                tmp = new byte[ivsize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (key.Length > bsize)
            {
                tmp = new byte[bsize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }

            try
            {
                //      SecretKeySpec keyspec=new SecretKeySpec(key, "AES");
                //		cipher=javax.crypto.Cipher.getInstance("AES/CBC/"+pad);

                //      cipher.init((mode==ENCRYPT_MODE?
                //		   javax.crypto.Cipher.ENCRYPT_MODE:
                //		   javax.crypto.Cipher.DECRYPT_MODE),
                //		  keyspec, new IvParameterSpec(iv));
                cipher = (mode == ENCRYPT_MODE ?
                                                   rijndael.CreateEncryptor(key, iv) :
                                                                                rijndael.CreateDecryptor(key, iv));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                cipher = null;
            }
        }

        public override void update(byte[] foo, int s1, int len, byte[] bar, int s2)
        {
            //cipher.update(foo, s1, len, bar, s2);
            cipher.TransformBlock(foo, s1, len, bar, s2);
        }

        public override string ToString()
        {
            return "aes128-cbc";
        }
    }
}


text:
<?php

namespace EngiShopBundle\Controller\Base;

class AdminController extends BaseController
{
}


text:
from precise_bbcode.bbcode import get_parser

from .models import Comment

def convert_all_comments():
    parser = get_parser()
    for comment in Comment.objects.exclude(text__exact=''):
        comment.html_text = parser.render(comment.text)
        comment.save()


text:
author: björn
comments: true
date: 2015-10-20
layout: post
slug: when-your-intranet-is-like-the-internet
title: When your intranet is like the internet
categories:
- blog
tags:
- programming
- ruby
- devops
---

# When your intranet is like the internet

Do you remember the good old days? When people were honest and we all could
trust one another? The internet used to be like that once. Then
[September never ended] and things changed.

The good thing is that when you're on your own intranet then it's like in the
good old days. Your own little gated community. Safe and sound. Well, yes, up to
a certain size. Then your intranet starts looking a whole lot like the public
internet. Multiple data centers, several branch offices, some public access
terminals and some WiFi to keep it in sync. All of a sudden there's no practical
difference from the public internet.

Rails by default lives in the glory of the good old days, everything on my
network is safe and I can trust them. Which is a sensible configuration for most
apps. If you can't trust the traffic in your own datacenter then, well, you're
probably reading blog posts like this.

One of these settings for Rails is the algorithm it uses to figure out what the
remote IP address is for the current request. By default this is done by
removing all [private IP addresses] from the [X-Forwarded-For] header, inverting
the order of the remaining IPs and then picking the first unknown IP. The logic
for all of this is in the [ActionDispatch::RemoteIp] middleware which is used
to. To learn more about how the middleware works and why it does it the way it
does, then read the excellent blog post
[Rails IP Spoofing Vulnerabilities and Protection].

## Our setup

In our case what ended up happening was that all requsts appeared to be coming
from our load balancer, which can hardly be called an end user. Our app setup is
straightforward. Some app servers, a load balancer, and in front of all of
this there's a reverse proxy that handles SSL termination and routing for the
different apps this datacenter provides.

<img src="http://i.imgur.com/dSymXXD.png"
     title="a simplified diagram of our datacenter"
     style="max-width: 500px;"
     class="center-block">

This datacenter lives in the `10.0.1.0/24` subnet. All our users come from
various other parts of the private IP space . All in all a request can hop
through up to five proxies and load balancers before reaching our app, each
adding the `X-Forwarded-For` header as traffic flows through it.

And because all the IP addresses in the `X-Forwarded-For` header are private
Rails will strip them. And when there's no addresses in `X-Forwarded-For` Rails
returns the `REMOTE_ADDR` instead. Which'll be the last visited node before the
webserver, in our case the load balancer.

## The solution

To work around this:

1. We got a list of all proxy ips/server subnets which we know no end-users will
   be accessing from
2. Installed the [Remote IP Proxy Scrubber] gem , which was built to handle this
   situation on the public internet. Like when you use CloudFlare in front of
   your app.
3. Configured the `ActionDispatch::RemoteIp` middleware to only ignore
   localhost by default, because if you can't trust yourself…

```ruby
# This is config/environments/production.rb

# First off swap out the original ActionDispatch::RemoteIp middleware with
# our own configured version
config.middleware.swap(
  ActionDispatch::RemoteIp,
  ActionDispatch::RemoteIp,
  false,  # Don't perform any IP spoofing checking
  %r{
    ^127\.0\.0\.1$ |  # localhost IPv4
    ^::1$             # localhost IPv6
  }x
)

TRUST_PROXIES_AND_SUBNETS = %w{
  # All servers in the datacenter is trusted to report the correct IP
  10.0.1.0/24
  # Proxy server in office A
  10.1.1.10
  # Proxy server in office B
  10.1.2.10
}

# Filter out any known proxies and trusted subnets
config.middleware.insert_before(
  Rails::Rack::Logger,
  RemoteIpProxyScrubber.filter_middleware,
  TRUSTED_PROXIES_AND_SUBNETS
)

# Now to log the correct IP address, note this is added after ActionDispatch::RemoteIp,
# so the IP has had a chance to be set
config.middleware.insert_after(
  ActionDispatch::RemoteIp,
  RemoteIpProxyScrubber.patched_logger
)
config.middleware.delete(Rails::Rack::Logger)
```

Now Rails will believe that our intranet is just another part of the internet,
with a few select trusted sources. And we're able to see our user's IP
addresses. We can really see that there has been no traffic from building C all
day, and it's not just that caller having issues connecting to our app.

[private IP addresses]: https://en.wikipedia.org/wiki/Private_network
[X-Forwarded-For]: https://en.wikipedia.org/wiki/X-Forwarded-For
[Rails IP Spoofing Vulnerabilities and Protection]: http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/
[ActionDispatch::RemoteIp]: https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L26
[Remote IP Proxy Scrubber]: https://github.com/metavida/remote_ip_proxy_scrubber
[September never ended]: https://en.wikipedia.org/wiki/Eternal_September


text:
<?php

namespace Scherzo\Router;

/**
 * Thrown by a Container if an entry is not found.
**/
class RouterMethodNotAllowedException extends RouterException {
    /** @var array */
    protected $allowedMethods = [];

    public function getAllowedMethods() : array {
        return $this->allowedMethods;
    }

    public function setAllowedMethods(array $methods) : self {
        $this->allowedMethods = $methods;
        return $this;
    }
}


text:
{% extends "layout.html" %}

{% block page_title %}
  Sponsor Licence Management
{% endblock %}

{% block content %}

        Prototype for managing a sponsor licence
        v0.1

      View the prototype

Changes which haven't begun testing with users yet

A thing which has been added/removed/changed

Etc

Previously tested versions

          Version
          Tested on
          Changes

           Version 1
          10 February 2017

                Changes included in this version

Thing which has been changed

Prototype kit examples and documentation

Example pages and documentation

GitHub

Other resources

						Guide to GOV.UK Elements

						Service design manual

						Government Digital Service Design Principles

{% endblock %}


text:
<?php

namespace Phalcon {

	/**
	 * Phalcon\Di
	 *
	 * Phalcon\Di is a component that implements Dependency Injection/Service Location
	 * of services and it's itself a container for them.
	 *
	 * Since Phalcon is highly decoupled, Phalcon\Di is essential to integrate the different
	 * components of the framework. The developer can also use this component to inject dependencies
	 * and manage global instances of the different classes used in the application.
	 *
	 * Basically, this component implements the `Inversion of Control` pattern. Applying this,
	 * the objects do not receive their dependencies using setters or constructors, but requesting
	 * a service dependency injector. This reduces the overall complexity, since there is only one
	 * way to get the required dependencies within a component.
	 *
	 * Additionally, this pattern increases testability in the code, thus making it less prone to errors.
	 *
	 *
	 * use Phalcon\Di;
	 * use Phalcon\Http\Request;
	 *
	 * $di = new Di();
	 *
	 * // Using a string definition
	 * $di->set("request", Request::class, true);
	 *
	 * // Using an anonymous function
	 * $di->setShared(
	 *     "request",
	 *     function () {
	 *         return new Request();
	 *     }
	 * );
	 *
	 * $request = $di->getRequest();
	 *
	 */

	class Di implements \Phalcon\DiInterface, \ArrayAccess {

		protected $_services;

		protected $_sharedInstances;

		protected $_freshInstance;

		protected $_eventsManager;

		protected static $_default;

		/**
		 * \Phalcon\Di constructor
		 */
		public function __construct(){ }

		/**
		 * Sets the internal event manager
		 */
		public function setInternalEventsManager(\Phalcon\Events\ManagerInterface $eventsManager){ }

		/**
		 * Returns the internal event manager
		 */
		public function getInternalEventsManager(){ }

		/**
		 * Registers a service in the services container
		 */
		public function set($name, $definition, $shared=null){ }

		/**
		 * Registers an "always shared" service in the services container
		 */
		public function setShared($name, $definition){ }

		/**
		 * Removes a service in the services container
		 * It also removes any shared instance created for the service
		 */
		public function remove($name){ }

		/**
		 * Attempts to register a service in the services container
		 * Only is successful if a service hasn't been registered previously
		 * with the same name
		 */
		public function attempt($name, $definition, $shared=null){ }

		/**
		 * Sets a service using a raw \Phalcon\Di\Service definition
		 */
		public function setRaw($name, \Phalcon\Di\ServiceInterface $rawDefinition){ }

		/**
		 * Returns a service definition without resolving
		 */
		public function getRaw($name){ }

		/**
		 * Returns a \Phalcon\Di\Service instance
		 */
		public function getService($name){ }

		/**
		 * Resolves the service based on its configuration
		 */
		public function get($name, $parameters=null){ }

		/**
		 * Resolves a service, the resolved service is stored in the DI, subsequent
		 * requests for this service will return the same instance
		 *
		 * @param string name
		 * @param array parameters
		 * @return mixed
		 */
		public function getShared($name, $parameters=null){ }

		/**
		 * Check whether the DI contains a service by a name
		 */
		public function has($name){ }

		/**
		 * Check whether the last service obtained via getShared produced a fresh instance or an existing one
		 */
		public function wasFreshInstance(){ }

		/**
		 * Return the services registered in the DI
		 */
		public function getServices(){ }

		/**
		 * Check if a service is registered using the array syntax
		 */
		public function offsetExists($name){ }

		/**
		 * Allows to register a shared service using the array syntax
		 *
		 *
		 * $di["request"] = new \Phalcon\Http\Request();
		 *
		 */
		public function offsetSet($name, $definition){ }

		/**
		 * Allows to obtain a shared service using the array syntax
		 *
		 *
		 * var_dump($di["request"]);
		 *
		 */
		public function offsetGet($name){ }

		/**
		 * Removes a service from the services container using the array syntax
		 */
		public function offsetUnset($name){ }

		/**
		 * Magic method to get or set services using setters/getters
		 */
		public function __call($method, $arguments=null){ }

		/**
		 * Registers a service provider.
		 *
		 *
		 * use \Phalcon\DiInterface;
		 * use \Phalcon\Di\ServiceProviderInterface;
		 *
		 * class SomeServiceProvider implements ServiceProviderInterface
		 * {
		 *     public function register(DiInterface $di)
		 *     {
		 *         $di->setShared('service', function () {
		 *             // ...
		 *         });
		 *     }
		 * }
		 *
		 */
		public function register(\Phalcon\Di\ServiceProviderInterface $provider){ }

		/**
		 * Set a default dependency injection container to be obtained into static methods
		 */
		public static function setDefault(\Phalcon\DiInterface $dependencyInjector){ }

		/**
		 * Return the latest DI created
		 */
		public static function getDefault(){ }

		/**
		 * Resets the internal default DI
		 */
		public static function reset(){ }

		/**
		 * Loads services from a yaml file.
		 *
		 *
		 * $di->loadFromYaml(
		 *     "path/services.yaml",
		 *     [
		 *         "!approot" => function ($value) {
		 *             return dirname(__DIR__) . $value;
		 *         }
		 *     ]
		 * );
		 *
		 *
		 * And the services can be specified in the file as:
		 *
		 *
		 * myComponent:
		 *     className: \Acme\Components\MyComponent
		 *     shared: true
		 *
		 * group:
		 *     className: \Acme\Group
		 *     arguments:
		 *         - type: service
		 *           name: myComponent
		 *
		 * user:
		 *    className: \Acme\User
		 *
		 *
		 * @link https://docs.phalconphp.com/en/latest/reference/di.html
		 */
		public function loadFromYaml($filePath, $callbacks=null){ }

		/**
		 * Loads services from a php config file.
		 *
		 *
		 * $di->loadFromPhp("path/services.php");
		 *
		 *
		 * And the services can be specified in the file as:
		 *
		 *
		 * return [
		 *      'myComponent' => [
		 *          'className' => '\Acme\Components\MyComponent',
		 *          'shared' => true,
		 *      ],
		 *      'group' => [
		 *          'className' => '\Acme\Group',
		 *          'arguments' => [
		 *              [
		 *                  'type' => 'service',
		 *                  'service' => 'myComponent',
		 *              ],
		 *          ],
		 *      ],
		 *      'user' => [
		 *          'className' => '\Acme\User',
		 *      ],
		 * ];
		 *
		 *
		 * @link https://docs.phalconphp.com/en/latest/reference/di.html
		 */
		public function loadFromPhp($filePath){ }

		/**
		 * Loads services from a Config object.
		 */
		protected function loadFromConfig(\Phalcon\Config $config){ }

	}
}


text:
package org.apache.beam.sdk.io.gcp.pubsublite.internal;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import org.apache.beam.sdk.transforms.SerializableFunction;

public class ManagedFactoryImpl<T extends AutoCloseable> implements ManagedFactory<T> {

  private final SerializableFunction<SubscriptionPartition, T> newInstance;

  @GuardedBy("this")
  private final Map<SubscriptionPartition, T> instances = new HashMap<>();

  ManagedFactoryImpl(SerializableFunction<SubscriptionPartition, T> newInstance) {
    this.newInstance = newInstance;
  }

  @Override
  public synchronized T create(SubscriptionPartition subscriptionPartition) {
    return instances.computeIfAbsent(subscriptionPartition, newInstance::apply);
  }

  @Override
  public synchronized void close() throws Exception {
    @Nullable Exception e = null;
    for (AutoCloseable c : instances.values()) {
      try {
        c.close();
      } catch (Exception e2) {
        if (e == null) {
          e = e2;
        } else {
          e.addSuppressed(e2);
        }
      }
    }
    if (e != null) {
      throw e;
    }
  }
}


text:
package it.ispw.efco.nottitranquille.model;

import java.util.*;

/**
 * @author Claudio Pastorini Omar Shalby Federico Vagnoni Emanuele Vannacci
 */
public class Notification {

    /**
     * Default constructor
     */
    public Notification() {
    }

}


text:
import { WorkerConnector } from '../types';
import { default as xs, Stream, Subscription} from 'xstream';
import { VNode, h } from '@cycle/dom';
import { default as uuid} from 'uuid/v4';

import fromEvent from 'xstream/extra/fromevent';
import sampleCombine from 'xstream/extra/samplecombine';
import dropRepeats  from 'xstream/extra/droprepeats';

import {
  adapt
} from '@cycle/run/lib/adapt';

import {
  WorkerDOMMessage,
  WorkerDOMMessageCommand,
  EventSynthesis,
  WorkerDOMEvent,
  WorkerEventFnOptions
} from './main';

import {
  SandboxMessageCommand
} from '../main'

export const DOMWorkerConnector: WorkerConnector = (rx, tx) => {
  rx.start();
  tx.start();
  return (sink$: Stream<VNode>): any => {
    const raf$ = fromEvent(self, 'message').filter(e => e.data.cmd === SandboxMessageCommand.raf);
    raf$.compose(sampleCombine(sink$))
    .map(([_, vnode]) => vnode)
    .compose(dropRepeats())
    .subscribe({
      next (vnode) {
        const message: WorkerDOMMessage = {
          cmd: WorkerDOMMessageCommand.vnode,
          payload: vnode
        }
        tx.postMessage(message);
      },
      error (error) {
        console.error(error);
      },
      complete () {
        rx.close();
        tx.close();
      }
    })

    function select (selector: string) {
      return {
        select: (suffix: string) => select(`${selector} ${suffix} `),
        events: (events: string, options?: WorkerEventFnOptions): Stream<EventSynthesis> => {
          const listenerId = uuid();
          let subscription: Subscription;
          return adapt(xs.create({
            start(observer) {
              const attachMessage = {
                cmd: WorkerDOMMessageCommand.attach,
                payload: {
                  selector: selector,
                  events: events,
                  options: options,
                  listenerId
                }
              }
              tx.postMessage(attachMessage);
              subscription = fromEvent(rx, 'message')
                .filter(e => (e.data as WorkerDOMEvent).listenerId === listenerId)
                .subscribe({
                  next (event) {
                    const payload = event.data.payload as EventSynthesis;
                    observer.next(payload);
                  },
                  error (error) {
                    console.error(error)
                  },
                  complete () {

                  }
                })
            },
            stop() {
              const detachMessage = {
                cmd: WorkerDOMMessageCommand.detach,
                payload: {
                  listenerId
                }
              }
              tx.postMessage(detachMessage);
              subscription.unsubscribe();
            }
          }) as Stream<EventSynthesis>);
        }
      }
    }
    const escape = {
      'document' : 1,
      ':root' : 1,
      'body' : 1
    };
    return {
      select,
      isolateSource (source: any, scope: string) {
				return {
					select: (sel) => {
            if (escape[sel]) {
              return select(sel);
            } else {
              return select(`[x-scope="${scope}"] ${sel} `)
            }
          }
				}
			},
			// optimistic isoloate
			isolateSink (sink: Stream<VNode>, scope: string) {
				return sink.map(
          (vnode: VNode): VNode => h('span', {attrs: {'x-scope': scope}}, [vnode])
        );
			}
    }
  }
}


text:
var ngCore = require('angular2/core'),
    ngCommonDirectives = require('angular2/src/common/directives'),
    ngRouter = require('angular2/router'),
    linkActiveClass = require('../../common/LinkActiveClassDirective'),
    jwt = require('angular2-jwt'),
    Auth = require('ng2-ui-auth'),
    navbarHtml = require('./navbar.html');

module.exports = ngCore
    .Component({
        selector: 'app-navbar',
        template: navbarHtml,
     directives: [ngRouter.ROUTER_DIRECTIVES, linkActiveClass, ngCommonDirectives.NgIf]
     })
    .Class({
        constructor: [Auth.Auth, jwt.JwtHelper, function(auth, jwtHelper) {
            this.auth = auth;
            this.jwtHelper = jwtHelper;
        }]
    });


text:
<?xml version="1.0"?>
<project basedir="." default="help">

	<property name="rootdir" value="${project.basedir}/" override="true" />
	<property name="bindir" value="${rootdir}vendor/bin/" override="false" />

	<target name="help">
		<echo message="Available targets" />
		<echo message="=================" />
		<echo message="phing phpunit   Runs all unit tests" />
		<echo message="phing phpcs     Runs PHP code style validation" />
		<echo message="phing phpcpd    Runs PHP code duplication detector" />
		<echo message="phing phpmd     Runs PHP mess detector" />
		<echo message="phing codecheck Calls every quality tool" />
		<echo message="phing coverage  Runs unit tests and generates code coverage report" />
		<echo message="phing help      Shows this help screen" />
	</target>

	<target name="phpunit">
		<exec command="${bindir}phpunit -c ${rootdir}phpunit.xml" checkreturn="false" logoutput="true" passthru="true" />
	</target>

	<target name="phpcs" description="PHP code style validation">
		<exec command="${bindir}phpcs -p --extensions=php --standard=PSR2 --report=full ${rootdir}lib" escape="false" logoutput="true" passthru="true" />
	</target>

	<target name="phpcpd" description="PHP code duplication detector">
		<exec command="${bindir}phpcpd --min-lines 7 --min-tokens 65 ${rootdir}lib" checkreturn="false" logoutput="true" passthru="true" />
	</target>

	<target name="phpmd" description="PHP mess detector">
		<exec command="${bindir}phpmd ${rootdir}lib text codesize,unusedcode,design" checkreturn="false" logoutput="true" passthru="true" />
	</target>

	<target name="codecheck" depends="phpunit,phpcs,phpcpd,phpmd" />

	<target name="coverage">
		<exec command="${bindir}phpunit --coverage-html ${rootdir}build/coverage/ -c ${rootdir}phpunit.xml" checkreturn="false" logoutput="true" passthru="true" />
	</target>

</project>


text:
PROJECT
{{ projectName }}
{{ project.type }}

Add Role

                <form class="form-inline">

                      <input type="text" class="form-control" placeholder="New Role Name" ng-model="newRoleName">
                      <input type="text" class="form-control" placeholder="Description" ng-model="newRoleDescription">
                      <button class="btn btn-primary btn" type="submit" ng-click="addRole()">Add</button>

                </form>

Roles / Salt States
      <input class="input-xs pull-right" ng-model="searchText" placeholder="Search" />

                Name
                Description
                Actions

                    {{ role.name }}

                    {{ role.description }}

                    <button type="button" class="btn btn-success btn-xs" ng-click="cloneRole(projectID, role.$id)">Clone</button>
                    Manage
                    <button popover="Click role name at top of next page to rename." popover-title="Rename Project" class="btn btn-warning btn-xs">Rename</button>
                    <button type="button" class="btn btn-danger btn-xs" ng-click="removeRole(role.$id)">Delete</button>


text:
<?php

namespace Ixoil\UserBundle\Entity;

use Doctrine\ORM\Mapping AS ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="ixoil_user_account_logistician")
 */
class LogisticianAccount
{
    /**
     * @ORM\Column(type="array", nullable=false)
     */
    private $delivery_areas;

    /**
     * @ORM\OneToOne(targetEntity="Ixoil\UserBundle\Entity\Account", inversedBy="logisticianAccount")
     * @ORM\JoinColumn(name="account_id", referencedColumnName="id", nullable=false, unique=true)
     * @ORM\Id
     */
    private $account;

    /**
     * Set delivery_areas
     *
     * @param array $deliveryAreas
     * @return LogisticianAccount
     */
    public function setDeliveryAreas($deliveryAreas)
    {
        $this->delivery_areas = $deliveryAreas;

        return $this;
    }

    /**
     * Get delivery_areas
     *
     * @return array
     */
    public function getDeliveryAreas()
    {
        return $this->delivery_areas;
    }

    /**
     * Set account
     *
     * @param \Ixoil\UserBundle\Entity\Account $account
     * @return LogisticianAccount
     */
    public function setAccount(\Ixoil\UserBundle\Entity\Account $account)
    {
        $this->account = $account;

        return $this;
    }

    /**
     * Get account
     *
     * @return \Ixoil\UserBundle\Entity\Account
     */
    public function getAccount()
    {
        return $this->account;
    }
}


text:
/* eslint-env jasmine, mocha */
import htmlContent from '../../lib/html-content';

describe('dom: insertBefore', () => {
  function runTests (type) {
    describe(`${type}: `, () => {
      let div;
      let elem;
      let fragment;
      let host;
      let root;
      let slot;

      beforeEach(() => {
        div = document.createElement('div');
        fragment = document.createDocumentFragment();
        host = document.createElement('div');
        root = host.attachShadow({ mode: 'open' });
        slot = document.createElement('slot');

        root.appendChild(slot);

        switch (type) {
          case 'div':
            elem = div;
            break;
          case 'fragment':
            elem = fragment;
            break;
          case 'host':
            elem = host;
            break;
          case 'root':
            root.innerHTML = '';
            elem = root;
            break;
          case 'slot':
            elem = slot;
            break;
        }
      });

      it('should throw if nothing to insert', () => {
        expect(() => {
          elem.insertBefore(null);
        }).to.throw(Error);
        expect(elem.childNodes.length).to.equal(0);
      });

      it('should return the inserted node', () => {
        const inserted = document.createElement('div');
        const changedElem = elem.insertBefore(inserted, null);
        expect(changedElem).not.to.equal(undefined);
        expect(changedElem).to.equal(inserted);
      });

      it('should append node if referenceNode is null', () => {
        htmlContent(elem, '

');
        const inserted = document.createElement('test');
        elem.insertBefore(inserted, null);

        expect(htmlContent(elem)).to.equal('

<test></test>');
        expect(elem.childNodes[2]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(3);
        }
      });

      it('should insert an element node to a parent with no children', () => {
        const inserted = document.createElement('test');
        elem.insertBefore(inserted, null);

        expect(htmlContent(elem)).to.equal('<test></test>');
        expect(elem.childNodes[0]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(1);
        }
      });

      it('should insert a text node to a parent with no children', () => {
        const inserted = document.createTextNode('text');
        elem.insertBefore(inserted, null);

        expect(htmlContent(elem)).to.equal('text');
        expect(elem.childNodes[0]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(1);
        }
      });

      it('should insert a comment node to a parent with no children', () => {
        const inserted = document.createComment('comment');
        elem.insertBefore(inserted, null);

        expect(htmlContent(elem)).to.equal('');
        expect(elem.childNodes[0]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(0);
        }
      });

      it('should insert an element node to a parent with one child', () => {
        htmlContent(elem, '

');
        const inserted = document.createElement('test');
        elem.insertBefore(inserted, elem.childNodes[0]);

        expect(htmlContent(elem)).to.equal('<test></test>

');
        expect(elem.childNodes[0]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(2);
        }
      });

      it('should insert a text node to a parent with one child', () => {
        htmlContent(elem, '

');
        const inserted = document.createTextNode('text');
        elem.insertBefore(inserted, elem.childNodes[0]);

        expect(htmlContent(elem)).to.equal('text

');
        expect(elem.childNodes[0]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(2);
        }
      });

      it('should insert a comment node to a parent with one child', () => {
        htmlContent(elem, '

');
        const inserted = document.createComment('comment');
        elem.insertBefore(inserted, elem.childNodes[0]);

        expect(htmlContent(elem)).to.equal('

');
        expect(elem.childNodes[0]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(1);
        }
      });

      it('should insert an element node to a parent with two or more children', () => {
        htmlContent(elem, '<div1></div1><div2></div2><div3></div3>');
        const inserted = document.createElement('test');
        elem.insertBefore(inserted, elem.childNodes[1]);

        expect(htmlContent(elem)).to.equal('<div1></div1><test></test><div2></div2><div3></div3>');
        expect(elem.childNodes[1]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(4);
        }
      });

      it('should insert a text node to a parent with two or more children', () => {
        htmlContent(elem, '<div1></div1><div2></div2><div3></div3>');
        const inserted = document.createTextNode('text');
        elem.insertBefore(inserted, elem.childNodes[1]);

        expect(htmlContent(elem)).to.equal('<div1></div1>text<div2></div2><div3></div3>');
        expect(elem.childNodes[1]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(4);
        }
      });

      it('should insert a comment node to a parent with two or more children', () => {
        htmlContent(elem, '<div1></div1><div2></div2><div3></div3>');
        const inserted = document.createComment('comment');
        elem.insertBefore(inserted, elem.childNodes[1]);

        expect(htmlContent(elem)).to.equal('<div1></div1><div2></div2><div3></div3>');
        expect(elem.childNodes[1]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(3);
        }
      });

      it('should insert a node with children', () => {
        const insertedHTML = '<div4></div4><div5><div6>text</div6></div5>';
        htmlContent(elem, '<div1>

</div1><div2></div2><div3></div3>');
        const inserted = document.createElement('test');
        inserted.innerHTML = insertedHTML;
        elem.insertBefore(inserted, elem.childNodes[2]);

        expect(htmlContent(elem)).to.equal(`<div1><div></div></div1><div2></div2><test>${insertedHTML}</test><div3></div3>`);
        expect(elem.childNodes[2]).to.equal(inserted);

        if (type === 'host') {
          expect(slot.assignedNodes().length).to.equal(4);
        }
      });
    });
  }

  runTests('div');
  runTests('fragment');
  runTests('host');
  runTests('root');
  runTests('slot');
});