text:
#ifndef Poedit_http_client_h
#define Poedit_http_client_h

#ifdef HAVE_HTTP_CLIENT

#include "concurrency.h"
#include "json.h"

#include <exception>
#include <map>
#include <memory>
#include <string>

class http_client;

/// Abstract base class for encoded body data
class http_body_data
{
public:
    http_body_data() {}
    virtual ~http_body_data() {}

    /// Content-Type header to use with the data.
    virtual std::string content_type() const = 0;

    /// Returns generated body of the request.
    virtual std::string body() const = 0;
};

/// Stores POSTed data (RFC 1867)
class multipart_form_data : public http_body_data
{
public:
    multipart_form_data();

    /// Add a form value.
    void add_value(const std::string& name, const std::string& value);

    /// Add file upload.
    void add_file(const std::string& name, const std::string& filename, const std::string& file_content);

    std::string content_type() const override;
    std::string body() const override;

private:
    std::string m_boundary;
    std::string m_body;
};

/// Stores application/x-www-form-urlencoded data
class urlencoded_data : public http_body_data
{
public:
    /// Add a form value.
    void add_value(const std::string& name, const std::string& value);

    std::string content_type() const override { return "application/x-www-form-urlencoded"; }
    std::string body() const override { return m_body; }

private:
    std::string m_body;
};

/// Stores application/json data
class json_data : public http_body_data
{
public:
    json_data(const json& data);

    std::string content_type() const override { return "application/json"; }
    std::string body() const override { return m_body; }

private:
    std::string m_body;
};

/**
    Client for accessing HTTP REST APIs.
 */
class http_client
{
public:
    /// Connection flags for the client.
    enum flags
    {
        // currently no flags are used
        default_flags = 0
    };

    /**
        Creates an instance of the client object.

        The client is good for accessing URLs with the provided prefix
        (which may be any prefix, not just the hostname).

        @param flags OR-combination of http_client::flags values.
     */
    http_client(const std::string& url_prefix, int flags = default_flags);
    virtual ~http_client();

#ifndef __DARWIN__
    /// Sets Accept-Language to use (language tag; managed automatically on macOS)
    static void set_ui_language(const std::string& lang);
#endif

    /// Return true if the server is reachable, i.e. client is online
    bool is_reachable() const;

    /// Sets Authorization header to be used in all requests
    void set_authorization(const std::string& auth);

    /// Perform a GET request at the given URL
    dispatch::future<json> get(const std::string& url);

    /**
        Perform a GET request and store the body in a file.

        Returned response's body won't be accessible in any way from @a handler.
     */
    dispatch::future<void> download(const std::string& url, const std::wstring& output_file);

    /**
        Perform a POST request with multipart/form-data formatted @a params.
     */
    dispatch::future<json> post(const std::string& url, const http_body_data& data);

    // Helper for encoding text as URL-encoded UTF-8

    enum encode_flags
    {
        encode_no_plus = 1,     // don't encode spaces as +
        encode_keep_slash = 2,  // don't encode / as %2f
    };

    static std::string url_encode(const std::string& s, int flags = 0);
    static std::string url_encode(const std::wstring& s, int flags = 0);

protected:
    /**
        Extract more detailed, client specific error response from the
        JSON body of error response, if available.

        Does nothing by default, but can be overridden in derived class.
     */
    virtual std::string parse_json_error(const json& /*response*/) const
        { return std::string(); }

    /**
         Called when an error response is returned, before calling error handler.

         Can be used to react to specific errors, e.g. invalidate expired OAuth tokens,
         or to modify the response.
     */
    virtual void on_error_response(int& /*statusCode*/, std::string& /*message*/) {};

private:
    class impl;
    std::unique_ptr<impl> m_impl;
};

#endif // HAVE_HTTP_CLIENT

#endif // Poedit_http_client_h


text:
About Andela

Are you ready for the truth?

Well, the way they make shows is, they make one show. That show's called a pilot. Then they show that show to the people who make shows, and on the strength of that one show they decide if they're going to make more shows. Some pilots get picked and become television programs. Some don't, become nothing. She starred in one of the ones that became nothing.

Uuummmm, this is a tasty burger!

Like you, I used to think the world was this great place where everybody lived by the same standards I did, then some kid with a nail showed me I was living in his world, a world where chaos rules not order, a world where righteousness is not rewarded. That's Cesar's world, and if you're not willing to play by his rules, then you're gonna have to pay the price.

I took lessons

The lysine contingency - it's intended to prevent the spread of the animals is case they ever got off the island. Dr. Wu inserted a gene that makes a single faulty enzyme in protein metabolism. The animals can't manufacture the amino acid lysine. Unless they're continually supplied with lysine by us, they'll slip into a coma and die.

Uuummmm, this is a tasty burger!

Well, the way they make shows is, they make one show. That show's called a pilot. Then they show that show to the people who make shows, and on the strength of that one show they decide if they're going to make more shows. Some pilots get picked and become television programs. Some don't, become nothing. She starred in one of the ones that became nothing.

So, you cold?

Yeah, I like animals better than people sometimes... Especially dogs. Dogs are the best. Every time you come home, they act like they haven't seen you in a year. And the good thing about dogs... is they got different dogs for different people. Like pit bulls. The dog of dogs. Pit bull can be the right man's best friend... or the wrong man's worst enemy. You going to give me a dog for a pet, give me a pit bull. Give me... Raoul. Right, Omar? Give me Raoul.

We happy?

The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.

Uuummmm, this is a tasty burger!

Yeah, I like animals better than people sometimes... Especially dogs. Dogs are the best. Every time you come home, they act like they haven't seen you in a year. And the good thing about dogs... is they got different dogs for different people. Like pit bulls. The dog of dogs. Pit bull can be the right man's best friend... or the wrong man's worst enemy. You going to give me a dog for a pet, give me a pit bull. Give me... Raoul. Right, Omar? Give me Raoul.

lorem ipsum

   ...

redpajama_set_name: RedPajamaGithub


text:
LongExposureInfraredFrameReader Events
======================================

Events
======

<colgroup>
<col width="30%" />
<col width="60%" />
</colgroup>

Name
Description

FrameArrived
Event that fires whenever a frame is captured.

PropertyChanged
Occurs when a property of the LongExposureInfraredFrameReader class changes.

See also
========

#### Reference

[LongExposureInfraredFrameReader Class](../LongExposureInfraredFrameR.md)
 [WindowsPreview.Kinect Namespace](../../Kinect.md)


text:
package maps

import . "github.com/objecthub/containerkit"
import "github.com/objecthub/containerkit/impl"

var HashMap MutableMapClass = HashMapClass(UniversalHash, UniversalEquality)

var ImmutableHashMap MapClass = ImmutableMap(HashMap)

func HashMapClass(hash Hashfunction, equals Equality) MutableMapClass {
  return &hashMapClass{hash, equals}
}

type hashMapClass struct {
  hash Hashfunction
  equals Equality
}

func (this *hashMapClass) Embed(obj MutableMap) MutableMap {
  res := new(hashMap)
  if obj == nil {
    obj = res
  }
  res.obj = obj
  res.MutableMapDerived = EmbeddedMutableMap(obj)
  res.table = impl.NewHashTable(17, 80, this.hash, this.equals)
  return res
}

func (this *hashMapClass) New(entries... MapEntry) MutableMap {
  res := this.Embed(nil)
  res.IncludeEntry(entries...)
  return res
}

func (this *hashMapClass) From(coll Container) MutableMap {
  res := this.Embed(nil)
  res.IncludeFrom(coll)
  return res
}

func (this *hashMapClass) FromNative(mp map[interface{}] interface{}) MutableMap {
  res := this.Embed(nil)
  res.IncludeFromNative(mp)
  return res
}

type MutableHashMap interface {
  MutableMap
  Print()
}

type hashMap struct {
  obj MutableMap
  table *impl.HashTable
  MutableMapDerived
}

func (this *hashMap) Size() int {
  return this.table.Size()
}

func (this *hashMap) Get(key interface{}) (value interface{}, exists bool) {
  if entry := this.table.FindEntry(key); entry != nil {
    return entry.Value, true
  }
  return nil, false
}

func (this *hashMap) Elements() Iterator {
  return &hashMapIterator{this.table.Iterator()}
}

func (this *hashMap) Class() MutableMapClass {
  return HashMapClass(this.table.Hash(), this.table.Equality())
}

func (this *hashMap) Include(key, value interface{}) {
  if entry := this.table.FindEntry(key); entry == nil {
    this.table.AddEntry(key, value)
  } else {
    entry.Value = value
  }
}

func (this *hashMap) Exclude(keys ...interface{}) {
  for _, key := range keys {
    this.table.DeleteEntry(key)
  }
}

func (this *hashMap) Clear() {
  this.table.Clear()
}

type hashMapIterator struct {
  hashEntryIter *impl.HashEntryIterator
}

func (this *hashMapIterator) HasNext() bool {
  return this.hashEntryIter.HasNext()
}

func (this *hashMapIterator) Next() interface{} {
  entry := this.hashEntryIter.Next()
  return KV(entry.Key, entry.Value)
}

func (this *hashMap) Print() {
  this.table.Print()
}


text:
function accordionItem(header, body) {
	return '
' + header + '

' + body + '
';
}

function createLogin(id, name, address, form, vars) {
	var hocid = 0;
	function collapsible(name, value, cp) {
		var copy = '';
		if (cp)
			copy = copyToClipboard(value);

		return '
' + name + ' ' + copy + '

' + value + '
';
	}

	var title = name + " (" + vars.name + ")"

	var r = "";

	if (!loginBroken(form)) {
		var flat = flattenMap(form.fields);

		var token = withToken(form);
		if (token != "") {
			r += '@text.get_token@';
			r += '@text.log_in@';
		} else {
			r += '@text.log_in@';
		}
	}

	r += '@text.goto@';
	r += '
' + collapsible("@text.username@", vars.name, true) + '
';
	r += '
' + collapsible("@text.password@", vars.password, true) + '
';

	if (vars.secret)
		r += '
' + collapsible("@text.secret@", vars.secret, false) + '
';

	if (vars.note)
		r += '
' + collapsible("@text.note@", addBr(vars.note), false) + '
';

	return accordionItem(title, r);
}

function viewCreatePageEntry(id, type, data) {
	if (type == 'login')
		return createLogin(id, data.name, data.address, data.form, data.vars);
	else
		return accordionItem(data.name, addBr(data.text));
}

function viewCreateListEntry(id, type, data) {
	return "";
}

function viewWrapPageTag(tag, text) {
	if (tag != '__default__')
		tag = '
' + tag + '
';
	else
		tag = '';

	return tag + '

' + text + '

';
}

function viewWrapListTag(tag, text) {
	return text;
}

function viewWrapPage(text) {
	return text;
}

function viewWrapList(text) {
	return text;
}

function lock() {
	lockTimeoutStop();

	if ($("#div-locked").is(":visible") && $("#div-unlocked").is(":visible")) {
		$("#div-generate").hide();
		$("#div-token").hide();
		$("#div-unlocked").hide();
	} else {
		$("#div-generate").dialog('close');
		$("#div-token").dialog('close');

		$("#div-locked").fadeIn();
		$("#div-unlocked").hide();
	}

	$(".generated").remove();
	$("#tabs").html('');
	$("#tabs").removeClass();

	$("#input-password").focus();
}

function dialogGenerateSubmit() {
	$("#intput-generated-password").val(generatePassword(
		$("#input-password-length").val(),
		$("#input-include-num").is(":checked"),
		$("#input-include-punc").is(":checked"),
		$("#input-include-uc").is(":checked"),
		$("#input-pronounceable").is(":checked")));
}

function dialogLoginSubmit(url, name, keys, values, tokens) {
	var formJson = $("#input-json").val();

	if (!formJson || formJson == "")
		return;

	$("#input-json").val("");
	$("#div-token").dialog('close');

	loginWithTokenData(url, name, keys, values, formJson);
}

function loginWithToken(url, name, keys, values, tokens) {
	$("#div-token").dialog({
		height: 140,
		width: 280,
		modal: true,
		buttons: {
			"Login": function() { dialogLoginSubmit(url, name, keys, values, tokens); },
			"Cancel": function() { $(this).dialog('close'); }
		}
	});

	$("#div-token").keydown(function(event) {
		if (event.keyCode == $.ui.keyCode.ENTER) {
			dialogLoginSubmit(url, name, keys, values, tokens);
		}
	});
}

$(document).ready(function() {
	lock();

	$(".button").button();

	$("#button-unlock").button({ icons: { primary: "ui-icon-unlocked" } });
	$("#button-lock").button({ icons: { primary: "ui-icon-locked" } });
	$("#button-generate-show").button({ icons: { primary: "ui-icon-gear" } });

	$("#form-unlock").submit(function(event) {
		event.preventDefault();
		try {
			var map = unlock($("#input-password").val());
			$("#input-password").val("");

			var tabs_list = '';
			var tabs = "";
			for (var key in map.page) {
				var name = key;
				if (cfg.page[key])
					name = cfg.page[key];

				tabs_list += '
' + name + '
';
				tabs += '
' + map.page[key] + '
';
			}

			$("#div-tabs").html('

' + tabs_list + '
' + tabs + '
');

			$(".button").button();
			$(".accordion").accordion({
				autoHeight: false,
				navigation: false,
				active: false,
				/* animated: false, */
				collapsible: true
			});
			$('.expand').click(function() {
				event.preventDefault();

				$(this).children().toggleClass('ui-icon-circlesmall-plus ui-icon-circlesmall-minus');
				$(this).next().toggle();
			}).next().hide();

			$("#tabs").tabs();
			$("#tabs").tabs('select', 0);

			$(".button-bookmark").button({ icons: { primary: "ui-icon-contact" } });
			$(".button-goto").button({ icons: { primary: "ui-icon-newwin" } });
			$(".button-login").button({ icons: { primary: "ui-icon-key" } });

			lockTimeoutStart();

			$("#div-locked").hide();
			$("#div-unlocked").fadeIn();

			$("#input-filter").focus();
		} catch(e) {
			alert("@text.incorrect_password@ " + e);
			return;
		}
	});

	$("body").mousemove(function() { lockTimeoutUpdate(); });

	$("#button-lock").click(function(event) {
		event.preventDefault();
		lock();
	});

	$("#button-generate-show").click(function(event) {
		event.preventDefault();
		$("#div-generate").dialog({
			resizable: false,
			buttons: {
				"Generate": function() { dialogGenerateSubmit(); },
				"Cancel": function() { $(this).dialog('close'); }
			}
		});
		$("#div-generate").keydown(function(event) {
			if (event.keyCode == $.ui.keyCode.ENTER) {
				dialogGenerateSubmit();
			}
		});
	});

	$("#input-pronounceable").click(function() {
		if ($("#input-pronounceable").is(":checked")) {
			$("#input-include-num").attr("disabled", true);
			$("#input-include-punc").attr("disabled", true);
		} else {
			$("#input-include-num").removeAttr("disabled");
			$("#input-include-punc").removeAttr("disabled");
		}
	});

	$("#input-filter").keyup(function() {
		var text = $("#input-filter").val().toLowerCase();

		if (text == "") {
			$("h3.ui-accordion-header").show();
			$("h4.tag-header").show();
		} else {
			$(".accordion").accordion('activate', false);
			$("h3.ui-accordion-header").hide();
			$("h4.tag-header").hide();
			$("h3.ui-accordion-header").filter(function() {
				if ($('a', this).html().toLowerCase().indexOf(text) >= 0)
					return true;
				else
					return false;
			}).show();
		}
	});
});


text:
import {Config as ViewManagerConfig} from 'aurelia-view-manager';
import {getLogger} from 'aurelia-logging';

export const logger = getLogger('aurelia-form');

export * from './decorator/index';

export function configure(aurelia, config) {
  aurelia.aurelia.use.plugin('aurelia-view-manager');

  aurelia.container.get(ViewManagerConfig).configureNamespace('spoonx/form', {
    location: './view/{{framework}}/{{view}}.html'
  });

  let defaultComponents = [
    'aurelia-form',
    'form-element',
    'form-label',
    'form-button',
    'form-help',
    'form-error',
    'form-group',
    'entity-form'
  ];

  let defaultElements = [
    'input',
    'checkbox',
    'radio',
    'select',
    'textarea',
  ];

  aurelia.globalResources(
    './attribute/attributes',
    './attribute/prefixed',
    ...defaultComponents.map(component => `./component/${component}`),
    ...defaultElements.map(component => `./component/form-${component}`)
  );

  defaultElements.forEach(element => {
    config.elements[element] = `form-${element}`
  });
}

export const config = {
  'aurelia-form': {
    defaultElement: 'input',
    submitButton  : {
      enabled: true,
      options: ['primary'],
      label  : 'Submit'
    },
    elements      : {},
    validation    : {},
    aliases       : {
      enum   : 'radio',
      int    : 'input',
      integer: 'input',
      number : 'input',
      float  : 'input',
      string : 'input',
      bool   : 'checkbox',
      boolean: 'checkbox',
      text   : 'textarea'
    }
  }
};


text:
package org.apache.turbine.services.weather;

import org.apache.turbine.services.TurbineServices;

/**
 *
 *
 * @author Jason van Zyl
 */
public class TurbineWeather
{
    /**
     * Utility method for accessing the service
     * implementation
     *
     * @return a WeatherService implementation instance
     */
    protected static WeatherService getService()
    {
        return (WeatherService)TurbineServices
            .getInstance().getService(WeatherService.SERVICE_NAME);
    }
}


text:
Go HttpService
==============

HTTP methods I use a lot.

## Basic HTTP Responses
This package offers a simple structure for sending back basic HTTP responses. This structure has two keys: *Success* and *Message*. To create a message one can use the method **NewBasicJsonResponse()** like so.

```golang
import (
    "github.com/adampresley/GoHttpService"
)

func DoSomething() {
    response := GoHttpService.NewBasicJsonResponse(true, "Everything worked great")
}
```

There are simplier methods for the most common operations such as responding with an error or success. The following samples illustrate these.

```golang
import (
    "net/http"

    "github.com/adampresley/GoHttpService"
)

/*
{ "success": false, "message": "An error occurred" }
*/
func AnError(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.Error(writer, "An error occurred")
}

/*
{ "success": false, "message": "Bad request sir!" }
*/
func BadRequest(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.BadRequest(writer, "Bad request sir!")
}

/*
{ "success": false, "message": "Not found!" }
*/
func NotFound(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.NotFound(writer, "Not found!")
}

/*
{ "success": true, "message": "Everything is awesome!" }
*/
func NotFound(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.Success(writer, "Everything is awesome!")
}
```

## Writing Arbitrary Data
Very often you'll need to write some arbitrary structure out as a response. Here is an example of doing that.

```golang
type Something struct {
    Id int `json:"id"`
    Name string `json:"name"`
}

/*
{ "id": 1, "name": "Bob" }
*/
func Arbitrary(writer http.ResponseWriter, request *http.Request) {
    result := Something{Id: 1, Name: "Bob"}
    GoHttpService.WriteJson(writer, result, 200)
}
```

## Parsing Information
Below are examples of functions for parsing data.

```golang
type Something struct {
    Id int `json:"id"`
    Name string `json:"name"`
}

/*
With a body of:

{"id": 2, "name": "Adam"}

result will be filled in with values from the parsed body
*/
func ParseJsonInBodySample(writer http.ResponseWriter, request *http.Request) {
    result := Something{}
    GoHttpService.ParseJsonBody(request, &result)
}

```

## Tests
To run the tests open a terminal and execute the following.

```bash
$ go test -v
```

## License
The MIT License (MIT)

Copyright (c) 2014 Adam Presley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
extern crate ogg_sys;
extern crate vorbis_sys;
extern crate vorbisfile_sys;
extern crate vorbis_encoder;
extern crate libc;
extern crate rand;

use std::io::{self, Read, Seek};

/// Allows you to decode a sound file stream into packets.
pub struct Decoder<R> where R: Read + Seek {
    // further informations are boxed so that a pointer can be passed to callbacks
    data: Box<DecoderData<R>>,
}

///
pub struct PacketsIter<'a, R: 'a + Read + Seek>(&'a mut Decoder<R>);

///
pub struct PacketsIntoIter<R: Read + Seek>(Decoder<R>);

/// Errors that can happen while decoding & encoding
#[derive(Debug)]
pub enum VorbisError {
    ReadError(io::Error),
    NotVorbis,
    VersionMismatch,
    BadHeader,
    Hole,
    InvalidSetup, //         OV_EINVAL - Invalid setup request, eg, out of range argument.
    Unimplemented, //        OV_EIMPL - Unimplemented mode; unable to comply with quality level request.
}

impl std::error::Error for VorbisError {
    fn description(&self) -> &str {
        match self {
            &VorbisError::ReadError(_) => "A read from media returned an error",
            &VorbisError::NotVorbis => "Bitstream does not contain any Vorbis data",
            &VorbisError::VersionMismatch => "Vorbis version mismatch",
            &VorbisError::BadHeader => "Invalid Vorbis bitstream header",
            &VorbisError::InvalidSetup => "Invalid setup request, eg, out of range argument or initial file headers are corrupt",
            &VorbisError::Hole => "Interruption of data",
            &VorbisError::Unimplemented => "Unimplemented mode; unable to comply with quality level request.",
        }
    }

    fn cause(&self) -> Option<&std::error::Error> {
        match self {
            &VorbisError::ReadError(ref err) => Some(err as &std::error::Error),
            _ => None
        }
    }
}

impl std::fmt::Display for VorbisError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(fmt, "{}", std::error::Error::description(self))
    }
}

impl From<io::Error> for VorbisError {
    fn from(err: io::Error) -> VorbisError {
        VorbisError::ReadError(err)
    }
}

struct DecoderData<R> where R: Read + Seek {
    vorbis: vorbisfile_sys::OggVorbis_File,
    reader: R,
    current_logical_bitstream: libc::c_int,
    read_error: Option<io::Error>,
}

unsafe impl<R: Read + Seek + Send> Send for DecoderData<R> {}

/// Packet of data.
///
/// Each sample is an `i16` ranging from I16_MIN to I16_MAX.
///
/// The channels are interleaved in the data. For example if you have two channels, you will
/// get a sample from channel 1, then a sample from channel 2, than a sample from channel 1, etc.
#[derive(Clone, Debug)]
pub struct Packet {
    pub data: Vec<i16>,
    pub channels: u16,
    pub rate: u64,
    pub bitrate_upper: u64,
    pub bitrate_nominal: u64,
    pub bitrate_lower: u64,
    pub bitrate_window: u64,
}

impl<R> Decoder<R> where R: Read + Seek {
    pub fn new(input: R) -> Result<Decoder<R>, VorbisError> {
        extern fn read_func<R>(ptr: *mut libc::c_void, size: libc::size_t, nmemb: libc::size_t,
            datasource: *mut libc::c_void) -> libc::size_t where R: Read + Seek
        {
            use std::slice;

            /*
             * In practice libvorbisfile always sets size to 1.
             * This assumption makes things much simpler
             */
            assert_eq!(size, 1);

            let ptr = ptr as *mut u8;

            let data: &mut DecoderData<R> = unsafe { std::mem::transmute(datasource) };

            let buffer = unsafe { slice::from_raw_parts_mut(ptr as *mut u8, nmemb as usize) };

            loop {
                match data.reader.read(buffer) {
                    Ok(nb) => return nb as libc::size_t,
                    Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
                    Err(e) => {
                        data.read_error = Some(e);
                        return 0
                    }
                }
            }
        }

        extern fn seek_func<R>(datasource: *mut libc::c_void, offset: ogg_sys::ogg_int64_t,
            whence: libc::c_int) -> libc::c_int where R: Read + Seek
        {
            let data: &mut DecoderData<R> = unsafe { std::mem::transmute(datasource) };

            let result = match whence {
                libc::SEEK_SET => data.reader.seek(io::SeekFrom::Start(offset as u64)),
                libc::SEEK_CUR => data.reader.seek(io::SeekFrom::Current(offset)),
                libc::SEEK_END => data.reader.seek(io::SeekFrom::End(offset)),
                _ => unreachable!()
            };

            match result {
                Ok(_) => 0,
                Err(_) => -1
            }
        }

        extern fn tell_func<R>(datasource: *mut libc::c_void) -> libc::c_long
            where R: Read + Seek
        {
            let data: &mut DecoderData<R> = unsafe { std::mem::transmute(datasource) };
            data.reader.seek(io::SeekFrom::Current(0)).map(|v| v as libc::c_long).unwrap_or(-1)
        }

        let callbacks = {
            let mut callbacks: vorbisfile_sys::ov_callbacks = unsafe { std::mem::zeroed() };
            callbacks.read_func = read_func::<R>;
            callbacks.seek_func = seek_func::<R>;
            callbacks.tell_func = tell_func::<R>;
            callbacks
        };

        let mut data = Box::new(DecoderData {
            vorbis: unsafe { std::mem::uninitialized() },
            reader: input,
            current_logical_bitstream: 0,
            read_error: None,
        });

        // initializing
        unsafe {
            let data_ptr = &mut *data as *mut DecoderData<R>;
            let data_ptr = data_ptr as *mut libc::c_void;
            try!(check_errors(vorbisfile_sys::ov_open_callbacks(data_ptr, &mut data.vorbis,
                std::ptr::null(), 0, callbacks)));
        }

        Ok(Decoder {
            data: data,
        })
    }

    pub fn time_seek(&mut self, s: f64) -> Result<(), VorbisError> {
        unsafe {
            check_errors(vorbisfile_sys::ov_time_seek(&mut self.data.vorbis, s))
        }
    }

    pub fn time_tell(&mut self) -> Result<f64, VorbisError> {
        unsafe {
            Ok(vorbisfile_sys::ov_time_tell(&mut self.data.vorbis))
        }
    }

    pub fn packets(&mut self) -> PacketsIter<R> {
        PacketsIter(self)
    }

    pub fn into_packets(self) -> PacketsIntoIter<R> {
        PacketsIntoIter(self)
    }

    fn next_packet(&mut self) -> Option<Result<Packet, VorbisError>> {
        let mut buffer = std::iter::repeat(0i16).take(2048).collect::<Vec<_>>();
        let buffer_len = buffer.len() * 2;

        match unsafe {
            vorbisfile_sys::ov_read(&mut self.data.vorbis,
                buffer.as_mut_ptr() as *mut libc::c_char,
                buffer_len as libc::c_int, 0, 2, 1, &mut self.data.current_logical_bitstream)
        } {
            0 => {
                match self.data.read_error.take() {
                    Some(err) => Some(Err(VorbisError::ReadError(err))),
                    None => None,
                }
            },

            err if err < 0 => {
                match check_errors(err as libc::c_int) {
                    Err(e) => Some(Err(e)),
                    Ok(_) => unreachable!()
                }
            },

            len => {
                buffer.truncate(len as usize / 2);

                let infos = unsafe { vorbisfile_sys::ov_info(&mut self.data.vorbis,
                    self.data.current_logical_bitstream) };

                let infos: &vorbis_sys::vorbis_info = unsafe { std::mem::transmute(infos) };

                Some(Ok(Packet {
                    data: buffer,
                    channels: infos.channels as u16,
                    rate: infos.rate as u64,
                    bitrate_upper: infos.bitrate_upper as u64,
                    bitrate_nominal: infos.bitrate_nominal as u64,
                    bitrate_lower: infos.bitrate_lower as u64,
                    bitrate_window: infos.bitrate_window as u64,
                }))
            }
        }
    }
}

impl<'a, R> Iterator for PacketsIter<'a, R> where R: 'a + Read + Seek {
    type Item = Result<Packet, VorbisError>;

    fn next(&mut self) -> Option<Result<Packet, VorbisError>> {
        self.0.next_packet()
    }
}

impl<R> Iterator for PacketsIntoIter<R> where R: Read + Seek {
    type Item = Result<Packet, VorbisError>;

    fn next(&mut self) -> Option<Result<Packet, VorbisError>> {
        self.0.next_packet()
    }
}

impl<R> Drop for Decoder<R> where R: Read + Seek {
    fn drop(&mut self) {
        unsafe {
            vorbisfile_sys::ov_clear(&mut self.data.vorbis);
        }
    }
}

fn check_errors(code: libc::c_int) -> Result<(), VorbisError> {
    match code {
        0 => Ok(()),

        vorbis_sys::OV_ENOTVORBIS => Err(VorbisError::NotVorbis),
        vorbis_sys::OV_EVERSION => Err(VorbisError::VersionMismatch),
        vorbis_sys::OV_EBADHEADER => Err(VorbisError::BadHeader),
        vorbis_sys::OV_EINVAL => Err(VorbisError::InvalidSetup),
        vorbis_sys::OV_HOLE => Err(VorbisError::Hole),

        vorbis_sys::OV_EREAD => unimplemented!(),

        vorbis_sys::OV_EIMPL => Err(VorbisError::Unimplemented),

        // indicates a bug or heap/stack corruption
        vorbis_sys::OV_EFAULT => panic!("Internal libvorbis error"),
        _ => panic!("Unknown vorbis error {}", code)
    }
}

#[derive(Debug)]
pub enum VorbisQuality {
    VeryHighQuality,
    HighQuality,
    Quality,
    Midium,
    Performance,
    HighPerforamnce,
    VeryHighPerformance,
}

pub struct Encoder {
    e: vorbis_encoder::Encoder,
}

impl Encoder {
    pub fn new(channels: u8, rate: u64, quality: VorbisQuality) -> Result<Self, VorbisError> {
        let quality = match quality {
            VorbisQuality::VeryHighQuality => {1.0f32},
            VorbisQuality::HighQuality => {0.8f32},
            VorbisQuality::Quality => {0.6f32},
            VorbisQuality::Midium => {0.4f32},
            VorbisQuality::Performance => {0.3f32},
            VorbisQuality::HighPerforamnce => {0.1f32},
            VorbisQuality::VeryHighPerformance => {-0.1f32},
        };
        Ok(Encoder {
            e: match vorbis_encoder::Encoder::new(channels as u32, rate, quality) {
                Ok(e) => {e},
                Err(i) => {
                    match check_errors(i) {
                        Ok(()) => panic!("Unexpected behavior, call hossein.noroozpour@gmail.com"),
                        Err(err) => return Err(err),
                    }
                }
            }
        })
    }

    // data is an interleaved array of samples
    pub fn encode(&mut self, data: &Vec<i16>) -> Result<Vec<u8>, VorbisError> {
        Ok(
            match self.e.encode(&data) {
                Ok(d) => {d},
                Err(i) => {
                    match check_errors(i) {
                        Ok(()) => panic!("Unexpected behavior, call hossein.noroozpour@gmail.com"),
                        Err(err) => return Err(err),
                    }
                }
            }
        )
    }

    pub fn flush(&mut self) -> Result<Vec<u8>, VorbisError> {
        Ok(
            match self.e.flush() {
                Ok(d) => {d},
                Err(i) => {
                    match check_errors(i) {
                        Ok(()) => panic!("Unexpected behavior, call hossein.noroozpour@gmail.com"),
                        Err(err) => return Err(err),
                    }
                }
            }
        )
    }
}


text:
package org.piccolo2d.examples;

import org.piccolo2d.PCanvas;
import org.piccolo2d.PLayer;
import org.piccolo2d.PNode;
import org.piccolo2d.activities.PActivity;
import org.piccolo2d.extras.PFrame;
import org.piccolo2d.nodes.PPath;

/**
 * This example shows how to use setTriggerTime to synchronize the start and end
 * of two activities.
 */
public class WaitForActivitiesExample extends PFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public WaitForActivitiesExample() {
        this(null);
    }

    public WaitForActivitiesExample(final PCanvas aCanvas) {
        super("WaitForActivitiesExample", false, aCanvas);
    }

    public void initialize() {
        final PLayer layer = getCanvas().getLayer();

        final PNode a = PPath.createRectangle(0, 0, 100, 80);
        final PNode b = PPath.createRectangle(0, 0, 100, 80);

        layer.addChild(a);
        layer.addChild(b);

        final PActivity a1 = a.animateToPositionScaleRotation(200, 200, 1, 0, 5000);
        final PActivity a2 = b.animateToPositionScaleRotation(200, 200, 1, 0, 5000);

        a2.startAfter(a1);
    }

    public static void main(final String[] args) {
        new WaitForActivitiesExample();
    }
}


text:
package org.unitils.inject.annotation;

import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

/**
 * Annotation indicating the object under test. The object(s) referenced by the annotated field(s) is (are) used as
 * default target for injection.
 *
 * @author Filip Neven
 * @author Tim Ducheyne
 */
@Target(FIELD)
@Retention(RUNTIME)
public @interface TestedObject {
}


text:
package course.spark

import org.apache.spark.{ SparkConf, SparkContext }
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{ SQLContext, DataFrame }

object MostRetweetedSparkSQL extends App {

  /*
   * At first, we should define our Spark context.
   * It will be the nexus to comunicate
   * the driver (our main program) with the spark
   * cluster (in this example, a local embeded one).
   */

  /*
   * We will first define its configuration
   */

  val sparkConf = new SparkConf()
    .setAppName("MostRetweetedSparkSQL")
    .setMaster("local[4]")

  /*
   * And then we initialize our spark context (the driver)
   */

  val sparkContext = new SparkContext(sparkConf)

  /*
   * For using SparkSQL, we will need to define an SQLContext,
   * based on our SparkContext
   */

  val sqlContext = new SQLContext(sparkContext)

  /*
   * We can define a new temporary table in SparkSQL with
   * the following syntax, setting where's the file to read
   * and the sampling ratio used to infer the schema.
   */

  val tweets: DataFrame =
    sqlContext.jsonFile("src/main/resources/tweets.txt", 1.0)
  tweets.registerTempTable("tweets")
  /*
   * Equals to:
   * sqlContext.sql(s"""
   *   |CREATE TEMPORARY TABLE tweets
   *   |USING org.apache.spark.sql.json
   *   |OPTIONS (
   *   |  path 'src/main/resources/tweets.txt',
   *   |  samplingRatio '1'
   *   |)
   * """.stripMargin)
   */

  /*
   * A DataFrame represents a particular RDD of Row type,
   * which also contains an schema of contained data.
   */

  /*
   * We could see which is the inferred schema by writing:
   */
  tweets.printSchema

  /*
   * And we could also print all records...
   */

  //tweets.foreach(println)

  /*
   * That's the awkward moment when you realize there's too much
   * useless stuff and you only want to select some fields. So...
   */

  val shortTweets =
    sqlContext.sql(s"""
       |SELECT id, text, retweet_count, user.screen_name
       |FROM tweets
     """.stripMargin)

  /*
   * And voilà!
   */

  shortTweets.printSchema

  //shortTweets.foreach(println)

  /*
   * So let's calculate, using 'SQL' statements, which is the
   * most retweeted tweet
   */

  val mostRetweeted =
    sqlContext.sql(s"""
       |SELECT id, text, retweet_count, user.screen_name
       |FROM tweets
       |ORDER BY retweet_count DESC LIMIT 1
    """.stripMargin)

  mostRetweeted.foreach(println)

  /*
   * That simple!
   */

  /*
   * Let's cleanup and free busy resources...
   */
  sparkContext.stop()

}


text:
/*global define*/

define(['backbone','marionette-original'],
  function (Backbone) {
    "use strict";
    // Checks to make sure Backbone and Marionette are on the page
    if(window.Backbone && window.Backbone.Marionette && window.Backbone.Marionette.Application) {

      Backbone.Marionette.Application.prototype.navigate = function (route, options) {
        options || (options = {});
        Backbone.history.navigate(route, options);
      }

      Backbone.Marionette.Application.prototype.getCurrentRoute = function () {
        return Backbone.history.fragment
      }

      return Backbone.Marionette.Application;

//      return Backbone.Marionette.Application.extend({
//
//        navigate: function (route, options) {
//          options || (options = {});
//          Backbone.history.navigate(route, options);
//        },
//        getCurrentRoute: function () {
//          return Backbone.history.fragment
//        }
//      });
    }

  });


text:
[![Build Status](https://secure.travis-ci.org/arqex/react-datetime.svg)](https://travis-ci.org/arqex/react-datetime)
[![npm version](https://badge.fury.io/js/react-datetime.svg)](http://badge.fury.io/js/react-datetime)

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is **highly customizable** and it even allows to edit date's milliseconds.

> **Back to the roots!** Thanks to the people of [YouCanBook.me (best scheduling tool)](https://youcanbook.me) for sponsoring react-datetime for so long. Now the project returns to the community and we are **looking for contributors** to continue improving react-datetime. [Would you like to give a hand?](contribute-home.md)

**Version 3 is out!** These are the docs for version 3 of the library. If you are still using the deprecated v2, [here it is its documentation](https://github.com/arqex/react-datetime/blob/2a83208452ac5e41c43fea31ef47c65efba0bb56/README.md), but we strongly recommend to migrate to version 3 in order to keep receiving updates. Please check [migrating react-datetime to version 3](migrateToV3.md) to safely update your app.

## Installation

Install using npm:
```sh
npm install --save react-datetime
```

Install using yarn:
```sh
yarn add react-datetime
```

## Usage

[React.js](http://facebook.github.io/react/) and [Moment.js](http://momentjs.com/) are peer dependencies for react-datetime (as well as [Moment.js timezones](https://momentjs.com/timezone/) if you want to use the `displayTimeZone` prop). These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

```js
// Import the library
import Datetime from 'react-datetime';

// return it from your components
return <Datetime />;
```
[See this example working](https://codesandbox.io/s/boring-dew-uzln3).

Do you want more examples? [Have a look at our resources gallery](resources.md).

**Don't forget to add the [CSS stylesheet](https://github.com/arqex/react-datetime/blob/master/css/react-datetime.css) to make it work out of the box.**. You only need to do this once in your app:

```js
import "react-datetime/css/react-datetime.css";
```

## API

Below we have all the props that we can use with the `<DateTime>` component. There are also some methods that can be used imperatively.

| Name         | Type    | Default | Description |
| ------------ | ------- | ------- | ----------- |
| **value** | `Date` | `new Date()` | Represents the selected date by the component, in order to use it as a [controlled component](https://facebook.github.io/react/docs/forms.html#controlled-components). This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. |
| **initialValue** | `Date` | `new Date()` | Represents the selected date for the component to use it as a [uncontrolled component](https://facebook.github.io/react/docs/uncontrolled-components.html). This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. If you need to set the selected date programmatically after the picker is initialized, please use the `value` prop instead. |
| **initialViewDate** | `Date` | `new Date()` | Define the month/year/decade/time which is viewed on opening the calendar. This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. If you want to set the view date after the component has been initialize [see the imperative API](#imperative-api). |
| **initialViewMode** | `string` or `number` | `'days'` | The default view to display when the picker is shown for the first time (`'years'`, `'months'`, `'days'`, `'time'`). If you want to set the view mode after the component has been initialize [see the imperative API](#imperative-api). |
| **updateOnView** | `string` | Intelligent guess | By default we can navigate through years and months without actualling updating the selected date. Only when we get to one view called the "updating view", we make a selection there and the value gets updated, triggering an `onChange` event. By default the updating view will get guessed by using the `dateFormat` so if our dates only show months and never days, the update is done in the `months` view. If we set `updateOnView="time"` selecting a day will navigate to the time view. The time view always updates the selected date, never navigates. If `closeOnSelect={ true }`, making a selection in the view defined by `updateOnView` will close the calendar. |
| **dateFormat**   | `boolean` or `string`  | `true` | Defines the format for the date. It accepts any [Moment.js date format](http://momentjs.com/docs/#/displaying/format/) (not in localized format). If `true` the date will be displayed using the defaults for the current locale. If `false` the datepicker is disabled and the component can be used as timepicker, see [available units docs](#specify-available-units). |
| **timeFormat**   | `boolean` or `string`  | `true` | Defines the format for the time. It accepts any [Moment.js time format](http://momentjs.com/docs/#/displaying/format/) (not in localized format). If `true` the time will be displayed using the defaults for the current locale. If `false` the timepicker is disabled and the component can be used as datepicker, see [available units docs](#specify-available-units). |
| **input** | `boolean` | `true` | Whether to show an input field to edit the date manually. |
| **open** | `boolean` | `null` | Whether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside. |
| **locale** | `string` | `null` | Manually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see [i18n docs](#i18n).
| **utc** | `boolean` | `false` | When true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
| **displayTimeZone** | `string` | `null` | **Needs [moment's timezone](https://momentjs.com/timezone/) available in your project.** When specified, input time values will be displayed in the given time zone. Otherwise they will default to the user's local timezone (unless `utc` specified).
| **onChange** | `function` | empty function | Callback trigger when the date changes. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string). |
| **onOpen** | `function` | empty function | Callback trigger for when the user opens the datepicker. |
| **onClose** | `function` | empty function | Callback trigger for when the calendar get closed. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returns the value in the input. |
| **onNavigate** | `function` | empty function | Callback trigger when the view mode changes. The callback receives the selected view mode string (`years`, `months`, `days` or `time`) as only parameter.|
| **onBeforeNavigate** | `function` | ( nextView, currentView, viewDate ) => nextView | Allows to intercept a change of the calendar view. The accepted function receives the view that it's supposed to navigate to, the view that is showing currently and the date currently shown in the view. Return a viewMode ( default ones are `years`, `months`, `days` or `time`) to navigate to it. If the function returns a "falsy" value, the navigation is stopped and we will remain in the current view. |
| **onNavigateBack** | `function` | empty function | Callback trigger when the user navigates to the previous month, year or decade. The callback receives the amount and type ('month', 'year') as parameters. |
| **onNavigateForward** | `function` | empty function | Callback trigger when the user navigates to the next month, year or decade. The callback receives the amount and type ('month', 'year') as parameters. |
| **className** | `string` or `string array` | `''` | Extra class name for the outermost markup element. |
| **inputProps** | `object` | `undefined` | Defines additional attributes for the input element of the component. For example: `onClick`, `placeholder`, `disabled`, `required`, `name` and `className` (`className` *sets* the class attribute for the input element). See [Customize the Input Appearance](#customize-the-input-appearance). |
| **isValidDate** | `function` | `() => true` | Define the dates that can be selected. The function receives `(currentDate, selectedDate)` and shall return a `true` or `false` whether the `currentDate` is valid or not. See [selectable dates](#selectable-dates).|
| **renderInput** | `function` | `undefined` | Replace the rendering of the input element. The function has the following arguments: the default calculated `props` for the input, `openCalendar` (a function which opens the calendar) and `closeCalendar` (a function which closes the calendar). Must return a React component or `null`. See [Customize the Input Appearance](#customize-the-input-appearance). |
| **renderView** | `function` | `(viewMode, renderDefault) => renderDefault()` | Customize the way the calendar is rendered. The accepted function receives the type of the view it's going to be rendered `'years', 'months', 'days', 'time'` and a function to render the default view of react-datetime, this way it's possible to wrap the original view adding our own markup or override it completely with our own code. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
| **renderDay** | `function` | `DOM.td(day)` | Customize the way that the days are shown in the daypicker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
| **renderMonth** | `function` | `DOM.td(month)` | Customize the way that the months are shown in the monthpicker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `month` and the `year` to be shown, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
| **renderYear** | `function` | `DOM.td(year)` | Customize the way that the years are shown in the year picker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `year` to be shown, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
| **strictParsing** | `boolean` | `true` | Whether to use Moment.js's [strict parsing](http://momentjs.com/docs/#/parsing/string-format/) when parsing input.
| **closeOnSelect** | `boolean` | `false` | When `true`, once the day has been selected, the datepicker will be automatically closed.
| **closeOnTab** | `boolean` | `true` | When `true` and the input is focused, pressing the `tab` key will close the datepicker.
| **timeConstraints** | `object` | `null` | Add some constraints to the timepicker. It accepts an `object` with the format `{ hours: { min: 9, max: 15, step: 2 }}`, this example means the hours can't be lower than `9` and higher than `15`, and it will change adding or subtracting `2` hours everytime the buttons are clicked. The constraints can be added to the `hours`, `minutes`, `seconds` and `milliseconds`.
| **closeOnClickOutside** | `boolean` | `true` | When the calendar is open and `closeOnClickOutside` is `true` (its default value), clickin outside of the calendar or input closes the calendar. If `false` the calendar stays open.

## Imperative API
Besides controlling the selected date, there is a navigation through months, years, decades that react-datetime handles for us. We can interfere in it, stopping view transtions by using the prop `onBeforeNavigate`, but we can also navigate to a specific view and date by using some imperative methods.

To do so, we need to create our component with a `ref` prop amd use the reference.
```js
// This would be the code to render the picker
<DateTime ref="datetime" />

// ... once rendered we can use the imperative API
// let's show the years view
this.refs.datetime.navigate('years')
```

Available methods are:
* **navigate( viewMode )**: Set the view currently shown by the calendar. View modes shipped with react-datetime are `years`, `months`, `days` and `time`, but you can alse navigate to custom modes that can be defined by using the `renderView` prop.
* **setViewDate( date )**: Set the date that is currently shown in the calendar. This is independent from the selected date and it's the one used to navigate through months or days in the calendar. It accepts a string in the format of the current locale, a `Date` or a `Moment` object as parameter.

## i18n
Different language and date formats are supported by react-datetime. React uses [Moment.js](http://momentjs.com/) to format the dates, and the easiest way of changing the language of the calendar is [changing the Moment.js locale](http://momentjs.com/docs/#/i18n/changing-locale/).

Don't forget to import your locale file from the moment's `moment/locale` folder.

```js
import moment from 'moment';
import 'moment/locale/fr';
// Now react-datetime will be in french
```

If there are multiple locales loaded, you can use the prop `locale` to define what language shall be used by the instance.
```js
<Datetime locale="fr-ca" />
<Datetime locale="de" />
```
[Here you can see the i18n example working](https://codesandbox.io/s/interesting-kare-0707b).

## Customize the Input Appearance
It is possible to customize the way that the input is displayed. The simplest is to supply `inputProps` which will get directly assigned to the `<input />` element within the component. We can tweak the inputs this way:

```js
let inputProps = {
    placeholder: 'N/A',
    disabled: true,
    onMouseLeave: () => alert('You went to the input but it was disabled')
};

<Datetime inputProps={ inputProps } />
```
[See the customized input working](https://codesandbox.io/s/clever-wildflower-81r26?file=/src/App.js)

Alternatively, if you need to render different content than an `<input />` element, you may supply a `renderInput` function which is called instead.

```js
class MyDTPicker extends React.Component {
    render(){
        return <Datetime renderInput={ this.renderInput } />;
    }
    renderInput( props, openCalendar, closeCalendar ){
        function clear(){
            props.onChange({target: {value: ''}});
        }
        return (
            <div>
                <input {...props} />
                <button onClick={openCalendar}>open calendar</button>
                <button onClick={closeCalendar}>close calendar</button>
                <button onClick={clear}>clear</button>
            </div>
        );
    }
}
```

[See this example working](https://codesandbox.io/s/peaceful-water-3gb5m)

Or maybe you just want to shown the calendar and don't need an input at all. In that case `input={ false }` will make the trick:

```js
    <Datetime input={ false } />;
```
[See react-datetime calendar working without an input](https://codesandbox.io/s/busy-vaughan-wh773)

## Customize the Datepicker Appearance
It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props `renderDay(props, currentDate, selectedDate)`, `renderMonth(props, month, year, selectedDate)` and `renderYear(props, year, selectedDate)` to customize the output of each rendering method.

```js
class MyDTPicker extends React.Component {
  render() {
    return (
      <Datetime
        renderDay={this.renderDay}
        renderMonth={this.renderMonth}
        renderYear={this.renderYear}
      />
    );
  }
  renderDay(props, currentDate, selectedDate) {
    // Adds 0 to the days in the days view
    return <td {...props}>{"0" + currentDate.date()}</td>;
  }
  renderMonth(props, month, year, selectedDate) {
    // Display the month index in the months view
    return <td {...props}>{month}</td>;
  }
  renderYear(props, year, selectedDate) {
    // Just display the last 2 digits of the year in the years view
    return <td {...props}>{year % 100}</td>;
  }
}
```
[See the customized calendar here.](https://codesandbox.io/s/peaceful-kirch-69e06)

It's also possible to override some view in the calendar completelly. Let's say that we want to add a today button in our calendars, when we click it we go to the today view:
```js
class MyDTPicker extends React.Component {
  render() {
    return (
      <Datetime
        ref="datetime"
        renderView={(mode, renderDefault) =>
          this.renderView(mode, renderDefault)
        }
      />
    );
  }

  renderView(mode, renderDefault) {
    // Only for years, months and days view
    if (mode === "time") return renderDefault();

    return (
      <div className="wrapper">
        {renderDefault()}
        <div className="controls">
          <button onClick={() => this.goToToday()}>Today</button>
        </div>
      </div>
    );
  }

  goToToday() {
    // Reset
    this.refs.datetime.setViewDate(new Date());
    this.refs.datetime.navigate("days");
  }
}
```
[See it working](https://codesandbox.io/s/frosty-fog-nrwk2)

#### Method Parameters
* `props` is the object that the datepicker has calculated for this object. It is convenient to use this object as the `props` for your custom component, since it knows how to handle the click event and its `className` attribute is used by the default styles.
* `selectedDate` and `currentDate` are [moment objects](http://momentjs.com) and can be used to change the output depending on the selected date, or the date for the current day.
* `month` and `year` are the numeric representation of the current month and year to be displayed. Notice that the possible `month` values range from `0` to `11`.

## Make it work as a year picker or a time picker
You can filter out what you want the user to be able to pick by using `dateFormat` and `timeFormat`, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a *timepicker* and can *only be used for selecting a time*.
```js
<Datetime dateFormat={false} />
```
[Working example of a timepicker here.](https://codesandbox.io/s/loving-nobel-sbok2)

In this example you can *only select a year and month*.
```js
<Datetime dateFormat="YYYY-MM" timeFormat={false} />
```
[Working example of only selecting year and month here.](https://codesandbox.io/s/recursing-pascal-xl643)

## Blocking some dates to be selected
It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop `isValidDate`, which admits a function in the form `function(currentDate, selectedDate)` where both arguments are [moment objects](http://momentjs.com). The function shall return `true` for selectable dates, and `false` for disabled ones.

In the example below are *all dates before today* disabled.

```js
import moment from 'moment';
var yesterday = moment().subtract( 1, 'day' );
var valid = function( current ){
    return current.isAfter( yesterday );
};
<Datetime isValidDate={ valid } />
```
[Working example of disabled days here.](https://codesandbox.io/s/thirsty-shape-l4qg4)

It's also possible to disable *the weekends*, as shown in the example below.
```js
var valid = function( current ){
    return current.day() !== 0 && current.day() !== 6;
};
<Datetime isValidDate={ valid } />
```
[Working example of disabled weekends here.](https://codesandbox.io/s/laughing-keller-3wq1g)

## Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not
required.

Typings for 1.8 are found in `react-datetime.d.ts` and typings for 2.0 are found in `typings/index.d.ts`.

```js
import * as Datetime from 'react-datetime';

class MyDTPicker extends React.Component<MyDTPickerProps, MyDTPickerState> {
    render() JSX.Element {
        return <Datetime />;
    }
}
```

## Contributions
react-datetime is made by the community for the community. People like you, interested in contribute, are the key of the project! 🙌🙌🙌

Have a look at [our contribute page](contribute-home.md) to know how to get started.

### [Changelog](CHANGELOG.md)

### [MIT Licensed](LICENSE.md)