text:
(function(moduleName, window) {
	var from = function(selectorOrElement, selectedPlugins) {
			var parent = selectorOrElement.nodeType === 1 ? selectorOrElement : document.querySelector(selectorOrElement),
				slides = [].filter.call(parent.children, function(el) { return el.nodeName !== 'SCRIPT'; }),
				activeSlide = slides[0],
				listeners = {},

				activate = function(index, customData) {
					if (!slides[index]) {
						return;
					}

					fire('deactivate', createEventData(activeSlide, customData));

					activeSlide = slides[index];

					slides.map(deactivate);

					fire('activate', createEventData(activeSlide, customData));

					addClass(activeSlide, 'active');
					removeClass(activeSlide, 'inactive');
				},

				deactivate = function(el, index) {
					var offset = index - slides.indexOf(activeSlide),
						offsetClass = offset > 0 ? 'after' : 'before';

					['before(-\\d+)?', 'after(-\\d+)?', 'active', 'inactive'].map(removeClass.bind(null, el));

					el !== activeSlide &&
						['inactive', offsetClass, offsetClass + '-' + Math.abs(offset)].map(addClass.bind(null, el));
				},

				slide = function(index, customData) {
					if (arguments.length) {
						fire('slide', createEventData(slides[index], customData)) && activate(index, customData);
					} else {
						return slides.indexOf(activeSlide);
					}
				},

				step = function(offset, customData) {
					var slideIndex = slides.indexOf(activeSlide) + offset;

					fire(offset > 0 ? 'next' : 'prev', createEventData(activeSlide, customData)) && activate(slideIndex, customData);
				},

				on = function(eventName, callback) {
					(listeners[eventName] || (listeners[eventName] = [])).push(callback);

					return function() {
						listeners[eventName] = listeners[eventName].filter(function(listener) {
							return listener !== callback;
						});
					};
				},

				fire = function(eventName, eventData) {
					return (listeners[eventName] || [])
						.reduce(function(notCancelled, callback) {
							return notCancelled && callback(eventData) !== false;
						}, true);
				},

				createEventData = function(el, eventData) {
					eventData = eventData || {};
					eventData.index = slides.indexOf(el);
					eventData.slide = el;
					return eventData;
				},

				deck = {
					on: on,
					fire: fire,
					slide: slide,
					next: step.bind(null, 1),
					prev: step.bind(null, -1),
					parent: parent,
					slides: slides
				};

			addClass(parent, 'parent');

			slides.map(function(el) {
				addClass(el, 'slide');
			});

			for (var pluginName in selectedPlugins) {
				if (!plugins[pluginName]) {
					throw Error('Missing plugin: ' + moduleName + '-' + pluginName);
				}
				selectedPlugins[pluginName] !== false && plugins[pluginName](deck, selectedPlugins[pluginName]);
			}

			activate(0);

			decks.push(deck);

			return deck;
		},

		decks = [],

		plugins = {},

		addClass = function(el, cls) {
			el.classList.add(moduleName + '-' + cls);
		},

		removeClass = function(el, cls) {
			el.className = el.className
				.replace(RegExp(moduleName + '-' + cls +'(\\s|$)', 'g'), ' ')
				.trim();
		},

		callOnAllDecks = function(method) {
			return function() {
				var args = arguments;
				decks.map(function(deck) {
					deck[method].apply(null, args);
				});
			};
		};

	window[moduleName] = {
		from: from,
		slide: callOnAllDecks('slide'),
		next: callOnAllDecks('next'),
		prev: callOnAllDecks('prev'),
		plugins: plugins
	};

}('bespoke', window));


text:
This should probably be kept in GitHub issues -- eventually

# Highlight.JS using JS in the browser

The current practice for code highlighting isn't working well.  The highlighting often looks bad.  Further, when Medium imports articles, it chokes badly on the highlighted code.

https://highlightjs.org/usage/ -- It can be configured to run JavaScript in the browser to perform the highlighting.

Alternatively there might be other tools that do a better job of code highlighting.

# Minimal metadata for social media

https://meiert.com/en/blog/minimal-social-markup/

https://cards-dev.twitter.com/validator

https://www.linkedin.com/post-inspector/

https://developers.facebook.com/tools/debug/

```html
<!-- <head> (and <body>) needed for LinkedIn -->
<head>
  <!-- "twitter:card" and title needed for Twitter -->
  <meta name=twitter:card content=summary_large_image>
  <meta property=og:title content="This is a test title">
  <!-- Quotes needed for WhatsApp and Signal -->
  <meta property="og:description" name="description" content="This is a test description.">
  <meta property="og:image" content="https://hell.meiert.org/core/png/test.png">
</head>
```

# Icons

https://humbleicons.com/

# Front end build tool

https://vitejs.dev/

# Using gh-pages w/ GitHub token, or GitHub actions

Publishing from a headless Jenkins slave means setting up a Personal Access Token.

* https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
* https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git
* https://github.com/GitCredentialManager/git-credential-manager

The credential manager was installed on Ubuntu from the `.deb` file supplied in that repository.  I had to manually run `npm run deploy` once:

```
$ npm run gh-pages

> guide@1.0.0 gh-pages /home/docker/jenkinslave/root/workspace/test-epubtools/guide
> akasharender gh-pages-publish config.js

Select an authentication method for 'https://github.com/':
  1. Device code (default)
  2. Personal access token
option (enter for default): 2
Enter GitHub personal access token for 'https://github.com/'...
Token:
OK
```

This stored the personal access token in the credential manager.  It should all be good now.

Another route is to use GitHub actions for the publishing step.  Maybe it's not desirable to use GitHub actions for everything - build/test/npm-publish - but it seems that using GitHub actions for publishing the website is preferable.

* https://github.com/tschaub/gh-pages/issues/345
* https://github.com/UniversalDataTool/universal-data-tool/blob/master/.github/workflows/release-on-master.yml
* https://github.com/nchaulet/github-action-gh-pages/blob/master/entrypoint.sh
* https://github.com/nchaulet/github-action-gh-pages

This task requires learning how to set up GitHub Actions.  Once that's done, those links contain scripts to use the standard gh-pages command from the gh-pages package.

Our task is to expose anything required in AkashaRender's gh-pages command.  In particular it seems that `-u "github-actions-bot <support+actions@github.com>` setting is required.

# Add @akashacms/create-xyzzy packages

The `npm init` command allows for easy creation of example projects.

* https://docs.npmjs.com/cli/v8/commands/npm-init
* https://www.npmjs.com/package/create-esm
* https://github.com/standard-things/create-esm
* https://www.npmjs.com/package/pkg-install

The `create-esm` package is an example.  It ultimately uses the `pkg-install` package.

The goal is:

* `create-github-site` uses the current `open-source-site` example
* `create-epub` uses `epub-skeleton`
* etc

# Replace sightmap

This is an ancient package, that basically see's zero usage.  Surely there is a better package.

Bonus points for something that builds Google News XML files

https://www.npmjs.com/package/sitemap - Looks very modern and comprehensive

https://www.npmjs.com/package/easy-sitemap - Much lighter weight

# Convert some or all code to TypeScript and/or ES6

It's the way of the future.  AkashaRender has some needs for advanced data type support.

# Revisit the choice of Commander in cli.js

Perhaps "yargs" is better?

Maybe cli.js can be rewritten as a zx script?

# Supporting responsive image formats

Nowadays we can write something like the following to instruct web browsers to use optional image sizes or formats.

```
<img srcset="img1-480.jpg 480w, img1-600.jpg 600w, img1.jpg"
    sizes="(media query) 480w, (media query) 600w"
    src="img1.jpg"/>
```

```
<picture>
    <source type="image/webp" src="img1.webp">
    ...
    <img src="img1.jpg"/>
</picture>
```

There's a lot more to this, and the MDN has a useful overview.  A dumb browser will fall back to the element it recognizes, `<img>`.  The other elements and attributes add new capabilities.  The gain is reducing the payload required to be loaded, and therefore improving page load times.

* https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
* https://blog.cloudfour.com/responsive-images-101-definitions

What AkashaCMS should do:

* Develop a processor function to take a simple standard `<img>` tag, and auto-convert it
* Configuration options in `config.js` to drive what to do
* Prefer the `<picture>` element, using `<source type=>` with no `media=` attribute.  The discussion on `blog.cloudfour.com` explains why
* Ignore images where there is an existing `<picture>` element or `srcset/sizes` attributes.  In such a case the author will have already selected what to do.
* Rewrite images to WEBP or other hyper-compressed format, then write the suitable `<picture>` element.

# Data tables

It will be useful to load data into the ForerunnerDB cache system.  The data can be useful to plugins or templates.

In `config.js`:

```js
config.dataTables([
    {
        href: 'path/to/file.yaml',  # Also support JSON or CSV
        name: 'collection-name',
        persist: true/false,
    },
    ...
]);
```

Create a `DataTable` class.  There must be a Chokidar instance to watch for changes in data table files.  When a data file is updated, reload, or if unlinked, then remove the table.

The `DataTable` class can provide a few methods for searching the data.

Perhaps a plugin like Affiliates can be rewritten to use DataTable?  As it stands, the Affiliates plugin has been rewritten with some custom code creating a Collection etc.

For example, a DataTable of electric vehicle attributes - of solar panel attributes - of Linux Single Board Computer attributes - could be used in content.

redpajama_set_name: RedPajamaGithub


text:
//
//  NavDescriptionView.m
//  NavKit
//
//  Created by Steve Dekorte on 6/4/14.
//  Copyright (c) 2014 voluntary.net. All rights reserved.
//

#import "NavDescriptionView.h"
#import "NSView+sizing.h"

@implementation NavDescriptionView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];

    if (self)
    {
        [self setAutoresizesSubviews:YES];
        [self setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];

        _textView = [[NavTextView alloc] initWithFrame:NSMakeRect(0, 0, self.width, self.height)];
        [self addSubview:_textView];
        [_textView setThemePath:@"code"];
        //_textView.textColor = [NSColor whiteColor];
       // _textView.backgroundColor = [NSColor colorWithCalibratedWhite:.5 alpha:1.0];
        //self.backgroundColor = [NSColor whiteColor];

        //[_textView setDelegate:self];
        //_textView.endsOnReturn = YES;
        //@property (strong) IBOutlet NSTextView *quantity;
    }

    return self;
}

- (void)setNode:(NavNode *)node
{
    _node = node;

    [self syncFromNode];
}

- (void)setFrame:(NSRect)frameRect
{
    [super setFrame:frameRect];
    [self layout];
    [self layout];
}

- (void)syncFromNode
{
    if ([_node respondsToSelector:@selector(descriptionJSONObject)])
    {
        id anObject = ((id <NavDescriptionViewProtocol>)_node).descriptionJSONObject;

        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:anObject
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

        if (error)
        {
            NSString *errorString = [[error userInfo] objectForKey:@"NSDebugDescription"];
            _textView.string = errorString;
            // change color?
        }
        else
        {
            NSString *aString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            _textView.string = aString;
        }
    }
    else
    {
        _textView.string = _node.description;
    }

    [_textView setNeedsDisplay:YES];

    //[self layout];
}

- (void)layout
{
    /*
    if (self.superview)
    {
        [self setWidth:self.superview.width];
        [self setHeight:self.superview.height];
    }
    */

    NSString *s = _textView.string;
    NSLog(@"%@", s);

    CGFloat margin = 30;

    [_textView setX:margin];
    [_textView setY:margin];

    [_textView setWidth:self.width   - margin * 2];
    [_textView setHeight:self.height - margin * 2];
}

@end


text:
package suggestions
package observablex

import scala.concurrent.{Future, ExecutionContext}
import scala.util._
import scala.util.Success
import scala.util.Failure
import java.lang.Throwable
import rx.lang.scala.Observable
import rx.lang.scala.Scheduler
import rx.lang.scala.subjects.ReplaySubject

object ObservableEx {

  /** Returns an observable stream of values produced by the given future.
   * If the future fails, the observable will fail as well.
   *
   * @param f future whose values end up in the resulting observable
   * @return an observable completed after producing the value of the future, or with an exception
   */
  def apply[T](f: Future[T])(implicit execContext: ExecutionContext): Observable[T] = {
    val subject = ReplaySubject[T]()
    f onComplete {
      case Success(t) => { subject.onNext(t); subject.onCompleted() }
      case Failure(t) => {
        subject.onError(t)
      }
    }
    subject
  }

}


text:
{% load static %}
{% load django_popup_view_field_tags %}

<script
    type="text/javascript"
    src="{% url "django_popup_view_field:javascript-catalog" %}">
</script>

{% django_popup_view_field_bootstrap_version as bootstrap_version %}
{% if bootstrap_version == 'bootstrap3' %}
    {% include 'django_popup_view_field/popup_view_dialog_bootstrap3.html' %}
    <script
        type="text/javascript"
        src="{% static 'django_popup_view_field/js/django_popup_view_field_bootstrap3.min.js' %}">
    </script>
{% elif bootstrap_version == 'bootstrap4' %}
    {% include 'django_popup_view_field/popup_view_dialog_bootstrap4.html' %}
    <script
        type="text/javascript"
        src="{% static 'django_popup_view_field/js/django_popup_view_field_bootstrap4.min.js' %}">
    </script>
{% endif %}


text:
import json
import sys

from boto.s3.connection import S3Connection
from boto.s3.key import Key

import config
import utils

if len(sys.argv) < 2:
    sys.exit('You must specify "staging" or "production" as an argument to this script.')

ENVIRONMENT = sys.argv[1]

collection = utils.get_label_collection()

row_count = 0
deployed = 0

c = S3Connection()
bucket = c.get_bucket(config.S3_BUCKETS[ENVIRONMENT])

for dataset in collection.find():
    row_count += 1

    del dataset['_id']

    print dataset['dataset']

    k = Key(bucket)
    k.key = '%s_labels.jsonp' % dataset['dataset']
    jsonp = 'labels_%s(%s)' % (dataset['dataset'], json.dumps(dataset))
    compressed = utils.gzip_data(jsonp)

    k.set_contents_from_string(compressed, headers={ 'Content-encoding': 'gzip', 'Content-Type': 'application/json' }, policy='public-read')

    deployed += 1

print 'deploy_labels:'
print ' Row count: %i' % row_count
print ' Deployed: %i' % deployed


text:
LibreBoard is an open-source *kanban* board that let you organize things in
cards, and cards in lists. You can use it alone, or with your team and family
thanks to our real-time synchronisation feature. Libreboard is a land of liberty
and you can implement all sort of workflows on it using tags, comments, member
assignation, and many more.

[![Our roadmap is self-hosted on LibreBoard][thumbnail]][roadmap]

Since it is a free software, you don't have to trust us with your data and can
install LibreBoard on your own computer or server. In fact we encourage you to
do that by providing one-click installation for the
[Sandstorm](https://sandstorm.io) platform and verified
[Docker](https://www.docker.com) images.

LibreBoard is released under the very permissive [MIT license](LICENSE), and
made with [Meteor](https://www.meteor.com).

[Our roadmap is self-hosted on LibreBoard][roadmap]

[travis-status]: https://travis-ci.org/libreboard/libreboard.svg
[travis-link]: https://travis-ci.org/libreboard/libreboard.svg
[thumbnail]: http://i.imgur.com/PMAh7qR.png
[roadmap]: http://libreboard.com/boards/MeSsFJaSqeuo9M6bs/libreboard-roadmap


text:
require 'sinatra/namespace'
class GtkApi < Sinatra::Base

  register Sinatra::Namespace
  helpers GtkApiHelper

  namespace '/api/v2/users' do
    options '/?' do
      response.headers['Access-Control-Allow-Origin'] = '*'
      response.headers['Access-Control-Allow-Methods'] = 'POST,PUT'
      response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
      halt 200
    end

    # POST new users
    post '/?' do
      log_message = 'GtkApi::POST /api/v2/users/?'
      params = JSON.parse(request.body.read, symbolize_names: true)

      logger.info(log_message) {"entered with params=#{params}"}

      # {"username" => "sampleuser", "firstName" => "User", "lastName" => "Sample", "email" => "user.sample@email.com.br", "password" => "1234", "user_type" => "developer"|"customer"|"admin"}

      json_error 400, 'User name is missing' unless (params.key?(:username) && !params[:username].empty?)
      json_error 400, 'User password is missing' unless (params.key?(:password) && !params[:password].empty?)
      json_error 400, 'User email is missing' unless (params.key?(:email) && !params[:email].empty?)
      json_error 400, 'User type is missing' unless (params.key?(:user_type) && !params[:user_type].empty?)

      begin
        user = User.create(params)
        logger.info(log_message) {"leaving with user #{user.inspect}"}
        headers 'Location'=> User.class_variable_get(:@@url)+"/api/v2/users/#{user.uuid}", 'Content-Type'=> 'application/json'
        halt 201, user.to_json(only: [:token])
      rescue UserNotCreatedError
        json_error 400, "Error creating user #{params}", log_message
      end
    end

    # GET many users
    get '/?' do
      log_message = 'GtkApi:: GET /api/v2/users'

      logger.debug(log_message) {'entered with '+query_string}

      @offset ||= params['offset'] ||= DEFAULT_OFFSET
      @limit ||= params['limit'] ||= DEFAULT_LIMIT
      logger.debug(log_message) {"offset=#{@offset}, limit=#{@limit}"}
      logger.debug(log_message) {"params=#{params}"}

      begin
        users = User.find(params)
        logger.debug(log_message) {"Found users #{users}"}
        logger.debug(log_message) {"links: request_url=#{request_url}, limit=#{@limit}, offset=#{@offset}, total=#{users.count}"}
        links = build_pagination_headers(url: request_url, limit: @limit.to_i, offset: @offset.to_i, total: users.count)
        logger.debug(log_message) {"links: #{links}"}
        headers 'Link'=> links, 'Record-Count'=> users.count.to_s
        halt 200, users.to_json
      rescue UsersNotFoundError
        logger.debug(log_message) {"Users not found"}
        halt 200, '[]'
      end
    end

    # GET a specific user
    get '/:name/?' do
      log_message = 'GtkApi:: GET /api/v2/services/:name'
      logger.debug(log_message) {"entered with #{params}"}

      if valid?(params[:name])
        # TODO: mind that, besides the URL-based uuid we might as well pass other params, like fields we want to show
        #params.delete :uuid
        user = User.find_by_name(params[:name])
        if user[:count] && !user[:items].empty?
          logger.debug(log_message) {"leaving with #{user}"}
          halt 200, user.to_json
        else
          logger.debug(log_message) {"leaving with message 'User #{params[:name]} not found'"}
          json_error 404, "User #{params[:name]} not found"
        end
      else
        message = "User #{params[:name]} not valid"
        logger.debug(log_message) {"leaving with message '"+message+"'"}
        json_error 404, message
      end
    end

    # GET .../api/v2/micro-services/users/public-key: To get the UM's public-key:
    get '/public-key/?' do
      log_message = 'GtkApi:: GET /api/v2/users/public-key'
      logger.debug(log_message) {"entered with #{params}"}

      begin
        pk = User.public_key
        logger.debug(log_message) {"leaving with #{pk}"}
        halt 200, pk.to_json
      rescue PublicKeyNotFoundError
        json_error 404, "No public key for the User Management micro-service was found", log_message
      end
    end
  end

  get '/api/v2/admin/users/logs/?' do
    log_message = 'GtkApi::GET /admin/users/logs'
    logger.debug(log_message) {'entered'}
    headers 'Content-Type' => 'text/plain; charset=utf8', 'Location' => '/'
    log = User.get_log(url:User.class_variable_get(:@@url)+'/admin/logs', log_message:log_message)
    logger.debug(log_message) {"leaving with log=#{log}"}
    halt 200, log
  end
end


text:
using UnityEngine;
using System.Collections;

public class InvaderControls : MonoBehaviour {

	public float horizontalForce;

	// Use this for initialization
	void Start () {
		GameObject[] objs = GameObject.FindGameObjectsWithTag("Human");
		foreach(GameObject o in objs) {
			HumanAi ai = o.GetComponent<HumanAi>();
			if( ai != null ) {
				ai.target = this.gameObject;
			}
		}
	}

	// Update is called once per frame
	void Update () {

	}
	void FixedUpdate() {
		float h = Input.GetAxis("Horizontal");

		rigidbody2D.AddForce(new Vector2(h * horizontalForce, 0));
	}
}


text:
{# Copyright (c) 2016-2017, NVIDIA CORPORATION.  All rights reserved. #}

{% from "helper.html" import print_flashes %}
{% from "helper.html" import print_errors %}
{% from "helper.html" import mark_errors %}

<small>Draw a bounding box around a detected object. The expected network output is a dictionary, keyed by class, where the values are lists of bounding boxes for that image. e.g. {'class1': [[l, t, r, b, confidence], ...], ...}</small>


text:
#ifndef _DECAF_UTIL_QUEUE_H_
#define _DECAF_UTIL_QUEUE_H_

#include <decaf/util/Config.h>
#include <decaf/util/Iterator.h>
#include <decaf/util/AbstractCollection.h>
#include <decaf/lang/Exception.h>
#include <decaf/lang/exceptions/IndexOutOfBoundsException.h>
#include <decaf/util/NoSuchElementException.h>

namespace decaf{
namespace util{

    /**
     * A kind of collection provides advanced operations than other basic
     * collections, such as insertion, extraction, and inspection.
     *
     * Generally, a queue orders its elements by means of first-in-first-out. While
     * priority queue orders its elements according to a comparator specified or the
     * elements' natural order. Furthermore, a stack orders its elements
     * last-in-first out.
     *
     * Queue does not provide blocking queue methods, which will block until the
     * operation of the method is allowed. BlockingQueue interface defines such
     * methods.
     *
     * Unlike the Java Queue interface the methods of this class cannot return null
     * to indicate that a Queue is empty since null has no meaning for elements such
     * as classes, structs and primitive types and cannot be used in a meaningful way
     * to check for an empty queue.  Methods that would have returned null in the
     * Java Queue interface have been altered to return a boolean value indicating if
     * the operation succeeded and take single argument that is a reference to the
     * location where the returned value is to be assigned.  This implies that elements
     * in the Queue must be assignable in order to utilize these methods.
     *
     * @since 1.0
     */
    template <typename E>
    class Queue : public virtual decaf::util::Collection<E> {
    public:

        virtual ~Queue() {}

        /**
         * Inserts the specified element into the queue provided that the condition
         * allows such an operation. The method is generally preferable to the
         * collection.add(E), since the latter might throw an exception if the
         * operation fails.
         *
         * @param value
         *        the specified element to insert into the queue.
         *
         * @return true if the operation succeeds and false if it fails.
         *
         * @throws NullPointerException if the Queue implementation does not allow Null values to
         *         be inserted into the Queue.
         * @throws IllegalArgumentException if some property of the specified
         *         element prevents it from being added to this queue
         */
        virtual bool offer( const E& value ) = 0;

        /**
         * Gets and removes the element in the head of the queue.  If the operation succeeds the
         * value of the element at the head of the Queue is assigned to the result parameter and
         * the method returns true.  If the operation fails the method returns false and the value
         * of the result parameter is undefined.
         *
         * @param result
         *        Reference to an instance of the contained type to assigned the removed value to.
         *
         * @return true if the element at the head of the queue was removed and assigned to the
         *         result parameter.
         */
        virtual bool poll( E& result ) = 0;

        /**
         * Gets and removes the element in the head of the queue. Throws a
         * NoSuchElementException if there is no element in the queue.
         *
         * @return the element in the head of the queue.
         *
         * @throws NoSuchElementException
         *         if there is no element in the queue.
         */
        virtual E remove() = 0;

        /**
         * Gets but not removes the element in the head of the queue.  The result if successful is
         * assigned to the result parameter.
         *
         * @param result
         *        Reference to an instance of the contained type to assigned the removed value to.
         *
         * @return true if the element at the head of the queue was removed and assigned to the
         *         result parameter.
         */
        virtual bool peek( E& result ) const = 0;

        /**
         * Gets but not removes the element in the head of the queue. Throws a
         * NoSuchElementException if there is no element in the queue.
         *
         * @return the element in the head of the queue.
         *
         * @throws NoSuchElementException if there is no element in the queue.
         */
        virtual E element() const = 0;

    };

}}

#endif /*_DECAF_UTIL_QUEUE_H_*/


text:
interface SwipeOptions {
    startSlide?: number;
    speed?: number;
    auto?: number;
    continuous?: boolean;
    disableScroll?: boolean;
    stopPropagation?: boolean;
    callback?: (index: number, elem: any) => void;
    transitionEnd?: (index: number, elem: any) => void;
    slideWidth?: number;
    breakDistance?: number;
}

declare class Swipe {
    constructor(container: HTMLElement, options: SwipeOptions);
    prev(): void;
    next(): void;
    getPos(): number;
    getNumSlides(): number;
    kill(): void;
    attachEvents(): void;
    setup(): void;
    slide(index: number, duration: number): void;
}


text:
package org.apache.camel.component.freemarker;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.camel.Category;
import org.apache.camel.Component;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.component.ResourceEndpoint;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.util.ObjectHelper;

/**
 * Transform messages using FreeMarker templates.
 */
@UriEndpoint(firstVersion = "2.10.0", scheme = "freemarker", title = "Freemarker", syntax = "freemarker:resourceUri",
             producerOnly = true, category = { Category.TRANSFORMATION })
public class FreemarkerEndpoint extends ResourceEndpoint {

    @UriParam(defaultValue = "false")
    private boolean allowTemplateFromHeader;
    @UriParam
    private String encoding;
    @UriParam
    private int templateUpdateDelay;
    @UriParam
    private Configuration configuration;

    public FreemarkerEndpoint() {
    }

    public FreemarkerEndpoint(String uri, Component component, String resourceUri) {
        super(uri, component, resourceUri);
    }

    @Override
    public ExchangePattern getExchangePattern() {
        return ExchangePattern.InOut;
    }

    @Override
    protected String createEndpointUri() {
        return "freemarker:" + getResourceUri();
    }

    public boolean isAllowTemplateFromHeader() {
        return allowTemplateFromHeader;
    }

    /**
     * Whether to allow to use resource template from header or not (default false).
     *
     * Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential
     * security vulnerability if the header is coming from a malicious user, so use this with care.
     */
    public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
        this.allowTemplateFromHeader = allowTemplateFromHeader;
    }

    /**
     * Sets the encoding to be used for loading the template file.
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public String getEncoding() {
        return encoding;
    }

    public int getTemplateUpdateDelay() {
        return templateUpdateDelay;
    }

    /**
     * Number of seconds the loaded template resource will remain in the cache.
     */
    public void setTemplateUpdateDelay(int templateUpdateDelay) {
        this.templateUpdateDelay = templateUpdateDelay;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    /**
     * Sets the Freemarker configuration to use
     */
    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public FreemarkerEndpoint findOrCreateEndpoint(String uri, String newResourceUri) {
        String newUri = uri.replace(getResourceUri(), newResourceUri);
        log.debug("Getting endpoint with URI: {}", newUri);
        return getCamelContext().getEndpoint(newUri, FreemarkerEndpoint.class);
    }

    @Override
    public void clearContentCache() {
        configuration.clearTemplateCache();
    }

    @Override
    protected void onExchange(Exchange exchange) throws Exception {
        String path = getResourceUri();
        ObjectHelper.notNull(configuration, "configuration");
        ObjectHelper.notNull(path, "resourceUri");

        if (allowTemplateFromHeader) {
            String newResourceUri = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_RESOURCE_URI, String.class);
            if (newResourceUri != null) {
                exchange.getIn().removeHeader(FreemarkerConstants.FREEMARKER_RESOURCE_URI);

                log.debug("{} set to {} creating new endpoint to handle exchange", FreemarkerConstants.FREEMARKER_RESOURCE_URI,
                        newResourceUri);
                FreemarkerEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
                newEndpoint.onExchange(exchange);
                return;
            }
        }

        Reader reader = null;
        String content = null;
        if (allowTemplateFromHeader) {
            content = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_TEMPLATE, String.class);
        }
        if (content != null) {
            // use content from header
            reader = new StringReader(content);
            // remove the header to avoid it being propagated in the routing
            exchange.getIn().removeHeader(FreemarkerConstants.FREEMARKER_TEMPLATE);
        }
        Object dataModel = null;
        if (allowTemplateFromHeader) {
            dataModel = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_DATA_MODEL, Object.class);
        }
        if (dataModel == null) {
            dataModel = ExchangeHelper.createVariableMap(exchange, isAllowContextMapAll());
        }
        // let freemarker parse and generate the result in buffer
        Template template;

        if (reader != null) {
            log.debug("Freemarker is evaluating template read from header {} using context: {}",
                    FreemarkerConstants.FREEMARKER_TEMPLATE, dataModel);
            template = new Template("temp", reader, new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
        } else {
            log.debug("Freemarker is evaluating {} using context: {}", path, dataModel);
            if (getEncoding() != null) {
                template = configuration.getTemplate(path, getEncoding());
            } else {
                template = configuration.getTemplate(path);
            }
        }
        StringWriter buffer = new StringWriter();
        template.process(dataModel, buffer);
        buffer.flush();

        // now lets output the results to the exchange
        Message out = exchange.getOut();
        out.setBody(buffer.toString());
        out.setHeaders(exchange.getIn().getHeaders());
    }
}


text:
CMICmdCmdTraceStatus::CMICmdCmdTraceStatus() {
  // Command factory matches this name with that received from the stdin stream
  m_strMiCmd = "trace-status";

  // Required by the CMICmdFactory when registering *this command
  m_pSelfCreatorFn = &CMICmdCmdTraceStatus::CreateSelf;
}

//++
//------------------------------------------------------------------------------------
// Details: CMICmdCmdTraceStatus destructor.
// Type:    Overrideable.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdCmdTraceStatus::~CMICmdCmdTraceStatus() {}

//++
//------------------------------------------------------------------------------------
// Details: The invoker requires this function. The command does work in this
// function.
//          The command is likely to communicate with the LLDB SBDebugger in
//          here.
// Type:    Overridden.
// Args:    None.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool CMICmdCmdTraceStatus::Execute() {
  // Do nothing
  return MIstatus::success;
}

//++
//------------------------------------------------------------------------------------
// Details: The invoker requires this function. The command prepares a MI Record
// Result
//          for the work carried out in the Execute().
// Type:    Overridden.
// Args:    None.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool CMICmdCmdTraceStatus::Acknowledge() {
  const CMICmnMIValueConst miValueConst(MIRSRC(IDS_CMD_ERR_NOT_IMPLEMENTED));
  const CMICmnMIValueResult miValueResult("msg", miValueConst);
  const CMICmnMIResultRecord miRecordResult(
      m_cmdData.strMiCmdToken, CMICmnMIResultRecord::eResultClass_Error,
      miValueResult);
  m_miResultRecord = miRecordResult;

  return MIstatus::success;
}

//++
//------------------------------------------------------------------------------------
// Details: Required by the CMICmdFactory when registering *this command. The
// factory
//          calls this function to create an instance of *this command.
// Type:    Static method.
// Args:    None.
// Return:  CMICmdBase * - Pointer to a new command.
// Throws:  None.
//--
CMICmdBase *CMICmdCmdTraceStatus::CreateSelf() {
  return new CMICmdCmdTraceStatus();
}


text:
require 'whois/record/parser/base'

module Whois
  class Record
    class Parser

      # Parser for the whois.dk-hostmaster.dk server.
      #
      # @note This parser is just a stub and provides only a few basic methods
      #   to check for domain availability and get domain status.
      #   Please consider to contribute implementing missing methods.
      #
      # @see Whois::Record::Parser::Example
      #   The Example parser for the list of all available methods.
      #
      # @author Simone Carletti <weppos@weppos.net>
      # @author Mikkel Kristensen <mikkel@tdx.dk>
      #
      class WhoisDkHostmasterDk < Base

        property_supported :status do
          if content_for_scanner =~ /Status:\s+(.+?)\n/
            case $1.downcase
              when "active"
                :registered
              when "deactivated"
                :expired
              else
                Whois.bug!(ParserError, "Unknown status `#{$1}'.")
            end
          else
            :available
          end
        end

        property_supported :available? do
          !!(content_for_scanner =~ /^No entries found for the selected source/)
        end

        property_supported :registered? do
          !available?
        end

        property_supported :created_on do
          if content_for_scanner =~ /Registered:\s+(.*)\n/
            Time.parse($1)
          end
        end

        property_not_supported :updated_on

        property_supported :expires_on do
          if content_for_scanner =~ /Expires:\s+(.*)\n/
            Time.parse($1)
          end
        end

        property_supported :nameservers do
          content_for_scanner.scan(/Hostname:\s+(.+)\n/).flatten.map do |name|
            Record::Nameserver.new(:name => name)
          end
        end

      end

    end
  end
end


text:
(function () {
    'use strict';

    angular
        .module('app.core')
        .provider('routerConfig', routerConfig)
        .factory('router', router);

    /********************* RouterConfig Provider *********************/
    function routerConfig() {
        /* jshint validthis:true */
        this.config = {
            // The following properties are setup within the app.module.js file during the initial app configuration.
            //      $stateProvider: undefined
            //      resolveAlways: {ready: function(){ } }
        };

        this.$get = function () {
            return {
                config: this.config
            };
        };
    }

    /********************** Router Service **********************/

    router.$inject = ['$rootScope'];

    function router($rootScope) {

        var stateWatchers = [];

        var service = {
            registerStateChangedListener: registerStateChangedListener,
            subscribeStateChange: subscribeStateChange,
            unsubscribeStateChange: unsubscribeStateChange
        };

        init();

        return service;

        /*************************** IMPLEMENTATION ***************************/

        function init() {
            $rootScope.$on('$stateChangeStart', onStateChangeStart);
            $rootScope.$on('$stateChangeSuccess', onStateChangeSuccess);
        }

        // #region STATE CHANGE WATCHERS
        // Let views be notified when the user is about to navigate away or to a given state (page)
        function subscribeStateChange(stateName, leavingCallback, enteringCallback) {
            var foundIndex = _.indexOf(stateWatchers, _.findWhere(stateWatchers, { stateName: stateName }));
            var newWatcher = null;

            if (foundIndex >= 0) {
                console.warn('Warning: state name has already been subscribed (' + stateName + ')');
                return;
            }

            newWatcher = {
                stateName: stateName,
                leavingCallback: leavingCallback,
                enteringCallback: enteringCallback
            };

            stateWatchers.push(newWatcher);
        }

        function unsubscribeStateChange(stateName) {
            var foundIndex = _.indexOf(stateWatchers, _.findWhere(stateWatchers, { stateName: stateName }));
            if (foundIndex >= 0) {
                stateWatchers.splice(foundIndex, 1);
            }
        }
        // #endregion

        function onStateChangeSuccess(event, toState, toParams, fromState, fromParams) {
            // Unfortunately, bootstraps tooltips can get stuck. At least clear them when the user navigates.
            clearAllTooltips();
        }

        function clearAllTooltips() {
            // When an item is removed from the DOM that has a tooltip, the tooltip can get stuck and never go away.
            // See https://github.com/twbs/bootstrap/issues/3084
            // But I find that there are other ways in which toolstips can get stuck. This one liner ensures all are turned off.
            $('.tooltip.in').remove();
        }

        function registerStateChangedListener(callback) {
            $rootScope.$on('$stateChangeSuccess', callback);
        }

        function onStateChangeStart(event, toState, toParams, fromState, fromParams) {
            stateWatchers.forEach(function (stateWatcher) {
                var stateChange = null;
                // Does the state change match the current watcher?
                if (stateWatcher.stateName === toState.name || new RegExp(stateWatcher.stateName, 'i').test(toState.name)) {
                    stateChange = 'entering';
                } else if (stateWatcher.stateName === fromState.name || new RegExp(stateWatcher.stateName, 'i').test(fromState.name)) {
                    stateChange = 'leaving';
                }

                if (stateChange) {
                    var callback = null;
                    var arg = null;
                    if (stateChange === 'entering') {
                        callback = stateWatcher.enteringCallback;
                        arg = toState;
                    } else {
                        callback = stateWatcher.leavingCallback;
                        arg = fromState;
                    }

                    if (callback && callback(arg) === false) {
                        event.preventDefault();
                    }
                }
            });
        }
        // #endregion
    }
})();


text:
<?php

namespace TinyApp\Exception;

use TinyApp\Exception\TemplateException;

/**
 * Exception must be thrown if given template not found.
 */
class TemplateNotFoundException extends TemplateException {}


text:
using System;

namespace agsXMPP.Idn
{
	public class StringprepException : Exception
	{
		public static string CONTAINS_UNASSIGNED    = "Contains unassigned code points.";
		public static string CONTAINS_PROHIBITED    = "Contains prohibited code points.";
		public static string BIDI_BOTHRAL           = "Contains both R and AL code points.";
		public static string BIDI_LTRAL             = "Leading and trailing code points not both R or AL.";

        public StringprepException(string message) : base(message)
		{
		}
	}
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.VisualStudio.Text;

namespace Microsoft.PythonTools.Intellisense {
    /// <summary>
    /// Provides information about names which are missing import statements but the
    /// name refers to an identifier in another module.
    ///
    /// New in 1.1.
    /// </summary>
    public sealed class MissingImportAnalysis {
        internal static MissingImportAnalysis Empty = new MissingImportAnalysis();
        private readonly ITrackingSpan _span;
        private readonly string _name;
        private readonly VsProjectAnalyzer _analyzer;
        private IEnumerable<ExportedMemberInfo> _imports;

        private MissingImportAnalysis() {
            _imports = Enumerable.Empty<ExportedMemberInfo>();
        }

        internal MissingImportAnalysis(string name, VsProjectAnalyzer state, ITrackingSpan span) {
            _span = span;
            _name = name;
            _analyzer = state;
        }

        /// <summary>
        /// The locations this name can be imported from.  The names are fully qualified with
        /// the module/package names and the name its self.  For example for "fob" defined in the "oar"
        ///  module the name here is oar.fob.  This list is lazily calculated (including loading of cached intellisense data)
        ///  so that you can break from the enumeration early and save significant work.
        /// </summary>
        /// <remarks>New in 2.2</remarks>
        public async Task<IEnumerable<ExportedMemberInfo>> GetAvailableImportsAsync(CancellationToken cancellationToken) {
            if (_imports != null) {
                return _imports;
            }

            var imports = await _analyzer.FindNameInAllModulesAsync(_name, cancellationToken);
            cancellationToken.ThrowIfCancellationRequested();
            return Interlocked.CompareExchange(ref _imports, imports, null) ?? imports;
        }

        /// <summary>
        /// The span which covers the identifier used to trigger this missing import analysis.
        /// </summary>
        public ITrackingSpan ApplicableToSpan {
            get {
                return _span;
            }
        }
    }
}


text:
To read the content of resources, the HTTP GET method is used.  The URI
to the resource will determine if an individual resource, all resources,
or some resources will be retrieved.

Reading the entire available resource list is done by simply calling the
API GET method with the collection URI and no parameters.  All data for
that resource will be returned.  An example of this API call is:

        GET /collection

It is also possible to page through the available resources.  This is
useful when there are many resources and the client wants to start
using the available list prior to receiving the entire list; for example
to start building a table in the user interface with the first entries
before the entire set of data has been received.

Reading partial lists is done by providing query parameters to the GET
method call that indicate the starting index (`start`) and number of
entries (`span`) to return.  The starting index is the offset in the
entire list from the first entry.  For example, calling

        GET /collection?start=51;span=50

will return the second 50 elements of the '/stations' resource that
are available.  Clients should be aware that if the resource collection
is updated between calls to these partial reads occur, the list being
accessed will not remain unchanged.

Individual resources can be read by simply adding the {resourceid} value
as the next element in the URI path:

        GET /collection/{rescourceid}

### Searching for Resources

It is possible to search for resources of a type.  This is done by using
the HTTP GET method at a URI relative to the resource being searched for.
Access from search is restricted to reading and effectively returns
those records that meet the search criteria.

Search URIs will be formed similar to:

        GET /search/collection?query=<query-string>

Query string formats have not been finalized at this time.


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/toolbar"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/actionBarColor"
    style="@style/ToolBarStyle"
    app:theme="@style/ActionBarThemeOverlay"
    app:popupTheme="@style/ActionBarPopupThemeOverlay"
    >

</android.support.v7.widget.Toolbar>


text:
import Vue from 'vue'
import Router from 'vue-router'
import Vnc from '@/components/Vnc'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Vnc',
      component: Vnc
    }
  ]
})


text:
USB DMA
~~~~~~~

In Linux 2.5 kernels (and later), USB device drivers have additional control
over how DMA may be used to perform I/O operations.  The APIs are detailed
in the kernel usb programming guide (kerneldoc, from the source code).

API overview
============

The big picture is that USB drivers can continue to ignore most DMA issues,
though they still must provide DMA-ready buffers (see
``Documentation/DMA-API-HOWTO.txt``).  That's how they've worked through
the 2.4 (and earlier) kernels, or they can now be DMA-aware.

DMA-aware usb drivers:

- New calls enable DMA-aware drivers, letting them allocate dma buffers and
  manage dma mappings for existing dma-ready buffers (see below).

- URBs have an additional "transfer_dma" field, as well as a transfer_flags
  bit saying if it's valid.  (Control requests also have "setup_dma", but
  drivers must not use it.)

- "usbcore" will map this DMA address, if a DMA-aware driver didn't do
  it first and set ``URB_NO_TRANSFER_DMA_MAP``.  HCDs
  don't manage dma mappings for URBs.

- There's a new "generic DMA API", parts of which are usable by USB device
  drivers.  Never use dma_set_mask() on any USB interface or device; that
  would potentially break all devices sharing that bus.

Eliminating copies
==================

It's good to avoid making CPUs copy data needlessly.  The costs can add up,
and effects like cache-trashing can impose subtle penalties.

- If you're doing lots of small data transfers from the same buffer all
  the time, that can really burn up resources on systems which use an
  IOMMU to manage the DMA mappings.  It can cost MUCH more to set up and
  tear down the IOMMU mappings with each request than perform the I/O!

  For those specific cases, USB has primitives to allocate less expensive
  memory.  They work like kmalloc and kfree versions that give you the right
  kind of addresses to store in urb->transfer_buffer and urb->transfer_dma.
  You'd also set ``URB_NO_TRANSFER_DMA_MAP`` in urb->transfer_flags::

	void *usb_alloc_coherent (struct usb_device *dev, size_t size,
		int mem_flags, dma_addr_t *dma);

	void usb_free_coherent (struct usb_device *dev, size_t size,
		void *addr, dma_addr_t dma);

  Most drivers should **NOT** be using these primitives; they don't need
  to use this type of memory ("dma-coherent"), and memory returned from
  :c:func:`kmalloc` will work just fine.

  The memory buffer returned is "dma-coherent"; sometimes you might need to
  force a consistent memory access ordering by using memory barriers.  It's
  not using a streaming DMA mapping, so it's good for small transfers on
  systems where the I/O would otherwise thrash an IOMMU mapping.  (See
  ``Documentation/DMA-API-HOWTO.txt`` for definitions of "coherent" and
  "streaming" DMA mappings.)

  Asking for 1/Nth of a page (as well as asking for N pages) is reasonably
  space-efficient.

  On most systems the memory returned will be uncached, because the
  semantics of dma-coherent memory require either bypassing CPU caches
  or using cache hardware with bus-snooping support.  While x86 hardware
  has such bus-snooping, many other systems use software to flush cache
  lines to prevent DMA conflicts.

- Devices on some EHCI controllers could handle DMA to/from high memory.

  Unfortunately, the current Linux DMA infrastructure doesn't have a sane
  way to expose these capabilities ... and in any case, HIGHMEM is mostly a
  design wart specific to x86_32.  So your best bet is to ensure you never
  pass a highmem buffer into a USB driver.  That's easy; it's the default
  behavior.  Just don't override it; e.g. with ``NETIF_F_HIGHDMA``.

  This may force your callers to do some bounce buffering, copying from
  high memory to "normal" DMA memory.  If you can come up with a good way
  to fix this issue (for x86_32 machines with over 1 GByte of memory),
  feel free to submit patches.

Working with existing buffers
=============================

Existing buffers aren't usable for DMA without first being mapped into the
DMA address space of the device.  However, most buffers passed to your
driver can safely be used with such DMA mapping.  (See the first section
of Documentation/DMA-API-HOWTO.txt, titled "What memory is DMA-able?")

- When you're using scatterlists, you can map everything at once.  On some
  systems, this kicks in an IOMMU and turns the scatterlists into single
  DMA transactions::

	int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
		struct scatterlist *sg, int nents);

	void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
		struct scatterlist *sg, int n_hw_ents);

	void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
		struct scatterlist *sg, int n_hw_ents);

  It's probably easier to use the new ``usb_sg_*()`` calls, which do the DMA
  mapping and apply other tweaks to make scatterlist i/o be fast.

- Some drivers may prefer to work with the model that they're mapping large
  buffers, synchronizing their safe re-use.  (If there's no re-use, then let
  usbcore do the map/unmap.)  Large periodic transfers make good examples
  here, since it's cheaper to just synchronize the buffer than to unmap it
  each time an urb completes and then re-map it on during resubmission.

  These calls all work with initialized urbs:  ``urb->dev``, ``urb->pipe``,
  ``urb->transfer_buffer``, and ``urb->transfer_buffer_length`` must all be
  valid when these calls are used (``urb->setup_packet`` must be valid too
  if urb is a control request)::

	struct urb *usb_buffer_map (struct urb *urb);

	void usb_buffer_dmasync (struct urb *urb);

	void usb_buffer_unmap (struct urb *urb);

  The calls manage ``urb->transfer_dma`` for you, and set
  ``URB_NO_TRANSFER_DMA_MAP`` so that usbcore won't map or unmap the buffer.
  They cannot be used for setup_packet buffers in control requests.

Note that several of those interfaces are currently commented out, since
they don't have current users.  See the source code.  Other than the dmasync
calls (where the underlying DMA primitives have changed), most of them can
easily be commented back in if you want to use them.


text:
package org.hubotek.service.http;

public enum RequestType {

	GET,
	POST,
	HEAD,
	PUT,
	PATCH,
	DELETE;

}


text:
import warning from 'warning';
import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';

export function titleize(string) {
  warning(
    typeof string === 'string' && string.length > 0,
    'titleize(string) expects a non empty string argument.',
  );

  return string
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

export function pageToTitle(page) {
  if (page.title) {
    return page.title;
  }

  const name = page.pathname.replace(/.*\//, '');

  if (page.pathname.indexOf('/api/') !== -1) {
    return upperFirst(camelCase(name));
  }

  return titleize(name);
}

export function getDependencies(raw, reactVersion = 'latest') {
  const deps = {
    'react-dom': reactVersion,
    react: reactVersion,
  };
  const versions = {
    'date-fns': 'next',
  };
  const re = /^import\s.*\sfrom\s+'([^']+)|import\s'([^']+)'/gm;
  let m;
  // eslint-disable-next-line no-cond-assign
  while ((m = re.exec(raw))) {
    let name;

    if (m[1]) {
      // full import
      // handle scope names
      name = m[1].charAt(0) === '@' ? m[1].split('/', 2).join('/') : m[1].split('/', 1)[0];
    } else {
      name = m[2];
    }

    if (!deps[name]) {
      deps[name] = versions[name] ? versions[name] : 'latest';
    }
  }
  return deps;
}

export function getCookie(name) {
  const regex = new RegExp(`(?:(?:^|.*;*)${name}*=*([^;]*).*$)|^.*$`);
  return document.cookie.replace(regex, '$1');
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorAccent" />

    <ImageView
        android:id="@+id/image_location"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="fitXY" />
</LinearLayout>