text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS110-2015S: Introduction to Computing
% Copyright 2015 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS110-2015S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def \topDirectory {../..}
\def \texDirectory {\topDirectory/src/main/tex}

\documentclass[10pt, compress]{beamer}

\usepackage{\texDirectory/template/style/directives}
\input{\texDirectory/template/config}
\usepackage{\texDirectory/template/style/beamerthemeUmassLecture}
\doc{number}{19}
%\setbeamertemplate{footline}[text line]{}

\begin{document}
\prepareCover

\section{Course Administration}

\begin{frame}[fragile]
\frametitle{Course Administration}
  \begin{block}{Announcements}
    \begin{itemize}
      \item[] Final Exam Practice released. Solutions will not be released.
      \item[] Final Exam review session to be held on May 12, 2015.
      \item[] Final Exam to be held on May 19, 2015 at 6:30 PM.
      \item[] Student evaluation on May 12, 2015. Please show up.
    \end{itemize}
  \end{block}
\end{frame}

\section*{Some Pieces of Advice From a Fellow Programmer}
\plain{}{Some Pieces of Advice\\From a Fellow Programmer}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    Programming is about thinking!
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    Computing problems are solved away from the keyboard.
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    Simple is always better.
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    10 percent of code for 90 percent of users\\
    90 percent of code for 10 percent of users
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    The \textbf{best} programming language is not invented yet.
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    90 percent of time for design,\\
    10 percent of time for the code
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    Always choose good names for your classes.
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    ``Let's make it run, we'll fix it later'' never works.
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    Comment your code.\\
    Unless you are really good at it.
  \end{center}
\end{frame}

\begin{frame}[fragile]
\frametitle{Some Pieces of Advice From a Fellow Programmer}
  \begin{center}
    Programming is on art and good programmers are impressionists.
  \end{center}
\end{frame}

\plain{}{Keep Calm\\and\\Enjoy Programming}

\end{document}


text:
#ifdef USE_TI_FILESYSTEM

#import "TiUtils.h"
#import "TiBlob.h"
#import "TiFilesystemFileProxy.h"
#import "TiFilesystemFileStreamProxy.h"

#define FILE_TOSTR(x) \
	([x isKindOfClass:[TiFilesystemFileProxy class]]) ? [(TiFilesystemFileProxy*)x nativePath] : [TiUtils stringValue:x]

@implementation TiFilesystemFileProxy

-(id)initWithFile:(NSString*)path_
{
	if (self = [super init])
	{
		fm = [[NSFileManager alloc] init];
		path = [path_ retain];
	}
	return self;
}

-(void)dealloc
{
	RELEASE_TO_NIL(fm);
	[super dealloc];
}

-(id)nativePath
{
	return [[NSURL fileURLWithPath:path] absoluteString];
}

-(id)exists:(id)args
{
	return NUMBOOL([fm fileExistsAtPath:path]);
}

#define FILEATTR(propName,attrKey,throwError) \
-(id) propName	\
{	\
	NSError *error = nil; \
	NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];\
	if ((throwError) && error!=nil)	\
	{	\
		[self throwException:TiExceptionOSError subreason:[error localizedDescription] location:CODELOCATION];	\
	}	\
	return [resultDict objectForKey:attrKey];\
}

FILEATTR(readonly,NSFileImmutable,NO)
FILEATTR(modificationTimestamp,NSFileModificationDate,YES);

-(id)createTimestamp
{
	NSError *error = nil;
	NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];
	if ((YES) && error!=nil)
	{
		[self throwException:TiExceptionOSError subreason:[error localizedDescription] location:CODELOCATION];
	}
	// Have to do this one up special because of 3.x bug where NSFileCreationDate is sometimes undefined
	id result = [resultDict objectForKey:NSFileCreationDate];
	if (result == nil) {
		result = [resultDict objectForKey:NSFileModificationDate];
	}
	return result;
}

//TODO: Should this be a method or a property? Until then, do both.
-(id)createTimestamp:(id)args
{
	return [self createTimestamp];
}

-(id)modificationTimestamp:(id)args
{
	return [self modificationTimestamp];
}

-(id)symbolicLink
{
	NSError *error = nil;
	NSDictionary * resultDict = [fm attributesOfItemAtPath:path error:&error];
	if (error!=nil)
	{
		[self throwException:TiExceptionOSError subreason:[error localizedDescription] location:CODELOCATION];
	}
	NSString * fileType = [resultDict objectForKey:NSFileType];

	return NUMBOOL([fileType isEqualToString:NSFileTypeSymbolicLink]);
}

-(id)writeable
{
	return NUMBOOL(![[self readonly] boolValue]);
}

-(id)writable
{
	NSLog(@"[WARN] The File.writable method is deprecated and should no longer be used. Use writeable instead.");
	return [self writeable];
}

#define FILENOOP(name) \
-(id)name\
{\
	return NUMBOOL(NO);\
}\

FILENOOP(executable);
FILENOOP(hidden);
FILENOOP(setReadonly:(id)x);
FILENOOP(setExecutable:(id)x);
FILENOOP(setHidden:(id)x);

-(id)getDirectoryListing:(id)args
{
	NSError * error=nil;
	NSArray * resultArray = [fm contentsOfDirectoryAtPath:path error:&error];
	if(error!=nil)
	{
		//TODO: what should be do?
	}
	return resultArray;
}

-(id)spaceAvailable:(id)args
{
	NSError *error = nil;
	NSDictionary * resultDict = [fm attributesOfFileSystemForPath:path error:&error];
	if (error!=nil) return NUMBOOL(NO);
	return [resultDict objectForKey:NSFileSystemFreeSize];
}

-(id)createDirectory:(id)args
{
	BOOL result = NO;
	if (![fm fileExistsAtPath:path])
	{
		BOOL recurse = args!=nil && [args count] > 0 ? [TiUtils boolValue:[args objectAtIndex:0]] : NO;
		result = [fm createDirectoryAtPath:path withIntermediateDirectories:recurse attributes:nil error:nil];
	}
	return NUMBOOL(result);
}

-(TiFilesystemFileStreamProxy *) open:(id) args {
	NSNumber *mode;
	ENSURE_ARG_AT_INDEX(mode, args, 0, NSNumber);
	ENSURE_VALUE_RANGE([mode intValue], TI_READ, TI_APPEND);

	NSArray *payload = [NSArray arrayWithObjects:[self path], mode, nil];

	return [[[TiFilesystemFileStreamProxy alloc] _initWithPageContext:[self executionContext] args:payload] autorelease];
}

-(id)createFile:(id)args
{
	BOOL result = NO;
	if(![fm fileExistsAtPath:path])
	{
		BOOL shouldCreate = args!=nil && [args count] > 0 ? [TiUtils boolValue:[args objectAtIndex:0]] : NO;
		if(shouldCreate)
		{
			[fm createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
			//We don't care if this fails.
		}
		result = [[NSData data] writeToFile:path options:0 error:nil];
	}
	return NUMBOOL(result);
}

-(id)deleteDirectory:(id)args
{
	BOOL result = NO;
	BOOL isDirectory = NO;
	BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDirectory];
	if (exists && isDirectory)
	{
		NSError * error = nil;
		BOOL shouldDelete = args!=nil && [args count] > 0 ? [TiUtils boolValue:[args objectAtIndex:0]] : NO;
		if (!shouldDelete)
		{
			NSArray * remainers = [fm contentsOfDirectoryAtPath:path error:&error];
			if(error==nil)
			{
				if([remainers count]==0)
				{
					shouldDelete = YES;
				}
			}
		}
		if(shouldDelete)
		{
			result = [fm removeItemAtPath:path error:&error];
		}
	}
	return NUMBOOL(result);
}

-(id)deleteFile:(id)args
{
	BOOL result = NO;
	BOOL isDirectory = YES;
	BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDirectory];
	if(exists && !isDirectory)
	{
		result = [fm removeItemAtPath:path error:nil];
	}
	return NUMBOOL(result);
}

-(NSString *)_grabFirstArgumentAsFileName_:(id)args {
    NSString * arg = [args objectAtIndex:0];
    NSString * file = FILE_TOSTR(arg);
	NSURL * fileUrl = [NSURL URLWithString:file];
	if([fileUrl isFileURL]){
		file = [fileUrl path];
	}
    NSString * dest = [file stringByStandardizingPath];

    return dest;
}

-(id)move:(id)args
{
	ENSURE_TYPE(args,NSArray);
	NSError * error=nil;
	NSString * dest = [self _grabFirstArgumentAsFileName_:args];

    if (![dest isAbsolutePath]) {
        NSString * subpath = [path stringByDeletingLastPathComponent];
        dest = [subpath stringByAppendingPathComponent:dest];
    }

	BOOL result = [fm moveItemAtPath:path toPath:dest error:&error];
	return NUMBOOL(result);
}

-(id)rename:(id)args
{
    ENSURE_TYPE(args,NSArray);
	NSString * dest = [self _grabFirstArgumentAsFileName_:args];
    NSString * ourSubpath = [path stringByDeletingLastPathComponent];

    if ([dest isAbsolutePath]) {
        NSString * destSubpath = [dest stringByDeletingLastPathComponent];

        if (![ourSubpath isEqualToString:destSubpath]) {
            return NUMBOOL(NO); // rename is not move
        }
    }

    return [self move:args];
}

-(id)read:(id)args
{
	BOOL exists = [fm fileExistsAtPath:path];
	if(!exists) return nil;
	return [[[TiBlob alloc] initWithFile:path] autorelease];
}

-(id)append:(id)args
{
	ENSURE_TYPE(args,NSArray);
	id arg = [args objectAtIndex:0];

	if([arg isKindOfClass:[TiFile class]]) {
		//allow the ability to append files to another file
		//e.g. file.append(Ti.Filesystem.getFile('somewhere'));

		TiFile *file_arg = (TiFile *) arg;
		NSError *err = nil;
		NSString *contents = [NSString stringWithContentsOfFile:[file_arg path] encoding:NSUTF8StringEncoding error:&err];
		if(contents != nil && err == nil) {
			arg = contents;
		} else {
			NSLog(@"[ERROR] Can't open file (%@) for reading!\n%@", [file_arg path], err);
			return NUMBOOL(NO);
		}
	}

	if ([arg isKindOfClass:[TiBlob class]] ||
		[arg isKindOfClass:[NSString class]]) {

		NSData *data = nil;
		if([arg isKindOfClass:[NSString class]]) {
			data = [arg dataUsingEncoding:NSUTF8StringEncoding];
		} else {
			data = [(TiBlob*) arg data];
		}

		if(data == nil) {
			return NUMBOOL(NO);
		}

		if(![fm fileExistsAtPath:path]) {
			//create the file if it doesn't exist already
			NSError *writeError = nil;
			[data writeToFile:path options:NSDataWritingAtomic error:&writeError];
			if(writeError != nil) {
				NSLog(@"[ERROR] Could not write data to file at path \"%@\"", path);
			}
			return NUMBOOL(writeError == nil);
		}

		NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:path];

		unsigned long long offset = [handle seekToEndOfFile];
		[handle writeData:data];

		BOOL success = ([handle offsetInFile] - offset) == [data length];
		[handle closeFile];

		return NUMBOOL(success);
	} else {
		NSLog(@"[ERROR] Can only append blobs and strings");
	}
	return NUMBOOL(NO);
}

-(id)write:(id)args
{
	ENSURE_TYPE(args,NSArray);
	id arg = [args objectAtIndex:0];

	//Short-circuit against non-supported types
	if(!([arg isKindOfClass:[TiFile class]] || [arg isKindOfClass:[TiBlob class]]
		 || [arg isKindOfClass:[NSString class]])) {
		return NUMBOOL(NO);
	}

	if([args count] > 1) {
		ENSURE_TYPE([args objectAtIndex:1], NSNumber);

		//We have a second argument, is it truthy?
		//If yes, we'll hand the args to -append:
		NSNumber *append = [args objectAtIndex:1];
		if([append boolValue] == YES) {
			return [self append:[args subarrayWithRange:NSMakeRange(0, 1)]];
		}
	}
	if ([arg isKindOfClass:[TiBlob class]])
	{
		TiBlob *blob = (TiBlob*)arg;
		return NUMBOOL([blob writeTo:path error:nil]);
	}
	else if ([arg isKindOfClass:[TiFile class]])
	{
		TiFile *file = (TiFile*)arg;
		[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
		NSError *error = nil;
		[[NSFileManager defaultManager] copyItemAtPath:[file path] toPath:path error:&error];
		if (error!=nil)
		{
			NSLog(@"[ERROR] error writing file: %@ to: %@. Error: %@",[file path],path,error);
		}
		return NUMBOOL(error==nil);
	}
	NSString *data = [TiUtils stringValue:arg];
	NSError *err = nil;
	[data writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err];
	if(err != nil) {
		NSLog(@"[ERROR] Could not write data to file at path \"%@\" - details: %@", path, err);
	}
	return NUMBOOL(err == nil);
}

-(id)extension:(id)args
{
	return [path pathExtension];
}

-(id)getParent:(id)args
{
	return [path stringByDeletingLastPathComponent];
}

-(id)name
{
	return [path lastPathComponent];
}

-(id)resolve:(id)args
{
	return path;
}

-(id)description
{
	return path;
}

+(id)makeTemp:(BOOL)isDirectory
{
	NSString * tempDir = NSTemporaryDirectory();
	NSError * error=nil;

	NSFileManager *fm = [NSFileManager defaultManager];
	if(![fm fileExistsAtPath:tempDir])
	{
		[fm createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:&error];
		if(error != nil)
		{
			//TODO: ?
			return nil;
		}
	}

	int timestamp = (int)(time(NULL) & 0xFFFFL);
	NSString * resultPath;
	do
	{
		resultPath = [tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%X",timestamp]];
		timestamp ++;
	} while ([fm fileExistsAtPath:resultPath]);

	if(isDirectory)
	{
		[fm createDirectoryAtPath:resultPath withIntermediateDirectories:NO attributes:nil error:&error];
	}
	else
	{
		[[NSData data] writeToFile:resultPath options:0 error:&error];
	}

	if (error != nil)
	{
		//TODO: ?
		return nil;
	}

	return [[[TiFilesystemFileProxy alloc] initWithFile:resultPath] autorelease];
}

@end

#endif

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
using Stratageme15.Core.Translation.Reactors;
using Stratageme15.ExtensionsPack.Prototyping;
using Stratageme15.ExtensionsPack.Tactics;

namespace Stratageme15.ExtensionsPack
{
    class ExtensionsPackReactorsBatch : ReactorBatchBase
    {
        private TacticsRepository _tactics;

        protected override void Reactors()
        {
            #region Prototypes
            RegisterReactor<PrototypeClassDeclarationSyntaxReactor, ClassDeclarationSyntax>();
            RegisterReactor<PrototypeMethodDeclarationSyntaxReactor,MethodDeclarationSyntax>();
            #endregion
        }

        public ExtensionsPackReactorsBatch(TacticsRepository tactics)
        {
            _tactics = tactics;
        }

        public override object ReactorBatchData
        {
            get { return _tactics; }
        }
    }
}


text: User.create! username: "bodacious", password: "password"


text:
package cmd

import (
	"bytes"
	"net/http"
	"testing"

	"k8s.io/kubernetes/pkg/client/typed/dynamic"
	"k8s.io/kubernetes/pkg/client/unversioned/fake"
)

func TestExtraArgsFail(t *testing.T) {
	initTestErrorHandler(t)
	buf := bytes.NewBuffer([]byte{})

	f, _, _, _ := NewAPIFactory()
	c := NewCmdCreate(f, buf)
	if ValidateArgs(c, []string{"rc"}) == nil {
		t.Errorf("unexpected non-error")
	}
}

func TestCreateObject(t *testing.T) {
	initTestErrorHandler(t)
	_, _, rc := testData()
	rc.Items[0].Name = "redis-master-controller"

	f, tf, codec, _ := NewAPIFactory()
	ns := dynamic.ContentConfig().NegotiatedSerializer
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: ns,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost:
				return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf := bytes.NewBuffer([]byte{})

	cmd := NewCmdCreate(f, buf)
	cmd.Flags().Set("filename", "../../../examples/guestbook/legacy/redis-master-controller.yaml")
	cmd.Flags().Set("output", "name")
	cmd.Run(cmd, []string{})

	// uses the name from the file, not the response
	if buf.String() != "replicationcontroller/redis-master-controller\n" {
		t.Errorf("unexpected output: %s", buf.String())
	}
}

func TestCreateMultipleObject(t *testing.T) {
	initTestErrorHandler(t)
	_, svc, rc := testData()

	f, tf, codec, _ := NewAPIFactory()
	ns := dynamic.ContentConfig().NegotiatedSerializer
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: ns,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/namespaces/test/services" && m == http.MethodPost:
				return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil
			case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost:
				return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf := bytes.NewBuffer([]byte{})

	cmd := NewCmdCreate(f, buf)
	cmd.Flags().Set("filename", "../../../examples/guestbook/legacy/redis-master-controller.yaml")
	cmd.Flags().Set("filename", "../../../examples/guestbook/frontend-service.yaml")
	cmd.Flags().Set("output", "name")
	cmd.Run(cmd, []string{})

	// Names should come from the REST response, NOT the files
	if buf.String() != "replicationcontroller/rc1\nservice/baz\n" {
		t.Errorf("unexpected output: %s", buf.String())
	}
}

func TestCreateDirectory(t *testing.T) {
	initTestErrorHandler(t)
	_, _, rc := testData()
	rc.Items[0].Name = "name"

	f, tf, codec, _ := NewAPIFactory()
	ns := dynamic.ContentConfig().NegotiatedSerializer
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: ns,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost:
				return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf := bytes.NewBuffer([]byte{})

	cmd := NewCmdCreate(f, buf)
	cmd.Flags().Set("filename", "../../../examples/guestbook/legacy")
	cmd.Flags().Set("output", "name")
	cmd.Run(cmd, []string{})

	if buf.String() != "replicationcontroller/name\nreplicationcontroller/name\nreplicationcontroller/name\n" {
		t.Errorf("unexpected output: %s", buf.String())
	}
}


text:
import unittest

from numba.cuda.testing import CUDATestCase, skip_on_cudasim
from numba.tests.support import captured_stdout

@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
class TestMonteCarlo(CUDATestCase):
    """
    Test monte-carlo integration
    """

    def setUp(self):
        # Prevent output from this test showing up when running the test suite
        self._captured_stdout = captured_stdout()
        self._captured_stdout.__enter__()
        super().setUp()

    def tearDown(self):
        # No exception type, value, or traceback
        self._captured_stdout.__exit__(None, None, None)
        super().tearDown()

    def test_ex_montecarlo(self):
        # ex_montecarlo.import.begin
        import numba
        import numpy as np
        from numba import cuda
        from numba.cuda.random import (
            create_xoroshiro128p_states,
            xoroshiro128p_uniform_float32,
        )
        # ex_montecarlo.import.end

        # ex_montecarlo.define.begin
        # number of samples, higher will lead to a more accurate answer
        nsamps = 1000000
        # ex_montecarlo.define.end

        # ex_montecarlo.kernel.begin
        @cuda.jit
        def mc_integrator_kernel(out, rng_states, lower_lim, upper_lim):
            """
            kernel to draw random samples and evaluate the function to
            be integrated at those sample values
            """
            size = len(out)

            gid = cuda.grid(1)
            if gid < size:
                # draw a sample between 0 and 1 on this thread
                samp = xoroshiro128p_uniform_float32(rng_states, gid)

                # normalize this sample to the limit range
                samp = samp * (upper_lim - lower_lim) + lower_lim

                # evaluate the function to be
                # integrated at the normalized
                # value of the sample
                y = func(samp)
                out[gid] = y
        # ex_montecarlo.kernel.end

        # ex_montecarlo.callfunc.begin
        @cuda.reduce
        def sum_reduce(a, b):
            return a + b

        def mc_integrate(lower_lim, upper_lim, nsamps):
            """
            approximate the definite integral of `func` from
            `lower_lim` to `upper_lim`
            """
            out = cuda.to_device(np.zeros(nsamps, dtype="float32"))
            rng_states = create_xoroshiro128p_states(nsamps, seed=42)

            # jit the function for use in CUDA kernels

            mc_integrator_kernel.forall(nsamps)(
                out, rng_states, lower_lim, upper_lim
            )
            # normalization factor to convert
            # to the average: (b - a)/(N - 1)
            factor = (upper_lim - lower_lim) / (nsamps - 1)

            return sum_reduce(out) * factor
        # ex_montecarlo.callfunc.end

        # ex_montecarlo.launch.begin
        # define a function to integrate
        @numba.jit
        def func(x):
            return 1.0 / x

        mc_integrate(1, 2, nsamps)  # array(0.6929643, dtype=float32)
        mc_integrate(2, 3, nsamps)  # array(0.4054021, dtype=float32)
        # ex_montecarlo.launch.end

        # values computed independently using maple
        np.testing.assert_allclose(
            mc_integrate(1, 2, nsamps), 0.69315, atol=0.001
        )
        np.testing.assert_allclose(
            mc_integrate(2, 3, nsamps), 0.4055, atol=0.001
        )

if __name__ == "__main__":
    unittest.main()


text:
title: Homepage Highlights
menu: Highlights
class: big
features:
  - header: Crazy Fast
    text: "Performance is not just an after thought, we baked it in from the start!"
    icon: airplane
  - header: Easy to build
    text: "Simple text files means Grav is trivial to install, and easy to maintain."
    icon: city
  - header: Awesome Technology
    text: "Grav employees best-in-class technologies such as Twig, Markdown & Yaml"
    icon: cube-outline
  - header: Super Flexible
    text: "From the ground up, with many plugin hooks, Grav is extremely extensible"
    icon: puzzle
---

## Built on top of Greatness
### Four core tenants keep Grav focused

We believe the best recipe for making something great is to bake with [quality ingredients](#) and add dollops of [cool stuff](#).


text:
"""
@brief      test log(time=50s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder, add_missing_development_version
import ensae_teaching_cs

class TestNotebookEnsaeSklearn(unittest.TestCase):

    def setUp(self):
        add_missing_development_version(["pymyinstall", "pyensae", "pymmails", "jyquickhelper"],
                                        __file__, hide=True)

    def test_notebook_runner_ensae_sklearn(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")
        from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks, clean_function_1a
        from ensae_teaching_cs.automation.notebook_test_helper import copy_data_file
        from ensae_teaching_cs.helpers.size_helper import total_size
        self.assertTrue(total_size)
        temp = get_temp_folder(__file__, "temp_notebook_ensae_sklearn")
        keepnote = ls_notebooks("sklearn_ensae_course")
        self.assertTrue(len(keepnote) > 0)
        copy_data_file("sklearn_ensae_course",
                       "iris_setosa.jpg", temp, fLOG=fLOG)
        copy_data_file("sklearn_ensae_course",
                       "iris_versicolor.jpg", temp, fLOG=fLOG)
        copy_data_file("sklearn_ensae_course",
                       "iris_virginica.jpg", temp, fLOG=fLOG)
        execute_notebooks(temp, keepnote,
                          lambda i, n: True,
                          fLOG=fLOG,
                          clean_function=clean_function_1a,
                          dump=ensae_teaching_cs,
                          additional_path=[os.path.dirname(keepnote[0])])

if __name__ == "__main__":
    unittest.main()


text:
'use strict';

const BBPromise = require('bluebird');
const fs = BBPromise.promisifyAll(require('fs'));
const path = require('path');
const HTTPError = require('../lib/util.js').HTTPError;

// Swagger-ui-dist helpfully exporting the absolute path of its dist directory
const docRoot = `${require('swagger-ui-dist').getAbsoluteFSPath()}/`;
const DOC_CSP = "default-src 'none'; " +
    "script-src 'self' 'unsafe-inline'; connect-src *; " +
    "style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';";

function processRequest(app, req, res) {

    const reqPath = req.query.path || '/index.html';
    const filePath = path.join(docRoot, reqPath);

    // Disallow relative paths.
    // Test relies on docRoot ending on a slash.
    if (filePath.substring(0, docRoot.length) !== docRoot) {
        throw new HTTPError({
            status: 404,
            type: 'not_found',
            title: 'File not found',
            detail: `${reqPath} could not be found.`
        });
    }

    return fs.readFileAsync(filePath)
    .then((body) => {
        if (reqPath === '/index.html') {
            const css = `
                /* Removes Swagger's image from the header bar */
                .topbar-wrapper .link img {
                    display: none;
                }
                /* Adds the application's name in the header bar */
                .topbar-wrapper .link::after {
                    content: "${app.info.name}";
                }
                /* Removes input field and explore button from header bar */
                .swagger-ui .topbar .download-url-wrapper {
                    display: none;
                }
                /* Modifies the font in the information area */
                .swagger-ui .info li, .swagger-ui .info p, .swagger-ui .info table, .swagger-ui .info a {
                    font-size: 16px;
                    line-height: 1.4em;
                }
                /* Removes authorize button and section */
                .scheme-container {
                    display: none
                }
            `;
            body = body.toString()
                .replace(/((?:src|href)=['"])/g, '$1?doc&path=')
                // Some self-promotion
                .replace(/<\/style>/, `${css}\n  </style>`)
                .replace(/<title>[^<]*<\/title>/, `<title>${app.info.name}</title>`)
                // Replace the default url with ours, switch off validation &
                // limit the size of documents to apply syntax highlighting to
                .replace(/dom_id: '#swagger-ui'/, 'dom_id: "#swagger-ui", ' +
                    'docExpansion: "none", defaultModelsExpandDepth: -1, validatorUrl: null, displayRequestDuration: true')
                .replace(/"https:\/\/petstore.swagger.io\/v2\/swagger.json"/,
                    '"/?spec"');
        }

        let contentType = 'text/html';
        if (/\.js$/.test(reqPath)) {
            contentType = 'text/javascript';
            body = body.toString()
                .replace(/underscore-min\.map/, '?doc&path=lib/underscore-min.map')
                .replace(/sourceMappingURL=/, 'sourceMappingURL=/?doc&path=');
        } else if (/\.png$/.test(reqPath)) {
            contentType = 'image/png';
        } else if (/\.map$/.test(reqPath)) {
            contentType = 'application/json';
        } else if (/\.ttf$/.test(reqPath)) {
            contentType = 'application/x-font-ttf';
        } else if (/\.css$/.test(reqPath)) {
            contentType = 'text/css';
            body = body.toString()
                .replace(/\.\.\/(images|fonts)\//g, '?doc&path=$1/')
                .replace(/sourceMappingURL=/, 'sourceMappingURL=/?doc&path=');
        }

        res.header('content-type', contentType);
        res.header('content-security-policy', DOC_CSP);
        res.header('x-content-security-policy', DOC_CSP);
        res.header('x-webkit-csp', DOC_CSP);
        res.send(body.toString());
    })
    .catch({ code: 'ENOENT' }, () => {
        res.status(404)
            .type('not_found')
            .send('not found');
    });

}

module.exports = {
    processRequest
};


text:
"""Tests for Plex config flow."""
import copy
import ssl
from unittest.mock import patch

import plexapi.exceptions
import requests.exceptions

from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.plex import config_flow
from homeassistant.components.plex.const import (
    AUTOMATIC_SETUP_STRING,
    CONF_IGNORE_NEW_SHARED_USERS,
    CONF_IGNORE_PLEX_WEB_CLIENTS,
    CONF_MONITORED_USERS,
    CONF_SERVER,
    CONF_SERVER_IDENTIFIER,
    CONF_USE_EPISODE_ART,
    DOMAIN,
    MANUAL_SETUP_STRING,
    PLEX_SERVER_CONFIG,
    SERVERS,
)
from homeassistant.config import async_process_ha_core_config
from homeassistant.config_entries import (
    ENTRY_STATE_LOADED,
    SOURCE_INTEGRATION_DISCOVERY,
    SOURCE_REAUTH,
)
from homeassistant.const import (
    CONF_HOST,
    CONF_PORT,
    CONF_SSL,
    CONF_TOKEN,
    CONF_URL,
    CONF_VERIFY_SSL,
)
from homeassistant.setup import async_setup_component

from .const import DEFAULT_OPTIONS, MOCK_SERVERS, MOCK_TOKEN, PLEX_DIRECT_URL
from .helpers import trigger_plex_update, wait_for_debouncer
from .mock_classes import MockGDM

from tests.common import MockConfigEntry

async def test_bad_credentials(hass):
    """Test when provided credentials are rejected."""
    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch(
        "plexapi.myplex.MyPlexAccount", side_effect=plexapi.exceptions.Unauthorized
    ), patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value="BAD TOKEN"
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])

        assert result["type"] == "form"
        assert result["step_id"] == "user"
        assert result["errors"][CONF_TOKEN] == "faulty_credentials"

async def test_bad_hostname(hass, mock_plex_calls):
    """Test when an invalid address is provided."""
    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch(
        "plexapi.myplex.MyPlexResource.connect",
        side_effect=requests.exceptions.ConnectionError,
    ), patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])

        assert result["type"] == "form"
        assert result["step_id"] == "user"
        assert result["errors"][CONF_HOST] == "not_found"

async def test_unknown_exception(hass):
    """Test when an unknown exception is encountered."""
    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch("plexapi.myplex.MyPlexAccount", side_effect=Exception), patch(
        "plexauth.PlexAuth.initiate_auth"
    ), patch("plexauth.PlexAuth.token", return_value="MOCK_TOKEN"):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "abort"
        assert result["reason"] == "unknown"

async def test_no_servers_found(hass, mock_plex_calls, requests_mock, empty_payload):
    """Test when no servers are on an account."""
    requests_mock.get("https://plex.tv/api/resources", text=empty_payload)

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "form"
        assert result["step_id"] == "user"
        assert result["errors"]["base"] == "no_servers"

async def test_single_available_server(hass, mock_plex_calls):
    """Test creating an entry with one server available."""

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "create_entry"

        server_id = result["data"][CONF_SERVER_IDENTIFIER]
        mock_plex_server = hass.data[DOMAIN][SERVERS][server_id]

        assert result["title"] == mock_plex_server.url_in_use
        assert result["data"][CONF_SERVER] == mock_plex_server.friendly_name
        assert (
            result["data"][CONF_SERVER_IDENTIFIER]
            == mock_plex_server.machine_identifier
        )
        assert (
            result["data"][PLEX_SERVER_CONFIG][CONF_URL] == mock_plex_server.url_in_use
        )
        assert result["data"][PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN

async def test_multiple_servers_with_selection(
    hass, mock_plex_calls, requests_mock, plextv_resources_base
):
    """Test creating an entry with multiple servers available."""

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    requests_mock.get(
        "https://plex.tv/api/resources",
        text=plextv_resources_base.format(second_server_enabled=1),
    )
    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "form"
        assert result["step_id"] == "select_server"

        result = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            user_input={CONF_SERVER: MOCK_SERVERS[0][CONF_SERVER]},
        )
        assert result["type"] == "create_entry"

        server_id = result["data"][CONF_SERVER_IDENTIFIER]
        mock_plex_server = hass.data[DOMAIN][SERVERS][server_id]

        assert result["title"] == mock_plex_server.url_in_use
        assert result["data"][CONF_SERVER] == mock_plex_server.friendly_name
        assert (
            result["data"][CONF_SERVER_IDENTIFIER]
            == mock_plex_server.machine_identifier
        )
        assert (
            result["data"][PLEX_SERVER_CONFIG][CONF_URL] == mock_plex_server.url_in_use
        )
        assert result["data"][PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN

async def test_adding_last_unconfigured_server(
    hass, mock_plex_calls, requests_mock, plextv_resources_base
):
    """Test automatically adding last unconfigured server when multiple servers on account."""

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_SERVER_IDENTIFIER: MOCK_SERVERS[1][CONF_SERVER_IDENTIFIER],
            CONF_SERVER: MOCK_SERVERS[1][CONF_SERVER],
        },
    ).add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    requests_mock.get(
        "https://plex.tv/api/resources",
        text=plextv_resources_base.format(second_server_enabled=1),
    )

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "create_entry"

        server_id = result["data"][CONF_SERVER_IDENTIFIER]
        mock_plex_server = hass.data[DOMAIN][SERVERS][server_id]

        assert result["title"] == mock_plex_server.url_in_use
        assert result["data"][CONF_SERVER] == mock_plex_server.friendly_name
        assert (
            result["data"][CONF_SERVER_IDENTIFIER]
            == mock_plex_server.machine_identifier
        )
        assert (
            result["data"][PLEX_SERVER_CONFIG][CONF_URL] == mock_plex_server.url_in_use
        )
        assert result["data"][PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN

async def test_all_available_servers_configured(
    hass, entry, requests_mock, plextv_account, plextv_resources_base
):
    """Test when all available servers are already configured."""

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    entry.add_to_hass(hass)

    MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_SERVER_IDENTIFIER: MOCK_SERVERS[1][CONF_SERVER_IDENTIFIER],
            CONF_SERVER: MOCK_SERVERS[1][CONF_SERVER],
        },
    ).add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    requests_mock.get("https://plex.tv/users/account", text=plextv_account)
    requests_mock.get(
        "https://plex.tv/api/resources",
        text=plextv_resources_base.format(second_server_enabled=1),
    )

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "abort"
        assert result["reason"] == "all_configured"

async def test_option_flow(hass, entry, mock_plex_server):
    """Test config options flow selection."""
    assert len(hass.config_entries.async_entries(DOMAIN)) == 1
    assert entry.state == ENTRY_STATE_LOADED

    result = await hass.config_entries.options.async_init(
        entry.entry_id, context={"source": "test"}, data=None
    )
    assert result["type"] == "form"
    assert result["step_id"] == "plex_mp_settings"

    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={
            CONF_USE_EPISODE_ART: True,
            CONF_IGNORE_NEW_SHARED_USERS: True,
            CONF_MONITORED_USERS: list(mock_plex_server.accounts),
        },
    )
    assert result["type"] == "create_entry"
    assert result["data"] == {
        MP_DOMAIN: {
            CONF_USE_EPISODE_ART: True,
            CONF_IGNORE_NEW_SHARED_USERS: True,
            CONF_MONITORED_USERS: {
                user: {"enabled": True} for user in mock_plex_server.accounts
            },
            CONF_IGNORE_PLEX_WEB_CLIENTS: False,
        }
    }

async def test_missing_option_flow(hass, entry, mock_plex_server):
    """Test config options flow selection when no options stored."""
    assert len(hass.config_entries.async_entries(DOMAIN)) == 1
    assert entry.state == ENTRY_STATE_LOADED

    result = await hass.config_entries.options.async_init(
        entry.entry_id, context={"source": "test"}, data=None
    )
    assert result["type"] == "form"
    assert result["step_id"] == "plex_mp_settings"

    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={
            CONF_USE_EPISODE_ART: True,
            CONF_IGNORE_NEW_SHARED_USERS: True,
            CONF_MONITORED_USERS: list(mock_plex_server.accounts),
        },
    )
    assert result["type"] == "create_entry"
    assert result["data"] == {
        MP_DOMAIN: {
            CONF_USE_EPISODE_ART: True,
            CONF_IGNORE_NEW_SHARED_USERS: True,
            CONF_MONITORED_USERS: {
                user: {"enabled": True} for user in mock_plex_server.accounts
            },
            CONF_IGNORE_PLEX_WEB_CLIENTS: False,
        }
    }

async def test_option_flow_new_users_available(hass, entry, setup_plex_server):
    """Test config options multiselect defaults when new Plex users are seen."""
    OPTIONS_OWNER_ONLY = copy.deepcopy(DEFAULT_OPTIONS)
    OPTIONS_OWNER_ONLY[MP_DOMAIN][CONF_MONITORED_USERS] = {"User 1": {"enabled": True}}
    entry.options = OPTIONS_OWNER_ONLY

    mock_plex_server = await setup_plex_server(config_entry=entry)
    await hass.async_block_till_done()

    server_id = mock_plex_server.machine_identifier
    monitored_users = hass.data[DOMAIN][SERVERS][server_id].option_monitored_users

    new_users = [x for x in mock_plex_server.accounts if x not in monitored_users]
    assert len(monitored_users) == 1
    assert len(new_users) == 2

    result = await hass.config_entries.options.async_init(
        entry.entry_id, context={"source": "test"}, data=None
    )
    assert result["type"] == "form"
    assert result["step_id"] == "plex_mp_settings"
    multiselect_defaults = result["data_schema"].schema["monitored_users"].options

    assert "[Owner]" in multiselect_defaults["User 1"]
    for user in new_users:
        assert "[New]" in multiselect_defaults[user]

async def test_external_timed_out(hass):
    """Test when external flow times out."""

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=None
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "abort"
        assert result["reason"] == "token_request_timeout"

async def test_callback_view(hass, aiohttp_client):
    """Test callback view."""

    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": "user"}
    )
    assert result["type"] == "form"
    assert result["step_id"] == "user"

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["type"] == "external"

        client = await aiohttp_client(hass.http.app)
        forward_url = f'{config_flow.AUTH_CALLBACK_PATH}?flow_id={result["flow_id"]}'

        resp = await client.get(forward_url)
        assert resp.status == 200

async def test_manual_config(hass, mock_plex_calls):
    """Test creating via manual configuration."""
    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    class WrongCertValidaitionException(requests.exceptions.SSLError):
        """Mock the exception showing an unmatched error."""

        def __init__(self):
            self.__context__ = ssl.SSLCertVerificationError(
                "some random message that doesn't match"
            )

    # Basic mode
    result = await hass.config_entries.flow.async_init(
        config_flow.DOMAIN, context={"source": "user"}
    )

    assert result["type"] == "form"
    assert result["step_id"] == "user"
    assert result["data_schema"] is None
    hass.config_entries.flow.async_abort(result["flow_id"])

    # Advanced automatic
    result = await hass.config_entries.flow.async_init(
        config_flow.DOMAIN, context={"source": "user", "show_advanced_options": True}
    )

    assert result["data_schema"] is not None
    assert result["type"] == "form"
    assert result["step_id"] == "user_advanced"

    with patch("plexauth.PlexAuth.initiate_auth"):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={"setup_method": AUTOMATIC_SETUP_STRING}
        )

    assert result["type"] == "external"
    hass.config_entries.flow.async_abort(result["flow_id"])

    # Advanced manual
    result = await hass.config_entries.flow.async_init(
        config_flow.DOMAIN, context={"source": "user", "show_advanced_options": True}
    )

    assert result["data_schema"] is not None
    assert result["type"] == "form"
    assert result["step_id"] == "user_advanced"

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], user_input={"setup_method": MANUAL_SETUP_STRING}
    )

    assert result["type"] == "form"
    assert result["step_id"] == "manual_setup"

    MANUAL_SERVER = {
        CONF_HOST: MOCK_SERVERS[0][CONF_HOST],
        CONF_PORT: MOCK_SERVERS[0][CONF_PORT],
        CONF_SSL: False,
        CONF_VERIFY_SSL: True,
        CONF_TOKEN: MOCK_TOKEN,
    }

    MANUAL_SERVER_NO_HOST_OR_TOKEN = {
        CONF_PORT: MOCK_SERVERS[0][CONF_PORT],
        CONF_SSL: False,
        CONF_VERIFY_SSL: True,
    }

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], user_input=MANUAL_SERVER_NO_HOST_OR_TOKEN
    )

    assert result["type"] == "form"
    assert result["step_id"] == "manual_setup"
    assert result["errors"]["base"] == "host_or_token"

    with patch(
        "plexapi.server.PlexServer",
        side_effect=requests.exceptions.SSLError,
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input=MANUAL_SERVER
        )

    assert result["type"] == "form"
    assert result["step_id"] == "manual_setup"
    assert result["errors"]["base"] == "ssl_error"

    with patch(
        "plexapi.server.PlexServer",
        side_effect=WrongCertValidaitionException,
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input=MANUAL_SERVER
        )

    assert result["type"] == "form"
    assert result["step_id"] == "manual_setup"
    assert result["errors"]["base"] == "ssl_error"

    with patch(
        "homeassistant.components.plex.PlexServer.connect",
        side_effect=requests.exceptions.SSLError,
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input=MANUAL_SERVER
        )

    assert result["type"] == "form"
    assert result["step_id"] == "manual_setup"
    assert result["errors"]["base"] == "ssl_error"

    with patch("homeassistant.components.plex.PlexWebsocket", autospec=True), patch(
        "homeassistant.components.plex.GDM", return_value=MockGDM(disabled=True)
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input=MANUAL_SERVER
        )
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"

    server_id = result["data"][CONF_SERVER_IDENTIFIER]
    mock_plex_server = hass.data[DOMAIN][SERVERS][server_id]

    assert result["title"] == mock_plex_server.url_in_use
    assert result["data"][CONF_SERVER] == mock_plex_server.friendly_name
    assert result["data"][CONF_SERVER_IDENTIFIER] == mock_plex_server.machine_identifier
    assert result["data"][PLEX_SERVER_CONFIG][CONF_URL] == mock_plex_server.url_in_use
    assert result["data"][PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN

async def test_manual_config_with_token(hass, mock_plex_calls):
    """Test creating via manual configuration with only token."""

    result = await hass.config_entries.flow.async_init(
        config_flow.DOMAIN, context={"source": "user", "show_advanced_options": True}
    )

    assert result["type"] == "form"
    assert result["step_id"] == "user_advanced"

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], user_input={"setup_method": MANUAL_SETUP_STRING}
    )

    assert result["type"] == "form"
    assert result["step_id"] == "manual_setup"

    with patch(
        "homeassistant.components.plex.GDM", return_value=MockGDM(disabled=True)
    ), patch("homeassistant.components.plex.PlexWebsocket", autospec=True):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={CONF_TOKEN: MOCK_TOKEN}
        )

    assert result["type"] == "create_entry"

    server_id = result["data"][CONF_SERVER_IDENTIFIER]
    mock_plex_server = hass.data[DOMAIN][SERVERS][server_id]

    assert result["title"] == mock_plex_server.url_in_use
    assert result["data"][CONF_SERVER] == mock_plex_server.friendly_name
    assert result["data"][CONF_SERVER_IDENTIFIER] == mock_plex_server.machine_identifier
    assert result["data"][PLEX_SERVER_CONFIG][CONF_URL] == mock_plex_server.url_in_use
    assert result["data"][PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN

async def test_setup_with_limited_credentials(hass, entry, setup_plex_server):
    """Test setup with a user with limited permissions."""
    with patch(
        "plexapi.server.PlexServer.systemAccounts",
        side_effect=plexapi.exceptions.Unauthorized,
    ) as mock_accounts:
        mock_plex_server = await setup_plex_server()

    assert mock_accounts.called

    plex_server = hass.data[DOMAIN][SERVERS][mock_plex_server.machine_identifier]
    assert len(plex_server.accounts) == 0
    assert plex_server.owner is None

    assert len(hass.config_entries.async_entries(DOMAIN)) == 1
    assert entry.state == ENTRY_STATE_LOADED

async def test_integration_discovery(hass):
    """Test integration self-discovery."""
    mock_gdm = MockGDM()

    with patch("homeassistant.components.plex.config_flow.GDM", return_value=mock_gdm):
        await config_flow.async_discover(hass)

    flows = hass.config_entries.flow.async_progress()

    assert len(flows) == 1

    flow = flows[0]

    assert flow["handler"] == DOMAIN
    assert flow["context"]["source"] == SOURCE_INTEGRATION_DISCOVERY
    assert (
        flow["context"]["unique_id"]
        == mock_gdm.entries[0]["data"]["Resource-Identifier"]
    )
    assert flow["step_id"] == "user"

async def test_trigger_reauth(hass, entry, mock_plex_server, mock_websocket):
    """Test setup and reauthorization of a Plex token."""
    await async_setup_component(hass, "persistent_notification", {})
    await async_process_ha_core_config(
        hass,
        {"internal_url": "http://example.local:8123"},
    )

    assert entry.state == ENTRY_STATE_LOADED

    with patch(
        "plexapi.server.PlexServer.clients", side_effect=plexapi.exceptions.Unauthorized
    ), patch("plexapi.server.PlexServer", side_effect=plexapi.exceptions.Unauthorized):
        trigger_plex_update(mock_websocket)
        await wait_for_debouncer(hass)

    assert len(hass.config_entries.async_entries(DOMAIN)) == 1
    assert entry.state != ENTRY_STATE_LOADED

    flows = hass.config_entries.flow.async_progress()
    assert len(flows) == 1
    assert flows[0]["context"]["source"] == SOURCE_REAUTH

    flow_id = flows[0]["flow_id"]

    with patch("plexauth.PlexAuth.initiate_auth"), patch(
        "plexauth.PlexAuth.token", return_value="BRAND_NEW_TOKEN"
    ):
        result = await hass.config_entries.flow.async_configure(flow_id, user_input={})
        assert result["type"] == "external"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "external_done"

        result = await hass.config_entries.flow.async_configure(result["flow_id"])
        assert result["type"] == "abort"
        assert result["reason"] == "reauth_successful"
        assert result["flow_id"] == flow_id

    assert len(hass.config_entries.flow.async_progress()) == 0
    assert len(hass.config_entries.async_entries(DOMAIN)) == 1

    assert entry.state == ENTRY_STATE_LOADED
    assert entry.data[CONF_SERVER] == mock_plex_server.friendly_name
    assert entry.data[CONF_SERVER_IDENTIFIER] == mock_plex_server.machine_identifier
    assert entry.data[PLEX_SERVER_CONFIG][CONF_URL] == PLEX_DIRECT_URL
    assert entry.data[PLEX_SERVER_CONFIG][CONF_TOKEN] == "BRAND_NEW_TOKEN"


text:
var validationPassword = 0;
var validationConfirmPassword = 0;
var validationFirstName = 0;
var validationLastName = 1;
var validationEmail = 0;
var validationNumber = 0;

function validateEmailId() {
	//Method to validate the format of Email ID and whether the email ID exists in the database or not

	//alert();

	var emailID = $('#email').val();
      atpos = emailID.indexOf("@");
      dotpos = emailID.lastIndexOf(".");
      if (atpos < 1 || ( dotpos - atpos < 2 )) {

            $("#email").css("color","#953b39");
            $("#email").css("border-color","#953b39");
			$("#email").css("font-weight","normal");
            validationEmail = 0;
            return 0;

      } //END if to check the email ID is in the correct format
      else {

          //email is in the valid format, now we need to check that the email ID doesnot exists in the database i.e unique email ID
		  var url = basePath+'home/checkEmailId';

		  //alert(url);

             $.ajax({
                    type: 'POST',

                    url: url,
                    data: {emailId: emailID},
                    success: function(data) {

					//alert(data);
                                   if(data == 0) {

                                        $("#email").css("color","GREEN");
                                        $("#email").css("border-color","GREEN");
										$("#email").css("font-weight","normal");
                                        validationEmail = 1;
                                        return 1;

                                  }
                                  else {
                                      //email not available
                                      $("#email").css("color","#953b39");
                                      $("#email").css("border-color","#953b39");
									  $("#email").css("font-weight","bold");
                                      validationEmail = 0;
                                      return 0;
                                  }

                    }
                });

            $("#email").css("color","GREEN");
            $("#email").css("border-color","GREEN");
            validationEmail = 1;
            return 1;

	  }// END else if the emailID is in correct format and is not available in the database

}

function validatePassword() {

      //Function to validate the password
      if($('#password').val().length > 5) {

            $("#password").css("color","GREEN");
            $("#password").css("border-color","GREEN");
            validationPassword = 1;
            return 1;
      }
      else {

             $("#password").css("color","#953b39");
             $("#password").css("border-color","#953b39");
             validationPassword = 0;
             return 0;
      }
}

function validateConfirmPassword() {

      //Function to check the password and confirm password matches

      if(($('#password').val().length == 0) || ($('#confirmPassword').val().length == 0)) {

            //If either password or confirmPassword is NULL

             $("#password").css("color","#953b39");
             $("#password").css("border-color","#953b39");

             $("#confirmPassword").css("color","#953b39");
             $("#confirmPassword").css("border-color","#953b39");
             validationConfirmPassword = 0;
             return 0;
      }// END If either password or confirmPassword is Null

      if($('#password').val() == $('#confirmPassword').val()) {

            //If password matches with the confirm password

             $("#password").css("color","GREEN");
             $("#password").css("border-color","GREEN");

             $("#confirmPassword").css("color","GREEN");
             $("#confirmPassword").css("border-color","GREEN");
             validationConfirmPassword = 1;
             return 1;

      }//END If the password and confirmPassword matches
      else {

            //If password does not matches with the confirm password

             $("#password").css("color","#953b39");
             $("#password").css("border-color","#953b39");

             $("#confirmPassword").css("color","#953b39");
             $("#confirmPassword").css("border-color","#953b39");
             validationConfirmPassword = 0;
             return 0;
      }//END Else if the Password and confirmPassword does not matches
}

function validateName() {

      //Function to validate the password
      if($('#name').val().length > 2) {

            $("#name").css("color","GREEN");
            $("#name").css("border-color","GREEN");
            validationName = 1;
            return 1;
      }
      else {

             $("#name").css("color","#953b39");
             $("#name").css("border-color","#953b39");
             validationName = 0;
             return 0;
      }
}

function validateNumber() {
	//Check whether the mobile number field is empty
	var mobileNumber = $("#mobileNumber");
	if(mobileNumber.val().length <9) {
		//If the mobile number is less than 10 digits
		validationNumber = 0;
		$("#mobileNumber").css("color","#953b39");
        $("#mobileNumber").css("border-color","#953b39");
	}
	else {
		validationNumber = 1;
		$("#mobileNumber").css("color","GREEN");
        $("#mobileNumber").css("border-color","GREEN");
	}
}

function validateFirstName() {
	//Method to validate the first Name
	var firstName = $("#firstName");
	if(firstName.val().length == 0) {
		//Name field is blank
		validationFirstName = 0;
		$("#firstName").css("color","#953b39");
        $("#firstName").css("border-color","#953b39");
	}
	else {
		validationFirstName = 1;
		$("#firstName").css("color","GREEN");
        $("#firstName").css("border-color","GREEN");
	}
}

function validateLastName() {
	//Method to validate the first Name
	var lastName = $("#lastName");
	if(lastName.val().length == 0) {
		//Name field is blank
		validationLastName = 0;
		$("#lastName").css("color","#953b39");
        $("#lastName").css("border-color","#953b39");
	}
	else {
		validationLastName = 1;
		$("#lastName").css("color","GREEN");
        $("#lastName").css("border-color","GREEN");
	}
}

function validateAll() {
      //Check whether all validation function returns 1

      validatePassword();
      validateConfirmPassword();
      validateEmailId();
	  validateNumber();
	  validateFirstName();
	  validateFirstName();

      if(validationPassword && validationConfirmPassword && validationFirstName && validationEmail && validationLastName && validationNumber) {

            //If all the fields are validated
            $('#joinSportsTeachers').addClass('btn-primary');
            $('#joinSportsTeachers').attr('type','submit');

      }
      else {
		  	//alert("Else");
            //If error in validation of any of the fields
            $('#joinSportsTeachers').removeClass('btn-primary');
            $('#joinSportsTeachers').attr('type','button');
      }
}


text:
         // { dg-warning "use of C99 long long integer constant .-Wlong-long." "use long long" { target *-*-* } 4 }
#endif


text:
<?php
namespace ReCaptcha2\Form\View\Helper\Captcha;

use Traversable;
use Zend\Captcha\AdapterInterface;
use Zend\Form\Element\Captcha;
use Zend\Form\ElementInterface;
use Zend\Form\Exception;
use Zend\Form\View\Helper\FormInput;

class ReCaptcha2 extends FormInput
{
    /**
     * @param  ElementInterface $element
     * @return string
     */
    public function __invoke(ElementInterface $element = null)
    {
        if (!$element) {
            return $this;
        }

        return $this->render($element);
    }

    /**
     * @param  ElementInterface $element
     * @throws Exception\DomainException
     * @return string
     */
    public function render(ElementInterface $element)
    {
        if (!$element instanceof Captcha) {
            throw new Exception\InvalidArgumentException(sprintf(
                '%s expects a valid implementation of Zend\Form\Element\Captcha; received "%s"',
                __METHOD__,
                (is_object($element) ? get_class($element) : gettype($element))
            ));
        }
        $captcha = $element->getCaptcha();

        if ($captcha === null || !$captcha instanceof AdapterInterface) {
            throw new Exception\DomainException(sprintf(
                '%s requires that the element has a "captcha" attribute implementing %s; none found',
                __METHOD__,
                AdapterInterface::class
            ));
        }

        /* @var $service \ReCaptcha2\Captcha\ServiceInterface */
        $service = $captcha->getService();

        $siteKey = $service->getSiteKey();
        if ($siteKey === null) {
            throw new Exception\DomainException('Missing site key');
        }

        $params = array_filter($service->getParams(), function ($param) {
            return $param !== null;
        });

        $apiPath = $service->getServiceUri();
        $scriptPath = sprintf('%s.js', $apiPath);
        $queryString = '';
        if (!empty($params)) {
            $queryString = http_build_query($params, '', '&');
            $scriptPath .= '?' . $queryString;
        }

        $attributes = $element->getAttributes();
        if ($attributes instanceof Traversable) {
            $attributes = iterator_to_array($attributes);
        }

        $attributes['class'] = 'g-recaptcha';
        $attributes['data-sitekey'] = $siteKey;
        $attributeString = $this->createAttributesString($attributes);

        $template = <<<HTML
<input type="hidden" name="%s" value="1">

HTML;
        $markup = sprintf($template, $element->getName(), $attributeString, $scriptPath);

        $queryString .= ($queryString ? '&' : '');
        $markup .= <<<HTML

        <textarea id="g-recaptcha-response" name="g-recaptcha-response"
                  class="g-recaptcha-response"
                  style="width: 250px; height: 40px; border: 1px solid #c1c1c1;
                         margin: 10px 25px; padding: 0px; resize: none;" >
        </textarea>

HTML;

        return $markup;
    }
}


text:
package microservices.api.sample.app;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import microservices.api.sample.resources.AirlinesResource;
import microservices.api.sample.resources.AvailabilityResource;
import microservices.api.sample.resources.BookingResource;

@ApplicationPath("/")
@SwaggerDefinition(
		info = @Info(description = "Service for booking and managing air flights",
					 version = "1.0.1",
					 title = "Airline Service"),
		tags= {@Tag(name="Airline Booking API",
					description="APIs for booking and managing air flights")})
public class JAXRSApp extends Application {
	@Override
	public Set<Object> getSingletons() {
		Set<Object> singletons = new HashSet<Object>();
		singletons.add(new AirlinesResource());
		singletons.add(new AvailabilityResource());
		singletons.add(new BookingResource());
		return singletons;
	}

}


text: module.exports = require('gulp');


text:
		<button type="submit" onclick="toggleCommentForm({{verseId}})" class="btn btn-primary">
	    	Add to the discussion
		</button>

      <select class="form-control" id="filter">
        <option>Filter by: All</option>
        <option>Questions</option>
        <option>Comments</option>
        <option>Cross Reference</option>
      </select>

      <select class="form-control" id="sort">
        <option>Sort by: Date</option>
        <option>Like Count</option>
        <option>Author</option>
        <option>Random</option>
        <option>Reputation</option>
      </select>

# if comment_dbs

	{% for c in comment_dbs %}

				{{c.user_key|get_username_by_user_key}}
				{{c.modified|get_pretty_date}}

				  <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
				    More
				  </button>

Flag Comment

Contact Author

Juice Boost (lots of likes)

{{c.comment}}

		{% if c.commentType == 'question' %}

					Reply to this question

		{% endif %}

				{% if c.tags %}
					{% for tag in c.tags %}
						<button type="button" class="btn btn-default btn-xs">
				    		{{tag}}
				  		</button>
					{% endfor %}
				{% endif %}

				like

	{% endfor %}

# endif


text:
require 'rails_helper'

RSpec.describe User, type: :model do
  subject { described_class.new }

  it { is_expected.to have_many(:appointment_summaries) }
end


text:
/*global define */

'use strict';

define([
	'depot'
], function (depot) {
	return depot('peditor', { idAttribute: 'id' });
});


text:
<?php
// src/Acme/StoreBundle/Entity/Product.php
namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 * @ORM\HasLifecycleCallbacks()
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $name;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    protected $price;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="date",nullable=true)
     */
    protected $created;

	/**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    protected $category;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param float $price
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set category
     *
     * @param \Acme\StoreBundle\Entity\Category $category
     * @return Product
     */
    public function setCategory(\Acme\StoreBundle\Entity\Category $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \Acme\StoreBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedValue()
    {
        $this->created = new \DateTime();
    }

    /**
     * Set created
     *
     * @param string $created
     * @return Product
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return string
     */
    public function getCreated()
    {
        return $this->created;
    }
}


text:
package net.sqlcipher.database;

/**
 * A listener for transaction events.
 */
public interface SQLiteTransactionListener {
    /**
     * Called immediately after the transaction begins.
     */
    void onBegin();

    /**
     * Called immediately before commiting the transaction.
     */
    void onCommit();

    /**
     * Called if the transaction is about to be rolled back.
     */
    void onRollback();
}


text:
;
(function(root, doc, factory) {
    if (typeof define === "function" && define.amd) {
        // AMD
        define( function() {
            return factory(root, doc);
        });
    } else {
        // None AMD
        factory(root, doc);
    }
}(window, document, function(window, document) {
    'use strict';

    /**
     * create faketouches instance
     * @param element
     * @constructor
     */
    function FakeTouches(element) {
        this.element = element;

        this.touches = [];
        this.touch_type = FakeTouches.TOUCH_EVENTS;
        this.has_multitouch = true;
    }

    FakeTouches.POINTER_TOUCH_EVENTS = 100;
    FakeTouches.POINTER_MOUSE_EVENTS = 200;
    FakeTouches.TOUCH_EVENTS = 300;
    FakeTouches.MOUSE_EVENTS = 400;
    FakeTouches.TOUCH_AND_MOUSE_EVENTS = 500;

    FakeTouches.POINTER_TYPE_MOUSE = 1000;
    FakeTouches.POINTER_TYPE_TOUCH = 2000;

    /**
     * set the kind of touchevents we want to trigger
     * @param   {Number}    touch_type
     */
    FakeTouches.prototype.setTouchType = function(touch_type) {
        this.touch_type = touch_type;

        this.has_multitouch = true;
        if(touch_type == FakeTouches.POINTER_MOUSE_EVENTS ||
            touch_type == FakeTouches.MOUSE_EVENTS) {
            this.has_multitouch = false;
        }
    };

    /**
     * uppercase first char
     * @param str
     * @returns {string}
     */
    function ucfirst(str) {
        str += '';
        var f = str.charAt(0).toUpperCase();
        return f + str.substr(1);
    }

    /**
     * insert touches by xy per touch
     * [ [x,y], [x,y] ]
     * @param {Array} touches
     */
    FakeTouches.prototype.setTouches = function(touches) {
        return this.touches = touches;
    };

    /**
     * simple methods to just trigger an event
     */
    ['start','end','move','cancel'].forEach(function(val) {
        FakeTouches.prototype['trigger'+ ucfirst(val)] = (function(type) {
            return function(touches) {
                if(touches) {
                    this.touches = touches;
                }

                this.triggerEvent(type);
            };
        })(val);
    });

    /**
     * move touches to new positions. all with x ammount, or per touch
     * @param  {Mixed}  dx      When dx is an array, each touch can be updated
     * @param  {Number} [dy]
     */
    FakeTouches.prototype.moveBy = function(dx, dy) {
        var self = this;
        // each touch must be updated
        if(typeof dx == 'object') {
            var delta_touches = dx;
            this.touches.forEach(function(val, i) {
                self.touches[i][0] += delta_touches[i][0];
                self.touches[i][1] += delta_touches[i][1];
            });
        }
        // add dx,dy to all touches
        else {
            this.touches.forEach(function(val, i) {
                self.touches[i][0] += dx;
                self.touches[i][1] += dy;
            });
        }

        this.triggerMove();

        return this.touches;
    };

    FakeTouches.prototype.createTouchList = function(touches) {
        var touchlist = [];
        touches.forEach(function(val, index) {
            touchlist.push({
                pageX: val[0],
                pageY: val[1],
                clientX: val[0],
                clientY: val[1],
                identifier: index
            });
        });
        return touchlist;
    };

    FakeTouches.prototype.triggerEvent = function(type) {
        switch(this.touch_type) {
            case FakeTouches.TOUCH_EVENTS:
                triggerTouch.call(this, type);
                break;

            case FakeTouches.MOUSE_EVENTS:
                triggerMouse.call(this, type);
                break;

            case FakeTouches.TOUCH_AND_MOUSE_EVENTS:
                triggerTouch.call(this, type);
                triggerMouse.call(this, type);
                break;

            case FakeTouches.POINTER_TOUCH_EVENTS:
                triggerPointerEvents.call(this, type, FakeTouches.POINTER_TYPE_TOUCH);
                break;

            case FakeTouches.POINTER_MOUSE_EVENTS:
                triggerPointerEvents.call(this, type, FakeTouches.POINTER_TYPE_MOUSE);
                break;
        }
    };

    /**
     * trigger touch event
     * @param type
     * @returns {Boolean}
     */
    function triggerTouch(type) {
        var event = document.createEvent('Event');
        event.initEvent('touch'+ type, true, true);

        var touchlist = this.createTouchList(this.touches);
        if(type == 'end' || type == 'cancel') {
            event.touches = [];
        }
        else {
            event.touches = touchlist;
        }

        return this.element.dispatchEvent(event);
    }

    /**
     * trigger mouse event
     * @param type
     * @returns {Boolean}
     */
    function triggerMouse(type) {
        var names = {
            start: 'mousedown',
            move: 'mousemove',
            end: 'mouseup'
        };

        var event = document.createEvent('Event');
        event.initEvent(names[type], true, true);
        var touchList = this.createTouchList(this.touches);
        if(touchList[0]) {
            event.pageX = touchList[0].pageX;
            event.pageY = touchList[0].pageY;
            event.clientX = touchList[0].clientX;
            event.clientY = touchList[0].clientY;
            event.target = this.element;
            event.which = 1;
        }
        return this.element.dispatchEvent(event);
    }

    /**
     * trigger pointer event
     * @param type
     * @param pointerType
     * @returns {Boolean}
     */
    function triggerPointerEvents(type, pointerType) {
        var self = this;
        var names = {
            start: 'MSPointerDown',
            move: 'MSPointerMove',
            end: 'MSPointerUp'
        };

        var touchList = this.createTouchList(this.touches);
        touchList.forEach(function(touch) {
            var event = document.createEvent('Event');
            event.initEvent(names[type], true, true);

            event.MSPOINTER_TYPE_MOUSE = FakeTouches.POINTER_TYPE_MOUSE;
            event.MSPOINTER_TYPE_TOUCH = FakeTouches.POINTER_TYPE_TOUCH;

            event.pointerId = touch.identifier;
            event.pointerType = pointerType;
            event.pageX = touch.pageX;
            event.pageY = touch.pageY;
            event.clientX = touch.clientX;
            event.clientY = touch.clientY;
            event.target = self.element;

            if(pointerType === FakeTouches.POINTER_TYPE_MOUSE) {
                event.which = 1;
            }

            self.element.dispatchEvent(event);
        });

        return true;
    }

    window.FakeTouches = FakeTouches;

    return FakeTouches;
}));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Persoonia 11(4): 463 (1982)

#### Original name
Entoloma allochroum Noordel.

### Remarks
null


text:
    <title>Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css" rel="stylesheet" type="text/css">

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

            </button>
            Login

                About

Welcome to the dist_health

Please Login:

            <form role="form">

                Email address
                <input class="form-control" id="exampleInputEmail1" placeholder="Enter email" type="email">

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

              <button type="submit" class="btn btn-default">Submit</button>
            </form>


text:
layout: post
title:  "Hello, Portland"
date:   2016-01-31 09:11:03
description: Phasellus hendrerit. Pellent aliquet nibh nec urna. In nis aliquet vel, dapibus id,mattis.
thumbnail: person1.jpeg
categories: category1

# Information for the author block
author: Nina Petropoulos
---
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut [enim ad minim][link1] veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. [Ut enim ad minim veniam][link2], quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, [consectetur adipisicing elit][link3], sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip

###Ut Labore et Dolore

Ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet:

1. consectetur adipisicing elit
2. sed do eiusmod tempor incididunt
3. ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

[link1]: example.net
[link2]: example.com
[link3]: example.org


text:
package gateway

import (
	"io/ioutil"
	"net"
	"os"
	"path/filepath"
	"sync"
	"testing"

	"github.com/NebulousLabs/Sia/build"
	"github.com/NebulousLabs/Sia/modules"
	siasync "github.com/NebulousLabs/Sia/sync"
)

// newTestingGateway returns a gateway read to use in a testing environment.
func newTestingGateway(name string, t *testing.T) *Gateway {
	if testing.Short() {
		panic("newTestingGateway called during short test")
	}

	g, err := New("localhost:0", false, build.TempDir("gateway", name))
	if err != nil {
		panic(err)
	}
	return g
}

// TestExportedMethodsErrAfterClose tests that exported methods like Close and
// Connect error with siasync.ErrStopped after the gateway has been closed.
func TestExportedMethodsErrAfterClose(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	g := newTestingGateway("TestCloseErrsSecondTime", t)
	if err := g.Close(); err != nil {
		t.Fatal(err)
	}
	if err := g.Close(); err != siasync.ErrStopped {
		t.Fatalf("expected %q, got %q", siasync.ErrStopped, err)
	}
	if err := g.Connect("localhost:1234"); err != siasync.ErrStopped {
		t.Fatalf("expected %q, got %q", siasync.ErrStopped, err)
	}
}

// TestAddress tests that Gateway.Address returns the address of its listener.
// Also tests that the address is not unspecified and is a loopback address.
// The address must be a loopback address for testing.
func TestAddress(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	g := newTestingGateway("TestAddress", t)
	defer g.Close()
	if g.Address() != g.myAddr {
		t.Fatal("Address does not return g.myAddr")
	}
	if g.Address() != modules.NetAddress(g.listener.Addr().String()) {
		t.Fatalf("wrong address: expected %v, got %v", g.listener.Addr(), g.Address())
	}
	host := modules.NetAddress(g.listener.Addr().String()).Host()
	ip := net.ParseIP(host)
	if ip == nil {
		t.Fatal("address is not an IP address")
	}
	if ip.IsUnspecified() {
		t.Fatal("expected a non-unspecified address")
	}
	if !ip.IsLoopback() {
		t.Fatal("expected a loopback address")
	}
}

// TestPeers checks that two gateways are able to connect to each other.
func TestPeers(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	g1 := newTestingGateway("TestRPC1", t)
	defer g1.Close()
	g2 := newTestingGateway("TestRPC2", t)
	defer g2.Close()
	err := g1.Connect(g2.Address())
	if err != nil {
		t.Fatal("failed to connect:", err)
	}
	peers := g1.Peers()
	if len(peers) != 1 || peers[0].NetAddress != g2.Address() {
		t.Fatal("g1 has bad peer list:", peers)
	}
	err = g1.Disconnect(g2.Address())
	if err != nil {
		t.Fatal("failed to disconnect:", err)
	}
	peers = g1.Peers()
	if len(peers) != 0 {
		t.Fatal("g1 has peers after disconnect:", peers)
	}
}

// TestNew checks that a call to New is effective.
func TestNew(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	if _, err := New("", false, ""); err == nil {
		t.Fatal("expecting persistDir error, got nil")
	}
	if _, err := New("localhost:0", false, ""); err == nil {
		t.Fatal("expecting persistDir error, got nil")
	}
	if g, err := New("foo", false, build.TempDir("gateway", "TestNew1")); err == nil {
		t.Fatal("expecting listener error, got nil", g.myAddr)
	}
	// create corrupted nodes.json
	dir := build.TempDir("gateway", "TestNew2")
	os.MkdirAll(dir, 0700)
	err := ioutil.WriteFile(filepath.Join(dir, "nodes.json"), []byte{1, 2, 3}, 0660)
	if err != nil {
		t.Fatal("couldn't create corrupted file:", err)
	}
	if _, err := New("localhost:0", false, dir); err == nil {
		t.Fatal("expected load error, got nil")
	}
}

// TestClose creates and closes a gateway.
func TestClose(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	t.Parallel()

	g := newTestingGateway("TestClose", t)
	err := g.Close()
	if err != nil {
		t.Fatal(err)
	}
}

// TestParallelClose spins up 3 gateways, connects them all, and then closes
// them in parallel. The goal of this test is to make it more vulnerable to any
// potential nondeterministic failures.
func TestParallelClose(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	t.Parallel()

	// Spin up three gateways in parallel.
	var g1, g2, g3 *Gateway
	var wg sync.WaitGroup
	wg.Add(3)
	go func() {
		g1 = newTestingGateway("TestParallelClose - 1", t)
		wg.Done()
	}()
	go func() {
		g2 = newTestingGateway("TestParallelClose - 2", t)
		wg.Done()
	}()
	go func() {
		g3 = newTestingGateway("TestParallelClose - 3", t)
		wg.Done()
	}()
	wg.Wait()

	// Connect g1 to g2, g2 to g3. They may connect to eachother further.
	wg.Add(2)
	go func() {
		err := g1.Connect(g2.myAddr)
		if err != nil {
			panic(err)
		}
		wg.Done()
	}()
	go func() {
		err := g2.Connect(g3.myAddr)
		if err != nil {
			panic(err)
		}
		wg.Done()
	}()
	wg.Wait()

	// Close all three gateways in parallel.
	wg.Add(3)
	go func() {
		err := g1.Close()
		if err != nil {
			panic(err)
		}
		wg.Done()
	}()
	go func() {
		err := g2.Close()
		if err != nil {
			panic(err)
		}
		wg.Done()
	}()
	go func() {
		err := g3.Close()
		if err != nil {
			panic(err)
		}
		wg.Done()
	}()
	wg.Wait()
}