text:
#ifndef FLAGS_H_
#define FLAGS_H_

#include <algorithm>
#include <array>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>

namespace flags {
namespace detail {
using argument_map =
    std::unordered_map<std::string_view, std::optional<std::string_view>>;

// Non-destructively parses the argv tokens.
// * If the token begins with a -, it will be considered an option.
// * If the token does not begin with a -, it will be considered a value for the
// previous option. If there was no previous option, it will be considered a
// positional argument.
struct parser {
  parser(const int argc, char** argv) {
    for (int i = 1; i < argc; ++i) {
      churn(argv[i]);
    }
    // If the last token was an option, it needs to be drained.
    flush();
  }
  parser& operator=(const parser&) = delete;

  const argument_map& options() const { return options_; }
  const std::vector<std::string_view>& positional_arguments() const {
    return positional_arguments_;
  }

 private:
  // Advance the state machine for the current token.
  void churn(const std::string_view& item) {
    item.at(0) == '-' ? on_option(item) : on_value(item);
  }

  // Consumes the current option if there is one.
  void flush() {
    if (current_option_) on_value();
  }

  void on_option(const std::string_view& option) {
    // Consume the current_option and reassign it to the new option while
    // removing all leading dashes.
    flush();
    current_option_ = option;
    current_option_->remove_prefix(current_option_->find_first_not_of('-'));

    // Handle a packed argument (--arg_name=value).
    if (const auto delimiter = current_option_->find_first_of('=');
        delimiter != std::string_view::npos) {
      auto value = *current_option_;
      value.remove_prefix(delimiter + 1 /* skip '=' */);
      current_option_->remove_suffix(current_option_->size() - delimiter);
      on_value(value);
    }
  }

  void on_value(const std::optional<std::string_view>& value = std::nullopt) {
    // If there's not an option preceding the value, it's a positional argument.
    if (!current_option_) {
      if (value) positional_arguments_.emplace_back(*value);
      return;
    }
    // Consume the preceding option and assign its value.
    options_.emplace(*current_option_, value);
    current_option_.reset();
  }

  std::optional<std::string_view> current_option_;
  argument_map options_;
  std::vector<std::string_view> positional_arguments_;
};

// If a key exists, return an optional populated with its value.
inline std::optional<std::string_view> get_value(
    const argument_map& options, const std::string_view& option) {
  if (const auto it = options.find(option); it != options.end()) {
    return it->second;
  }
  return std::nullopt;
}

// Coerces the string value of the given option into <T>.
// If the value cannot be properly parsed or the key does not exist, returns
// nullopt.
template <class T>
std::optional<T> get(const argument_map& options,
                     const std::string_view& option) {
  if (const auto view = get_value(options, option)) {
    if (T value; std::istringstream(std::string(*view)) >> value) return value;
  }
  return std::nullopt;
}

// Since the values are already stored as strings, there's no need to use `>>`.
template <>
inline std::optional<std::string_view> get(const argument_map& options,
                                    const std::string_view& option) {
  return get_value(options, option);
}

template <>
inline std::optional<std::string> get(const argument_map& options,
                               const std::string_view& option) {
  if (const auto view = get<std::string_view>(options, option)) {
    return std::string(*view);
  }
  return std::nullopt;
}

// Special case for booleans: if the value is any of the below, the option will
// be considered falsy. Otherwise, it will be considered truthy just for being
// present.
constexpr std::array<const char*, 5> falsities{{"0", "n", "no", "f", "false"}};
template <>
inline std::optional<bool> get(const argument_map& options,
                        const std::string_view& option) {
  if (const auto value = get_value(options, option)) {
    return std::none_of(falsities.begin(), falsities.end(),
                        [&value](auto falsity) { return *value == falsity; });
  }
  if (options.find(option) != options.end()) return true;
  return std::nullopt;
}

// Coerces the string value of the given positional index into <T>.
// If the value cannot be properly parsed or the key does not exist, returns
// nullopt.
template <class T>
std::optional<T> get(const std::vector<std::string_view>& positional_arguments,
                     size_t positional_index) {
  if (positional_index < positional_arguments.size()) {
    if (T value; std::istringstream(
                     std::string(positional_arguments[positional_index])) >>
                 value)
      return value;
  }
  return std::nullopt;
}

// Since the values are already stored as strings, there's no need to use `>>`.
template <>
inline std::optional<std::string_view> get(
    const std::vector<std::string_view>& positional_arguments,
    size_t positional_index) {
  if (positional_index < positional_arguments.size()) {
    return positional_arguments[positional_index];
  }
  return std::nullopt;
}

template <>
inline std::optional<std::string> get(
    const std::vector<std::string_view>& positional_arguments,
    size_t positional_index) {
  if (positional_index < positional_arguments.size()) {
    return std::string(positional_arguments[positional_index]);
  }
  return std::nullopt;
}
}  // namespace detail

struct args {
  args(const int argc, char** argv) : parser_(argc, argv) {}

  template <class T>
  std::optional<T> get(const std::string_view& option) const {
    return detail::get<T>(parser_.options(), option);
  }

  template <class T>
  T get(const std::string_view& option, T&& default_value) const {
    return get<T>(option).value_or(default_value);
  }

  template <class T>
  std::optional<T> get(size_t positional_index) const {
    return detail::get<T>(parser_.positional_arguments(), positional_index);
  }

  template <class T>
  T get(size_t positional_index, T&& default_value) const {
    return get<T>(positional_index).value_or(default_value);
  }

  const std::vector<std::string_view>& positional() const {
    return parser_.positional_arguments();
  }

 private:
  const detail::parser parser_;
};

}  // namespace flags

#endif  // FLAGS_H_


text:
This library provides [Hamcrest](https://github.com/hamcrest/JavaHamcrest/)
matchers for [Querydsl](https://github.com/querydsl/querydsl/). In particular,
the following matchers for query results are included:

- `hasResultSize`
- `hasColumnRange`
- `hasColumnMax`
- `hasColumnMin`
- `hasColumnContainingAll`
- `hasColumnContainingAny`

## Installation

Just add the following dependency to your `pom.xml`:

```xml
<dependency>
    <groupId>com.ibm</groupId>
    <artifactId>hamcrest-querydsl</artifactId>
    <version>1.0</version>
    <scope>test</scope>
</dependency>
```

## Usage

To use the matchers, add the following static import to your test class:

```Java
import static com.ibm.hamcrest.querydsl.Matchers.*;
```

## Examples

The examples are given using the collections back-end (querydsl-collections),
but the matchers work seamlessly for the SQL, JPA, and JDO back-ends.

Assume that you have a collection of cats with names and ages:

```Java
List<Cat> cats = Arrays.asList(
        new Cat("Kitty", 5),
        new Cat("Smokey", 2),
        new Cat("Princess", 4),
        new Cat("Oreo", 3),
        new Cat("Lucky", 7));
```

Then, a query to select all the cats is:

```Java
Cat c = alias(Cat.class), "cat"); // required for the collections back-end
CollQuery q = from($(c), cats);
```

### hasResultSize

Matches the size of the query results:

```Java
assertThat(q, hasResultSize(5));
```

It can be combined with other matchers:

```Java
assertThat(q, hasResultSize(greaterThan(1)));
assertThat(q, hasResultSize(lessThan(10)));
assertThat(q, hasResultSize(not(0)));
```

The query can have arbitrary conditions:

```Java
assertThat(q.where($(c.getAge()).gt(3)), hasResultSize(3));
```

In case of an assertion error (e.g., `assertThat(q, hasResultSize(4));`), a meaningful
message is printed:

```
Expected: query results with size of <4>
but: actual size was <5>
```

### hasColumnRange

Matches the range of a column in the query results:

```Java
assertThat(q, hasColumnRange($(c.getAge()), 2, 7));
```

### hasColumnMax

Matches the maximum value of a column in the query results:

```Java
assertThat(q, hasColumnMax($(c.getAge()), 7));
assertThat(q, hasColumnMax($(c.getAge()), greaterThan(6)));
assertThat(q.where($(c.getAge()).lt(5)), hasColumnMax($(c.getAge()), 4));
```

### hasColumnMin

Matches the minimum value of a column in the query results:

```Java
assertThat(q, hasColumnMin($(c.getAge()), 2));
assertThat(q, hasColumnMin($(c.getAge()), greaterThan(1)));
assertThat(q.where($(c.getAge()).gt(3)), hasColumnMin($(c.getAge()), 4));
```

### hasColumnContainingAll

Checks whether a column in the query results contains all of the listed values:

```Java
assertThat(q, hasColumnContainingAll($(c.getName()), "Oreo"));
assertThat(q, hasColumnContainingAll($(c.getName()), "Oreo", "Kitty", "Smokey"));
assertThat(q.where($(c.getAge()).lt(6)), hasColumnContainingAll($(c.getName()), "Oreo", "Kitty", "Smokey"));
```

In addition to varargs, an Iterable of the required values can be passed:

```Java
assertThat(q, hasColumnContainingAll($(c.getName()), Arrays.asList("Oreo")));
assertThat(q, hasColumnContainingAll($(c.getName()), Arrays.asList("Oreo", "Kitty", "Smokey")));
assertThat(q.where($(c.getAge()).lt(6)), hasColumnContainingAll($(c.getName()), Arrays.asList("Oreo", "Kitty", "Smokey")));
```

### hasColumnContainingAny

Checks whether a column in the query results contains any of the listed values:

```Java
assertThat(q, hasColumnContainingAny($(c.getName()), "Oreo"));
assertThat(q, hasColumnContainingAny($(c.getName()), "Oreo", "Kitty", "Smokey"));
assertThat(q, hasColumnContainingAny($(c.getName()), "Oreo", "Schrodinger's"));
assertThat(q.where($(c.getAge()).lt(4)), hasColumnContainingAny($(c.getName()), "Oreo", "Kitty", "Smokey"));
```

Similarly to hasColumnContainingAll, this matcher supports Iterables:

```Java
assertThat(q, hasColumnContainingAny($(c.getName()), Arrays.asList("Oreo")));
assertThat(q, hasColumnContainingAny($(c.getName()), Arrays.asList("Oreo", "Kitty", "Smokey")));
assertThat(q, hasColumnContainingAny($(c.getName()), Arrays.asList("Oreo", "Schrodinger's")));
assertThat(q.where($(c.getAge()).lt(4)), hasColumnContainingAny($(c.getName()), Arrays.asList("Oreo", "Kitty", "Smokey")));
```

Suggestions for new matchers are welcome!

## Author

The project has been developed by [Anton Beloglazov](http://beloglazov.info/).

For more open-source projects from IBM, head over to (http://ibm.github.io).

## Copyright and license

© Copyright IBM Corporation 2014. Distributed under the [Apache 2.0 license](LICENSE).

redpajama_set_name: RedPajamaGithub


text:
[![Analytics](https://ga-beacon.appspot.com/UA-8535255-2/unosquare/embedio/)](https://github.com/igrigorik/ga-beacon)
 [![Build Status](https://travis-ci.org/unosquare/embedio.svg?branch=master)](https://travis-ci.org/unosquare/embedio)
 [![Build status](https://ci.appveyor.com/api/projects/status/w59t7sct3a8ir96t?svg=true)](https://ci.appveyor.com/project/geoperez/embedio)
 [![NuGet version](https://badge.fury.io/nu/embedio.svg)](https://www.nuget.org/packages/Embedio)
[![Coverage Status](https://coveralls.io/repos/unosquare/embedio/badge.svg?branch=master)](https://coveralls.io/r/unosquare/embedio?branch=master)

![EmbedIO](http://unosquare.github.io/embedio/images/embedio.png)

A tiny, cross-platform, module based, MIT-licensed web server.

* Network operations use the relatively recent async/await pattern
* Cross-platform (tested in Mono 3.10.x on Windows and on a custom Yocto image for the Raspberry Pi)
* Extensible (Write your own modules. For example, video streaming, UPnP, etc.). Check EmbedIO Extras for more modules.
* Small memory footprint
* Create REST APIs quickly with the out-of-the-box Web Api module
* Serve static files with 1 line of code (also out-of-the-box)
* Handle sessions with the built-in LocalSessionWebModule
* Web Sockets support (Not available on Mono though)
* CORS support. Origin, Headers and Methods validation with OPTIONS preflight
* [OWIN](http://owin.org/) Middleware support via [Owin Middleware Module](https://github.com/unosquare/embedio-extras/tree/master/Unosquare.Labs.EmbedIO.OwinMiddleware).

*For detailed usage and REST API implementation, download the code and take a look at the Samples project*

NuGet Installation:
-------------------
```
PM> Install-Package EmbedIO
```

Basic Example:
--------------

*Please note the comments are the important part here. More info is available in the samples.*

```csharp
namespace Company.Project
{
    using System;
    using Unosquare.Labs.EmbedIO;
    using Unosquare.Labs.EmbedIO.Log;
    using Unosquare.Labs.EmbedIO.Modules;

    class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(string[] args)
        {
            var url = "http://localhost:9696/";
            if (args.Length > 0)
                url = args[0];

            // Our web server is disposable. Note that if you don't want to use logging,
            // there are alternate constructors that allow you to skip specifying an ILog object.
            using (var server = new WebServer(url, new SimpleConsoleLog()))
            {
                // First, we will configure our web server by adding Modules.
                // Please note that order DOES matter.
                // ================================================================================================
                // If we want to enable sessions, we simply register the LocalSessionModule
                // Beware that this is an in-memory session storage mechanism so, avoid storing very large objects.
                // You can use the server.GetSession() method to get the SessionInfo object and manupulate it.
                // You could potentially implement a distributed session module using something like Redis
                server.RegisterModule(new LocalSessionModule());

                // Here we setup serving of static files
                server.RegisterModule(new StaticFilesModule("c:/web"));
                // The static files module will cache small files in ram until it detects they have been modified.
                server.Module<StaticFilesModule>().UseRamCache = true;
                server.Module<StaticFilesModule>().DefaultExtension = ".html";
                // We don't need to add the line below. The default document is always index.html.
                //server.Module<Modules.StaticFilesWebModule>().DefaultDocument = "index.html";

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                // This is a non-blocking method (it return immediately) so in this case we avoid
                // disposing of the object until a key is pressed.
                //server.Run();
                server.RunAsync();

                // Fire up the browser to show the content if we are debugging!
#if DEBUG
                var browser = new System.Diagnostics.Process()
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }
                };
                browser.Start();
#endif
                // Wait for any key to be pressed before disposing of our web server.
                // In a service we'd manage the lifecycle of of our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }
        }
    }
}
```

Fluent Example:
---------------

```csharp
namespace Company.Project
{
    using System;
    using Unosquare.Labs.EmbedIO;

    internal class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static void Main(string[] args)
        {
            var url = "http://localhost:9696/";
            if (args.Length > 0)
                url = args[0];

            // Create Webserver with console logger and attach LocalSession and Static
            // files module and CORS enabled
            var server = WebServer
                .CreateWithConsole(url)
                .EnableCors()
                .WithLocalSession()
                .WithStaticFolderAt("c:/web");

			var cts = new CancellationTokenSource();
            var task = server.RunAsync(cts);

            // Fire up the browser to show the content if we are debugging!
#if DEBUG
            var browser = new System.Diagnostics.Process()
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo(url) {UseShellExecute = true}
            };
            browser.Start();
#endif
            // Wait for any key to be pressed before disposing of our web server.
            // In a service we'd manage the lifecycle of of our web server using
            // something like a BackgroundWorker or a ManualResetEvent.
            Console.ReadKey(true);
			cts.Cancel();
			try
			{
				task.Wait();
			} catch (AggregateException)
			{
				// We'd also actually verify the exception cause was that the task
				// was cancelled.
				server.Dispose();
			}
        }
    }
}
```

REST API Example:
-----------------

*During server setup:*
```csharp
server.RegisterModule(new WebApiModule());
server.Module<WebApiModule>().RegisterController<PeopleController>();
```

*And our controller class looks like:*

```csharp
public class PeopleController : WebApiController
{
    [WebApiHandler(HttpVerbs.Get, "/api/people/*")]
    public bool GetPeople(WebServer server, HttpListenerContext context)
    {
        try
        {
            var lastSegment = context.Request.Url.Segments.Last();
            if (lastSegment.EndsWith("/"))
                return context.JsonResponse(People);

            int key = 0;
            if (int.TryParse(lastSegment, out key) && People.Any(p => p.Key == key))
            {
                return context.JsonResponse(People.FirstOrDefault(p => p.Key == key));
            }

            throw new KeyNotFoundException("Key Not Found: " + lastSegment);
        }
        catch (Exception ex)
        {
            return HandleError(context, ex, (int)HttpStatusCode.InternalServerError);
        }
    }

    protected bool HandleError(HttpListenerContext context, Exception ex, int statusCode = 500)
    {
        var errorResponse = new
        {
            Title = "Unexpected Error",
            ErrorCode = ex.GetType().Name,
            Description = ex.ExceptionMessage(),
        };

        context.Response.StatusCode = statusCode;
        return context.JsonResponse(errorResponse);
    }
}
```

Web Sockets Example:
-----------------

*During server setup:*
```csharp
server.RegisterModule(new WebSocketsModule());
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsChatServer>("/chat");
```

*And our web sockets server class looks like:*

```csharp

/// <summary>
/// Defines a very simple chat server
/// </summary>
public class WebSocketsChatServer : WebSocketsServer
{

    public WebSocketsChatServer()
        : base(true, 0)
    {
        // placeholder
    }

    /// <summary>
    /// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="rxBuffer">The rx buffer.</param>
    /// <param name="rxResult">The rx result.</param>
    protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult)
    {
        var session = this.WebServer.GetSession(context);
        foreach (var ws in this.WebSockets)
        {
            if (ws != context)
                this.Send(ws, Encoding.UTF8.GetString(rxBuffer));
        }
    }

    /// <summary>
    /// Gets the name of the server.
    /// </summary>
    /// <value>
    /// The name of the server.
    /// </value>
    public override string ServerName
    {
        get { return "Chat Server"; }
    }

    /// <summary>
    /// Called when this WebSockets Server accepts a new WebSockets client.
    /// </summary>
    /// <param name="context">The context.</param>
    protected override void OnClientConnected(WebSocketContext context)
    {
        this.Send(context, "Welcome to the chat room!");
        foreach (var ws in this.WebSockets)
        {
            if (ws != context)
                this.Send(ws, "Someone joined the chat room.");
        }
    }

    /// <summary>
    /// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="rxBuffer">The rx buffer.</param>
    /// <param name="rxResult">The rx result.</param>
    protected override void OnFrameReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult)
    {
        return;
    }

    /// <summary>
    /// Called when the server has removed a WebSockets connected client for any reason.
    /// </summary>
    /// <param name="context">The context.</param>
    protected override void OnClientDisconnected(WebSocketContext context)
    {
        this.Broadcast(string.Format("Someone left the chat room."));
    }
}
```


text:
/**
 * Module dependencies.
 */

var path = require('path');
var assert = require('assert');
var deamdify = require('deamdify');
var toArray = require('stream-to-array');
var BrowserifySingleFile = require('../');

describe('deamdify', function () {

  it('should convert AMD-style modules to CommonJS-style', function (done) {
    var filename = path.resolve(__dirname, 'fixtures', 'amd.js');
    var bsf = new BrowserifySingleFile(filename);

    // apply "deamdify" transform
    bsf.transform(deamdify);

    toArray(bsf.bundle(), function (err, arr) {
      var str = Buffer.concat(arr).toString('utf8');

      // should include the expected compiled JS
      assert(-1 !== str.indexOf('var alpha = require(\'alpha\');'));
      assert(-1 !== str.indexOf('module.exports = {'));
      assert(-1 !== str.indexOf('return alpha.verb() + 2'));

      // should *not* include a sourceMappingURL :(
      assert(-1 === str.indexOf('sourceMappingURL='));

      done();
    });
  });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns="http://schemas.mediachase.com/ecf/view">
	<ListViewUI>
		<Grid>
			<add>
				<Columns>
					<Column columnType="CheckBox" />
					<Column width="50" headingText="" columnType="Action" dataField="SiteId">
						<Item imageUrl="~/Apps/Shell/styles/images/toolbar/copy.gif" commandName="cmdContentGridSiteCopy" commandParameters="SiteId" toolTip="Copy" permissions="content:site:mng:edit" />
						<Item imageUrl="~/Apps/Shell/styles/Images/toolbar/export.png" commandName="cmdContentGridSiteExport" commandParameters="SiteId,Name" toolTip="Export" permissions="content:site:mng:export" />
					</Column>
					<Column visible="false" width="30" allowSorting="true" dataField="SiteId" headingText="{SharedStrings:SiteId}" />
					<Column visible="false" width="30" allowSorting="true" dataField="Name" headingText="{SharedStrings:Name}" />
					<Column headingText="{SharedStrings:Name}" id="name" width="400" columnType="HyperLink" dataNavigateUrlFields="SiteId" dataNavigateUrlFormatString="javascript:CSManagementClient.ChangeView('Content', 'Site-Edit','siteid={0}');" dataTextFields="Name" dataTextFormatString="{0}" />
					<Column headingText="{SharedStrings:Active}" id="active" dataField="IsActive" />
					<Column headingText="{SharedStrings:Folder}" id="folder" width="200" dataField="Folder" />
					<Column headingText="{SharedStrings:Default_Site}" id="isdefault" width="200" dataField="IsDefault" />
				</Columns>
			</add>
		</Grid>
		<Toolbar>
			<add>
				<Menu id="ActionsSplitButton" text="{SharedStrings:Create_New}" imageUrl="~/Apps/Shell/styles/Images/new.png" permissions="content:site:mng:create">
					<Button id="NewSite" text="{SharedStrings:New_Site}" imageUrl="~/Apps/Shell/styles/Images/Icons/Node.gif" commandName="cmdNewSite" permissions="content:site:mng:create"/>
				</Menu>
				<Splitter id="ActionsSplitter"/>
				<Menu id="MoreActionsSplitButton" text="{SharedStrings:More_Actions}" imageUrl="~/Apps/Shell/styles/Images/toolbar/newtask.gif">
					<Button id="DeleteSelected" text="{SharedStrings:Delete_Selected}" imageUrl="~/Apps/Shell/styles/Images/toolbar/delete.gif" commandName="cmdSiteDelete" permissions="content:site:mng:delete"/>
					<Button id="ImportSite" text="{SharedStrings:Import_Site}" imageUrl="~/Apps/Shell/styles/Images/toolbar/import.png" commandName="cmdSiteImport" permissions="content:site:mng:import"/>
					<Button id="ExportSite" text="{SharedStrings:Export_Site}" imageUrl="~/Apps/Shell/styles/Images/toolbar/export.png" commandName="cmdSiteExport" permissions="content:site:mng:export"/>
				</Menu>
			</add>
		</Toolbar>

		<Commands>
			<add>
				<Command id="cmdNewSite">
					<CommandType>ClientAction</CommandType>
					<ClientScript>CSContentClient.NewSite()</ClientScript>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>

				<Command id="cmdSiteDelete">
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.CommonEnableHandler, Mediachase.ConsoleManager" />
					<BeforeClientScript>Toolbar_GridHasItemsSelected</BeforeClientScript>
					<ConfirmationText>{CommerceManager:DeleteSelectedItemsConfirmation}</ConfirmationText>
					<CommandType>ServerAction</CommandType>
					<Handler type="Mediachase.Commerce.Manager.Content.CommandHandlers.SiteDeleteHandler, Mediachase.ConsoleManager" />
					<UpdatePanelIds>panelMainListView</UpdatePanelIds>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>
				<Command id="cmdSiteImport">
					<!--<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.SiteImportEnableHandler, Mediachase.ConsoleManager" />-->
					<CommandType>ClientAction</CommandType>
					<ClientScript>CSContentClient.ImportSite()</ClientScript>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>
				<Command id="cmdSiteExport">
					<!--<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.SiteExportEnableHandler, Mediachase.ConsoleManager" />-->
					<BeforeClientScript>Toolbar_GridHasItemsSelected</BeforeClientScript>
					<CommandType>ClientAction</CommandType>
					<ClientScript>CSContentClient.ExportSite(params)</ClientScript>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>

				<!-- Grid commands -->
				<Command id="cmdContentGridSiteCopy">
					<CommandType>ClientAction</CommandType>
					<ClientScript>CSContentClient.CopySite(params)</ClientScript>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>
				<Command id="cmdContentGridSiteExport">
					<CommandType>ClientAction</CommandType>
					<ClientScript>CSContentClient.ExportSite2(params)</ClientScript>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>
			</add>
		</Commands>

	</ListViewUI>
	<ViewConfig>
		<setAttributes id="Site-List" controlUrl="Content/Site/SiteList.ascx" permissions="content:site:mng:view" help="Content+Management" />
	</ViewConfig>
</View>


text:
var win = Titanium.UI.currentWindow;
win.orientationModes = [Ti.UI.PORTRAIT];
// ライブラリの読み込み
Titanium.include('include/fw/container.js');
con.UI.tableView.separatorStyle = Titanium.UI.iPhone.TableViewSeparatorStyle.NONE;

//ヘッダ画像////////////////////////////////////////
var row = Ti.UI.createTableViewRow({
    height:setting.header_img_height,
    touchEnabled : false,
    selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
    hasChild:false,
    ext : {
        rowTitle : 'home'
    }
    });
row.add(cu.createWrapImageView('img/header_' + setting.lang_string + setting.os_width + '.jpg',setting.os_width,setting.header_img_height));
con.UI.tableView.appendRow(row);

//検索////////////////////////////////////////
var budgets = [];
var maps = [];

var conditions = { maps: maps, budgets: budgets};

var row = Ti.UI.createTableViewRow({
    height:115,
    touchEnabled : false,
    selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
    hasChild:false
    });

var search_table = Titanium.UI.createTableView({
    backgroundColor:setting.row_title_background_color,
    scrollable:false
});
if (Ti.Platform.osname !== 'mobileweb') {
    search_table.style = Titanium.UI.iPhone.TableViewStyle.GROUPED;
}

//budget////////////////////////////////////////////
var row_budget = Ti.UI.createTableViewRow({
    backgroundColor:'#FFFFFF',
    hasChild:true,
    key:'budget'
});

var picker_budget_title = Ti.UI.createLabel({
    text:L('search_budget_action'),
    color:'#000000',
    //width:width,
    height:40,
    top:0,
    left:10,
    font:{fontSize:16,fontWeight:'bold'},
});
row_budget.add( picker_budget_title );
if(setting.os == 'ipad'){
    var budget_popover = require("include/ui/parts/budget_popover");
    budget_popover.exec(conditions,picker_budget_title,row_budget);
}else{
    var budget_picker = require("include/ui/parts/budget_picker");
    budget_picker.exec(conditions,picker_budget_title,row_budget);
}
search_table.appendRow(row_budget);

//region//////////////////////////////////////////
var row_region = Ti.UI.createTableViewRow({
    backgroundColor:'#FFFFFF',
    hasChild:true,
    key:'region'
});
var picker_region_title = Ti.UI.createLabel({
    text:L('search_map_action'),
    color:'#000000',
    height:40,
    top:0,
    left:10,
    font:{fontSize:16,fontWeight:'bold'},
});
row_region.add( picker_region_title );
search_table.appendRow(row_region);
if(setting.os == 'ipad'){
    var region_popover = require("include/ui/parts/region_popover");
    region_popover.exec(conditions,picker_region_title,row_region);
}else{
    var region_picker = require("include/ui/parts/region_picker");
    region_picker.exec(conditions,picker_region_title,row_region);
}

var search_button = Ti.UI.createButton({
  backgroundImage:'img/search_btn_' + setting.lang_string + '.png',
  color:'#ffffff',
  width:300,
  height:35,
  //top:110,
  top:5,
  bottom:5,
  opacity:1,
});
search_button.addEventListener('click', function(e){
    if(conditions.budgets.length > 0 || conditions.maps.length > 0){
        Ti.UI.currentTab.open(
            Ti.UI.createWindow({
                title: L('property_search_window_title'),
                url: "search.js",
                navBarHidden: false,
                barColor: setting.bar_color,
                // Extended
                ext : {
                    conditions : conditions
                }
            })
        );
    }
});
row.add(search_table);
var label = cu.createTitleLabel(L('search_title'),setting.row_title_color,'auto','auto',0,20);
label.font = {fontSize:15,fontWeight:'bold'};
row.add(label);
con.UI.tableView.appendRow(row);

var row = Ti.UI.createTableViewRow({
    //height:35,
    backgroundColor:setting.row_title_background_color,
    touchEnabled : false,
    selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
    hasChild:false
    });
row.add(search_button);
con.UI.tableView.appendRow(row);

//キャンペーン画像////////////////////////////////////////
var row = Ti.UI.createTableViewRow({
    url: 'campaign.js',
    height:setting.campaign_img_height,
    hasChild:true,
    ext : {
        rowTitle : L('campaign_' + setting.season)
    }
});
row.add(cu.createWrapImageView('img/campaign_' + setting.season + setting.os_width +  '.jpg',setting.os_width,setting.campaign_img_height));

con.UI.tableView.appendRow(row);

row.addEventListener('click', function(e) {
    var newWindow = Titanium.UI.createWindow({
        title: e.rowData.ext.rowTitle,
        backgroundColor: '#fff',
        url: e.rowData.url,
        navBarHidden: false,
        barColor: setting.bar_color
    });
    Titanium.UI.currentTab.open(newWindow);
});
win.add(con.UI.tableView);
if(setting.os == 'ipad'){
    con.loadCampaign('index',true,null);
}else{
    con.loadBigFaceCampaign('index',true,null);
}
/*
win.addEventListener('focus', function(e){
    Ti.API.info(Ti.Platform.availableMemory);
});
*/


text:
/*
 * Login router
 */
module.exports = function(req, res, next) {
	var _Login = {};
	config = require('../configs/server.js');
	var configs = config.configs,
	    server_prefix = configs.server_prefix || 'CORE';
	console.log(server_prefix + " - Login router required.");
	var express = require('express'),
		redirect = require('express-redirect'),
		bodyParser = require('body-parser'),
		passport = require('passport');
	_Login = express.Router();
	_Login.use(function(req, res, next) {
		console.log(server_prefix + ' - Login router process');
		// process each login request
		next();
	});
	// routes starting with '/'
	_Login.route('/')
		.all(function(req, res, next) {
			console.log(server_prefix + " - Login all");
			// process all, runs each time
			next();
		})
		.get(function(req, res, next) {
			console.log(server_prefix + " - Login get");
			// process the get (e.g. render)
			if(req.user) {
		    	// already logged in
		    	res.redirect('/?app=calculator'); // TODO make dynamic
			} else {
		    	// not logged in, show the login form, remember to pass the message
		    	// for displaying when error happens
		    	console.log(server_prefix + " - Login requested");
				var app = 'login'; // default
				if(typeof configs.title === 'undefined'){
					var title = 'Untitled';
				}
				else {
					var title = configs.title;
				}
		    	res.render('pages/login', { title: title, message: req.session.messages, layout: false });
		    	// and then remember to clear the message
		    	req.session.messages = null;
			}
		})
		.put(function(req, res, next) {
			console.log(server_prefix + " - Login put");
			// process the put (e.g. update)
			next();
		})
		.post(function(req, res, next) {
			console.log(server_prefix + " - Login post");
			// process the post (e.g. insert)
			// ask passport to authenticate
			passport.authenticate('local', function(err, username, info) {
			    if (err) {
			    	console.log(server_prefix + " - Login, error: " + err);
			    	// if error happens
			    	return next(err);
			    }
			    if (!username) {
			    	// if authentication fail, get the error message that we set
			    	// from previous (info.message) step, assign it into to
			    	// req.session and redirect to the login page again to display
			    	console.log(server_prefix + " - Login, message: " + info.message);
			    	req.session.messages = req.i18n.__(info.message);
			    	return res.redirect('/login');
			    }
			    // if everything is OK
			    req.logIn(username, function(err) {
			    	if (err) {
			    		console.log(server_prefix + " - Login, error: " + err);
			        	req.session.messages = req.i18n.__("Error");
			        	return next(err);
			    	}
			    	// set the message
			    	console.log(server_prefix + " - Login successful, redirecting ...");
			    	req.session.messages = req.i18n.__("Login successfully.");
			    	return res.redirect('/?app=calculator'); // TODO make dynamic
			    });
			})(req, res, next);
		})
		.delete(function(req, res, next) {
			console.log(server_prefix + " - Login delete");
			// process the delete (e.g. delete)
			next();
		});
	return _Login;
}();// calls itself


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

using System.Collections.Generic;
using System.Data;
using Graphene.Data;
using Microsoft.SqlServer.Server;

namespace Graphene.Publishing
{
    public interface IPersist
    {
        void Persist(TrackerData trackerData);

        bool PersistPreAggregatedBuckets { get; }
    }
}


text:
A pattern for Meteor's check package to catch divide by zero errors.

    check(Infinity, Number); // passes
    check(1/0, Number); // passes

    meteor add danimal:checkvalidnumber
    check(Infinity, validNumber); // errors
    check(1/0, validNumber); // errors

Also includes a function that returns true or false.

    isValidNumber(10); // true
    isValidNumber(Infinity); // false


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Verh. zool. -bot. Ges. Wein 22: 283 (1872)

#### Original name
Pertusaria lactea var. lactea

### Remarks
null


text:
class AddLockedSinceToStacks < ActiveRecord::Migration[4.2]
  def change
    add_column :stacks, :locked_since, :datetime, null: true
  end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using sadx_model_view.Extensions;
using sadx_model_view.Ninja;

namespace sadx_model_view.SA1
{
	[Flags]
	public enum LandTableFlags
	{
		Animation   = 0x1,
		TextureList = 0x2,
		TextureName = 0x8,
	}

	public class LandTable : IDisposable
	{
		public static int SizeInBytes => 0x24;

		public short          COLCount  => (short)ColList.Count;
		public short          AnimCount => (short)AnimData.Count;
		public LandTableFlags Flags;
		public float          Unknown_1;

		public readonly List<Col> ColList;
		public readonly List<GeoAnimData> AnimData;

		public string       TexName;
		public NJS_TEXLIST? TexList;
		public int          Unknown_2;
		public int          Unknown_3;

		public uint TexListPointer;

		public LandTable(Stream stream)
		{
			TexList = null;

			byte[] buffer = new byte[SizeInBytes];
			stream.Read(buffer, 0, buffer.Length);

			short colCount = BitConverter.ToInt16(buffer, 0x00);
			short animCount = BitConverter.ToInt16(buffer, 0x02);

			Flags = (LandTableFlags)BitConverter.ToInt32(buffer, 0x04);
			Unknown_1 = BitConverter.ToSingle(buffer, 0x08);

			uint colOffset  = BitConverter.ToUInt32(buffer, 0x0C);
			uint animOffset = BitConverter.ToUInt32(buffer, 0x10);
			uint nameOffset = BitConverter.ToUInt32(buffer, 0x14);
			TexListPointer  = BitConverter.ToUInt32(buffer, 0x18);

			Unknown_2 = BitConverter.ToInt32(buffer, 0x1C);
			Unknown_3 = BitConverter.ToInt32(buffer, 0x20);

			long position = stream.Position;

			if (colCount > 0 && colOffset > 0)
			{
				ColList = new List<Col>(capacity: colCount);

				stream.Position = colOffset;
				for (int i = 0; i < colCount; i++)
				{
					ColList.Add(new Col(stream));
				}
			}
			else
			{
				ColList = new List<Col>();
			}

			if (animCount > 0 && animOffset > 0)
			{
				AnimData = new List<GeoAnimData>(capacity: animCount);

				stream.Position = animOffset;
				for (int i = 0; i < animCount; i++)
				{
					AnimData.Add(new GeoAnimData(stream));
				}
			}
			else
			{
				AnimData = new List<GeoAnimData>();
			}

			if (nameOffset > 0)
			{
				byte[] str = new byte[255];
				stream.Position = nameOffset;
				TexName = Encoding.UTF8.GetString(str, 0, stream.ReadString(ref str));
			}
			else
			{
				TexName = string.Empty;
			}

			stream.Position = position;
		}

		public LandTable()
		{
			Flags     = 0;
			Unknown_1 = 0.0f;
			ColList   = new List<Col>();
			AnimData  = new List<GeoAnimData>();
			TexName   = string.Empty;
			TexList   = null;
			Unknown_2 = 0;
			Unknown_3 = 0;
		}

		public IEnumerable<ObjectTriangles> GetTriangles()
		{
			foreach (Col c in ColList)
			{
				// HACK: since we're only displaying visible COL elements, only get triangles for visible
				if ((c.Flags & ColFlags.Visible) == 0)
				{
					continue;
				}

				foreach (ObjectTriangles pair in c.GetTriangles())
				{
					yield return pair;
				}
			}
		}

		public void CommitVertexBuffer(Renderer device)
		{
			foreach (Col c in ColList)
			{
				c.CommitVertexBuffer(device);
			}
		}

		public void Dispose()
		{
			foreach (Col col in ColList)
			{
				col.Dispose();
			}

			ColList.Clear();

			foreach (GeoAnimData anim in AnimData)
			{
				anim.Dispose();
			}

			AnimData.Clear();
		}
	}
}


text:
'use strict';

var login = angular.module('login', []);

// Values used by "handleCompletedAuth", below.
var returnedData;
var dataHasReturned = false;

// Handle a completed auth - this function is called by the popup window whenever it closes,
// and serves as a link between the popup window and the rest of the application.
var handleCompletedAuth = function(obj) {
    returnedData = obj;
    dataHasReturned = true;
}

login.controller('LoginController', function LoginController($scope, $http, $timeout, $window, userinfo, browserinfo) {
    // Configuration
    var errorBannerDuration = 5000;
    var loggedOutBannerDuration = 5000;

    // General initialization.
    $scope.showError = false;
    $scope.logoutMessage = "Logged out.";
    $scope.isTapIn = true;
    $scope.showJustLoggedOutBanner = false;

    // Error messages mapping, used to easily implement new errors and keep them all organized in 1 area.
    $scope.errorMessages = {
        access_denied: "Authentication denied.",
        invalid_id_token: "Oops, an error has occurred. Please try again.",
        no_connection: "Oops, can't reach server. Please try again."
    };

    // Have to add the userinfo service to the scope so the page can directly access it.
    $scope.userinfo = userinfo;

    // Check that this is a supported browser - show a modal if not.
    if (browserinfo.isSupported() === false) {
        bootbox.alert({
            title: "Browser Not Supported",
            message: "This demo site is not optimized for this browser, please try using Chrome, Firefox, or Safari."
        });
    }

    // Convert an error code into an actual error message and present it to the user,
    // then hide it after a certain amount of time.
    $scope.showErrorFromCode = function (errorCode) {
        // Determine the error message based on the code.
        $scope.errorMessage = $scope.errorMessages[errorCode];

        // Tell the page to show the error.
        $scope.showError = true;

        // Hide the error banner after X seconds.
        $timeout(function () {
            $scope.showError = false;
        }, errorBannerDuration);
    }

    // If the user has just logged out, display the Just Logged Out banner after .2 seconds.
    // Stop showing the banner after X amount of time.
    $timeout(function () {
        if (userinfo.justLoggedOut === true) {
            $scope.showJustLoggedOutBanner = true;
            $timeout(function () {
                userinfo.justLoggedOut = false;
                $scope.showJustLoggedOutBanner = false;
            }, loggedOutBannerDuration);
        }
    }, 200);

    // Assign the popup window's URL, then begin polling for the post-login values
    // we are expecting to be present.
    $scope.assignPopupURL = function (response) {
        $scope.popupWindow.location.href = response.data;
        $scope.pollPopupForCompletedAuth();
    }

    // Continuously poll the popup Privakey Login Page window for the values that are
    // present after a successful login/rejection/cancellation.
    $scope.pollPopupForCompletedAuth = function () {

        // If the data has returned, the login is complete.
        if (dataHasReturned === true) {

            // If "subject" is present, the login was successful, so redirect to the authenticated page.
            if ("subject" in returnedData) {
                userinfo.populate(returnedData.username, returnedData.email, returnedData.details, $scope.isTapIn);

                $window.location.href = '/#/auth';
            }
            // Otherwise, an error occurred (rejection of login, etc.) so present the error.
            else {
                $scope.showErrorFromCode(returnedData.error);
            }

            // Reset "dataHasReturned" so the poll can occur again in the future.
            dataHasReturned = false;
        }
        // If data hasn't returned yet, and the window wasn't closed, keep polling.
        else if ($scope.popupWindow.closed === false) {
            $timeout($scope.pollPopupForCompletedAuth, 1000);
        }
        // If the window was closed manually, do nothing.
        else {

        }
    }

    // Handle an error that results from the HTTP GET failing.
    $scope.handleGetURLError = function (response) {
        $scope.showErrorFromCode("no_connection");
    }

    // Initiate a login by getting the IDP URL from the server then opening it in a new popup window.
    // Should be passed True or False if this is a tap-in auth or not.
    $scope.initiateLogin = function (isTapIn) {
        $scope.isTapIn = isTapIn;

        // In case an error is showing, hide it.
        $scope.showError = false;

        // Open the popup window, leave it blank for now.
        $scope.popupWindow = $window.open('', 'popupWindow', 'height=640,width=500');

        // Make the GET call to the server, then handle the response accordingly.
        $http({
            url:'/loginWithPrivaKey',
            method: 'POST',
            data: {
                'isTapIn': isTapIn
            }
        }).then(
            $scope.assignPopupURL, $scope.handleGetURLError);

        // $http.get('/loginWithPrivaKey'/* + isTapIn*/).
        //     then($scope.assignPopupURL, $scope.handleGetURLError);
    };
});


text:
Readme
======

This directory is for images used by for the Sphinx
documentation. Because images are relatively large files compared to
source code, they are not stored in the git repository. Instead we
just store MD5/SHA512 hashed of the files then utilize [CMake's
ExternalData](https://cmake.org/cmake/help/v3.10/module/ExternalData.html)
module to download the data.

To add data to this directory, the file must be uploaded to one of the
binary data stores, and the md5 and sha512 files are committed to the repository.


text:
import React from "react";
import PostLink from "../components/PostLink";
import styles from "../styles/Hero.module.css";
import stylesPosts from "../styles/Posts.module.css";

const IndexPage = ({ data: { allMarkdownRemark: { edges } } }) => {
  let layoutTwoPost = false;

  if (edges.length === 2) {
    layoutTwoPost = stylesPosts.postsItemLayoutTwo;
  }

  const Posts = edges
    .filter(edge => !!edge.node.frontmatter.date) // You can filter your posts based on some criteria
    .map(edge => {
      return (
        <PostLink
          key={edge.node.id}
          post={edge.node}
          styles={stylesPosts}
          classTwoPosts={layoutTwoPost}
        />
      );
    });

  return (

Bienvenido a mi blog personal

            Por medio de articulos, tutoriales y experiencias. Te compartiré
            consejos, aprendizajes, proyectos o aportando información acerca de
            alguna tecnología en particular.

        <h1 className={`heading ${stylesPosts.postsHeading}`}>
          Entradas más recientes

        {Posts}

        {Posts.length >= 6 && (

              Ver todas las entradas

        )}

  );
};

export default IndexPage;

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(
      sort: { order: DESC, fields: [frontmatter___date] }
      limit: 6
    ) {
      edges {
        node {
          id
          excerpt(pruneLength: 180)
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            path
            title
            thumbnail
            cover
          }
        }
      }
    }
  }
`;


text:
"""
These tests are meant to model the real ways in which a user interacts
with the student notes feature.  Currently there are five actions a
learner can take in student notes:

    - Create a note
    - Edit a note
    - Delete a note
    - Browse notes in the notes tab
    - Search notes in the notes tab

There are many TaskSets for interacting with particular parts of
student notes.  The `LmsNotesTasks` TaskSet attempts to model how an
average user might interact with student notes.
"""
import os
import sys

# due to locust sys.path manipulation, we need to re-add the project root.
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from contextlib import contextmanager
from copy import copy
import json
from locust import HttpLocust, task, TaskSet
import logging
import random

from helpers import settings
# NOTE: the host URL passed in via command-line '--host' flag is the host of
# the LMS!  Make sure to set the notes service URL via the NOTES_HOST setting.
settings.init(__name__, required_data=[
    'courses',
    'NOTES_HOST',
    'NUM_NOTES',
    'NUM_WORDS',
    'NUM_TAGS',
    'NUM_SEARCH_TERMS',
    'LOCUST_TASK_SET',
    'LOCUST_MIN_WAIT',
    'LOCUST_MAX_WAIT',
])

from helpers.mixins import EnrollmentTaskSetMixin
from helpers.edx_app import EdxAppTasks

# Constants used by the LMS when searching student notes.
HIGHLIGHT_TAG = 'span'
HIGHLIGHT_CLASS = 'note-highlight'

# Internal constants
DATA_DIRECTORY = os.path.join(os.path.dirname(__file__), 'notes_data/')
with open(os.path.join(DATA_DIRECTORY, 'basic_words.txt')) as f:
    NOTES_TEXT = [word for line in f for word in line.split()]

log = logging.getLogger(__name__)

def pick_some(sequence, num_items):
    """
    Return a list of between 1 and `num_items` (inclusive) items from
    `sequence`.
    """
    return random.sample(sequence, random.randint(1, num_items))

class BaseNotesTask(EdxAppTasks, EnrollmentTaskSetMixin):
    """
    Base class for all TaskSet classes which interact with student notes.
    """
    def __init__(self, *args, **kwargs):
        """
        Keep track of notes we post.
        """
        super(BaseNotesTask, self).__init__(*args, **kwargs)
        self._notes = {}

        # The notes API is sensitive to being offered basic auth credentials.
        # It needs JWTs for auth, but it needs the basic auth credentials to be
        # absent from the request or else it will return 403.  We avoid that
        # situation entirely by making a copy of self.client with stripped
        # basic auth settings.  Only use this copy with calls to the notes API,
        # not the LMS.
        self.api_client = copy(self.client)
        self.api_client.auth = None

    def on_start(self):
        """
        Runs before any requests are made.
        """
        self.auto_auth()
        self.enroll(self.course_id)

    @property
    def annotator_auth_token(self):
        """
        Get the JWT key for making requests to the notes service from the LMS.
        """
        return self.client.get(
            '/courses/{course_id}/edxnotes/token/'.format(course_id=self.course_id),
            headers={'content-type': 'text/plain'},
        ).content

    @contextmanager
    def get_posted_student_note(self, warning_message):
        """
        Yield a note that the current locust has created.  If there are none
        left, create a new note and yield it.
        """
        try:
            yield self._notes[random.choice(self._notes.keys())]
        except IndexError:  # No notes remaining
            log.debug(warning_message)
            yield self._create_note()

    def _request_from_notes_service(self, method, path, params_or_body=None, **kwargs):
        """
        Internal helper for making a request to the notes service.

        Arguments:
            method (str): HTTP method to execute.
            path (str): URL path to the resource being requested.
            params_or_body (dict): Dict of data to pass in the request.
        Returns:
            response: Response to the request that was made.
        """
        method = method.lower()
        # Pass in the JWT token and CSRF token from edx platform
        kwargs.update({
            'headers': {
                'x-annotator-auth-token': self.annotator_auth_token,
                'X-CSRFToken': self.client.cookies.get('csrftoken', ''),
                'content-type': 'application/json',
            },
        })
        if params_or_body is not None:
            if method == 'get':
                kwargs.update({'params': params_or_body})
            elif method in ['post', 'patch', 'put', 'delete']:
                kwargs.update({'data': json.dumps(params_or_body)})
        return getattr(self.api_client, method)(
            settings.data['NOTES_HOST'] + path,
            **kwargs
        )

    def get(self, path, params=None, **kwargs):
        """
        Internal helper for making a GET request to the notes service.
        """
        return self._request_from_notes_service('get', path, params, **kwargs)

    def post(self, path, body=None, **kwargs):
        """
        Internal helper for making a POST request to the notes service.
        """
        return self._request_from_notes_service('post', path, body, **kwargs)

    def put(self, path, body=None, **kwargs):
        """
        Internal helper for making a PUT request to the notes service.
        """
        return self._request_from_notes_service('put', path, body, **kwargs)

    def delete(self, path, params=None, **kwargs):
        """
        Internal helper for making a DELETE request to the notes service.
        """
        return self._request_from_notes_service('delete', path, params, **kwargs)

    def _create_note(self):
        """
        Post a note containing random text to the notes service.  Because of
        the complex and unnecessary nature of scraping course text, the 'text',
        'tags', and 'quote' fields will be arbitrarily generated.
        """
        data = {
            'user': self._anonymous_user_id,
            'course_id': self.course_id,
            'text': ' '.join(pick_some(
                NOTES_TEXT,
                settings.data['NUM_WORDS'],
            )),
            'tags': pick_some(
                NOTES_TEXT,
                settings.data['NUM_TAGS'],
            ),
            'quote': ' '.join(pick_some(NOTES_TEXT, 5)),
            'usage_id': self.course_data.html_usage_id,
            'ranges': [
                {
                    'start': '/div[1]/p[1]',
                    'end': '/div[1]/p[1]',
                    'startOffset': 0,
                    'endOffset': 6
                }
            ],
        }
        note = json.loads(self.post('/api/v1/annotations/', data).content)
        self._notes[note['id']] = note
        return note

    def _create_many_notes(self, num_notes):
        """
        Create many notes within the course for the current user.
        """
        for _ in xrange(num_notes):
            self._create_note()

    def _delete_note(self):
        """
        Delete a note.
        """
        collection_path = '/api/v1/annotations/'
        with self.get_posted_student_note('No notes left to delete.') as note:
            self.delete(collection_path + note['id'], note, name=collection_path + '[id]')
            self._notes.pop(note['id'])

    def _edit_note(self):
        """
        Edit a note.
        """
        collection_path = '/api/v1/annotations/'
        with self.get_posted_student_note('No notes left to edit.') as note:
            note['text'] = ' '.join(pick_some(
                NOTES_TEXT,
                settings.data['NUM_WORDS'],
            ))
            self.put(collection_path + note['id'], note, name=collection_path + '[id]')
            self._notes[note['id']] = note

    def _list_notes(self):
        """
        List notes in the LMS.
        """
        path = '/courses/{course_id}/edxnotes/'.format(course_id=self.course_id)
        self.client.get(path, verify=False)

    def _search_notes(self):
        """
        Search notes from the LMS for random text.
        """
        path = '/courses/{course_id}/edxnotes/notes/'.format(course_id=self.course_id)
        params = {
            'text': ' '.join(pick_some(
                NOTES_TEXT,
                settings.data['NUM_SEARCH_TERMS'],
            )),
        }
        # Custom name ensures searches are grouped together in locust results.
        self.client.get(path, params=params, name=path + '?text=[search_text]', verify=False)

    @property
    def is_child(self):
        """
        Return True if this TaskSet is a child of another TaskSet
        """
        return isinstance(self.parent, TaskSet)

class ModifyNotesTasks(BaseNotesTask):
    """
    Create, edit, and delete notes with weighted probabilities.
    """
    @task(10)
    def create_note(self):
        """
        Create a note.
        """
        self._create_note()

    @task(2)
    def delete_note(self):
        self._delete_note()

    @task(3)
    def edit_note(self):
        self._edit_note()

class ListLmsNotesTasks(BaseNotesTask):
    """
    List notes on the LMS notes tab.
    """
    def on_start(self):
        """
        Create a constant number of notes
        """
        super(ListLmsNotesTasks, self).on_start()
        self._create_many_notes(settings.data['NUM_NOTES'])

    @task(10)
    def list_notes(self):
        self._list_notes()

    @task(1)
    def stop(self):
        if self.is_child:
            self.interrupt()

class SearchLmsNotesTasks(BaseNotesTask):
    """
    Search the notes API through the LMS, as a user would.
    """
    def on_start(self):
        """
        Create a constant number of notes
        """
        super(SearchLmsNotesTasks, self).on_start()
        self._create_many_notes(settings.data['NUM_NOTES'])

    @task(10)
    def search_notes(self):
        self._search_notes()

    @task(1)
    def stop(self):
        if self.is_child:
            self.interrupt()

class BrowseLmsNotesTasks(TaskSet):
    """
    Parent TaskSet for viewing the notes list and searching the notes list.
    """
    tasks = {ListLmsNotesTasks: 3, SearchLmsNotesTasks: 1}

class LmsNotesTasks(BaseNotesTask):
    """
    Parent TaskSet modeling how users might interact with student
    notes overall.
    """
    @task(10)
    def create_note(self):
        self._create_note()

    @task(2)
    def delete_note(self):
        self._delete_note()

    @task(3)
    def edit_note(self):
        self._edit_note()

    @task(30)
    def list_notes(self):
        self._list_notes()

    @task(10)
    def search_notes(self):
        self._search_notes()

class SearchApiNotesTasks(BaseNotesTask):
    """
    Search the notes API directly.
    """
    @task
    def search_notes(self):
        """
        Search notes for random text.
        """
        path = '/api/v1/search/'
        self.get(
            path,
            {
                'user': self._anonymous_user_id,
                'course_id': self.course_id,
                'text': ' '.join(pick_some(
                    NOTES_TEXT,
                    settings.data['NUM_SEARCH_TERMS'],
                )),
                'highlight': True,
                'highlight_tag': HIGHLIGHT_TAG,
                'highlight_class': HIGHLIGHT_CLASS
            },
            name=path + '?text=[search_text]'
        )

class NotesLocust(HttpLocust):
    task_set = globals()[settings.data['LOCUST_TASK_SET']]
    min_wait = settings.data['LOCUST_MIN_WAIT']
    max_wait = settings.data['LOCUST_MAX_WAIT']


text:
A silex provider for Doctine DBAL using puzzle/configuration (https://github.com/Niktux/puzzle-configuration)

[![SensioLabsInsight](https://insight.sensiolabs.com/projects/f21c76b7-44f8-447a-9368-5775a6fbc5bc/big.png)](https://insight.sensiolabs.com/projects/f21c76b7-44f8-447a-9368-5775a6fbc5bc) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/silex-spear/dbal-provider/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/silex-spear/dbal-provider/?branch=master)

## Installation

```
{
    "require": {
        "silex-spear/dbal-provider": "~2.0"
    }
}
```

or

```bash
composer require silex-spear/dbal-provider
```

#### What is the `config/db.yml-dist.example` file ?

It's a configuration example file for the configuration file hydrator karma (https://github.com/Niktux/karma)


text:
namespace Qoollo.PerformanceCounters
{
    /// <summary>
    /// Типы счетчиков для создания
    /// За более подробной информацией на msdn.
    /// </summary>
    public enum CounterTypes
    {
        /// <summary>
        /// Счетчик мгновенного значения, показывающий последнее наблюдавшееся значение.
        /// Используется, например, для хранения числа элементов или операций.
        /// </summary>
        NumberOfItems,

        /// <summary>
        /// Счетчик , показывающий среднее число операций, завершенных в течение каждой секунды интервала измерения.
        /// </summary>
        OperationsPerSecond,

        /// <summary>
        /// Счетчик среднего значения предназначен для исследования средней длины очереди к ресурсу за все время наблюдения.
        /// Он показывает разницу между длинами очередей, наблюдаемых в течение двух последних интервалов измерения,
        /// деленную на продолжительность интервала.
        /// Этот тип счетчика обычно используется для хранения числа элементов, ожидающих очереди.
        /// </summary>
        //CountPerTimeInterval,

        /// <summary>
        /// Счетчик средних значений, показывающий, сколько элементов обработано в среднем за операцию.
        /// Счетчики этого типа отображают отношение обработанных элементов к числу завершенных операций.
        /// Отношение вычисляется соотношением числа обработанных элементов в течение последнего интервала времени
        /// к числу завершенных операций за этот же интервал.
        /// </summary>
        AverageCount,

        /// <summary>
        /// Счетчик среднего значения, измеряющий время, которое он в среднем займет для завершения процесса или операции.
        /// Счетчики этого типа отображают отношение всего прошедшего интервала измерения к числу процессов или операций,
        /// завершенных за это время.
        /// Этот тип счетчика измеряет время в тактах системных часов.
        /// Не перепутайте! Этот счетчик не показывает среднее время всех измерений, а название свое он берет из усреднения
        /// времени замера при увеличении базового счетчика больше чем на 1 еденицу.
        /// </summary>
        AverageTime,

        /// <summary>
        /// Счётчик моментального значения времени. Хранит последнее записанное в него время.
        /// </summary>
        MomentTime,

        /// <summary>
        /// Счетчик мгновенного значения в процентах, показывающий отношение подмножества к множеству в процентах.
        /// Например, он позволяет сравнить число байтов, используемых на диске, и общее число байтов на этом диске.
        /// Счетчики этого типа отображают только текущий процент, а не среднее значение за все время.
        /// </summary>
        //RawFraction,

        /// <summary>
        /// Счетчик процентов, отображающий процент отношения активности одного или более компонентов
        /// ко всему интервалу измерения.
        /// Поскольку числитель записывает время активности работающих компонентов одновременно,
        /// результат может превышать 100%.
        /// Этот счетчик является мультитаймером.Мультитаймеры записывают данные более одного экземпляра компонента,
        /// например процессора или диска.
        /// </summary>
        //CounterMultiTimer,

        /// <summary>
        /// Счетчик среднего значения, который показывает среднее число операций,
        /// завершенных за одну секунду.Когда счетчик этого типа измеряет данные,
        /// каждое выборочное прерывание возвращает единицу или ноль.
        /// Данными счетчика является число измеренных единиц.
        /// Он измеряет время в тактах системного таймера производительности.
        /// </summary>
        //SampleCounter,

        /// <summary>
        /// Счетчик процентов, показывающий среднее отношение обращений ко всем операциям
        /// за последние два интервала измерения.
        /// </summary>
        //SampleFraction,

        /// <summary>
        /// Counter for the difference between the raw value at the beginning and the end of the measured time frame.
        /// </summary>
        Delta,

        /// <summary>
        /// Таймер, который показывает полное время от начала работы компонента или процесса
        /// </summary>
        ElapsedTime,

        //Не используем
        //CounterTimer
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>SignLanguagetranslator-using-Kinect2-DTW: Class Index</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

SignLanguagetranslator-using-Kinect2-DTW

Main Page

Related Pages

Packages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Class Index

A | B | D | G | J | M | R

  A

	BodyView (SignLanguageTranslatorDTW)   	GestureResultView (SignLanguageTranslatorDTW)

  M

  D

	GestureStore (SignLanguageTranslatorDTW)

App (SignLanguageTranslatorDTW)

  J

	MainWindow (SignLanguageTranslatorDTW)

  B

	DTW

  R

  G

	JointsExtractor (SignLanguageTranslatorDTW)

Body2D (SignLanguageTranslatorDTW)   		Recorder (SignLanguageTranslatorDTW)

	GestureDetector (SignLanguageTranslatorDTW)

A | B | D | G | J | M | R

<address class="footer">
Generated on Sun Mar 29 2015 22:09:04 for SignLanguagetranslator-using-Kinect2-DTW by

 1.8.9.1
</address>


text:
```julia
using Plots
unicodeplots()
```

### Lines

A simple line plot of the columns.

```julia
plot(fakedata(50,5),w=3)
```

![](img/unicodeplots/unicodeplots_example_1.png)

### Parametric plots

Plot function pair (x(u), y(u)).

```julia
plot(sin,(x->begin  # /Users/tom/.julia/v0.4/Plots/docs/example_generation.jl, line 50:
            sin(2x)
        end),0,2π,line=4,leg=false,fill=(0,:orange))
```

![](img/unicodeplots/unicodeplots_example_3.png)

### Colors

Access predefined palettes (or build your own with the `colorscheme` method).  Line/marker colors are auto-generated from the plot's palette, unless overridden.  Set the `z` argument to turn on series gradients.

```julia
y = rand(100)
plot(0:10:100,rand(11,4),lab="lines",w=3,palette=:grays,fill=(0.5,:auto))
scatter!(y,z=abs(y - 0.5),m=(10,:heat),lab="grad")
```

![](img/unicodeplots/unicodeplots_example_4.png)

### Global

Change the guides/background/limits/ticks.  Convenience args `xaxis` and `yaxis` allow you to pass a tuple or value which will be mapped to the relevant args automatically.  The `xaxis` below will be replaced with `xlabel` and `xlims` args automatically during the preprocessing step. You can also use shorthand functions: `title!`, `xaxis!`, `yaxis!`, `xlabel!`, `ylabel!`, `xlims!`, `ylims!`, `xticks!`, `yticks!`

```julia
plot(rand(20,3),xaxis=("XLABEL",(-5,30),0:2:20,:flip),background_color=RGB(0.2,0.2,0.2),leg=false)
title!("TITLE")
yaxis!("YLABEL",:log10)
```

![](img/unicodeplots/unicodeplots_example_5.png)

### Two-axis

Use the `axis` arguments.

Note: Currently only supported with Qwt and PyPlot

```julia
plot(Vector[randn(100),randn(100) * 100],axis=[:l :r],ylabel="LEFT",yrightlabel="RIGHT")
```

![](img/unicodeplots/unicodeplots_example_6.png)

### Arguments

Plot multiple series with different numbers of points.  Mix arguments that apply to all series (marker/markersize) with arguments unique to each series (colors).  Special arguments `line`, `marker`, and `fill` will automatically figure out what arguments to set (for example, we are setting the `linestyle`, `linewidth`, and `color` arguments with `line`.)  Note that we pass a matrix of colors, and this applies the colors to each series.

```julia
plot(Vector[rand(10),rand(20)],marker=(:ellipse,8),line=(:dot,3,[:black :orange]))
```

![](img/unicodeplots/unicodeplots_example_7.png)

### Build plot in pieces

Start with a base plot...

```julia
plot(rand(100) / 3,reg=true,fill=(0,:green))
```

![](img/unicodeplots/unicodeplots_example_8.png)

###

and add to it later.

```julia
scatter!(rand(100),markersize=6,c=:orange)
```

![](img/unicodeplots/unicodeplots_example_9.png)

### Line types

```julia
types = intersect(supportedTypes(),[:line,:path,:steppre,:steppost,:sticks,:scatter])'
n = length(types)
x = Vector[sort(rand(20)) for i = 1:n]
y = rand(20,n)
plot(x,y,line=(types,3),lab=map(string,types),ms=15)
```

![](img/unicodeplots/unicodeplots_example_11.png)

### Line styles

```julia
styles = setdiff(supportedStyles(),[:auto])'
plot(cumsum(randn(20,length(styles)),1),style=:auto,label=map(string,styles),w=5)
```

![](img/unicodeplots/unicodeplots_example_12.png)

### Marker types

```julia
markers = setdiff(supportedMarkers(),[:none,:auto,Shape])'
n = length(markers)
x = (linspace(0,10,n + 2))[2:end - 1]
y = repmat(reverse(x)',n,1)
scatter(x,y,m=(8,:auto),lab=map(string,markers),bg=:linen)
```

![](img/unicodeplots/unicodeplots_example_13.png)

### Bar

x is the midpoint of the bar. (todo: allow passing of edges instead of midpoints)

```julia
bar(randn(999))
```

![](img/unicodeplots/unicodeplots_example_14.png)

### Histogram

```julia
histogram(randn(1000),nbins=50)
```

![](img/unicodeplots/unicodeplots_example_15.png)

### Subplots

  subplot and subplot! are distinct commands which create many plots and add series to them in a circular fashion.
  You can define the layout with keyword params... either set the number of plots `n` (and optionally number of rows `nr` or
  number of columns `nc`), or you can set the layout directly with `layout`.

```julia
subplot(randn(100,5),layout=[1,1,3],t=[:line :hist :scatter :step :bar],nbins=10,leg=false)
```

![](img/unicodeplots/unicodeplots_example_16.png)

### Adding to subplots

Note here the automatic grid layout, as well as the order in which new series are added to the plots.

```julia
subplot(fakedata(100,10),n=4,palette=[:grays :blues :heat :lightrainbow],bg=[:orange :pink :darkblue :black])
```

![](img/unicodeplots/unicodeplots_example_17.png)

###

```julia
subplot!(fakedata(100,10))
```

![](img/unicodeplots/unicodeplots_example_18.png)

### Custom Markers

A `Plots.Shape` is a light wrapper around vertices of a polygon.  For supported backends, pass arbitrary polygons as the marker shapes.  Note: The center is (0,0) and the size is expected to be rougly the area of the unit circle.

```julia
verts = [(-1.0,1.0),(-1.28,0.6),(-0.2,-1.4),(0.2,-1.4),(1.28,0.6),(1.0,1.0),(-1.0,1.0),(-0.2,-0.6),(0.0,-0.2),(-0.4,0.6),(1.28,0.6),(0.2,-1.4),(-0.2,-1.4),(0.6,0.2),(-0.2,0.2),(0.0,-0.2),(0.2,0.2),(-0.2,-0.6)]
plot(0.1:0.2:0.9,0.7 * rand(5) + 0.15,l=(3,:dash,:lightblue),m=(Shape(verts),30,RGBA(0,0,0,0.2)),bg=:pink,fg=:darkblue,xlim=(0,1),ylim=(0,1),leg=false)
```

![](img/unicodeplots/unicodeplots_example_21.png)

- Supported arguments: `group`, `label`, `legend`, `linestyle`, `linetype`, `markershape`, `nbins`, `show`, `size`, `title`, `windowtitle`, `x`, `xlabel`, `xlims`, `y`, `ylabel`, `ylims`
- Supported values for axis: `:auto`, `:left`
- Supported values for linetype: `:bar`, `:heatmap`, `:hexbin`, `:hist`, `:hline`, `:line`, `:none`, `:path`, `:scatter`, `:steppost`, `:sticks`, `:vline`
- Supported values for linestyle: `:auto`, `:solid`
- Supported values for marker: `:auto`, `:ellipse`, `:none`
- Is `subplot`/`subplot!` supported? Yes

(Automatically generated: 2015-10-18T00:07:46)


text:
package knorxx.framework.generator.web.server.rpc;

import com.google.common.base.Optional;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import knorxx.framework.generator.util.HttpCookieUtils;
import knorxx.framework.generator.web.client.RpcService;
import knorxx.framework.generator.web.server.json.JsonHelper;
import knorxx.framework.generator.web.server.rpc.RpcResult.Status;

/**
 *
 * @author sj
 */
public class RpcCaller {

    public final static String CSRF_PROTECTION_COOKIE_NAME = "RPCSESSIONID";

    public RpcResult call(RpcCall rpcCall, ExceptionMarshaller exceptionSerializer, JsonHelper jsonHelper,
            List<RpcService> rpcServices, HttpServletRequest request) {
        Optional<Cookie> csrfProtectionCookie = HttpCookieUtils.getCookie(CSRF_PROTECTION_COOKIE_NAME, request);
        if(!csrfProtectionCookie.isPresent()) {
            throw new MissingCsrfProtectionCookieException(String.format("Can't find a CSRF protection cookie "
                    + "named '%s'!", CSRF_PROTECTION_COOKIE_NAME));
        } else if(!csrfProtectionCookie.get().getValue().equals(rpcCall.getCsrfProtectionToken())) {
            throw new CsrfAttackException(String.format("A CSRF attack was detected while calling the method "
                    + "'%s' of the service '%s'.", rpcCall.getMethodName(), rpcCall.getServiceName()));
        }

        for(RpcService rpcService : rpcServices) {
            Class serviceClass = rpcService.getClass();
            if(serviceClass.getName().equals(rpcCall.getServiceName())) {
                for(Method method : serviceClass.getDeclaredMethods()) {
                    if(method.getName().equals(rpcCall.getMethodName())) {
                        List<Object> arguments = new ArrayList<>();
                        int argIndex = 0;

                        for(Class<?> parameterType : method.getParameterTypes()) {
                            if(parameterType.equals(HttpServletRequest.class)) {
                                arguments.add(request);
                                argIndex++;
                            } else if(parameterType.equals(HttpSession.class)) {
                                arguments.add(request.getSession());
                                argIndex++;
                            } else if(argIndex < rpcCall.getArgumentsJsons().size()) {
                                arguments.add(jsonHelper.fromJson(rpcCall.getArgumentsJsons().get(argIndex), parameterType));
                                argIndex++;
                            } else {
                                arguments.add(null);
                            }
                        }

                        Object rpcResult;
                        try {
                            rpcResult = method.invoke(rpcService, arguments.toArray());
                        } catch (IllegalAccessException | IllegalArgumentException ex) {
                            throw new IllegalStateException(String.format("An error occured while invoking the metohd "
                                    + "'%s' of the service '%s' via refelction.", rpcCall.getMethodName(),
                                    rpcCall.getServiceName()), ex);
                        } catch(InvocationTargetException ex) {
                            return new RpcResult(Status.EXCEPTION, exceptionSerializer.marshall(ex.getCause(), jsonHelper));
                        }

                        return new RpcResult(Status.SUCCESS, jsonHelper.toJson(rpcResult, method.getReturnType()));
                    }
                }

                throw new IllegalStateException("The service '" + rpcCall.getServiceName() + "' has no public method "
                        + "named '" + rpcCall.getMethodName() + "'!");
            }
        }

        throw new IllegalStateException("There's no registered service with the name '" + rpcCall.getServiceName() + "'!");
    }
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("zerver", "0393_realm_want_advertise_in_communities_directory"),
    ]

    operations = [
        migrations.AlterField(
            model_name="realm",
            name="want_advertise_in_communities_directory",
            field=models.BooleanField(db_index=True, default=False),
        ),
    ]


text:
<?php

namespace StealThisShow\StealThisTracker\Bencode;

/**
 * Test class for Parser.
 *
 * @package StealThisTracker
 * @author  StealThisShow <info@stealthisshow.com>
 * @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause
 */
class ParserTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test parse
     *
     * @param string $string_to_parse String
     *
     * @throws Error\Parse
     * @return void
     *
     * @dataProvider parseableStrings
     */
    public function testParse($string_to_parse)
    {
        $object = new Parser($string_to_parse);

        // Parse method returns AbstractValue objects,
        // and they are converted back to string by calling __toString.
        $this->assertEquals($string_to_parse, $object->parse() . '');
    }

    /**
     * Returns array
     *
     * @return array
     */
    public static function parseableStrings()
    {
        return array(
            array('i123e'), // Integer.
            array('i-55e'), // Integer.
            array('5:funny'), // String.
            array('li123e5:funnye'), // List.
            array('d5:funnyi555e4:test2:OKe'), // Dictionary.
            array(
                'd7:Address17:1 Time Square, NY6:Phonesli123456e10:0012567890ee'
            ), // Complex.
        );
    }

    /**
     * Test parse error invalid value
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorInvalidValue()
    {
        $object = new Parser('something stupid');
        $object->parse();
    }

    /**
     * Test parse error unstructured
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorUnstructured()
    {
        $object = new Parser('i456ei222e');
        $object->parse();
    }

    /**
     * Test parse error incomplete dictionary
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorIncompleteDictionary()
    {
        $object = new Parser('d3:foo3:bar3:baze');
        $object->parse();
    }

    /**
     * Test parse error unbalanced ending
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorUnbalancedEnding()
    {
        $object = new Parser('lee');
        $object->parse();
    }

    /**
     * Test parse error missing integer ending
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorMissingIntegerEnding()
    {
        $object = new Parser('i222');
        $object->parse();
    }

    /**
     * Test parse error invalid string length
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorInvalidStringLength()
    {
        $object = new Parser('12abc:string');
        $object->parse();
    }

    /**
     * Test parse error missing string colon
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorMissingStringColon()
    {
        $object = new Parser('123');
        $object->parse();
    }

    /**
     * Test parse error unended container
     *
     * @expectedException \StealThisShow\StealThisTracker\Bencode\Error\Parse
     *
     * @return void
     */
    public function testParseErrorUnendedContainer()
    {
        $object = new Parser('ld2:AB2:CDe');
        $object->parse();
    }

}