text:
/*----------------------------------------------------------------------------*/
/*  mainwin.c                                                                 */
/*----------------------------------------------------------------------------*/
/*  copyright         : (C) 2002 by Dao Hai Lam                               */
/*                      VISC Software & Security Consultant Company           */
/*                      Hall 3, Quang Trung Software City                     */
/*                      Tan Chanh Hiep Ward, District 12,                     */
/*                      Ho Chi Minh city, VIETNAM                             */
/*  website           : http://www.visc-network.com                           */
/*  email             : lam@visc-network.com                                  */
/*  last modify       : Thu, 18 Apr 2002 22:00:33 +0700                       */
/*----------------------------------------------------------------------------*/
/*                                                                            */
/*   This program is free software; you can redistribute it and/or modify     */
/*   it under the terms of the GNU General Public License as published by     */
/*   the Free Software Foundation; either version 2 of the License, or        */
/*   (at your option) any later version.                                      */
/*                                                                            */
/*----------------------------------------------------------------------------*/
#include "data.h"
#include "menu.h"
#include "event.h"
#include "systray.h"
/*----------------------------------------------------------------------------*/
char *Ss[] = { "Off", "Vni", "Telex", "Viqr" };
/*----------------------------------------------------------------------------*/
void VKIconLoadInterface()
{
	Ss[0] = vk_interface==VK_VIETNAMESE ? "Tắt" : "Off";
}
/*----------------------------------------------------------------------------*/
void VKMainWindowProcess(XEvent *event, void *data);
/*----------------------------------------------------------------------------*/
void VKDrawIcon()
{
	long x, y, h, l;
	char *S = (vk_docking == VKD_ON) ? (vk_method == VKM_OFF ? "N" : "V") : Ss[vk_method];

#ifdef USE_XFT
	XftDraw *draw;
	XGlyphInfo fi;
	XftTextExtentsUtf8(display, vk_font, (uchar *)S, l=strlen(S), &fi);
#else
	XRectangle fi;
	XmbTextExtents(vk_fontset, S, l=strlen(S), 0, &fi);
#endif
	h = vk_text_height;
	x = (vk_icon_width - fi.width)/2;
	y = vk_text_ascent + (vk_icon_height - h)/2 + 1;

	XClearWindow(display, main_window);
	VKSetColor(display, main_gc, clBackground);
	XFillRectangle(display, main_window, main_gc,
							0, 0, vk_icon_width, vk_icon_height);
	VKSetColor(display, main_gc, clBorder);
	XDrawRectangle(display, main_window, main_gc,
							1, 1, vk_icon_width-3, vk_icon_height-3);
#ifdef USE_XFT
	draw = XftDrawCreate(display, main_window, visual, colormap);
	XftDrawStringUtf8(draw, &clGray, vk_font, x+1, y+1, (XftChar8*)S, l);
	XftDrawStringUtf8(draw, &clText, vk_font, x, y, (XftChar8*)S, l);
	XftDrawDestroy(draw);
#else
	XSetForeground(display, main_gc, clGray);
	XmbDrawString(display, main_window, vk_fontset, main_gc, x+1, y+1, S, l);
	XSetForeground(display, main_gc, clText);
	XmbDrawString(display, main_window, vk_fontset, main_gc, x, y, S, l);
#endif
}
/*----------------------------------------------------------------------------*/
void VKSetDefaultColor()
{
	clBackground = clWhite;
	clBorder = clMenuBar;
	clText = clRed;
}
/*----------------------------------------------------------------------------*/
void VKSetMainWindowHints(int w, int h)
{
	XSizeHints sh;
	sh.flags = PMinSize | PMaxSize;
	sh.min_width = sh.max_width = w;
	sh.min_height = sh.max_height = h;
	XSetWMNormalHints(display, main_window, &sh);
}
/*----------------------------------------------------------------------------*/
void VKCalcMainWindowSize()
{
	if( vk_docking == VKD_ON ) {
		VKSystrayCalcIconSize();
		return;
	}
#ifdef USE_XFT
	XGlyphInfo fi;
	XftTextExtentsUtf8(display, vk_font, (uchar *)"Telex", 5, &fi);
	vk_icon_width = fi.width + 16;
	vk_icon_height = 16 + vk_text_height;
#else
	vk_icon_width = XTextWidth(vk_font, "Telex", 5) + 16;
	vk_icon_height = 16 + vk_text_height;
#endif
	if( vk_x==-1 && vk_y==-1 ) {
		vk_x = screen_width - vk_icon_width - 12;
		vk_y = screen_height - vk_icon_height - 2;
	}
	else {
		if( vk_x<0 )
			vk_x = 0;
		else
		if( vk_x+vk_icon_width>=screen_width )
			vk_x = screen_width - vk_icon_width - 1;

		if( vk_y<0 )
			vk_y = 0;
		else
		if( vk_y+vk_icon_height>=screen_height )
			vk_y = screen_height - vk_icon_height - 1;
	}
}
/*----------------------------------------------------------------------------*/
void VKCreateMainWindow()
{
	VKIconLoadInterface();
	VKCalcMainWindowSize();
	main_window = XCreateWindow(display, root,
					vk_x, vk_y, vk_icon_width, vk_icon_height, 0,
					DefaultDepth(display, screen), InputOutput, visual,
					vk_attribmask, &vk_attrib);
	XSetSelectionOwner(display, visckey_atom, main_window, CurrentTime);
	XSelectInput(display, main_window,
		MAIN_EVENT_MASKS|VisibilityChangeMask|StructureNotifyMask);

	main_gc = XCreateGC(display, main_window, 0, 0);
	XDefineCursor(display, main_window, vk_cursor);
#ifndef USE_XFT
	XSetFont(display, main_gc, vk_font->fid);
#endif
	XStoreName(display, main_window, PROGRAM_NAME);
	XChangeProperty(display, main_window, XInternAtom(display, "WM_CLASS", False),
		XA_STRING, 8, PropModeReplace, (uchar *)PROGRAM_NAME, strlen(PROGRAM_NAME));
	XChangeProperty(display, main_window, XInternAtom(display, "_NET_WM_NAME", False),
		XA_STRING, 8, PropModeReplace, (uchar *)PROGRAM_NAME, strlen(PROGRAM_NAME));
	VKRegisterEvent(main_window, VKMainWindowProcess, NULL);

	if( vk_docking != VKD_OFF ) { // ON or AUTO
		if( VKIsDockable() ) {
			vk_docking = VKD_ON;
			VKSetMainWindowHints(vk_icon_height, vk_icon_height);
			VKRequestDocking();
		}
		else {
			vk_docking = VKD_OFF;
			XMapWindow(display, main_window);
			VKSetAutoDocking(VKD_ON);
		}
	}
	else {
		vk_docking = VKD_OFF;
		XMapWindow(display, main_window);
	}

	VKSetDefaultColor();
}
/*----------------------------------------------------------------------------*/
void VKDestroyMainWindow()
{
	VKUnregisterEvent(main_window);

	XFreeGC(display, main_gc);
	XDestroyWindow(display, main_window);
}
/*----------------------------------------------------------------------------*/
void VKDockMainWindow()
{
	if( VKIsDockable() ) {
		vk_docking = VKD_ON;
		VKDestroyMainWindow();
		VKCreateMainWindow();
		VKUpdateDockingMessage();
	}
}
/*----------------------------------------------------------------------------*/
void VKUndockMainWindow()
{
	vk_docking = VKD_OFF;
	VKDestroyMainWindow();
	VKCreateMainWindow();
	VKUpdateDockingMessage();
}
/*----------------------------------------------------------------------------*/
void VKMainWindowProcess(XEvent *event, void *data)
{
	static int x, y;
	static int dragging = False, has_moved = False;

	switch( event->type ) {
		case Expose:
		case GraphicsExpose:
			VKDrawIcon();
			break;
		case ButtonPress:
			VKHideMenu();
			x = event->xbutton.x_root;
			y = event->xbutton.y_root;
			dragging = event->xbutton.button==Button1;
			break;
		case MotionNotify:
			if( vk_docking != VKD_ON && dragging ) {
				has_moved = True;
				vk_x += event->xbutton.x_root - x;
				vk_y += event->xbutton.y_root - y;
				x = event->xbutton.x_root;
				y = event->xbutton.y_root;
				if( vk_x<0 ) vk_x = 0;
				if( vk_y<0 ) vk_y = 0;
				if( vk_x+vk_icon_width>=screen_width )
					vk_x = screen_width-vk_icon_width-1;
				if( vk_y+vk_icon_height>=screen_height )
					vk_y = screen_height-vk_icon_height-1;
				XMoveWindow(display, main_window, vk_x, vk_y);
			}
			break;
		case ButtonRelease:
			dragging = False;
			if( has_moved )
				has_moved = False;
			else
			switch( event->xbutton.button ) {
				case Button1:
					VKSwitchMethod();
					VKDrawIcon();
					break;
				case Button2:
					vk_done = True;
					break;
				case Button3:
					// * Workaround for Fluxbox systray
					// Fluxbox systray doesn't report absolute position
					// of client in ConfigureNotify message event
					vk_x = event->xbutton.x_root - event->xbutton.x;
					vk_y = event->xbutton.y_root - event->xbutton.y;
					VKShowMenu();
					break;
			}
			break;
		case VisibilityNotify:
			if( ((XVisibilityEvent *)event)->state != VisibilityUnobscured )
				XRaiseWindow(display, main_window);
			break;
		case ReparentNotify:
			if( vk_docking == VKD_ON && event->xreparent.parent == root ) {
				VKUndockMainWindow();
				VKSetAutoDocking(VKD_ON);
			}
			break;
		case ConfigureNotify:
			if( vk_docking == VKD_ON ) {
				vk_x = event->xconfigure.x;
				vk_y = event->xconfigure.y;
				vk_icon_width = event->xconfigure.width;
				vk_icon_height = event->xconfigure.height;
				if( vk_icon_height > vk_icon_width )
					vk_icon_width = vk_icon_height;
				else
					vk_icon_height = vk_icon_width;

				VKSetMainWindowHints(vk_icon_width, vk_icon_height);
			}
			break;
		case ClientMessage:
			TRACE("MessageID = %ld\n", event->xclient.data.l[1]);
	}
}
/*----------------------------------------------------------------------------*/


text:
package com.ericsson.research.trap.nhttpd;

import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.net.ssl.SSLContext;

import com.ericsson.research.trap.nio.Nio;
import com.ericsson.research.trap.nio.ServerSocket;
import com.ericsson.research.trap.nio.ServerSocket.ServerSocketHandler;
import com.ericsson.research.trap.nio.Socket;

public class NanoHTTPD implements ServerSocketHandler
{
    /**
     * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) This is required as the Keep-Alive HTTP
     * connections would otherwise block the socket reading thread forever (or as long the browser is open).
     */
    public static final int        SOCKET_READ_TIMEOUT    = 5000;
    /**
     * Common mime type for dynamic content: plain text
     */
    public static final String     MIME_PLAINTEXT         = "text/plain";
    /**
     * Common mime type for dynamic content: html
     */
    public static final String     MIME_HTML              = "text/html";
    /**
     * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.
     */
    private static final String    QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
    private final String           hostname;
    private final int              myPort;
    private ServerSocket           myServerSocket;
    private Set<Socket>            openConnections        = new HashSet<Socket>();
    /**
     * Pluggable strategy for asynchronously executing requests.
     */
    AsyncRunner                    asyncRunner;
    /**
     * Pluggable strategy for creating and cleaning up temporary files.
     */
    private TempFileManagerFactory tempFileManagerFactory;
    private SSLContext             sslc;

    /**
     * Constructs an HTTP server on given port.
     */
    public NanoHTTPD(int port)
    {
        this(null, port);
    }

    /**
     * Constructs an HTTP server on given hostname and port.
     */
    public NanoHTTPD(String hostname, int port)
    {
        this.hostname = hostname;
        this.myPort = port;
        setTempFileManagerFactory(new DefaultTempFileManagerFactory());
        setAsyncRunner(new DefaultAsyncRunner());
    }

    static final void safeClose(Closeable closeable)
    {
        if (closeable != null)
        {
            try
            {
                closeable.close();
            }
            catch (IOException e)
            {
            }
        }
    }

    private static final void safeClose(Socket closeable)
    {
        if (closeable != null)
        {
            closeable.close();
        }
    }

    private static final void safeClose(ServerSocket closeable)
    {
        if (closeable != null)
        {
            closeable.close();
        }
    }

    /**
     * Start the server.
     *
     * @throws IOException
     *             if the socket is in use.
     */
    public void start() throws IOException
    {
        if (getSslc() != null)
            myServerSocket = Nio.factory().sslServer(getSslc(), this);
        else
            myServerSocket = Nio.factory().server(this);
        myServerSocket.listen((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    }

    /**
     * Stop the server.
     */
    public void stop()
    {
        try
        {
            safeClose(myServerSocket);
            closeAllConnections();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Registers that a new connection has been set up.
     *
     * @param socket
     *            the {@link Socket} for the connection.
     */
    public synchronized void registerConnection(Socket socket)
    {
        openConnections.add(socket);
    }

    /**
     * Registers that a connection has been closed
     *
     * @param socket
     *            the {@link Socket} for the connection.
     */
    public synchronized void unRegisterConnection(Socket socket)
    {
        openConnections.remove(socket);
    }

    /**
     * Forcibly closes all connections that are open.
     */
    public synchronized void closeAllConnections()
    {
        for (Socket socket : openConnections)
        {
            safeClose(socket);
        }
    }

    public final int getListeningPort()
    {
        try
        {
            return myServerSocket == null ? -1 : myServerSocket.getInetAddress().getPort();
        }
        catch (IOException e)
        {
            return -1;
        }
    }

    public final boolean wasStarted()
    {
        return myServerSocket != null;
    }

    public final boolean isAlive()
    {
        return wasStarted() && !myServerSocket.isClosed();
    }

    /**
     * Override this to customize the server.
     *

     *

     * (By default, this delegates to serveFile() and allows directory listing.)
     *
     * @param uri
     *            Percent-decoded URI without parameters, for example "/index.cgi"
     * @param method
     *            "GET", "POST" etc.
     * @param parms
     *            Parsed, percent decoded parameters from URI and, in case of POST, data.
     * @param headers
     *            Header entries, percent decoded
     * @return HTTP response, see class Response for details
     */
    @Deprecated
    public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files)
    {
        return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
    }

    /**
     * Override this to customize the server.
     *

     *

     * (By default, this delegates to serveFile() and allows directory listing.)
     *
     * @param session
     *            The HTTP session
     * @return HTTP response, see class Response for details
     */
    public Response serve(IHTTPSession session)
    {
        Map<String, String> files = new HashMap<String, String>();
        Method method = session.getMethod();
        if (Method.PUT.equals(method) || Method.POST.equals(method))
        {
            try
            {
                session.parseBody(files);
            }
            catch (IOException ioe)
            {
                return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
            }
            catch (ResponseException re)
            {
                return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
            }
        }

        Map<String, String> parms = session.getParms();
        parms.put(QUERY_STRING_PARAMETER, session.getQueryParameterString());
        return serve(session.getUri(), method, session.getHeaders(), parms, files);
    }

    /**
     * Decode percent encoded String values.
     *
     * @param str
     *            the percent encoded String
     * @return expanded form of the input, for example "foo%20bar" becomes "foo bar"
     */
    protected static String decodePercent(String str)
    {
        String decoded = null;
        try
        {
            decoded = URLDecoder.decode(str, "UTF8");
        }
        catch (UnsupportedEncodingException ignored)
        {
        }
        return decoded;
    }

    /**
     * Decode parameters from a URL, handing the case where a single parameter name might have been supplied several
     * times, by return lists of values. In general these lists will contain a single element.
     *
     * @param parms
     *            original NanoHttpd parameters values, as passed to the serve() method.
     * @return a map of String (parameter name) to List<String> (a list of the values
     *         supplied).
     */
    protected Map<String, List<String>> decodeParameters(Map<String, String> parms)
    {
        return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER));
    }

    /**
     * Decode parameters from a URL, handing the case where a single parameter name might have been supplied several
     * times, by return lists of values. In general these lists will contain a single element.
     *
     * @param queryString
     *            a query string pulled from the URL.
     * @return a map of String (parameter name) to List<String> (a list of the values
     *         supplied).
     */
    protected Map<String, List<String>> decodeParameters(String queryString)
    {
        Map<String, List<String>> parms = new HashMap<String, List<String>>();
        if (queryString != null)
        {
            StringTokenizer st = new StringTokenizer(queryString, "&");
            while (st.hasMoreTokens())
            {
                String e = st.nextToken();
                int sep = e.indexOf('=');
                String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
                if (!parms.containsKey(propertyName))
                {
                    parms.put(propertyName, new ArrayList<String>());
                }
                String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null;
                if (propertyValue != null)
                {
                    parms.get(propertyName).add(propertyValue);
                }
            }
        }
        return parms;
    }

    // ------------------------------------------------------------------------------- //
    //
    // Threading Strategy.
    //
    // ------------------------------------------------------------------------------- //

    /**
     * Pluggable strategy for asynchronously executing requests.
     *
     * @param asyncRunner
     *            new strategy for handling threads.
     */
    public void setAsyncRunner(AsyncRunner asyncRunner)
    {
        this.asyncRunner = asyncRunner;
    }

    // ------------------------------------------------------------------------------- //
    //
    // Temp file handling strategy.
    //
    // ------------------------------------------------------------------------------- //

    /**
     * Pluggable strategy for creating and cleaning up temporary files.
     *
     * @param tempFileManagerFactory
     *            new strategy for handling temp files.
     */
    public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory)
    {
        this.tempFileManagerFactory = tempFileManagerFactory;
    }

    /**
     * HTTP Request methods, with the ability to decode a String back to its enum value.
     */
    public enum Method
    {
        GET, PUT, POST, DELETE, HEAD, OPTIONS;

        static Method lookup(String method)
        {
            for (Method m : Method.values())
            {
                if (m.toString().equalsIgnoreCase(method))
                {
                    return m;
                }
            }
            return null;
        }
    }

    /**
     * Pluggable strategy for asynchronously executing requests.
     */
    public interface AsyncRunner
    {
        void exec(Runnable code);
    }

    @Override
    public void accept(Socket sock, ServerSocket ss)
    {
        registerConnection(sock);
        sock.setSoTimeout(SOCKET_READ_TIMEOUT);
        TempFileManager tempFileManager = tempFileManagerFactory.create();
        try
        {
            new HTTPSession(this, tempFileManager, sock);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void error(Throwable exc, ServerSocket ss)
    {
        // TODO Auto-generated method stub

    }

    public SSLContext getSslc()
    {
        return sslc;
    }

    public void setSslc(SSLContext sslc)
    {
        this.sslc = sslc;
    }

    public InetSocketAddress getAddress() throws IOException
    {
        return myServerSocket.getInetAddress();
    }

    // ------------------------------------------------------------------------------- //

}

redpajama_set_name: RedPajamaGithub


text:
<TITLE>Review for Wag the Dog (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Wag the Dog (1997)

reviewed by
Edward Johnson-Ott

Wag The Dog (1997)
Robert De Niro, Dustin Hoffman, Anne Heche, Woody Harrelson, Denis Leary,
Andrea Martin, Willie Nelson, Suzie Plakson, Kirsten Dunst, William H.
Macy, Craig T. Nelson. Directed by Barry Levinson. Rated R, 4 stars (out
of five stars)

Review by Ed Johnson-Ott, NUVO Newsweekly
www.nuvo-online.com/film/
Archive reviews at http://us.imdb.com/M/reviews_by?Edward+Johnson-ott

In politics, image is absolutely everything. Early in "Wag The Dog,"
someone challenges a top-level Presidential spin doctor about truth and
he snaps "The truth? I'll tell you about truth. I saw the first draft of
the Warren Commission Report. It said Kennedy was killed by a drunk
driver."
"Wag The Dog" is a hilarious black comedy about people so far removed
from morals that questions of right or wrong never even enter their minds.
 Their only consideration is the effectiveness of their elaborate
deceptions, and who gets a cut of the merchandising profits. Cynical? Of
course, but Barry Levinson's crackerjack direction maintains such a giddy
momentum that there's really no time to reflect on how awful these people
are. Instead, you just sit back and enjoy their brazen scheming.
Here's the set-up. 11 days before the election, the incumbent President,
who has enjoyed a 17% lead in the polls, is accused of hitting on an
underage girl during a White House tour. Within hours, his challenger
(Craig T. Nelson) has crafted devastating new TV ads, set to the tune of
"Thank Heavens For Little Girls." Quickly, Presidential assistant
Winifred Ames (Anne Heche) calls in damage control expert Conrad Brean
(Robert De Niro,) who reasons that the only way for the President to be
re-elected is if they create a crisis big enough to divert the nation's
attention from the scandal. Perhaps a war, maybe with Albania. "Why
Albania?" asks Ames. "Why not," laughs Brean. To orchestrate the pretend
war, he enlists the aid of Hollywood producer Stanley Motss (Dustin
Hoffman,) who is more than happy to help. "You know, there's not an
Academy Award for producers," he moans, "Why is that? Do they think these
things produce themselves?"
Motss quickly plots out the scenario for the crisis, then pulls together
his experts to work on the really important stuff; the war's official
slogan, theme song and merchandising tie-ins. When "that yellow ribbon
business" is mentioned, Ames interrupts to explain that the yellow
ribbons were a naturally occurring phenomenon. She stops short though,
when she notices Brean smiling wearily at her naiveté.
And so the scam begins, with Brean instructing a White House Press
Secretary to tell reporters that there is absolutely no truth to the
rumors about problems in Albania relating to the B-3 bomber. When
reminded that there is no B-3 bomber, Brean smiles confidently and says,
"Exactly." The White House press corps dutifully responds to the bait,
and within hours the nation is riveted to their TV sets, watching the
latest on the crisis in Albania.
David Mamet and Hilary Henkin's screenplay, based on the book by Larry
Beinhart, is incredibly slick and fast-moving, operating on the
assumption that movie-goers are savvy enough to roll with the concept.
And, thanks to the surreal political realities of today, the absurdist
story seems all too possible.
Barry Levinson is a uneven director, turning out a few great works ("Rain
Man") and some real dogs ("Toys",) but he's in top form here. He shot
"Wag The Dog" in just 29 days, and the film has an immediacy that keeps
the proceedings buoyant. His camera work displays a breezy confidence and
a great sense of play. It's obvious the director was having a wonderful
time turning out this wicked little film.
Of course, it would be hard not to have fun with a cast like this. Anne
Heche has a beguiling effervescence as the president's assistant.
Winifred Ames may be new to deception at such a massive scale, but she
hops right in and does her part. Robert De Niro exudes an ominous
confidence as the man making the big decisions. His exact title is never
divulged; you simply understand that when things go wrong, he's the guy
you call to fix them. His role is much like Harvey Keitel's suave mob
character in "Pulp Fiction," which makes perfect sense in this perverse
context. Adding to the lunacy is Woody Harrelson in a deliciously twisted
cameo as the designated hero for the bogus war.
But despite the fine performances of the rest of the cast, it's Dustin
Hoffman who steals the show with his Oscar-worthy portrayal of producer
Stanley Motss. Rich, spoiled and self-obsessed, Motss is a fascinating
character. Mid-way through the film, when the opposition catches on and
orchestrates a televised announcement that the war has ended, Motss
explodes, shouting "Over?! This war isn't over until I say it's over!" To
Hoffman's credit, you don't doubt him for a second.
Skirting the line between preposterousness and uncomfortable plausibility,
 "Wag The Dog" is a nightmarish delight that invites comparisons to such
great satires as "Network" and "Dr. Strangelove." Prepare to laugh
yourself silly, and let's all pray that the film is less true than it
seems to be.

Copyright 1997, Ed Johnson-Ott

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import logging
import pytest
from copy import deepcopy

from testdata.common import widetable
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
from tests.util.test_file_parser import *
from tests.common.test_dimensions import create_single_exec_option_dimension

class TestScannersAllTableFormats(ImpalaTestSuite):
  BATCH_SIZES = [0, 1, 16]

  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestScannersAllTableFormats, cls).add_test_dimensions()
    if cls.exploration_strategy() == 'core':
      # The purpose of this test is to get some base coverage of all the file formats.
      # Even in 'core', we'll test each format by using the pairwise strategy.
      cls.TestMatrix.add_dimension(cls.create_table_info_dimension('pairwise'))
    cls.TestMatrix.add_dimension(
        TestDimension('batch_size', *TestScannersAllTableFormats.BATCH_SIZES))

  def test_scanners(self, vector):
    new_vector = deepcopy(vector)
    new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
    self.run_test_case('QueryTest/scanners', new_vector)

# Test all the scanners with a simple limit clause. The limit clause triggers
# cancellation in the scanner code paths.
class TestScannersAllTableFormatsWithLimit(ImpalaTestSuite):
  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestScannersAllTableFormatsWithLimit, cls).add_test_dimensions()

  def test_limit(self, vector):
    # Use a small batch size so changing the limit affects the timing of cancellation
    vector.get_value('exec_option')['batch_size'] = 100
    iterations = 50
    query_template = "select * from alltypes limit %s"
    for i in range(1, iterations):
      # Vary the limit to vary the timing of cancellation
      query = query_template % ((iterations * 100) % 1000 + 1)
      self.execute_query(query, vector.get_value('exec_option'),
          table_format=vector.get_value('table_format'))

# Test case to verify the scanners work properly when the table metadata (specifically the
# number of columns in the table) does not match the number of columns in the data file.
class TestUnmatchedSchema(ImpalaTestSuite):
  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestUnmatchedSchema, cls).add_test_dimensions()
    cls.TestMatrix.add_dimension(create_single_exec_option_dimension())
    # Avro has a more advanced schema evolution process which is covered in more depth
    # in the test_avro_schema_evolution test suite.
    cls.TestMatrix.add_constraint(\
        lambda v: v.get_value('table_format').file_format != 'avro')

  def __get_table_location(self, table_name, vector):
    result = self.execute_query_using_client(self.client,
        "describe formatted %s" % table_name, vector)
    for row in result.data:
      if 'Location:' in row:
        return row.split('\t')[1]
    # This should never happen.
    assert 0, 'Unable to get location for table: ' + table_name

  def __create_test_table(self, vector):
    """
    Creates the test table

    Cannot be done in a setup method because we need access to the current test vector
    """
    self.__drop_test_table(vector)
    self.execute_query_using_client(self.client,
        "create external table jointbl_test like jointbl", vector)

    # Update the location of the new table to point the same location as the old table
    location = self.__get_table_location('jointbl', vector)
    self.execute_query_using_client(self.client,
        "alter table jointbl_test set location '%s'" % location, vector)

  def __drop_test_table(self, vector):
    self.execute_query_using_client(self.client,
        "drop table if exists jointbl_test", vector)

  def test_unmatched_schema(self, vector):
    table_format = vector.get_value('table_format')
    # jointbl has no columns with unique values. When loaded in hbase, the table looks
    # different, as hbase collapses duplicates.
    if table_format.file_format == 'hbase':
      pytest.skip()
    self.__create_test_table(vector)
    self.run_test_case('QueryTest/test-unmatched-schema', vector)
    self.__drop_test_table(vector)

# Tests that scanners can read a single-column, single-row, 10MB table
class TestWideRow(ImpalaTestSuite):
  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestWideRow, cls).add_test_dimensions()
    # I can't figure out how to load a huge row into hbase
    cls.TestMatrix.add_constraint(
      lambda v: v.get_value('table_format').file_format != 'hbase')

  def test_wide_row(self, vector):
    new_vector = deepcopy(vector)
    # Use a 5MB scan range, so we will have to perform 5MB of sync reads
    new_vector.get_value('exec_option')['max_scan_range_length'] = 5 * 1024 * 1024
    # We need > 10 MB of memory because we're creating extra buffers:
    # - 10 MB table / 5 MB scan range = 2 scan ranges, each of which may allocate ~20MB
    # - Sync reads will allocate ~5MB of space
    # The 80MB value used here was determined empirically by raising the limit until the
    # query succeeded for all file formats -- I don't know exactly why we need this much.
    # TODO: figure out exact breakdown of memory usage (IMPALA-681)
    new_vector.get_value('exec_option')['mem_limit'] = 80 * 1024 * 1024
    self.run_test_case('QueryTest/wide-row', new_vector)

class TestWideTable(ImpalaTestSuite):
  # TODO: expand this to more rows when we have the capability
  NUM_COLS = [250, 500, 1000]

  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestWideTable, cls).add_test_dimensions()
    cls.TestMatrix.add_constraint(
      lambda v: v.get_value('table_format').file_format != 'hbase')
    cls.TestMatrix.add_dimension(TestDimension("num_cols", *cls.NUM_COLS))
    # To cut down on test execution time, only run in exhaustive.
    if cls.exploration_strategy() != 'exhaustive':
      cls.TestMatrix.add_constraint(lambda v: False)

  def test_wide_table(self, vector):
    NUM_COLS = vector.get_value('num_cols')
    NUM_ROWS = 10
    DB_NAME = QueryTestSectionReader.get_db_name(vector.get_value('table_format'))
    TABLE_NAME = "%s.widetable_%s_cols" % (DB_NAME, NUM_COLS)

    result = self.client.execute("select count(*) from %s " % TABLE_NAME)
    assert result.data == [str(NUM_ROWS)]

    expected_result = widetable.get_data(NUM_COLS, NUM_ROWS, quote_strings=True)
    result = self.client.execute("select * from %s" % TABLE_NAME)

    types = parse_column_types(result.schema)
    labels = parse_column_labels(result.schema)
    expected = QueryTestResult(expected_result, types, labels, order_matters=False)
    actual = QueryTestResult(parse_result_rows(result), types, labels,
        order_matters=False)
    assert expected == actual

class TestParquet(ImpalaTestSuite):
  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestParquet, cls).add_test_dimensions()
    cls.TestMatrix.add_constraint(
      lambda v: v.get_value('table_format').file_format == 'parquet')

  def test_parquet(self, vector):
    self.run_test_case('QueryTest/parquet', vector)

# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]

class TestScanRangeLengths(ImpalaTestSuite):
  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestScanRangeLengths, cls).add_test_dimensions()
    cls.TestMatrix.add_dimension(
        TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))

  def test_scan_ranges(self, vector):
    vector.get_value('exec_option')['max_scan_range_length'] =\
        vector.get_value('max_scan_range_length')
    self.run_test_case('QueryTest/hdfs-tiny-scan', vector)


text:
package software.amazon.awssdk.enhanced.dynamodb.model;

import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.async.SdkPublisher;

/**
 * Represents the result from paginated operations such as scan and query.
 *

 * You can either subscribe to the {@link Page}s or flattened items across all pages via {@link #items()}.
 *
 * Example:
 *

 * 1) Subscribing to {@link Page}s
 *

 * {@code
 *
 * PagePublisher<MyItem> publisher = mappedTable.scan();
 * publisher.subscribe(page -> page.items().forEach(item -> System.out.println(item)))
 *          .exceptionally(failure -> {
 *              failure.printStackTrace();
 *              return null;
 *          });
 * }
 *

 *
 *

 * 2) Subscribing to items across all pages.
 *

 * {@code
 *
 * PagePublisher<MyItem> publisher = mappedTable.scan();
 * publisher.items()
 *          .subscribe(item -> System.out.println(item))
 *          .exceptionally(failure -> {
 *              failure.printStackTrace();
 *              return null;
 *          });
 * }
 *

 *
 * @param <T> The modelled type of the object in a page.
 */
@SdkPublicApi
@ThreadSafe
public interface PagePublisher<T> extends SdkPublisher<Page<T>> {

    /**
     * Creates a flattened items publisher with the underlying page publisher.
     */
    static <T> PagePublisher<T> create(SdkPublisher<Page<T>> publisher) {
        return publisher::subscribe;
    }

    /**
     * Returns a publisher that can be used to request a stream of items across all pages.
     *
     *

     * This method is useful if you are interested in subscribing the items in the response pages
     * instead of the top level pages.
     */
    default SdkPublisher<T> items() {
        return this.flatMapIterable(Page::items);
    }
}


text:
var C = require('../index');
var assert = require('chai').assert;

describe('.all', function() {
    var promises;

    describe('when its arguments are native promises', function() {
        beforeEach(function() {
            promises = [
                Promise.resolve(1),
                Promise.resolve(2)
            ];
        });

        it('waits for its arguments to be settled', function() {
            return C.all(promises).then(function (arg){
                assert.sameMembers(arg, [1, 2]);
            });
        });
    });

    describe('when its arguments are cranberry promises', function() {
        beforeEach(function() {
            promises = [
                C.resolve(1),
                C.resolve(2)
            ];
        });

        it('waits for its arguments to be settled', function() {
            return C.all(promises).then(function (arg){
                assert.sameMembers(arg, [1, 2]);
            });
        });
    });
});


text:
        <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">

        </button>
        WordNet Workbench
Client: v{{clientVersion}}, API: v{{apiVersion}}

-1">
                Edit view

Admin view

                Admin view

Main view

                 {{workingLexicon.resource.name}} {{workingLexicon.version}} [{{workingLexicon.language}}]

                        {{value.resource.name}} {{value.version}} [{{value.language}}]

                 Lexicon stats

-1" class="dropdown" style="line-height: 1em;">
                 New

                        New SynSet

 Browse

-1"> Advanced search

{{principal.first_name}} {{principal.last_name}} ({{principal.username}})

 Log out


text:
<?xml version="1.0" encoding="utf-8"?>
<extension version="2.1" type="plugin" group="cart">
	<name>plg_cart_upay</name>
	<author>HUBzero</author>
	<authorUrl>hubzero.org</authorUrl>
	<authorEmail>support@hubzero.org</authorEmail>
	<copyright>Copyright 2005-2019 HUBzero Foundation, LLC.</copyright>
	<license>http://opensource.org/licenses/MIT MIT</license>
	<description>PLG_CART_UPAY_XML_DESCRIPTION</description>
	<files>
		<filename plugin="upay">upay.php</filename>
	</files>
	<languages>
		<language tag="en-GB">en-GB.plg_cart_upay.ini</language>
	</languages>
	<config>
		<fields name="params">
			<fieldset name="basic">
				<field name="title" type="text" default="PayPal" label="Tab title" description="Tab title"/>

				<field type="spacer" />

				<field name="paymentSiteId" type="text" default="" label="UPay site ID" description="UPay site ID"/>
				<field name="paymentValidationKey" type="text" default="" label="Payment validation key" description="Payment validation key"/>
				<field name="env" type="radio" label="Environment" default="1" description="Environment">
					<option value="live">Live</option>
					<option value="sandbox">Sandbox</option>
				</field>
			</fieldset>
		</fields>
	</config>
</extension>


text:
namespace Burrows.Saga.Pipeline
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    /// <summary>
	/// Determines if a message property is compared to the CorrelationId of the saga and if so
	/// returns an expression that can be used to return that id
	/// </summary>
	/// <typeparam name="TSaga"></typeparam>
	/// <typeparam name="TMessage"></typeparam>
	public class CorrelationExpressionToSagaIdVisitor<TSaga, TMessage> :
		Util.ExpressionVisitor
	{
		Expression<Func<TMessage, Guid>> _result;

		public Expression<Func<TMessage, Guid>> Build(Expression<Func<TSaga, TMessage, bool>> expression)
		{
			_result = null;

			Visit(expression);

			return _result;
		}

		protected override Expression VisitBinary(BinaryExpression b)
		{
			if (b == null)
				return null;

			var left = b.Left as MemberExpression;
			var right = b.Right as MemberExpression;
			if(left != null && right != null && left.Expression != null && right.Expression != null)
			{
				if(left.Expression.NodeType == ExpressionType.Parameter && left.Expression.Type == typeof(TMessage) &&
					right.Expression.NodeType == ExpressionType.Parameter && right.Expression.Type == typeof(TSaga))
				{
					EvaluateMessageToSaga(left, right);
				}

				if (right.Expression.NodeType == ExpressionType.Parameter && right.Expression.Type == typeof(TMessage) &&
					left.Expression.NodeType == ExpressionType.Parameter && left.Expression.Type == typeof(TSaga))
				{
					EvaluateMessageToSaga(right, left);
				}
			}

			return base.VisitBinary(b);
		}

		void EvaluateMessageToSaga(MemberExpression messageExpression, MemberExpression sagaExpression)
		{
			if (sagaExpression.Member.MemberType == MemberTypes.Property && sagaExpression.Member.Name == "CorrelationId")
			{
				_result = Expression.Lambda<Func<TMessage, Guid>>(messageExpression,
					(ParameterExpression) messageExpression.Expression);
			}
		}
	}
}


text:
from hello_1 import app

def test_index_returns_200():
    request, response = app.test_client.get('/')
    assert response.status == 200

def test_index_put_not_allowed():
    req, res = app.test_client.put('/')
    assert res.status == 405


text:
<?php
namespace Fwk\Security\Password;

class Generator implements SaltedPassword
{
    /**
     * The Password Adapter name
     *
     * @var string
     */
    protected $adapterName;

    /**
     * Adapter constructor options
     *
     * @var array
     */
    protected $adapterOptions = array();

    /**
     * The Password Adapter
     *
     * @var PasswordInterface
     */
    protected $adapter;

    /**
     * Constructor
     *
     * @param string|PasswordInterface $adapter Adapter or Adapter name
     * @param array                    $options Adapter constructor options
     * (if any)
     *
     * @return void
     */
    public function __construct($adapter, array $options = array())
    {
        if (is_string($adapter)) {
            $this->adapterName = $adapter;
            $this->adapterOptions = $options;
        } elseif ($adapter instanceof PasswordInterface) {
            $this->adapter = $adapter;
        } else {
            throw new \InvalidArgumentException(
                'The $adapter parameter should be a string or an instance of ' .
                'Zend\Crypt\Password\PasswordInterface'
            );
        }
    }

    /**
     * Crypts a password
     *
     * @param string $password
     *
     * @return string
     */
    public function create($password)
    {
        return $this->getAdapter()->create($password);
    }

    /**
     * (Build if needed) and return the Password Adapter
     * {@see PasswordInterface}
     *
     * @return PasswordInterface
     */
    public function getAdapter()
    {
        if (!isset($this->adapter)) {
            $factory = new AdapterFactoryStrategy($this->adapterName);
            $this->adapter = $factory->factory($this->adapterOptions);
        }

        return $this->adapter;
    }

    /**
     * Verifies a password.
     *
     * @param string $password The password to verify
     * @param string $hash     The already crypted password to compare
     *
     * @return boolean
     */
    public function verify($password, $hash)
    {
        return $this->getAdapter()->verify($password, $hash);
    }

    /**
     * Returns the actual salt of the Adapter or null if not present/supported
     *
     * @return string|null
     */
    public function getSalt()
    {
        $adapter = $this->getAdapter();
        if ($adapter instanceof SaltedPassword) {
            return $adapter->getSalt();
        }

        return null;
    }

    /**
     * Defines a Salt for a SaltedPasswordInterface Adapter
     *
     * @param string $salt
     *
     * @return Generator
     */
    public function setSalt($salt)
    {
        $adapter = $this->getAdapter();
        if ($adapter instanceof SaltedPassword) {
            $adapter->setSalt($salt);
        }

        return $this;
    }

    public function clearSalt()
    {
        $adapter = $this->getAdapter();
        if ($adapter instanceof SaltedPassword) {
            $adapter->clearSalt();
        }

        return $this;
    }
}


text:
layout: post
title: The best comment section
---

I've wanted to put this commenting form on a my site for a while. Unfortunately, I think this could come off as too sarcastic and a bit mean. I pride myself on doing my best to not be mean online; I slip up sometimes, sure, but I try to keep friendly and supportive.

So, I hate comment sections. They really are horrible places. When I set up this new blog, I chose to not include any form of commenting section.

Sometimes, though, people read something and really want to respond. They have some passionate reaction and need to clear the air. Just like Rubber Ducking in programming, sometimes just the act of writing out your response is enough. Nobody really needs to read it, your relief can come from just writing it down. So, wouldn't this be the absolute best comment form?

Would you like to leave a comment?

  <form>

      Comment:

      <textarea rows='10' placeholder="leave comment here"></textarea>

      Now that you've gotten that off your chest, feel free to click the button below.

      <input type='reset' value="Click here to erase what you've written"></input>

  </form>
  Powered by Don't Read the Comments


text:
<!doctype html>

	<meta charset="gb2312">
	<title>΢ÐÅɨÃèµÇ¼</title>
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<link rel="stylesheet" href="./css/common.css">

¹§Ï²Äú£¬³É¹¦µÇ¼{#$QISHI.site_name#}

½øÈë»áÔ±ÖÐÐÄ


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

abstract class Ksmarty {

	protected static $instance;

	/**
	 * Ksmarty singleton instance
	 *
	 * @return  singleton
	 */
	public static function instance()
	{
		// Check if the instance already exists
		if (Ksmarty::$instance === NULL) {

			// Load Smarty
			if (!class_exists('Smarty', FALSE)) {
				require Kohana::find_file('vendor', 'smarty/Smarty.class');
			}

			// Initialize Smarty
			$s = new Smarty();

			// Apply configuration data
			$s->compile_dir		= Kohana::$config->load('smarty')->compile_dir;
			$s->plugins_dir		= Kohana::$config->load('smarty')->plugins_dir;
			$s->cache_dir		= Kohana::$config->load('smarty')->cache_dir;
			$s->config_dir		= Kohana::$config->load('smarty')->config_dir;

			$s->debug_tpl		= Kohana::$config->load('smarty')->debug_tpl;
			$s->debugging_ctrl	= Kohana::$config->load('smarty')->debugging_ctrl;
			$s->debugging		= Kohana::$config->load('smarty')->debugging;
			$s->caching			= Kohana::$config->load('smarty')->caching;
			$s->force_compile	= Kohana::$config->load('smarty')->force_compile;

			// Register the autoload filters
			$s->autoload_filters = array(
											'pre'		=> Kohana::$config->load('smarty')->pre_filters,
											'post'		=> Kohana::$config->load('smarty')->post_filters,
											'output'	=> Kohana::$config->load('smarty')->output_filters
										);

			// Create the instance singleton
			Ksmarty::$instance = $s;
		}

		// Return the singleton
		return 	Ksmarty::$instance;
	}
} // End Ksmarty


text:
<?php

/**
 * Define Consts
 */
define('PUZZLE_SIZE', 8);

define('SOLUTION_LIMIT', 100);                    // Stop after found (*) solutions - for large puzzle size

/**
 * Class NQueenSolver
 */
class NQueenSolver {

  private static $__puzzle_size = PUZZLE_SIZE;
  private static $__instance = null;

  private static $solved = false;
  private static $solutions = null;
  private static $solutions_count = 0;

  private static $partial_complete = false;       // indicator for stoppped before finishing all posibilities
  private static $queens = null;                  // just for convenience as class variable - for share between functions

  /**
   * Singleton Pattern for this class
   */
  private function __construct(){}
  public static function getInstance(){
    if (self::$__instance == null) self::$__instance = new NQueenSolver;
    return self::$__instance;
  }

  /**
   * Check if the puzzle has been solved
   */
  public function isSolved() {
    return self::$solved;
  }

  /**
   * Check if all posibilities have been tested
   */
  public function isSolvedPartially() {
    return self::$partial_complete;
  }

  /**
   * Return solutions results as muti-level array, work out the puzzle if haven't solved before
   */
  public function getSolutions() {
    if (self::$solved != true) self::_solve();
    return self::$solutions;
  }

  /**
   * Solve the puzzle and return count of solutions, not re-solve if done already
   */
  private function _solve() {
    if (self::$solved != true) {                  // try solve only if has not been completed before
      self::$solutions = array();
      self::$queens = array();
      $y = 1; $x = 1;                             // start from (1, 1)
      while ($y > 0) {
        if (self::$solutions_count == SOLUTION_LIMIT) { // Stop after found (*) solutions
          self::$partial_complete = true;
          break;
        }
        if ($x > PUZZLE_SIZE) {                   // if reaches the last position on board - move up a line
            // - Move up -
            $x = self::$queens[$y - 1] + 1;
            $y --;
            continue;
        }
        // Try place a queen
        self::$queens[$y] = $x;
        if (self::_isConflict($y)) {              // Test for confilict
          $x ++;                                  // Try next position
          continue;
        }
        if ($y < PUZZLE_SIZE) {                   // More queens to place, try next line
          // - Move down -
          $y ++;
          $x = 1;
          continue;
        }
        self::_recordSolution();                  // In last line and solution found
        $x ++;                                    // keep going
      }
    }
  }

  /**
   * Solve the puzzle and return count of solutions, not re-solve if done already
   */
  private function _isConflict($y) {
    $x = self::$queens[$y];
    for ($t_y = 1; $t_y < $y ; $t_y ++) {
      $t_x = self::$queens[$t_y];
      if ($t_x == $x or
          abs($t_x - $x) == abs($t_y - $y)) {
        // conflict detected
        return true;
      }
    }
    return false;
  }

  /**
   * code block for recording a solution
   */
  private function _recordSolution() {
    self::$solutions[] = self::$queens;           // save solution
    self::$solutions_count ++;                    // increase counter
  }

}


text:
from os.path import abspath

from flask import current_app
from flask.ext.script import Manager
from flask.ext.assets import ManageAssets
from flask.ext.migrate import Migrate, MigrateCommand

from bluespot import create_app

app = create_app(mode= 'development')

app.run(host='0.0.0.0',debug = True)


text:
package test.gov.nih.nci.cacoresdk.domain.other.primarykey;

import gov.nih.nci.cacoresdk.domain.other.primarykey.CharacterKey;
import gov.nih.nci.system.applicationservice.ApplicationException;

import java.util.Collection;
import java.util.Iterator;

import test.gov.nih.nci.cacoresdk.SDKTestBase;

public class CharacterKeyTest extends SDKTestBase
{
	public static String getTestCaseName()
	{
		return "Character Key Test Case";
	}

	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws ApplicationException
	 */
	public void testEntireObjectNestedSearch() throws ApplicationException
	{
		CharacterKey searchObject = new CharacterKey();
		Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.other.primarykey.CharacterKey",searchObject );

		assertNotNull(results);
		assertEquals(4,results.size());

		for(Iterator i = results.iterator();i.hasNext();)
		{
			CharacterKey result = (CharacterKey)i.next();
			assertNotNull(result);
			assertNotNull(result.getId());
			assertNotNull(result.getName());
		}
	}

	/**
	 * Uses Class for search
	 * Searches by the primary key
	 * Verifies size of the result set
	 *
	 * @throws ApplicationException
	 */
	public void testPrimaryKeyNestedSearch() throws ApplicationException
	{
		CharacterKey searchObject = new CharacterKey();
		searchObject.setId('9');
		Collection results = getApplicationService().search(CharacterKey.class,searchObject );

		assertNotNull(results);
		assertEquals(1,results.size());
	}
}


text:
package org.scalawiki.copyvio

import org.scalawiki.dto.Page
import org.scalawiki.dto.cmd.Action
import org.scalawiki.dto.cmd.query.prop._
import org.scalawiki.dto.cmd.query.{PageIdsParam, Query}
import org.scalawiki.http.HttpClient
import org.scalawiki.query.QueryLibrary
import org.scalawiki.{MwBot, WithBot}
import play.api.libs.functional.syntax._
import play.api.libs.json.{Json, _}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class CopyVio(val http: HttpClient) {

  implicit val sourceReads =
    ((__ \ "url").read[String] ~
      (__ \ "confidence").read[Double] ~
      (__ \ "violation").read[String] ~
      (__ \ "skipped").read[Boolean]) (CopyVioSource.apply _)

  val sourcesReads = (__ \ "sources").read[Seq[CopyVioSource]]

  def baseUrl(project: String = "wikipedia", lang: String = "uk") =
    s"https://tools.wmflabs.org/copyvios/api.json?version=1&action=search&project=$project&lang=$lang"

  def search(title: String, lang: String = "uk", project: String = "wikipedia") =
    http.get(baseUrl(project, lang) + s"&title=$title") map parseResponse

  def searchByRevId(revId: Long, lang: String = "uk", project: String = "wikipedia") =
    http.get(baseUrl(project, lang) + s"&oldid=$revId") map parseResponse

  def searchByPage(page: Page) = {
    println(s"# [[${page.title}]]")
    searchByRevId(page.revisions.head.revId.get)
  }

  def parseResponse(body: String) = Json.parse(body).validate(sourcesReads).get

}

object CopyVio extends WithBot with QueryLibrary {

  val host = MwBot.ukWiki

  def pagesByIds(ids: Seq[Long]): Future[Seq[Page]] = {
    import org.scalawiki.dto.cmd.query.prop.rvprop._

    val action = Action(Query(PageIdsParam(ids), Prop(Info(), Revisions(RvProp(Ids) /*,RvLimit("max")*/))))

    bot.run(action)
  }

  def main(args: Array[String]) {
    val copyVio = new CopyVio(HttpClient.get())

    for (revIds <- articlesWithTemplate("Вікіпедія любить пам'ятки");
         pages <- pagesByIds(revIds);
         page <- pages;
         sources <- copyVio.searchByPage(page);
         suspected <- sources.filter(_.isPossible)) {
      println(s"## url: [${suspected.url}], violation ${suspected.violation}, confidence ${suspected.confidence}")
    }
  }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#include "sim_constants.h"

namespace hr { namespace franp { namespace rsim {

const simConstants g_sim_constants;

simConstants::simConstants() {
}

}}} // namespace


text:
var OAuth2 = require("./oauth2")
, util = require("util")

function Instagram(options) {
  this.code = {
    protocol: "https",
    host: "api.instagram.com",
    pathname: "/oauth/authorize/",
    query: {
      response_type: "code",
      client_id: options.id,
      scope: options.scope || []
    }
  }

  this.token = {
    method: "POST",
    host: "api.instagram.com",
    path: "/oauth/access_token",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    query: {
      client_id: options.id,
      client_secret: options.secret,
      grant_type: "authorization_code"
    }
  }

  this.user = {
    host: "api.instagram.com",
    path: "/v1/users/self",
    query: {}
  }

  this.on("request", this.onRequest.bind(this))

  OAuth2.call(this)
}

util.inherits(Instagram, OAuth2)

Instagram.prototype.getId = function(data) {
  return data.data.id
}

module.exports = Instagram


text:
<?php

namespace Jose\Algorithm\KeyEncryption;

use AESGCM\AESGCM;
use Assert\Assertion;
use Base64Url\Base64Url;
use Jose\Object\JWKInterface;

/**
 * Class AESGCMKW.
 */
abstract class AESGCMKW implements KeyWrappingInterface
{
    /**
     * {@inheritdoc}
     */
    public function wrapKey(JWKInterface $key, $cek, array $complete_headers, array &$additional_headers)
    {
        $this->checkKey($key);
        $kek = Base64Url::decode($key->get('k'));
        $iv = random_bytes(96 / 8);
        $additional_headers['iv'] = Base64Url::encode($iv);

        list($encrypted_cek, $tag) = AESGCM::encrypt($kek, $iv, $cek, null);
        $additional_headers['tag'] = Base64Url::encode($tag);

        return $encrypted_cek;
    }

    /**
     * {@inheritdoc}
     */
    public function unwrapKey(JWKInterface $key, $encrypted_cek, array $header)
    {
        $this->checkKey($key);
        $this->checkAdditionalParameters($header);

        $kek = Base64Url::decode($key->get('k'));
        $tag = Base64Url::decode($header['tag']);
        $iv = Base64Url::decode($header['iv']);

        return AESGCM::decrypt($kek, $iv, $encrypted_cek, null, $tag);
    }

    /**
     * {@inheritdoc}
     */
    public function getKeyManagementMode()
    {
        return self::MODE_WRAP;
    }

    /**
     * @param JWKInterface $key
     */
    protected function checkKey(JWKInterface $key)
    {
        Assertion::eq($key->get('kty'), 'oct', 'Wrong key type.');
        Assertion::true($key->has('k'), 'The key parameter "k" is missing.');
    }

    /**
     * @param array $header
     */
    protected function checkAdditionalParameters(array $header)
    {
        Assertion::keyExists($header, 'iv', 'Parameter "iv" is missing.');
        Assertion::keyExists($header, 'tag', 'Parameter "tag" is missing.');
    }

    /**
     * @return int
     */
    abstract protected function getKeySize();
}


text:
<?php

function initController($controller_name)
{
  $controller = new $controller_name();
  $vars = $controller->init();

  foreach ($vars as $key => $value) {
    $GLOBALS[$key] = $value;
  }
}

function loadController($template)
{
  $template_name   = ucfirst(str_replace('.php', '', basename($template)));
  $template_name   = ucwords(str_replace('-', ' ', $template_name));
  $template_name   = str_replace(' ', '', $template_name);
  $controller_name = 'Controller\\'.$template_name.'Controller';

  if(class_exists($controller_name)) {
    initController($controller_name);
  }

  return $template;
}

add_action('template_include', 'loadController');


text:
import { FSWatcher } from 'chokidar';
import { Dispatcher } from './dispatcher';
export interface FileWatcherOptions {
    readonly dispatcher: Dispatcher;
    readonly cwd: string;
    readonly watchPath: string;
    readonly convertAudioExtensions: string[];
    readonly convertVideoExtensions: string[];
    readonly copyAudioExtensions: string[];
    readonly copyVideoExtensions: string[];
}
export declare class FileWatcher {
    private options;
    private dispatcher;
    private fswatcher;
    constructor(options: FileWatcherOptions);
    init(): Promise<FSWatcher>;
    private onAdd;
    private handleFileEvent;
    private handleFile;
    private getJobType;
    private isValidFileType;
}
export declare function createFileWatcher(options: FileWatcherOptions): FileWatcher;
//# sourceMappingURL=fileWatcher.d.ts.map


text:
cloudapps
=========

All open cloud apps offered by Kiezo


text:
package eu.leads.processor.common.utils;

/**
 * Created by tr on 19/11/2014.
 */
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;

public class StringPathFilter implements PathFilter
{
    private String str;

    public StringPathFilter(String filter)
    {
        str = filter;
    }

    @Override
    public boolean accept(Path path)
    {
        // TODO Auto-generated method stub
        if (path.getName().startsWith(str))
        {
            System.out.println("accepting " + path.getName());
            return true;
        }
        // System.out.println("Filtering " + path.getName());
        return false;
    }

}


text:
package com.google.common.truth;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.Map;

/**
 * Tests for {@link Map} subjects.
 *
 * @author Christian Gruber
 * @author Kurt Alfred Kluever
 */
@RunWith(JUnit4.class)
public class MapSubjectTest {
  @Test
  public void containsExactlyWithNullKey() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, "value");

    assertThat(actual).containsExactly(null, "value");
    assertThat(actual).containsExactly(null, "value").inOrder();
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
  }

  @Test
  public void containsExactlyWithNullValue() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put("key", null);

    assertThat(actual).containsExactly("key", null);
    assertThat(actual).containsExactly("key", null).inOrder();
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
  }

  @Test
  public void containsExactlyEmpty() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of();

    assertThat(actual).containsExactly();
    assertThat(actual).containsExactly().inOrder();
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
  }

  @Test
  public void containsExactlyOneEntry() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);

    assertThat(actual).containsExactly("jan", 1);
    assertThat(actual).containsExactly("jan", 1).inOrder();
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
  }

  @Test
  public void containsExactlyMultipleEntries() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);

    assertThat(actual).containsExactly("jan", 1, "feb", 2, "march", 3);
    assertThat(actual).containsExactly("jan", 1, "feb", 2, "march", 3).inOrder();
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
  }

  @Test
  public void containsExactlyDuplicateKeys() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);

    try {
      assertThat(actual).containsExactly("jan", 1, "jan", 2, "jan", 3);
      fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
      assertThat(expected)
          .hasMessage("Duplicate keys ([jan x 3]) cannot be passed to containsExactly().");
    }
  }

  @Test
  public void containsExactlyMultipleDuplicateKeys() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);

    try {
      assertThat(actual).containsExactly("jan", 1, "jan", 1, "feb", 2, "feb", 2);
      fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
      assertThat(expected)
          .hasMessage("Duplicate keys ([jan x 2, feb x 2]) cannot be passed to containsExactly().");
    }
  }

  @Test
  public void containsExactlyMissingEntry() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();

    try {
      assertThat(actual).containsExactly("jan", 1, "feb", 2);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <[jan=1, feb=2, march=3]> contains exactly <[jan=1, feb=2]>. "
                  + "It has unexpected items <[march=3]>");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void containsExactlyMissingEntryInOrder() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();

    try {
      assertThat(actual).containsExactly("feb", 2, "jan", 1).inOrder();
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <[jan=1, feb=2, march=3]> contains exactly <[feb=2, jan=1]>. "
                  + "It has unexpected items <[march=3]>");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void containsExactlyNotInOrder() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();

    assertThat(actual).containsExactly("jan", 1, "march", 3, "feb", 2);
    try {
      assertThat(actual).containsExactly("jan", 1, "march", 3, "feb", 2).inOrder();
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <[jan=1, feb=2, march=3]> contains only these elements in order "
                  + "<[jan=1, march=3, feb=2]>");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void containsExactlyBadNumberOfArgs() {
    ImmutableMap<String, Integer> actual =
        ImmutableMap.of("jan", 1, "feb", 2, "march", 3, "april", 4, "may", 5);
    assertThat(actual).containsExactlyEntriesIn(actual);
    assertThat(actual).containsExactlyEntriesIn(actual).inOrder();

    try {
      assertThat(actual)
          .containsExactly("jan", 1, "feb", 2, "march", 3, "april", 4, "may", 5, "june", 6, "july");
      fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
      assertThat(expected)
          .hasMessage(
              "There must be an equal number of key/value pairs "
                  + "(i.e., the number of key/value parameters (13) must be even).");
    }
  }

  @Test
  public void isEqualToPass() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);

    assertThat(actual).isEqualTo(expectedMap);
  }

  @Test
  public void isEqualToFailureExtraMissingAndDiffering() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "april", 4, "march", 5);

    try {
      assertThat(actual).isEqualTo(expectedMap);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, april=4, march=5}>. "
                  + "The subject is missing the following entries: {april=4} and "
                  + "has the following extra entries: {feb=2} and "
                  + "has the following different entries: {march=(5, 3)}");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void isEqualToFailureDiffering() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 4);

    try {
      assertThat(actual).isEqualTo(expectedMap);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2, march=4}>. "
                  + "The subject has the following different entries: {march=(4, 3)}");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void namedMapIsEqualToFailureDiffering() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 4);

    try {
      assertThat(actual).named("foo").isEqualTo(expectedMap);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that foo (<{jan=1, feb=2, march=3}>) is equal to <{jan=1, feb=2, march=4}>."
                  + " The subject has the following different entries: {march=(4, 3)}");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void isEqualToFailureExtra() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2);

    try {
      assertThat(actual).isEqualTo(expectedMap);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2}>. "
                  + "The subject has the following extra entries: {march=3}");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void isEqualToFailureMissing() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);

    try {
      assertThat(actual).isEqualTo(expectedMap);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <{jan=1, feb=2}> is equal to <{jan=1, feb=2, march=3}>. "
                  + "The subject is missing the following entries: {march=3}");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void isEqualToFailureExtraAndMissing() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
    ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "mar", 3);

    try {
      assertThat(actual).isEqualTo(expectedMap);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2, mar=3}>. "
                  + "The subject is missing the following entries: {mar=3} "
                  + "and has the following extra entries: {march=3}");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void isNotEqualTo() {
    ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);

    try {
      assertThat(actual).isNotEqualTo(actual);
    } catch (AssertionError expected) {
      assertThat(expected)
          .hasMessage(
              "Not true that <{jan=1, feb=2, march=3}> is not equal to <{jan=1, feb=2, march=3}>");
      return;
    }
    fail("Should have thrown.");
  }

  @Test
  public void isEmpty() {
    ImmutableMap<String, String> actual = ImmutableMap.of();
    assertThat(actual).isEmpty();
  }

  @Test
  public void isEmptyWithFailure() {
    ImmutableMap<Integer, Integer> actual = ImmutableMap.of(1, 5);
    try {
      assertThat(actual).isEmpty();
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{1=5}> is empty");
    }
  }

  @Test
  public void isNotEmpty() {
    ImmutableMap<Integer, Integer> actual = ImmutableMap.of(1, 5);
    assertThat(actual).isNotEmpty();
  }

  @Test
  public void isNotEmptyWithFailure() {
    ImmutableMap<Integer, Integer> actual = ImmutableMap.of();
    try {
      assertThat(actual).isNotEmpty();
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{}> is not empty");
    }
  }

  @Test
  public void hasSize() {
    assertThat(ImmutableMap.of(1, 2, 3, 4)).hasSize(2);
  }

  @Test
  public void hasSizeZero() {
    assertThat(ImmutableMap.of()).hasSize(0);
  }

  @Test
  public void hasSizeNegative() {
    try {
      assertThat(ImmutableMap.of(1, 2)).hasSize(-1);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  @Test
  public void containsKey() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    assertThat(actual).containsKey("kurt");
  }

  @Test
  public void containsKeyFailure() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    try {
      assertThat(actual).containsKey("greg");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{kurt=kluever}> contains key <greg>");
    }
  }

  @Test
  public void containsKeyNullFailure() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    try {
      assertThat(actual).containsKey(null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{kurt=kluever}> contains key <null>");
    }
  }

  @Test
  public void containsNullKey() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, "null");
    assertThat(actual).containsKey(null);
  }

  @Test
  public void doesNotContainKey() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    assertThat(actual).doesNotContainKey("greg");
    assertThat(actual).doesNotContainKey(null);
  }

  @Test
  public void doesNotContainKeyFailure() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    try {
      assertThat(actual).doesNotContainKey("kurt");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{kurt=kluever}> does not contain key <kurt>");
    }
  }

  @Test
  public void doesNotContainNullKey() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, "null");
    try {
      assertThat(actual).doesNotContainKey(null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{null=null}> does not contain key <null>");
    }
  }

  @Test
  public void containsEntry() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    assertThat(actual).containsEntry("kurt", "kluever");
  }

  @Test
  public void containsEntryFailure() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    try {
      assertThat(actual).containsEntry("greg", "kick");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{kurt=kluever}> contains entry <greg=kick>");
    }
  }

  @Test
  public void containsNullKeyAndValue() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    try {
      assertThat(actual).containsEntry(null, null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{kurt=kluever}> contains entry <null=null>");
    }
  }

  @Test
  public void containsNullEntry() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, null);
    assertThat(actual).containsEntry(null, null);
  }

  @Test
  public void containsNullEntryValue() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, null);
    try {
      assertThat(actual).containsEntry("kurt", null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e)
          .hasMessage(
              "Not true that <{null=null}> contains entry <kurt=null>. "
                  + "However, the following keys are mapped to <null>: [null]");
    }
  }

  @Test
  public void containsNullEntryKey() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, null);
    try {
      assertThat(actual).containsEntry(null, "kluever");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e)
          .hasMessage(
              "Not true that <{null=null}> contains entry <null=kluever>. "
                  + "However, it has a mapping from <null> to <null>");
    }
  }

  @Test
  public void doesNotContainEntry() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    assertThat(actual).doesNotContainEntry("greg", "kick");
    assertThat(actual).doesNotContainEntry(null, null);
    assertThat(actual).doesNotContainEntry("kurt", null);
    assertThat(actual).doesNotContainEntry(null, "kluever");
  }

  @Test
  public void doesNotContainEntryFailure() {
    ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
    try {
      assertThat(actual).doesNotContainEntry("kurt", "kluever");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e)
          .hasMessage("Not true that <{kurt=kluever}> does not contain entry <kurt=kluever>");
    }
  }

  @Test
  public void doesNotContainNullEntry() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, null);
    assertThat(actual).doesNotContainEntry("kurt", null);
    assertThat(actual).doesNotContainEntry(null, "kluever");
  }

  @Test
  public void doesNotContainNullEntryFailure() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put(null, null);
    try {
      assertThat(actual).doesNotContainEntry(null, null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{null=null}> does not contain entry <null=null>");
    }
  }

  @Test
  public void failMapContainsKey() {
    ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
    try {
      assertThat(actual).containsKey("b");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{a=A}> contains key <b>");
    }
  }

  @Test
  public void failMapContainsKeyWithNull() {
    ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
    try {
      assertThat(actual).containsKey(null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{a=A}> contains key <null>");
    }
  }

  @Test
  public void failMapLacksKey() {
    ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
    try {
      assertThat(actual).doesNotContainKey("a");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Not true that <{a=A}> does not contain key <a>");
    }
  }

  @Test
  public void containsKeyWithValue() {
    ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
    assertThat(actual).containsEntry("a", "A");
  }

  @Test
  public void containsKeyWithNullValueNullExpected() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put("a", null);
    assertThat(actual).containsEntry("a", null);
  }

  @Test
  public void failMapContainsKeyWithValue() {
    ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
    try {
      assertThat(actual).containsEntry("a", "a");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e)
          .hasMessage(
              "Not true that <{a=A}> contains entry <a=a>. "
                  + "However, it has a mapping from <a> to <A>");
    }
  }

  @Test
  public void failMapContainsKeyWithNullValuePresentExpected() {
    Map<String, String> actual = Maps.newHashMap();
    actual.put("a", null);
    try {
      assertThat(actual).containsEntry("a", "A");
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e)
          .hasMessage(
              "Not true that <{a=null}> contains entry <a=A>. "
                  + "However, it has a mapping from <a> to <null>");
    }
  }

  @Test
  public void failMapContainsKeyWithPresentValueNullExpected() {
    ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
    try {
      assertThat(actual).containsEntry("a", null);
      fail("Should have thrown.");
    } catch (AssertionError e) {
      assertThat(e)
          .hasMessage(
              "Not true that <{a=A}> contains entry <a=null>. "
                  + "However, it has a mapping from <a> to <A>");
    }
  }
}


text:
function handleHeaders(event) {
  const headers = Array.from(event.request.headers);
  event.respondWith(new Response(JSON.stringify(headers)));
}

function handleString(event) {
  event.respondWith(new Response('Test string'));
}

function handleBlob(event) {
  event.respondWith(new Response(new Blob(['Test blob'])));
}

function handleReferrer(event) {
  event.respondWith(new Response(new Blob(
    ['Referrer: ' + event.request.referrer])));
}

function handleReferrerPolicy(event) {
  event.respondWith(new Response(new Blob(
    ['ReferrerPolicy: ' + event.request.referrerPolicy])));
}

function handleReferrerFull(event) {
  event.respondWith(new Response(new Blob(
    ['Referrer: ' + event.request.referrer + '\n' +
     'ReferrerPolicy: ' + event.request.referrerPolicy])));
}

function handleClientId(event) {
  var body;
  if (event.clientId !== "") {
    body = 'Client ID Found: ' + event.clientId;
  } else {
    body = 'Client ID Not Found';
  }
  event.respondWith(new Response(body));
}

function handleResultingClientId(event) {
  var body;
  if (event.resultingClientId !== "") {
    body = 'Resulting Client ID Found: ' + event.resultingClientId;
  } else {
    body = 'Resulting Client ID Not Found';
  }
  event.respondWith(new Response(body));
}

function handleNullBody(event) {
  event.respondWith(new Response());
}

function handleFetch(event) {
  event.respondWith(fetch('other.html'));
}

function handleFormPost(event) {
  event.respondWith(new Promise(function(resolve) {
      event.request.text()
        .then(function(result) {
            resolve(new Response(event.request.method + ':' +
                                 event.request.headers.get('Content-Type') + ':' +
                                 result));
          });
    }));
}

function handleMultipleRespondWith(event) {
  var logForMultipleRespondWith = '';
  for (var i = 0; i < 3; ++i) {
    logForMultipleRespondWith += '(' + i + ')';
    try {
      event.respondWith(new Promise(function(resolve) {
        setTimeout(function() {
          resolve(new Response(logForMultipleRespondWith));
        }, 0);
      }));
    } catch (e) {
      logForMultipleRespondWith += '[' + e.name + ']';
    }
  }
}

var lastResponseForUsedCheck = undefined;

function handleUsedCheck(event) {
  if (!lastResponseForUsedCheck) {
    event.respondWith(fetch('other.html').then(function(response) {
        lastResponseForUsedCheck = response;
        return response;
      }));
  } else {
    event.respondWith(new Response(
        'bodyUsed: ' + lastResponseForUsedCheck.bodyUsed));
  }
}
function handleFragmentCheck(event) {
  var body;
  if (event.request.url.indexOf('#') === -1) {
    body = 'Fragment Not Found';
  } else {
    body = 'Fragment Found :' +
           event.request.url.substring(event.request.url.indexOf('#'));
  }
  event.respondWith(new Response(body));
}
function handleCache(event) {
  event.respondWith(new Response(event.request.cache));
}
function handleEventSource(event) {
  if (event.request.mode === 'navigate') {
    return;
  }
  var data = {
    mode: event.request.mode,
    cache: event.request.cache,
    credentials: event.request.credentials
  };
  var body = 'data:' + JSON.stringify(data) + '\n\n';
  event.respondWith(new Response(body, {
      headers: { 'Content-Type': 'text/event-stream' }
    }
  ));
}

function handleIntegrity(event) {
  event.respondWith(new Response(event.request.integrity));
}

function handleRequestBody(event) {
  event.respondWith(event.request.text()
    .then(text => {
        return new Response(text);
      }));
}

function handleKeepalive(event) {
  event.respondWith(new Response(event.request.keepalive));
}

function handleIsReloadNavigation(event) {
  const request = event.request;
  const body =
    `method = ${request.method}, ` +
    `isReloadNavigation = ${request.isReloadNavigation}`;
  event.respondWith(new Response(body));
}

function handleIsHistoryNavigation(event) {
  const request = event.request;
  const body =
    `method = ${request.method}, ` +
    `isHistoryNavigation = ${request.isHistoryNavigation}`;
  event.respondWith(new Response(body));
}

function handleUseAndIgnore(event) {
  const request = event.request;
  request.text();
  return;
}

function handleCloneAndIgnore(event) {
  const request = event.request;
  request.clone().text();
  return;
}

var handle_status_count = 0;
function handleStatus(event) {
  handle_status_count++;
  event.respondWith(async function() {
    const res = await fetch(event.request);
    const text = await res.text();
    return new Response(`${text}. Request was sent ${handle_status_count} times.`,
      {"status": new URL(event.request.url).searchParams.get("status")});
  }());
}

self.addEventListener('fetch', function(event) {
    var url = event.request.url;
    var handlers = [
      { pattern: '?headers', fn: handleHeaders },
      { pattern: '?string', fn: handleString },
      { pattern: '?blob', fn: handleBlob },
      { pattern: '?referrerFull', fn: handleReferrerFull },
      { pattern: '?referrerPolicy', fn: handleReferrerPolicy },
      { pattern: '?referrer', fn: handleReferrer },
      { pattern: '?clientId', fn: handleClientId },
      { pattern: '?resultingClientId', fn: handleResultingClientId },
      { pattern: '?ignore', fn: function() {} },
      { pattern: '?null', fn: handleNullBody },
      { pattern: '?fetch', fn: handleFetch },
      { pattern: '?form-post', fn: handleFormPost },
      { pattern: '?multiple-respond-with', fn: handleMultipleRespondWith },
      { pattern: '?used-check', fn: handleUsedCheck },
      { pattern: '?fragment-check', fn: handleFragmentCheck },
      { pattern: '?cache', fn: handleCache },
      { pattern: '?eventsource', fn: handleEventSource },
      { pattern: '?integrity', fn: handleIntegrity },
      { pattern: '?request-body', fn: handleRequestBody },
      { pattern: '?keepalive', fn: handleKeepalive },
      { pattern: '?isReloadNavigation', fn: handleIsReloadNavigation },
      { pattern: '?isHistoryNavigation', fn: handleIsHistoryNavigation },
      { pattern: '?use-and-ignore', fn: handleUseAndIgnore },
      { pattern: '?clone-and-ignore', fn: handleCloneAndIgnore },
      { pattern: '?status', fn: handleStatus },
    ];

    var handler = null;
    for (var i = 0; i < handlers.length; ++i) {
      if (url.indexOf(handlers[i].pattern) != -1) {
        handler = handlers[i];
        break;
      }
    }

    if (handler) {
      handler.fn(event);
    } else {
      event.respondWith(new Response(new Blob(
        ['Service Worker got an unexpected request: ' + url])));
    }
  });


text:
git init
if [ $1 == "ALL" ] ; then
	git add --all .
else
	git add $1
fi
git commit -m "$2"
cat ~/.netrc | grep heroku || heroku login && heroku keys:add ~/.ssh/id_rsa.pub
heroku apps:destroy engineering-capoeiraretreats-com --confirm engineering-capoeiraretreats-com
heroku apps:create engineering-capoeiraretreats-com
heroku domains:add engineering.capoeiraretreats.com --app engineering-capoeiraretreats-com
heroku git:remote -a engineering-capoeiraretreats-com
git push heroku master


text:
<?php
/**
 * Created by PhpStorm.
 * User: myles
 * Date: 8/1/2017
 * Time: 10:23 PM
 */
require __DIR__ . '/../src/SMS_Manager/Manager.php';

$action = "";

if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    send_response(['error' => 'no action'], false);
}

$MG = new \SMS_Manager\Manager();

switch ($action) {
    case 'report':
        if (isset($_POST['data'])) {
            $data = $_POST['data'];
            $data_decoded = json_decode($data, true);
            if (json_last_error() == JSON_ERROR_NONE) {

                $report_result = $MG->saveReport($data_decoded);
                if ($report_result === true) {
                    send_response([], true);
                } else {
                    if (isset($report_result['error'])) {
                        send_response(['error' => $report_result['error']], false);
                    } else {
                        send_response(['error' => 'unknown error'], false);
                    }
                }
            } else {
                send_response(['error' => 'data decode error'], false);
            }
        } else {
            send_response(['error' => 'no data'], false);
        }
        break;

    case 'connect':
        send_response([], true);
        break;

    case 'get_simple_id':
        if (isset($_POST['uuid'])) {
            $uuid = $_POST['uuid'];

            $simple_id = $MG->getSimpleID($uuid);
            if ($simple_id) {
                send_response(['simple_id' => $simple_id], true);
            } else {
                send_response(['error' => 'get simple_id error'], false);
            }

        } else {
            send_response(['error' => 'no device uuid'], false);
        }
        break;

    case 'get_uuid':
        if (isset($_POST['simple_id'])) {
            $simple_id = $_POST['simple_id'];

            $MG = new \SMS_Manager\Manager();
            $uuid = $MG->getUUID($simple_id);
            if ($uuid) {
                send_response(['uuid' => $uuid], true);
            } else {
                send_response(['error' => 'get uuid error'], false);
            }

        } else {
            send_response(['error' => 'no device simple_id'], false);
        }
        break;

    default:
        send_response(['error' => 'unknown action: ' . $action], false);
}

function send_response($res, $success)
{
    header('Content-Type: application/json; charset=UTF-8');
    $res = array_merge($res, ['success' => $success]);
    echo json_encode($res);
    exit();
}


text:
package com.github.mkopylec.recaptcha.validation;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.slf4j.Logger;

import static org.slf4j.LoggerFactory.getLogger;

public enum ErrorCode {

    //reCAPTCHA verification errors
    MISSING_SECRET_KEY("missing-input-secret"),
    INVALID_SECRET_KEY("invalid-input-secret"),
    MISSING_USER_CAPTCHA_RESPONSE("missing-input-response"),
    INVALID_USER_CAPTCHA_RESPONSE("invalid-input-response"),
    BAD_REQUEST("bad-request"),
    TIMEOUT_OR_DUPLICATE("timeout-or-duplicate"),

    //Custom errors
    MISSING_USERNAME_REQUEST_PARAMETER("missing-username-request-parameter"),
    MISSING_CAPTCHA_RESPONSE_PARAMETER("missing-captcha-response-parameter"),
    VALIDATION_HTTP_ERROR("validation-http-error"),
    UNSUPPORTED_ERROR_CODE("unsupported_error_code");

    private static final Logger log = getLogger(ErrorCode.class);

    private final String text;

    ErrorCode(String text) {
        this.text = text;
    }

    @JsonCreator
    private static ErrorCode fromValue(String value) {
        if (value == null) {
            return null;
        }
        switch (value) {
            case "missing-input-secret":
                return MISSING_SECRET_KEY;
            case "invalid-input-secret":
                return INVALID_SECRET_KEY;
            case "missing-input-response":
                return MISSING_USER_CAPTCHA_RESPONSE;
            case "invalid-input-response":
                return INVALID_USER_CAPTCHA_RESPONSE;
            case "bad-request":
                return BAD_REQUEST;
            case "timeout-or-duplicate":
                return TIMEOUT_OR_DUPLICATE;
            case "missing-username-request-parameter":
                return MISSING_USERNAME_REQUEST_PARAMETER;
            case "missing-captcha-response-parameter":
                return MISSING_CAPTCHA_RESPONSE_PARAMETER;
            case "validation-http-error":
                return VALIDATION_HTTP_ERROR;
            default:
                log.warn("Unsupported error code: {}", value);
                return UNSUPPORTED_ERROR_CODE;
        }
    }

    @JsonValue
    public String getText() {
        return text;
    }
}


text:
const CGFloat IPAspectRatio = 1.0259f;
const CGFloat IPFullPictureAspectRatio = 10.8 / 8.9;

const CGFloat IPyOffset = 98.0f;
const CGFloat IPyOffsetTallScreen = 172.0f;

const NSTimeInterval IPPreExposeDelay = 2.0;
const NSTimeInterval IPExposeDelay = 3.0;

NSString * const IPTourWasShownDefaultsKey = @"IPTourWasShownDefaultsKey";
NSString * const IPFilmPickerWasShownDefaultsKey = @"IPFilmPickerWasShownDefaultsKey";
NSString * const IPSelectedInstaLabFilmDefaultsKey = @"IPSelectedInstaLabFilm";
NSString * const IPInstaLabDebugCustomExposureTimeDefaultsKey = @"IPInstaLabDebugCustomExposureTime";
NSString * const IPInstaLabDebugExposureXAdjustDefaultsKey = @"IPInstaLabDebugExposureXAdjust";
NSString * const IPInstaLabScannerSaveInfoWasShownDefaultsKey = @"IPInstaLabScannerSaveInfoWasShownDefaultsKey";
NSString * const IPInstaLabExposureInstructionVideoWasShownDefaultsKey = @"IPInstaLabExposureInstructionVideoWasShownDefaultsKey";
NSString * const IPInstaLabTowerExtensionPopupWasShownDefaultsKey = @"IPInstaLabTowerExtensionPopupWasShownDefaultsKey";
NSString * const IPTermsOfServicePopupWasShownDefaultsKey = @"IPTermsOfServicePopupWasShownDefaultsKey";

NSString * const IPSelectedInstaLabFilmLocalizedNameKey = @"localizedName"; // value should be NSString
NSString * const IPSelectedInstaLabFilmIdentifierKey = @"identifier"; // value should be NSString
NSString * const IPSelectedInstaLabFilmExposureKey = @"exposureTimeInSeconds"; // value should be NSNumber

NSString * const IPAlbumName_InstantLab = @"Instant Lab Sources";
NSString * const IPAlbumName_Scans = @"Impossible Scans";

BOOL IPAppIsRunningOnTallScreen() {
    return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone &&
    [UIScreen mainScreen].bounds.size.height >= 568.0f;
}


text:
name: cljs.spec/*explain-out*
see also:
---

## Summary

## Details

## Examples


text:
title: Editor Components
---

## EditorTextField

Compared to
[Swing JTextArea](http://docs.oracle.com/javase/8/docs/api/javax/swing/JTextArea.html), the
*IntelliJ Platform's* editor component has a ton of advantages: syntax highlighting support, code completion, code folding and much more.
*IntelliJ Platform* editors are normally displayed in editor tabs, but they can be embedded in dialogs or toolwindows, too.
This is enabled by the
[EditorTextField](upsource:///platform/platform-impl/src/com/intellij/ui/EditorTextField.java)
component.

When creating an
[EditorTextField](upsource:///platform/platform-impl/src/com/intellij/ui/EditorTextField.java),
you can specify the following attributes:

*  The file type according to which the text in the text field is parsed;

*  Whether the text field is read-only or editable;

*  Whether the text field is single-line or multiline.

A common use case for
[EditorTextField](upsource:///platform/platform-impl/src/com/intellij/ui/EditorTextField.java)
is entering the name of a Java class or package.
This can be accomplished with the following steps:

*  Use
   [JavaCodeFragmentFactory.getInstance().createReferenceCodeFragment()](upsource:///java/java-psi-api/src/com/intellij/psi/JavaCodeFragmentFactory.java)
   to create a code fragment representing the class or package name;

*  Call
   [PsiDocumentManager.getInstance().getDocument()](upsource:///platform/core-api/src/com/intellij/psi/PsiDocumentManager.java)
   to get the document corresponding to the code fragment;

*  Pass the returned document to the
   [EditorTextField](upsource:///platform/platform-impl/src/com/intellij/ui/EditorTextField.java)
   constructor or its `setDocument()` method.