text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Microsoft.PlayerFramework.Samples.Common;
using Microsoft.PlayerFramework.Advertising;
using Microsoft.Media.Advertising;
using System.Threading;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Microsoft.PlayerFramework.Samples
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ProgrammaticAdPage : Page
    {
        private NavigationHelper navigationHelper;

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }
        AdHandlerPlugin adHandler;

        public ProgrammaticAdPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            adHandler = new AdHandlerPlugin();
            player.Plugins.Add(new AdHandlerPlugin());
            player.Markers.Add(new TimelineMarker() { Time = TimeSpan.FromSeconds(5), Type = "myAd" });
            player.MarkerReached += pf_MarkerReached;
        }

        async void pf_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
        {
            if (e.Marker.Type == "myAd")
            {
                var adSource = new RemoteAdSource() { Type = VastAdPayloadHandler.AdType, Uri = new Uri("http://smf.blob.core.windows.net/samples/win8/ads/vast_linear.xml") };
                //var adSource = new AdSource() { Type = DocumentAdPayloadHandler.AdType, Payload = SampleAdDocument };
                var progress = new Progress<AdStatus>();
                try
                {
                    await player.PlayAd(adSource, progress, CancellationToken.None);
                }
                catch { /* ignore */ }
            }
        }

        static AdDocumentPayload SampleAdDocument
        {
            get
            {
                var result = AdModelFactory.CreateAdDocumentPayload();
                var adPod = AdModelFactory.CreateAdPod();
                var ad = AdModelFactory.CreateAd();

                var companions = AdModelFactory.CreateCreativeCompanions();
                companions.Sequence = 1;
                var companion = AdModelFactory.CreateCompanion();
                companion.AdSlotId = "banner";
                var staticResource = AdModelFactory.CreateStaticResource();
                staticResource.CreativeType = "image/jpg";
                staticResource.Value = new Uri("http://smf.blob.core.windows.net/samples/win8/ads/media/6.jpg");
                companion.Item = staticResource;
                companions.Companions.Add(companion);
                ad.Creatives.Add(companions);

                var linear = AdModelFactory.CreateCreativeLinear();
                linear.Sequence = 1;
                var media = AdModelFactory.CreateMediaFile();

                media.Type = "video/x-ms-wmv";
                media.Value = new Uri("http://smf.blob.core.windows.net/samples/win8/ads/media/XBOX_HD_DEMO_700_2_000_700_4x3.wmv");

                linear.MediaFiles.Add(media);
                ad.Creatives.Add(linear);

                var nonlinears = AdModelFactory.CreateCreativeNonLinears();
                nonlinears.Sequence = 2;
                var nonlinear = AdModelFactory.CreateNonLinear();
                nonlinear.MinSuggestedDuration = TimeSpan.FromSeconds(5);
                var staticResource2 = AdModelFactory.CreateStaticResource();
                staticResource2.CreativeType = "image/jpg";
                staticResource2.Value = new Uri("http://smf.blob.core.windows.net/samples/win8/ads/media/1.jpg");
                nonlinear.Item = staticResource2;

                nonlinears.NonLinears.Add(nonlinear);
                ad.Creatives.Add(nonlinears);

                adPod.Ads.Add(ad);
                result.AdPods.Add(adPod);
                return result;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            backButton.Command = this.navigationHelper.GoBackCommand;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            player.Dispose();
            base.OnNavigatedFrom(e);
        }
    }
}


text:
#ifndef _LIBADT_LIST_COMMONS_H
#define _LIBADT_LIST_COMMONS_H

typedef void (*t_destroyfunc)(void *data);

enum list_insert_el_mode {
	HEAD,
	TAIL
};

typedef struct _list_root list_root;

typedef struct _list_node list_node;

struct _list_node;

struct _list_root {
	int size;			// Size of the list structure.
	t_destroyfunc destroyfunc;
	list_node *head;	// Position from where we start walking the list.
	list_node *tail;	// Last item on the list.
	enum list_insert_el_mode mode;
};

/*
 * Returns the size of the list.
 */
#define list_size(list) ((list) ->size)

#endif /* _LIBADT_LIST_COMMONS_H */

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe SpreeTwitterTestimony do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
package magpie.data.materials;

import java.io.File;
import java.io.PrintWriter;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Logan Ward
 */
public class ElementDatasetTest {

    @Test
    public void testClone() throws Exception {
        // Create a blank dataset
        ElementDataset data = new ElementDataset();
        data.addElementalPropertySet("general");
        data.addEntry("Fe");

        // Make an empty clone
        ElementDataset clone = data.emptyClone();
        assertEquals(0, clone.NEntries());
        clone.removeElementalProperty("AtomicNumber");
        assertNotEquals(data.getElementalProperties().size(),
                clone.getElementalProperties().size());

        // Make a regular clone
        clone = (ElementDataset) data.clone();
        assertEquals(data.NEntries(), clone.NEntries());
    }

    @Test
    public void testImport() throws Exception {
        // Create a sample input file
        File dataFile = File.createTempFile("magpie", "data");
        PrintWriter fo = new PrintWriter(dataFile);
        fo.println("element sln_energy valency{2+,3+,4+}");
        fo.println("Al\t0.78 3+");
        fo.println("Ni None 2+");
        fo.println("Fe 0.39 None");
        fo.close();

        // Read it in
        ElementDataset data = new ElementDataset();
        data.importText(dataFile.getCanonicalPath(), null);

        // Test results
        assertEquals(2, data.NProperties());
        assertArrayEquals("sln_energy valency".split(" "), data.getPropertyNames());
        assertArrayEquals("2+,3+,4+".split(","), data.getPropertyClasses("valency"));

        assertEquals(3, data.NEntries());
        assertEquals("Al", data.getEntry(0).toString());
        assertEquals(0.78, data.getEntry(0).getMeasuredProperty(0), 1e-5);
        assertEquals(0, data.getEntry(1).getMeasuredProperty(1), 1e-5);
        assertFalse(data.getEntry(2).hasMeasuredProperty(1));
    }

    @Test
    public void testAttributes() throws Exception {
        ElementDataset data = new ElementDataset();
        data.addElementalPropertySet("general");

        // Compute attributes
        data.generateAttributes();
        assertEquals(data.getElementalProperties().size(), data.NAttributes());
    }
}


text:
namespace YAF.Controls
{
  #region Using

  using System;

  using YAF.Core;
  using YAF.Types;

  #endregion

  /// <summary>
  /// The post options.
  /// </summary>
  public partial class PostOptions : BaseUserControl
  {
    #region Properties

    /// <summary>
    ///   Gets or sets a value indicating whether IsQuestionChecked.
    /// </summary>
    public bool IsQuestionChecked
    {
      get
      {
        return this.chkIsQuestion.Checked;
      }

      set
      {
        this.chkIsQuestion.Checked = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether IsQuestionVisible.
    /// </summary>
    public bool IsQuestionVisible
    {
      get
      {
        return this.liQuestion.Visible;
      }

      set
      {
        this.liQuestion.Visible = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether Persistent Checked.
    /// </summary>
    public bool PersistantChecked
    {
      get
      {
        return this.Persistency.Checked;
      }

      set
      {
        this.Persistency.Checked = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether Persistent Option Visible.
    /// </summary>
    public bool PersistentOptionVisible
    {
      get
      {
        return this.liPersistency.Visible;
      }

      set
      {
        this.liPersistency.Visible = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether Poll Option is Visible.
    /// </summary>
    public bool PollChecked
    {
      get
      {
        return this.AddPollCheckBox.Checked;
      }

      set
      {
        this.AddPollCheckBox.Checked = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether Poll Option is Visible.
    /// </summary>
    public bool PollOptionVisible
    {
      get
      {
        return this.liAddPoll.Visible;
      }

      set
      {
        this.liAddPoll.Visible = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether WatchChecked.
    /// </summary>
    public bool WatchChecked
    {
      get
      {
        return this.TopicWatch.Checked;
      }

      set
      {
        this.TopicWatch.Checked = value;
      }
    }

    /// <summary>
    ///   Gets or sets a value indicating whether WatchOptionVisible.
    /// </summary>
    public bool WatchOptionVisible
    {
      get
      {
        return this.liTopicWatch.Visible;
      }

      set
      {
        this.liTopicWatch.Visible = value;
      }
    }

    #endregion

    #region Methods

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
    {
    }

    #endregion
  }
}


text:
using System.Reflection;

[assembly: AssemblyProduct("Pegasus")]
[assembly: AssemblyCopyright("Copyright © 2018 John Gietzen")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]


text:
namespace sys {
class ComponentContext;
class OutgoingDirectory;
class ServiceDirectory;
}  // namespace sys

namespace base {

class FilteredServiceDirectory;

// Replaces the process-global sys::ComponentContext (as returned by the
// base::ComponentContextForProcess() function) with an empty instance which the
// calling test can configure, and restores the original when deleted.
//
// The test ComponentContext runs on the test main thread, which means that:
// - Tests using TestComponentContextForProcess must instantiate a
//   [SingleThread]TaskEnvironment with UI or IO main-thread-type.
// - If all services exposed via the test ComponentContext run on the test
//   main thread, and the code under test does as well, then RunUntilIdle() can
//   normally be used to "flush" any pending FIDL requests and related work.
//   Note that this is not true if any services, or code under test, use threads
//   or processes!
//
// The test ComponentContext is typically instantiated within a test body or
// test base-class:
//
//   TEST(MyFunkyTest, IsFunky) {
//     TestComponentContextForProcess test_context;
//     // Configure the |test_context|.
//     // Run tests of code that uses ComponentContextForProcess().
//   }
//
// By default created context doesn't expose any services. Services from the
// original process-global ComponentContext (usually the environment in which
// the test process is running), can be exposed through the |test_context| with
// AddServices(), during test setup:
//
//   test_context.AddServices({fuchsia::memorypressure::Provider::Name_, ...});
//   // ... Execute tests which use fuchsia.memorypressure.Provider ...
//
// Alternatively InitialState::kCloneAll can be passed to the constructor to
// expose all services listed in /svc, e.g.:
//
//   TestComponentContextForProcess test_context(
//       TestComponentContextForProcess::InitialState::kCloneAll);
//
// Fake/mock implementations can be exposed via additional_services():
//
//   ScopedServiceBinding<funky::Service> binding(
//       test_context.additional_services(), &funky_implementation);
//   // ... Execute tests which use funky.Service.
//
// Services published to the process' ComponentContext by code-under-test
// can be accessed via published_services():
//
//   funky::HamsterPtr hamster_service;
//   test_context.published_services()->Connect(hamster_service.NewRequest());
//   // ... Execute tests which exercise the funky.Hamster implementation.
//
class BASE_EXPORT TestComponentContextForProcess {
 public:
  enum class InitialState {
    kEmpty,
    kCloneAll,
  };

  explicit TestComponentContextForProcess(
      InitialState initial_state = InitialState::kEmpty);
  ~TestComponentContextForProcess();

  TestComponentContextForProcess(const TestComponentContextForProcess&) =
      delete;
  TestComponentContextForProcess& operator=(
      const TestComponentContextForProcess&) = delete;

  // Returns an OutgoingDirectory into which additional services may be
  // published for use by the code-under test.
  sys::OutgoingDirectory* additional_services();

  // Allows the specified service(s) from the original ComponentContext to be
  // exposed via the test default ComponentContext.
  void AddService(const base::StringPiece service);
  void AddServices(base::span<const base::StringPiece> services);

  // Returns the directory of services that the code under test has published
  // to its outgoing service directory.
  sys::ServiceDirectory* published_services() const {
    return published_services_.get();
  }

 private:
  std::unique_ptr<sys::ComponentContext> old_context_;

  std::unique_ptr<FilteredServiceDirectory> context_services_;
  std::unique_ptr<sys::ServiceDirectory> published_services_;
};

}  // namespace base

#endif  // BASE_FUCHSIA_TEST_COMPONENT_CONTEXT_FOR_PROCESS_H_


text:
@implementation OTTelephoneModifier

#pragma mark -
#pragma mark UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return [self stringIsLatin:string];
}

#pragma mark -
#pragma mark overriden methods

- (void) initTextField:(UITextField *) textField
{
    [super initTextField:textField];
    textField.keyboardType = UIKeyboardTypeNumberPad;
}

#pragma mark -

- (BOOL) stringIsLatin: (NSString*) string;
{
    int index;
    unichar aChar;
    for (index = 0; index < [string length]; index++)
    {
        aChar = [string characterAtIndex: index];
        if (!(aChar >= (unsigned int)'0' && aChar <= (unsigned int)'9'))
            return FALSE;
    }
    return TRUE;
}

#pragma mark -

- (NSString *) modifyTextField:(UITextField *) textField
{
    [self.delegate setValue:textField.text];
    return textField.text;
}

@end


text:
This is the homepage of Hann.

Content by Hann, theme by  [Yevgeniy Brikman](http://www.ybrikman.com).

## Key features
1. about
2. CV
3. Research with paper, video, presentation
4. some notes about study, tools & service, review on paper/book,
course

### Tools

* coding *

  [code editor](http://code.tutsplus.com/courses/perfect-workflow-in-sublime-text-2)

  [markdown with sublime](http://plaintext-productivity.net/2-04-how-to-set-up-sublime-text-for-markdown-editing.html)

  [latex with sublime]()

* cheet sheets *

  [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)

* Latex writing *

$\omega = d\phi / dt$.
$$I = \int \rho R^{2} dV$$

## Local setup

1. Use Git to clone this repo
2. Install [Jekyll](http://jekyllrb.com/docs/installation/) (requires Xcode Command-Line tools in mac)
`sudo gem install jekyll` (in the local folder)
(Just the first time: `sudo gem install bundler` and `bundle install`)
3. To build the site and serve it: `bundle exec jekyll serve`
4. To test: `http://localhost:4000`

See the [Jekyll](http://jekyllrb.com/) and [GitHub Pages](https://pages.github.com/)
documentation for more info.


text:
<?php

namespace PHPExiftool\Driver\Tag\MNG;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class TerminationAction extends AbstractTag
{

    protected $Id = 0;

    protected $Name = 'TerminationAction';

    protected $FullName = 'MNG::TerminationAction';

    protected $GroupName = 'MNG';

    protected $g0 = 'MNG';

    protected $g1 = 'MNG';

    protected $g2 = 'Image';

    protected $Type = 'int8u';

    protected $Writable = false;

    protected $Description = 'Termination Action';

    protected $Values = array(
        0 => array(
            'Id' => 0,
            'Label' => 'Show Last Frame',
        ),
        1 => array(
            'Id' => 1,
            'Label' => 'Display Nothing',
        ),
        2 => array(
            'Id' => 2,
            'Label' => 'Show First Frame',
        ),
        3 => array(
            'Id' => 3,
            'Label' => 'Repeat Sequence',
        ),
    );
}


text:
package com.miracle.framework.remote.netty.fixture.model;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class Foo implements Serializable {

	private static final long serialVersionUID = 2213133522077991039L;

	private String bar;
}


text:
<head>
	<meta charset="utf-8">
	<meta http-equiv="x-ua-compatible" content="ie=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Nalini Singh</title>

	<link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
	<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
	<link href='https://fonts.googleapis.com/css?family=Lora:400,300,700,800,600' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
	<link rel="shortcut icon" type="image/x-icon" href="assets/favicon.ico">

	<!-- Analytics -->
	<script>
		(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

		ga('create', 'UA-89463163-1', 'auto');
		ga('send', 'pageview');
	</script>
</head>


text:
'use strict';

// Implementation of Juttle built-in Math module.

var _ = require('underscore');
var errors = require('../errors');
var values = require('../values');
var seedrandom = require('seedrandom');
var round = require('./decimal-round');

function wrapMathFunction(name) {
    return function() {
        _.each(arguments, function(arg) {
            if (!values.isNumber(arg)) {
                throw errors.typeErrorFunction('Math.' + name, 'number', arg);
            }
        });

        return Math[name].apply(Math, Array.prototype.slice.call(arguments, 0));
    };
}

function wrapRoundFunction(name) {
    return function(value, digits) {
        if (!values.isNumber(value)) {
            throw errors.typeErrorFunction('Math.' + name, 'number', value);
        }
        if (digits !== undefined && !values.isNumber(digits)) {
            throw errors.typeErrorFunction('Math.' + name, 'number', digits);
        }
        return round[name + '10'](value, digits ? -digits : digits);
    };
}

var _random = Math.random; // juttle's global RNG

var seed = function(seed) {
    if (!values.isNumber(seed)) {
        throw errors.typeErrorFunction('Math.seed', 'number', seed);
    }
    _random = seedrandom(seed);
    return null;
};

var math = {
    abs:    wrapMathFunction('abs'),
    acos:   wrapMathFunction('acos'),
    asin:   wrapMathFunction('asin'),
    atan:   wrapMathFunction('atan'),
    atan2:  wrapMathFunction('atan2'),
    ceil:   wrapRoundFunction('ceil'),
    cos:    wrapMathFunction('cos'),
    exp:    wrapMathFunction('exp'),
    floor:  wrapRoundFunction('floor'),
    log:    wrapMathFunction('log'),
    max:    wrapMathFunction('max'),
    min:    wrapMathFunction('min'),
    pow:    wrapMathFunction('pow'),
    random: function() { return _random(); },
    round:  wrapRoundFunction('round'),
    sin:    wrapMathFunction('sin'),
    seed:   seed,
    sqrt:   wrapMathFunction('sqrt'),
    tan:    wrapMathFunction('tan')
};

module.exports = math;


text:
"""Commands for reading and manipulating VPN Gateways."""

from googlecloudsdk.calliope import base

class VpnTunnels(base.Group):
  """Read and manipulate Google Compute Engine VPN Tunnels."""

  # Placeholder to indicate that a detailed_help field exists and should
  # be set outside the class definition.
  detailed_help = None

VpnTunnels.detailed_help = {
    'brief': 'Read and manipulate Google Compute Engine VPN Tunnels'
}


text:
bone [![GoDoc](https://godoc.org/github.com/squiidz/bone?status.png)](http://godoc.org/github.com/go-zoo/bone) [![Build Status](https://travis-ci.org/go-zoo/bone.svg)](https://travis-ci.org/go-zoo/bone) [![Codeship Status for squiidz/bone](https://codeship.com/projects/172dae70-802a-0132-9038-321707412590/status?branch=master)](https://codeship.com/projects/57454)
=======

## What is bone ?

Bone is a lightweight and lightning fast HTTP Multiplexer for Golang. It support :

- URL Parameters
- REGEX Parameters
- Wildcard routes
- Router Prefix
- Sub Router, `mux.SubRoute()`, support most standard router (bone, gorilla/mux, httpRouter etc...)
- Http method declaration
- Support for `http.Handler` and `http.HandlerFunc`
- Custom NotFound handler
- Respect the Go standard `http.Handler` interface

![alt tag](https://c2.staticflickr.com/2/1070/540747396_5542b42cca_z.jpg)

## Speed

```
- BenchmarkBoneMux        10000000               118 ns/op
- BenchmarkZeusMux          100000               144 ns/op
- BenchmarkHttpRouterMux  10000000               134 ns/op
- BenchmarkNetHttpMux      3000000               580 ns/op
- BenchmarkGorillaMux       300000              3333 ns/op
- BenchmarkGorillaPatMux   1000000              1889 ns/op
```

 These test are just for fun, all these router are great and really efficient.
 Bone do not pretend to be the fastest router for every job.

## Example

``` go

package main

import(
  "net/http"

  "github.com/go-zoo/bone"
)

func main () {
  mux := bone.New()

  // mux.Get, Post, etc ... takes http.Handler
  mux.Get("/home/:id", http.HandlerFunc(HomeHandler))
  mux.Get("/profil/:id/:var", http.HandlerFunc(ProfilHandler))
  mux.Post("/data", http.HandlerFunc(DataHandler))

  // Support REGEX Route params
  mux.Get("/index/#id^[0-9]$", http.HandleFunc(IndexHandler))

  // Handle take http.Handler
  mux.Handle("/", http.HandlerFunc(RootHandler))

  // GetFunc, PostFunc etc ... takes http.HandlerFunc
  mux.GetFunc("/test", Handler)

  http.ListenAndServe(":8080", mux)
}

func Handler(rw http.ResponseWriter, req *http.Request) {
  // Get the value of the "id" parameters.
  val := bone.GetValue(req, "id")

  rw.Write([]byte(val))
}

```
## Changelog

#### Update 25 September 2015

- Add support for Sub router

Example :
``` go
func main() {
    mux := bone.New()
    sub := mux.NewRouter()

    sub.GetFunc("/test/example", func(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte("From sub router !"))
    })

    mux.SubRoute("/api", sub)

    http.ListenAndServe(":8080", mux)
}

```

#### Update 26 April 2015

- Add Support for REGEX parameters, using ` # ` instead of ` : `.
- Add Mux method ` mux.GetFunc(), mux.PostFunc(), etc ... `, takes ` http.HandlerFunc ` instead of ` http.Handler `.

Example :
``` go
func main() {
    mux.GetFunc("/route/#var^[a-z]$", handler)
}

func handler(rw http.ResponseWriter, req *http.Request) {
    bone.GetValue(req, "var")
}
```

#### Update 29 january 2015

- Speed improvement for url Parameters, from ```~ 1500 ns/op ``` to ```~ 1000 ns/op ```.

#### Update 25 december 2014

After trying to find a way of using the default url.Query() for route parameters, i decide to change the way bone is dealing with this. url.Query() is too slow for good router performance.
So now to get the parameters value in your handler, you need to use
` bone.GetValue(req, key) ` instead of ` req.Url.Query().Get(key) `.
This change give a big speed improvement for every kind of application using route parameters, like ~80x faster ...
Really sorry for breaking things, but i think it's worth it.

## TODO

- DOC
- More Testing
- Debugging
- Optimisation

## Contributing

1. Fork it
2. Create your feature branch (git checkout -b my-new-feature)
3. Write Tests!
4. Commit your changes (git commit -am 'Add some feature')
5. Push to the branch (git push origin my-new-feature)
6. Create new Pull Request

## License
MIT

## Links
- Blog post talking about bone : http://www.peterbe.com/plog/my-favorite-go-multiplexer

## Libs
- Errors dump for Go : [Trash](https://github.com/go-zoo/trash)
- Middleware Chaining module : [Claw](https://github.com/go-zoo/claw)


text:
package org.chamomile.ios.uikit;

import org.chamomile.ios.core.graphics.CGRect;

/*-[
#import "UIKit4J_common.h"
 ]-*/

/**
 * A horizontal control made of multiple segments, each segment functioning as a
 * discrete button.
 *
 * @author ggeorg
 */
public interface UISegmentedControl extends UIControl {
	final class UISegmentedControlFactory {
		static native UISegmentedControl create() /*-[
		//@formatter:off
			return [[UISegmentedControl alloc] init];
		//@formatter:on
		]-*/;

		static native UISegmentedControl createWithFrame(double x, double y, double width, double height) /*-[
		//@formatter:off
			return [[UISegmentedControl alloc] initWithFrame:CGRectMake((CGFloat)x, (CGFloat)y, (CGFloat)width, (CGFloat)height)];
		//@formatter:on
		]-*/;
	}

	// ---------------------------------------------------------------------
	// Initializing the Switch Object
	// ---------------------------------------------------------------------

	static UISegmentedControl create() {
		return UISegmentedControlFactory.create();
	}

	static UISegmentedControl createWithFrame(CGRect frame) {
		return UISegmentedControlFactory.createWithFrame(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
	}

	static UISegmentedControl createWithFrame(double x, double y, double width, double height) {
		return UISegmentedControlFactory.createWithFrame(x, y, width, height);
	}

	// TODO initWithCoder:
}


text:
package org.duracloud.mill.bit;

import org.duracloud.mill.bitlog.BitIntegrityResult;

/**
 * @author Daniel Bernstein
 * Date: May 15, 2014
 */
public class HandlerResult {
    private String message;
    private BitIntegrityResult result;
    private boolean handled = false;

    public HandlerResult() {
    }

    /**
     * @param result
     * @param message
     */
    public HandlerResult(BitIntegrityResult result, String message) {
        super();
        if (result == null) {
            throw new IllegalArgumentException("result must be non-null");
        }

        if (result.equals(BitIntegrityResult.FAILURE)
            || result.equals(BitIntegrityResult.ERROR)) {
            if (message == null) {
                throw new IllegalArgumentException(
                    "message must be non null in cases of error or failure.");
            }
        }
        this.result = result;
        this.message = message;
        handled = true;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @return the result
     */
    public BitIntegrityResult getResult() {
        return result;
    }

    /**
     * @return the handled
     */
    public boolean isHandled() {
        return handled;
    }
}


text:
// -----------------------------------------------------------------------
// Licensed to The .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// -----------------------------------------------------------------------

using System;
using System.Buffers.Binary;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Kerberos.NET.Client;
using Kerberos.NET.Credentials;
using Kerberos.NET.Crypto;
using Kerberos.NET.Entities;
using Kerberos.NET.Transport;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests.Kerberos.NET
{
    [TestClass]
    public class HttpKerberosTransportTests
    {
        [TestMethod]
        public async Task HttpsTransportReceivesSuccess()
        {
            var transport = new HandledHttpsKerberosTransport(new SuccessKdcMessageDelegatingHandler());
            transport.DomainPaths["adasdf"] = new Uri("https://test.internal/fake");

            var asReq = KrbAsReq.CreateAsReq(new KerberosPasswordCredential(UserUpn, "P@ssw0rd!"), AuthenticationOptions.Forwardable);

            var response = await transport.SendMessage<KrbAsRep>("adasdf", asReq.EncodeApplication());

            Assert.IsNotNull(response);

            transport.Dispose();
        }

        [TestMethod]
        [ExpectedException(typeof(HttpRequestException))]
        public async Task HttpsTransportReceivesFailure()
        {
            var transport = new HandledHttpsKerberosTransport(new FailureKdcMessageDelegatingHandler());
            transport.DomainPaths["adasdf"] = new Uri("https://test.internal/fake");

            var asReq = KrbAsReq.CreateAsReq(new KerberosPasswordCredential(UserUpn, "P@ssw0rd!"), AuthenticationOptions.Forwardable);

            await transport.SendMessage<KrbAsRep>("adasdf", asReq.EncodeApplication());

            transport.Dispose();
        }

        private class HandledHttpsKerberosTransport : HttpsKerberosTransport
        {
            private readonly DelegatingHandler handler;

            public HandledHttpsKerberosTransport(DelegatingHandler handler)
            {
                this.handler = handler;
            }

            protected override HttpClient Client => new HttpClient(this.handler);
        }

        internal static readonly byte[] TgtKey = new byte[]
        {
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        };

        private const string Realm = "corp.test.internal";
        private const string UserUpn = "user@test.internal";

        private class FailureKdcMessageDelegatingHandler : DelegatingHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var response = new HttpResponseMessage(HttpStatusCode.BadRequest);

                return Task.FromResult(response);
            }
        }

        private class SuccessKdcMessageDelegatingHandler : DelegatingHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var realmService = new FakeRealmService(Realm);
                var principal = realmService.Principals.Find(KrbPrincipalName.FromString(UserUpn));

                var principalKey = principal.RetrieveLongTermCredential();

                var rst = new ServiceTicketRequest
                {
                    Principal = principal,
                    EncryptedPartKey = principalKey,
                    ServicePrincipalKey = new KerberosKey(key: TgtKey, etype: EncryptionType.AES256_CTS_HMAC_SHA1_96)
                };

                var tgt = KrbAsRep.GenerateTgt(rst, realmService);

                var encoded = tgt.EncodeApplication();

                var response = new Memory<byte>(new byte[encoded.Length + 4]);
                BinaryPrimitives.WriteInt32BigEndian(response.Span.Slice(0, 4), encoded.Length);
                encoded.CopyTo(response.Slice(4));

                var kdcMessage = new KdcProxyMessage
                {
                    KerbMessage = response
                };

                return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(kdcMessage.Encode().ToArray())
                });
            }
        }
    }
}


text:
KDE (Plasma5) Frontend of Zku - integrated into KRunner

## License
Apache License 2.0

## Third Party License
Boost C++ Library - Boost Software License 1.0 (http://www.boost.org/LICENSE_1_0.txt)

Zkutils - (Source not released to public yet)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Vermicularia silphii Schwein.

### Remarks
null


text:
const rectangle = ({
  proto = {
    x: 1,
    y: 1,
    size: 1,
    rotation: '0deg'
  }, x, y, size, rotation }) => {

  const instance = Object.create(proto);
  if (x !== undefined) instance.x = x;
  if (y !== undefined) instance.y = y;
  if (size !== undefined) instance.size = size;
  if (rotation !== undefined) instance.rotation = rotation;

  return instance;
};

export default rectangle;


text:
package ru.stqa.pft.mantis.tests;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import ru.stqa.pft.mantis.appmanager.HttpSession;

public
class LoginTests extends TestBase{

@Test
  public void testLogin() throws IOException {
  HttpSession session = app.newSession();
  Assert.assertTrue(session.login("administrator", "root"));
  Assert.assertTrue(session.isLoggedInAs("administrator"));

}

}


text:
package net.automatalib.graphs;

import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;

import com.google.common.collect.Iterators;
import net.automatalib.graphs.concepts.NodeIDs;
import net.automatalib.graphs.helpers.SimpleNodeIDs;
import net.automatalib.visualization.DefaultVisualizationHelper;
import net.automatalib.visualization.VisualizationHelper;

/**
 * The finite version of a {@link IndefiniteSimpleGraph}.
 *
 * @param <N>
 *         node type
 *
 * @author Malte Isberner
 */
public interface SimpleGraph<N> extends IndefiniteSimpleGraph<N>, Iterable<N> {

    /**
     * Retrieves the number of nodes of this graph.
     *
     * @return the number of nodes of this graph.
     */
    default int size() {
        return getNodes().size();
    }

    /**
     * Retrieves an (unmodifiable) collection of the nodes in this graph.
     *
     * @return the nodes in this graph
     */
    Collection<N> getNodes();

    @Override
    default Iterator<N> iterator() {
        return Iterators.unmodifiableIterator(getNodes().iterator());
    }

    default Stream<N> nodesStream() {
        return getNodes().stream();
    }

    default NodeIDs<N> nodeIDs() {
        return new SimpleNodeIDs<>(this);
    }

    default VisualizationHelper<N, ?> getVisualizationHelper() {
        return new DefaultVisualizationHelper<>();
    }

    @Override
    default Graph<N, ?> asNormalGraph() {
        return new NormalGraphView<>(this);
    }

    class NormalGraphView<N, G extends SimpleGraph<N>> extends IndefiniteSimpleGraph.NormalGraphView<N, G>
            implements Graph<N, N> {

        public NormalGraphView(G simpleGraph) {
            super(simpleGraph);
        }

        @Override
        public int size() {
            return simpleGraph.size();
        }

        @Override
        public Collection<N> getNodes() {
            return simpleGraph.getNodes();
        }

        @Override
        public Iterator<N> iterator() {
            return simpleGraph.iterator();
        }

        @Override
        public Stream<N> nodesStream() {
            return simpleGraph.nodesStream();
        }

    }

}


text:
.. This file is licensed under the MIT License (MIT) available on
   http://opensource.org/licenses/MIT.

addnode
=======

``addnode "node" "add|remove|onetry"``

Attempts to add or remove a node from the addnode list.

Or try a connection to a node once.

Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be
full nodes/support SegWit as other outbound peers are (though such peers will not be synced from).

Argument #1 - node
~~~~~~~~~~~~~~~~~~

**Type:** string, required

The node (see getpeerinfo for nodes)

Argument #2 - command
~~~~~~~~~~~~~~~~~~~~~

**Type:** string, required

'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once

Examples
~~~~~~~~

.. highlight:: shell

::

  DeepOnion-cli addnode "192.168.0.6:9333" "onetry"

::

  curl --user myusername --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "addnode", "params": ["192.168.0.6:9333", "onetry"] }' -H 'content-type: text/plain;' http://127.0.0.1:9332/


text:
from __future__ import absolute_import

import os
import re
import json
import inspect
import requests
import mimetypes

from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime, timedelta
from django.conf import settings
from django.db import transaction
from docutils.core import publish_doctree
from pytz import utc
from random import randint
from six import StringIO

# Do not import from sentry here!  Bad things will happen

optional_group_matcher = re.compile(r"\(\?\:([^\)]+)\)")
named_group_matcher = re.compile(r"\(\?P<(\w+)>[^\)]+\)")
non_named_group_matcher = re.compile(r"\([^\)]+\)")
# [foo|bar|baz]
either_option_matcher = re.compile(r"\[([^\]]+)\|([^\]]+)\]")
camel_re = re.compile(r"([A-Z]+)([a-z])")
rst_indent_re = re.compile(r"^\s{2,}")
rst_block_re = re.compile(r"^\.\.\s[a-z]+::$")

API_PREFIX = "/api/0/"

scenarios = {}

def simplify_regex(pattern):
    """Clean up urlpattern regexes into something somewhat readable by
    Mere Humans: turns something like
    "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" into
    "{sport_slug}/athletes/{athlete_slug}/"
    """
    pattern = optional_group_matcher.sub(lambda m: "[%s]" % m.group(1), pattern)

    # handle named groups first
    pattern = named_group_matcher.sub(lambda m: "{%s}" % m.group(1), pattern)

    # handle non-named groups
    pattern = non_named_group_matcher.sub("{var}", pattern)

    # handle optional params
    pattern = either_option_matcher.sub(lambda m: m.group(1), pattern)

    # clean up any outstanding regex-y characters.
    pattern = (
        pattern.replace("^", "")
        .replace("$", "")
        .replace("?", "")
        .replace("//", "/")
        .replace("\\", "")
    )
    if not pattern.startswith("/"):
        pattern = "/" + pattern
    return pattern

def get_internal_endpoint_from_pattern(pattern):
    from sentry.api.base import Endpoint

    if not hasattr(pattern, "callback"):
        return
    if hasattr(pattern.callback, "cls"):
        cls = pattern.callback.cls
        if issubclass(cls, Endpoint):
            return cls
    elif hasattr(pattern.callback, "cls_instance"):
        inst = pattern.callback.cls_instance
        if isinstance(inst, Endpoint):
            return inst.__class__

def extract_documentation(func):
    doc = inspect.getdoc(func)
    if doc is not None:
        return doc.decode("utf-8")

def get_endpoint_path(internal_endpoint):
    return "%s.%s" % (internal_endpoint.__module__, internal_endpoint.__name__)

def parse_doc_string(doc):
    """
    Parse a docstring into a tuple.

    The tuple contains:

    (title, lines, warning, params)

    `lines` is a list for backwards compatibility with
    the JSON formatter.
    """
    title = None
    current_param = ""
    in_warning = False
    param_lines = []
    lines = []
    warning = []
    iterable = iter((doc or u"").splitlines())

    for line in iterable:
        stripped = line.strip()
        if title is None:
            if not line:
                continue
            title = line.strip()
        elif stripped and stripped[0] * len(stripped) == stripped:
            # is an RST underline
            continue
        elif rst_block_re.match(stripped):
            # Presently the only RST block we use is `caution` which
            # displays as a 'warning'
            in_warning = True
        elif line and stripped.startswith(":"):
            # Is a new parameter or other annotation
            if current_param:
                param_lines.append(current_param)
            current_param = stripped
        elif current_param:
            # Adding to an existing parameter annotation
            current_param = current_param + " " + stripped
        else:
            if in_warning:
                # If we're indented at least 2 spaces assume
                # we're in the RST block
                if rst_indent_re.match(line) or not line:
                    warning.append(stripped)
                    continue
                # An un-indented non-empty line means we
                # have other content.
                elif line:
                    in_warning = False
            # Normal text. We want empty lines here so we can
            # preserve paragraph breaks.
            lines.append(stripped)

    if current_param:
        param_lines.append(current_param)

    if warning:
        warning = "\n".join(warning).strip()
    if not warning:
        warning = None

    return title, lines, warning, parse_params(param_lines)

def get_node_text(nodes):
    """Recursively read text from a node tree."""
    text = []
    format_tags = {"literal": "`", "strong": "**", "emphasis": "*"}
    for node in nodes:
        # Handle inline formatting elements.
        if node.nodeType == node.ELEMENT_NODE and node.tagName in format_tags:
            wrap = format_tags[node.tagName]
            text.append(wrap + get_node_text(node.childNodes) + wrap)
            continue
        if node.nodeType == node.TEXT_NODE:
            text.append(node.data)
        if node.nodeType == node.ELEMENT_NODE:
            text.append(get_node_text(node.childNodes))
    return "".join(text)

def parse_params(params):
    """
    Parse parameter annotations.

    docutils doesn't give us much to work with, but
    we can get a DomDocument and traverse that for path parameters
    and query parameters, and layer on some text munging to get
    enough data to make the output we need.
    """
    parsed = defaultdict(list)
    param_tree = publish_doctree("\n".join(params)).asdom()
    field_names = param_tree.getElementsByTagName("field_name")
    field_values = param_tree.getElementsByTagName("field_body")

    for i, field in enumerate(field_names):
        name = get_node_text(field.childNodes)
        value = ""
        field_value = field_values.item(i)
        if field_value:
            value = get_node_text(field_value.childNodes)
        if name.startswith("pparam"):
            field_type = "path"
            name = name[7:]
        elif name.startswith("qparam"):
            field_type = "query"
            name = name[7:]
        elif name.startswith("auth"):
            field_type = "auth"
            name = ""
        else:
            field_type = "param"
            _, name = name.split(" ", 1)

        # Split out the parameter type
        param_type = ""
        if " " in name:
            param_type, name = name.split(" ", 1)
        parsed[field_type].append(dict(name=name, type=param_type, description=value))
    return parsed

def camelcase_to_dashes(string):
    def handler(match):
        camel, regular = match.groups()
        if len(camel) != 1:
            camel = camel[:-1].lower() + "-" + camel[-1].lower()
        else:
            camel = camel.lower()
        return "-" + camel + regular.lower()

    return camel_re.sub(handler, string).lstrip("-")

def extract_endpoint_info(pattern, internal_endpoint):
    path = simplify_regex(pattern.regex.pattern)
    from sentry.constants import HTTP_METHODS

    for method_name in HTTP_METHODS:
        if method_name in ("HEAD", "OPTIONS"):
            continue
        method = getattr(internal_endpoint, method_name.lower(), None)
        if method is None:
            continue
        doc = extract_documentation(method)
        if doc is None:
            continue
        section = getattr(internal_endpoint, "doc_section", None)
        if section is None:
            continue
        endpoint_name = method.__name__.title() + internal_endpoint.__name__
        if endpoint_name.endswith("Endpoint"):
            endpoint_name = endpoint_name[:-8]
        endpoint_name = camelcase_to_dashes(endpoint_name)
        title, text, warning, params = parse_doc_string(doc)
        yield dict(
            path=API_PREFIX + path.lstrip("/"),
            method=method_name,
            title=title,
            text=text,
            warning=warning,
            params=params,
            scenarios=getattr(method, "api_scenarios", None) or [],
            section=section.name.lower(),
            internal_path="%s:%s" % (get_endpoint_path(internal_endpoint), method.__name__),
            endpoint_name=endpoint_name,
        )

def iter_endpoints():
    from sentry.api.urls import urlpatterns

    for pattern in urlpatterns:
        internal_endpoint = get_internal_endpoint_from_pattern(pattern)
        if internal_endpoint is None:
            continue
        for endpoint in extract_endpoint_info(pattern, internal_endpoint):
            yield endpoint

def scenario(ident):
    def decorator(f):
        if ident in scenarios:
            raise RuntimeError("Scenario duplicate: %s" % ident)
        scenarios[ident] = f
        f.api_scenario_ident = ident
        return f

    return decorator

def attach_scenarios(scenarios):
    def decorator(f):
        f.api_scenarios = [x.api_scenario_ident for x in scenarios]
        return f

    return decorator

def iter_scenarios():
    # Make sure everything is imported.
    for endpoint in iter_endpoints():
        pass
    return iter(sorted(scenarios.items()))

def get_sections():
    from sentry.api.base import DocSection

    return dict((x.name.lower(), x.value) for x in DocSection)

def create_sample_time_series(event):
    from sentry.app import tsdb

    group = event.group

    now = datetime.utcnow().replace(tzinfo=utc)

    for _ in range(60):
        count = randint(1, 10)
        tsdb.incr_multi(
            ((tsdb.models.project, group.project.id), (tsdb.models.group, group.id)), now, count
        )
        tsdb.incr_multi(
            (
                (tsdb.models.organization_total_received, group.project.organization_id),
                (tsdb.models.project_total_received, group.project.id),
            ),
            now,
            int(count * 1.1),
        )
        tsdb.incr_multi(
            (
                (tsdb.models.organization_total_rejected, group.project.organization_id),
                (tsdb.models.project_total_rejected, group.project.id),
            ),
            now,
            int(count * 0.1),
        )
        now = now - timedelta(seconds=1)

    for _ in range(24 * 30):
        count = randint(100, 1000)
        tsdb.incr_multi(
            ((tsdb.models.project, group.project.id), (tsdb.models.group, group.id)), now, count
        )
        tsdb.incr_multi(
            (
                (tsdb.models.organization_total_received, group.project.organization_id),
                (tsdb.models.project_total_received, group.project.id),
            ),
            now,
            int(count * 1.1),
        )
        tsdb.incr_multi(
            (
                (tsdb.models.organization_total_rejected, group.project.organization_id),
                (tsdb.models.project_total_rejected, group.project.id),
            ),
            now,
            int(count * 0.1),
        )
        now = now - timedelta(hours=1)

class MockUtils(object):
    def create_user(self, mail):
        from sentry.models import User

        user, _ = User.objects.get_or_create(username=mail, defaults={"email": mail})
        user.set_password("dummy")
        user.save()
        return user

    def create_org(self, name, owner):
        from sentry.models import Organization, OrganizationMember

        org, _ = Organization.objects.get_or_create(name=name)

        dummy_member, _ = OrganizationMember.objects.get_or_create(
            user=owner, organization=org, defaults={"role": "owner"}
        )

        return org

    def create_api_token(self, user):
        from django.conf import settings
        from sentry.models import ApiToken

        return ApiToken.objects.create(
            user=user, scope_list=settings.SENTRY_SCOPES, refresh_token=None, expires_at=None
        )

    def create_client_key(self, project, label="Default"):
        from sentry.models import ProjectKey

        return ProjectKey.objects.get_or_create(project=project, label=label)[0]

    def create_team(self, name, org):
        from sentry.models import Team

        return Team.objects.get_or_create(name=name, defaults={"organization": org})[0]

    def join_team(self, team, user):
        from sentry.models import OrganizationMember, OrganizationMemberTeam

        member = OrganizationMember.objects.get(
            organization_id=team.organization_id, user_id=user.id
        )
        return OrganizationMemberTeam.objects.create(team=team, organizationmember=member)

    def create_project(self, name, teams, org):
        from sentry.models import Project

        project = Project.objects.get_or_create(name=name, defaults={"organization": org})[0]
        for team in teams:
            project.add_team(team)
        return project

    def create_release(self, project, user, version=None):
        from sentry.models import Release, Activity

        if version is None:
            version = os.urandom(20).encode("hex")
        with transaction.atomic():
            release = Release.objects.filter(
                version=version, organization_id=project.organization_id, projects=project
            ).first()
            if not release:
                release = Release.objects.filter(
                    version=version, organization_id=project.organization_id
                ).first()
                if not release:
                    release = Release.objects.create(
                        version=version, organization_id=project.organization_id
                    )
                release.add_project(project)
        Activity.objects.create(
            type=Activity.RELEASE,
            project=project,
            ident=Activity.get_version_ident(version),
            user=user,
            data={"version": version},
        )
        return release

    def create_release_file(self, project, release, path, content_type=None, contents=None):
        from sentry.models import File, ReleaseFile

        if content_type is None:
            content_type = mimetypes.guess_type(path)[0] or "text/plain"
            if content_type.startswith("text/"):
                content_type += "; encoding=utf-8"
        f = File.objects.create(
            name=path.rsplit("/", 1)[-1],
            type="release.file",
            headers={"Content-Type": content_type},
        )
        f.putfile(StringIO(contents or ""))
        return ReleaseFile.objects.create(
            organization_id=project.organization_id, release=release, file=f, name=path
        )

    def create_event(self, project, release, platform="python", raw=True):
        from sentry.utils.samples import create_sample_event

        event = create_sample_event(
            project=project, platform=platform, release=release.version, raw=raw
        )
        create_sample_time_series(event)
        return event

class Runner(object):
    """The runner is a special object that holds state for the automatic
    running of example scenarios.  It gets created by api-docs/generator.py
    which does the majority of the heavy lifting.  It mainly exists here
    so that the scenarios can be run separately if needed.
    """

    def __init__(self, ident, func, api_token, org, me, teams=None):
        self.ident = ident
        self.func = func
        self.requests = []

        self.utils = MockUtils()

        self.api_token = api_token
        self.org = org
        self.me = me
        self.teams = teams

    @property
    def default_team(self):
        return self.teams[0]["team"]

    @property
    def default_project(self):
        return self.teams[0]["projects"][0]["project"]

    @property
    def default_release(self):
        return self.teams[0]["projects"][0]["release"]

    @property
    def default_event(self):
        return self.teams[0]["projects"][0]["events"][0]

    @contextmanager
    def isolated_project(self, project_name):
        from sentry.models import Group, Event

        project = self.utils.create_project(project_name, teams=[self.default_team], org=self.org)
        release = self.utils.create_release(project=project, user=self.me)
        self.utils.create_event(project=project, release=release, platform="python")
        self.utils.create_event(project=project, release=release, platform="java")
        try:
            yield project
        finally:
            # Enforce safe cascades into Group/Event
            Group.objects.filter(project=project).delete()
            Event.objects.filter(project_id=project.id).delete()
            project.delete()

    @contextmanager
    def isolated_org(self, org_name):
        from sentry.models import Group, Event

        org = self.utils.create_org(org_name, owner=self.me)
        try:
            yield org
        finally:
            # Enforce safe cascades into Group/Event
            Group.objects.filter(project__organization=org).delete()
            Event.objects.filter(project_id__in=org.project_set.values("id")).delete()
            org.delete()

    def request(self, method, path, headers=None, data=None, api_token=None, format="json"):
        if api_token is None:
            api_token = self.api_token
        path = "/api/0/" + path.lstrip("/")
        headers = dict(headers or {})

        request_is_json = True
        body = None
        files = None
        was_multipart = False
        if data is not None:
            if format == "json":
                body = json.dumps(data, sort_keys=True)
                headers["Content-Type"] = "application/json"
            elif format == "multipart":
                files = {}
                for key, value in data.items():
                    if hasattr(value, "read") or isinstance(value, tuple):
                        files[key] = value
                        del data[key]
                        was_multipart = True
                body = data

        req_headers = dict(headers)
        req_headers["Host"] = "sentry.io"
        req_headers["Authorization"] = "Bearer %s" % api_token.token

        url = "http://127.0.0.1:%s%s" % (settings.SENTRY_APIDOCS_WEB_PORT, path)

        response = requests.request(
            method=method, url=url, files=files, headers=req_headers, data=body
        )
        response_headers = dict(response.headers)

        # Don't want those
        response_headers.pop("server", None)
        response_headers.pop("date", None)

        if response.headers.get("Content-Type") == "application/json":
            response_data = response.json()
            is_json = True
        else:
            response_data = response.text
            is_json = False

        if was_multipart:
            headers["Content-Type"] = response.request.headers["content-type"]
            data = response.request.body
            request_is_json = False

        rv = {
            "request": {
                "method": method,
                "path": path,
                "headers": headers,
                "data": data,
                "is_json": request_is_json,
            },
            "response": {
                "headers": response_headers,
                "status": response.status_code,
                "reason": response.reason,
                "data": response_data,
                "is_json": is_json,
            },
        }

        self.requests.append(rv)
        return rv

    def to_json(self):
        """Convert the current scenario into a dict
        """
        doc = extract_documentation(self.func)
        title, text, warning, params = parse_doc_string(doc)
        return {
            "ident": self.ident,
            "requests": self.requests,
            "title": title,
            "text": text,
            "params": params,
            "warning": warning,
        }


text:
var path = require('path'),
    fs = require('fs'),
    async = require('async'),
    crypto = require('crypto'),
    common = require('../common.js');

// remove temp content
common.reset();
fs.mkdirSync(common.temp);

// create 6 random files with equal length
var size = 1024*1024;
var buffer = crypto.randomBytes(size);

var files = ('abcdefghijkl').split('').map(function (value) {
  return path.resolve(common.temp, value + '.txt');
});

// Create the big files
files.forEach(function (filepath) {
  fs.writeFileSync(filepath, buffer);
});

// Read seperate files
function step1() {
  console.time('seperate files parallel');
  var query = files.slice(0, 5).map(function (filepath) {
    return function (callback) {
      var stream = fs.createReadStream(filepath);
      stream.on('close', callback);
    };
  });

  async.parallel(query, function () {
    console.timeEnd('seperate files parallel');
    step2();
  });
}

// Read seperate files
function step2() {
  console.time('seperate files series');
  var query = files.slice(5, 10).map(function (filepath) {
    return function (callback) {
      var stream = fs.createReadStream(filepath);
      stream.on('close', callback);
    };
  });

  async.series(query, function () {
    console.timeEnd('seperate files series');
    step3();
  });
}

function step3() {
  console.time('same files parallel');

  var query = [1,2,3,4,5].map(function () {
    return function (callback) {
      var stream = fs.createReadStream(files[10]);
      stream.on('close', callback);
    };
  });

  async.parallel(query, function () {
    console.timeEnd('same files parallel');
    step4();
  });
}

// Read seperate files
function step4() {
  console.time('same files series');

  var query = [1,2,3,4,5].map(function () {
    return function (callback) {
      var stream = fs.createReadStream(files[11]);
      stream.on('close', callback);
    };
  });

  async.series(query, function () {
    console.timeEnd('same files series');
  });
}

step1();


text:
/*                        __    __  __  __    __  ___
 *                       \  \  /  /    \  \  /  /  __/
 *                        \  \/  /  /\  \  \/  /  /
 *                         \____/__/  \__\____/__/.ɪᴏ
 * ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
 */
package io.vavr.collection;

import java.io.Serializable;
import java.util.Comparator;

/**
 * INTERNAL: Common {@code Comparator} related functions (not intended to be public).
 *
 * @author Daniel Dietrich
 */
final class Comparators {

    private Comparators() {
    }

    /**
     * Returns the natural comparator for type U, i.e. treating it as {@code Comparable<U>}.
     * The returned comparator is also {@code java.io.Serializable}.
     * <p>
     * Please note that this will lead to runtime exceptions, if U is not Comparable.
     *
     * @param <U> The type
     * @return The natural Comparator of type U
     */
    @SuppressWarnings("unchecked")
    static <U> Comparator<U> naturalComparator() {
        return NaturalComparator.instance();
    }

}

final class NaturalComparator<T> implements Comparator<T>, Serializable {

    private static final long serialVersionUID = 1L;

    private static final NaturalComparator<?> INSTANCE = new NaturalComparator<>();

    private NaturalComparator() {
    }

    @SuppressWarnings("unchecked")
    static <T> NaturalComparator<T> instance() {
        return (NaturalComparator<T>) INSTANCE;
    }

    @SuppressWarnings("unchecked")
    @Override
    public int compare(T o1, T o2) {
        return ((Comparable<T>) o1).compareTo(o2);
    }

    /**
     * Instance control for object serialization.
     *
     * @return The singleton instance of NaturalComparator.
     * @see java.io.Serializable
     */
    private Object readResolve() {
        return INSTANCE;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://www.springframework.org/schema/aop
                      http://www.springframework.org/schema/aop/spring-aop.xsd
                      http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context-4.0.xsd
                      http://www.springframework.org/schema/tx
                      http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!-- Enable Spring Annotation Configuration -->
	<context:annotation-config />

	<!-- Scan for all of Spring components such as Spring Service -->
	<context:component-scan base-package="com.sap.c4c.wechat.service"></context:component-scan>

	<!-- Necessary to get the entity manager injected into the factory bean -->
	<bean
		class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

	<!-- Define EclipseLink JPA Vendor Adapter -->
	<bean id="jpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
		<property name="databasePlatform"
			value="org.eclipse.persistence.platform.database.HANAPlatform" />
		<property name="generateDdl" value="false" />
		<property name="showSql" value="true" />
	</bean>

	<!-- Entity Manager Factory -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="persistence-with-jpa"></property>
		<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
	</bean>

	<!-- Transaction Manager -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<!-- Detect @Transactional -->
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>


text:
package org.pcsoft.framework.jcoding.jobject;

import org.pcsoft.framework.jcoding.jobject.type.JEnumerationReference;

/**
 * Descriptor for enumeration reference, create with {@link JEnumerationReferenceBuilder}
 */
public final class JEnumerationReferenceDescriptor extends JTypeReferenceDescriptor<JEnumerationReference> {

    JEnumerationReferenceDescriptor() {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

  <Preference
    android:key="enable_protection"
    android:title="@string/pref_enable_protect"/>
  <Preference
    android:enabled="true"
    android:key="enable_pin"
    android:title="@string/pref_security_pin"/>
  <Preference
    android:enabled="true"
    android:key="enable_pattern"
    android:title="@string/pref_security_pattern"/>

</PreferenceScreen>


text:
/**
 * Provides an SQL Injection protection against many kinds of attacks.
 */
(function() {
    var _config;
    var _patternSql  = [];
    var _blocker;
    var _logger;

    function SqlModule(config, blocker, logger) {
        _config = config;
        _blocker = blocker;
        _logger = logger;

        var _xemplar = require('xemplar');
        _patternSql.push(_xemplar.security.sql);
        //TODO (a big one) all these keywords could be packed in a better RegExp
        //_patternSql.push(/and/i); //TODO These keywords might appear in normal url
        //_patternSql.push(/or/i); //TODO These keywords might appear in normal url
        _patternSql.push(/SELECT/i);
        _patternSql.push(/UNION/i);
        _patternSql.push(/JOIN/i);
        _patternSql.push(/ORDER/i);
        _patternSql.push(/GROUP/i);
        _patternSql.push(/INSERT/i);
        //_patternSql.push(/UPDATE/i);
        _patternSql.push(/\/\*/i);
        _patternSql.push(/\*\//i);
        _patternSql.push(/--/i);
        _patternSql.push(/SUBSTRING/i);
        _patternSql.push(/SLEEP/i);
    }

    /**
     * Checks whether there is an SQL Injection Attack in the request.
     * Checks the url and the body.
     *
     * @param req request from host
     * @param res response to host
     * @param cb to get back to the app
     */
    SqlModule.prototype.check = function (req, res, cb) {
        _logger.log('Check SQL Injection');
        var _host = req.ip;

        if (req.method === 'GET' || req.method === 'DELETE') {
            checkGetOrDeleteRequest(req, res, cb);
        } else if (req.method === 'POST' || req.method === 'PUT') {
            checkPostOrPutRequest(req, res, cb);
        }

        function checkPostOrPutRequest(req, res, cb) {
            if (req.body) {
                for(var i in req.body) {
                    for(var j in _patternSql){
                        if (_patternSql[j].test(req.body[i]) && _blocker.blockHost) {
                            handleAttack();
                            cb = undefined;
                            break;
                        }
                    }
                    if(!cb){
                        break;
                    }
                }
            }
            if (cb) {
                cb();
            }
        }

        function checkGetOrDeleteRequest(req, res, cb) {
            var _url = req.url;
            for(var i in _patternSql){
                if (_patternSql[i].test(_url) && _blocker.blockHost) {
                    handleAttack();
                    cb = undefined;
                    break;
                }
            }
            if (cb) {
                cb();
            }
        }

        /**
         * Handles the attack by logging the host and blocking him.
         */
        function handleAttack() {
            _logger.logAttack('SQL Injection', _host);
            _blocker.blockHost(_host);
            res.status(403).end();
        }
    };

    module.exports = SqlModule;

})();


text:
var express = require('express');
var glob = require('glob');
var extend = require('node.extend');

var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var methodOverride = require('method-override');

var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);

var exphbs  = require('express-handlebars');

var flash = require('connect-flash');

module.exports = function (app, config) {
  var env = process.env.NODE_ENV || 'development';
  app.locals.ENV = env;
  app.locals.ENV_DEVELOPMENT = env == 'development';
  app.locals.GOOGLE_ANALYTICS_ID = config.google_analytics_id;

  //---------------------------
  // View/template engine - in this case Handlebars
  //---------------------------

  var hbs = exphbs.create({
    layoutsDir: config.root + '/app/views/layouts/',
    defaultLayout: 'main',
    partialsDir: [
      // partials just for the server-side
      config.root + '/app/views/partials/',

      // partials shared between the server-side and client-side
      config.root + '/app/views/shared_templates'
    ],

    // Specify helpers which are only registered on this instance.
    // they can be overwritten (or added more) in for a specific view inside the specific 'render' method
    //helpers: {
    //  global_helper: function () { return 'Global Helper'; },
    //  global_helper2: function () { return 'Global Helper 2'; }
    //},
    // or just defined all the  helpers inside another JavaScript file
    helpers: require('./../app/helpers')
  });

  app.engine('handlebars', hbs.engine);
  app.set('views', config.root + '/app/views');
  app.set('view engine', 'handlebars');

  // Middleware to expose the app's shared templates to the cliet-side of the app
  // for pages which need them.
  function exposeTemplates(req, res, next) {
    // Uses the `ExpressHandlebars` instance to get the get the **precompiled**
    // templates which will be shared with the client-side of the app.
    hbs.getTemplates(config.root + '/app/views/shared_templates', {
      cache      : app.enabled('view cache'),
      precompiled: true
    }).then(function (templates) {
      // RegExp to remove the ".handlebars" extension from the template names.
      var extRegex = new RegExp(hbs.extname + '$');

      // Creates an array of templates which are exposed via
      // `res.locals.templates`.
      templates = Object.keys(templates).map(function (name) {
        return {
          name    : name.replace(extRegex, ''),
          template: templates[name]
        };
      });

      // Exposes the templates during view rendering.
      if (templates.length) {
        res.locals.templates = templates;
      }

      setImmediate(next);
    })
      .catch(next);
  }
  app.exposeTemplates = exposeTemplates;

  //---------------------------
  //---------------------------
  //---------------------------

  // uncomment after placing your favicon in /public
  // the favicon is cached in memory - not read each time from the file
  //var favicon = require('serve-favicon');
  //app.use(favicon(config.root + '/public/favicon.ico'));

  // a simple logger middleware
  app.use(logger('dev'));

  // use the static middleware here before all the rest
  app.use(express.static(config.root + '/public'));

  // body-parsing middlewares
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
    extended: true
  }));

  // other useful middlewares
  app.use(cookieParser());
  app.use(compress());
  app.use(methodOverride());

  //---------------------------
  //---------------------------
  //---------------------------

  // add a session middleware and store the sessions in MongoDB

  // 1. First create the MongoDB connector
  var mongoStoreSession = new MongoDBStore({
    uri: config.db,
    collection: 'sessions'
  }, function (error) {
    // Should have gotten an error
  });

  // 2. Create the session middleware
  app.use(session(extend(true, {}, config.session, {
    // Force a cookie to be set on every response. This resets the expiration date.
    rolling: false,
    // Forces the session to be saved back to the session store, even if the session was never modified during the request
    resave: false,
    // Forces a session that is "uninitialized" to be saved to the store.
    // Choosing false is useful for implementing login sessions
    saveUninitialized: false,

    // use MongoDB
    store: mongoStoreSession
  })));

  //---------------------------
  //---------------------------
  //---------------------------

  // use connect-flash for flash messages stored in session
  app.use(flash());

  //---------------------------
  //---------------------------
  //---------------------------

  // add the passport middleware
  require('./passport')(app, config);

  //---------------------------
  //---------------------------
  //---------------------------

  // all other custom routes
  var routes = glob.sync(config.root + '/app/routes/*.js');
  routes.forEach(function (route) {
    require(route)(app, config, hbs);
  });

  //---------------------------
  //---------------------------
  //---------------------------

  // finally the error middlewares
  app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  });

  if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: err,
        title: 'error'
      });
    });
  } else {
    app.use(function (err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
      });
    });
  }

};


text:
const path = require('path');
const svgo = require('svgo');
const xmldom = require('@xmldom/xmldom');
const svgElementAttributes = require('svg-element-attributes');
const { omit, concat, uniqBy } = require('lodash');
const { merge } = require('webpack-merge');
const { VAR_NAMESPACE, VAR_NAMESPACE_VALUE, hasVariables, hasVarNamespace, addVarNamespace } = require('./variable-parser');

// Helpers
const idify = require('./helpers/idify');
const calculateY = require('./helpers/calculate-y');
const generateSpritePrefix = require('./helpers/generate-sprite-prefix');
const generateSVGOConfig = require('./helpers/generate-svgo-config');

// Errors
const { SpriteParsingWarning } = require('./errors');

const validSymbolAttributes = [
    ...svgElementAttributes['*'],
    ...svgElementAttributes.svg.filter(attr => svgElementAttributes.symbol.includes(attr))
];

const validViewAttributes = [
    ...svgElementAttributes['*'],
    ...svgElementAttributes.svg.filter(attr => svgElementAttributes.view.includes(attr))
];

const validUseAttributes = [
    ...svgElementAttributes['*'],
    ...svgElementAttributes.svg.filter(attr => svgElementAttributes.use.includes(attr))
];

module.exports = (sources = [], options = {}, warnings = []) => {
    options = merge({
        sprite: {
            prefix: '',
            idify: idify,
            gutter: 0,
            generate: {
                title: true,
                symbol: true,
                use: false,
                view: false
            }
        },
        output: {
            svg: {
                sizes: false
            },
            svgo: {
                plugins: []
            }
        },
        input: {
            patterns: []
        }
    }, options);

    // No point in generating when there are no files
    if ( !sources.length ) {
        return;
    }

    // Initialize DOM/XML/SVGO
    const DOMParser = new xmldom.DOMParser();
    const XMLSerializer = new xmldom.XMLSerializer();
    const XMLDoc = new xmldom.DOMImplementation().createDocument(null, null, null);

    // Create SVG element
    const svg = XMLDoc.createElement('svg');
    const sizes = {
        width: [],
        height: []
    };

    const formatPostfix = (value) => {
        if ( typeof value === 'string' ) {
            return value;
        }

        return '';
    };

    const getDocumentElement = (item) => {
        try {
            const sprite = DOMParser.parseFromString(item.sprite);
            const documentElement = sprite.documentElement;

            if (!documentElement) {
                warnings.push(new SpriteParsingWarning(`Sprite '${item.id}' has no documentElement.`));
                return;
            }

            return documentElement;
        } catch(error) {
            warnings.push(new SpriteParsingWarning(`Sprite '${item.id}' could not be parsed.\n${error}`));
        }
    }

    // Add namespaces
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');

    if ( options.sprite.generate.use ) {
        svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
    }

    const items = sources.map((source) => {
        const prefix = generateSpritePrefix(options.sprite.prefix, source.path);
        const id = `${prefix}${options.sprite.idify(path.basename(source.path, path.extname(source.path)))}`;

        if ( options.output.svgo === false ) {
            return {
                id: id,
                sprite: source.content
            };
        }

        const sprite = (() => {
            if ( hasVariables(source.content) && !hasVarNamespace(source.content) ) {
                return addVarNamespace(source.content);
            }

            return source.content;
        })();

        try {
            const config = generateSVGOConfig(merge({}, options.output.svgo, {
                path: source.path
            }), [],  [{
                name: 'removeEmptyAttrs',
                active: false // Prevent empty var:* attributes from getting removed prematurely
            }, {
                name: 'moveGroupAttrsToElems',
                active: false // Prevent groups from getting optimized prematurely as they may contain var:* attributes
            }, {
                name: 'collapseGroups',
                active: false // Prevent groups from getting removed prematurely as they may contain var:* attributes
            }, {
                name: 'removeTitle',
                active: false // Prevent titles from getting removed prematurely
            }]);
            const output = svgo.optimize(sprite, config);

            return {
                prefix: prefix,
                file: source.path,
                id: id,
                sprite: output.data
            };
        } catch (error) {
            warnings.push(new SpriteParsingWarning(`Sprite '${id}' could not be optimized.\n${error}`));
        }
    }).filter(Boolean)

    // Add the xmlns:var attribute when variables are found in any sprite
    if ( hasVariables(items.map((item) => item.sprite).join('\n')) ) {
        svg.setAttribute(`xmlns:${VAR_NAMESPACE}`, VAR_NAMESPACE_VALUE);
    }

    items.forEach((item) => {
        if (!item.sprite.trim()) {
            warnings.push(new SpriteParsingWarning(`Sprite '${item.id}' has an empty source file.`));
            return;
        }

        const documentElement = getDocumentElement(item);

        if (!documentElement) {
            return;
        }

        // Attributes that should be transferred to output SVG
        const attributes = Array.from(documentElement.attributes).reduce((attributes, attribute) => {
            // Blacklist several attributes as they'll be added/removed while parsing
            if ( ['viewbox', 'width', 'height', 'id', 'xmlns'].includes(attribute.name.toLowerCase()) ) {
                return attributes;
            }

            return [...attributes, {
                name: attribute.name,
                value: attribute.value
            }];
        }, []);

        // Add xmlns:* attributes to root SVG
        attributes.forEach((attribute) => {
            if ( !attribute.name.toLowerCase().startsWith('xmlns:') ) {
                return;
            }

            svg.setAttribute(attribute.name, attribute.value);
        });

        // Get sizes
        let viewbox = (documentElement.getAttribute('viewBox') || documentElement.getAttribute('viewbox')).split(' ').map((a) => parseFloat(a));
        let width = parseFloat(documentElement.getAttribute('width'));
        let height = parseFloat(documentElement.getAttribute('height'));

        if ( viewbox.length !== 4 && ( isNaN(width) || isNaN(height) ) ) {
            warnings.push(new SpriteParsingWarning(`Sprite '${item.id}' is invalid, it's lacking both a viewBox and width/height attributes.`));

            return;
        }

        if ( viewbox.length !== 4 ) {
            viewbox = [0, 0, width, height];
        }

        if ( isNaN(width) ) {
            width = viewbox[2];
        }

        if ( isNaN(height) ) {
            height = viewbox[3];
        }

        // Create symbol
        if ( options.sprite.generate.symbol ) {
            const symbol = XMLDoc.createElement('symbol');

            // Attributes
            attributes.forEach((attribute) => {
                if ( !validSymbolAttributes.includes(attribute.name) ) {
                    return;
                }

                symbol.setAttribute(attribute.name, attribute.value);
            });

            symbol.setAttribute('id', `${item.id}${formatPostfix(options.sprite.generate.symbol)}`);
            symbol.setAttribute('viewBox', viewbox.join(' '));
            if ( options.sprite.generate.title ) {
                // Make sure we don't overwrite the existing title
                const hasTitle = (documentElement) => {
                    const titles = Array.from(documentElement.childNodes).filter((childNode) => {
                        return childNode.nodeName.toLowerCase() === 'title';
                    });

                    return !!titles.length;
                };

                // Add title to improve accessibility
                if ( !hasTitle(documentElement) ) {
                    const title = XMLDoc.createElement('title');
                    title.appendChild(XMLDoc.createTextNode(item.id.replace(item.prefix, '')));
                    symbol.appendChild(title);
                }
            }

            // Clone the original contents of the SVG file into the new symbol
            Array.from(documentElement.childNodes).forEach((childNode) => {
                symbol.appendChild(childNode);
            });

            svg.appendChild(symbol);
        }

        if ( options.sprite.generate.use ) {
            // Generate <use> elements within spritemap to allow usage within CSS
            const use = XMLDoc.createElement('use');
            const y = calculateY(sizes.height, options.sprite.gutter);

            // Attributes
            attributes.forEach((attribute) => {
                if ( !validUseAttributes.includes(attribute.name) ) {
                    return;
                }

                use.setAttribute(attribute.name, attribute.value);
            });

            use.setAttribute('xlink:href', `#${item.id}${formatPostfix(options.sprite.generate.symbol)}`);
            use.setAttribute('x', '0');
            use.setAttribute('y', y);
            use.setAttribute('width', width.toString());
            use.setAttribute('height', height.toString());
            svg.appendChild(use);
        }

        if ( options.sprite.generate.view ) {
            // Generate <view> elements within spritemap to allow usage within CSS
            const view = XMLDoc.createElement('view');
            const y = calculateY(sizes.height, options.sprite.gutter);

            // Attributes
            attributes.forEach((attribute) => {
                if ( !validViewAttributes.includes(attribute.name) ) {
                    return;
                }

                view.setAttribute(attribute.name, attribute.value);
            });

            view.setAttribute('id', `${item.id}${formatPostfix(options.sprite.generate.view)}`);
            view.setAttribute('viewBox', `0 ${Math.max(0, y - (options.sprite.gutter / 2))} ${width + (options.sprite.gutter / 2)} ${height + (options.sprite.gutter / 2)}`);
            svg.appendChild(view);
        }

        // Update sizes
        sizes.width.push(width);
        sizes.height.push(height);
    });

    if ( options.output.svg.sizes ) {
        // Add width/height to spritemap
        svg.setAttribute('width', Math.max.apply(null, sizes.width).toString());
        svg.setAttribute('height', (sizes.height.reduce((a, b) => a + b, 0) + ((sizes.height.length - 1) * options.sprite.gutter)).toString());
    }

    // Add custom attributes to spritemap
    Object.entries(options.output.svg.attributes).forEach(([name, value]) => {
        svg.setAttribute(name, value);
    });

    return XMLSerializer.serializeToString(svg);
};


text:
<ion-header id="about-header">
    <ion-navbar color="primary">
        <ion-title>About</ion-title>
    </ion-navbar>
</ion-header>
<ion-content id="about-content">

Hi there!

        My name is Tom Aalbers. I am a reasonable experienced developer (full stack) in the Ionic, Aurelia and .NET frameworks. I
        work with these frameworks every day.

        A long time ago I started the Ionic 2 Examples repo which into, I added a few examples on how to work
        with the Ionic Framework. I received a lot of positive feedback and requests after that. So that is why I started
        this ionic example app to show some examples on how to use the framework. If you want to get in touch you can head
        over to my website and contact me through any of the options there. If you can't
        find your example, head over to the github page and create an issue to request
        it! I will try to add them when I can!

</ion-content>


text:
package ssim

// A SelectableEventWriter is an EventWriter that
// is easier to write to from a select statement.
type SelectableEventWriter interface {
	Write() chan<- Event
}

// A SelectableEventEmitter is an EventEmitter that
// is easier to subscribe to from a select statement.
type SelectableEventEmitter interface {
	Subscribe() chan<- EventWriter
}

// A SelectableEventStream is an EventStream that
// is easier to use from a select statement.
type SelectableEventStream interface {
	SelectableEventWriter
	SelectableEventEmitter
	HaltStream() EventStream
}

type eventStreamHaltReq struct {
	hasHalted chan<- EventStream
}

type syncedEventStream struct {
	in   chan<- Event
	subs chan<- EventWriter

	halt chan<- eventStreamHaltReq
}

func (s syncedEventStream) Write() chan<- Event {
	return s.in
}

func (s syncedEventStream) Subscribe() chan<- EventWriter {
	return s.subs
}

func (s syncedEventStream) HaltStream() EventStream {
	stream := make(chan EventStream)
	s.halt <- eventStreamHaltReq{stream}
	return <-stream
}

// NewSyncedEventStream starts a go routine that synchronizes
// access to an EventStream. It returns an interface that is
// friendly to usage from a select statement.
func NewSyncedEventStream(stream EventStream) SelectableEventStream {
	var (
		sync syncedEventStream

		in   <-chan Event
		subs <-chan EventWriter
		halt <-chan eventStreamHaltReq
	)

	closeChans := func() func() {
		var (
			inCh   = make(chan Event)
			subsCh = make(chan EventWriter)
			haltCh = make(chan eventStreamHaltReq)
		)

		sync.in, in = inCh, inCh
		sync.subs, subs = subsCh, subsCh
		sync.halt, halt = haltCh, haltCh

		return func() {
			close(inCh)
			close(subsCh)
			close(haltCh)
		}
	}()

	go func() {
		var haltReq eventStreamHaltReq

	communication:
		for {
			select {
			case e := <-in:
				stream.Write(e)

			case w := <-subs:
				stream.Subscribe(w)

			case haltReq = <-halt:
				break communication
			}
		}

		closeChans()
		haltReq.hasHalted <- stream
	}()

	return sync
}


text:
namespace AngleSharp.Dom
{
    using AngleSharp.Html.Dom;
    using AngleSharp.Text;
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Provides a number of methods for performing operations that are
    /// independent of any particular instance of the DOM.
    /// </summary>
    sealed class DomImplementation : IImplementation
    {
        #region Features

        static readonly Dictionary<String, String[]> features = new Dictionary<String, String[]>(StringComparer.OrdinalIgnoreCase)
        {
            { "XML", new[] { "1.0", "2.0" } },
            { "HTML", new[] { "1.0", "2.0" } },
            { "Core", new[] { "2.0" } },
            { "Views", new[] { "2.0" } },
            { "StyleSheets", new[] { "2.0" } },
            { "CSS", new[] { "2.0" } },
            { "CSS2", new[] { "2.0" } },
            { "Traversal", new[] { "2.0" } },
            { "Events", new[] { "2.0" } },
            { "UIEvents", new[] { "2.0" } },
            { "HTMLEvents", new[] { "2.0" } },
            { "Range", new[] { "2.0" } },
            { "MutationEvents", new[] { "2.0" } },
        };

        #endregion

        #region Fields

        readonly Document _owner;

        #endregion

        #region ctor

        public DomImplementation(Document owner)
        {
            _owner = owner;
        }

        #endregion

        #region Methods

        public IDocumentType CreateDocumentType(String qualifiedName, String publicId, String systemId)
        {
            if (qualifiedName is null)
            {
                throw new ArgumentNullException(nameof(qualifiedName));
            }

            if (!qualifiedName.IsXmlName())
            {
                throw new DomException(DomError.InvalidCharacter);
            }

            if (!qualifiedName.IsQualifiedName())
            {
                throw new DomException(DomError.Namespace);
            }

            return new DocumentType(_owner, qualifiedName)
            {
                PublicIdentifier = publicId,
                SystemIdentifier = systemId
            };
        }

        public IDocument CreateHtmlDocument(String title)
        {
            var document = new HtmlDocument();
            document.AppendChild(new DocumentType(document, TagNames.Html));
            document.AppendChild(document.CreateElement(TagNames.Html));
            document.DocumentElement.AppendChild(document.CreateElement(TagNames.Head));

            if (!String.IsNullOrEmpty(title))
            {
                var titleElement = document.CreateElement(TagNames.Title);
                titleElement.AppendChild(document.CreateTextNode(title));
                document.Head!.AppendChild(titleElement);
            }

            document.DocumentElement.AppendChild(document.CreateElement(TagNames.Body));
            document.BaseUrl = _owner.BaseUrl;
            return document;
        }

        public Boolean HasFeature(String feature, String? version = null)
        {
            if (feature is null)
            {
                throw new ArgumentNullException(nameof(feature));
            }

            if (features.TryGetValue(feature, out var versions))
            {
                return versions.Contains(version ?? String.Empty, StringComparison.OrdinalIgnoreCase);
            }

            return false;
        }

        #endregion
    }
}


text:
using Microsoft.Practices.Prism.Mvvm;
using System;
using System.Linq;
using Calculateur.Backend;

namespace Calculateur.ViewModel
{
    internal class SavingThrow : BindableBase
    {
        private Character character;

        public int Willpower
        {
            get
            {
                if (character == null)
                    return 0;
                return 2
                       + character.GetTalent("Volonté").Level
                       + Math.Max(character.GetAspectValue(Aspect.Arcane), character.GetAspectValue(Aspect.Feu))/2;
            }
        }

        public int Robustesse
        {
            get
            {
                if (character == null)
                    return 0;
                return 2
                       + character.GetTalent("Endurance").Level
                       + Math.Max(character.GetAspectValue(Aspect.Acier), character.GetAspectValue(Aspect.Terre)) / 2;
            }
        }

        public int Reflex
        {
            get
            {
                if (character == null)
                    return 0;
                return 2
                       + character.GetTalent("Esquive").Level
                       + Math.Max(character.GetAspectValue(Aspect.Eau), character.GetAspectValue(Aspect.Vent)) / 2;
            }
        }

        public int WillpowerAjust
        {
            get { return WillpowerAjustBase + WillpowerAjustBonus; }
        }

        public int WillpowerAjustBase
        {
            get
            {
                if (character == null)
                    return 0;
                return (Math.Max(character.GetAspectValue(Aspect.Arcane), character.GetAspectValue(Aspect.Feu))
                        + 1)/2;
            }
        }

        public int WillpowerAjustBonus
        {
            get
            {
                if (character == null)
                    return 0;
                int bonus = 0;
                if (character.getClasse() != null)
                    bonus = character.getClasse().GetSaveBonus(character.GetLevel(), "Volonté");
                return bonus;
            }
        }

        public int ReflexeAjust
        {
            get { return ReflexeAjustBase + ReflexeAjustBonus; }
        }

        public int ReflexeAjustBase
        {
            get
            {
                if (character == null)
                    return 0;
                return (Math.Max(character.GetAspectValue(Aspect.Eau), character.GetAspectValue(Aspect.Vent))
                    +1)/2;
            }
        }

        public int ReflexeAjustBonus
        {
            get
            {
                if (character == null)
                    return 0;
                int bonus = 0;
                if (character.getClasse() != null)
                    bonus = character.getClasse().GetSaveBonus(character.GetLevel(), "Réflexe");
                return bonus;
            }
        }

        public int RobustAjust
        {
            get { return RobustAjustBase + RobustAjustBonus; }
        }

        public int RobustAjustBase
        {
            get
            {
                if (character == null)
                    return 0;
                return (Math.Max(character.GetAspectValue(Aspect.Acier), character.GetAspectValue(Aspect.Terre))
                    +1)/2;
            }
        }

        public int RobustAjustBonus
        {
            get
            {
                if (character == null)
                    return 0;
                int bonus = 0;
                if (character.getClasse() != null)
                    bonus = character.getClasse().GetSaveBonus(character.GetLevel(), "Robustesse");
                return bonus;
            }
        }

        public SavingThrow()
        {
            CharacterManager.CharacterChanged += CharacterManager_OnCharacterChanged;
        }

        private void CharacterManager_OnCharacterChanged(Character caller)
        {
            character = caller;
            if (character != null)
                character.PAChanged += CharacterOnPAChanged;
            OnPropertyChanged(null);
        }

        private void CharacterOnPAChanged(Character caller)
        {
            OnPropertyChanged(null);
        }
    }
}