text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Bootstrap 3 Control Panel</title>
<meta name="generator" content="Bootply" />
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="../../js/bootstrap/bootstrap.min.css" rel="stylesheet">

<link href="css/styles.css" rel="stylesheet">

				<button type="button" class="navbar-toggle" data-toggle="collapse"
					data-target=".navbar-collapse">

				</button>
				Control Panel

  Admin

My Profile

									Logout

					 Toolbox

 Alerts

 Links

 Reports

 Books

 Tools

 Real-time

 Advanced..

					 Dashboard

							Inbox Messages 3

Processing Status

								Complete

										72% Complete

								In Progress

										20% Complete

								At Risk

										80% Complete

3

1. Is there a way..

2. Hello, admin. I would..

All messages

							This is a responsive dashboard-style layout that uses Bootstrap 3. You can use
							this template as a starting point to create something more
							unique.

							Visit the Bootstrap Playground at Bootply to tweak this layout,
							or discover 1000's of Bootstrap code examples and snippets.

 Service

 Cloud

 Tools

 Help

				 Reports

							Visits
							ROI
							Source
							Description and Notes

							45
							2.45%
							Direct
							Sam sapien massa, aliquam in cursus ut, ullamcorper in
								tortor. Aliquam mauris arcu, tristique a lobortis vitae,
								condimentum feugiat justo.

							289
							56.2%
							Referral
							After RWD massa, aliquam in cursus ut, ullamcorper in
								tortor. Aliquam mauris arcu, tristique a lobortis vitae,
								condimentum feugiat justo.

							98
							25%
							Type
							Wil sapien massa, aliquam in cursus ut, ullamcorper in
								tortor. Liquam mauris arcu, tristique a lobortis vitae,
								condimentum feugiat justo.

							109
							8%
							..
							Forfoot aliquam in cursus ut, ullamcorper in tortor.
								Okma mauris arcu, tristique a lobortis vitae, condimentum
								feugiat justo.

							34
							14%
							..
							Mikel sapien massa, aliquam in cursus ut, ullamcorper in
								tortor. Maliquam mauris arcu, tristique a lobortis vitae,
								condimentum feugiat justo.

Profile

Messages

Settings

							Lorem profile dolor sit amet, consectetur adipiscing elit. Duis
							pharetra varius quam sit amet vulputate.

Quisque mauris augue, molestie tincidunt condimentum
								vitae, gravida a libero. Aenean sit amet felis dolor, in
								sagittis nisi. Sed ac orci quis tortor imperdiet venenatis. Duis
								elementum auctor accumsan. Aliquam in felis sit amet augue.

							Message ipsum dolor sit amet, consectetur adipiscing elit. Duis
							pharetra varius quam sit amet vulputate.

Quisque mauris augue, molestie tincidunt condimentum
								vitae, gravida a libero. Aenean sit amet felis dolor, in
								sagittis nisi. Sed ac orci quis tortor imperdiet venenatis. Duis
								elementum auctor accumsan. Aliquam in felis sit amet augue.

							Lorem settings dolor sit amet, consectetur adipiscing elit. Duis
							pharetra varius quam sit amet vulputate.

Quisque mauris augue, molestie tincidunt condimentum
								vitae, gravida a libero. Aenean sit amet felis dolor, in
								sagittis nisi. Sed ac orci quis tortor imperdiet venenatis. Duis
								elementum auctor accumsan. Aliquam in felis sit amet augue.

New Requests

							Hosting virtual
								mailbox serv.. Dedicated
								server doesn't.. RHEL 6
								install on new..

					<button type="button" class="close" data-dismiss="alert">×</button>
					Please remember to Logout for classified security.

							Layouts & Templates

							Toolbox

							Widgets

							Reports

							Pages

							Social Media

Submit Request

						<form class="form form-vertical">

								Name

									<input type="text" class="form-control"
										placeholder="Enter Name">

								Title

									<input type="password" class="form-control"
										placeholder="Password">

								Details

									<textarea class="form-control"></textarea>

								Select

									<select class="form-control"><option>General
											Question</option>
										<option>Server Issues</option>
										<option>Billing Question</option></select>

									<button type="submit" class="btn btn-primary">Post</button>

						</form>

Engagement

		This Bootstrap 3 dashboard layout is compliments of Bootply.com

					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">×</button>

Add Widget

Add a widget stuff here..

					Close Save changes


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

<ftx>{math}10*8/3.18{~math}</ftx>
<ftx>{date:full}dd/mm/yyyy h:m:s{~date}</ftx>
<ftx>{if:hour=17}this{else}that{~if}</ftx>
<ftx>{if:day=10}this{else}
Dummy text
{~if}</ftx>
<ftx>{if:month=6}this{else}that{~if}</ftx>
<ftx>{if:[round(9*21)]=9}this{~if}</ftx>
<ftx>{if:[floor(84/10)]=8}this expression is true{~if}</ftx>
<ftx>{form:login}class:old,id:nene,style:null,action:theserver.com/form/{~form}</ftx>
<ftx>{panel:standard}
here's the inside of the panel
{~panel}</ftx>
<ftx>{gutter:closed}
Dummy text
{~gutter}</ftx>
<fta>{json://davidemaser.github.io/data/temp-table.json}node=table,show=5,saveAs=myData,hide=false{~json}</fta>
<ftx>{modal:full}title:this is the title,message:this would be the message part,prompt:full,promptConfirm:I Agree,promptRefuse:No,cta:Click Here{~modal}</ftx>
<ftx>{html}
    section[name=A_NAME_HERE] -- div*3[first,second,third]
    section[class=this,id=that] -- nav -- section[name=mine] -- div[class=this,id=another,bind=click(test)] -- p[data-render=long]{this will render in the paragraph}
    strong -- i{this will be italic}
    {~html}</ftx>
<ftx>{animate:points}object:that,points:[1-500,5-200,8-185,100-800]{~animate}</ftx>
<ftx>{nav:horizontal}{json:nav}{~nav}</ftx>
<ftx>{placeholder:large}{~placeholder}</ftx>
<ftx>
    {accordion}
    [title=A_NAME_HERE] This is the content
    [title=ANOTHER_NAME_HERE] This is more content
    {~accordion}
</ftx>
<ftx>{table:basic}{json:table}{~table}</ftx>
<ftx>{group}
Dummy text

More dummy text
{~group}</ftx>
<ftx>{sticky:top}I'm a sticky item{~sticky}</ftx>
<ftx>{search:default}target:this_link,placeholder:Enter Search Term Here,button:true,label:Search{~search}</ftx>
<ftx>{bind}this,that,another{~bind}</ftx>
<ftx>{random:div}

Foo

Bar

Foo bar

    {~random}</ftx>
<ftx>{mobile}

Dummy text

Dummy text

Dummy text

    {~mobile}</ftx>
<ftx>{banner:full}
    {image://via.placeholder.com/350x150,title:this is a title,subtext:this is the subtext,button:hello,action:link}

second entry

third entry

    {~banner}</ftx>
<ftx>{video:default}url://www.w3schools.com/html/movie.mp4,width:280,controls:true,autoplay:true,poster:url,subtitles:[en url,fr url]{~video}</ftx>
<ftx>{video:default}url:[//www.w3schools.com/html/movie.mp4 mp4,//www.w3schools.com/html/movie.ogg ogg,link webm],width:500,height:280,controls:true,autoplay:true,poster:url,subtitles:[en url,fr url]{~video}</ftx>
<ftx>{prefetch}
    //via.placeholder.com/350x150
    {~prefetch}</ftx>
<ftx>{image:quarter}url://images.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png{~image}</ftx>
<ftx>{analytics:gtm}id:your_id_here{~analytics}</ftx>
<ftx>{stylize}make div background red color green size 22px overflow hidden
    this is the content of the above item (in this case a div)
    more content
    and more{~stylize}</ftx>
<ftx>{stylize}make paragraph background black color white size 22px font-family Verdana
    this is the content of the above item (in this case a div)
    more content
    and more{~stylize}</ftx>
<ftx>{trim:20,start}{ellipsis}this is the content of the above item (in this case a div){~trim}</ftx>
<ftx>{trim:20}this is the content of the above item (in this case a div){ellipsis}{~trim}</ftx>
<ftx>{links:order}
    this is the text,thelink.com > this is the text,thelink.com > this is the text,thelink.com > this is the text,thelink.com
    this is another link,thelinlisthi.como
    and wow another one,thenolionl.com{~map}</ftx>
<ftx>{filter:language}
this bit of caca is like crap and it's really quite poo
{~filter}</ftx>
<ftx>{filter:code}{rules:li,br}
this bit of text is really weird and it's really
 quite full
 of html
{~filter}</ftx>
<ftx>{filter:code}
this bit of text will have absolutely no html code
 in it
 when processed
{~filter}</ftx>
<ftx>{wrap:word}{some b,those div}those are some really cool words for some of us{~wrap}</ftx>
<ftx>{object:array}{save:saveAsThis}one,two,three,four{~object}</ftx>
<ftx>{object:object}{save:myObject}
    {
    "this": {
    "text": "something",
    "subtitle": "else"
    }
    }
    {~object}</ftx>
<ftx>{object:variable}{save:[myVar=this,anotherVar=hello,thisVar]}{~object}</ftx>
<ftx>{object:function}{save:tempFunc}console.log('hi there'){~object}</ftx>
<ftx>{poll}www.google.com{~poll}</ftx>

redpajama_set_name: RedPajamaGithub


text:
* Polling and Long-Polling
  * Polling
    * client sends request
    * client periodically requests updates via AJAX
  * Long Polling
    * AJAX requests have a property called timeout
    * setting the timeout to a long time, reduces the number of requests
* Forever Frame
  * iframe
  * embed document, script tags are sent from the server to update the data
* HTML5 Server-Sent Events
  * EventSource object

#### HTML5 WebSockets - The Basics
* Evolution of the Web
  * academia tackled how to transfer one document to another
  * HTTP made sense, stateless etc.
  * new headers added for features, user-agent (what browser is making this request)
  * large headers were not a problem, the body far outweighed them
  * as web apps progressed to request little pieces of data more often, headers are a bigger problem
* WebSockets vs. Other Techniques
  * using websockets means you are not using HTTP anymore, you upgrade the connection
  * a handshake occurs when upgrading
  * no header overhead
* WebSockets basics
  * instantiate a websocket object
  * OnOpen, OnMessage, OnError, OnClose events
  * OnClose takes event with wasClean, code and reason
  * methods supported are Send and Close
  * failovers, auto-connect etc. require a higher library to be used

### HTML5 WebSockets - The Demo
* Server-side Code
  * WebSocketCollection, can check a request for web socket and upgrade if required
* Client-side Code
  * send JSON to the server via the websocket
  * the server takes action, then broadcasts the update to all connections
  * when the client receives the message it updates the div with the latest information
* Data Transfer Types
  * can send blobs and byte_arrays
  * on the client check type of event.data for ArrayBuffer
* Authentication
  * give the notes lists a dictionary with a guid as an id
  * add a session to the user (in the URL here)
  * only send updates to connections that share that ID
* Security
  * WS & WSS Schemes
  * Web Socket Secure -> uses TLS (like HTTPS for HTTP)
  * DOS, XSS etc.
* Fallbacks
  * Modernizer to check
* Inspecting
  * filter chrome dev tools to websockets on the network tab
* WebRTC fundemantals course for real-time streaming


text:
Meteor.startup(function () {
  Template[getTemplate('pages')].helpers({
    pages: function(){
      return Pages.collection.find({}, {sort: {order: 1}});
    },
    pageItem: function () {
      return getTemplate('pageItem');
    }
  });
});


text:
#include <boost/python.hpp>
#include "/home/harper/Documents/Work/SEJITS/pyCombBLAS/trunk/kdt/pyCombBLAS/pyOperations.h"
#include <stdint.h>
#include "test_cpp_file.h"

using namespace boost::python;

namespace op
{

  template <typename T>
  struct my_op_s : public ConcreteUnaryFunction<T>
  {
    T operator()(const T& x) const
    {
		return (x < 0) ? -static_cast<doubleint>(x) : x;
    }
  };

  UnaryFunction my_op()
  {
    return UnaryFunction(new my_op_s<doubleint>());
  }
}

/*
PyObject* my_op_py(object x)
{
  //float val = extract<float>(x.attr("__float__"));
  double f = extract<double>(x);
  if(f < 0) f = -f;
  PyObject* ret = PyFloat_FromDouble(f);
  return ret;
}

BOOST_PYTHON_MODULE(module)
{
  //class_<op::UnaryFunction>("UnaryFunction", init<op::ConcreteUnaryFunction<doubleint>*>());
  //def("my_op", &op::my_op);
  //def("apply_my_op", &apply_my_op);
  def("my_op_py", &my_op_py);
}
*/


text:
@interface UIView (ZDFrame)

@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;

@end


text:
<?php

namespace ZendTest\Diactoros\Response;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Diactoros\Response\JsonResponse;

class JsonResponseTest extends TestCase
{
    public function testConstructorAcceptsDataAndCreatesJsonEncodedMessageBody()
    {
        $data = [
            'nested' => [
                'json' => [
                    'tree',
                ],
            ],
        ];
        $json = '{"nested":{"json":["tree"]}}';

        $response = new JsonResponse($data);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/json', $response->getHeaderLine('content-type'));
        $this->assertSame($json, (string) $response->getBody());
    }

    public function scalarValuesForJSON()
    {
        return [
            'null'         => [null],
            'false'        => [false],
            'true'         => [true],
            'zero'         => [0],
            'int'          => [1],
            'zero-float'   => [0.0],
            'float'        => [1.1],
            'empty-string' => [''],
            'string'       => ['string'],
        ];
    }

    /**
     * @dataProvider scalarValuesForJSON
     */
    public function testScalarValuePassedToConstructorJsonEncodesDirectly($value)
    {
        $response = new JsonResponse($value);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/json', $response->getHeaderLine('content-type'));
        // 15 is the default mask used by JsonResponse
        $this->assertSame(json_encode($value, 15), (string) $response->getBody());
    }

    public function testCanProvideStatusCodeToConstructor()
    {
        $response = new JsonResponse(null, 404);
        $this->assertEquals(404, $response->getStatusCode());
    }

    public function testCanProvideAlternateContentTypeViaHeadersPassedToConstructor()
    {
        $response = new JsonResponse(null, 200, ['content-type' => 'foo/json']);
        $this->assertEquals('foo/json', $response->getHeaderLine('content-type'));
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testJsonErrorHandlingOfResources()
    {
        // Serializing something that is not serializable.
        $resource = fopen('php://memory', 'r');
        new JsonResponse($resource);
    }

    public function testJsonErrorHandlingOfBadEmbeddedData()
    {
        if (version_compare(PHP_VERSION, '5.5', 'lt')) {
            $this->markTestSkipped('Skipped as PHP versions prior to 5.5 are noisy about JSON errors');
        }

        if (defined('HHVM_VERSION')) {
            $this->markTestSkipped('Skipped as HHVM happily serializes embedded resources');
        }

        // Serializing something that is not serializable.
        $data = [
            'stream' => fopen('php://memory', 'r'),
        ];

        $this->setExpectedException('InvalidArgumentException', 'Unable to encode');
        new JsonResponse($data);
    }

    public function valuesToJsonEncode()
    {
        return [
            'uri'    => ['https://example.com/foo?bar=baz&baz=bat', 'uri'],
            'html'   => ['
content
', 'html'],
            'string' => ["Don't quote!", 'string'],
        ];
    }

    /**
     * @dataProvider valuesToJsonEncode
     */
    public function testUsesSaneDefaultJsonEncodingFlags($value, $key)
    {
        $defaultFlags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES;

        $response = new JsonResponse([$key => $value]);
        $stream   = $response->getBody();
        $contents = (string) $stream;

        $expected = json_encode($value, $defaultFlags);
        $this->assertContains(
            $expected,
            $contents,
            sprintf('Did not encode %s properly; expected (%s), received (%s)', $key, $expected, $contents)
        );
    }
}


text:
package co.poynt.postman.runner;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class PostmanHttpResponse {
	private static final Logger logger = LoggerFactory.getLogger(PostmanHttpResponse.class);
	public int code;
	public String body;
	public Map<String, String> headers = new HashMap<>();

	public PostmanHttpResponse(int code, String body) {
		this.code = code;
		this.body = body;
	}

	public PostmanHttpResponse(HttpResponse response) {
		this.code = response.getStatusLine().getStatusCode();

		if (code > 399) {
			logger.warn("HTTP Response code: " + code);
		}
		if (code > 499) {
			logger.error("Failed to make POSTMAN request call.");
		}

		HttpEntity entity = response.getEntity();
		if (entity != null) {
			try (InputStream resIs = entity.getContent()) {
				byte[] rawResponse = IOUtils.toByteArray(resIs);
				this.body = new String(rawResponse);
			} catch (IOException e) {
				throw new HaltTestFolderException();
			}
		}

		for (Header h : response.getAllHeaders()) {
			this.headers.put(h.getName(), h.getName());
		}
	}
}


text:
/
namespace WinPhoneOneNoteServiceSample
{
    public partial class MainPage
    {
        private string _accessToken;
        private DateTimeOffset _accessTokenExpiration;
        private string _refreshToken; // Refresh token (only applicable when the app uses the wl.offline_access wl.signin scopes)
        private StandardResponse _response;
		private string sectionName;

		public string PagesEndpoint
		{
			get
			{
				if (String.IsNullOrWhiteSpace(sectionName) || sectionName.Equals(SectionNameHint))
				{
					return PagesEndpointBaseUrl;
				}
				else
				{
					return string.Format("{0}/?sectionName={1}", PagesEndpointBaseUrl, sectionName);
				}
			}
			set
			{
				sectionName = value;
			}
		}

        // OneNote Service API v1.0 Endpoint
        private const string PagesEndpointBaseUrl = "https://www.onenote.com/api/v1.0/pages";
		private const string SectionNameHint = "Enter Section Name";

        // Collateral used to refresh access token (only applicable when the app uses the wl.offline_access wl.signin scopes)
        private const string MsaTokenRefreshUrl = "https://login.live.com/oauth20_token.srf";
        private const string TokenRefreshContentType = "application/x-www-form-urlencoded";
        private const string TokenRefreshRedirectUri = "https://login.live.com/oauth20_desktop.srf";
        private const string TokenRefreshRequestBody = "client_id={0}&redirect_uri={1}&grant_type=refresh_token&refresh_token={2}";

        // Constructor
        public MainPage()
        {
            InitializeComponent();
			this.sectionName = "";
            this.Loaded += CheckIfClientIdUpdated;
			this.textBox_sectionName.Text = SectionNameHint;
        }

        private void CheckIfClientIdUpdated(object sender, RoutedEventArgs e)
        {
            if ((string)Resources["ClientId"] == "Insert Your Client Id Here")
            {
                MessageBox.Show("Visit http://go.microsoft.com/fwlink/?LinkId=392537 for instructions on getting a Client Id. Please specify your client ID in the MainPage.xaml file and rebuild the application.");
            }
        }

        #region Send create page requests

        ///
        /// Send a create page request
        ///
        /// <param name="createMessage">The HttpRequestMessage which contains the page information</param>
        private async Task SendCreatePageRequest(HttpRequestMessage createMessage)
        {
            var httpClient = new HttpClient();
            _response = null;

            // Check if Auth token needs to be refreshed
            await RefreshAuthTokenIfNeeded();

            // Add Authorization header
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
            // Note: API only supports JSON return type.
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Get and parse the HTTP response from the service
            HttpResponseMessage response = await httpClient.SendAsync(createMessage);
            _response = await ParseResponse(response);

            // Update the UI accordingly
            UpdateUIAfterRequest(response);
        }

        ///
        /// Create a page with simple html content
        ///
        private async void btn_CreateSimple_Click(object sender, RoutedEventArgs e)
        {
            string date = GetDate();

            string simpleHtml = "" +
                          "" +
                          "<title>A page created from basic HTML-formatted text (WinPhone8 Sample)</title>" +
                          "<meta name=\"created\" content=\"" + date + "\" />" +
                          "" +
                          "" +
                          "
This is a page that just contains some simple formatted text
" +
                          "" +
                          "";

            // Create the request message, which is a text/html single part in this case
            // The Service also supports content type multipart/form-data for more complex scenarios
			var createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndpoint)
            {
                Content = new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html")
            };

            await SendCreatePageRequest(createMessage);
        }

        ///
        /// Create page with image
        ///
        private async void btn_CreateWithImage_Click(object sender, RoutedEventArgs e)
        {
            const string imagePartName = "image1";

            string date = GetDate();
            string simpleHtml = "" +
                                "" +
                                "<title>A page with an image on it (WinPhone8 Sample)</title>" +
                                "<meta name=\"created\" content=\"" + date + "\" />" +
                                "" +
                                "" +
                                "
This is a page with an image on it
" +
                                "" +
                                "" +
                                "";

            // Create the image part - make sure it is disposed after we've sent the message in order to close the stream.
            Stream imageStream = GetAssetFileStream("assets\\Logo.jpg");
            using (var imageContent = new StreamContent(imageStream))
            {
                imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
				HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndpoint)
                {
                    // Create a multipart/form data request in this case
                    // The Service also supports single part text/html content for simple scenarios
                    Content = new MultipartFormDataContent
                    {
                        {new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
                        {imageContent, imagePartName}
                    }
                };

                // Must send the request within the using block, or the image stream will have been disposed.
                await SendCreatePageRequest(createMessage);
            }
        }

        ///
        /// Create page with URL snapshot
        ///
        private async void btn_CreateWithUrl_Click(object sender, RoutedEventArgs e)
        {
            string date = GetDate();
            string simpleHtml = @"" +
                                "" +
                                "<title>A Page Created With a URL Snapshot on it (WinPhone8 Sample)</title>" +
                                "<meta name=\"created\" content=\"" + date + "\" />" +
                                "" +
                                "" +
                                "
This is a page with an image of an html page rendered from a URL on it.
" +
                                "" +
                                "" +
                                "";

            // Create the request message, which is a text/html single part in this case
            // The Service also supports content type multipart/form-data for more complex scenarios
			var createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndpoint)
            {
                Content = new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html")
            };

            await SendCreatePageRequest(createMessage);
        }

        ///
        /// Create page with HTML snapshot
        ///
        private async void btn_CreateWithHtml_Click(object sender, RoutedEventArgs e)
        {
            const string embeddedPartName = "embedded1";
            const string embeddedWebPage =
                "" +
                "" +
                "<title>Embedded HTML</title>" +
                "" +
                "" +
                "
This is a screen grab of a web page
" +
                "
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vehicula magna quis mauris accumsan, nec imperdiet nisi tempus. Suspendisse potenti. " +
                "Duis vel nulla sit amet turpis venenatis elementum. Cras laoreet quis nisi et sagittis. Donec euismod at tortor ut porta. Duis libero urna, viverra id " +
                "aliquam in, ornare sed orci. Pellentesque condimentum gravida felis, sed pulvinar erat suscipit sit amet. Nulla id felis quis sem blandit dapibus. Ut " +
                "viverra auctor nisi ac egestas. Quisque ac neque nec velit fringilla sagittis porttitor sit amet quam.
" +
                "" +
                "";

            string date = GetDate();

            string simpleHtml = "" +
                                "" +
                                "<title>A Page Created With Snapshot of Webpage in it (WinPhone8 Sample)</title>" +
                                "<meta name=\"created\" content=\"" + date + "\" />" +
                                "" +
                                "" +
                                "
This is a page with an image of an html page on it.
" +
                                "" +
                                "" +
                                "";

			var createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndpoint)
            {
                // Create a multipart/form data request in this case
                // The Service also supports single part text/html for more simpler scenarios
                Content = new MultipartFormDataContent
                        {
                            {new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
                            {new StringContent(embeddedWebPage, System.Text.Encoding.UTF8, "text/html"), embeddedPartName}
                        }
            };

            await SendCreatePageRequest(createMessage);
        }

        ///
        /// Creates a OneNote page with a PDF document attached and rendered
        ///
		private async void btn_CreateWithAttachmentAndPdfRendering_Click(object sender, RoutedEventArgs e)
        {
            const string attachmentPartName = "pdfattachment1";
            string date = GetDate();
            string attachmentHtml = "" +
                                "" +
                                "<title>A page created with a file attachment (WinPhone8 Sample)</title>" +
                                "<meta name=\"created\" content=\"" + date + "\" />" +
                                "" +
                                "" +
                                "
This is a page with a PDF file attachment
" +
                                "<object data-attachment=\"attachment.pdf\" data=\"name:" + attachmentPartName + "\" />" +
								"
Here's the Content of the PDF document :
" +
								"" +
                                "" +
                                "";
            // Create the attachment part - make sure it is disposed after we've sent the message in order to close the stream.
            Stream attachmentStream = GetAssetFileStream("Assets\\attachment.pdf");
            using (var attachmentContent = new StreamContent(attachmentStream))
            {
                attachmentContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
				HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndpoint)
                {
                    Content = new MultipartFormDataContent
                            {
                                {new StringContent(attachmentHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
                                {attachmentContent, attachmentPartName}
                            }
                };
                // Must send the request within the using block, or the attachment file stream will have been disposed.
                await SendCreatePageRequest(createMessage);
            }
        }

        #endregion

        #region Open OneNote Hyperlink

        ///
        /// Open the created page in the OneNote app
        ///
        private async void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (_response as CreateSuccessResponse != null)
            {
                CreateSuccessResponse successResponse = (CreateSuccessResponse)_response;
                await Windows.System.Launcher.LaunchUriAsync(FormulatePageUri(successResponse.OneNoteClientUrl));
            }
        }

        ///
        /// Formulate the OneNoteClientUrl so that we can open the OneNote app directly
        ///
        /// <param name="oneNoteClientUrl">The OneNoteClientUrl received in the API JSON response</param>
        private static Uri FormulatePageUri(string oneNoteClientUrl)
        {
            // Regular expression for identifying GUIDs in the URL returned by the server.
            // We need to wrap such GUIDs in curly braces before sending them to OneNote.
            Regex guidRegex = new Regex(@"=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})&",
                RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
            if (!String.IsNullOrEmpty(oneNoteClientUrl))
            {
                var matches = guidRegex.Matches(oneNoteClientUrl);
                if (matches.Count == 2)
                {
                    oneNoteClientUrl =
                        oneNoteClientUrl.Replace(matches[0].Groups[1].Value, "{" + matches[0].Groups[1].Value + "}")
                            .Replace(matches[1].Groups[1].Value, "{" + matches[1].Groups[1].Value + "}");
                }
                return new Uri(oneNoteClientUrl);
            }
            return null;
        }

        #endregion

        #region LiveSDK authentication/token refresh

        ///
        /// This method is called when the Live session status changes
        ///
        private void OnSessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            switch (e.Status)
            {
                case LiveConnectSessionStatus.Connected:
                    _accessToken = e.Session.AccessToken;
                    _accessTokenExpiration = e.Session.Expires;
                    _refreshToken = e.Session.RefreshToken;

                    SetCreateButtonsEnabled(true);
                    infoTextBlock.Text = "Authentication successful";
                    break;
                case LiveConnectSessionStatus.NotConnected:
                    SetCreateButtonsEnabled(false);
                    infoTextBlock.Text = "Authentication failed.";
                    break;
                default:
                    SetCreateButtonsEnabled(false);
                    infoTextBlock.Text = "Not Authenticated";
                    break;
            }
        }

        ///
        /// This method tries to refresh the token if it expires. The authentication token needs to be
        /// refreshed continuosly, so that the user is not prompted to sign in again
        ///
        /// <returns></returns>
        private async Task AttemptAccessTokenRefresh()
        {
            var createMessage = new HttpRequestMessage(HttpMethod.Post, MsaTokenRefreshUrl)
            {
                Content = new StringContent(
                    String.Format(CultureInfo.InvariantCulture, TokenRefreshRequestBody,
                        Resources["ClientId"],
                        TokenRefreshRedirectUri,
                        _refreshToken),
                    System.Text.Encoding.UTF8,
                    TokenRefreshContentType)
            };

            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.SendAsync(createMessage);
            await ParseRefreshTokenResponse(response);
        }

        ///
        /// Handle the RegreshToken response
        ///
        /// <param name="response">The HttpResponseMessage from the TokenRefresh request</param>
        private async Task ParseRefreshTokenResponse(HttpResponseMessage response)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                _accessToken = responseObject.access_token;
                _accessTokenExpiration = _accessTokenExpiration.AddSeconds((double)responseObject.expires_in);
                _refreshToken = responseObject.refresh_token;
            }
        }

        #endregion

        #region Helper functions

        ///
        /// Get date in ISO8601 format with local timezone offset
        ///
        /// <returns>Date as ISO8601 string</returns>
        private static string GetDate()
        {
            return DateTime.Now.ToString("o");
        }

        ///
        /// Get an asset file packaged with the application and return it as a managed stream
        ///
        /// <param name="assetFile">The path name of an asset relative to the application package root</param>
        /// <returns>A managed stream of the asset file data, opened for read</returns>
        private static Stream GetAssetFileStream(string assetFile)
        {
            StreamResourceInfo resource = Application.GetResourceStream(new Uri(assetFile, UriKind.Relative));
            return resource.Stream;
        }

        ///
        /// Refreshes the live authentication token if it has expired
        ///
        private async Task RefreshAuthTokenIfNeeded()
        {
            if (_accessTokenExpiration.CompareTo(DateTimeOffset.UtcNow) <= 0)
            {
                infoTextBlock.Text = "Access token needs to be refreshed";
                await AttemptAccessTokenRefresh();
            }
            infoTextBlock.Text = "Sending Request...";
            hyperlinkCreatedPage.Visibility = Visibility.Collapsed;
        }

        ///
        /// Update the UI after a create page request, depending on if it was
        /// successful or not
        ///
        /// <param name="response">The HttpResponseMessage from the create page request</param>
        private void UpdateUIAfterRequest(HttpResponseMessage response)
        {
            if (response.StatusCode == HttpStatusCode.Created)
            {
                infoTextBlock.Text = "Page successfully created.";
                hyperlinkCreatedPage.Visibility = Visibility.Visible;
            }
            else
            {
                infoTextBlock.Text = "Page creation failed with error code: " + response.StatusCode;
                hyperlinkCreatedPage.Visibility = Visibility.Collapsed;
            }
        }

        ///
        /// Parse the OneNote Service API create page response
        ///
        /// <param name="response">The HttpResponseMessage from the create page request</param>
        private async static Task<StandardResponse> ParseResponse(HttpResponseMessage response)
        {
            StandardResponse standardResponse;
            if (response.StatusCode == HttpStatusCode.Created)
            {
                dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                standardResponse = new CreateSuccessResponse
                {
                    StatusCode = response.StatusCode,
                    OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
                    OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
                };
            }
            else
            {
                standardResponse = new StandardErrorResponse
                {
                    StatusCode = response.StatusCode,
                    Message = await response.Content.ReadAsStringAsync()
                };
            }

            // Extract the correlation id.  Apps should log this if they want to collect data to diagnose failures with Microsoft support
            IEnumerable<string> correlationValues;
            if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues))
            {
                standardResponse.CorrelationId = correlationValues.FirstOrDefault();
            }

            return standardResponse;
        }

        ///
        /// Change "create page" buttons to enabled/disabled
        ///
        /// <param name="shouldBeEnabled">A bool value indicating if the buttons should be enabled</param>
        private void SetCreateButtonsEnabled(bool shouldBeEnabled)
        {
            btn_CreateSimple.IsEnabled = shouldBeEnabled;
            btn_CreateWithHtml.IsEnabled = shouldBeEnabled;
            btn_CreateWithImage.IsEnabled = shouldBeEnabled;
            btn_CreateWithUrl.IsEnabled = shouldBeEnabled;
			btn_CreateWithAttachmentAndPdfRendering.IsEnabled = shouldBeEnabled;
        }

        #endregion

		private void sectionName_GotFocus(object sender, RoutedEventArgs e)
		{
			string currentFieldValue = textBox_sectionName.Text;
			if (SectionNameHint.Equals(currentFieldValue))
			{
				textBox_sectionName.Text = string.Empty;
			}
		}

		private void sectionName_Change(object sender, System.Windows.Controls.TextChangedEventArgs e)
		{
			sectionName = textBox_sectionName.Text;
		}

		private void sectionName_LostFocus(object sender, RoutedEventArgs e)
		{
			string newValue = textBox_sectionName.Text;
			if (String.IsNullOrWhiteSpace(newValue))
			{
				sectionName = string.Empty;
				textBox_sectionName.Text = SectionNameHint;
			}
			else
			{
				sectionName = newValue;
			}
		}
    }
}


text:
package ai.wit.eval.wit_eval;

/**
 * Created by Nekrothunder on 29/11/2014.
 */

        import java.util.ArrayList;
        import java.util.Iterator;

        import org.apache.http.NameValuePair;
        import org.apache.http.message.BasicNameValuePair;
        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;

        import android.app.Activity;
        import android.os.Handler;
        import android.os.Message;
        import android.view.View;
        import android.widget.Toast;

public class ServerManager {

    private static String SERVER_URL="http://logtomobile.com/leonid/src/talk_xml.php";

    /**
     * carica la carta della categoria desiderata
     * @param outputActivity
     * @param textToSend

     */
    public static void callLeonidService(final MainActivity outputActivity,String textToSend){

        Handler handler;
        handler = new Handler(){

            @Override
            public void handleMessage(Message msg)
            {
                String errors="";
                switch (msg.what)
                {
                    case HttpPostThread.SUCCESS:

                        System.out.println(msg.toString());
                        String answer=msg.toString();
                         answer = answer.split("<odp>")[1];
                        System.out.println("***********"+answer);
                        answer=answer.split("</odp>")[0];

                        if (answer != null)
                        {
                            outputActivity.mLeonidAnswer=answer;
                            outputActivity.utterLeonidAnswer();
                        }
                        break;

                    case HttpPostThread.FAILURE:

                        errors=" "+msg.what;
                        System.out.println(msg.what);
                        // do some error handling
                        break;

                    default:
                        break;
                }/*fine switch*/
            }/*fine handleMessage*/

        };

        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("Pytanie", textToSend));
        pairs.add(new BasicNameValuePair("Submit","submit"));/*not needed*/
        HttpPostThread thread = new  HttpPostThread(SERVER_URL,pairs, handler);
        thread.start();

    }

}


text:
landlab.graph.matrix.ext package
================================

Submodules
----------

landlab.graph.matrix.ext.at_patch module
----------------------------------------

.. automodule:: landlab.graph.matrix.ext.at_patch
    :members:
    :undoc-members:
    :show-inheritance:

landlab.graph.matrix.ext.matrix module
--------------------------------------

.. automodule:: landlab.graph.matrix.ext.matrix
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: landlab.graph.matrix.ext
    :members:
    :undoc-members:
    :show-inheritance:


text:
//set up the theme switcher on the homepage
$('div').live('pagecreate',function(event){
if( !$(this).is('.ui-dialog')){
var appendEl = $(this).find('.ui-footer:last');
if( !appendEl.length ){
appendEl = $(this).find('.ui-content');
}
if( appendEl.is("[data-position]") ){
return;
}
$('Switch theme')
.buttonMarkup({
'icon':'gear',
'inline': true,
'shadow': false,
'theme': 'd'
})
.appendTo( appendEl )
.wrap('
')
.bind( "vclick", function(){
$.themeswitcher();
});
}
});
//collapse page navs after use
$(function(){
$('body').delegate('.content-secondary .ui-collapsible-content', 'click', function(){
$(this).trigger("collapse");
});
});
function setDefaultTransition(){
var winwidth = $( window ).width(),
trans ="slide";
if( winwidth >= 1000 ){
trans = "none";
}
else if( winwidth >= 650 ){
trans = "fade";
}
$.mobile.defaultPageTransition = trans;
}
$(function(){
setDefaultTransition();
$( window ).bind( "throttledresize", setDefaultTransition );
});
// Turn off AJAX for local file browsing
if ( location.protocol.substr(0,4) === 'file' ||
location.protocol.substr(0,11) === '*-extension' ||
location.protocol.substr(0,6) === 'widget' ) {
// Start with links with only the trailing slash and that aren't external links
var fixLinks = function() {
$( "a[href$='/'], a[href='.'], a[href='..']" ).not( "[rel='external']" ).each( function() {
this.href = $( this ).attr( "href" ).replace( /\/$/, "" ) + "/index.html";
});
};
// fix the links for the initial page
$(fixLinks);
// fix the links for subsequent ajax page loads
$(document).bind( 'pagecreate', fixLinks );
// Check to see if ajax can be used. This does a quick ajax request and blocks the page until its done
$.ajax({
url: '.',
async: false,
isLocal: true
}).error(function() {
// Ajax doesn't work so turn it off
$( document ).bind( "mobileinit", function() {
$.mobile.ajaxEnabled = false;
var message = $( '
' , {
'class': "ui-footer ui-bar-e",
style: "overflow: auto; padding:10px 15px;",
'data-ajax-warning': true
});
message
.append( "
Note: Navigation may not work if viewed locally
" )
.append( "
The AJAX-based navigation used throughout the jQuery Mobile docs may need to be viewed on a web server to work in certain browsers. If you see an error message when you click a link, try a different browser or view help.
" );
$( document ).bind( "pagecreate", function( event ) {
$( event.target ).append( message );
});
});
});
}


text:
<title>dlib C++ Library - svm_c_linear_trainer_abstract.h</title>

// Copyright (C) 2010  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_SVM_C_LiNEAR_TRAINER_ABSTRACT_Hh_
#ifdef DLIB_SVM_C_LiNEAR_TRAINER_ABSTRACT_Hh_

#include "../matrix/matrix_abstract.h"
#include "../algs.h"
#include "function_abstract.h"
#include "kernel_abstract.h"
#include "sparse_kernel_abstract.h"

namespace dlib
{
    template <
        typename K
        >
    class svm_c_linear_trainer
    {
        /*!
            REQUIREMENTS ON K
                Is either linear_kernel or sparse_linear_kernel.

            WHAT THIS OBJECT REPRESENTS
                This object represents a tool for training the C formulation of
                a support vector machine.  It is optimized for the case where
                linear kernels are used.

                In particular, it is implemented using the OCAS algorithm
                described in the following paper:
                    Optimized Cutting Plane Algorithm for Large-Scale Risk Minimization
                        Vojtech Franc, Soren Sonnenburg; Journal of Machine Learning
                        Research, 10(Oct):2157--2192, 2009.
        !*/

    public:
        typedef K kernel_type;
        typedef typename kernel_type::scalar_type scalar_type;
        typedef typename kernel_type::sample_type sample_type;
        typedef typename kernel_type::mem_manager_type mem_manager_type;
        typedef decision_function<kernel_type> trained_function_type;

        svm_c_linear_trainer (
        );
        /*!
            ensures
                - This object is properly initialized and ready to be used
                  to train a support vector machine.
                - #get_oca() == oca() (i.e. an instance of oca with default parameters)
                - #get_c_class1() == 1
                - #get_c_class2() == 1
                - #get_epsilon() == 0.001
                - this object will not be verbose unless be_verbose() is called
                - #get_max_iterations() == 10000
                - #learns_nonnegative_weights() == false
                - #force_last_weight_to_1() == false
                - #has_prior() == false
        !*/

        explicit svm_c_linear_trainer (
            const scalar_type& C
        );
        /*!
            requires
                - C > 0
            ensures
                - This object is properly initialized and ready to be used
                  to train a support vector machine.
                - #get_oca() == oca() (i.e. an instance of oca with default parameters)
                - #get_c_class1() == C
                - #get_c_class2() == C
                - #get_epsilon() == 0.001
                - this object will not be verbose unless be_verbose() is called
                - #get_max_iterations() == 10000
                - #learns_nonnegative_weights() == false
                - #force_last_weight_to_1() == false
                - #has_prior() == false
        !*/

        void set_epsilon (
            scalar_type eps
        );
        /*!
            requires
                - eps > 0
            ensures
                - #get_epsilon() == eps
        !*/

        const scalar_type get_epsilon (
        ) const;
        /*!
            ensures
                - returns the error epsilon that determines when training should stop.
                  Smaller values may result in a more accurate solution but take longer to
                  train.  You can think of this epsilon value as saying "solve the
                  optimization problem until the probability of misclassification is within
                  epsilon of its optimal value".
        !*/

        void set_max_iterations (
            unsigned long max_iter
        );
        /*!
            ensures
                - #get_max_iterations() == max_iter
        !*/

        unsigned long get_max_iterations (
        );
        /*!
            ensures
                - returns the maximum number of iterations the SVM optimizer is allowed to
                  run before it is required to stop and return a result.
        !*/

        void be_verbose (
        );
        /*!
            ensures
                - This object will print status messages to standard out so that a
                  user can observe the progress of the algorithm.
        !*/

        void be_quiet (
        );
        /*!
            ensures
                - this object will not print anything to standard out
        !*/

        void set_oca (
            const oca& item
        );
        /*!
            ensures
                - #get_oca() == item
        !*/

        const oca get_oca (
        ) const;
        /*!
            ensures
                - returns a copy of the optimizer used to solve the SVM problem.
        !*/

        const kernel_type get_kernel (
        ) const;
        /*!
            ensures
                - returns a copy of the kernel function in use by this object.  Since
                  the linear kernels don't have any parameters this function just
                  returns kernel_type()
        !*/

        bool learns_nonnegative_weights (
        ) const;
        /*!
            ensures
                - The output of training is a weight vector and a bias value.  These
                  two things define the resulting decision function.  That is, the
                  decision function simply takes the dot product between the learned
                  weight vector and a test sample, then subtracts the bias value.
                  Therefore, if learns_nonnegative_weights() == true then the resulting
                  learned weight vector will always have non-negative entries.  The
                  bias value may still be negative though.
        !*/

        void set_learns_nonnegative_weights (
            bool value
        );
        /*!
            ensures
                - #learns_nonnegative_weights() == value
                - if (value == true) then
                    - #has_prior() == false
        !*/

        void set_prior (
            const trained_function_type& prior
        );
        /*!
            requires
                - prior == a function produced by a call to this class's train() function.
                  Therefore, it must be the case that:
                    - prior.basis_vectors.size() == 1
                    - prior.alpha(0) == 1
            ensures
                - Subsequent calls to train() will try to learn a function similar to the
                  given prior.
                - #has_prior() == true
                - #learns_nonnegative_weights() == false
                - #forces_last_weight_to_1() == false
        !*/

        bool has_prior (
        ) const
        /*!
            ensures
                - returns true if a prior has been set and false otherwise.  Having a prior
                  set means that you have called set_prior() and supplied a previously
                  trained function as a reference.  In this case, any call to train() will
                  try to learn a function that matches the behavior of the prior as close
                  as possible but also fits the supplied training data.  In more technical
                  detail, having a prior means we replace the ||w||^2 regularizer with one
                  of the form ||w-prior||^2 where w is the set of parameters for a learned
                  function.
        !*/

        bool forces_last_weight_to_1 (
        ) const;
        /*!
            ensures
                - returns true if this trainer has the constraint that the last weight in
                  the learned parameter vector must be 1.  This is the weight corresponding
                  to the feature in the training vectors with the highest dimension.
                - Forcing the last weight to 1 also disables the bias and therefore the b
                  field of the learned decision_function will be 0 when forces_last_weight_to_1() == true.
        !*/

        void force_last_weight_to_1 (
            bool should_last_weight_be_1
        );
        /*!
            ensures
                - #forces_last_weight_to_1() == should_last_weight_be_1
                - if (should_last_weight_be_1 == true) then
                    - #has_prior() == false
        !*/

        void set_c (
            scalar_type C
        );
        /*!
            requires
                - C > 0
            ensures
                - #get_c_class1() == C
                - #get_c_class2() == C
        !*/

        const scalar_type get_c_class1 (
        ) const;
        /*!
            ensures
                - returns the SVM regularization parameter for the +1 class.
                  It is the parameter that determines the trade off between
                  trying to fit the +1 training data exactly or allowing more errors
                  but hopefully improving the generalization of the resulting
                  classifier.  Larger values encourage exact fitting while
                  smaller values of C may encourage better generalization.
        !*/

        const scalar_type get_c_class2 (
        ) const;
        /*!
            ensures
                - returns the SVM regularization parameter for the -1 class.
                  It is the parameter that determines the trade off between
                  trying to fit the -1 training data exactly or allowing more errors
                  but hopefully improving the generalization of the resulting
                  classifier.  Larger values encourage exact fitting while
                  smaller values of C may encourage better generalization.
        !*/

        void set_c_class1 (
            scalar_type C
        );
        /*!
            requires
                - C > 0
            ensures
                - #get_c_class1() == C
        !*/

        void set_c_class2 (
            scalar_type C
        );
        /*!
            requires
                - C > 0
            ensures
                - #get_c_class2() == C
        !*/

        template <
            typename in_sample_vector_type,
            typename in_scalar_vector_type
            >
        const decision_function<kernel_type> train (
            const in_sample_vector_type& x,
            const in_scalar_vector_type& y
        ) const;
        /*!
            requires
                - is_learning_problem(x,y) == true
                  (Note that it is ok for x.size() == 1)
                - All elements of y must be equal to +1 or -1
                - x == a matrix or something convertible to a matrix via mat().
                  Also, x should contain sample_type objects.
                - y == a matrix or something convertible to a matrix via mat().
                  Also, y should contain scalar_type objects.
                - if (has_prior()) then
                    - The vectors in x must have the same dimensionality as the vectors
                      used to train the prior given to set_prior().
            ensures
                - trains a C support vector classifier given the training samples in x and
                  labels in y.
                - returns a decision function F with the following properties:
                    - F.alpha.size() == 1
                    - F.basis_vectors.size() == 1
                    - F.alpha(0) == 1
                    - if (new_x is a sample predicted have +1 label) then
                        - F(new_x) >= 0
                    - else
                        - F(new_x) < 0
        !*/

        template <
            typename in_sample_vector_type,
            typename in_scalar_vector_type
            >
        const decision_function<kernel_type> train (
            const in_sample_vector_type& x,
            const in_scalar_vector_type& y,
            scalar_type& svm_objective
        ) const;
        /*!
            requires
                - is_learning_problem(x,y) == true
                  (Note that it is ok for x.size() == 1)
                - All elements of y must be equal to +1 or -1
                - x == a matrix or something convertible to a matrix via mat().
                  Also, x should contain sample_type objects.
                - y == a matrix or something convertible to a matrix via mat().
                  Also, y should contain scalar_type objects.
                - if (has_prior()) then
                    - The vectors in x must have the same dimensionality as the vectors
                      used to train the prior given to set_prior().
            ensures
                - trains a C support vector classifier given the training samples in x and
                  labels in y.
                - #svm_objective == the final value of the SVM objective function
                - returns a decision function F with the following properties:
                    - F.alpha.size() == 1
                    - F.basis_vectors.size() == 1
                    - F.alpha(0) == 1
                    - if (new_x is a sample predicted have +1 label) then
                        - F(new_x) >= 0
                    - else
                        - F(new_x) < 0
        !*/

    };

}

#endif // DLIB_SVM_C_LiNEAR_TRAINER_ABSTRACT_Hh_


text:
GenPHP
======
GenPHP is a powerful, flexible PHP code/project generator,
which helps you avoid repeating jobs.

GenPHP can generate anything you defined in the flavor,
In the generator class, you can use the simple generator API to generate your code.

By using GenPHP, you can also seperate your global generator (`~/.genphp/flavors`), project-scope generator (`./flavors`).

GenPHP is using Twig template engine from Symfony.

[![Build Status](https://secure.travis-ci.org/c9s/GenPHP.png)](http://travis-ci.org/c9s/GenPHP)

![](https://github.com/c9s/GenPHP/raw/master/screenshots/screenshot01.png)

Requirements
------------
- PHP5.3

Installation
------------
Copy this line to install genphp:

    $ curl https://raw.github.com/c9s/GenPHP/master/scripts/install.sh | bash

Install built-in flavors
------------------------

    $ git clone https://github.com/c9s/GenPHP-Flavors ~/.genphp/flavors

## Usage

After installation, you can run `list` command to list your flavors,
You can put your flavor (generator) in global flavor path (`~/.genphp/flavors`) or
your current project flavor path (`./flavors` or `./.flavors`), for example:

    ~GenPHP $ genphp list

    Available flavors:
        command     flavors
        flavor      flavors
        operation   flavors
        phpunit     flavors
        project     flavors
        flavor      /Users/c9s/.genphp/flavors
        phpunit     /Users/c9s/.genphp/flavors

### Creating New Flavors

The concept of GenPHP is pretty simple, when you run `genphp new`, it first initialize a flavor loader,
then use the flavor loader to look up matched flavor from several locations.

The loaded flavor instance initializes a generator (which can be GenericGenerator, or BaseGenerator) to generate the stuff
from the flavor resource directory to the destination directory. your
generator class works between the flavor resource directory and the destination
directory.

#### Creating Flavor

To create your flavor from your codebase in your project, type:

    $ cd your_project
    $ mkdir flavors
    $ genphp new flavor foo ~/path/to/codebase

    Loading flavor...
    Inializing option specs...
    Running generator...
        create        flavors/foo/Resource
        create        flavors/foo/Resource/file1
        create        flavors/foo/Resource/file2
        create        flavors/foo/Resource/file3
    Done

You can see those created files files here, it's using GenericGenerator to copy
`flavors/foo/Resource` to current directory.

Now you can put your own files (used by generator) into the `Resource` directory.

#### Customizing Your Flavor and Generator

For more complex usage, to create your own generator, just run:

    $ genphp new flavor foo

    Loading flavor...
    Inializing option specs...
    Running generator...
        create        flavors/foo/Resource
        render        flavors/foo/Generator.php
    Done

Create new flavor without codebase path, then open the `Generator.php` file, write your
generator actions in the `generate` function.

```php
class Generator {

    public function brief() { return 'your generator brief'; }

    public function generate($argument1,$argument2)
    {
        // do your operations here
        $this->copyDir('etc','etc');
    }
}
```

Put your favorite files into `flavors/foo/Resource`, then you can write operation code in PHP.

#### Testing Your Flavor

Once you have done, You can run `new` command to generate your flavor:

    $ genphp new foo argument1 argument2

And your code is generated.

If you want your flavor be global (system-wide), you can run install command:

    $ genphp install flavors/foo

This installs flavor to your global flavor path.

### Using Operation

GenPHP provides a lot of useful operations for you to write generation tasks very easily.

#### CopyOperation

To copy directory recursively from flavors/foo/Resource/from/path to to/path

```php
$this->copyDir('from/path','to/path');
```

#### TouchOperation

To touch a file

```php
$this->touch('path/to/touch');
```

#### CreateOperation

To create a new file with content

```php
$this->create('path/to/file', 'file content' );
```

#### CopyOperation

To copy a file, copy path/file1 from Resource dir to file2

```php
$this->copy( 'path/file1' , 'file2' );
```

#### CreateDirOperation

To create a directory:

```php
$this->createDir( 'path/to/directory' );
```

#### RenderOperation

To load templateName.php.twig template from flavors/foo/Resource
and render the code template with variables to a file:

```php
$this->render('templateName.php.twig','path/to/file', array(
    'className' => $className
));
```

#### WriteJsonOperation

To write a json file

```php
$this->writeJson('file.json', array( 'name' => 'John' ) );  // executes WriteJsonOperation
```

#### WriteYamlOperation

To write a yaml file

```php
$this->writeYaml('file.yaml', array( 'name' => 'John' ) );  // executes WriteJsonOperation
```

#### GitCloneOperation

To clone/pull a git repository:
```php
$this->gitClone( 'git@github.com:.....git' , 'path/to/repo' );
```

#### HgCloneOperation

To clone/pull a hg repository:
```php
$this->hgClone( 'hg uri' , 'path/to/repo' );
```

Command Usage
-------------

To generate a generic PHP project structure, GenPHP provides a built-in
template for this:

```bash
$ genphp new project Foo

    create
    create      src
    create      src/Foo.php
    create      src/Foo
    dependency ant
    create      build.xml
    dependency phpunit
    create      phpunit.xml.dist
    create      tests
```

genphp looks for flavor in `./flavors`, `./.flavors`, `~/.genphp/flavors`, you
can define your generator in those paths.

to generate a new flavor:

```bash
$ genphp new flavor flavorName
```

To generate a new flavor from current existing code base:

```bash
$ genphp new flavor ProjectA ~/path/to/OneProject
```

To list schemas

```bash
$ genphp list
```

please check `./flavors` directory of this repository
for more details.

## Flavor API

```php
$path = $flavor->path( 'license' );

```

## Generator Runner

```php
$loader = new \Flavor\FlavorLoader;
$flavor = $loader->load( $flavorName );
$generator = $flavor->getGenerator();
$generator->setLogger( $this->getLogger() );

$args = func_get_args();
array_shift($args);

$runner = new \GenPHP\GeneratorRunner;
$runner->logger = $logger;
$runner->run($generator,$args);
```

## Generator API

```php
public fucntion generate($argument1,$argument2, ... )
{
    $file = $this->flavorLoader->load('license')->path('LICENSE.GPL2');
    $this->copy($file, 'LICENSE' );
    $this->copyDir( );
}
```

### Operations
By using built-in operations, you can create your code generator very easily,
for example, the built-in flavor code generator from GenPHP:

```php
namespace flavor;
use GenPHP\Flavor\BaseGenerator;
use GenPHP\Path;

class Generator extends BaseGenerator
{
    public function brief() {
        return "Default Flavor";
    }

    public function generate($name)
    {
        $paths = Path::get_flavor_paths();
        foreach( $paths as $path ) {
            if( file_exists($path) ) {
                $base = $path . DIRECTORY_SEPARATOR . $name;
                $this->createDir( $base . DIRECTORY_SEPARATOR . "Resource");
                $this->render( 'Generator.php.twig',
                    $base . DIRECTORY_SEPARATOR . 'Generator.php',
                    array( 'name' => $name ) );
            }
        }

    }
}
```

Operation name magic:

```php
// executes CopyDirOperation
$this->copyDir('from/path','to/path');

// executes TouchOperation
$this->touch('path/to/touch');

// executes TouchOperation
$this->create('path/to/file', 'file content' );

// executes RenderOperation
$this->render('templateName.php.twig','path/to/file', array(
    'className' => $className
));

// executes WriteJsonOperation
$this->writeJson('file.json', array( ... ) );  // executes WriteJsonOperation
```

GenPHP supports many operations:

- CopyDirOperation
- CopyOperation
- CreateDirOperation
- CreateOperation
- RenderOperation
- TouchOperation
- WriteJsonOperation
- WriteYamlOperation

## Development

- Fork this probject on GitHub
- Git clone it:

    $ git clone git@github.com:{{ your Id }}/GenPHP.git

- Install onion <http://github.com/c9s/Onion>
- run `onion bundle` to install PEAR dependencies.
- run `scripts/genphp` to test your genphp script.
- run `phpunit` to run the test suites.
- run `scripts/compile.sh` to compile whole library into a executable phar file.

### Create New Opeartion

There is a flavor for creating new opeartion already, just run:

    $ ./scripts/genphp new operation DoSomething

### Create New Flavor

    $ ./scripts/genphp new flavor flavor_name

### IRC

Join us on irc channel: #genphp on irc.freenode.net

## Reference
* newgem: http://newgem.rubyforge.org/
* Rails: http://guides.rubyonrails.org/command\_line.html


text:
package com.endikaiglesias.alertacobertura;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by endikaig on 1/12/14.
 */
public class BBDD extends SQLiteOpenHelper {
    //Sentencia SQL para crear la tabla de Usuarios
    String sqlCreate = "CREATE TABLE historial (estado TEXT, fecha TEXT)";
    String sqlCreateO = "CREATE TABLE opciones (id TEXT, value TEXT)";

    public BBDD(Context context,CursorFactory factory) {
        super(context, "DBalerta_cobertura", factory, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Se ejecuta la sentencia SQL de creaci\u00f3n de la tabla
        db.execSQL(sqlCreate);
        db.execSQL(sqlCreateO);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
        //NOTA: Por simplicidad del ejemplo aqu\u00ed utilizamos directamente la opci\u00f3n de
        //      eliminar la tabla anterior y crearla de nuevo vac\u00eda con el nuevo formato.
        //      Sin embargo lo normal ser\u00e1 que haya que migrar datos de la tabla antigua
        //      a la nueva, por lo que este m\u00e9todo deber\u00eda ser m\u00e1s elaborado.

        //Se elimina la versi\u00f3n anterior de la tabla
        //db.execSQL("DROP TABLE IF EXISTS historial");
        db.execSQL("DROP TABLE IF EXISTS opciones");

        //Se crea la nueva versi\u00f3n de la tabla
        //db.execSQL(sqlCreate);
        db.execSQL(sqlCreateO);

        db.execSQL("INSERT INTO opciones (id, value) VALUES ('sonido', '1')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('vibrar', '1')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('tosta', '1')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('barra', '1')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('sonidoTipo', '0')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('autoinicio', '1')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('volumen', '20')");
        db.execSQL("INSERT INTO opciones (id, value) VALUES ('repetir', '0')");
    }

}


text:
import { Texture } from "./Texture";

export class Texture2D extends Texture {
    constructor(
        gl: WebGLRenderingContext,
        url?: string,
    ) {
        super(
            gl,
            url,
        );
    }

    public apply(gl: WebGLRenderingContext) {
        super.apply(gl);
        gl.texImage2D(this.target, 0, this.format, this.format, this.type, this.image);
        return this;
    }
}


text:
package org.lightadmin.logging.configurer.logback;

import java.util.List;
import java.util.Map;

/**
 * TODO: Document me!
 *
 * @author Maxim Kharchenko (kharchenko.max@gmail.com)
 */
public interface LoggerManager<LOGGER, LEVEL> {

    Map<String, String> getLoggerContextParameters();

    List<LOGGER> getLoggers();

    LOGGER changeLevel(String logger, LEVEL level);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Shared.Core.Context;
using Shared.Dtos.Users;
using PagedList;
using Server.Model;
using System.Linq.Expressions;
using Shared.Core.Context.Expressions;
using Shared.Core.Dtos.References;

namespace Server.Daos
{
    internal class UserDao : BaseDao
    {
        internal UserDao(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        /// <summary>
        /// Finds paged users.
        /// </summary>
        /// <param name="userFilterDto">The filtering DTO</param>
        /// <returns>The User DTO page</returns>
        internal IPagedList<UserDto> FindPaged(UserFilterDto userFilterDto)
        {
            return _modelContext.Set<User>()
                .Where(ExpressionBuilder.BuildWhere<User>(userFilterDto))
                .OrderBy(x => x.Surname)
                .Select(x => new UserDto() {
                    Id = x.Id,
                    FirstName = x.FirstName,
                    Surname = x.Surname,
                    Email = x.Email,
                    PaintingsCount = x.Paintings.Count
                })
                .ToPagedList(userFilterDto.Page, userFilterDto.PageSize);
        }

        /// <summary>
        /// Finds the user by prefix which is
        /// </summary>
        /// <param name="prefix">The prefix for search the users</param>
        /// <param name="selector">The specific selector</param>
        /// <returns>The list of the referenced DTOs</returns>
        internal List<ReferenceDto> FindByPrefix(string prefix, Expression<Func<User, ReferenceDto>> selector)
        {
            return _modelContext.Set<User>()
                .Where(x => x.FirstName.Contains(prefix) || x.Surname.Contains(prefix))
                .Select(selector)
                .ToList();
        }

        ///// <summary>
        ///// Finds max order value.
        ///// </summary>
        ///// <returns>The max value of the order column</returns>
        //internal int FindMaxOrderValue()
        //{
        //    return _modelContext.Set<User>()
        //        .Max(x => x.Order);
        //}

        ///// <summary>
        ///// Finds the User with the greater order than the specified ID.
        ///// </summary>
        ///// <param name="id">The ID of the User</param>
        ///// <param name="order">The order of the User</param>
        ///// <returns>The first User with the greater order.</returns>
        //internal User FindUserWithGreaterOrder(Guid id, int order)
        //{
        //    return _modelContext.Set<User>()
        //        .Where(x => x.Order > order)
        //        .OrderBy(x => x.Order)
        //        .FirstOrDefault();
        //}

        ///// <summary>
        ///// Finds the User with the lower order than the specified ID.
        ///// </summary>
        ///// <param name="id">The ID of the User</param>
        ///// <param name="order">The order of the User</param>
        ///// <returns>The first Use rwith the lower order</returns>
        //internal User FindUserWithLowerOrder(Guid id, int order)
        //{
        //    return _modelContext.Set<User>()
        //        .Where(x => x.Order < order)
        //        .OrderByDescending(x => x.Order)
        //        .FirstOrDefault();
        //}
    }
}


text:
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry
{

// Ring Identifier. It is currently: source,multi,ring
struct ring_identifier
{

    inline ring_identifier()
        : source_index(-1)
        , multi_index(-1)
        , ring_index(-1)
    {}

    inline ring_identifier(signed_size_type src,
                           signed_size_type mul,
                           signed_size_type rin)
        : source_index(src)
        , multi_index(mul)
        , ring_index(rin)
    {}

    inline bool operator<(ring_identifier const& other) const
    {
        return source_index != other.source_index ? source_index < other.source_index
            : multi_index !=other.multi_index ? multi_index < other.multi_index
            : ring_index < other.ring_index
            ;
    }

    inline bool operator==(ring_identifier const& other) const
    {
        return source_index == other.source_index
            && ring_index == other.ring_index
            && multi_index == other.multi_index
            ;
    }

#if defined(BOOST_GEOMETRY_DEBUG_IDENTIFIER)
    friend std::ostream& operator<<(std::ostream &os, ring_identifier const& ring_id)
    {
        os << "(s:" << ring_id.source_index;
        if (ring_id.ring_index >= 0) os << ", r:" << ring_id.ring_index;
        if (ring_id.multi_index >= 0) os << ", m:" << ring_id.multi_index;
        os << ")";
        return os;
    }
#endif

    signed_size_type source_index;
    signed_size_type multi_index;
    signed_size_type ring_index;
};

}} // namespace geofeatures_boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RING_IDENTIFIER_HPP


text:
export interface IBooksDatabase {
    getBooks: () => string[];
}

export class BooksDatabase implements IBooksDatabase {
    public getBooks() {
        return [
            'book1',
            'book2',
            'book3'
        ]
    }
}


text:
package connect.ui.activity.login;

/**
 * Created by pujin on 2017/5/19.
 */

public class StartTest {
}


text:
import logging
import sys

from nose.tools import assert_equal, assert_not_equal, assert_true, assert_false, assert_raises

from desktop.lib.exceptions_renderable import PopupException
from desktop.lib.django_test_util import make_logged_in_client
from useradmin.models import User

from impala.server import ImpalaDaemonApi, _get_impala_server_url

if sys.version_info[0] > 2:
  from unittest.mock import patch, Mock, MagicMock
else:
  from mock import patch, Mock, MagicMock

LOG = logging.getLogger(__name__)

class TestImpalaDaemonApi():

  def setUp(self):
    self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False)
    self.user = User.objects.get(username="test")

  def test_get_impala_server_url_when_no_session(self):
    assert_raises(PopupException, _get_impala_server_url, session=None)

  def test_digest_auth(self):

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          DAEMON_API_USERNAME_get.return_value = 'impala'
          DAEMON_API_PASSWORD_get.return_value = 'impala'

          server = ImpalaDaemonApi('localhost')

          server._client.set_digest_auth.assert_called()
          server._client.set_kerberos_auth.assert_not_called()
          server._client.set_basic_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          DAEMON_API_USERNAME_get.return_value = None
          DAEMON_API_PASSWORD_get.return_value = 'impala'

          server = ImpalaDaemonApi('localhost')

          server._client.set_digest_auth.assert_not_called()
          server._client.set_kerberos_auth.assert_not_called()
          server._client.set_basic_auth.assert_not_called()

  def test_basic_auth(self):

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.DAEMON_API_AUTH_SCHEME.get') as DAEMON_API_AUTH_SCHEME_get:
            DAEMON_API_USERNAME_get.return_value = 'impala'
            DAEMON_API_PASSWORD_get.return_value = 'impala'
            DAEMON_API_AUTH_SCHEME_get.return_value = 'basic'

            server = ImpalaDaemonApi('localhost')

            server._client.set_basic_auth.assert_called()
            server._client.set_digest_auth.assert_not_called()
            server._client.set_kerberos_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.DAEMON_API_AUTH_SCHEME.get') as DAEMON_API_AUTH_SCHEME_get:
            DAEMON_API_USERNAME_get.return_value = 'impala'
            DAEMON_API_PASSWORD_get.return_value = None
            DAEMON_API_AUTH_SCHEME_get.return_value = 'basic'

            server = ImpalaDaemonApi('localhost')

            server._client.set_basic_auth.assert_not_called()
            server._client.set_digest_auth.assert_not_called()
            server._client.set_kerberos_auth.assert_not_called()

  def test_kerberos_auth(self):

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.is_webserver_spnego_enabled') as is_webserver_spnego_enabled:

            DAEMON_API_USERNAME_get.return_value = 'impala'
            DAEMON_API_PASSWORD_get.return_value = 'impala'
            is_webserver_spnego_enabled.return_value = True

            server = ImpalaDaemonApi('localhost')

            server._client.set_digest_auth.assert_called()
            server._client.set_kerberos_auth.assert_not_called()
            server._client.set_basic_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.is_webserver_spnego_enabled') as is_webserver_spnego_enabled:

            DAEMON_API_USERNAME_get.return_value = None
            DAEMON_API_PASSWORD_get.return_value = 'impala'
            is_webserver_spnego_enabled.return_value = False

            server = ImpalaDaemonApi('localhost')

            server._client.set_digest_auth.assert_not_called()
            server._client.set_kerberos_auth.assert_not_called()
            server._client.set_basic_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.is_kerberos_enabled') as is_kerberos_enabled:
            DAEMON_API_USERNAME_get.return_value = None
            DAEMON_API_PASSWORD_get.return_value = None
            is_kerberos_enabled.return_value = True

            server = ImpalaDaemonApi('localhost')

            server._client.set_digest_auth.assert_not_called()
            server._client.set_kerberos_auth.assert_called()
            server._client.set_basic_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.is_webserver_spnego_enabled') as is_webserver_spnego_enabled:

            DAEMON_API_USERNAME_get.return_value = None
            DAEMON_API_PASSWORD_get.return_value = None
            is_webserver_spnego_enabled.return_value = True

            server = ImpalaDaemonApi('localhost')

            server._client.set_digest_auth.assert_not_called()
            server._client.set_kerberos_auth.assert_called()
            server._client.set_basic_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.is_kerberos_enabled') as is_kerberos_enabled:
            with patch('impala.server.is_webserver_spnego_enabled') as is_webserver_spnego_enabled:
              DAEMON_API_USERNAME_get.return_value = None
              DAEMON_API_PASSWORD_get.return_value = None
              is_kerberos_enabled.return_value = False
              is_webserver_spnego_enabled.return_value = False

              server = ImpalaDaemonApi('localhost')

              server._client.set_digest_auth.assert_not_called()
              server._client.set_kerberos_auth.assert_not_called()
              server._client.set_basic_auth.assert_not_called()

    with patch('impala.server.DAEMON_API_USERNAME.get') as DAEMON_API_USERNAME_get:
      with patch('impala.server.DAEMON_API_PASSWORD.get') as DAEMON_API_PASSWORD_get:
        with patch('impala.server.HttpClient') as HttpClient:
          with patch('impala.server.is_kerberos_enabled') as is_kerberos_enabled:
            with patch('impala.server.is_webserver_spnego_enabled') as is_webserver_spnego_enabled:
              DAEMON_API_USERNAME_get.return_value = None
              DAEMON_API_PASSWORD_get.return_value = None
              is_kerberos_enabled.return_value = True
              is_webserver_spnego_enabled.return_value = True

              server = ImpalaDaemonApi('localhost')

              server._client.set_digest_auth.assert_not_called()
              server._client.set_kerberos_auth.assert_called()
              server._client.set_basic_auth.assert_not_called()


text:
title: "Archive Layout with Content"
layout: archive
permalink: /archive-layout-with-content/
sitemap: false
---

A variety of common markup showing how the theme styles them.

# Header one

## Header two

### Header three

#### Header four

##### Header five

###### Header six

## Blockquotes

Single line blockquote:

> Stay hungry. Stay foolish.

Multi line blockquote with a cite reference:

> People think focus means saying yes to the thing you've got to focus on. But that's not what it means at all. It means saying no to the hundred other good ideas that there are. You have to pick carefully. I'm actually as proud of the things we haven't done as the things I have done. Innovation is saying no to 1,000 things.

Steve Jobs --- Apple Worldwide Developers' Conference, 1997
{: .small}

## Tables

| Employee         | Salary |                                                              |
| --------         | ------ | ------------------------------------------------------------ |
| [John Doe](#)    | $1     | Because that's all Steve Jobs needed for a salary.           |
| [Jane Doe](#)    | $100K  | For all the blogging she does.                               |
| [Fred Bloggs](#) | $100M  | Pictures are worth a thousand words, right? So Jane × 1,000. |
| [Jane Bloggs](#) | $100B  | With hair like that?! Enough said.                           |

| Header1 | Header2 | Header3 |
|:--------|:-------:|--------:|
| cell1   | cell2   | cell3   |
| cell4   | cell5   | cell6   |
|-----------------------------|
| cell1   | cell2   | cell3   |
| cell4   | cell5   | cell6   |
|=============================|
| Foot1   | Foot2   | Foot3   |

## Definition Lists

Definition List Title
:   Definition list division.

Startup
:   A startup company or startup is a company or temporary organization designed to search for a repeatable and scalable business model.

#dowork
:   Coined by Rob Dyrdek and his personal body guard Christopher "Big Black" Boykins, "Do Work" works as a self motivator, to motivating your friends.

Do It Live
:   I'll let Bill O'Reilly [explain](https://www.youtube.com/watch?v=O_HyZ5aW76c "We'll Do It Live") this one.

## Unordered Lists (Nested)

  * List item one
      * List item one
          * List item one
          * List item two
          * List item three
          * List item four
      * List item two
      * List item three
      * List item four
  * List item two
  * List item three
  * List item four

## Ordered List (Nested)

  1. List item one
      1. List item one
          1. List item one
          2. List item two
          3. List item three
          4. List item four
      2. List item two
      3. List item three
      4. List item four
  2. List item two
  3. List item three
  4. List item four

## Buttons

Make any link standout more when applying the `.btn` class.

```html
<a href="#" class="btn--success">Success Button</a>
```

[Primary Button](#){: .btn}
[Success Button](#){: .btn .btn--success}
[Warning Button](#){: .btn .btn--warning}
[Danger Button](#){: .btn .btn--danger}
[Info Button](#){: .btn .btn--info}
[Inverse Button](#){: .btn .btn--inverse}
[Light Outline Button](#){: .btn .btn--light-outline}

```markdown
[Primary Button Text](#link){: .btn}
[Success Button Text](#link){: .btn .btn--success}
[Warning Button Text](#link){: .btn .btn--warning}
[Danger Button Text](#link){: .btn .btn--danger}
[Info Button Text](#link){: .btn .btn--info}
[Inverse Button](#link){: .btn .btn--inverse}
[Light Outline Button](#link){: .btn .btn--light-outline}
```

[X-Large Button](#){: .btn .btn--x-large}
[Large Button](#){: .btn .btn--large}
[Default Button](#){: .btn}
[Small Button](#){: .btn .btn--small}

```markdown
[X-Large Button](#link){: .btn .btn--x-large}
[Large Button](#link){: .btn .btn--large}
[Default Button](#link){: .btn}
[Small Button](#link){: .btn .btn--small}
```

## Notices

**Watch out!** You can also add notices by appending `{: .notice}` to a paragraph.
{: .notice}

## HTML Tags

### Address Tag

<address>
  1 Infinite Loop
 Cupertino, CA 95014
 United States
</address>

### Anchor Tag (aka. Link)

This is an example of a [link](http://apple.com "Apple").

### Abbreviation Tag

The abbreviation CSS stands for "Cascading Style Sheets".

*[CSS]: Cascading Style Sheets

### Cite Tag

"Code is poetry." ---Automattic

### Code Tag

You will learn later on in these tests that `word-wrap: break-word;` will be your best friend.

### Strike Tag

This tag will let you strikeout text.

### Emphasize Tag

The emphasize tag should _italicize_ text.

### Insert Tag

This tag should denote inserted text.

### Keyboard Tag

This scarcely known tag emulates keyboard text, which is usually styled like the `<code>` tag.

### Preformatted Tag

This tag styles large blocks of code.

.post-title {
  margin: 0 0 5px;
  font-weight: bold;
  font-size: 38px;
  line-height: 1.2;
  and here's a line of some really, really, really, really long text, just to see how the PRE tag handles it and to find out how it overflows;
}

### Quote Tag

<q>Developers, developers, developers…</q> –Steve Ballmer

### Strong Tag

This tag shows **bold text**.

### Subscript Tag

Getting our science styling on with H2O, which should push the "2" down.

### Superscript Tag

Still sticking with science and Isaac Newton's E = MC2, which should lift the 2 up.

### Variable Tag

This allows you to denote <var>variables</var>.

{% include base_path %}
{% for post in site.pages %}
{% include archive-single.html %}
{% endfor %}


text:
// .NAME vtkImageCacheFilter - Caches multiple vtkImageData objects.

// .SECTION Description
// vtkImageCacheFilter keep a number of vtkImageDataObjects from previous
// updates to satisfy future updates without needing to update the input.  It
// does not change the data at all.  It just makes the pipeline more
// efficient at the expense of using extra memory.

#ifndef __vtkImageCacheFilter_h
#define __vtkImageCacheFilter_h

#include "vtkImageAlgorithm.h"

class vtkExecutive;

class VTK_IMAGING_EXPORT vtkImageCacheFilter : public vtkImageAlgorithm
{
public:
  static vtkImageCacheFilter *New();
  vtkTypeMacro(vtkImageCacheFilter,vtkImageAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // This is the maximum number of images that can be retained in memory.
  // it defaults to 10.
  void SetCacheSize(int size);
  int GetCacheSize();

protected:
  vtkImageCacheFilter();
  ~vtkImageCacheFilter();

  // Create a default executive.
  virtual vtkExecutive* CreateDefaultExecutive();
  virtual void ExecuteData(vtkDataObject *);

private:
  vtkImageCacheFilter(const vtkImageCacheFilter&);  // Not implemented.
  void operator=(const vtkImageCacheFilter&);  // Not implemented.
};

#endif


text:
package fate.webapp.blog.listener;

import java.util.Date;

public class SiteStatistics {

	/**
	 * 当前在线人数
	 */
	private static long online = 0;
	/**
	 * 历史最高在线人数
	 */
	private static long histrry_online = 0;
	/**
	 * 统计更新时间
	 */
	private static Date updateTime = new Date();
	/**
	 * 站点主题总数
	 */
	private static long theme = 0;
	/**
	 * 用户总数
	 */
	private static long user = 0;
	/**
	 * 评论总户
	 */
	private static long comment = 0;
	/**
	 * 搜索次数
	 */
	private static long search = 0;

	/**
	 * 浏览次数
	 */
	private static long views = 0;

	public static long getOnline() {
		return online;
	}

	public static void raise() {
		online++;
	}

	public static void reduce() {
		online--;
	}

	public static long getHistrry_online() {
		return histrry_online;
	}

	public static void setHistrry_online(long histrry_online) {
		SiteStatistics.histrry_online = histrry_online;
	}

	public static Date getUpdateTime() {
		return updateTime;
	}

	public static void setUpdateTime(Date updateTime) {
		SiteStatistics.updateTime = updateTime;
	}

	public static long getTheme() {
		return theme;
	}

	public static void setTheme(long theme) {
		SiteStatistics.theme = theme;
	}

	public static long getUser() {
		return user;
	}

	public static void setUser(long user) {
		SiteStatistics.user = user;
	}

	public static long getComment() {
		return comment;
	}

	public static void setComment(long comment) {
		SiteStatistics.comment = comment;
	}

	public static long getSearch() {
		return search;
	}

	public static void setSearch(long search) {
		SiteStatistics.search = search;
	}

	public static long getViews() {
		return views;
	}

	public static void setViews(long views) {
		SiteStatistics.views = views;
	}

}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Image;
use App\Wall;
use App\Pedigree;
use App\Message;
use App\Gallery;
use Validator;
use Auth;
use Redirect;

class UserController extends Controller
{

    /**
    *   Constante para el path a media
    */
    protected $custom_path = '../public/media/'; //->Desarrollo
    //protected $custom_path = '../public_html/media/'; //->Producción

    public function __construct()
    {
        $this->middleware('auth');

    }

    /**
     * [Devuelve el formulario de modificación de usuario]
     * @return [type] [description]
     */
    public function getForm()
    {
        $user = Auth::user();
        return view('users.home_modify_user', ['user' => $user]);
    }

    /**
     * [Modifica el usuario]
     * @param  Request $request [Datos del formulario]
     * @return [type]           [description]
     */
    public function modifyUser(Request $request)
    {
        $data = $request->all();
        $rules = [
            'name' => 'required|max:255',
            'surname' => 'required|max:255'
            //'user' => 'required|max:255|unique:users',
            //'email' => 'required|email|max:255|unique:users'
        ];
        $validator = Validator::make($data, $rules);
        if ($validator->fails())
        {
            //Redirect::back()->withErrors($validator->messages())->withInput();
            return Redirect::back()->withErrors($validator->messages())->withInput();
        }
        else {
            $user = User::find($data['id']);
            $user -> name = $data['name'];
            $user -> surname = $data['surname'];
            $user -> save();
            return redirect('/home')->with('message', 'Usuario modificado correctamente');
        }

    }

    //Devuelve la vista para dar de baja un usuario
    public function deleteAccount()
    {
        return view('users.user_delete_account');
    }

    //Función que elimina un usuario
    public function deleteUser()
    {
        $user = Auth::user();
        $pets = $user->pets;
        //Se borran todas las mascotas
        foreach ($pets as $key => $value) {
            //Se borran las fotos de la mascota y la galeria
            $gallery = $value->gallery;
            Image::where('idGaleria', '=', $gallery->id)->delete();
            $gallery->delete();
            //Se borran los mensajes y el muro de la mascota
            $wall = $value->wall;
            Message::where('idMuro', '=', $wall->id)->delete();
            Message::where('idMascota', '=', $value->id)->delete();
            $wall->delete();
            //Eliminar pedigree
            if($value->idPedigree != null)
            {
                Pedigree::where('id', '=', $value->idPedigree)->delete();
            }
            //Borrar carpeta
            $this->deleteDir($this->custom_path . $value->idUsuario.'/pets'.'/'.$value->id);
            $value->delete();
        }
        $this->deleteDir($this->custom_path . $user->id);
        $user->delete();
        return redirect('/');
    }

    /*-----------METODOS PRIVADOS----------------------*/

    /*Borrar directorio recursivamente*/
    private function deleteDir($carpeta)
    {
        foreach(glob($carpeta . '/*') as $archivos_carpeta)
        {
            //si es un directorio volvemos a llamar recursivamente
            if (is_dir($archivos_carpeta))
                $this->deleteDir($archivos_carpeta);
            else//si es un archivo lo eliminamos
            unlink($archivos_carpeta);
        }
        rmdir($carpeta);
    }

}


text:
package org.dpolivaev.mnemonicsetter;

import java.awt.event.KeyEvent;

import javax.swing.Action;

public class ActionNameMnemonicHolder implements INameMnemonicHolder {
	final private Action action;

	public ActionNameMnemonicHolder(final Action action) {
		super();
		this.action = action;
	}

	public String getText() {
		return (String) action.getValue(Action.NAME);
	}

	public void setDisplayedMnemonicIndex(final int mnemoSignIndex) {
		action.putValue("SwingDisplayedMnemonicIndexKey", mnemoSignIndex);

	}

	public void setMnemonic(final char charAfterMnemoSign) {
		final int keyCode = KeyEvent.getExtendedKeyCodeForChar((int) charAfterMnemoSign);
		setMnemonic(keyCode);
	}

	public void setMnemonic(final int keyCode) {
		action.putValue(Action.MNEMONIC_KEY,  keyCode);
	}

	public void setText(final String text) {
		action.putValue(Action.NAME, text);
	}

	@Override
	public int getMnemonic() {
		final Object mnemonic = action.getValue(Action.MNEMONIC_KEY);
		if(mnemonic instanceof Integer)
			return ((Integer)mnemonic).intValue();
		else
			return 0;
	}

	@Override
	public boolean hasAccelerator() {
		return action.getValue(Action.ACCELERATOR_KEY) != null;
	}
}