text:
use {Attachment, AttachmentName, AttachmentPath, DatabaseName, DocumentId, DocumentPath, Error, Revision};
use {mime, serde, serde_json, std};
use IntoDocumentPath;
use attachment::AttachmentBuilder;

/// Contains a specific version of a document.
///
/// A `Document` is an in-memory representation of a document, including its
/// content, attachments, and meta-information.
///
/// A `Document` may represent a document of any type: normal, design, or local.
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
    doc_path: DocumentPath,
    revision: Revision,
    deleted: bool,
    attachments: std::collections::HashMap<AttachmentName, Attachment>,
    content: serde_json::Value,
}

impl Document {
    #[doc(hidden)]
    pub fn new_from_decoded(db_name: DatabaseName, doc: JsonDecodableDocument) -> Self {
        Document {
            doc_path: DocumentPath::from((db_name, doc.doc_id)),
            revision: doc.revision,
            deleted: doc.deleted,
            attachments: doc.attachments,
            content: doc.content,
        }
    }

    pub fn path(&self) -> &DocumentPath {
        &self.doc_path
    }

    /// Returns the document's revision.
    pub fn revision(&self) -> &Revision {
        &self.revision
    }

    /// Returns `true` if and only if the document is deleted.
    ///
    /// Normally, the CouchDB server returns a `NotFound` error if the
    /// application attempts to read a deleted document. However, the
    /// application may specify a revision when reading the document, and, if
    /// the revision marks when the document was deleted, then the server will
    /// respond successfully with a `Document` "stub" marked as deleted.
    ///
    pub fn is_deleted(&self) -> bool {
        self.deleted
    }

    /// Decodes and returns the document content, from a JSON object into a Rust
    /// type.
    pub fn get_content<C: serde::Deserialize>(&self) -> Result<C, Error> {
        serde_json::from_value(self.content.clone()).map_err(|e| Error::JsonDecode { cause: e })
    }

    /// Encodes the document content, from a Rust type into a JSON object.
    ///
    /// The `set_content` method modifies the `Document` instance but doesn't
    /// update the document on the CouchDB server. To update the document on the
    /// server, the application must use the `UpdateDocument` action upon the
    /// modified `Document`.
    ///
    pub fn set_content<C: serde::Serialize>(&mut self, new_content: &C) -> Result<(), Error> {
        self.content = serde_json::to_value(new_content);
        Ok(())
    }

    /// Returns the document's attachment of a given name, if the attachment
    /// exists.
    pub fn get_attachment<'a, A>(&self, att_name: A) -> Option<&Attachment>
    where
        A: Into<AttachmentName>,
    {
        let att_name = att_name.into();
        self.attachments.get(&att_name)
    }

    /// Creates or replaces the document's attachment of a given name.
    ///
    /// This method does _not_ change state on the CouchDB server, and the newly
    /// created attachment exists only in memory on the client-side. To store
    /// the document on the CouchDB server, the client must execute an action to
    /// update the document, at which time the client will send the attachment
    /// to the server.
    ///
    pub fn insert_attachment<'a, A>(&mut self, att_name: A, content_type: mime::Mime, content: Vec<u8>)
    where
        A: Into<AttachmentName>,
    {
        let att_name = att_name.into();
        self.attachments.insert(
            att_name,
            AttachmentBuilder::new_unsaved(content_type, content).unwrap(),
        );
    }

    /// Deletes the document's attachment of a given name, if the attachment
    /// exists.
    ///
    /// This method does _not_ change state on the CouchDB server, and the newly
    /// deleted attachment will continue to exist on the CouchDB server until
    /// the client executes an action to update the document.
    ///
    pub fn remove_attachment<'a, A>(&mut self, att_name: A)
    where
        A: Into<AttachmentName>,
    {
        let att_name = att_name.into();
        self.attachments.remove(&att_name);
    }

    /// Returns an iterator to all attachments to the document.
    pub fn attachments(&self) -> AttachmentIter {
        AttachmentIter {
            doc_path: &self.doc_path,
            inner: self.attachments.iter(),
        }
    }
}

#[doc(hidden)]
impl serde::Serialize for Document {
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
    where
        S: serde::Serializer,
    {
        // Serde requires structure field names to have static lifetimes.
        // However, our document content is dynamic. As a workaround, we construct a
        // serde_json::Value instance containing both the document's content and
        // its attachments.

        let mut value = self.content.clone();

        if let serde_json::Value::Object(ref mut fields) = value {
            if !self.attachments.is_empty() {
                let mut attachments = std::collections::BTreeMap::new();
                for (name, attachment) in self.attachments.iter() {
                    attachments.insert(String::from(name.clone()), serde_json::to_value(attachment));
                }
                fields.insert(
                    "_attachments".to_string(),
                    serde_json::Value::Object(attachments),
                );
            }
        } else {
            panic!("Document content is not a JSON object");
        }

        value.serialize(serializer)
    }
}

pub struct AttachmentIter<'a> {
    doc_path: &'a DocumentPath,
    inner: std::collections::hash_map::Iter<'a, AttachmentName, Attachment>,
}

impl<'a> Iterator for AttachmentIter<'a> {
    type Item = (AttachmentPath, &'a Attachment);

    fn next(&mut self) -> Option<Self::Item> {
        match self.inner.next() {
            None => None,
            Some((att_name, att)) => Some((
                AttachmentPath::from(
                    (self.doc_path.clone(), att_name.clone()),
                ),
                att,
            )),
        }
    }
}

#[cfg(test)]
mod document_tests {

    use super::*;
    use {AttachmentName, Error, IntoDocumentPath, Revision};
    use {base64, serde_json, std};
    use attachment::AttachmentBuilder;

    #[test]
    fn get_content_ok() {

        let content = serde_json::builder::ObjectBuilder::new()
            .insert("field_1", 42)
            .insert("field_2", "foo")
            .build();

        let doc = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: "1-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: content.clone(),
        };

        let expected = content;
        let got = doc.get_content().unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn get_content_ok_document_is_deleted() {

        let content = serde_json::builder::ObjectBuilder::new().build();

        let doc = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: "1-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: true,
            attachments: std::collections::HashMap::new(),
            content: content.clone(),
        };

        let expected = content;
        let got = doc.get_content().unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn get_content_nok_decode_error() {

        let doc = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: "1-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        match doc.get_content::<i32>() {
            Err(Error::JsonDecode { .. }) => (),
            x @ _ => unexpected_result!(x),
        }
    }

    #[test]
    fn serialize_empty() {

        let document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: true, // This value should have no effect.
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let encoded = serde_json::to_string(&document).unwrap();
        let expected = serde_json::builder::ObjectBuilder::new().build();
        let got = serde_json::from_str(&encoded).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn serialize_with_content_and_attachments() {

        let document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: true, // This value should have no effect.
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    AttachmentName::from("attachment_1"),
                    AttachmentBuilder::new_saved_with_content(
                        mime!(Text / Plain),
                        "md5-XNdWXQ0FO9vPx7skS0GuYA==",
                        17,
                        "Blah blah blah",
                    ).unwrap(),
                );
                m.insert(
                    AttachmentName::from("attachment_2"),
                    AttachmentBuilder::new_unsaved(
                        mime!(Text / Html),
                        "
Yak yak yak
".to_string().into_bytes(),
                    ).unwrap(),
                );
                m
            },
            content: serde_json::builder::ObjectBuilder::new()
                .insert("field_1", 17)
                .insert("field_2", "hello")
                .build(),
        };

        let encoded = serde_json::to_string(&document).unwrap();

        let expected = serde_json::builder::ObjectBuilder::new()
            .insert("field_1", 17)
            .insert("field_2", "hello")
            .insert_object("_attachments", |x| {
                x.insert_object("attachment_1", |x| x.insert("stub", true))
                    .insert_object("attachment_2", |x| {
                        x.insert("content_type", "text/html").insert(
                            "data",
                            base64::encode(
                                "
Yak yak yak
"
                                    .as_bytes(),
                            ),
                        )
                    })
            })
            .build();

        let got = serde_json::from_str(&encoded).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn get_attachment_exists() {

        let attachment_1 = AttachmentBuilder::new_saved_with_content(
            mime!(Text / Plain),
            "md5-XNdWXQ0FO9vPx7skS0GuYA=\
                                                                      =",
            17,
            "Blah blah blah",
        ).unwrap();

        let document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(AttachmentName::from("attachment_1"), attachment_1.clone());
                m
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let got = document.get_attachment("attachment_1");
        assert_eq!(Some(&attachment_1), got);
    }

    #[test]
    fn get_attachment_no_exist() {

        let document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let got = document.get_attachment("attachment_1");
        assert_eq!(None, got);
    }

    #[test]
    fn insert_attachment_new() {

        let mut document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        document.insert_attachment("foo", mime!(Text / Plain), "This is the content.".into());
        document.insert_attachment(
            "bar",
            mime!(Text / Plain),
            "This is the second attachment.".into(),
        );

        let expected = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    AttachmentName::from("foo"),
                    AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the content.").unwrap(),
                );
                m.insert(
                    AttachmentName::from("bar"),
                    AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the second attachment.").unwrap(),
                );
                m
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        assert_eq!(expected, document);
    }

    #[test]
    fn insert_attachment_replace() {

        let mut document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        document.insert_attachment("foo", mime!(Text / Plain), "This is the content.".into());
        document.insert_attachment(
            "foo",
            mime!(Text / Plain),
            "This is the second attachment.".into(),
        );

        let expected = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    AttachmentName::from("foo"),
                    AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the second attachment.").unwrap(),
                );
                m
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        assert_eq!(expected, document);
    }

    #[test]
    fn remove_attachment_exists() {

        let mut document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    AttachmentName::from("foo"),
                    AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the content.").unwrap(),
                );
                m
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        document.remove_attachment("foo");

        let expected = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        assert_eq!(expected, document);
    }

    #[test]
    fn remove_attachment_no_exist() {

        let mut document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    AttachmentName::from("foo"),
                    AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the content.").unwrap(),
                );
                m
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        document.remove_attachment("bar");

        let expected = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    AttachmentName::from("foo"),
                    AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the content.").unwrap(),
                );
                m
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        assert_eq!(expected, document);
    }

    #[test]
    fn iterate_through_attachments() {

        let attachments = {
            let mut m = std::collections::HashMap::new();
            m.insert(
                AttachmentName::from("foo"),
                AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the content.").unwrap(),
            );
            m.insert(
                AttachmentName::from("bar"),
                AttachmentBuilder::new_unsaved(mime!(Text / Plain), "This is the second attachment.").unwrap(),
            );
            m
        };

        let document = Document {
            doc_path: "/database/document_id".into_document_path().unwrap(),
            revision: Revision::parse("42-1234567890abcdef1234567890abcdef").unwrap(),
            deleted: false,
            attachments: attachments.clone(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let got = document
            .attachments()
            .map(|(path, attachment)| {
                (path.attachment_name().clone(), attachment.clone())
            })
            .collect();
        assert_eq!(attachments, got);
    }
}

// JsonDecodableDocument is necessary because the Document type is not
// decodable. It's not decodable because it requires a database name, which is
// not known at decode-time.
#[derive(Debug, PartialEq)]
pub struct JsonDecodableDocument {
    pub doc_id: DocumentId,
    pub revision: Revision,
    pub deleted: bool,
    pub attachments: std::collections::HashMap<AttachmentName, Attachment>,
    pub content: serde_json::Value,
}

impl serde::Deserialize for JsonDecodableDocument {
    fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer,
    {
        enum Field {
            Attachments,
            Content(String),
            Deleted,
            Id,
            Rev,
        }

        impl serde::Deserialize for Field {
            fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
            where
                D: serde::Deserializer,
            {
                struct Visitor;

                impl serde::de::Visitor for Visitor {
                    type Value = Field;

                    fn visit_str<E>(&mut self, value: &str) -> Result<Field, E>
                    where
                        E: serde::de::Error,
                    {
                        match value {
                            "_attachments" => Ok(Field::Attachments),
                            "_deleted" => Ok(Field::Deleted),
                            "_id" => Ok(Field::Id),
                            "_rev" => Ok(Field::Rev),
                            _ => Ok(Field::Content(value.to_string())),
                        }
                    }
                }

                deserializer.deserialize(Visitor)
            }
        }

        struct Visitor;

        impl serde::de::Visitor for Visitor {
            type Value = JsonDecodableDocument;

            fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
            where
                V: serde::de::MapVisitor,
            {
                let mut attachments = None;
                let mut deleted = None;
                let mut id = None;
                let mut revision = None;
                let mut content_builder = serde_json::builder::ObjectBuilder::new();

                loop {
                    match try!(visitor.visit_key()) {
                        Some(Field::Attachments) => {
                            attachments = Some(try!(visitor.visit_value()));
                        }
                        Some(Field::Content(name)) => {
                            let value = Some(try!(visitor.visit_value::<serde_json::Value>()));
                            content_builder = content_builder.insert(name, value);
                        }
                        Some(Field::Deleted) => {
                            deleted = Some(try!(visitor.visit_value()));
                        }
                        Some(Field::Id) => {
                            id = Some(try!(visitor.visit_value()));
                        }
                        Some(Field::Rev) => {
                            revision = Some(try!(visitor.visit_value()));
                        }
                        None => {
                            break;
                        }
                    }
                }

                try!(visitor.end());

                Ok(JsonDecodableDocument {
                    doc_id: match id {
                        Some(x) => x,
                        None => try!(visitor.missing_field("_id")),
                    },
                    revision: match revision {
                        Some(x) => x,
                        None => try!(visitor.missing_field("_rev")),
                    },
                    deleted: deleted.unwrap_or(false),
                    attachments: attachments.unwrap_or(std::collections::HashMap::new()),
                    content: content_builder.build(),
                })
            }
        }

        static FIELDS: &'static [&'static str] = &["_attachments", "_deleted", "_id", "_rev"];
        deserializer.deserialize_struct("JsonDecodableDocument", FIELDS, Visitor)
    }
}

#[derive(Debug, PartialEq)]
pub struct WriteDocumentResponse {
    pub ok: bool,
    pub doc_id: DocumentId,
    pub revision: Revision,
}

impl serde::Deserialize for WriteDocumentResponse {
    fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer,
    {
        enum Field {
            Id,
            Ok,
            Rev,
        }

        impl serde::Deserialize for Field {
            fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer,
            {
                struct Visitor;

                impl serde::de::Visitor for Visitor {
                    type Value = Field;

                    fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E>
                    where
                        E: serde::de::Error,
                    {
                        match value {
                            "id" => Ok(Field::Id),
                            "ok" => Ok(Field::Ok),
                            "rev" => Ok(Field::Rev),
                            _ => Err(E::unknown_field(value)),
                        }
                    }
                }

                deserializer.deserialize(Visitor)
            }
        }

        struct Visitor;

        impl serde::de::Visitor for Visitor {
            type Value = WriteDocumentResponse;

            fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
            where
                V: serde::de::MapVisitor,
            {
                let mut id = None;
                let mut ok = None;
                let mut rev = None;
                loop {
                    match try!(visitor.visit_key()) {
                        Some(Field::Id) => {
                            id = Some(try!(visitor.visit_value()));
                        }
                        Some(Field::Ok) => {
                            ok = Some(try!(visitor.visit_value()));
                        }
                        Some(Field::Rev) => {
                            rev = Some(try!(visitor.visit_value()));
                        }
                        None => {
                            break;
                        }
                    }
                }

                try!(visitor.end());

                Ok(WriteDocumentResponse {
                    doc_id: match id {
                        Some(x) => x,
                        None => try!(visitor.missing_field("id")),
                    },
                    ok: match ok {
                        Some(x) => x,
                        None => try!(visitor.missing_field("ok")),
                    },
                    revision: match rev {
                        Some(x) => x,
                        None => try!(visitor.missing_field("rev")),
                    },
                })
            }
        }

        static FIELDS: &'static [&'static str] = &["id", "ok", "rev"];
        deserializer.deserialize_struct("WriteDocumentResponse", FIELDS, Visitor)
    }
}

#[derive(Debug)]
pub struct DocumentBuilder(Document);

impl DocumentBuilder {
    pub fn new
(doc_path: P, revision: Revision) -> Self {
        DocumentBuilder(Document {
            doc_path: doc_path.into_document_path().unwrap().into(),
            revision: revision,
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        })
    }

    pub fn unwrap(self) -> Document {
        let DocumentBuilder(doc) = self;
        doc
    }

    pub fn with_content<C: serde::Serialize>(mut self, new_content: &C) -> Self {
        {
            let DocumentBuilder(ref mut doc) = self;
            doc.content = serde_json::to_value(new_content);
        }
        self
    }

    pub fn build_content<F>(self, f: F) -> Self
    where
        F: FnOnce(serde_json::builder::ObjectBuilder) -> serde_json::builder::ObjectBuilder,
    {
        self.with_content(&f(serde_json::builder::ObjectBuilder::new()).build())
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use AttachmentName;
    use DocumentId;
    use attachment::AttachmentBuilder;
    use serde_json;
    use std;

    #[test]
    fn json_decodable_document_deserialize_ok_as_minimum() {

        let expected = JsonDecodableDocument {
            doc_id: DocumentId::from("document_id"),
            revision: "42-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let source = serde_json::builder::ObjectBuilder::new()
            .insert("_id", "document_id")
            .insert("_rev", "42-1234567890abcdef1234567890abcdef")
            .build();

        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str(&source).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn json_decodable_document_deserialize_ok_as_deleted() {

        let expected = JsonDecodableDocument {
            doc_id: DocumentId::from("document_id"),
            revision: "42-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: true,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let source = serde_json::builder::ObjectBuilder::new()
            .insert("_id", "document_id")
            .insert("_rev", "42-1234567890abcdef1234567890abcdef")
            .insert("_deleted", true)
            .build();

        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str(&source).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn json_decodable_document_deserialize_ok_with_content() {

        let expected = JsonDecodableDocument {
            doc_id: DocumentId::from("document_id"),
            revision: "42-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: false,
            attachments: std::collections::HashMap::new(),
            content: serde_json::builder::ObjectBuilder::new()
                .insert("field_1", 42)
                .insert("field_2", 17)
                .build(),
        };

        let source = serde_json::builder::ObjectBuilder::new()
            .insert("_id", "document_id")
            .insert("_rev", "42-1234567890abcdef1234567890abcdef")
            .insert("field_1", 42)
            .insert("field_2", 17)
            .build();

        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str(&source).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn json_decodable_document_deserialize_ok_with_attachments() {

        let expected = JsonDecodableDocument {
            doc_id: DocumentId::from("document_id"),
            revision: "42-1234567890abcdef1234567890abcdef".parse().unwrap(),
            deleted: false,
            attachments: {
                let mut map = std::collections::HashMap::new();
                map.insert(
                    AttachmentName::from("attachment_1"),
                    AttachmentBuilder::new_saved(
                        mime!(Application / WwwFormUrlEncoded),
                        "md5-XNdWXQ0FO9vPx7skS0GuYA==".to_string(),
                        23,
                        517,
                    ).unwrap(),
                );
                map
            },
            content: serde_json::builder::ObjectBuilder::new().build(),
        };

        let source = serde_json::builder::ObjectBuilder::new()
            .insert("_id", "document_id")
            .insert("_rev", "42-1234567890abcdef1234567890abcdef")
            .insert_object("_attachments", |x| {
                x.insert_object("attachment_1", |x| {
                    x.insert("content_type", "application/x-www-form-urlencoded")
                        .insert("length", 517)
                        .insert("stub", true)
                        .insert("digest", "md5-XNdWXQ0FO9vPx7skS0GuYA==")
                        .insert("revpos", 23)
                })
            })
            .build();

        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str(&source).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn json_decodable_document_deserialize_nok_missing_id() {

        let source = serde_json::builder::ObjectBuilder::new()
            .insert("_rev", "42-1234567890abcdef1234567890abcdef")
            .build();

        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str::<JsonDecodableDocument>(&source);
        expect_json_error_missing_field!(got, "_id");
    }

    #[test]
    fn json_decodable_document_deserialize_nok_missing_rev() {

        let source = serde_json::builder::ObjectBuilder::new()
            .insert("_id", "document_id")
            .build();

        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str::<JsonDecodableDocument>(&source);
        expect_json_error_missing_field!(got, "_rev");
    }

    #[test]
    fn write_document_response_deserialize_ok_with_all_fields() {
        let expected = WriteDocumentResponse {
            doc_id: "foo".into(),
            ok: true,
            revision: "1-12345678123456781234567812345678".parse().unwrap(),
        };
        let source = serde_json::builder::ObjectBuilder::new()
            .insert("id", "foo")
            .insert("ok", true)
            .insert("rev", "1-12345678123456781234567812345678")
            .build();
        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str(&source).unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn write_document_response_deserialize_nok_missing_id_field() {
        let source = serde_json::builder::ObjectBuilder::new()
            .insert("ok", true)
            .insert("rev", "1-12345678123456781234567812345678")
            .build();
        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str::<WriteDocumentResponse>(&source);
        expect_json_error_missing_field!(got, "id");
    }

    #[test]
    fn write_document_response_deserialize_nok_missing_ok_field() {
        let source = serde_json::builder::ObjectBuilder::new()
            .insert("id", "foo")
            .insert("rev", "1-12345678123456781234567812345678")
            .build();
        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str::<WriteDocumentResponse>(&source);
        expect_json_error_missing_field!(got, "ok");
    }

    #[test]
    fn write_document_response_deserialize_nok_missing_rev_field() {
        let source = serde_json::builder::ObjectBuilder::new()
            .insert("id", "foo")
            .insert("ok", true)
            .build();
        let source = serde_json::to_string(&source).unwrap();
        let got = serde_json::from_str::<WriteDocumentResponse>(&source);
        expect_json_error_missing_field!(got, "rev");
    }
}


text:
Reference.Utilities.Events = [
    { name: 'T.Utils.elementDestroyed', description: '', arguments: [{ name: 'element' }], returns: 'jQuery.Deferred' },
    { name: 'T.Utils.raiseDocumentEvent', description: '', arguments: [{ name: 'name' }, { name: 'data' }] },
    { name: 'T.Utils.handleDocumentEvent', description: '', arguments: [{ name: 'name' }, { name: 'handler' }] },
    { name: '$.complete', description: '', arguments: [{ name: 'deferreds' }] },
    { name: 'jQuery.Event("destroyed")' }
];

redpajama_set_name: RedPajamaGithub


text:
require("luci.sys")

m = Map("TianYi", translate("TianYi"), translate("TianYi clinet"))

s = m:section(TypedSection, "login", "")
s.addremove = false
s.anonymous = true

enable = s:option(Flag, "enable", translate("Enable"))
name = s:option(Value, "username", translate("Username"))
name.rmempty  = false
pass = s:option(Value, "password", translate("Password"))
pass.password = true
pass.rmempty  = false
nasip = s:option(Value, "nasip", translate("wlanacip"))
nasip.datatype = "ipaddr"
nasip.rmempty  = false
phone = s:option(Flag, "phone", translate("secend clinet"),translate("simulate phone clinet"))

local apply = luci.http.formvalue("cbi.apply")
if apply then
    io.popen(" /etc/init.d/TianYi restart")
end

return m


text:
package org.scribble.ast;

import java.util.List;
import java.util.stream.Collectors;

import org.antlr.runtime.tree.CommonTree;
import org.scribble.ast.name.simple.ScopeNode;
import org.scribble.sesstype.kind.ProtocolKind;

public abstract class Interruptible<K extends ProtocolKind> extends CompoundInteractionNode<K> implements ScopedNode
{
	public final ScopeNode scope;
	public final ProtocolBlock<K> block;
	private final List<? extends Interrupt> interrs;

	protected Interruptible(CommonTree source, ScopeNode scope, ProtocolBlock<K> block, List<? extends Interrupt> interrs)
	{
		super(source);
		this.scope = scope;
		this.block = block;
		this.interrs = interrs;
	}

	/*protected abstract Interruptible<T1, T2> reconstruct(CommonTree ct, ScopeNode scope, T1 block, List<T2> interrs, CompoundInteractionNodeContext icontext, Env env);

	@Override
	public NodeContextBuilder enterContextBuilding(NodeContextBuilder builder) throws ScribbleException
	{
		builder.pushContext(new CompoundInteractionNodeContext());
		return builder;
	}

	@Override
	public Interruptible<T1, T2> leaveContextBuilding(NodeContextBuilder builder) throws ScribbleException
	{
		CompoundInteractionNodeContext icontext = (CompoundInteractionNodeContext) builder.popContext();
		builder.replaceContext(((CompoundInteractionContext) builder.peekContext()).merge(icontext));
		icontext = (CompoundInteractionNodeContext) icontext.merge(this.block.getContext());
		//return new Interruptible<T1, T2>(this.ct, this.scope, this.block, this.interrs, icontext);
		return reconstruct(this.ct, this.scope, this.block, this.interrs, icontext, getEnv());
	}

	@Override
	public Interruptible<T1, T2> leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException
	{
		checker.getEnv().leave(this, checker);
		return this;

		/*Role src = this.src.toName();
		for (Message msg : this.msgs.stream().map((mn) -> mn.toMessage()).collect(Collectors.toList()))
		{
			for (Role dest : ((GlobalInterruptContext) getContext()).getDestinations())
			{
				//checker.getEnv().addInterrupt(src, dest, msg);  // No: src must be enabled, and if receiver may be enabled by this interrupt then it must also be receiving normally inside the interruptible block

				System.out.println("2a: " + src + ", " + dest + ", " + msg);

				checker.getEnv().addMessage(src, dest, msg);
			}
		}* /
	}

	@Override
	public Interruptible<T1, T2> leaveReachabilityCheck(ReachabilityChecker checker) throws ScribbleException
	{
		checker.getEnv().leave(this, checker);
		return this;
	}

	@Override
	public Interruptible<T1, T2> visitChildren(NodeVisitor nv) throws ScribbleException
	{
		ScopeNode scope = this.scope;
		if (scope != null)
		{
			scope = (ScopeNode) visitChild(this.scope, nv);
		}
		//ProtocolBlock<? extends InteractionSequence<? extends InteractionNode>> block = (ProtocolBlock<? extends InteractionSequence<? extends InteractionNode>>) nv.visit(this.block);
		T1 block = visitChildWithClassCheck(this, this.block, nv);
		List<T2> interrs = visitChildListWithClassCheck(this, this.interrs, nv);
		//return new Interruptible<>(this.ct, scope, block, interrs, getContext(), getEnv());
		return reconstruct(this.ct, scope, block, interrs, getContext(), getEnv());
	}

	@Override
	public boolean isEmptyScope()
	{
		return false;
	}

	@Override
	//public Scope getScope()
	public SimpleName getScopeElement()
	{
		return this.scope.toName();
	}*/

	public boolean isScopeNodeImplicit()
	{
		return this.scope == null;
	}

	@Override
	public String toString()
	{
		String s = Constants.INTERRUPTIBLE_KW + " ";
		if (!isScopeNodeImplicit())
		{
			s += this.scope + ": ";
		}
		s += this.block + " " + Constants.WITH_KW + " {\n";
		s += this.interrs.stream().map((i) -> i.toString()).collect(Collectors.joining("\n")) + "\n";
		return s + "}";
	}
}


text:
package iht.forms.application.assets

import iht.forms.FormTestHelper
import iht.models.application.basicElements.BasicEstateElement
import play.api.data.Form

trait BasicEstateElementFormBehaviour extends FormTestHelper{

  def basicEstateElementForm(form: Form[BasicEstateElement], selectErrorKey:String = "error.selectAnswer") = {
      behave like yesNoQuestion[BasicEstateElement]("isOwned", form, _.isOwned, selectErrorKey)
      behave like currencyValue[BasicEstateElement]("value", form)
  }

}


text:
package io.dwadden.gps.httpsource;

import io.dwadden.gps.entities.GpsWaypoint;
import io.dwadden.gps.entities.RawGpsWaypoint;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import org.springframework.stereotype.Component;

@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@Component
public class AssignKeyTransformer {

    IdGenerator<Long> idGenerator;

    public AssignKeyTransformer(IdGenerator<Long> idGenerator) {
        this.idGenerator = idGenerator;
    }

    public GpsWaypoint assignKey(RawGpsWaypoint rawGpsWaypoint) {
        return GpsWaypoint.builder()
            .id(idGenerator.generateId())
            .latitude(rawGpsWaypoint.getLatitude())
            .longitude(rawGpsWaypoint.getLongitude())
            .heading(rawGpsWaypoint.getHeading())
            .speed(rawGpsWaypoint.getSpeed())
            .timestamp(rawGpsWaypoint.getTimestamp())
            .build();
    }

}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Competition extends Model
{
    //指定表名
    protected $table = 'competition_list';

    //指定id
    protected $primaryKey = 'id';

    //指定允许批量赋值的字段
    protected $fillable = ['name','age'];
}


text:
package net.mcarolan.whenzebus.api.value;

public class StopPointName extends StringValue {
	public StopPointName(String value) {
		super(value);
	}
}


text:
<component name="libraryTable">
  <library name="library-1.1.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.jd-alexander/library/1.1.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.jd-alexander/library/1.1.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package com.shootemoff.game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;

import android.content.res.Configuration;

import com.shootemoff.framework.Audio;
import com.shootemoff.framework.Game;
import com.shootemoff.framework.Graphics;
import com.shootemoff.framework.Input.KeyEvent;
import com.shootemoff.framework.Input.TouchEvent;
import com.shootemoff.framework.Sound;

/* I should have used pools for my objects not to make garbage
 * collector angry. As it freezes the game sometimes,
 * I avoided some object creations. However, it doesn't help.
 */

public class World
{
	Random random = new Random();
	Game game;
	private final int DOTS_COUNT = 15;
	private final int GUN_SHOTS_COUNT = 10;
	// In this case ArrayList is better than LinkedList:
	// list will never be resized.
	public List<Dot> dots = new ArrayList<Dot>(DOTS_COUNT);

	public List<Dot> shots = new ArrayList<Dot>(GUN_SHOTS_COUNT);

	public Core core = new Core();
	public ControlPad shieldControl = new ControlPad();
	public ControlPad gunControl = new ControlPad();
	public float offScreenRadius;
	private final float SHIELD_HEALTH = 20.0F;
	private final float CORE_HEALTH = 6.0F;
	//private final int[] ALLOWED_ANGLES = {110, 330, 10, 180, 350, 300, 30, 200, -20, 100, 50, 320, 270};
	private final int[] ALLOWED_ANGLES = {30, 200, -20, 100, 50, 320, 270, 0, 70, 340, 45, 20, 190, -80};

	public boolean just_aimed = false;
	public double aim_angle;
	public VectorF aim_beam;

	public float shield_top_coef = (float)0.65;//0.05;
	public float shield_bottom_coef = (float)0.95;//0.35;
	public float shield_right_coef = (float)0.30;
	public float shield_left_coef = (float)0.06;
	public float shield_top;
	public float shield_bottom;
	public float shield_right;
	public float shield_left;

	public float gun_top_coef = (float)0.05;//0.65;
	public float gun_bottom_coef = (float)0.35;//0.95;
	public float gun_right_coef = (float)0.30;
	public float gun_left_coef = (float)0.06;
	public float gun_top;
	public float gun_bottom;
	public float gun_right;
	public float gun_left;

	//default base speed
	float base_speed;

	private float time = 0.0F; // in seconds
	private float last_shot_time = 0.0F;

	public enum GameState {Ready, Running, Paused, GameOver}

	public GameState state = GameState.Ready;

	private float difficulty = 0.04F; // Max 0.1F

	// Sounds
	// Dot collides with core
	Sound coreHurt;
	Sound coreHealth;
	Sound coreShield;
	// Dot collides with shield
	Sound shieldCollision;

	Sound gameOver;
	Sound gunShot;
	Sound shieldMove;
	Sound gunShotCollision;
	Sound gameOn;

	public World(Game game, int screen_layout)
	{
		this.game = game;
		Graphics g = game.getGraphics();

		// Construct core
		core.coords = new VectorF((float) g.getWidth() / 4,
			   	(float) g.getHeight() / (float) 2);
		core.shieldRadius = (float) g.getWidth() / 4;
		core.maxRadius = core.shieldRadius * 0.7F;
		core.angle = 45.0F;
		core.health = 1.0F;
		core.shieldEnergy = 0.0F;

		//Construct shield arc
		shieldControl.angle = 45.0F;
		shieldControl.coords = new VectorF( (float)(g.getWidth() * 0.13),(float)(g.getHeight() * 0.80) );
		shieldControl.ARC_RADIUS = (float)(g.getHeight() * 0.15);
		shieldControl.SHIELD_RADIUS = (float)(shieldControl.ARC_RADIUS * 0.9F);

		//Construct gun arc
		gunControl.coords = new VectorF( (float)(g.getWidth() * 0.13),(float)(g.getHeight() * 0.20) );
		gunControl.ARC_RADIUS = (float)(g.getHeight() * 0.15);
		gunControl.SHIELD_RADIUS = (float)(gunControl.ARC_RADIUS * 0.9F);

		// Set offScreenRadius
		offScreenRadius = (float) Math.hypot((double) g.getWidth() / 2,
				(double) g.getHeight() / (float) 1.4);

		// Max dot radius (when it's energy is 1.0F)
		Dot.maxRadius = core.maxRadius / 8.0F;

		DetermineBaseSpeed(screen_layout);
		loadSounds();
	}

	//return 1-small, 2-normal, 3-large, 2-other sizes
	private int DetermineScreenSize(int screen_layout)
	{
		int screen_size;
		if ( (screen_layout & Configuration.SCREENLAYOUT_SIZE_MASK ) == Configuration.SCREENLAYOUT_SIZE_LARGE ) {
	        screen_size = 3;
	    }
	    else if ( (screen_layout & Configuration.SCREENLAYOUT_SIZE_MASK ) == Configuration.SCREENLAYOUT_SIZE_NORMAL ) {
	    	screen_size = 2;
	    }
	    else if ( (screen_layout & Configuration.SCREENLAYOUT_SIZE_MASK ) == Configuration.SCREENLAYOUT_SIZE_SMALL ) {
	    	screen_size = 1;
	    }
	    else {
	    	screen_size = 2;
	    }

		return screen_size;
	}

	private void DetermineBaseSpeed(int screen_layout)
	{
		int screen_size = DetermineScreenSize(screen_layout);
		switch(screen_size){
			case 1:
				this.base_speed = 5F;
				break;
			case 2:
				this.base_speed = 15F;
				break;
			case 3:
				this.base_speed = 25F;
				break;
			default:
				this.base_speed = 15F;
		}

	}

	private void loadSounds()
	{
		Audio a = game.getAudio();
		coreHurt = a.newSound("core_hurt.wav");
		coreHealth = a.newSound("core_health.wav");
		coreShield = a.newSound("core_shield.wav");
		shieldCollision = a.newSound("clash_02.wav");
		gameOver = a.newSound("game_over.wav");
		gunShot = a.newSound("laser_shot.wav");
		shieldMove = a.newSound("shield_move.wav");
		gunShotCollision = a.newSound("clash_01.wav");
		gameOn = a.newSound("saber_on.wav");
	}

	// Restart the game
	public void renew()
	{
		dots.clear();
		core.health = 1.0F;
		core.shieldEnergy = 0.0F;
		time = 0.0F;
		last_shot_time = 0.0F;
		state = GameState.Ready;
		difficulty = 0.04F;
		generateStartDots(DOTS_COUNT);
	}
	// Add randomness
	private void generateStartDots(int count)
	{
		for(int i = 0; i < count; i++)
		{
			generateNewDot(true);
		}
	}

	private VectorF generateNewDotCoordsInRandomPlace()
	{
		//should stick to predefined angles to make the enemies can from above
		int index = random.nextInt(ALLOWED_ANGLES.length -1 );
		int angle = ALLOWED_ANGLES[ index ];

		VectorF coords = new VectorF((float) Math.cos(angle),
				(float) Math.sin(angle));

		coords = coords.multiply(core.shieldRadius + (offScreenRadius -
					core.shieldRadius) * random.nextFloat());
		return coords;
	}

	public void update(float deltaTime)
	{
		if(state == GameState.Ready){
			updateReady(deltaTime);
		}
		if(state == GameState.Running){
			updateRunning(deltaTime);
		}
		if(state == GameState.Paused){
			updatePaused(deltaTime);
		}
		if(state == GameState.GameOver){
			updateGameOver(deltaTime);
		}
	}

	private void doInput()
	{
		if(game.getInput().isTouchDown()){

			double touchX = (double) game.getInput().getTouchX();
			double touchY = (double) game.getInput().getTouchY();
			//shield pad controls
			if(touchY >= shield_left && touchX <= shield_right &&
					touchY >= shield_top && touchY <= shield_bottom){

				float shield_pad_width = shield_bottom - shield_top;
				float touchPoint = (float)((touchY - shield_top) / shield_pad_width);

				core.angle = (270 - (200 * touchPoint)) + 200;
				shieldControl.angle = core.angle;
				shieldMove.play(20);
			}
			else if( touchY >= gun_left && touchX <= gun_right &&
						touchY >= gun_top && touchY <= gun_bottom ){

				//double shot_offset = (int)(time - last_shot_time);
				if(shots.size() < GUN_SHOTS_COUNT){

					float gun_pad_width = gun_bottom - gun_top;
					float touchPoint = (float)((touchY - gun_top) / gun_pad_width);
					aim_angle = (270 - (200 * touchPoint)) + 200 + 90;
					double radians = Math.toRadians(aim_angle);

					float current_radius = core.maxRadius * 3;
					double x_coord = core.coords.x + (Math.sin(radians) * current_radius);
					double y_coord = core.coords.y + (Math.cos(radians) * current_radius);
					aim_beam = new VectorF((float)x_coord, (float)y_coord);
					just_aimed = true;
					last_shot_time = time;
				}
				/*
					// Y-axis is inverted. See checkCollisionWithShield(...)
					// method
					normAngle(((float) (Math.atan2(-(touchY - core.coords.y),
							touchX - core.coords.x) / (Math.PI * 2) *
					360.0)) - Core.GAP_ANGLE/2F);
				*/
			}
		}
		//remember the aiming angle and sheooooouut...
		if(just_aimed == true && last_shot_time < time){
			double radians = Math.toRadians(aim_angle);

			float current_radius = core.maxRadius * core.health;
			double x_coord = core.coords.x + (Math.sin(radians) * current_radius);
			double y_coord = core.coords.y + (Math.cos(radians) * current_radius);

			gunShot.play(40);
			generateNewGunShot(x_coord, y_coord, radians);
			just_aimed = false;
		}

	}

	private void updateReady(float deltaTime)
	{
		if(checkTouchUp() || checkMenuUp())
			state = GameState.Running;
	}

	private boolean checkTouchUp()
	{
		for(TouchEvent event : game.getInput().getTouchEvents())
		{
			if(event.type == TouchEvent.TOUCH_UP)
				return true;
		}
		return false;
	}

	private boolean checkMenuUp()
	{
		for(KeyEvent event : game.getInput().getKeyEvents())
		{
			if(event.keyCode == android.view.KeyEvent.KEYCODE_MENU)
			{
				if(event.type == KeyEvent.KEY_UP)
					return true;
			}

		}
		return false;
	}

	private void updatePaused(float deltaTime)
	{
		if(checkTouchUp() || checkMenuUp())
			state = GameState.GameOver;
	}

	private void updateGameOver(float deltaTime)
	{
		if(checkTouchUp() || checkMenuUp())
			renew();
	}

	private void updateRunning(float deltaTime)
	{
		checkTouchUp(); // Just to clear touch event buffer

		if(checkMenuUp())
			state = GameState.Paused;

		countTime(deltaTime);

		doInput();

		generateNewDots(DOTS_COUNT);

		handleShotPositions();
		handleCollisions();
		moveDots(deltaTime);
		moveShots(deltaTime);
		decreaseShieldEnergy(deltaTime);
	}

	private void decreaseShieldEnergy(float deltaTime)
	{
		if(core.shieldEnergy > 0.0F)
		{
			core.shieldEnergy -= deltaTime / SHIELD_HEALTH;
			if(core.shieldEnergy < 0.0F)
			core.shieldEnergy = 0.0F;
		}
	}

	private void generateNewDots(int neededCount)
	{
		if(neededCount > dots.size())
			generateNewDot(false);
	}

	private void increaseDifficulty()
	{
		difficulty += 0.00005F;
	}

	private void generateNewGunShot(double x, double y, double radians)
	{
		float linearSpeed = this.base_speed * difficulty;
		Dot gun_shot = new Dot();

		gun_shot.coords = new VectorF((float)x, (float)y);

		gun_shot.angle_radians = radians;

		VectorF speed  = new VectorF(linearSpeed, linearSpeed);
		gun_shot.speed = speed;
		gun_shot.energy = 1.0F;
		//gun_shot.coords.subtractFromThis(core.coords);
		//gun_shot.coords = generateNewDotCoordsInRandomPlace();
		gun_shot.type = Dot.Type.Gunshot;

		shots.add(gun_shot);
	}

	private void generateNewDot(boolean atStart)
	{
		float linearSpeed = this.base_speed * difficulty;
		Dot dot = new Dot();
		if(atStart)
		{
			dot.coords = generateNewDotCoordsInRandomPlace();
		}
		else
		{
			dot.coords = generateNewDotAtOffScreenRadius();
			increaseDifficulty();
		}
		VectorF speed = new VectorF(
				linearSpeed * (-dot.coords.x / dot.coords.length()),
			   linearSpeed * (-dot.coords.y / dot.coords.length()));
		dot.speed = speed;
		dot.coords.addToThis(core.coords);
		dot.energy = random.nextFloat();
		if(dot.energy <= 0.3F)
			dot.energy = 0.3F;
		float typeRand = random.nextFloat();
		Dot.Type type;
		if (typeRand >= 0.8){
			type = Dot.Type.Health;
		}
		else{
			type = Dot.Type.Enemy;
		}
		dot.type = type;
		dots.add(dot);
	}

	private void countTime(float deltaTime)
	{
		time += deltaTime;
	}

	public String getTime()
	{
		int seconds = (int) time;
		int minutes = seconds / 60;
		seconds %= 60;
		String result = "";
		if(minutes > 0)
			result += minutes + ":";
		result += String.format("%02d", seconds);
		return result;
	}

	private VectorF generateNewDotAtOffScreenRadius()
	{
		//should stick to predefined angles to make the enemies can from above
		int index = random.nextInt(ALLOWED_ANGLES.length -1 );
		int angle = ALLOWED_ANGLES[ index ];

		VectorF coords =
		   	new VectorF(offScreenRadius * ((float) Math.cos(angle)),
					offScreenRadius * ((float) Math.sin(angle)));

		return coords;
	}

	private void moveShots(float deltaTime)
	{
		for(Dot dot : shots)
		{
			dot.coords.addToThis((float)(dot.speed.x * deltaTime * 100.0F * Math.sin(dot.angle_radians)),
					(float)(dot.speed.y * deltaTime * 100.0F * Math.cos(dot.angle_radians)));

		}
	}

	private void moveDots(float deltaTime)
	{
		for(Dot dot : dots)
		{
			dot.coords.addToThis(dot.speed.x * deltaTime * 100.0F,
					dot.speed.y * deltaTime * 100.0F);
		}
	}

	private void handleShotPositions()
	{
		Iterator<Dot> iterator = shots.iterator();
		while(iterator.hasNext())
		{
			handleShotPosition(iterator.next(), iterator);
		}
	}

	private void handleShotPosition(Dot shot, Iterator<Dot> iterator)
	{

		Graphics g = game.getGraphics();
		if(shot.coords.x < 0 || shot.coords.y < 0 || shot.coords.x > g.getWidth() || shot.coords.x > g.getHeight()){
			iterator.remove();
		}
	}

	private void handleShotCollision(Dot shot, Iterator<Dot> shot_iterator, Dot dot, Iterator<Dot> dot_iterator)
	{
		if(Math.abs(shot.coords.x - dot.coords.x) <= Dot.maxRadius &&
				Math.abs(shot.coords.y - dot.coords.y) <= Dot.maxRadius){

			shot_iterator.remove();
			dot_iterator.remove();
			gunShotCollision.play(40);
			game.getVibration().vibrate(30);
		}
	}

	private void handleCollisions()
	{
		Iterator<Dot> iterator = dots.iterator();
		while(iterator.hasNext())
		{
			handleCollision(iterator.next(), iterator);
		}
	}

	private void handleCollision(Dot dot, Iterator<Dot> iterator)
	{
		float lengthToCoreCenter = (float)Math.hypot(
				(double)(dot.coords.x - core.coords.x),
				(double)(dot.coords.y - core.coords.y));

		if(Math.abs(lengthToCoreCenter -
					core.shieldRadius) <= dot.maxRadius * dot.energy +
				Core.SHIELD_WIDTH)
		{
			checkCollisionWithShield(dot, iterator);
		}
		else if (lengthToCoreCenter - core.maxRadius * core.health <=
			   	Dot.maxRadius * dot.energy){
			handleCollisionWithCore(dot, iterator);
		}
		else{
			try{
				if(shots.size() > 0 && dot.type == Dot.Type.Enemy){
					Iterator<Dot> shot_iterator = shots.iterator();
					while(shot_iterator.hasNext()){
						handleShotCollision(shot_iterator.next(), shot_iterator, dot, iterator);
					}
				}
			}
			catch(NoSuchElementException e){
				// just sit this one out
			}
		}
	}

	private void checkCollisionWithShield(Dot dot, Iterator<Dot> iterator)
	{
		// I normalize (move into (0; 360) interval) angles
		// in some places. Don't know if it's needed.
		if(core.shieldEnergy > 0.0F)
		{
			iterator.remove();
			shieldCollision.play(dot.energy);
			game.getVibration().vibrate(30);
		}
		else
		{
		// Pay attention at -v.y! Y-axis is inverted,
		// because it points downwards.
		float dotAngle = (float) Math.atan2((double) -
				(dot.coords.y - core.coords.y),
			   	(double) (dot.coords.x - core.coords.x));
		dotAngle = dotAngle / (((float) Math.PI) * 2.0F) * 360.0F;
		dotAngle = normAngle(dotAngle);
		// For example, dotAngle = 3, and core.angle = 365
		// We need to solve this somehow:
		core.angle = normAngle(core.angle);
		while(dotAngle < core.angle)
		{
			dotAngle += 360.0F;
		}
		// OK, and check if dotAngle is within the gap
		if(!((dotAngle > core.angle) &&
				   	(dotAngle < core.angle + core.GAP_ANGLE)))
		{
			iterator.remove();
			shieldCollision.play(dot.energy);
			game.getVibration().vibrate(40);
		}
		}
	}

	private float normAngle(float angle)
	{
		float angle2 = angle;
		while(angle2 < 0.0F)
			angle2 += 360.0F;

		while(angle2 > 360.0F)
			angle2 -= 360.0F;

		return angle2;
	}

	private void handleCollisionWithCore(Dot dot, Iterator<Dot> iterator)
	{
		if(dot.type == Dot.Type.Enemy){
			core.health -= dot.energy / CORE_HEALTH;
			if(core.health < 0.0F)
			{
				//state = GameState.GameOver;
				state = GameState.Paused;
				gameOver.play(1F);
				game.getVibration().vibrate(10);
				game.getVibration().vibrate(40);
				game.getVibration().vibrate(100);
				core.health = 0.0F;
			}
			coreHurt.play(dot.energy);
			}
			else if (dot.type == Dot.Type.Health)
			{
			core.health += dot.energy / CORE_HEALTH;
			if(core.health > 1.0F)
			{
				core.health = 1.0F;
			}
			coreHealth.play(dot.energy);
		}

		iterator.remove();
		game.getVibration().vibrate(30);
	}

}


text:
require('dotenv').config({ silent: true });
const Crawler = require('simplecrawler');
const jsdom = require('jsdom');
const colors = require('colors');
const string = require('string');
const jquery = require('jquery');
const fs = require('fs');
const path = require('path');
const parseArgs = require('minimist');

class Results {
  constructor(onlyErrors, params) {
    this.onlyErrors = onlyErrors;
    this.params = params;
    this.results = [];
  }

  saveResult(result) {
    this.results.push(result);
  }

  printResults() {
    const activeResults = this.results.filter(result => (!this.onlyErrors || result.isError));

    if (!this.onlyErrors || activeResults.length > 0) {
      console.log('');
      // eslint-disable-next-line prefer-template
      console.log(`Results for ${this.params.url}`
        + colors.dim(` (${this.params.bufferLength} bytes, type ${this.params.contentType})`));

      activeResults.forEach(result => {
        const printWithColor = result.isError ? colors.red : colors.green;
        console.log(printWithColor(result.message));
      });
    }
  }
}

function downloadSite(initialUrl, rules, verbose) {
  const crawler = new Crawler(initialUrl);

  crawler.interval = 500;
  crawler.maxConcurrency = 3;
  crawler.decodeResponses = true;

  crawler.on('fetchcomplete', (queueItem, responseBuffer, response) => {
    process.stdout.write('.');

    if (!string(response.headers['content-type']).startsWith('text/html')) {
      return;
    }

    jsdom.env(
      responseBuffer,
      ['http://code.jquery.com/jquery.js'],
      (err, window) => {
        const $ = jquery(window);
        const params = {
          url: queueItem.url,
          bufferLength: responseBuffer.length,
          contentType: response.headers['content-type'],
        };
        const results = new Results(!verbose, params);

        const rulePromises = [];
        rules.forEach(rule => {
          const rulePromise = rule.run($, results, params);
          if (rulePromise instanceof Promise) {
            rulePromises.push(rulePromise);
          }
        });

        Promise.all(rulePromises).then(() => {
          results.printResults();
        }, () => {
          results.printResults();
        });
      }
    );
  });

  crawler.on('complete', () => {
    console.log('');
    console.log('Done crawling! Async rules may still be in progress.');
  });

  crawler.start();
}

const argv = parseArgs(process.argv.slice(2));

if (argv._.length < 1) {
  console.error('Usage: node seotest.js http://testsite.com [enabled-rules, ...]');
  process.exit(1);
}

const enabledRules = argv._.slice(1).map(rule => (
  string(rule).chompRight('.js').toString()
));

const rulesDir = 'rules';
const normalizedPath = path.join(__dirname, rulesDir);
const loadedRules = [];
fs.readdirSync(normalizedPath).forEach(file => {
  loadedRules.push({
    name: string(file).chompRight('.js').toString(),
    run: require(`./${rulesDir}/${file}`), // eslint-disable-line global-require
  });
});

const rules = [];
console.log(colors.green('Rules'));
loadedRules.forEach(rule => {
  const isEnabled = enabledRules.length === 0 || enabledRules.includes(rule.name);
  console.log(
    `* ${rule.name.toString()} [${isEnabled ? colors.green('enabled') : colors.red('disabled')}]`);
  if (isEnabled) {
    rules.push(rule);
  }
});

downloadSite(argv._[0], rules, argv.verbose || argv.v);


text:
The lexer scans over a preprocessed Cix file character-by-character and is the second stage of compilation. It builds individual words by determining if a character is in a legal position. It removes comments and whitespace, then separates a file into a list of words.

## Contexts

The lexer's context is its state. The context can be set by the character most recently scanned. The contexts are:

* Root: No context has been set yet.
* Whitespace: The last character was a whitespace or line terminator.
* Word: The last charater was a character in a word or identifier not inside a string literal.
* Operator: The last character was an operator character.
* NumericLiteral: A number after whitespace not inside a string literal was found, and no . character, {u l f d} character, or whitespace has been reached yet.
* NumericLiteralFraction. A . character was found during a NumericLiteral context, and no {u l f d} character or whitespace has been reached yet.
* NumericLiteralSuffix: A {u l f d} character was found during a NumericLiteral or NumericLiteralFraction context, and no whitespace has been reached yet.
* HexadecimalNumericLiteral: An 'x' character was found during a NumericLiteral context, and no whitespace has been reached yet.
* StringLiteral: An unescaped " character not inside a string literal was found, and no matching unescaped " character has been reached yet.

## What to Do for Each Character
### Whitespace or Line Terminator
* Root: Ignore.
* Whitespace: Ignore.
* Word: Yield the builder.
* Operator: Yield the builder.
* NumericLiteral: Yield the builder.
* NumericLiteralFraction: Yield the builder.
* NumericLiteralSuffix: Yield the builder.
* StringLiteral: Append "\r\n" to the builder.

### Brace, Bracket, or Parenthesis
* Root: INVALID. These cannot appear as the first character. Add an error to the error list.
* Whitespace: Yield the character.
* Word: Yield the word, and then the character.
* Operator: INVALID. These do not succeed operators. Add an error to the error list.
* NumericLiteral: INVALID. Braces do not appear immediately after numeric literals. Brackets and parentheses only follow a number if it's part of a word. Add an error to the error list.
* NumericLiteralFraction: Same as NumericLiteral.
* NumericLiteralSuffix: Same as NumericLiteral.
* StringLiteral: Append to the builder.

### At Sign (@)
* Root: Starts an identifier (@funcptr, in this case). Switch to Word and append to builder.
* Whitespace: Starts an identifier. Switch to Word and append to builder.
* Word: INVALID. The At Sign can only start an identifier. Add an error to the error list.
* Operator: Yield and clear the builder. Append to builder and change context to Word.
* NumericLiteral: INVALID. At Signs require whitespace after a number to be parsed as an identifier. Add an error to the error list.
* NumericLiteralFraction: INVALID. At Signs require whitespace after a number to be parsed as an identifier. Add an error to the error list.
* NumericLiteralSuffix: INVALID. At Signs require whitespace after a number to be parsed as an identifier. Add an error to the error list.
* HexadecimalNumericLiteral: INVALID. At Signs require whitespace after a number to be parsed as an identifier. Add an error to the error list.
* StringLiteral: Append to builder.

### Letter or Underscore
* Root: Starts an identifier. Switch to Word and append to builder.
* Whitespace: Starts an identifier. Switch to Word and append to builder.
* Word: Append to builder.
* Operator: Yield and clear the builder. Append to builder and change context to Word.
* NumericLiteral: Is it {u l f d}? Switch to NumericLiteralSuffix and append to builder. No? INVALID. No other letters appear within numeric literals. Add an error to the error list.
* NumericLiteralFraction: Same as in NumericLiteral.
* NumericLiteralSuffix: Is it l and the last letter u? Append to builder and yield. No? INVALID. No other character appears after u and no other character is used as a second character. Throw
* StringLiteral: Append to builder.

### Quotation Mark (")
* Root: INVALID. String literals cannot be started in a root context. Add an error to the error list.
* Whitespace: Append the quote to the builder and change context to StringLiteral.
* Word: INVALID. Quotation marks may not appear in words. Add an error to the error list.
* Operator: Yield and clear the builder. Append to builder and change context to StringLiteral.
* NumericLiteral: Same as in Word.
* NumericLiteralFraction: Same as in Word.
* NumericLiteralSuffix: Same as in Word.
* StringLiteral: Check previous character. If it's a \, append a quote to the builder. If it's not, append to builder, yield, and switch context to Whitespace.

### Plus Sign (+)
* Root: INVALID. This character is invalid in a root context. Add an error to the error list.
* Whitespace: Append to the builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if last character was +. If so, append to builder, yield, change context to Whitespace, otherwise add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Same as in NumericLiteral.
* NumericLiteralSuffix: Same as in NumericLiteral.
* StringLiteral: Append to builder.

### Minus Sign (-)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if last character was -. If so, append to builder, yield, and change context to Whitespace, otherwise add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Same as in NumericLiteral.
* NumericLiteralSuffix: Same as in NumericLiteral.
* StringLiteral: Append to builder.

### Exclamation Mark (!)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Is the next character =? If yes, yield the builder, switch context to Operator, and append to builder. If not, add an error to the error list.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Same as in NumericLiteral.
* NumericLiteralSuffix: Same as in NumericLiteral.
* StringLiteral: Append to builder.

### Tilde (~)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Is the next character =? If yes, yield the builder, switch context to Operator, and append to builder. If not, add an error to the error list.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Same as in Word.
* NumericLiteralFraction: Same as in Word.
* NumericLiteralSuffix: Same as in Word.
* StringLiteral: Append to builder.

### Asterisk (*)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Same as in NumericLiteral.
* NumericLiteralSuffix: Same as in NumericLiteral.
* StringLiteral: Append to builder.

### Back Slash (/)
* Root: INVALID. Add an error to the error list.
* Whitespace: Is the next character { * / }? If so, change context to Comment. Otherwise, append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Percent Sign (%)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Less-Than Sign (<)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and switch context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if the last character was <; if so, append to builder, otherwise add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Greater-Than Sign (>)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and switch context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if the last character was one of { * > }; if so, append to builder, otherwise add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Ampersand (&)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and switch context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if the last character was &; if so, append to builder, otherwise add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Pipe (|)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and switch context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if the last character was |; if so, append to builder, otherwise add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Caret (^)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and switch context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Dot (.)
* Root: INVALID. Add an error to the error list.
* Whitespace: INVALID. Add an error to the error list.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Append to builder and switch context to NumericLiteralFraction.
* NumericLiteralFraction: INVALID. Add an error to the error list.
* NumericLiteralSuffix: INVALID. Add an error to the error list.
* StringLiteral: Append to builder.

### Question Mark (?)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Colon (:)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Equals Sign (=)
* Root: INVALID. Add an error to the error list.
* Whitespace: Append to builder and change context to Operator.
* Word: Yield and clear the builder. Append to builder and change context to Operator.
* Operator: Check if last character was one of { < > = + * * / % < > & | ^ }. If so, append to builder and change context to Whitespace. If not, add an error to the error list.
* NumericLiteral: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralFraction: Yield and clear the builder. Append to builder and change context to Operator.
* NumericLiteralSuffix: Yield and clear the builder. Append to builder and change context to Operator.
* StringLiteral: Append to builder.

### Forward Slash (\\)
* Root: INVALID. Add an error to the error list.
* Whitespace: INVALID. Add an error to the error list.
* Word: INVALID. Add an error to the error list.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: INVALID. Add an error to the error list.
* NumericLiteralFraction: INVALID. Add an error to the error list.
* NumericLiteralSuffix: INVALID. Add an error to the error list.
* StringLiteral: Append to builder.

### Semicolon (;)
* Root: Append to builder and change context to Whitespace.
* Whitespace: Same as in Root.
* Word: Same as in Root.
* Operator: Same as in Root.
* NumericLiteral: Same as in Root.
* NumericLiteralFraction: Same as in Root.
* NumericLiteralSuffix: Same as in Root.
* StringLiteral: Append to builder.

### At Sign (@)
* Root: Starts an identifier to be treated as an intrinsic. Switch context to Word and append to builder.
* Whitespace: Starts an identifier to be treated as an intrinsic. Switch context to Word and append to builder.
* Word: INVALID. At signs only appear at the start of intrinsic identifiers. Add an error to the error list.
* Operator: Yield and clear the builder. Append to builder and change context to Word.
* NumericLiteral: Is it {u l f d}? Switch to NumericLiteralSuffix and append to builder. No? INVALID. No other letters appear within numeric literals. Add an error to the error list.
* NumericLiteralFraction: Same as in NumericLiteral.
* NumericLiteralSuffix: Is it l and the last letter u? Append to builder and yield. No? INVALID. No other character appears after u and no other character is used as a second character. Throw
* StringLiteral: Append to builder.

### Any Other Character
* Root: INVALID. Add an error to the error list.
* Whitespace: INVALID. Add an error to the error list.
* Word: INVALID. Add an error to the error list.
* Operator: INVALID. Add an error to the error list.
* NumericLiteral: INVALID. Add an error to the error list.
* NumericLiteralFraction: INVALID. Add an error to the error list.
* NumericLiteralSuffix: INVALID. Add an error to the error list.
* StringLiteral: Append to builder.


text:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var basePath = __dirname;

module.exports = {
  context: path.join(basePath, 'src'),
  entry: {
    app: './index.js',
    vendor: [
      'angular',
    ],
    vendorStyles: [
      '../node_modules/bootstrap/dist/css/bootstrap.css',
    ],
  },
  output: {
    path: path.join(basePath, 'dist'),
    filename: '[name].[chunkhash].js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            { loader: 'css-loader', },
            { loader: 'sass-loader', },
          ],
        }),
      },
      {
        test: /\.css$/,
        include: /node_modules/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: {
            loader: 'css-loader',
          },
        }),
      },
      // Loading glyphicons => https://github.com/gowravshekar/bootstrap-webpack
      // Using here url-loader and file-loader
      {
        test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff'
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader'
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
      },
      {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: 'html-loader',
      },
    ],
  },
  // For development https://webpack.js.org/configuration/devtool/#for-development
  devtool: 'inline-source-map',
  devServer: {
    port: 8080,
  },
  plugins: [
    //Generate index.html in /dist => https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html', //Name of file in ./dist/
      template: 'index.html', //Name of template in ./src
      hash: true,
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
    }),
    new webpack.HashedModuleIdsPlugin(),
    new ExtractTextPlugin({
      filename: '[name].[chunkhash].css',
      disable: false,
      allChunks: true,
    }),
  ],
};


text:
<?php include('plugin/page_declaration.php');?>
	<title>Checkout</title>

	<?php include('plugin/header.php');?>

	<?php
	if($_SESSION['isloggedin'] = 'true' && $_POST['patUserID'])
	{?>

    <?php
      require_once 'braintree_setup.php';
      //collects user id of client_id
      $customerId = $_POST['user_id'];
      //Collects the payment nonce from the client
      $nonceFromTheClient = $_POST["payment_method_nonce"];
      //Collects customer details
      $firstName=$_POST['firstName'];
      $lastName=$_POST['lastName'];
      $telephone=$_POST['telephone'];
      $patUserID=$_POST['patUserID'];
			$email = $_POST['email'];
      //Collects the amount
      $amount = $_POST['amount'];

      //Create the customer
      $result = Braintree_Customer::create
      ([
        'firstName' => $firstName,
        'lastName' => $lastName,
        'phone' => $telephone,
				'email' => $email,
        'paymentMethodNonce' => $nonceFromTheClient
      ]);

			$result->success;
			# true
			echo('
You have subscribed successfully
');

			$braintreeCustomerID = $result->customer->id;
			echo('
Thank you and welcome to full access
');

			$braintreeCustomerPaymentToken = $result->customer->paymentMethods[0]->token;

			//Attempt to initiate a subscription
			$result = Braintree_Subscription::create
			([
  			'paymentMethodToken' => $braintreeCustomerPaymentToken,
  			'planId' => 'kwy2'
			]);
			$braintreeSubscriptionId = $result->subscription->id;
			//echo ('
Subscription id is '.$braintreeSubscriptionId.'
');
      ?>

			<?php
			$subscriptionObject = Braintree_Subscription::find($braintreeSubscriptionId);
			$status_history = $subscriptionObject->statusHistory;
			//$subscription = $subscriptionObject->subscription;
			//$nextBillingDate = $subscriptionObject->nextBillingDate;
			$id=$subscriptionObject->id;
			$status=$subscriptionObject->status;

			//echo('
Balance = '.$status_history[0]->balance.'
');
			//echo('
Status = '.$status_history[0]->status.'
');
			//echo('
ID = '.$id.'
');
			//echo('
Status = '.$status.'
');
			//echo('
First Billling Date = '.$subscription->firstBillingDate .'
');
			//echo('
Next Billling Date = '.$subscription->nextBillingDate .'
');
			//echo('
Paid Through Date = '.$subscription->paidThroughDate  .'
');

			//#=> "12.34"
			?>

			<?php
				$user_id = $_SESSION['user_id'];
				$customer_id = $braintreeCustomerID;
				//Create connection
				require($_SESSION['includes'].'PAT_tester.php');
				$mysql =("	UPDATE loginDB.pat_testers
										SET braintree_customer_id = \"$braintreeCustomerID\", braintree_subscription_id = \"$braintreeSubscriptionId\"
										WHERE user_id = \"$user_id\"");
				//echo $mysql;
				if(mysqli_query($conn, $mysql ))
				{
				}
				else
				{
					echo('
My SQL ERROR!!! DB not inserted to.
');
					echo('
$mysql = '.$mysql.'
');
					echo mysql_errno($conn) . ": " . mysql_error($conn). "\n";
				}

			?>

      <?php
      $body = print_r($_POST, true);
      //echo ('
'.$body.'
');
      ?>
       Back to home

	<?php
	}
	else
	{
		echo('
Sorry, there must have been a mistake, you should not be here.
');
	}?>

		<?php $_SESSION['braintree_subscription_status'] = "Active"; ?>
		<?php include('plugin/footer.php'); ?>


text:
package volume

import (
	"github.com/astaxie/beego"
	"github.com/cloudawan/cloudone_gui/controllers/identity"
	"github.com/cloudawan/cloudone_utility/restclient"
)

type DeleteController struct {
	beego.Controller
}

// @Title delete
// @Description delete the gluster volume
// @Param glusterfsVolume path string true "The name of gluster volume"
// @Param clusterName path string true "The name of gluster cluster configuration"
// @Success 200 {string} {}
// @Failure 404 error reason
// @router /:clusterName/:glusterfsVolume [delete]
func (c *DeleteController) Delete() {
	clusterName := c.GetString(":clusterName")
	glusterfsVolume := c.GetString(":glusterfsVolume")

	cloudoneProtocol := beego.AppConfig.String("cloudoneProtocol")
	cloudoneHost := beego.AppConfig.String("cloudoneHost")
	cloudonePort := beego.AppConfig.String("cloudonePort")

	url := cloudoneProtocol + "://" + cloudoneHost + ":" + cloudonePort +
		"/api/v1/glusterfs/clusters/" + clusterName + "/volumes/" + glusterfsVolume

	tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string)

	_, err := restclient.RequestDelete(url, nil, tokenHeaderMap, true)

	if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {
		return
	}

	if err != nil {
		// Error
		c.Data["json"] = make(map[string]interface{})
		c.Data["json"].(map[string]interface{})["error"] = err.Error()
		c.Ctx.Output.Status = 404
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = make(map[string]interface{})
		c.ServeJSON()
	}
}


text:
#define pr_fmt(fmt) "kasan: " fmt
#include <linux/bootmem.h>
#include <linux/kasan.h>
#include <linux/kdebug.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/vmalloc.h>

#include <asm/tlbflush.h>
#include <asm/sections.h>

extern pgd_t early_level4_pgt[PTRS_PER_PGD];
extern struct range pfn_mapped[E820_X_MAX];

static int __init map_range(struct range *range)
{
	unsigned long start;
	unsigned long end;

	start = (unsigned long)kasan_mem_to_shadow(pfn_to_kaddr(range->start));
	end = (unsigned long)kasan_mem_to_shadow(pfn_to_kaddr(range->end));

	/*
	 * end + 1 here is intentional. We check several shadow bytes in advance
	 * to slightly speed up fastpath. In some rare cases we could cross
	 * boundary of mapped shadow, so we just map some more here.
	 */
	return vmemmap_populate(start, end + 1, NUMA_NO_NODE);
}

static void __init clear_pgds(unsigned long start,
			unsigned long end)
{
	for (; start < end; start += PGDIR_SIZE)
		pgd_clear(pgd_offset_k(start));
}

static void __init kasan_map_early_shadow(pgd_t *pgd)
{
	int i;
	unsigned long start = KASAN_SHADOW_START;
	unsigned long end = KASAN_SHADOW_END;

	for (i = pgd_index(start); start < end; i++) {
		pgd[i] = __pgd(__pa_nodebug(kasan_zero_pud)
				| _KERNPG_TABLE);
		start += PGDIR_SIZE;
	}
}

#ifdef CONFIG_KASAN_INLINE
static int kasan_die_handler(struct notifier_block *self,
			     unsigned long val,
			     void *data)
{
	if (val == DIE_GPF) {
		pr_emerg("CONFIG_KASAN_INLINE enabled");
		pr_emerg("GPF could be caused by NULL-ptr deref or user memory access");
	}
	return NOTIFY_OK;
}

static struct notifier_block kasan_die_notifier = {
	.notifier_call = kasan_die_handler,
};
#endif

void __init kasan_early_init(void)
{
	int i;
	pteval_t pte_val = __pa_nodebug(kasan_zero_page) | __PAGE_KERNEL;
	pmdval_t pmd_val = __pa_nodebug(kasan_zero_pte) | _KERNPG_TABLE;
	pudval_t pud_val = __pa_nodebug(kasan_zero_pmd) | _KERNPG_TABLE;

	for (i = 0; i < PTRS_PER_PTE; i++)
		kasan_zero_pte[i] = __pte(pte_val);

	for (i = 0; i < PTRS_PER_PMD; i++)
		kasan_zero_pmd[i] = __pmd(pmd_val);

	for (i = 0; i < PTRS_PER_PUD; i++)
		kasan_zero_pud[i] = __pud(pud_val);

	kasan_map_early_shadow(early_level4_pgt);
	kasan_map_early_shadow(init_level4_pgt);
}

void __init kasan_init(void)
{
	int i;

#ifdef CONFIG_KASAN_INLINE
	register_die_notifier(&kasan_die_notifier);
#endif

	memcpy(early_level4_pgt, init_level4_pgt, sizeof(early_level4_pgt));
	load_cr3(early_level4_pgt);
	__flush_tlb_all();

	clear_pgds(KASAN_SHADOW_START, KASAN_SHADOW_END);

	kasan_populate_zero_shadow((void *)KASAN_SHADOW_START,
			kasan_mem_to_shadow((void *)PAGE_OFFSET));

	for (i = 0; i < E820_X_MAX; i++) {
		if (pfn_mapped[i].end == 0)
			break;

		if (map_range(&pfn_mapped[i]))
			panic("kasan: unable to allocate shadow!");
	}
	kasan_populate_zero_shadow(
		kasan_mem_to_shadow((void *)PAGE_OFFSET + MAXMEM),
		kasan_mem_to_shadow((void *)__START_KERNEL_map));

	vmemmap_populate((unsigned long)kasan_mem_to_shadow(_stext),
			(unsigned long)kasan_mem_to_shadow(_end),
			NUMA_NO_NODE);

	kasan_populate_zero_shadow(kasan_mem_to_shadow((void *)MODULES_END),
			(void *)KASAN_SHADOW_END);

	memset(kasan_zero_page, 0, PAGE_SIZE);

	load_cr3(init_level4_pgt);
	__flush_tlb_all();
	init_task.kasan_depth = 0;

	pr_info("KernelAddressSanitizer initialized\n");
}


text:
package com.gmail.trentech.pja.commands;

import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

import com.gmail.trentech.pja.Main;
import com.gmail.trentech.pja.utils.ConfigManager;
import com.gmail.trentech.pja.utils.Resource;

import ninja.leaping.configurate.ConfigurationNode;

public class CMDDelete implements CommandExecutor {

	@Override
	public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
		if (!args.hasAny("name")) {
			src.sendMessage(Text.of(TextColors.YELLOW, "/auto delete <name>"));
			return CommandResult.empty();
		}
		String name = args.<String> getOne("name").get().toLowerCase();

		ConfigManager configManager = new ConfigManager();
		ConfigurationNode config = configManager.getConfig();

		if (config.getNode("Schedulers", name).getString() == null) {
			src.sendMessage(Text.of(TextColors.DARK_RED, name, " does not exist"));
			return CommandResult.empty();
		}

		if (!config.getNode("Schedulers").removeChild(name)) {
			src.sendMessage(Text.of(TextColors.DARK_RED, "Something went wrong"));
			return CommandResult.empty();
		}

		configManager.save();

		for (Task t : Main.getGame().getScheduler().getScheduledTasks()) {
			if (t.getName().equals(Resource.NAME + ":" + name)) {
				t.cancel();
			}
		}

		src.sendMessage(Text.of(TextColors.DARK_GREEN, name, " removed"));

		return CommandResult.empty();
	}

}