text:
// @(#)$Id: doubleAbstractFilteringIteratorDecorator.java-generic,v 1.11 2005/12/24 21:20:31 chalin Exp $

// Copyright (C) 2005 Iowa State University
//
// This file is part of the runtime library of the Java Modeling Language.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2.1,
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with JML; see the file LesserGPL.txt.  If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301  USA.

package org.jmlspecs.jmlunit.strategies;

import java.util.NoSuchElementException;

/** An filtering decorator for an indefinite iterator over type double.
 * @author Gary T. Leavens
 */
// FIXME: adapt this file to non-null-by-default and remove the following modifier.
/*@ nullable_by_default @*/
public abstract class DoubleAbstractFilteringIteratorDecorator
    extends DoubleAbstractIterator
{
    private /*@ spec_public non_null @*/ DoubleIterator rawElems;
    //@ in objectState; maps rawElems.objectState \into objectState;

    //@ public ghost boolean dented = false;

    //@ public invariant !dented ==> (atEnd() <==> rawElems.atEnd());
    /*@ public invariant !dented ==>
      @                   (!atEnd() ==> get().equals(rawElems.get()));
      @ public invariant_redundantly !dented ==>
      @                 (!atEnd() ==>
      @                 new Double(getDouble())
      @                 .equals(new Double(rawElems.getDouble())));
      @*/

    /** Initialize this iterator decorator */
    /*@ public normal_behavior
      @   requires iter != null;
      @   assignable rawElems, objectState, owner;
      @   ensures (* rawElems is a clone of iter *);
      @   ensures owner == null;
      @*/
    public DoubleAbstractFilteringIteratorDecorator
        (DoubleIterator iter)
    {
        rawElems = (DoubleIterator) iter.clone();
        //@ set rawElems.owner = this;
        //@ set owner = null;
        setCursor();
    }

    /** Partially intialize this iterator decorator, with a call to
     * initialize needed after this call. */
    /*@ public normal_behavior
      @   requires iter != null;
      @   assignable rawElems, dented, owner;
      @   ensures (* rawElems is a clone of iter *) && dented;
      @   ensures owner == null;
      @*/
    public DoubleAbstractFilteringIteratorDecorator
        (DoubleIterator iter, double ignored)
    {
        //@ set dented = true;
        rawElems = (DoubleIterator) iter.clone();
        //@ set rawElems.owner = this;
        //@ set owner = null;
    }

    /** Complete initialization of this object. */
    //@ assignable objectState, dented;
    //@ ensures !dented;
    //@ ensures !atEnd() ==> approve(getDouble());
    public void initialize() {
        setCursor();
        //@ set dented = false;
    }

    /** Set the cursor to the next element that is approved, if any. */
    //@ assignable objectState;
    //@ ensures !rawElems.atEnd() ==> approve(rawElems.getDouble());
    private void setCursor() {
        while (!rawElems.atEnd() && !approve(rawElems.getDouble())) {
            rawElems.advance();
        }
    }

    /** Return true if the element is to be returned by the
     * getDouble() method. */
    //@ public normal_behavior
    //@   assignable \nothing;
    public abstract /*@ pure @*/ boolean approve(double elem);

    // doc comment inherited
    /*@ also public normal_behavior
      @   assignable \nothing;
      @   ensures \result == rawElems.atEnd();
      @*/
    public /*@ pure @*/ boolean atEnd() {
        return rawElems.atEnd();
    }

    /** Return the current approved element. */
    public /*@ pure @*/ double getDouble()
        throws NoSuchElementException
    {
        return rawElems.getDouble();
    }

    // doc comment inherited
    //@ also public normal_behavior
    //@   assignable objectState;
    //@   ensures !atEnd() ==> approve(getDouble());
    public void advance() {
        rawElems.advance();
        setCursor();
    }

    public /*@ non_null @*/ Object clone() {
        DoubleAbstractFilteringIteratorDecorator ret
            = (DoubleAbstractFilteringIteratorDecorator) super.clone();
        ret.rawElems = (DoubleIterator) rawElems.clone();
        return ret;
    }

    public /*@ non_null @*/ String toString() {
        return "DoubleAbstractFilteringIteratorDecorator("
            + rawElems + ")";
    }
}


text:
package org.elasticsearch.transport.nio;

import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.PageCacheRecycler;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.plugins.NetworkPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.Transport;

import java.util.Collections;
import java.util.Map;
import java.util.function.Supplier;

public class MockNioTransportPlugin extends Plugin implements NetworkPlugin {

    public static final String MOCK_NIO_TRANSPORT_NAME = "mock-nio";

    @Override
    public Map<String, Supplier<Transport>> getTransports(
        Settings settings,
        ThreadPool threadPool,
        PageCacheRecycler pageCacheRecycler,
        CircuitBreakerService circuitBreakerService,
        NamedWriteableRegistry namedWriteableRegistry,
        NetworkService networkService
    ) {
        return Collections.singletonMap(
            MOCK_NIO_TRANSPORT_NAME,
            () -> new MockNioTransport(
                settings,
                Version.CURRENT,
                threadPool,
                networkService,
                pageCacheRecycler,
                namedWriteableRegistry,
                circuitBreakerService
            )
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Sharwyn Hucrele"
date: 2017-09-10
tags: [medium, humanoid, cr1/2, tales-from-the-yawning-portal]
---

**Medium humanoid (human), neutral evil**

**Armor Class** 16 (Barkskin trait)

**Hit Points** 13 (2d8+4)

**Speed** 30 ft.

|   STR   |   DEX   |   CON   |   INT   |   WIS   |   CHA   |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 11 (0) | 13 (+1) | 14 (+2) | 16 (+3) | 14 (+2) | 9 (-1) |

**Skills** Arcana +5, Insight +4, Persuasion + 1

**Languages** Common, Draconic, Goblin

**Challenge** 1/2 (100 XP)

***Source.*** tales from the yawning portal,  page 242

***Barkskin.*** Sharwyn's AC can't be lower than 16.

***Special Equipment.*** Sharwyn has a spell book that contains the spells listed in her Spellcasting trait, plus detect magic and silent image.

***Spellcasting.*** Sharwyn is a 1st-level spellcaster. Her spellcasting ability is Intelligence (spell save DC 13, +5 to hit with spell attacks). She has the following wizard spells prepared:

Cantrips (at will): light, prestidigitation, ray of frost

1st level (2 slots): color spray, magic missile, shield, sleep.

***Tree Thrall.*** If the Gulthias Tree dies, Sharwyn dies 24 hours later.

**Actions**

***Dagger.*** Melee Weapon Attack: +4 to hit, reach 5 ft., one target. Hit: 4 (1d4 + 2) piercing damage.


text:
FROM alpine:3.6
MAINTAINER SalmiRnD <https://salmi.com.se>

COPY \
  patch_reverse_proxy \
  patch_portal_mustache_1 \
  patch_portal_mustache_2 \
  patch_synology.sh /

# "/spksrc", Should point to same folder that you pointed to in nginx_build/Dockerfile
# "/rc.sysv", Should pont to /usr/syno/etc.defaults/rc.sysv/ on host
# "/mustache", Should point to /usr/syno/share/nginx/ on host
# "/host/bin", Should point to /usr/bin/ on host
# "/etc_nginx", Should point to /etc/nginx/ on host
VOLUME ["/spksrc", "/rc.sysv", "/mustache", "/host/bin", "/etc_nginx"]

ENTRYPOINT ["/patch_synology.sh"]


text:
%-----------------------------------------------------------------------------
%
%               Template for sigplanconf LaTeX Class
%
% Name:         sigplanconf-template.tex
%
% Purpose:      A template for sigplanconf.cls, which is a LaTeX 2e class
%               file for SIGPLAN conference proceedings.
%
% Guide:        Refer to "Author's Guide to the ACM SIGPLAN Class,"
%               sigplanconf-guide.pdf
%
% Author:       Paul C. Anagnostopoulos
%               Windfall Software
%               978 371-2316
%               paul@windfall.com
%
% Created:      15 February 2005
%
%-----------------------------------------------------------------------------

\documentclass{sigplanconf}

% The following \documentclass options may be useful:

% preprint      Remove this option only once the paper is in final form.
% 10pt          To set in 10-point type instead of 9-point.
% 11pt          To set in 11-point type instead of 9-point.
% authoryear    To obtain author/year citation style instead of numeric.

\usepackage{amsmath}

\begin{document}

\special{papersize=8.5in,11in}
\setlength{\pdfpageheight}{\paperheight}
\setlength{\pdfpagewidth}{\paperwidth}

\conferenceinfo{CONF 'yy}{Month d--d, 20yy, City, ST, Country}
\copyrightyear{20yy}
\copyrightdata{978-1-nnnn-nnnn-n/yy/mm}
\doi{nnnnnnn.nnnnnnn}

% Uncomment one of the following two, if you are not going for the
% traditional copyright transfer agreement.

%\exclusivelicense                % ACM gets exclusive license to publish,
                                  % you retain copyright

%\permissiontopublish             % ACM gets nonexclusive license to publish
                                  % (paid open-access papers,
                                  % short abstracts)

\titlebanner{banner above paper title}        % These are ignored unless
\preprintfooter{short description of paper}   % 'preprint' option specified.

\title{Title Text}
\subtitle{Subtitle Text, if any}

\authorinfo{Name1}
           {Affiliation1}
           {Email1}
\authorinfo{Name2\and Name3}
           {Affiliation2/3}
           {Email2/3}

\maketitle

\begin{abstract}
This is the text of the abstract.
\end{abstract}

\category{CR-number}{subcategory}{third-level}

% general terms are not compulsory anymore,
% you may leave them out
\terms
term1, term2

\keywords
keyword1, keyword2

\section{Introduction}

The text of the paper begins here.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

More text.

Lots of text.

\appendix
\section{Appendix Title}

This is the text of the appendix, if you need one.

\acks

Acknowledgments, if needed.

% We recommend abbrvnat bibliography style.

\bibliographystyle{abbrvnat}

% The bibliography should be embedded for final submission.

\begin{thebibliography}{}
\softraggedright

\bibitem[Smith et~al.(2009)Smith, Jones]{smith02}
P. Q. Smith, and X. Y. Jones. ...reference text...

\end{thebibliography}

\end{document}

%                       Revision History
%                       -------- -------
%  Date         Person  Ver.    Change
%  ----         ------  ----    ------

%  2013.06.29   TU      0.1--4  comments on permission/copyright notices


text:
module HonestRenter
  class PetType < BaseModel
    ATTRIBUTES = [
      :id,
      :label
    ].freeze

    attr_accessor *ATTRIBUTES

    include Unrequestable

    class << self
      def attr_name
        'pet_types'
      end
    end
  end
end


text:
Indent Respectful Sort is a Sublime Text plugin that provides sort functionality while respecting the block structure defined by indendation.

You may find this plugin useful when you have a consistently indented (all tabs or all 4 spaces etc.) file and would like to sort logical blocks (methods, classes or unordered lists) while maintaining inner structure of the blocks.

Note that this approach would only work in cases where indentation is not only present for readability but also for **dictating** the structure.

# Usage
## Using predefined commands
Open command palette by typing `Ctrl + Shift + P` and start typing `IndentRespectulSort` to use one of the predefined sort options.

As an example, running **Indent Respectful Sort: Indented by 2 Spaces & Max Depth = 2** command on the below snippet

    First Level Item 5
      Second Level Item 2
      Second Level Item 3
      Second Level Item 1
        Third Level Item 3
        Third Level Item 1
        Third Level Item 2
    First Level Item 2
      Second Level Item 2
        Third Level Item 2
        Third Level Item 1
      Second Level Item 1

would yield the following.

    First Level Item 2
      Second Level Item 1
      Second Level Item 2
        Third Level Item 2
        Third Level Item 1
    First Level Item 5
      Second Level Item 1
        Third Level Item 3
        Third Level Item 1
        Third Level Item 2
      Second Level Item 2
      Second Level Item 3

## Running a custom sort command
You may run `IndentRespectfulSort` directly from the console if you need custom sort options.

1.  Open the Python console by pressing ``Ctrl+` `` or by selecting View | Show Console in the menu.
2.  Type `view.run_command("indent_respectful_sort")` and hit `Enter` to run `IndentRespectfulSort` with default options (tab delimited).
3.  You may specify arguments in the second parameter of the run command. Eg. `view.run_command("indent_respectful_sort", {"indent": "  ", "maxDepth": 2})`

### Args
- *maxDepth*: Do not sort blocks beyond levels specified by this argument. (default: unlimited)
- *onlyDepth*: Only sort the blocks in the level specified by this argument. If *onlyDepth* is specified, then *maxDepth* is ignored. (default: None)
- *indent*: Specify the indentation used in this file. (default: "\t")

# Installation
## Using Package Control
IndentRespectfulSort can easily be installed via Package Control.

1. Make sure Package Control is installed. (See https://packagecontrol.io/installation).
2. Press `ctrl + shift + p `(Win, Linux) or `cmd + shift + p` (OSX) to open command palette. Find and select `Package Control : Install Package` and hit `Enter`.
3. In the newly opened panel, start typing `IndentRespectfulSort` and hit `Enter` after you have found and selected.
4. Done!

## Manual Installation
1. Create a folder named `IndentRespectfulSort` in the sublime packages folder.
2. Simply extract the contents of this repository into the newly created `IndentRespectfulSort` folder.


text:
package org.openqa.selenium.remote.server.handler;

import org.openqa.selenium.remote.server.Session;

public class ClearElement extends WebElementHandler<Void> {

  public ClearElement(Session session) {
    super(session);
  }

  @Override
  public Void call() throws Exception {
    getElement().clear();
    return null;
  }

  @Override
  public String toString() {
    return String.format("[clear: %s]", getElementAsString());
  }
}


text:
package moneybird

import (
	"net/http"
	"strings"
	"testing"
)

func TestClientBaseURL(t *testing.T) {
	c := &Client{
		AdministrationID: "administration-id",
	}

	if u := c.resourceURL("contacts"); !strings.HasSuffix(u, "administration-id/contacts") {
		t.Errorf("Resource URL does not include administration ID. Got %#v", u)
	}
}

func TestNewRequest(t *testing.T) {
	var req *http.Request

	client := &Client{
		AdministrationID: "administration-id",
		Token:            "token",
	}

	req, _ = client.newRequest("POST", "contacts", nil)
	if h := req.Header.Get("Authorization"); h != "Bearer token" {
		t.Errorf("Expected header %#v, got %#v", "Bearer token", h)
	}

	expected := "application/json"
	if h := req.Header.Get("Content-Type"); h != expected {
		t.Errorf("Expected header %#v, got %#v", expected, h)
	}

}


text:
public class NodeConfig {

	public static final String REQUEST="REQUEST";
	public static final String LOCKED="LOCKED";
	public static final String RELEASE="RELEASE";
	public static final String RELINQUISH="RELINQUISH";
	public static final String FAILED="FAILED";
	public static final String INQUIRE="INQUIRE";

	public static String getclienthostname(int NodeID){
		String hostname="";

		if(NodeID==1){

			//hostname="net01.utdallas.edu";
			hostname="localhost";

		}else if(NodeID==2){

			//hostname="net02.utdallas.edu";
			hostname="localhost";

		}else if(NodeID==3){

			//hostname="net03.utdallas.edu";
			hostname="localhost";

		} else if(NodeID==4){

			//hostname="net04.utdallas.edu";
			hostname="localhost";

		}else if(NodeID==5){
			//hostname="net05.utdallas.edu";
			hostname="localhost";
		}else if(NodeID==6){
			//hostname="net06.utdallas.edu";
			hostname="localhost";

		}else if(NodeID==7){
			//hostname="net07.utdallas.edu";
			hostname="localhost";

		}

		return hostname;
	}

	public static int getClientport(int clientNodeID2 ){
		int portnum=0;

		if(clientNodeID2==1){
			portnum=2000;

		}else if(clientNodeID2==2){
			portnum=2011;

		}else if(clientNodeID2==3){
			portnum=2022;

		}else if(clientNodeID2==4){
			portnum=2033;

		}else if(clientNodeID2==5){
			portnum=2044;

		}else if(clientNodeID2==6){
			portnum=2055;

		}else if(clientNodeID2==7){
			portnum=2066;
		}

		return portnum;
	}

}


text:
import Axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

import {
    BOARD_LIST_REQUESTED,
    BOARD_LIST_LOADED,
} from '../../types';

import {
  fetchBoardList
} from '..';

const mock = new MockAdapter(Axios)
mock.onAny('/api').reply(200);

const dispatch = expect.createSpy();

const provider = "4chan"

export default createSuite('BoardList', () => {

  // it('creates BOARD_LIST_REQUESTED', () => {
  //   const fn = fetchBoardList(provider);
  //   expect(fn).toBeA('function');
  //   const getState = () => ({ boardList: { items: {}, didInvalidate: null } });

  //   fn(dispatch, getState);
  //   expect(dispatch).toHaveBeenCalledWith({ type: BOARD_LIST_REQUESTED });

  //   // expect(dispatch).toHaveBeenCalledWith({ type: BOARD_LIST_REQUESTED });
  // });

  // it('creates BOARD_REQUESTED action', () => {
  //   const fn = fetchBoard({ provider: '4chan' });
  //   expect(fn).toBeA('function');
  //   const dispatch = expect.createSpy();
  //   const getState = () => ({ provider: '4chan' });
  //   fn(dispatch, getState);
  //   expect(dispatch).toHaveBeenCalledWith({ type: BOARD_LIST_REQUESTED });
  // });

  // it('creates STOP_LOADING action', () => {
  //   expect(stopLoading()).toEqual({
  //     type: STOP_LOADING
  //   });
  // });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus leptospermi F. Muell.

### Remarks
null


text:
Imports System.Net

Public Class updatefeed
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        CheckForUpdates()
    End Sub
    Public Sub CheckForUpdates()
        Dim ws As New WebClient
        Dim newestversion = ws.DownloadString("http://modjokergaming.tk/ComputerHelper/Version/")
        Dim request As HttpWebRequest = WebRequest.Create("http://modjokergaming.tk/Computer%20Helper/UpdateFeed/")
        Dim response As HttpWebResponse = request.GetResponse()
        Dim sr As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
        RichTextBox1.Text = newestversion
    End Sub

    Private Sub updatefeed_Load(sender As Object, e As EventArgs) Handles Me.Load
        CheckForUpdates()
    End Sub

    Private Sub HuraButton1_Click(sender As Object, e As EventArgs) Handles HuraButton1.Click
        Close()
    End Sub

    Private Sub HuraButton2_Click(sender As Object, e As EventArgs) Handles HuraButton2.Click
        WindowState = FormWindowState.Minimized
    End Sub

    Private Sub HuraForm1_Click(sender As Object, e As EventArgs) Handles HuraForm1.Click

    End Sub
End Class


text:
layout: default
description: This is an introduction to ArangoDB's interface for indexes in general
---
Handling Indexes
================

This is an introduction to ArangoDB's interface for indexes in general.
There are special sections for

- [Index Basics](indexing-index-basics.html): Introduction to all index types
- [Which index to use when](indexing-which-index.html): Index type and options adviser
- [Index Utilization](indexing-index-utilization.html): How ArangoDB uses indexes
- [Working with Indexes](indexing-working-with-indexes.html): How to handle indexes
  programmatically using the `db` object
  - [Persistent Indexes](indexing-persistent.html)
  - [Inverted Indexes](indexing-inverted.html)
  - [TTL Indexes](indexing-ttl.html)
  - [Fulltext Indexes](indexing-fulltext.html)
  - [Multi-dimensional Indexes](indexing-multi-dim.html)
  - [Geo-spatial Indexes](indexing-geo.html)
  - [Vertex-centric Indexes](indexing-vertex-centric.html)
- [ArangoSearch](arangosearch.html): How to use Views, Analyzers, and search functions.


text:
export BOWTIE2_INDEXES=/home3/redwards/phage/crAssphage/

# read a line
FQ=$(head -n $SGE_TASK_ID fastq_paired_files.txt | tail -n 1)

# echo  the ID to stderr, so that we know what the fastq file was if there is any bowtie output to stderr
>&2 echo $FQ

# the revised fastq_pairs.py prints out the complete line we need so we don't need to split on spaces any more
# this allows it to correct for uneven lengthed fastq files

# split this on spaces. The second option will be a filename
IFS=' ' read -r -a ARRAY <<< $FQ

OUT=$(echo ${ARRAY[1]} | sed -e 's/.clean//; s/.unique//; s/.fastq.gz//; s/.fastq$//; s/fastq/crassphage/;  s/_[0-9]\+$//')
>&2 echo "OUTPUT TO $OUT.sam"

if [ ! -e $OUT.sam ]; then
	$HOME/bin/bowtie/current/bowtie2 -q -x JQ995537 --no-unal $FQ -S $OUT.sam
else
	echo "Not overwriting $OUT.sam";
fi;

# If the file is over 1000 bytes it has something interesting. Convert it to a bam file and index it
FILESIZE=$(wc -c <"$OUT.sam")
if [ "$FILESIZE" -gt "1000" ]; then
 	$HOME/bin/samtools/samtools-1.2/samtools view -bS $OUT.sam | $HOME/bin/samtools/samtools-1.2/samtools sort - $OUT;
 	$HOME/bin/samtools/samtools-1.2/samtools index $OUT.bam;
fi


text:
"""
Folium Tests
-------

"""
import pytest

import os
import json
try:
    from unittest import mock
except ImportError:
    import mock
import pandas as pd
import jinja2
from jinja2 import Environment, PackageLoader
import vincent
import folium
import base64

from branca.six import PY3
from branca.colormap import ColorMap
import branca.element

from folium.map import Popup, Marker, FitBounds, FeatureGroup
from folium.features import GeoJson, TopoJson, PolyLine, MultiPolyLine
from folium.plugins import ImageOverlay

rootpath = os.path.abspath(os.path.dirname(__file__))

def setup_data():
    """Import economic data for testing."""
    with open(os.path.join(rootpath, 'us-counties.json'), 'r') as f:
        get_id = json.load(f)

    county_codes = [x['id'] for x in get_id['features']]
    county_df = pd.DataFrame({'FIPS_Code': county_codes}, dtype=str)

    # Read into Dataframe, cast to string for consistency.
    df = pd.read_csv(os.path.join(rootpath, 'us_county_data.csv'),
                     na_values=[' '])
    df['FIPS_Code'] = df['FIPS_Code'].astype(str)

    # Perform an inner join, pad NA's with data from nearest county.
    merged = pd.merge(df, county_df, on='FIPS_Code', how='inner')
    return merged.fillna(method='pad')

def test_get_templates():
    """Test template getting."""

    env = branca.utilities.get_templates()
    assert isinstance(env, jinja2.environment.Environment)

class TestFolium(object):
    """Test class for the Folium library."""

    def setup(self):
        """Setup Folium Map."""
        with mock.patch('branca.element.uuid4') as uuid4:
            uuid4().hex = '0' * 32
            self.map = folium.Map(location=[45.5236, -122.6750], width=900,
                                  height=400, max_zoom=20, zoom_start=4)
        self.env = Environment(loader=PackageLoader('folium', 'templates'))

    def test_init(self):
        """Test map initialization."""

        assert self.map.get_name() == 'map_00000000000000000000000000000000'
        assert self.map.get_root() == self.map._parent
        assert self.map.location == [45.5236, -122.6750]
        assert self.map.zoom_start == 4
        assert self.map.max_lat == 90
        assert self.map.min_lat == -90
        assert self.map.max_lon == 180
        assert self.map.min_lon == -180
        assert self.map.position == 'relative'
        assert self.map.height == (400, 'px')
        assert self.map.width == (900, 'px')
        assert self.map.left == (0, '%')
        assert self.map.top == (0, '%')
        assert self.map.to_dict() == {
            "name": "Map",
            "id": "00000000000000000000000000000000",
            "children": {
                "openstreetmap": {
                    "name": "TileLayer",
                    "id": "00000000000000000000000000000000",
                    "children": {}
                    }
                }
            }

    def test_cloudmade(self):
        """Test cloudmade tiles and the API key."""
        with pytest.raises(ValueError):
            folium.Map(location=[45.5236, -122.6750], tiles='cloudmade')

        map = folium.Map(location=[45.5236, -122.6750], tiles='cloudmade',
                         API_key='###')
        cloudmade = 'http://{s}.tile.cloudmade.com/###/997/256/{z}/{x}/{y}.png'
        assert map._children['cloudmade'].tiles == cloudmade

        bounds = map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_builtin_tile(self):
        """Test custom maptiles."""

        default_tiles = ['OpenStreetMap', 'Stamen Terrain', 'Stamen Toner']
        for tiles in default_tiles:
            map = folium.Map(location=[45.5236, -122.6750], tiles=tiles)
            tiles = ''.join(tiles.lower().strip().split())
            url = 'tiles/{}/tiles.txt'.format
            attr = 'tiles/{}/attr.txt'.format
            url = map._env.get_template(url(tiles)).render()
            attr = map._env.get_template(attr(tiles)).render()

            assert map._children[tiles].tiles == url
            assert map._children[tiles].attr == attr

        bounds = map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_custom_tile(self):
        """Test custom tile URLs."""

        url = 'http://{s}.custom_tiles.org/{z}/{x}/{y}.png'
        attr = 'Attribution for custom tiles'

        with pytest.raises(ValueError):
            folium.Map(location=[45.5236, -122.6750], tiles=url)

        map = folium.Map(location=[45.52, -122.67], tiles=url, attr=attr)
        assert map._children[url].tiles == url
        assert map._children[url].attr == attr

        bounds = map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_feature_group(self):
        """Test FeatureGroup."""

        map = folium.Map()
        feature_group = FeatureGroup()
        feature_group.add_child(Marker([45, -30], popup=Popup('-30')))
        feature_group.add_child(Marker([45, 30], popup=Popup('30')))
        map.add_child(feature_group)
        map.add_child(folium.map.LayerControl())

        map._repr_html_()

        bounds = map.get_bounds()
        assert bounds == [[45, -30], [45, 30]], bounds

    def test_simple_marker(self):
        """Test simple marker addition."""

        self.map = folium.Map(location=[44, -73], zoom_start=3)
        mark_templ = self.env.get_template('simple_marker.js')
        popup_templ = self.env.get_template('simple_popup.js')

        # Single Simple marker.
        self.map.simple_marker(location=[45.50, -122.7])
        marker_1 = list(self.map._children.values())[-1]
        mark_1 = mark_templ.render({'marker': marker_1.get_name(),
                                    'lat': 45.50,
                                    'lon': -122.7,
                                    'icon': "{icon:new L.Icon.Default()}"})
        assert (''.join(mark_1.split())[:-1] in
                ''.join(self.map.get_root().render().split()))

        bounds = self.map.get_bounds()
        assert bounds == [[45.5, -122.7], [45.5, -122.7]], bounds

        # Test Simple marker addition.
        self.map.simple_marker(location=[45.60, -122.8], popup='Hi')
        marker_2 = list(self.map._children.values())[-1]
        popup_2 = list(marker_2._children.values())[-1]
        html_2 = list(popup_2.html._children.values())[0]
        mark_2 = mark_templ.render({'marker': marker_2.get_name(),
                                    'lat': 45.60,
                                    'lon': -122.8,
                                    'icon': "{icon:new L.Icon.Default()}"})
        pop_2 = popup_templ.render({'pop_name': popup_2.get_name(),
                                    'pop_txt': 'Hi',
                                    'html_name': html_2.get_name(),
                                    'width': 300})
        # assert self.map.mark_cnt['simple'] == 2
        assert (''.join(mark_2.split())[:-1] in
                ''.join(self.map.get_root().render().split()))
        assert (''.join(pop_2.split())[:-1] in
                ''.join(self.map.get_root().render().split()))
        # assert self.map.template_vars['custom_markers'][1][2] == pop_2

        # Test no popup.
        self.map.simple_marker(location=[45.60, -122.8])
        for child in list(self.map._children.values())[-1]._children.values():
            assert not isinstance(child, Popup)

        bounds = self.map.get_bounds()
        assert bounds == [[45.5, -122.8], [45.6, -122.7]], bounds

    def test_circle_marker(self):
        """Test circle marker additions."""

        self.map = folium.Map(location=[45.60, -122.8])
        circ_templ = self.env.get_template('circle_marker.js')

        # Single Circle marker.
        marker = folium.features.CircleMarker([45.60, -122.8], popup='Hi')
        self.map.add_child(marker)
        circle_1 = circ_templ.render({'circle': marker.get_name(),
                                      'lat': 45.60,
                                      'lon': -122.8, 'radius': 500,
                                      'line_color': 'black',
                                      'fill_color': 'black',
                                      'fill_opacity': 0.6})
        assert (''.join(circle_1.split())[:-1] in
                ''.join(self.map.get_root().render().split()))

        # Second circle marker.
        marker = folium.features.CircleMarker([45.70, -122.9], popup='Hi')
        self.map.add_child(marker)
        circle_2 = circ_templ.render({'circle': marker.get_name(),
                                      'lat': 45.70,
                                      'lon': -122.9, 'radius': 500,
                                      'line_color': 'black',
                                      'fill_color': 'black',
                                      'fill_opacity': 0.6})
        assert (''.join(circle_2.split())[:-1] in
                ''.join(self.map.get_root().render().split()))

        bounds = self.map.get_bounds()
        assert bounds == [[45.6, -122.9], [45.7, -122.8]], bounds

    def test_poly_marker(self):
        """Test polygon marker."""

        self.map = folium.Map(location=[45.5, -122.5])
        poly_temp = self.env.get_template('poly_marker.js')

        self.map.polygon_marker(location=[45.5, -122.5])
        marker = list(self.map._children.values())[-1]
        polygon = poly_temp.render({'marker': marker.get_name(),
                                    'lat': 45.5,
                                    'lon': -122.5,
                                    'line_color': 'black',
                                    'line_opacity': 1,
                                    'line_weight': 2,
                                    'fill_color': 'blue',
                                    'fill_opacity': 1,
                                    'num_sides': 4,
                                    'rotation': 0,
                                    'radius': 15})

        assert ((''.join(polygon.split()))[-1] in
                ''.join(self.map.get_root().render().split()))

        bounds = self.map.get_bounds()
        assert bounds == [[45.5, -122.5], [45.5, -122.5]], bounds

    def test_latlng_pop(self):
        """Test lat/lon popovers."""

        self.map.lat_lng_popover()
        pop = list(self.map._children.values())[-1]
        tmpl = 'lat_lng_popover.js'
        pop_templ = self.env.get_template(tmpl).render(popup=pop.get_name(),
                                                       map=self.map.get_name())
        assert ((''.join(pop_templ.split()))[:-1] in
                ''.join(self.map.get_root().render().split()))

        bounds = self.map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_click_for_marker(self):
        """Test click for marker functionality."""

        # Lat/lon popover.
        self.map = folium.Map([46, 3])
        self.map.click_for_marker()
        click_templ = self.env.get_template('click_for_marker.js')
        click = click_templ.render({'popup': ('"Latitude: " + lat + "
'
                                              'Longitude: " + lng '),
                                    'map': self.map.get_name()})
        assert ((''.join(click.split()))[:-1] in
                ''.join(self.map.get_root().render().split()))

        # Custom popover.
        self.map.click_for_marker(popup='Test')
        click_templ = self.env.get_template('click_for_marker.js')
        click = click_templ.render({'popup': '"Test"',
                                    'map': self.map.get_name()})
        assert ((''.join(click.split()))[:-1] in
                ''.join(self.map.get_root().render().split()))

        bounds = self.map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_vega_popup(self):
        """Test vega popups."""

        self.map = folium.Map([45.60, -122.8])

        vega_templ = self.env.get_template('vega_marker.js')
        vega_parse = self.env.get_template('vega_parse.js')

        vis = vincent.Bar(width=675 - 75, height=350 - 50, no_data=True)
        data = json.loads(vis.to_json())

        self.map.simple_marker(location=[45.60, -122.8],
                               popup=(vis, 'vis.json'))

        marker = list(self.map._children.values())[-1]
        popup = list(marker._children.values())[-1]
        vega = list(popup._children.values())[-1]
        vega_str = vega_templ.render({'vega': vega.get_name(),
                                      'popup': popup.get_name(),
                                      'marker': marker.get_name(),
                                      'vega_json': json.dumps(data),
                                      })
        out = ''.join(self.map.get_root().render().split())
        assert ''.join(vega_parse.render().split()) in out
        assert (''.join(vega_str.split()))[:-1] in out

        bounds = self.map.get_bounds()
        assert bounds == [[45.6, -122.8], [45.6, -122.8]], bounds

    def test_geo_json_simple(self):
        """Test geojson method."""

        # No data binding.
        self.map = folium.Map([43, -100], zoom_start=4)
        path = os.path.join(rootpath, 'us-counties.json')
        self.map.geo_json(geo_path=path)

        self.map._repr_html_()

        bounds = self.map.get_bounds()
        assert bounds == [[18.948267, -171.742517],
                          [71.285909, -66.979601]], bounds

    def test_geo_json_str(self):
        # No data binding.
        self.map = folium.Map([43, -100], zoom_start=4)
        path = os.path.join(rootpath, 'us-counties.json')

        data = json.load(open(path))

        for feature in data['features']:
            feature.setdefault('properties', {}).setdefault('style', {}).update({  # noqa
                'color': 'black',
                'opacity': 1,
                'fillOpacity': 0.6,
                'weight': 1,
                'fillColor': 'blue',
            })

        self.map.geo_json(geo_str=json.dumps(data))

        geo_json = [x for x in self.map._children.values() if
                    isinstance(x, GeoJson)][0]

        out = ''.join(self.map._parent.render().split())

        # Verify the geo_json object
        obj_temp = jinja2.Template("""
            var {{ this.get_name() }} = L.geoJson({{ this.style_data() }})
                .addTo({{ this._parent.get_name() }});
            {{ this.get_name() }}.setStyle(function(feature) {return feature.properties.style;});
                """)
        obj = obj_temp.render(this=geo_json, json=json)
        assert ''.join(obj.split())[:-1] in out

        bounds = self.map.get_bounds()
        assert bounds == [[18.948267, -171.742517],
                          [71.285909, -66.979601]], bounds

    def test_geo_json_bad_color(self):
        """Test geojson method."""

        self.map = folium.Map([43, -100], zoom_start=4)

        path = os.path.join(rootpath, 'us-counties.json')

        # Data binding incorrect color value error.
        data = setup_data()
        with pytest.raises(ValueError):
            self.map.geo_json(path, data=data,
                              columns=['FIPS_Code', 'Unemployed_2011'],
                              key_on='feature.id', fill_color='blue')

        bounds = self.map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_geo_json_bad_threshold_scale(self):
        """Test geojson method."""

        self.map = folium.Map([43, -100], zoom_start=4)

        path = os.path.join(rootpath, 'us-counties.json')

        # Data binding threshold_scale too long.
        data = setup_data()
        with pytest.raises(ValueError):
            self.map.geo_json(path, data=data,
                              columns=['FIPS_Code', 'Unemployed_2011'],
                              key_on='feature.id',
                              threshold_scale=[1, 2, 3, 4, 5, 6, 7],
                              fill_color='YlGnBu')

        bounds = self.map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_geo_json_data_binding(self):
        """Test geojson method."""
        data = setup_data()

        self.map = folium.Map([43, -100], zoom_start=4)

        path = os.path.join(rootpath, 'us-counties.json')

        # With DataFrame data binding, default threshold scale.
        self.map.choropleth(geo_path=path, data=data,
                            threshold_scale=[4.0, 1000.0, 3000.0,
                                             5000.0, 9000.0],
                            columns=['FIPS_Code', 'Unemployed_2011'],
                            key_on='feature.id', fill_color='YlGnBu',
                            reset=True)

        out = self.map._parent.render()

        # Verify the colorscale
        domain = [4.0, 1000.0, 3000.0, 5000.0, 9000.0]
        palette = branca.utilities.color_brewer('YlGnBu')
        d3range = palette[0: len(domain) + 2]
        colorscale_obj = [val for key, val in self.map._children.items() if
                          isinstance(val, ColorMap)][0]
        colorscale_temp = self.env.get_template('color_scale.js')
        colorscale = colorscale_temp.render({
            'this': colorscale_obj,
            'domain': domain,
            'range': d3range})
        assert ''.join(colorscale.split())[:-1] in ''.join(out.split())

        bounds = self.map.get_bounds()
        assert bounds == [[18.948267, -171.742517],
                          [71.285909, -66.979601]], bounds

    def test_topo_json(self):
        """Test topojson method."""

        self.map = folium.Map([43, -100], zoom_start=4)

        # Adding TopoJSON as additional layer.
        path = os.path.join(rootpath, 'or_counties_topo.json')
        self.map.geo_json(geo_path=path, topojson='objects.or_counties_geo')

        out = self.map._parent.render()

        # Verify TopoJson
        topo_json = [val for key, val in self.map._children.items()
                     if isinstance(val, TopoJson)][0]
        topojson_str = topo_json._template.module.script(topo_json)
        assert ''.join(topojson_str.split())[:-1] in ''.join(out.split())

        bounds = self.map.get_bounds()
        assert bounds == [[41.99187135900012, -124.56617536999985],
                          [46.28768217800006, -116.46422312599977]], bounds

    def test_topo_json_smooth_factor(self):
        """Test topojson smooth factor method."""
        self.map = folium.Map([43, -100], zoom_start=4)

        # Adding TopoJSON as additional layer.
        path = os.path.join(rootpath, 'or_counties_topo.json')
        self.map.choropleth(geo_path=path,
                            topojson='objects.or_counties_geo',
                            smooth_factor=0.5)

        out = self.map._parent.render()

        # Verify TopoJson
        topo_json = [val for key, val in self.map._children.items()
                     if isinstance(val, TopoJson)][0]
        topojson_str = topo_json._template.module.script(topo_json)
        assert ''.join(topojson_str.split())[:-1] in ''.join(out.split())

    def test_map_build(self):
        """Test map build."""

        # Standard map.
        self.setup()
        out = self.map._parent.render()
        html_templ = self.env.get_template('fol_template.html')
        attr = ('Data by OpenStreetMap'
                ',under '
                'ODbL.')
        tile_layers = [
            {'id': 'tile_layer_'+'0'*32,
             'address': 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
             'attr': attr,
             'max_zoom': 20,
             'min_zoom': 1,
             'detect_retina': False,
             }]
        tmpl = {'map_id': 'map_' + '0' * 32,
                'lat': 45.5236, 'lon': -122.675,
                'size': 'width: 900.0px; height: 400.0px;',
                'zoom_level': 4,
                'min_lat': -90,
                'max_lat': 90,
                'min_lon': -180,
                'max_lon': 180,
                'tile_layers': tile_layers,
                'crs': 'EPSG3857',
                }
        HTML = html_templ.render(tmpl, plugins={})

        assert ''.join(out.split()) == ''.join(HTML.split())

    def test_tile_attr_unicode(self):
        """Test tile attribution unicode

        Test not cover b'юникод'
        because for python 3 bytes can only contain ASCII literal characters.
        """

        if not PY3:
            map = folium.Map(location=[45.5236, -122.6750],
                             tiles='test', attr=b'unicode')
            map._parent.render()
        else:
            map = folium.Map(location=[45.5236, -122.6750],
                             tiles='test', attr=u'юникод')
            map._parent.render()
        map = folium.Map(location=[45.5236, -122.6750],
                         tiles='test', attr='юникод')
        map._parent.render()

    def test_create_map(self):
        """Test create map."""

        map = folium.Map(location=[45.5236, -122.6750],
                         tiles='test', attr='юникод')

        # Add json data.
        path = os.path.join(rootpath, 'us-counties.json')
        data = setup_data()
        map.geo_json(geo_path=path, data=data,
                     columns=['FIPS_Code', 'Unemployed_2011'],
                     key_on='feature.id', fill_color='YlGnBu',
                     reset=True)

        # Add plugins.
        map.polygon_marker(location=[45.5, -122.5])

        # Test write.
        map._parent.render()
        map.save('map.html')

    def test_line(self):
        """Test line."""

        line_temp = self.env.get_template('polyline.js')

        line_opts = {
            'color': 'blue',
            'weight': 2,
            'opacity': 1
        }
        locations = [
            [[45.5236, -122.6750], [45.5236, -122.6751]],
            [[45.5237, -122.6750], [45.5237, -122.6751]],
            [[45.5238, -122.6750], [45.5238, -122.6751]]
        ]

        self.setup()
        self.map.line(locations=locations,
                      line_color=line_opts['color'],
                      line_weight=line_opts['weight'],
                      line_opacity=line_opts['opacity'])
        polyline = [val for key, val in self.map._children.items()
                    if isinstance(val, PolyLine)][0]
        out = self.map._parent.render()

        line_rendered = line_temp.render({'line': 'line_1',
                                          'this': polyline,
                                          'locations': locations,
                                          'options': line_opts})

        assert ''.join(line_rendered.split()) in ''.join(out.split())

        bounds = self.map.get_bounds()
        assert bounds == [[45.5236, -122.6751], [45.5238, -122.675]], bounds

    def test_multi_polyline(self):
        """Test multi_polyline."""

        multiline_temp = self.env.get_template('multi_polyline.js')

        multiline_opts = {'color': 'blue',
                          'weight': 2,
                          'opacity': 1}
        locations = [[[45.5236, -122.6750], [45.5236, -122.6751]],
                     [[45.5237, -122.6750], [45.5237, -122.6751]],
                     [[45.5238, -122.6750], [45.5238, -122.6751]]]

        self.setup()
        self.map.multiline(locations=locations,
                           line_color=multiline_opts['color'],
                           line_weight=multiline_opts['weight'],
                           line_opacity=multiline_opts['opacity'])
        multipolyline = [val for key, val in self.map._children.items()
                         if isinstance(val, MultiPolyLine)][0]
        out = self.map._parent.render()

        multiline_rendered = multiline_temp.render({'multiline': 'multiline_1',
                                                    'this': multipolyline,
                                                    'locations': locations,
                                                    'options': multiline_opts})

        assert ''.join(multiline_rendered.split()) in ''.join(out.split())

        bounds = self.map.get_bounds()
        assert bounds == [[45.5236, -122.6751], [45.5238, -122.675]], bounds

    def test_fit_bounds(self):
        """Test fit_bounds."""
        bounds = ((52.193636, -2.221575), (52.636878, -1.139759))

        self.setup()
        self.map.fit_bounds(bounds)
        fitbounds = [val for key, val in self.map._children.items() if
                     isinstance(val, FitBounds)][0]
        out = self.map._parent.render()

        fit_bounds_tpl = self.env.get_template('fit_bounds.js')
        fit_bounds_rendered = fit_bounds_tpl.render({
            'bounds': json.dumps(bounds),
            'this': fitbounds,
            'fit_bounds_options': {}, })

        assert ''.join(fit_bounds_rendered.split()) in ''.join(out.split())

        self.setup()
        self.map.fit_bounds(bounds, max_zoom=15, padding=(3, 3))
        fitbounds = [val for key, val in self.map._children.items() if
                     isinstance(val, FitBounds)][0]
        out = self.map._parent.render()

        fit_bounds_tpl = self.env.get_template('fit_bounds.js')
        fit_bounds_rendered = fit_bounds_tpl.render({
            'bounds': json.dumps(bounds),
            'fit_bounds_options': json.dumps({'maxZoom': 15,
                                              'padding': (3, 3), },
                                             sort_keys=True),
            'this': fitbounds,
            })

        assert ''.join(fit_bounds_rendered.split()) in ''.join(out.split())

        bounds = self.map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds

    def test_image_overlay(self):
        """Test image overlay."""
        # from numpy.random import random
        from branca.utilities import write_png
        # import base64

        data = [[[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]],
                [[1, 1, 0, 0.5], [0, 0, 1, 1], [0, 0, 1, 1]]]
        min_lon, max_lon, min_lat, max_lat = -90.0, 90.0, -180.0, 180.0

        self.setup()
        image_url = 'data.png'
        self.map.image_overlay(data, filename=image_url)
        out = self.map._parent.render()

        imageoverlay = [val for key, val in self.map._children.items() if
                        isinstance(val, ImageOverlay)][0]

        png_str = write_png(data)
        # with open('data.png', 'wb') as f:
        #    f.write(png_str)
        png = "data:image/png;base64,{}".format
        inline_image_url = png(base64.b64encode(png_str).decode('utf-8'))

        image_tpl = self.env.get_template('image_layer.js')
        image_name = 'Image_Overlay'
        image_opacity = 0.25
        image_bounds = [[min_lon, min_lat], [max_lon, max_lat]]

        image_rendered = image_tpl.render({'image_name': image_name,
                                           'this': imageoverlay,
                                           'image_url': image_url,
                                           'image_bounds': image_bounds,
                                           'image_opacity': image_opacity})

        assert ''.join(image_rendered.split()) in ''.join(out.split())

        self.setup()
        self.map.image_overlay(data, mercator_project=True)
        out = self.map._parent.render()

        imageoverlay = [val for key, val in self.map._children.items() if
                        isinstance(val, ImageOverlay)][0]

        image_rendered = image_tpl.render({'image_name': image_name,
                                           'this': imageoverlay,
                                           'image_url': inline_image_url,
                                           'image_bounds': image_bounds,
                                           'image_opacity': image_opacity})

        assert ''.join(image_rendered.split()) in ''.join(out.split())

        bounds = self.map.get_bounds()
        assert bounds == [[-90.0, -180.0], [90.0, 180.0]], bounds

    def test_custom_icon(self):
        """Test CustomIcon."""
        self.setup()

        icon_image = "http://leafletjs.com/docs/images/leaf-green.png"
        shadow_image = "http://leafletjs.com/docs/images/leaf-shadow.png"

        self.map = folium.Map([45, -100], zoom_start=4)
        i = folium.features.CustomIcon(icon_image,
                                       icon_size=(38, 95),
                                       icon_anchor=(22, 94),
                                       shadow_image=shadow_image,
                                       shadow_size=(50, 64),
                                       shadow_anchor=(4, 62),
                                       popup_anchor=(-3, -76),)
        mk = folium.map.Marker([45, -100], icon=i,
                               popup=folium.map.Popup('Hello'))
        self.map.add_child(mk)
        self.map._parent.render()

        bounds = self.map.get_bounds()
        assert bounds == [[45, -100], [45, -100]], bounds

    def test_tile_layer(self):
        mapa = folium.Map([48., 5.], tiles='stamentoner', zoom_start=6)
        layer = 'http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png'
        mapa.add_child(folium.map.TileLayer(layer, name='MapQuest',
                                            attr='attribution'))
        mapa.add_child(folium.map.TileLayer(layer,
                                            name='MapQuest2',
                                            attr='attribution2',
                                            overlay=True))
        mapa.add_child(folium.map.LayerControl())
        mapa._repr_html_()

        bounds = self.map.get_bounds()
        assert bounds == [[None, None], [None, None]], bounds


text:
{% extends 'index.html' %}

{% block content %}

    {{ form.begin(request.route_url('add_message', name=topic)) }}

        {{ form.errorlist("title") }}
        {{ form.label("title") }}
        {{ form.text('title') }}

        {{ form.errorlist("author") }}
        {{ form.label("author") }}
        {{ form.text('author') }}

        {{ form.errorlist("content") }}
        {{ form.label("content") }}
        {{ form.textarea('content') }}

    <button class='btn btn-primary'>Send Message</button>
    Back Messages
    {{ form.end() }}
{% endblock %}


text:
"""This module adds shared support for generic Amazon AWS modules

**This code is not yet ready for use in user modules.  As of 2017**
**and through to 2018, the interface is likely to change**
**aggressively as the exact correct interface for ansible AWS modules**
**is identified.  In particular, until this notice goes away or is**
**changed, methods may disappear from the interface.  Please don't**
**publish modules using this except directly to the main Ansible**
**development repository.**

In order to use this module, include it as part of a custom
module as shown below.

  from ansible.module_utils.aws import AnsibleAWSModule
  module = AnsibleAWSModule(argument_spec=dictionary, supports_check_mode=boolean
                            mutually_exclusive=list1, required_together=list2)

The 'AnsibleAWSModule' module provides similar, but more restricted,
interfaces to the normal Ansible module.  It also includes the
additional methods for connecting to AWS using the standard module arguments

    m.resource('lambda') # - get an AWS connection as a boto3 resource.

or

    m.client('sts') # - get an AWS connection as a boto3 client.

To make use of AWSRetry easier, it can now be wrapped around any call from a
module-created client. To add retries to a client, create a client:

    m.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10))

Any calls from that client can be made to use the decorator passed at call-time
using the `aws_retry` argument. By default, no retries are used.

    ec2 = m.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10))
    ec2.describe_instances(InstanceIds=['i-123456789'], aws_retry=True)

The call will be retried the specified number of times, so the calling functions
don't need to be wrapped in the backoff decorator.

"""

import re
import logging
import traceback
from functools import wraps
from distutils.version import LooseVersion

try:
    from cStringIO import StringIO
except ImportError:
    # Python 3
    from io import StringIO

from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native
from ansible.module_utils.ec2 import HAS_BOTO3, camel_dict_to_snake_dict, ec2_argument_spec, boto3_conn, get_aws_connection_info

# We will also export HAS_BOTO3 so end user modules can use it.
__all__ = ('AnsibleAWSModule', 'HAS_BOTO3', 'is_boto3_error_code')

class AnsibleAWSModule(object):
    """An ansible module class for AWS modules

    AnsibleAWSModule provides an a class for building modules which
    connect to Amazon Web Services.  The interface is currently more
    restricted than the basic module class with the aim that later the
    basic module class can be reduced.  If you find that any key
    feature is missing please contact the author/Ansible AWS team
    (available on #ansible-aws on IRC) to request the additional
    features needed.
    """
    default_settings = {
        "default_args": True,
        "check_boto3": True,
        "auto_retry": True,
        "module_class": AnsibleModule
    }

    def __init__(self, **kwargs):
        local_settings = {}
        for key in AnsibleAWSModule.default_settings:
            try:
                local_settings[key] = kwargs.pop(key)
            except KeyError:
                local_settings[key] = AnsibleAWSModule.default_settings[key]
        self.settings = local_settings

        if local_settings["default_args"]:
            # ec2_argument_spec contains the region so we use that; there's a patch coming which
            # will add it to aws_argument_spec so if that's accepted then later we should change
            # over
            argument_spec_full = ec2_argument_spec()
            try:
                argument_spec_full.update(kwargs["argument_spec"])
            except (TypeError, NameError):
                pass
            kwargs["argument_spec"] = argument_spec_full

        self._module = AnsibleAWSModule.default_settings["module_class"](**kwargs)

        if local_settings["check_boto3"] and not HAS_BOTO3:
            self._module.fail_json(
                msg=missing_required_lib('botocore or boto3'))

        self.check_mode = self._module.check_mode
        self._diff = self._module._diff
        self._name = self._module._name

        self._botocore_endpoint_log_stream = StringIO()
        self.logger = None
        if self.params.get('debug_botocore_endpoint_logs'):
            self.logger = logging.getLogger('botocore.endpoint')
            self.logger.setLevel(logging.DEBUG)
            self.logger.addHandler(logging.StreamHandler(self._botocore_endpoint_log_stream))

    @property
    def params(self):
        return self._module.params

    def _get_resource_action_list(self):
        actions = []
        for ln in self._botocore_endpoint_log_stream.getvalue().split('\n'):
            ln = ln.strip()
            if not ln:
                continue
            found_operational_request = re.search(r"OperationModel\(name=.*?\)", ln)
            if found_operational_request:
                operation_request = found_operational_request.group(0)[20:-1]
                resource = re.search(r"https://.*?\.", ln).group(0)[8:-1]
                actions.append("{0}:{1}".format(resource, operation_request))
        return list(set(actions))

    def exit_json(self, *args, **kwargs):
        if self.params.get('debug_botocore_endpoint_logs'):
            kwargs['resource_actions'] = self._get_resource_action_list()
        return self._module.exit_json(*args, **kwargs)

    def fail_json(self, *args, **kwargs):
        if self.params.get('debug_botocore_endpoint_logs'):
            kwargs['resource_actions'] = self._get_resource_action_list()
        return self._module.fail_json(*args, **kwargs)

    def debug(self, *args, **kwargs):
        return self._module.debug(*args, **kwargs)

    def warn(self, *args, **kwargs):
        return self._module.warn(*args, **kwargs)

    def deprecate(self, *args, **kwargs):
        return self._module.deprecate(*args, **kwargs)

    def boolean(self, *args, **kwargs):
        return self._module.boolean(*args, **kwargs)

    def md5(self, *args, **kwargs):
        return self._module.md5(*args, **kwargs)

    def client(self, service, retry_decorator=None):
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(self, boto3=True)
        conn = boto3_conn(self, conn_type='client', resource=service,
                          region=region, endpoint=ec2_url, **aws_connect_kwargs)
        return conn if retry_decorator is None else _RetryingBotoClientWrapper(conn, retry_decorator)

    def resource(self, service):
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(self, boto3=True)
        return boto3_conn(self, conn_type='resource', resource=service,
                          region=region, endpoint=ec2_url, **aws_connect_kwargs)

    def fail_json_aws(self, exception, msg=None):
        """call fail_json with processed exception

        function for converting exceptions thrown by AWS SDK modules,
        botocore, boto3 and boto, into nice error messages.
        """
        last_traceback = traceback.format_exc()

        # to_native is trusted to handle exceptions that str() could
        # convert to text.
        try:
            except_msg = to_native(exception.message)
        except AttributeError:
            except_msg = to_native(exception)

        if msg is not None:
            message = '{0}: {1}'.format(msg, except_msg)
        else:
            message = except_msg

        try:
            response = exception.response
        except AttributeError:
            response = None

        failure = dict(
            msg=message,
            exception=last_traceback,
            **self._gather_versions()
        )

        if response is not None:
            failure.update(**camel_dict_to_snake_dict(response))

        self.fail_json(**failure)

    def _gather_versions(self):
        """Gather AWS SDK (boto3 and botocore) dependency versions

        Returns {'boto3_version': str, 'botocore_version': str}
        Returns {} if neither are installed
        """
        if not HAS_BOTO3:
            return {}
        import boto3
        import botocore
        return dict(boto3_version=boto3.__version__,
                    botocore_version=botocore.__version__)

    def boto3_at_least(self, desired):
        """Check if the available boto3 version is greater than or equal to a desired version.

        Usage:
            if module.params.get('assign_ipv6_address') and not module.boto3_at_least('1.4.4'):
                # conditionally fail on old boto3 versions if a specific feature is not supported
                module.fail_json(msg="Boto3 can't deal with EC2 IPv6 addresses before version 1.4.4.")
        """
        existing = self._gather_versions()
        return LooseVersion(existing['boto3_version']) >= LooseVersion(desired)

    def botocore_at_least(self, desired):
        """Check if the available botocore version is greater than or equal to a desired version.

        Usage:
            if not module.botocore_at_least('1.2.3'):
                module.fail_json(msg='The Serverless Elastic Load Compute Service is not in botocore before v1.2.3')
            if not module.botocore_at_least('1.5.3'):
                module.warn('Botocore did not include waiters for Service X before 1.5.3. '
                            'To wait until Service X resources are fully available, update botocore.')
        """
        existing = self._gather_versions()
        return LooseVersion(existing['botocore_version']) >= LooseVersion(desired)

class _RetryingBotoClientWrapper(object):
    __never_wait = (
        'get_paginator', 'can_paginate',
        'get_waiter', 'generate_presigned_url',
    )

    def __init__(self, client, retry):
        self.client = client
        self.retry = retry

    def _create_optional_retry_wrapper_function(self, unwrapped):
        retrying_wrapper = self.retry(unwrapped)

        @wraps(unwrapped)
        def deciding_wrapper(aws_retry=False, *args, **kwargs):
            if aws_retry:
                return retrying_wrapper(*args, **kwargs)
            else:
                return unwrapped(*args, **kwargs)
        return deciding_wrapper

    def __getattr__(self, name):
        unwrapped = getattr(self.client, name)
        if name in self.__never_wait:
            return unwrapped
        elif callable(unwrapped):
            wrapped = self._create_optional_retry_wrapper_function(unwrapped)
            setattr(self, name, wrapped)
            return wrapped
        else:
            return unwrapped

def is_boto3_error_code(code, e=None):
    """Check if the botocore exception is raised by a specific error code.

    Returns ClientError if the error code matches, a dummy exception if it does not have an error code or does not match

    Example:
    try:
        ec2.describe_instances(InstanceIds=['potato'])
    except is_boto3_error_code('InvalidInstanceID.Malformed'):
        # handle the error for that code case
    except botocore.exceptions.ClientError as e:
        # handle the generic error case for all other codes
    """
    from botocore.exceptions import ClientError
    if e is None:
        import sys
        dummy, e, dummy = sys.exc_info()
    if isinstance(e, ClientError) and e.response['Error']['Code'] == code:
        return ClientError
    return type('NeverEverRaisedException', (Exception,), {})

def get_boto3_client_method_parameters(client, method_name, required=False):
    op = client.meta.method_to_api_mapping.get(method_name)
    input_shape = client._service_model.operation_model(op).input_shape
    if not input_shape:
        parameters = []
    elif required:
        parameters = list(input_shape.required_members)
    else:
        parameters = list(input_shape.members.keys())
    return parameters


text:
namespace TentsNTrails.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class SentMessagesUpdate : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.Messages", "DeletedSender", c => c.Boolean(nullable: false));
            AddColumn("dbo.Messages", "DeletedRecipient", c => c.Boolean(nullable: false));
        }

        public override void Down()
        {
            DropColumn("dbo.Messages", "DeletedRecipient");
            DropColumn("dbo.Messages", "DeletedSender");
        }
    }
}


text:
<?php

namespace Myproject\Middleware;

use Slim\Middleware;

class BeforeMiddleware extends Middleware
{
    public function call()
    {
        $this->app->hook('slim.before', [$this, 'run']);

        $this->next->call();
    }
    public function run()
    {
        if (isset($_SESSION[$this->app->config->get('auth.session')])) {
            $this->app->auth = $this->app->user->where('id', $_SESSION[$this->app->config->get('auth.session')])->first();
        }

        $this->app->view()->appendData([
            'auth' => $this->app->auth
        ]);
    }
}

?>


text:
/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "experimental"
};

// Add-on SDK
const { Cu, Ci } = require("chrome");
const { Class } = require("sdk/core/heritage");
const Clipboard = require("sdk/clipboard");

// Firebug SDK
const { Locale } = require("firebug.sdk/lib/core/locale.js");
const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);
const { SidePanelBase } = require("firebug.sdk/lib/side-panel-base.js");
const { PanelToolbar } = require("firebug.sdk/lib/panel-toolbar.js");

// Firebug.next
const { Events } = require("../core/events.js");
const { PrettyPrint } = require("./pretty-print.js");

/**
 * This object is responsible for logic related to a command editor (known
 * also as multiline command line). This editor is available in the Console
 * panel and can be used to execute JS code.
 */
const CommandEditor = Class(
/** @lends CommandEditor */
{
  extends: SidePanelBase,

  id: "commandEditor",
  label: Locale.$STR("commandEditor.tab.label"),
  tooltip: Locale.$STR("commandEditor.tab.tip"),
  icon: "./icon-16.png",
  url: "./command-editor/command-editor.html",

  // Initialization

  setup: function({debuggee, frame, toolbox}) {
    SidePanelBase.prototype.setup.apply(this, arguments);

    Trace.sysout("commandEditor.setup;");

    this.onMessage = this.onMessage.bind(this);
    this.onRun = this.onRun.bind(this);

    this.toolbar = new PanelToolbar({parentNode: frame.parentNode });
    this.toolbar.createItems(this.getPanelToolbarButtons());
  },

  onReady: function(options) {
    SidePanelBase.prototype.onReady.apply(this, arguments);

    Trace.sysout("commandEditor.onReady;");

    this.window = XPCNativeWrapper.unwrap(options.window);

    // Setup communication channel with the frame (type == content).
    // The content (panel frame) can send messages to this panel object
    // through 'sendMessage' method. The message are handled by
    // 'onMessage' below.
    Cu.exportFunction(this.onMessage, this.window, {
      defineAs: "sendMessage"
    });
  },

  onMessage: function(event) {
    Trace.sysout("commandEditor.onMessage; From CM " + event, event);

    switch (event.type) {
      case "evaluate":
        this.doRun();
        break;
      case "escape":
        break;
    }
  },

  // Toolbar

  getPanelToolbarButtons: function() {
    let buttons = [];

    // xxxHonza: TESTME (all the commands)
    buttons.push({
      id: "firebug-commandeditor-run",
      label: "commandEditor.run.label",
      tooltiptext: "commandEditor.run.tip",
      command: this.onRun.bind(this)
    });

    buttons.push({
      id: "firebug-commandeditor-clear",
      label: "commandEditor.clear.label",
      tooltiptext: "commandEditor.clear.tip",
      command: this.onClear.bind(this)
    });

    buttons.push({
      id: "firebug-commandeditor-prettyprint",
      label: "commandEditor.prettyPrint.label",
      tooltiptext: "commandEditor.prettyPrint.tip",
      command: this.onPrettyPrint.bind(this)
    });

    buttons.push({
      id: "firebug-commandeditor-copy",
      label: "commandEditor.copy.label",
      tooltiptext: "commandEditor.copy.tip",
      type: "menu-button",
      command: this.onCopy.bind(this),
      items: [{
        id: "firebug-commandeditor-copyas-bookmarklet",
        label: "commandEditor.copyAsBookmarklet.label",
        tooltiptext: "commandEditor.copyAsBookmarklet.tip",
        command: this.onCopyAsBookmarklet.bind(this)
      }],
    });

    return buttons;
  },

  doRun: function() {
    let editor = this.window.editor;
    let selection = editor.getSelection();
    let expression = selection ? selection : editor.getValue();
    this.owner.execute(expression);
  },

  // Command Handlers

  onRun: function() {
    this.doRun();
  },

  onClear: function() {
    this.window.editor.setValue("");
  },

  onCopy: function() {
    let value = this.window.editor.getValue();
    Clipboard.set(value, "text");
  },

  onCopyAsBookmarklet: function(event) {
    // xxxHonza: This needs escaping, and stripNewLines is exactly the
    // wrong thing to do when it comes to JavaScript.
    // (see also the original implementation).
    let value = this.window.editor.getValue();
    let expr = "javascript: " + value.replace(/[\r\n]/gm, " ");
    Clipboard.set(expr, "text");
    Events.cancelEvent(event);
  },

  onPrettyPrint: function() {
    let value = this.window.editor.getValue();
    PrettyPrint.run(value).then(value => {
      this.window.editor.setValue(value);
    });
  },
});

// Exports from this module
exports.CommandEditor = CommandEditor;


text:
package g3

import (
	"os"
	"io"
	"io/ioutil"
	"image"
)

func ReadStringsFromFiles(fileNames ...string) ([]string, os.Error) {
	strings := make([]string, 0)
	for _, fileName := range fileNames {
		str, err := ReadStringFromFile(fileName)
		if err != nil {
			return strings, err
		}
		strings = append(strings, str)
	}
	return strings, nil
}

func ReadStringFromStream(reader io.Reader) (string, os.Error) {
	data, err := ioutil.ReadAll(reader)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

func ReadStringFromFile(fileName string) (string, os.Error) {
	file, err := os.Open(fileName, os.O_RDONLY, 0666)
	if err != nil {
		return "", err
	}
	defer file.Close()
	return ReadStringFromStream(file)
}

// Images

func ReadImagesFromStreams(readers ...io.Reader) ([]image.Image, os.Error) {
	images := make([]image.Image, 0)
	for _, reader := range readers {
		img, _, err := image.Decode(reader)
		if err != nil {
			return images, err
		}
		images = append(images, img)
	}
	return images, nil
}

func ReadImagesFromFiles(fileNames ...string) ([]image.Image, os.Error) {
	images := make([]image.Image, 0, len(fileNames))
	for _, fileName := range fileNames {
		reader, err := os.Open(fileName, os.O_RDONLY, 0666)
		if err != nil {
			return images, err
		}
		defer reader.Close()

		img, _, err := image.Decode(reader)
		if err != nil {
			return images, err
		}
		images = append(images, img)
	}
	return images, nil
}


text:
package ch.raffael.sangria.modules.jmx;

import com.google.inject.AbstractModule;

import ch.raffael.sangria.annotations.Install;

/**
 * @author Raffael Herzog
 */
@Install
public class JmxModule extends AbstractModule {

    @Override
    protected void configure() {
        // FIXME: Not implemented
    }

}


text:
import os
import json
import logging
import subprocess

HOME = os.environ['HOME']
KEY_PATH = os.path.join(HOME, ".m2")

'''
This file would do the following items:
    Import keys from AWS Credential services
    Create settings.xml in .m2 with pass phrase
    Create security-settings.xml in .m2 with master password
    Import keys.asc the encrypted keys in gpg
'''

def getCredentials():
    import boto3
    import botocore
    endpoint_url = os.environ['MAVEN_PUBLISH_SECRET_ENDPOINT_URL']
    secret_creds_name = os.environ['MAVEN_PUBLISH_SECRET_NAME_CREDENTIALS']
    secret_key_name = os.environ['MAVEN_PUBLISH_SECRET_NAME_GPG']
    region_name = os.environ['DOCKERHUB_SECRET_ENDPOINT_REGION']

    session = boto3.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name,
        endpoint_url=endpoint_url
    )
    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_creds_name
        )
        get_secret_key_response = client.get_secret_value(
            SecretId=secret_key_name
        )
    except botocore.exceptions.ClientError as client_error:
        if client_error.response['Error']['Code'] == 'ResourceNotFoundException':
            name = (secret_key_name if get_secret_value_response
                    else secret_creds_name)
            logging.exception("The requested secret %s was not found", name)
        elif client_error.response['Error']['Code'] == 'InvalidRequestException':
            logging.exception("The request was invalid due to:")
        elif client_error.response['Error']['Code'] == 'InvalidParameterException':
            logging.exception("The request had invalid params:")
        raise
    else:
        secret = get_secret_value_response['SecretString']
        secret_dict = json.loads(secret)
        secret_key = get_secret_key_response['SecretString']
        return secret_dict, secret_key

def importASC(key, gpgPassphrase):
    filename = os.path.join(KEY_PATH, "key.asc")
    with open(filename, 'w') as f:
        f.write(key)
    subprocess.check_output(['gpg2', '--batch', '--yes',
                    '--passphrase-fd', '0',
                    "--import", "{}".format(filename)],
                   input=str.encode(gpgPassphrase))

def encryptMasterPSW(password):
    filename = os.path.join(KEY_PATH, "encryptMasterPassword.exp")
    with open(filename, 'w') as f:
        f.write('''
        spawn mvn --encrypt-master-password
        expect -exact "Master password: "
        send -- "{}\r"
        expect eof
        '''.format(password))
    result = subprocess.check_output(['expect', filename])
    return str(result).split('\r\n')[-1][2:-3]

def encryptPSW(password):
    filename = os.path.join(KEY_PATH, "encryptPassword.exp")
    with open(filename, 'w') as f:
        f.write('''
        spawn mvn --encrypt-password
        expect -exact "Password: "
        send -- "{}\r"
        expect eof
        '''.format(password))
    result = subprocess.check_output(['expect', filename])
    return str(result).split('\r\n')[-1][2:-3]

def masterPSW(password):
    with open(os.path.join(KEY_PATH, "settings-security.xml"), "w") as f:
        f.write("<settingsSecurity>\n <master>{}</master>\n</settingsSecurity>"
                .format(password))

def serverPSW(username, password, gpgPassphrase):
    with open(os.path.join(KEY_PATH, "settings.xml"), "w") as f:
        settingsString = '''<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<pluginGroups></pluginGroups>
<proxies></proxies>
<servers>
<server>
        <id>apache.snapshots.https</id>
        <username>{}</username>
        <password>{}</password>
</server>
<!-- To stage a release of some part of Maven -->
<server>
        <id>apache.releases.https</id>
        <username>{}</username>
        <password>{}</password>
</server>
</servers>
<mirrors></mirrors>
<profiles>
<profile>
        <id>gpg</id>
        <properties>
        <gpg.executable>gpg2</gpg.executable>
        <gpg.passphrase>{}</gpg.passphrase>
        <gpg.skip>true</gpg.skip>
        </properties>
</profile>
</profiles>
<activeProfiles>
        <activeProfile>gpg</activeProfile>
</activeProfiles>
</settings> '''.format(username, password, username, password, gpgPassphrase)
        f.write(settingsString)

if __name__ == "__main__":
    if not os.path.exists(KEY_PATH):
        os.makedirs(KEY_PATH)
    credentials, gpgKey = getCredentials()
    masterPass = encryptMasterPSW(credentials['masterpass'])
    masterPSW(masterPass)
    passwordEncrypted = encryptPSW(credentials['password'])
    serverPSW(credentials['user'], passwordEncrypted,
             credentials['gpgPassphrase'])
    importASC(gpgKey, credentials['gpgPassphrase'])


text:
import pluginHooks from './plugin-hooks'
import initConstructor from './init-constructor'
import {
  KEY_EVENT_LISTENERS,
  INITIALIZED_KEY,
  COELEMENT_DATA_KEY_PREFIX
} from './util/const'

/**
 * Initialize component.
 * @param Constructor The coelement class
 * @param el The element
 * @param name The coelement name
 * @return The created coelement instance
 */
export default (Constructor: any, el: HTMLElement, name?: string): any => {
  if (!Constructor[INITIALIZED_KEY]) {
    initConstructor(Constructor, name)
  }

  const coelem = new Constructor()

  // Assigns element to coelement's .el property
  coelem.el = el

  if (name) {
    // Assigns coelement to element's "hidden" property
    ;(el as any)[COELEMENT_DATA_KEY_PREFIX + name] = coelem
  }

  // Initialize event listeners defined by @emit decorator
  ;(Constructor[KEY_EVENT_LISTENERS] || []).map((listenerBinder: any) => {
    listenerBinder(el, coelem, name)
  })

  // Executes plugin hooks
  pluginHooks.forEach(pluginHook => {
    pluginHook(el, coelem)
  })

  if (typeof coelem.__mount__ === 'function') {
    coelem.__mount__()
  }

  return coelem
}


text:
<Alloy>
<Collection src="users"></Collection>
<Collection src="session"></Collection>
	<Window>
		<View id="bar">
			<Label text="جزئیات حضور و غیاب" color="white" height="50" left="10"></Label>
		</View>
		<Picker id="picker"
		onChange="report"
		top=3
		useSpinner= true
		visibleItems= 2></Picker>
<!--
		<View class="Row">
				<TextField id="SessionDate" class="inp" hintText="تاریخ جلسه" keyboardType="KEYBOARD_NUMBER_PAD"></TextField>
		</View> -->

	</Window>
</Alloy>


text:
package com.thoughtworks.go.server.materials.postcommit;

/**
 * @understands: PostCommitHookMaterial
 */
public interface PostCommitHookMaterialType {
    boolean isKnown();
    boolean isValid(String type);
    PostCommitHookImplementer getImplementer();
}


text:
<?php

namespace CB\FairBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BakedItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('description')
            ->add('quantity')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CB\FairBundle\Entity\BakedItem'
        ));
    }

    public function getName()
    {
        return 'cb_fairbundle_bakeditemtype';
    }
}


text:
#define TEST_NAME "auth"
#include "cmptest.h"

/* "Test Case 2" from RFC 4231 */
static unsigned char key[32] = "Jefe";
static unsigned char c[] = "what do ya want for nothing?";

/* Hacker manifesto */
static unsigned char key2[] = "Another one got caught today, it's all over the papers. \"Teenager Arrested in Computer Crime Scandal\", \"Hacker Arrested after Bank Tampering\"... Damn kids. They're all alike.";

static unsigned char a[crypto_auth_BYTES];
static unsigned char a2[crypto_auth_hmacsha512_BYTES];

int main(void)
{
    crypto_auth_hmacsha512_state st;
    size_t i;

    assert(crypto_auth_hmacsha512_statebytes() ==
           sizeof(crypto_auth_hmacsha512_state));
    crypto_auth(a, c, sizeof c - 1U, key);
    for (i = 0; i < sizeof a; ++i) {
        printf(",0x%02x", (unsigned int)a[i]);
        if (i % 8 == 7)
            printf("\n");
    }
    printf("\n");

    crypto_auth_hmacsha512_init(&st, key, sizeof key);
    crypto_auth_hmacsha512_update(&st, c, 1U);
    crypto_auth_hmacsha512_update(&st, c, sizeof c - 2U);
    crypto_auth_hmacsha512_final(&st, a2);
    for (i = 0; i < sizeof a2; ++i) {
        printf(",0x%02x", (unsigned int)a2[i]);
        if (i % 8 == 7)
            printf("\n");
    }
    printf("\n");

    crypto_auth_hmacsha512_init(&st, key2, sizeof key2);
    crypto_auth_hmacsha512_update(&st, c, 1U);
    crypto_auth_hmacsha512_update(&st, c, sizeof c - 2U);
    crypto_auth_hmacsha512_final(&st, a2);
    for (i = 0; i < sizeof a2; ++i) {
        printf(",0x%02x", (unsigned int)a2[i]);
        if (i % 8 == 7)
            printf("\n");
    }

    assert(crypto_auth_bytes() > 0U);
    assert(crypto_auth_keybytes() > 0U);
    assert(strcmp(crypto_auth_primitive(), "hmacsha512256") == 0);
    assert(crypto_auth_hmacsha256_bytes() > 0U);
    assert(crypto_auth_hmacsha256_keybytes() > 0U);
    assert(crypto_auth_hmacsha512_bytes() > 0U);
    assert(crypto_auth_hmacsha512_keybytes() > 0U);
    assert(crypto_auth_hmacsha512256_bytes() == crypto_auth_bytes());
    assert(crypto_auth_hmacsha512256_keybytes() == crypto_auth_keybytes());
    assert(crypto_auth_hmacsha512256_statebytes() >=
           crypto_auth_hmacsha512256_keybytes());
    assert(crypto_auth_hmacsha256_statebytes() ==
           sizeof(crypto_auth_hmacsha256_state));
    assert(crypto_auth_hmacsha512_statebytes() ==
           sizeof(crypto_auth_hmacsha512_state));

    return 0;
}


text:
package org.jboss.resteasy.test.finegrain.resource;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.test.BaseResourceTest;
import org.jboss.resteasy.test.TestPortProvider;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Spec requires that HEAD and OPTIONS are handled in a default manner
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class InheritanceTest extends BaseResourceTest
{

   public static interface ParentResource
   {

      @GET
      @Produces("text/plain")
      public String firstest();

   }

   @Path(value = "/InheritanceTest")
   public static class ChildResource implements ParentResource
   {

      public String firstest()
      {
         return "First";
      }
   }

   public static interface ParentResource1
   {

      @GET
      @Produces("text/xml")
      public String secondtest();
   }

   @Path(value = "/InheritanceTest1")
   public static class ChildResource1 implements ParentResource1
   {
      static String html_content =
              "" + "<title>JAX-RS Test</title>" +
                      "Second";

      @GET
      @Produces("text/html")
      public String secondtest()
      {
         return html_content;
      }
   }

   @Before
   public void setUp() throws Exception
   {
      deployment.getRegistry().addPerRequestResource(ChildResource.class);
      deployment.getRegistry().addPerRequestResource(ChildResource1.class);
   }

   /*
    *
    * Client sends a request on a resource at /InheritanceTest,
    *                 Verify that inheritance works.
    */
   @Test
   public void Test1() throws Exception
   {
      ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/InheritanceTest"));
      request.header("Accept", "text/plain");
      ClientResponse<String> response = request.get(String.class);
      Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
      Assert.assertEquals("First", response.getEntity());
   }

   /*
    *  Client sends a request on a resource at /InheritanceTest1,
    *                 Verify that inheritance works.
    */
   @Test
   public void Test2() throws Exception
   {
      ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/InheritanceTest1"));
      request.header("Accept", "text/html");
      ClientResponse<String> response = request.get(String.class);
      Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
      Assert.assertTrue(response.getEntity().indexOf("Second") > -1);
   }

}


text:
First introduced over twenty years ago, WiFi has become the most popular wireless networking technology. The SPWF04Sx family of modules from STMicroelectronics have an easy-to-use AT command based socket API that allow applications to quickly connect to the Internet. They also support Transport Layer Security, which is vital in an IoT environment.

Take a look at the [FEZ WiFi sample](https://github.com/ghi-electronics/TinyCLR-Samples/) for a working example to get going quickly.

The [TinyCLR Driver repo](https://github.com/ghi-electronics/TinyCLR-Drivers) includes the complete source code.

## Hardware

### Firmware Updating

To update the firmware, please see this [page](../../../../hardware/components/spwf04sa.md).

## Software

### Constructors

#### SPWF04SxInterface()

`SPWF04SxInterface(SpiDevice spi, GpioPin irq, GpioPin reset)`. Used to create a new instance of the WiFi driver. Takes the SPI device and the IRQ and RESET GPIO pins as arguments. Has no return value. You must also set the mode pin but the constructor does not yet do this for you. Be sure to see the [sample](https://github.com/ghi-electronics/TinyCLR-Samples/blob/master/FEZ/FEZWiFi/Program.cs) for the correct setup or your device will not work.

### Methods

#### ClearTlsServerRootCertificate()

`ClearTlsServerRootCertificate()`. Erases the currently loaded root certificates from the WiFi module's flash memory. Takes no arguments and has no return value.

#### CloseSocket()

`CloseSocket(int id)`. Closes the socket specified by the id parameter. The socket id is assigned by the `OpenSocket()` method when the socket is created. Has no return value.

#### DisableRadio()

`DisableRadio()`. Disables the WiFi radio. Takes no arguments and has no return value.

#### Dispose()

`Dispose()`. Disposes of the WiFi instance. Takes no arguments and has no return value.

#### EnableRadio()

`EnableRadio()`. Enables the WiFi radio. Takes no arguments and has no return value.

#### GetConnectionSettings()

`GetConnectionSettings(SpiChipSelectType chipSelectType, int chipSelectLine)`. Returns the SPI connection settings used to open an SPI port for communication with the WiFi module. The first parameter taken by this function specifies the type of chip select used -- only `SpiChipSelectType.Gpio` is supported at this time. The second parameter specifies the GPIO pin that controls the WiFi module's chip select pin.

#### JoinNetwork()

`JoinNetwork(string ssid, string password)`. Attempts to join the WiFi network specified by the ssid and password values. Has no return value.

#### ListSocket()

`ListSocket()`. Returns a string that lists all open socket clients in the format `AT-S.List::<id>:<connected>:<kind>:<len>:<IP>:<port>`. Takes no arguments.

#### OpenSocket()

`OpenSocket(string host, int port, SPWF04SxConnectionType connectionType, SPWF04SxConnectionSecurityType connectionSecurity, string commonName)`. Opens a socket client. Arguments are a string host name, an integer port number, an SPWF04SxConnectionType connection type, and a connection security type of `none` or `Tls`. Returns an integer ID number for the socket.

#### QuerySocket()

`QuerySocket(int socket)`. Queries a socket client for pending data. Returns an integer number of bytes that are waiting on the socket. Takes the socket id as its only argument. The socket id is returned by the `OpenSocket()` method when the socket is created.

#### ReadHttpResponse()

`ReadHttpResponse(byte[] buffer, int offset, int count)`. Reads the response to the currently active HTTP command. Arguments are a byte array buffer to store the incoming data, an integer offset into the array, and an integer count of the size in bytes of available buffer. Returns an integer value of the number of bytes read.

#### ReadSocket()

`ReadSocket(int socket, byte[] buffer, int offset, int count)`. Reads data from a socket client. Arguments are an integer socket ID, an input buffer byte array, an integer offset into the array, and an integer count of how many bytes can be read into the buffer array. The socket id is returned by the `OpenSocket()` method when the socket is created. Returns an integer number of bytes received.

#### ResetConfiguration()

`ResetConfiguration()`. Restores the factory configuration variables to the flash of the WiFi module. It is necessary to perform a hardware or software reset of the WiFi module after a factory restore. Takes no arguments and has no return value.

#### SendHttpGet()

`SendHttpGet(string host, string path, int port, SPWF04SxConnectionSecurityType connectionSecurity)`. Sends a single http get request to the given host and path to retrieve information from a server. Arguments are a string host name, a string host path, an integer port number, and a connection security type of `none` or `Tls`. Returns an integer HTTP server status code.

#### SendHttpPost()

`SendHttpPost(string host, string path, int port, SPWF04SxConnectionSecurityType connectionSecurity)`. Sends an HTTP post request to a remote host. Arguments are a string host name, a string host path, an integer port number, and a connection security type of `none` or `Tls`. Returns an integer HTTP server status code.

#### SetTlsServerRootCertificate()

`SetTlsServerRootCertificate(byte[] certificate)`. Loads a TLS certificate into the flash memory of the WiFi module. Accepts a byte array containing the certificate as its only argument. Returns a string containing the Subject Key Identifier (SKI) of the certificate. The certificate must be loaded into your application as part of a resources file, be DER encoded, and have the extension .cer.

You can use your web browser to obtain a website's root certificate. In Chrome, click on the lock icon to the left of the web address. Then click on `Certificate` and select the `Details` tab. In `Details` click on the `Copy to File...` button. The `Certificate Export Wizard` will appear. Export the certificate as `DER encoded binary X.509 (.CER)`.

In Micorosoft Edge click on the lock icon to the left of the web address and then select `View certificate.` Click on the `Export to file` button and save the file with a .cer extension.

#### TurnOff()

`TurnOff()`. Turns off the WiFi module. Takes no arguments and has no return value.

#### TurnOn()

`TurnOn()`. Turns on the WiFi module. Takes no arguments and has no return value.

#### WriteSocket()

`WriteSocket(int socket, byte[] data)`. Writes data to a socket client. Arguments are an integer ID number for the socket and a byte array of data. The socket id is returned by the `OpenSocket()` method when the socket is created.

`WriteSocket(int socket, byte[] data, int offset, int count)`. Same as above but also takes integer arguments for the offset into the data array and a count for the number bytes to send.

### Events

#### IndicationReceived

Fires an event when a WiFi indication (WIND) message is received.

#### ErrorReceived

Fires an event when a WiFi error message is received.

### Properties

#### ForceSocketsTls

Boolean property that can be used to ensure a socket is opened as a secure TLS socket. For example, executing `wifi.ForceSocketsTls = true;` before `OpenSocket()` will cause the socket to be opened as a TLS Socket.

#### ForceSocketsTlsCommonName

String property used to specify the common name as found in the websites certificate. The common name is listed in the `Subject Alternative Name` field of the certificate.

#### State

Read only property of type `SPWF04SxWiFiState` that reflects the current state of the WiFi module. For example:

`if (wifi.State == SPWF04SxWiFiState.HardwareFailure) Debug.WriteLine("Hardware Failure");`

The possible states are: `HardwarePowerUp`, `HardwareFailure`, `RadioTerminatedByUser`, `RadioIdle`, `ScanInProgress`, `ScanComplete`, `JoinInProgress`, `Joined`, `AccessPointStarted`, `HandshakeComplete`, and `ReadyToTransmit`.


text:
<?php

function synved_option_section_default_name($id, $page)
{
	return $page . '_section_general';
}

function synved_option_section_default($id, $page)
{
	$section = synved_option_section_default_name($id, $page);

	return array('name' => $section, 'type' => 'options-section', 'label' => __('General Settings', 'synved-option'), 'tip' => __('General Settings for', 'synved-option') . ' ' . synved_option_label_from_id($id));
}

function synved_option_settings_section_cb($name, $item)
{
	$tip = synved_option_item_tip($item);

	if ($tip != null)
	{
		echo '<p>' . $tip . '</p>';
	}
}

?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.monitor.models;

import com.azure.core.annotation.Immutable;

/**
 * Proxy Resource
 *
 * <p>The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location.
 */
@Immutable
public final class ProxyResourceAutoGenerated extends ResourceAutoGenerated3 {
    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
    }
}


text:
from audit_log.models.fields import CreatingUserField, LastUserField
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils import timezone

class SourceReference(models.Model):
    """
    Model representing a specific copy of a book (i.e. that can be borrowed from the library).
    """

    reference_name = models.TextField(max_length=1000, help_text="Enter a brief description of the reference")
    master_reference = models.ForeignKey('MasterReference', on_delete=models.SET_NULL, null=True)
    created_date = models.DateTimeField(auto_now_add=True)
    created_by = CreatingUserField(related_name = "created_source_reference")
    modified_date = models.DateTimeField(auto_now=True)
    modified_by = LastUserField()

    DELETED = (
        (1, 'Deleted'),
        (0, 'Active'),
    )

    is_deleted = models.PositiveSmallIntegerField(choices=DELETED, default=0, blank=True, help_text='Is deleted')

    class Meta:
        ordering = ["reference_name"]

    def get_absolute_url(self):
        return reverse('sourcereference-detail', args=[str(self.id)])

    def __str__(self):
        """
        String for representing the Model object
        """
        return '%s (%s)' % (self.id,self.reference_name)

class MasterReference(models.Model):
    """
    Model representing a specific copy of a book (i.e. that can be borrowed from the library).
    """
    reference_name = models.TextField(max_length=1000, help_text="Enter a brief description of the reference")
    type = models.ForeignKey('ReferenceType', on_delete=models.SET_NULL, null=True, help_text="Select type for the reference")
    doi = models.CharField(blank=True, null=True, max_length=80, help_text="Enter a brief description of the reference")
    year = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1700), MaxValueValidator(2017)])
    title = models.TextField(blank=True, null=True, max_length=1000, help_text="Enter a brief description of the reference")
    container_title = models.CharField(blank=True, null=True, max_length=100, help_text="Enter a brief description of the reference")
    volume = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(1000)])
    issue = models.PositiveIntegerField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(1000)])
    page = models.CharField(blank=True, null=True, max_length=10, help_text="The page number(s) of the reference")
    created_date = models.DateTimeField(auto_now_add=True)
    created_by = CreatingUserField(related_name = "created_master_reference")
    modified_date = models.DateTimeField(auto_now=True)
    modified_by = LastUserField()

    DELETED = (
        (1, 'Deleted'),
        (0, 'Active'),
    )

    is_deleted = models.PositiveSmallIntegerField(choices=DELETED, default=0, blank=True, help_text='Is deleted')

    class Meta:
        ordering = ["reference_name"]

    def get_absolute_url(self):
        return reverse('masterreference-detail', args=[str(self.id)])

    def __str__(self):
        """
        String for representing the Model object
        """
        return '%s: %s (%s)' % (self.id,self.reference_name,self.type.type_label)

class ReferenceType(models.Model):
    """
    Model representing a specific type of the Reference. More information from https://github.com/greenelab/scihub/issues/7
    """
    type = models.CharField(max_length=20, help_text="Type of the reference")
    type_label = models.CharField(max_length=30, help_text="Label text of the reference")
    type_data_order = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(20)], help_text="Selection order for referenced data")
    created_date = models.DateTimeField(auto_now_add=True)
    created_by = CreatingUserField(related_name = "created_reference_type")
    modified_date = models.DateTimeField(auto_now=True)
    modified_by = LastUserField()

    DELETED = (
        (1, 'Deleted'),
        (0, 'Active'),
    )

    is_deleted = models.PositiveSmallIntegerField(choices=DELETED, default=0, blank=True, help_text='Is deleted')

    class Meta:
        ordering = ["type_label"]

    def __str__(self):
        """
        String for representing the Model object
        """
        return '%s' % (self.type_label)