text:
package com.topkc.chinesechess.chess;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.topkc.chinesechess.R;

public class ArchiveManagerActivity extends Activity {

	//¹ÜÀí´æµµÎļþµÄÀà
	ArchiveContorller archiveContorller = new ArchiveContorller(ArchiveManagerActivity.this);

	//ÔÚÊÖ»ú½çÃæÏÔʾÁбí
	ListView list = null;

	//´æ·ÅÔÚListViewÖÐÏñÒªÏÔʾµÄÄÚÈÝ
	ArrayList<HashMap<String, Object>> listItem = null;

	//ListViewµÄÊÊÅäÆ÷
	SimpleAdapter listItemAdapter = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.archives_display);

		// °ó¶¨LayoutÀïÃæµÄListView
		list = (ListView) findViewById(R.id.archives_display_ListView);

		// Éú³É¶¯Ì¬Êý×飬¼ÓÈëÊý¾Ý
		listItem = new ArrayList<HashMap<String, Object>>();

		//¶ÁÈ¡ÓÎÏ·´æµµ
		String[] fileNames = archiveContorller.getArchiveDir();
		for(int i = 0; i<fileNames.length;i++){
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("archives_display_ItemImage", R.drawable.icon);// ͼÏñ×ÊÔ´µÄID
			//map.put("archives_display_ItemText01", "´æµµ " + (i+1));
			map.put("archives_display_ItemText01", "ÓÎÏ·´æµµ ");
			map.put("archives_display_ItemText02", fileNames[i].subSequence(0, fileNames[i].length()-4));
			listItem.add(map);
		}

		// Éú³ÉÊÊÅäÆ÷µÄItemºÍ¶¯Ì¬Êý×é¶ÔÓ¦µÄÔªËØ
		listItemAdapter = new SimpleAdapter(this, listItem,// Êý¾ÝÔ´
				R.layout.archives_display_item,// ListItemµÄXMLʵÏÖ
				// ¶¯Ì¬Êý×éÓëImageItem¶ÔÓ¦µÄ×ÓÏî
				new String[] { "archives_display_ItemImage",
						"archives_display_ItemText01",
						"archives_display_ItemText02" },
				// ImageItemµÄXMLÎļþÀïÃæµÄÒ»¸öImageView,Á½¸öTextView ID
				new int[] { R.id.archives_display_ItemImage,
						R.id.archives_display_ItemText01,
						R.id.archives_display_ItemText02 });

		// Ìí¼Ó²¢ÇÒÏÔʾ
		list.setAdapter(listItemAdapter);

		// Ìí¼Óµã»÷
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//»ñµÃ´æµµÃû×Ö
				String fileName = (String)listItem.get(arg2).get("archives_display_ItemText02");
				fileName +=".txt";

				//¼ÓÔØÓÎÏ·²¼¾ÖÐÅÏ¢
				boolean flag = archiveContorller.readArchiveFile(fileName);

				//Çå³ýµô±ê¼ÇÐÅÏ¢
				ChineseChess.resetChessmanPosition();

				//Ìøתµ½ÓÎÏ·½çÃæ
				Intent intent = new Intent();
				intent.setClass(ArchiveManagerActivity.this, GameViewActivity.class);
				ArchiveManagerActivity.this.startActivity(intent);

				//setTitle("µã»÷µÚ" + arg2 + "¸öÏîÄ¿");
			}
		});

		// Ìí¼Ó³¤°´µã»÷
		list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("´æµµÑ¡Ïî");
				menu.add(0, 0, 0, "ɾ³ý");
				menu.add(0, 1, 0, "È¡Ïû");
			}
		});
	}

	//³¤°´²Ëµ¥ÏìÓ¦º¯Êý
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		//setTitle("µã»÷ÁË"+clickItem+"³¤°´²Ëµ¥ÀïÃæµÄµÚ" + item.getItemId() + "¸öÏîÄ¿");

		//´¦Àí³¤°´²Ëµ¥
		switch (item.getItemId()) {

		case 0://ɾ³ýµ±Ç°´æµµ
			//¹Ø¼ü´úÂëÔÚÕâÀï ,»ñÈ¡ItemµÄID
	        AdapterView.AdapterContextMenuInfo menuInfo;
	        menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	        //Êä³öposition
			int selectedPosition = menuInfo.position;//»ñÈ¡µã»÷Á˵ڼ¸ÐÐ

			//ɾ³ýÎļþ
			String fileName = (String)listItem.get(selectedPosition).get("archives_display_ItemText02");
			fileName +=".txt";
			boolean flag = archiveContorller.deleteArchiveFile(fileName);
			if(flag == true){
				//ÔÚListViewÖÐɾ³ýÑ¡ÖеÄÏîÄ¿£¬ÖØиüÐÂ
				listItem.remove(selectedPosition);
				listItemAdapter.notifyDataSetChanged();
				list.invalidate();
			}
			break;
		case 1://È¡Ïû

			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!-- settings for simple button -->
<Scroll name="'simpleButtonSettings'" defaults="'Screen,Level2'">
    <VBox widthPt="100" childPadding="2" paddingTop="20">
        <Text defaults="'Dark'" text="'Basic settings for button'" widthPt="100" align="'center,middle'"/>
        <Text defaults="'DarkTip'" text="'There are more settings described in docs'" widthPt="100" align="'center,middle'" />
        <Widget defaults="'HRLight'" />

        <!--Icon on/off -->
        <HBox widthPt="100" align="'middle'">
            <VBox left="10" align="'left,middle'" widthPt="60">
                <Text defaults="'Dark'" text="'Enable icon'" />
                <Text defaults="'DarkTip'" text="'It\'s also possible to set separate icon for each state'" />
            </VBox>

            <Switch right="10" selected="false" on-change="
                var btn = #Button(simpleButton);

                if( $this.selected ){
                    btn.ico.bitmapData = ru.stablex.ui.themes.android4.Main.getBitmapData('img/ico/light/star.png');
                }else{
                    btn.ico = null;
                }

                btn.refresh();
            "/>
        </HBox>
        <Widget defaults="'HRLight'" />

        <!-- Vertical -->
        <HBox widthPt="100" align="'middle'">
            <VBox left="10" align="'left,middle'" widthPt="60">
                <Text defaults="'Dark'" text="'Vertical'" />
                <Text defaults="'DarkTip'" text="'Whether label and icon should be placed top to bottom or left to right'" />
            </VBox>

            <Switch right="10" selected="false" on-change="
                var btn = #Button(simpleButton);

                if( $this.selected ){
                    btn.vertical = true;
                }else{
                    btn.vertical = false;
                }

                btn.alignElements();
            "/>
        </HBox>
        <Widget defaults="'HRLight'" />

        <!-- Ico position relative to label -->
        <HBox widthPt="100" align="'middle'">
            <VBox left="10" align="'left,middle'" widthPt="60">
                <Text defaults="'Dark'" text="'Icon before label'" />
            </VBox>

            <Switch right="10" on-change="
                var btn = #Button(simpleButton);

                if( $this.selected ){
                    btn.icoBeforeLabel = true;
                }else{
                    btn.icoBeforeLabel = false;
                }

                btn.alignElements();
            "/>
        </HBox>
        <Widget defaults="'HRLight'" />

        <!-- Apart on/off -->
        <HBox widthPt="100" align="'middle'">
            <VBox left="10" align="'left,middle'" widthPt="60">
                <Text defaults="'Dark'" text="'Move apart'" />
                <Text defaults="'DarkTip'" text="'Stick ico and text to opposite borders'" />
            </VBox>

            <Switch right="10" selected="false" on-change="
                var btn = #Button(simpleButton);

                if( $this.selected ){
                    btn.apart = true;
                }else{
                    btn.apart = false;
                }

                btn.alignElements();
            "/>
        </HBox>
        <Widget defaults="'HRLight'" />

        <!-- Disabled -->
        <HBox widthPt="100" align="'middle'">
            <VBox left="10" align="'left,middle'" widthPt="60">
                <Text defaults="'Default,Dark'" text="'Disable'" />
                <Text defaults="'Default,DarkTip'" text="'Make button ignore mouse events'" />
            </VBox>

            <Switch right="10" selected="false" on-change="
                #Button(simpleButton).disabled = $this.selected;
            "/>
        </HBox>
        <Widget defaults="'HRLight'" />
    </VBox>
</Scroll>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>BodyParser Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          Kitura Docs

         (98% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

      Kitura Reference

      BodyParser Class Reference

            Classes

                BodyParser

                ContentType

                Kitura

                RouteRegex

                Router

                RouterMiddlewareGenerator

                RouterRequest

                RouterResponse

                StaticFileServer

                – CacheOptions

                – Options

            Enums

                JSONPError

                LinkParameter

                ParsedBody

                RouterMethod

            Protocols

                ResponseHeadersSetter

                RouterMiddleware

            Structs

                HTTPVersion

                Headers

                Part

                – HeaderType

                SSLConfig

            Typealiases

                LifecycleHandler

                RouterHandler

                RouterParameterHandler

                WrittenDataFilter

BodyParser

public class BodyParser: RouterMiddleware

Router middleware for parsing the body of the request.

                    init()

Initializes a BodyParser instance.
Needed since default initalizer is internal.

Declaration

Swift

public init()

                    handle(request:response:next:)

Handle the request, i.e. parse the body of the request.

Declaration

Swift

public func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws

Parameters

                                request

the router request.

                                response

the router response.

                                next

the closure for the next execution block.

                    parse(_:contentType:)

Parse the body of the incoming message.

Declaration

Swift

public class func parse(_ message: RouterRequest, contentType: String?) -> ParsedBody?

Parameters

                                message

message coming from the socket.

                                contentType

the content type as a String.

Return Value

the parsed body.

                    readBodyData(with:)

Read the body data of the request.

Throws

    Socket.Error if an error occurred while reading from a socket.

Declaration

Swift

public class func readBodyData(with reader: RouterRequest) throws -> Data

Parameters

                                with

the socket reader.

Return Value

data for the body.

© 2017 IBM. All rights reserved. (Last updated: 2017-04-20)

Generated by jazzy ♪♫ v0.7.5, a Realm project.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>phpCAS: Callback from the CAS server</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Modules

Classes

Files

Examples

Functions |
Variables

Callback from the CAS server

[CAS Proxy features (CAS 2.0, Proxy Granting Tickets)]

Functions

 	CAS_Client::setCallbackMode ($callback_mode)

 	CAS_Client::isCallbackMode ()

 	CAS_Client::getCallbackURL ()

 	CAS_Client::setCallbackURL ($url)

 	CAS_Client::callback ()

Variables

 	CAS_Client::$_callback_mode

 	CAS_Client::$_callback_url

Function Documentation

          CAS_Client::callback
          (

           )
           [private, inherited]

This method is called by CAS_Client::CAS_Client() when running in callback mode. It stores the PGT and its PGT Iou, prints its output and halts.

Definition at line 1942 of file Client.php.

References phpCAS::error(), phpCAS::trace(), phpCAS::traceBegin(), and phpCAS::traceExit().

Referenced by CAS_Client::wasPreviouslyAuthenticated().

          CAS_Client::getCallbackURL
          (

           )
           [private, inherited]

This method returns the URL that should be used for the PGT callback (in fact the URL of the current request without any CGI parameter, except if phpCAS::setFixedCallbackURL() was used).

Returns:

The callback URL

Definition at line 1912 of file Client.php.

Referenced by CAS_Client::validateST().

          CAS_Client::isCallbackMode
          (

           )
           [private, inherited]

This method returns TRUE when the CAs client is running i callback mode, FALSE otherwise.

Returns:

A boolean.

Definition at line 1891 of file Client.php.

Referenced by CAS_Client::__construct(), and CAS_Client::wasPreviouslyAuthenticated().

          CAS_Client::setCallbackMode
          (
          $
           callback_mode
           )
           [private, inherited]

This method sets/unsets callback mode.

Parameters:

	$callback_mode 	TRUE to set callback mode, FALSE otherwise.

Definition at line 1880 of file Client.php.

Referenced by CAS_Client::__construct().

          CAS_Client::setCallbackURL
          (
          $
           url
           )
           [inherited]

This method sets the callback url.

Parameters:

	$callback_url 	url to set callback

Definition at line 1933 of file Client.php.

Variable Documentation

          CAS_Client::$_callback_mode [private, inherited]

each PHP script using phpCAS in proxy mode is its own callback to get the PGT back from the CAS server. callback_mode is detected by the constructor thanks to the GET parameters. a boolean to know if the CAS client is running in callback mode. Written by CAS_Client::setCallBackMode(), read by CAS_Client::isCallbackMode().

Definition at line 1873 of file Client.php.

          CAS_Client::$_callback_url [private, inherited]

the URL that should be used for the PGT callback (in fact the URL of the current request without any CGI parameter). Written and read by CAS_Client::getCallbackURL().

Definition at line 1903 of file Client.php.

<address class="footer">Generated on Sun Jun 5 2011 19:05:26 for phpCAS by

 1.7.1 </address>


text:
using NUnit.Framework;

namespace Vertica.Utilities.Tests
{
	[TestFixture]
	public partial class RangeTester
	{
		[Test]
		public void Intersect_Null_Empty()
		{
			Range<int> notEmpty = Range.New(1, 10);

			var intersection = notEmpty.Intersect(null);
			Assert.That(intersection, Is.SameAs(Range.Empty<int>()));
		}

		[Test]
		public void Intersect_NotEmptyToEmpty_Empty()
		{
			Range<int> notEmpty = Range.New(1, 10);

			var intersection = notEmpty.Intersect(Range.Empty<int>());
			Assert.That(intersection, Is.SameAs(Range.Empty<int>()));
		}

		[Test]
		public void Intersect_EmptyToNull_Empty()
		{
			var intersection = Range<byte>.Empty.Intersect(null);
			Assert.That(intersection, Is.SameAs(Range.Empty<byte>()));
		}

		[Test]
		public void Intersect_EmptyToNotEmpty_Empty()
		{
			Range<int> notEmpty = Range.New(1, 10);
			var intersection = Range<int>.Empty.Intersect(notEmpty);
			Assert.That(intersection, Is.SameAs(Range.Empty<int>()));
		}

		[Test]
		public void Intersect_EmptyToEmpty_Empty()
		{
			var intersection = Range<byte>.Empty.Intersect(Range.Empty<byte>());
			Assert.That(intersection, Is.SameAs(Range.Empty<byte>()));
		}

		[Test]
		public void Intersect_WellDisjoint_Empty()
		{
			Range<int> oneToTen = Range.New(1, 10),
				fiftytoHundred = Range.New(50, 100);

			var intersection = oneToTen.Intersect(fiftytoHundred);
			Assert.That(intersection, Is.SameAs(Range.Empty<int>()));
		}

		[Test]
		public void Intersect_LowerBoundNotTouchedByUpperBound_Empty()
		{
			Range<int> open = Range.Open(5, 10);
			Range<int> closed = Range.Closed(1, 5);

			var intersection = open.Intersect(closed);
			Assert.That(intersection, Is.SameAs(Range.Empty<int>()));
		}

		[Test]
		public void Intersect_UpperBoundNotTouchedByLowerBound_Empty()
		{
			Range<int> closed = Range.HalfOpen(5, 10);
			Range<int> halfClosed = Range.HalfClosed(10, 15);

			var intersection = closed.Intersect(halfClosed);
			Assert.That(intersection, Is.SameAs(Range.Empty<int>()));
		}

		[Test]
		public void Intersect_LowerBoundTouchingUpperBound_ClosedSingleLower()
		{
			Range<int> halfOpen = Range.HalfOpen(5, 10);
			Range<int> halfClosed = Range.HalfClosed(1, 5);

			var intersection = halfOpen.Intersect(halfClosed);

			Assert.That(intersection.LowerBound, Is.EqualTo(5));
			Assert.That(intersection.UpperBound, Is.EqualTo(5));
			Assert.That(intersection.Contains(5), Is.True);
		}

		[Test]
		public void Intersect_UpperBoundTouchingLowerBound_ClosedSingleUpper()
		{
			Range<int> halfClosed = Range.HalfClosed(5, 10);
			Range<int> halfOpen = Range.HalfOpen(10, 15);

			var intersection = halfClosed.Intersect(halfOpen);

			Assert.That(intersection.LowerBound, Is.EqualTo(10));
			Assert.That(intersection.UpperBound, Is.EqualTo(10));
			Assert.That(intersection.Contains(10), Is.True);
		}

		[Test]
		public void Intersect_WellContained_Contained()
		{
			Range<int> container = Range.New(1, 10),
				contained = Range.New(3, 6);

			var intersection = container.Intersect(contained);

			Assert.That(intersection, Is.EqualTo(contained));
		}

		[Test]
		public void Intersect_CleanIntersection_MaxLowerMinUpper()
		{
			Range<int> left = Range.Closed(1, 5),
				right = Range.Closed(3, 8);

			var intersection = left.Intersect(right);

			Assert.That(intersection.LowerBound, Is.EqualTo(3));
			Assert.That(intersection.UpperBound, Is.EqualTo(5));
		}

		[Test]
		public void Intersect_CleanIntersection_LowerNatureAsOfMaxLower()
		{
			Range<int> left = Range.Closed(1, 5),
				open = Range.Open(3, 8),
				closed = Range.Closed(3, 8);

			var openLower = left.Intersect(open);
			Assert.That(openLower.Contains(3), Is.False);

			var closedLower = left.Intersect(closed);
			Assert.That(closedLower.Contains(3), Is.True);
		}

		[Test]
		public void Intersect_CleanIntersection_UpperNatureAsOfMinUpper()
		{
			Range<int> right = Range.Closed(3, 8),
				open = Range.Open(1, 5),
				closed = Range.Closed(1, 5);

			var openUpper = right.Intersect(open);
			Assert.That(openUpper.Contains(5), Is.False);

			var closedUpper = right.Intersect(closed);
			Assert.That(closedUpper.Contains(3), Is.True);
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>core-common</artifactId>
        <groupId>com.jtbdevelopment.core-common</groupId>
        <version>1.11-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>core-spring-web-hazelcast</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.jtbdevelopment.core-common</groupId>
            <artifactId>core-spring-hazelcast</artifactId>
            <version>1.11-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
            <version>${spring.session.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servletapi.version}</version>
        </dependency>

    </dependencies>
</project>


text:
namespace YAF.Types.Interfaces
{
    using System;
    using System.Web.Security;

    /// <summary>
    /// The SendNotification Interface
    /// </summary>
    public interface ISendNotification
    {
        /// <summary>
        /// Sends Notifications to Moderators that Message Needs Approval
        /// </summary>
        /// <param name="forumId">The forum id.</param>
        /// <param name="newMessageId">The new message id.</param>
        /// <param name="isSpamMessage">if set to <c>true</c> [is spam message].</param>
        void ToModeratorsThatMessageNeedsApproval(int forumId, int newMessageId, bool isSpamMessage);

        /// <summary>
        /// Sends Notifications to Moderators that a Message was Reported
        /// </summary>
        /// <param name="pageForumID">
        /// The page Forum ID.
        /// </param>
        /// <param name="reportedMessageId">
        /// The reported message id.
        /// </param>
        /// <param name="reporter">
        /// The reporter.
        /// </param>
        /// <param name="reportText">
        /// The report Text.
        /// </param>
        void ToModeratorsThatMessageWasReported(int pageForumID, int reportedMessageId, int reporter, string reportText);

        /// <summary>
        /// Sends notification about new PM in user's inbox.
        /// </summary>
        /// <param name="toUserId">
        /// User supposed to receive notification about new PM.
        /// </param>
        /// <param name="subject">
        /// Subject of PM user is notified about.
        /// </param>
        void ToPrivateMessageRecipient(int toUserId, [NotNull] string subject);

        /// <summary>
        /// The to watching users.
        /// </summary>
        /// <param name="newMessageId">
        /// The new message id.
        /// </param>
        void ToWatchingUsers(int newMessageId);

        /// <summary>
        /// Send an Email to the Newly Created User with
        /// his Account Info (Pass, Security Question and Answer)
        /// </summary>
        /// <param name="user">
        /// The user.
        /// </param>
        /// <param name="pass">
        /// The pass.
        /// </param>
        /// <param name="securityAnswer">
        /// The security answer.
        /// </param>
        /// <param name="templateName">
        /// The template Name.
        /// </param>
        void SendRegistrationNotificationToUser(
            [NotNull] MembershipUser user,
            [NotNull] string pass,
            [NotNull] string securityAnswer,
            string templateName);

        /// <summary>
        /// Sends notification that the User was awarded with a Medal
        /// </summary>
        /// <param name="toUserId">To user id.</param>
        /// <param name="medalName">Name of the medal.</param>
        void ToUserWithNewMedal([NotNull] int toUserId, [NotNull] string medalName);

        /// <summary>
        /// The send registration notification email.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="userId">The user id.</param>
        void SendRegistrationNotificationEmail([NotNull] MembershipUser user, int userId);

        /// <summary>
        /// Sends a spam bot notification to admins.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="userId">The user id.</param>
        void SendSpamBotNotificationToAdmins([NotNull] MembershipUser user, int userId);

        /// <summary>
        /// Sends the user welcome notification.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="userId">The user identifier.</param>
        void SendUserWelcomeNotification([NotNull] MembershipUser user, int? userId);

        /// <summary>
        /// Sends the verification email.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="email">The email.</param>
        /// <param name="userID">The user identifier.</param>
        /// <param name="newUsername">The new username.</param>
        void SendVerificationEmail(
            [NotNull] MembershipUser user,
            [NotNull] string email,
            int? userID,
            string newUsername = null);

        /// <summary>
        /// Sends the user a suspension notification.
        /// </summary>
        /// <param name="suspendedUntil">The suspended until.</param>
        /// <param name="suspendReason">The suspend reason.</param>
        /// <param name="email">The email.</param>
        /// <param name="userName">Name of the user.</param>
        void SendUserSuspensionNotification(
            [NotNull] DateTime suspendedUntil,
            [NotNull] string suspendReason,
            [NotNull] string email,
            [NotNull] string userName);

        /// <summary>
        /// Sends the user a suspension ended notification.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="userName">Name of the user.</param>
        void SendUserSuspensionEndedNotification(
            [NotNull] string email,
            [NotNull] string userName);
    }
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper

  def login_required
    redirect_to('/') if !logged_in?
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="standardPrototype" class="com.programmingspring.koans.PrototypeBean" scope="prototype"/>

    <bean id="standardSingleton" class="com.programmingspring.koans.SingletonBean">
        <property name="prototypeBean" ref="standardPrototype"/>
    </bean>

    <bean id="singletonWithOverriddenLookupMethod" class="com.programmingspring.koans.SingletonBean">
        <lookup-method name="getPrototypeBean" bean="standardPrototype"/>
    </bean>

</beans>


text:
import React, { Component } from 'react';
import Index from './Index'
import Category from './Category'
import Post from './Post'
import PostNew from './PostNew'
import PostEdit from './EditPost'
import CommentEdit from './EditComment'
import Header from './Header'
import { Route, Switch } from 'react-router-dom'
import '../App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Header />
        <Switch>
          <Route path="/" exact component={Index} />
          <Route path="/post/new" exact component={PostNew} />
          <Route path="/:category" exact component={Category} />
          <Route path="/:category/:post_id" exact component={Post} />
          <Route path="/:category/:post_id/edit" component={PostEdit} />
          <Route path="/:category/:post_id/comments/:comment_id/edit" component={CommentEdit} />
        </Switch>
      </div>
    );
  }
}

export default App;


text:
require 'test_helper'

class ChiefTest < ActiveSupport::TestCase
  def setup
    @full_name = 'linuxfoundation/cii-best-practices-badge'
    @human_name = 'Core Infrastructure Initiative Best Practices Badge'

    @sample_project = Project.new
    @sample_project[:repo_url] = "https://github.com/#{@full_name}"
  end

  test 'CII badge results correct' do
    new_chief = Chief.new(@sample_project, proc { Octokit::Client.new })
    VCR.use_cassette('github') do
      new_chief.autofill
    end
    results = @sample_project

    # skip 'Temporarily skip while debugging website problem.'
    mit_ok = 'The MIT license is approved by the Open Source Initiative (OSI).'
    assert_equal 'MIT', results[:license]
    assert_equal @human_name, results[:name]
    assert_equal 'Met', results[:floss_license_status]
    assert_equal mit_ok, results[:floss_license_justification]
    assert_equal 'Met', results[:floss_license_osi_status]
    assert_equal mit_ok, results[:floss_license_osi_justification]
    assert_equal 'Met', results[:contribution_status]
    assert_equal 'Non-trivial contribution file in repository: ' \
                 '<https://github.com/linuxfoundation/' \
                 'cii-best-practices-badge/blob/master/CONTRIBUTING.md>.',
                 results[:contribution_justification]
    assert_equal 'Met', results[:release_notes_status]
    assert_equal 'Non-trivial release notes file in repository: ' \
                 '<https://github.com/linuxfoundation/' \
                 'cii-best-practices-badge/blob/master/CHANGELOG.md>.',
                 results[:release_notes_justification]
    assert_equal 'Met', results[:build_status]
    assert_equal 'Non-trivial build file in repository: ' \
                 '<https://github.com/linuxfoundation/' \
                 'cii-best-practices-badge/blob/master/Rakefile>.',
                 results[:build_justification]
  end

  test 'Fatal exceptions in a Detective will not crash production system' do
    old_environment = ENV['RAILS_ENV']
    # TEMPORARILY make this a 'production' environment (it isn't really)
    ENV['RAILS_ENV'] = 'production'

    new_chief = Chief.new(@sample_project, Octokit::Client.new)

    # Create special exception that happens nowhere else.  That way if
    # a *different* exception happens we don't accidentally pass the test.
    class WeirdException < StandardError
    end
    # Mock a detective who always fails
    class BadRepoFilesExamineDetective < RepoFilesExamineDetective
      def analyze(_, _)
        raise WeirdException,
              'Exception of BadRepoFilesExamineDetective', caller
      end
    end
    detective = BadRepoFilesExamineDetective.new

    VCR.use_cassette('github') do
      my_results = new_chief.propose_one_change(detective, {})
      # Restore original environment BEFORE assertions (clean up FIRST)
      if old_environment
        ENV['RAILS_ENV'] = old_environment
      else
        ENV.delete('RAILS_ENV')
      end
      # Ruby weirdness: {} is considered a block, not an empty hash,
      # so we can't use 'assert_equal {}, ...'.  We can't surround the {}
      # with parentheses to disambiguate it, because rubocop complains
      # with Lint/ParenthesesAsGroupedExpression.  So, do this instead.
      empty_hash = {}
      assert_equal empty_hash, my_results
    end
  end

  test 'Fatal exceptions in a Detective will crash the test system' do
    # Note difference with previous test.
    # Here we ensure that Detective exceptions WILL crash during testing.
    # This is an important distinction - we want the test environment
    # to crash quickly, so we detect problems and their causes quickly.
    # However, in production we don't want the system to crash.
    # Normally we want test and production systems to be the same,
    # but not in this way.  Thus, we must more carefully test the alternatives,
    # to ensure that both behaviors occur.

    old_environment = ENV['RAILS_ENV']
    # TEMPORARILY make this a 'test' environment (it probably is anyway)
    ENV['RAILS_ENV'] = 'test'

    new_chief = Chief.new(@sample_project, Octokit::Client.new)

    # Create special exception that happens nowhere else.  That way if
    # a *different* exception happens we don't accidentally pass the test.
    class WeirdException < StandardError
    end
    # Mock a detective who always fails
    class BadRepoFilesExamineDetective < RepoFilesExamineDetective
      def analyze(_, _)
        raise WeirdException,
              'Exception of BadRepoFilesExamineDetective', caller
      end
    end
    detective = BadRepoFilesExamineDetective.new

    VCR.use_cassette('github') do
      assert_raises WeirdException do
        new_chief.propose_one_change(detective, {})
      end
    end
    # Restore original environment.
    if old_environment
      ENV['RAILS_ENV'] = old_environment
    else
      ENV.delete('RAILS_ENV')
    end
  end
end


text:
class HomeAssistantError < StandardError
end


text:
@interface IMDatePickerVC : IMViewController

@property (nonatomic, strong) NSDate *minimumDate;
@property (nonatomic, strong) NSDate *maximumDate;
@property (nonatomic, strong) NSDate *date;

@property (nonatomic, copy) void (^onDateChanged)(NSDate *selectedDate);
@property (nonatomic, copy) void (^onDone)(NSDate *selectedDate);
@property (nonatomic, copy) void (^onCancel)(void);

- (id)initWithAction:(void (^)(NSDate *selectedDate))action;
- (id)initWithDoneHandler:(void (^)(NSDate *selectedDate))doneHandler onCancel:(void(^)(void))onCancel;

@end


text:
package com.thoughtworks.go.config.update;

import com.thoughtworks.go.config.BasicCruiseConfig;
import com.thoughtworks.go.config.elastic.ElasticProfile;
import com.thoughtworks.go.helper.GoConfigMother;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.ElasticProfileNotFoundException;
import com.thoughtworks.go.server.service.EntityHashingService;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ElasticAgentProfileUpdateCommandTest {
    private Username currentUser;
    private GoConfigService goConfigService;
    private BasicCruiseConfig cruiseConfig;
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Before
    public void setUp() throws Exception {
        currentUser = new Username("bob");
        goConfigService = mock(GoConfigService.class);
        cruiseConfig = GoConfigMother.defaultCruiseConfig();
    }

    @Test
    public void shouldRaiseErrorWhenUpdatingNonExistentProfile() throws Exception {
        cruiseConfig.server().getElasticConfig().getProfiles().clear();
        ElasticAgentProfileUpdateCommand command = new ElasticAgentProfileUpdateCommand(null, null, new ElasticProfile("foo", "docker"), null, new HttpLocalizedOperationResult(), null);
        thrown.expect(ElasticProfileNotFoundException.class);
        command.update(cruiseConfig);
    }

    @Test
    public void shouldUpdateExistingProfile() throws Exception {
        ElasticProfile oldProfile = new ElasticProfile("foo", "docker");
        ElasticProfile newProfile = new ElasticProfile("foo", "aws");

        cruiseConfig.server().getElasticConfig().getProfiles().add(oldProfile);
        ElasticAgentProfileUpdateCommand command = new ElasticAgentProfileUpdateCommand(null, null, newProfile, null, null, null);
        command.update(cruiseConfig);
        assertThat(cruiseConfig.server().getElasticConfig().getProfiles().find("foo"), is(equalTo(newProfile)));
    }

    @Test
    public void shouldNotContinueWithConfigSaveIfUserIsUnauthorized() {
        when(goConfigService.isUserAdmin(currentUser)).thenReturn(false);

        ElasticProfile oldProfile = new ElasticProfile("foo", "docker");
        ElasticProfile newProfile = new ElasticProfile("foo", "aws");

        cruiseConfig.server().getElasticConfig().getProfiles().add(oldProfile);
        HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
        ElasticAgentProfileUpdateCommand command = new ElasticAgentProfileUpdateCommand(goConfigService, null, newProfile, null, result, currentUser);

        assertThat(command.canContinue(cruiseConfig), is(false));
        assertThat(result.toString(), containsString("UNAUTHORIZED_TO_EDIT"));
    }

    @Test
    public void shouldNotContinueWithConfigSaveIfRequestIsNotFresh() {
        when(goConfigService.isUserAdmin(currentUser)).thenReturn(true);

        ElasticProfile oldProfile = new ElasticProfile("foo", "docker");
        ElasticProfile newProfile = new ElasticProfile("foo", "aws");

        cruiseConfig.server().getElasticConfig().getProfiles().add(oldProfile);

        EntityHashingService entityHashingService = mock(EntityHashingService.class);

        when(entityHashingService.md5ForEntity(oldProfile)).thenReturn("md5");

        HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
        ElasticAgentProfileUpdateCommand command = new ElasticAgentProfileUpdateCommand(goConfigService, entityHashingService, newProfile, "bad-md5", result, currentUser);

        assertThat(command.canContinue(cruiseConfig), is(false));
        assertThat(result.toString(), containsString("STALE_RESOURCE_CONFIG"));
    }
}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.common.zookeeper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;

import org.apache.aurora.common.io.Codec;
import org.apache.aurora.common.thrift.Endpoint;
import org.apache.aurora.common.thrift.ServiceInstance;
import org.apache.aurora.common.thrift.Status;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Gson.class)
public class JsonCodecTest {

  private static final Codec<ServiceInstance> STANDARD_JSON_CODEC = new JsonCodec();

  @Test
  public void testJsonCodecRoundtrip() throws Exception {
    Codec<ServiceInstance> codec = STANDARD_JSON_CODEC;
    ServiceInstance instance1 = new ServiceInstance(
        new Endpoint("foo", 1000),
        ImmutableMap.of("http", new Endpoint("foo", 8080)),
        Status.ALIVE)
        .setShard(0);
    byte[] data = ServerSets.serializeServiceInstance(instance1, codec);
    assertTrue(ServerSets.deserializeServiceInstance(data, codec).getServiceEndpoint().isSetPort());
    assertTrue(ServerSets.deserializeServiceInstance(data, codec).isSetShard());

    ServiceInstance instance2 = new ServiceInstance(
        new Endpoint("foo", 1000),
        ImmutableMap.of("http-admin1", new Endpoint("foo", 8080)),
        Status.ALIVE);
    data = ServerSets.serializeServiceInstance(instance2, codec);
    assertTrue(ServerSets.deserializeServiceInstance(data, codec).getServiceEndpoint().isSetPort());
    assertFalse(ServerSets.deserializeServiceInstance(data, codec).isSetShard());

    ServiceInstance instance3 = new ServiceInstance(
        new Endpoint("foo", 1000),
        ImmutableMap.<String, Endpoint>of(),
        Status.ALIVE);
    data = ServerSets.serializeServiceInstance(instance3, codec);
    assertTrue(ServerSets.deserializeServiceInstance(data, codec).getServiceEndpoint().isSetPort());
    assertFalse(ServerSets.deserializeServiceInstance(data, codec).isSetShard());
  }

  @Test
  public void testJsonCompatibility() throws IOException {
    ServiceInstance instance = new ServiceInstance(
        new Endpoint("foo", 1000),
        ImmutableMap.of("http", new Endpoint("foo", 8080)),
        Status.ALIVE).setShard(42);

    ByteArrayOutputStream results = new ByteArrayOutputStream();
    STANDARD_JSON_CODEC.serialize(instance, results);
    assertEquals(
        "{\"serviceEndpoint\":{\"host\":\"foo\",\"port\":1000},"
            + "\"additionalEndpoints\":{\"http\":{\"host\":\"foo\",\"port\":8080}},"
            + "\"status\":\"ALIVE\","
            + "\"shard\":42}",
        results.toString());
  }

  @Test
  public void testInvalidSerialize() {
    // Gson is final so we need to call on PowerMock here.
    Gson gson = PowerMock.createMock(Gson.class);
    gson.toJson(EasyMock.isA(Object.class), EasyMock.isA(Appendable.class));
    EasyMock.expectLastCall().andThrow(new JsonIOException("error"));
    PowerMock.replay(gson);

    ServiceInstance instance =
        new ServiceInstance(new Endpoint("foo", 1000), ImmutableMap.of(), Status.ALIVE);

    try {
      new JsonCodec(gson).serialize(instance, new ByteArrayOutputStream());
      fail();
    } catch (IOException e) {
      // Expected.
    }

    PowerMock.verify(gson);
  }

  @Test
  public void testDeserializeMinimal() throws IOException {
    String minimal = "{\"serviceEndpoint\":{\"host\":\"foo\",\"port\":1000},\"status\":\"ALIVE\"}";
    ByteArrayInputStream source = new ByteArrayInputStream(minimal.getBytes(Charsets.UTF_8));
    ServiceInstance actual = STANDARD_JSON_CODEC.deserialize(source);
    ServiceInstance expected =
        new ServiceInstance(new Endpoint("foo", 1000), ImmutableMap.of(), Status.ALIVE);
    assertEquals(expected, actual);
  }

  @Test
  public void testInvalidDeserialize() {
    // Not JSON.
    assertInvalidDeserialize(new byte[] {0xC, 0xA, 0xF, 0xE});

    // No JSON object.
    assertInvalidDeserialize("");
    assertInvalidDeserialize("[]");

    // Missing required fields.
    assertInvalidDeserialize("{}");
    assertInvalidDeserialize("{\"serviceEndpoint\":{\"host\":\"foo\",\"port\":1000}}");
    assertInvalidDeserialize("{\"status\":\"ALIVE\"}");
  }

  private void assertInvalidDeserialize(String data) {
    assertInvalidDeserialize(data.getBytes(Charsets.UTF_8));
  }

  private void assertInvalidDeserialize(byte[] data) {
    try {
      STANDARD_JSON_CODEC.deserialize(new ByteArrayInputStream(data));
      fail();
    } catch (IOException e) {
      // Expected.
    }
  }
}


text:
""" Device42 manager caching class """

import os
import json
import pickle
import glob
import device42_mgr.lib.utils as utils

class Cachier(object):
  """ Read/update the uri cache """
  def _load_from_cache(self, only_pickle=False):
    """ Method to load from cache - abstract how data is cached """
    data = {}

    if not only_pickle:
      json_files = glob.glob(os.path.join(self.cache_dir, '*.json'))
      for json_file in json_files:
        data.update(utils.load_json_file(json_file))

    pickled_files = glob.glob(os.path.join(self.cache_dir, '*.pickle'))
    for pickled_file in pickled_files:
      with open(pickled_file) as fdesc:
        data.update(pickle.load(fdesc))

    return data

  def _dump_to_cache(self, data):
    """ Method to dump to cache - abstract how data is cached """
    curr_ds = {}
    if os.path.exists(self.cache_filepath):
      curr_ds.update(self._load_from_cache(only_pickle=True))

    curr_ds.update(data)

    with open(self.cache_filepath, 'wb') as fdesc:
      pickle.dump(curr_ds, fdesc)

  def refresh(self, uris_ds_map):
    """ Refresh the cache """
    self._dump_to_cache(uris_ds_map)

  def load(self, uris=None):
    """ Load cached uri data from previous runs """
    if uris is None:
      uris = []

    data = self._load_from_cache()

    if not data:
      return {}

    if uris:
      valid_uris = set(data.keys()) & set(uris)
      if not valid_uris:
        return {}

      for invalid_uri in set(data.keys()) - valid_uris:
        del data[invalid_uri]

    return data

  def __str__(self):
    """ Handler when object is printed """
    return json.dumps(self.__dict__, indent=2)

  def __init__(self, cache_dir, cache_filename):
    self.cache_dir = cache_dir
    self.cache_filename = cache_filename
    self.cache_filepath = os.path.join(cache_dir, cache_filename)
    self.cache_exists = True
    if not os.path.exists(self.cache_filepath):
      self.cache_exists = False


text:
package alg.basic;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedQueue<Item> implements Iterable<Item>{
	private int n;
	private Node head;
	private Node tail;

	public LinkedQueue() {
		n = 0;
		head = null;
		tail = null;
	}

	public void enqueue(Item item) {
		Node oldtail = tail;
		tail = new Node();
		tail.item = item;
		tail.next = null;
		if (isEmpty()) {
			head = tail;
		} else {
			oldtail.next = tail;
		}
		n++;
	}
	public Item dequeue() {
		if (isEmpty()) {
			throw new NoSuchElementException("queue empty");
		}
		Item item = head.item;
		head = head.next;
		n--;
		if (isEmpty()) {
			tail = null;
		}
		return item;
	}
	public boolean isEmpty() {
		return n == 0;
	}

	public int size() {
		return n;
	}
	private class Node {
		private Item item;
		private Node next;
	}

	public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this) {
            s.append(item);
            s.append(' ');
        }
        return s.toString();
    }

	@Override
	public Iterator<Item> iterator() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import image_cropping.fields

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0005_auto_20151012_1611'),
    ]

    operations = [
        migrations.AddField(
            model_name='page',
            name='content3',
            field=models.TextField(blank=True, help_text='This content appears AFTER the SECOND banner', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='pagedraft',
            name='content3',
            field=models.TextField(blank=True, help_text='This content appears AFTER the SECOND banner', null=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='page',
            name='banner2',
            field=image_cropping.fields.ImageRatioField('image_banner2', '1920x1200', allow_fullsize=False, adapt_rotation=False, help_text=None, hide_image_field=False, size_warning=False, verbose_name='banner2', free_crop=False),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='page',
            name='content1',
            field=models.TextField(blank=True, help_text='This content appears AFTER the FIRST banner', null=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='page',
            name='content2',
            field=models.TextField(blank=True, help_text='This content appears BEFORE the FIRST banner', null=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='pagedraft',
            name='banner2',
            field=image_cropping.fields.ImageRatioField('image_banner2', '1920x1200', allow_fullsize=False, adapt_rotation=False, help_text=None, hide_image_field=False, size_warning=False, verbose_name='banner2', free_crop=False),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='pagedraft',
            name='content1',
            field=models.TextField(blank=True, help_text='This content appears AFTER the FIRST banner', null=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='pagedraft',
            name='content2',
            field=models.TextField(blank=True, help_text='This content appears BEFORE the FIRST banner', null=True),
            preserve_default=True,
        ),
    ]


text:
package net.kwas.impatient.ch5

class AgedPerson(var age: Int) {
  age = if (age < 0) 0 else age
}


text:
<?php

/**
 * HTML5 email input property.
 */
class Papi_Property_Email extends Papi_Property_String {

	/**
	 * The input type to use.
	 *
	 * @var string
	 */
	public $input_type = 'email';

}


text:
/*
 * These authors would like to acknowledge the Spanish Ministry of Industry,
 * Tourism and Trade, for the support in the project TSI020301-2008-2
 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled
 * Mobile Dynamic Environments", led by Treelogic
 * ( http://www.treelogic.com/ ):
 *
 *   http://www.piramidepse.com/
 */

package com.google.zxing.oned.rss.expanded;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.common.AbstractBlackBoxTestCase;

public final class RSSExpandedBlackBox2TestCase extends AbstractBlackBoxTestCase {

  public RSSExpandedBlackBox2TestCase() {
    super("test/data/blackbox/rssexpanded-2", new MultiFormatReader(), BarcodeFormat.RSS_EXPANDED);
    addTest(21, 23, 0.0f);
    addTest(19, 23, 180.0f);
  }
}


text:
Getting Started: Building a Chrome Extension

  Extensions allow you to add functionality to Chrome without diving deeply
  into native code. You can create new extensions for Chrome with those core
  technologies that you're already familiar with from web development: HTML,
  CSS, and JavaScript. If you've ever built a web page, you should feel right at
  home with extensions pretty quickly; we'll put that to the test right now by
  walking through the construction of a simple extension that will give you
  one-click access to pictures of kittens. Kittens!

  We'll do so by implementing a UI element we call a
  browser action, which allows us to place a
  clickable icon right next to Chrome's Omnibox for easy access. Clicking that
  icon will open a popup window filled with kittenish goodness, which will look
  something like this:

  If you'd like to follow along at home (and you should!), create a shiny new
  directory on your computer, and pop open your favourite text editor. Let's get
  going!

Something to Declare

  The very first thing we'll need to create is a <dfn>manifest file</dfn> named
  manifest.json. The manifest is nothing more than a JSON-formatted
  table of contents, containing properties like your extension's name and
  description, its version number, and so on. At a high level, we'll use it to
  declare to Chrome what the extension is going to do, and what permissions it
  requires in order to do those things.

  In order to display kittens, we'll want to tell Chrome that we'd like to
  create a browser action, and that we'd like free-reign to access kittens from
  a particular source on the net. A manifest file containing those instructions
  looks like this:

{
  "manifest_version": 2,

  "name": "One-click Kittens",
  "description": "This extension demonstrates a browser action with kittens.",
  "version": "1.0",

  "permissions": [
    "https://secure.flickr.com/"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

  Go ahead and save that data to a file named manifest.json in the
  directory you created, or

    download a copy of manifest.json from our sample repository
  .

What does it mean?

  The attribute names are fairly self-descriptive, but let's walk through the
  manifest line-by-line to make sure we're all on the same page.

  The first line, which declares that we're using version 2 of the manifest file
  format, is mandatory (version 1 is old, deprecated, and generally not
  awesome).

  The next block defines the extension's name, description, and version. These
  will be used both inside of Chrome to show a user which extensions you have
  installed, and also on the Chrome Web Store to display your extension to
  potentially new users. The name should be short and snappy, and the
  description no longer than a sentence or so (you'll have more room for a
  detailed description later).

  The final block first requests permission to work with data on
  https://secure.flickr.com/, and declares that this extension
  implements a browser action, assigning it a default icon and popup in the
  process.

Resources

  You probably noticed that manifest.json pointed at two resource
  files when defining the browser action: icon.png and
  popup.html. Both resources must exist inside the extension
  package, so let's create them now:

      icon.png will be displayed next to the Omnibox, waiting for
      user interaction. Download a copy of icon.png from our sample repository,

        Download a copy of icon.png from our sample repository
      , and save it into the directory you're working in. You could also
      create your own if you're so inclined; it's just a 19px-square PNG file.

      popup.html will be rendered inside the popup window that's
      created in response to a user's click on the browser action. It's a
      standard HTML file, just like you're used to from web development, giving
      you more or less free reign over what the popup displays.

        Download a copy of popup.html from our sample repository
      , and save it into
      the directory you're working in.

      popup.html requires an additional JavaScript file in order to
      do the work of grabbing kitten images from the web and loading them into
      the popup. To save you some effort, just

        download a copy of popup.js from our sample repository
      , and save it into the directory you're working in.

  You should now have four files in your working directory:
  icon.png,
  manifest.json,
  popup.html,
  popup.js.
  The next step is to load those files into Chrome.

Load the extension

  Extensions that you download from the Chrome Web Store are packaged up as
  .crx files, which is great for distribution, but not so great for
  development. Recognizing this, Chrome gives you a quick way of loading up your
  working directory for testing. Let's do that now.

      Visit chrome://extensions in your browser (or open up the
      Chrome menu by clicking the icon to the far right of the Omnibox:
      . and
      select Extensions under the Tools menu
      to get to the same place).

      Ensure that the Developer mode checkbox in the top
      right-hand corner is checked.

      Click Load unpacked extension… to pop up a
      file-selection dialog.

      Navigate to the directory in which your extension files live, and select
      it.

  If the extension is valid, it'll be loaded up and active right away! If it's
  invalid, an error message will be displayed at the top of the page. Correct
  the error, and try again.

Fiddle with Code

  Now that you've got your first extension up and running, let's fiddle with
  things so that you have an idea what your development process might look like.
  As a trivial example, let's change the data source to search for pictures of
  puppies instead of kittens.

  Hop into popup.js, and edit line 11 from
  var QUERY = 'kittens'; to read
  var QUERY = 'puppies';, and save your changes.

  If you click on your extension's browser action again, you'll note that your
  change hasn't yet had an effect. You'll need to let Chrome know that something
  has happened, either explicitly by going back to the extension page
  (chrome://extensions, or
  Tools > Extensions under the Chrome menu), and clicking
  Reload under your extension, or by reloading the extensions
  page itself (either via the reload button to the left of the Omnibox, or by
  hitting F5 or Ctrl-R).

  Once you've reloaded the extension, click the browser action icon again.
  Puppies galore!

What next?

  You now know about the manifest file's central role in bringing things
  together, and you've mastered the basics of declaring a browser action, and
  rendering some kittens (or puppies!) in response to a user's click. That's a
  great start, and has hopefully gotten you interested enough to explore
  further. There's a lot more out there to play around with.

      The Chrome Extension Overview backs up a bit,
      and fills in a lot of detail about extensions' architecture in general,
      and some specific concepts you'll want to be familiar with going forward.
      It's the best next step on your journey towards extension mastery.

      No one writes perfect code on the first try, which means that you'll need
      to learn about the options available for debugging your creations. Our
      debugging tutorial is perfect for that,
      and is well worth carefully reading.

      Chrome extensions have access to powerful APIs above and beyond what's
      available on the open web: browser actions are just the tip of the
      iceburg. Our chrome.* APIs documentation will
      walk you through each API in turn.

      Finally, the developer's guide has dozens of
      additional links to pieces of documentation you might be interested in.


text:
define(["jquery", "underscore", "socket-io", "helpers", "constants"],
    function ($, _, io, Helpers) {

        var globalConfig = {};
        var instances = [];

        var socket = io.connect(window.office.node_server_url);

        socket.on(Events.CONNECT, function () {
            socket.emit(Events.FRONT_GET_GLOBAL_CONF);
        });

        socket.on(Events.FRONT_SEND_GLOBAL_CONF, function (config) {
            console.log("front received global conf");
            globalConfig = config;

            // set up modules grid layout
            var dashboardInstances = $("#modules");
            dashboardInstances.css("grid-template-columns", Helpers.generateGridTemplateProperty(globalConfig["grid"]["columns"]));
            dashboardInstances.css("grid-template-rows", Helpers.generateGridTemplateProperty(globalConfig["grid"]["rows"]));

            socket.emit(Events.FRONT_GET_MODULES_INSTANCES);
        });

        var addUpdateModule = function (moduleConfig) {
            // Instanciate the module if it hasn't been yet
            // Only non-singleton modules with different ids can be instanciated several times
            var configs = _.pluck(instances, "config");
            // 'exist' indicates whether or not a module of the same type has already been instanciated
            var exist = _.findWhere(configs, { "type": moduleConfig["type"] });
            // 'instanciated' indicates whether or not a module with the same id has already been instanciated
            var instanciated = _.findWhere(configs, { "id": moduleConfig["id"] });
            // 'singleton' indicates wether or not this kind of module is allowed to instanciated several times within the same view
            var singleton = (typeof moduleConfig["singleton"] !== "undefined") ? moduleConfig["singleton"] : false;
            // 'dock' indicates wether or not this kind of module is docked to the top or bottom of the screen
            var dock = (typeof moduleConfig["dock"] !== "undefined") ? moduleConfig["dock"] : false;

            if (!instanciated) {
                if (!(exist && singleton)) {
                    // Instanciate front module
                    console.log("add new module", moduleConfig["id"]);
                    require(["modules/" + moduleConfig['type'] + "/frontend"], function (Module) {
                        instances.push(new Module(moduleConfig, $("#modules"), socket));
                    });
                }
            }
            else {
                // update module instance config
                console.log("update module", moduleConfig["id"]);
                _.findWhere(instances, { "id": instanciated["id"] }).updateConfig(moduleConfig);
            }
        };

        // send all modules
        socket.on(Events.FRONT_SEND_MODULES_INSTANCES, function (modules) {
            console.log("front received modules instances");
            modules.forEach(addUpdateModule);

            // if no grid layout, fallback to gridster
            if (!("grid-row-start" in document.body.style)) {
                require(["gridster"], function () {
                    var modulesEl = $("#modules");
                    modulesEl.parent().addClass("gridster");
                    modulesEl.gridster({
                        widget_base_dimensions: [ Math.round($("body").width() / globalConfig["grid"]["columns"]), Math.round($("body").height() / globalConfig["grid"]["rows"])],
                        widget_margins: [0, 0]
                    });
                    modulesEl.width($("body").width());
                });
            }
        });

        // Add new module
        socket.on(Events.FRONT_ADD_MODULE_INSTANCE, addUpdateModule);

        // Delete existing module
        socket.on(Events.FRONT_DELETE_MODULE_INSTANCE, function (moduleId) {
            console.log("delete module instance ", moduleId);

            // Destroy module instances
            var toDestroy = false;
            var indexDelete = null;
            instances.forEach(function (module, index) {
                if (moduleId === module.config.id) {
                    toDestroy = true;
                    indexDelete = index;
                }
            });
            if (toDestroy) {
                instances[indexDelete].destroy();
                instances.splice(indexDelete, 1);
            }
        });
    }
);


text:
<?php

namespace PragmaRX\Tracker\Data\Repositories;

class Language extends Repository
{
}


text:
/**
 * Chris Leuer 3/10/14
 * site Multi-series Line Chart as example , http://bl.ocks.org/mbostock/3884955
 */
    var bbVis, brush, createVis, dataSet, handle, height, margin, svg, svg2, width;

    margin = {
        top: 50,
        right: 50,
        bottom: 50,
        left: 50
    };

    width = 1300 - margin.left - margin.right;

    height = 900 - margin.bottom - margin.top;

    bbVis = {
        x: 0 + 100,
        y: 10,
        w: width - 100,
        h: 800
    };

    var dataSet = [];  // a bit perplexing so going to use http://bl.ocks.org/mbostock/3884955 method
                   // dataSet will be an array of object, each representing an estimate category
                   // where pcat:<estimate name>, popArr: <single dimension array of year:<value> and pop:<population>

    var dataSetFull = []; //similar structure as dataSet but includes missing years with estimates +
                          // includes an extra array isRealDataArr to indicate Y for real data , N for estimate

    svg = d3.select("#vis").append("svg").attr({
        width: width + margin.left + margin.right,
        height: height + margin.top + margin.bottom
    }).append("g").attr({
            transform: "translate(" + margin.left + "," + margin.top + ")"
        });

    //cl: new variables
    var maxYear;
    var color = d3.scale.category10();    //used to color the lines
    var pCats = []; //estimate categories

    d3.csv("worldpopulation.csv", function(data) {

       maxYear = d3.max(data, function(d) { return d.Year; } );

      // get estimate categories from first row of data
       pCats = d3.keys(data[0]).filter(function(key) { return key !== "Year"; });
       color.domain(pCats);  //each category gets a color

        //since dataSet is sparse, only populate array for population when category has value
        pCats.forEach( function(pcat, index) {
            var popArr = [];
            data.forEach( function (data, i) {
                if (data[pcat]) {
                    var pop =  {year: +data.Year, pop: +data[pcat]};
                    popArr.push(pop);
                }
            });
            //popArr is populated with a single estimate category. add to dataSet
            dataSet.push({pcat:pcat, popArr:popArr});

        });

        // -------------------------------------- Interpolation ---------------------------------------
        //
        // this fun algorithm populates dataSetFull with missing population estimates
        for (var key in dataSet) {    // key is the index for population object

            //yScalePop accepts a year and returns an population estimate
            var yScalePop = d3.scale.linear()
                .domain(dataSet[key].popArr.map(function(d) {return d.year;}))
                .range(dataSet[key].popArr.map(function(d) { return d.pop; }));

            var yearMin = d3.min(dataSet[key].popArr.map(function(d) {return d.year;}));
            var yearMax = d3.max(dataSet[key].popArr.map(function(d) {return d.year;}));
            var popArrFull =[];                 //popArr + missing estimates is the full array
            var isRealDataArr = [];             // array of Y/N indicator for real vs. estimate. used for styling
            var i = 0;                          // index for popArr

            for (var year = yearMin; year <= yearMax ; year++) {
                if ( dataSet[key].popArr[i].year == year) {
                    popArrFull.push(dataSet[key].popArr[i]); //push the current element into full array
                    isRealDataArr.push('Y');
                    i++;                        //iterate to next element
                } else {
                    var popMissing =  {year: year, pop: yScalePop(year)}; //magic to create missing pop estimate
                    popArrFull.push(popMissing);
                    isRealDataArr.push('N');
                }
            }
            dataSetFull.push({pcat:dataSet[key].pcat, popArr:popArrFull, isRealDataArr:isRealDataArr});
        }
        //---------------------------------------------------------------------------------------------

      return createVis();
    });

    // returns max population
    function maxPop () {
        var maxPopArr = [];
        for (var key in dataSet) {
            maxPopArr.push(d3.max(dataSet[key].popArr, function(d) { return d.pop;}));
        }
        return d3.max(maxPopArr);
    }

    createVis = function() {
        var xAxis, xScale, yAxis,  yScale;

		  // example that translates to the bottom left of our vis space:
		  var visFrame = svg.append("g").attr({
		      "transform": "translate(" + bbVis.x + "," + (bbVis.y + bbVis.h) + ")"
		  	  //....  cl:  looks like rect box is getting moved down 10 + 100, and right 100.
              // Only relationship between bbVis margin definition, is w: width - 100 where width is 960 - margin.left - margin.right .
              // so w:width really is 960 - 50 - 50 - 100 = 760 .   So basically the bbVis width is 200 smaller than the main SVG.
		  });

		  visFrame.append("rect");
		  //.... make cosmetic changes here to rect. revisit

          xScale = d3.scale.pow()
            .exponent(5)
            .domain([0,maxYear])
            .range([0, bbVis.w]);

          yScale = d3.scale.pow()
            .exponent(.9)
            .domain([0,maxPop()])
            .range([bbVis.h, 0]);   //reverse it. only 100 px. seems small

          yAxis = d3.svg.axis()
            .scale(yScale)
            .orient("left");

          xAxis = d3.svg.axis()
             .scale(xScale)
              .tickFormat(d3.format("d"))
              .tickValues([0, 1000,1200,1400,1500,1600, 1650, 1700,1750,1800, 1850,1900,1950,2000,2050])
             .orient("bottom");

          //add Y axis
          svg.append("g")
            .attr("class", "y axis")
            .attr("transform", "translate("+bbVis.x+"," + bbVis.y+ ")")//move right 100, down 110
            .call(yAxis);

          // add X axis
          svg.append("g")
            .attr("class", "xaxis")
            .attr("transform", "translate("+bbVis.x+"," + (bbVis.y + bbVis.h) + ")")//move right 100, down 110
            .call(xAxis);

          svg.append("text")
            .attr("class", "x label")
            .attr("text-anchor", "end")
            .attr("x", width)
            .attr("y", height - 6)
            .text("Years");

          svg.append("text")
            .attr("class", "y label")
            .attr("text-anchor", "end")
            .attr("y", 6)
            .attr("dy", ".75em")
            .attr("transform",  "translate("+bbVis.x+"," + 0 + ")" + "rotate(-90)")
            .text("Population");

          var populations = svg.selectAll(".population")
                .data(dataSetFull)
                .enter().append("g")
                .attr("class", "population");

          var line = d3.svg.line()
                .interpolate("basis")
                .x(function(d) { return (xScale(d.year) + bbVis.x); })
                .y(function(d) { return (yScale(d.pop) + bbVis.y); });

          populations.append("path")
                .attr("class", "line")
                .attr("d", function(d) {
                    return line(d.popArr); })
                .style("stroke", function(d) { return color(d.pcat); });

          for (var key in dataSetFull) {
                var realPoints = svg.selectAll(".realpoint")
                    .data(dataSetFull[key].popArr.filter (
                        function (d,i) {
                             return (dataSetFull[key].isRealDataArr[i] == 'Y');
                        }))
                    .enter().append("svg:circle")
                    .attr("stroke", "blue")
                    .attr("fill", function(d, i) { return "blue" })
                    .attr("cx", function(d, i) { return (xScale(d.year) + bbVis.x) })
                    .attr("cy", function(d, i) { return (yScale(d.pop) + bbVis.y) })
                    .attr("r", function(d, i) { return 2 });

                var estPoints = svg.selectAll(".realpoint")
                    .data(dataSetFull[key].popArr.filter (
                        function (d,i) {
                            return (
                                (dataSetFull[key].isRealDataArr[i] == 'N')
                                && ((dataSetFull[key].popArr[i].year % 20 == 0))  //only display estimates for every 20 years
                            );
                        }))
                    .enter().append("svg:circle")
                    .attr("stroke", "grey")
                    .attr("fill", function(d, i) { return "red" })
                    .attr("cx", function(d, i) { return (xScale(d.year) + bbVis.x) })
                    .attr("cy", function(d, i) { return (yScale(d.pop) + bbVis.y) })
                    .attr("r", function(d, i) { return 1 });

            }

    };


text:
package com.murphysean.bzrflag.agents;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.murphysean.bzrflag.interfaces.Agent;
import com.murphysean.bzrflag.models.Tank;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "type")
@JsonSubTypes({
		@JsonSubTypes.Type(value = PFAgent.class,name = "dumb"),
		@JsonSubTypes.Type(value = PFAgent.class,name = "pf")
})
public abstract class AbstractAgent extends Tank implements Agent{
	protected volatile String type;
	protected volatile float desiredSpeed;
	protected volatile float desiredAngularVelocity;
	protected volatile boolean desiredTriggerStatus;

	public AbstractAgent(){
		type = "abstract";
		desiredSpeed = 0.0f;
		desiredAngularVelocity = 0.0f;
		desiredTriggerStatus = false;
	}

	public synchronized String getType(){
		return type;
	}

	public synchronized float getDesiredSpeed(){
		return desiredSpeed;
	}

	public synchronized void setDesiredSpeed(float desiredSpeed){
		this.desiredSpeed = desiredSpeed;
	}

	public synchronized float getDesiredAngularVelocity(){
		return desiredAngularVelocity;
	}

	public synchronized void setDesiredAngularVelocity(float desiredAngularVelocity){
		this.desiredAngularVelocity = desiredAngularVelocity;
	}

	public synchronized boolean getDesiredTriggerStatus(){
		return false;
	}

	public synchronized void setDesiredTriggerStatus(boolean desiredTriggerStatus){
		this.desiredTriggerStatus = desiredTriggerStatus;
	}
}


text:
module Nanocoin.Network.Service (
  Service(..)
) where

import Protolude

-- This module describes the different services (processes) running on a
-- Nanocoin node.
--
-- PeerDiscovery:
--   Handles the discovery of new peers and the removal of dead peers.
--
-- Messaging;
--   Handles basic network messages for communication between nodes.

data Service = PeerDiscovery | Messaging
  deriving (Show)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
MockPortletSession (Commons FileUpload 1.2.1 Test API)
</TITLE>

<META NAME="date" CONTENT="2008-01-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.commons.fileupload

Class MockPortletSession

java.lang.Object
  org.apache.commons.fileupload.MockPortletSession

All Implemented Interfaces:
javax.portlet.PortletSession

public class MockPortletSession
extends java.lang.Object
implements javax.portlet.PortletSession

A mock portlet session, useful for unit testing and offline utilities
 Note: currently doesn't support scoping

Version:

$Id: MockPortletSession.java 479262 2006-11-26 03:09:24Z niallp $

Author:

David Sean Taylor

Field Summary

Fields inherited from interface javax.portlet.PortletSession

APPLICATION_SCOPE, PORTLET_SCOPE

Constructor Summary

MockPortletSession()

Method Summary

 java.lang.Object
getAttribute(java.lang.String name)

 java.lang.Object
getAttribute(java.lang.String name,
             int scope)

 java.util.Enumeration
getAttributeNames()

 java.util.Enumeration
getAttributeNames(int scope)

 long
getCreationTime()

 java.lang.String
getId()

 long
getLastAccessedTime()

 int
getMaxInactiveInterval()

 javax.portlet.PortletContext
getPortletContext()

 void
invalidate()

 boolean
isNew()

 void
removeAttribute(java.lang.String name)

 void
removeAttribute(java.lang.String name,
                int scope)

 void
setAttribute(java.lang.String name,
             java.lang.Object value)

 void
setAttribute(java.lang.String name,
             java.lang.Object value,
             int scope)

 void
setMaxInactiveInterval(int interval)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MockPortletSession

public MockPortletSession()

Method Detail

getAttribute

public java.lang.Object getAttribute(java.lang.String name)

Specified by:
getAttribute in interface javax.portlet.PortletSession

getAttribute

public java.lang.Object getAttribute(java.lang.String name,
                                     int scope)

Specified by:
getAttribute in interface javax.portlet.PortletSession

getAttributeNames

public java.util.Enumeration getAttributeNames(int scope)

Specified by:
getAttributeNames in interface javax.portlet.PortletSession

getCreationTime

public long getCreationTime()

Specified by:
getCreationTime in interface javax.portlet.PortletSession

getId

public java.lang.String getId()

Specified by:
getId in interface javax.portlet.PortletSession

getLastAccessedTime

public long getLastAccessedTime()

Specified by:
getLastAccessedTime in interface javax.portlet.PortletSession

getMaxInactiveInterval

public int getMaxInactiveInterval()

Specified by:
getMaxInactiveInterval in interface javax.portlet.PortletSession

invalidate

public void invalidate()

Specified by:
invalidate in interface javax.portlet.PortletSession

isNew

public boolean isNew()

Specified by:
isNew in interface javax.portlet.PortletSession

removeAttribute

public void removeAttribute(java.lang.String name)

Specified by:
removeAttribute in interface javax.portlet.PortletSession

removeAttribute

public void removeAttribute(java.lang.String name,
                            int scope)

Specified by:
removeAttribute in interface javax.portlet.PortletSession

setAttribute

public void setAttribute(java.lang.String name,
                         java.lang.Object value)

Specified by:
setAttribute in interface javax.portlet.PortletSession

getAttributeNames

public java.util.Enumeration getAttributeNames()

Specified by:
getAttributeNames in interface javax.portlet.PortletSession

setAttribute

public void setAttribute(java.lang.String name,
                         java.lang.Object value,
                         int scope)

Specified by:
setAttribute in interface javax.portlet.PortletSession

setMaxInactiveInterval

public void setMaxInactiveInterval(int interval)

Specified by:
setMaxInactiveInterval in interface javax.portlet.PortletSession

getPortletContext

public javax.portlet.PortletContext getPortletContext()

Specified by:
getPortletContext in interface javax.portlet.PortletSession

      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright ? 2002-2008 The Apache Software Foundation. All Rights Reserved.


text:
const {
  doc: {
    builders: { hardline, join }
  },
  util: { hasNewline }
} = require('prettier');

function isIndentableBlockComment(comment) {
  // If the comment has multiple lines and every line starts with a star
  // we can fix the indentation of each line. The stars in the `/*` and
  // `*/` delimiters are not included in the comment value, so add them
  // back first.
  const lines = `*${comment.raw}*`.split('\n');
  return lines.length > 1 && lines.every((line) => line.trim()[0] === '*');
}

function printIndentableBlockComment(comment) {
  const lines = comment.raw.split('\n');

  return [
    '/*',
    join(
      hardline,
      lines.map((line, index) =>
        index === 0
          ? line.trimRight()
          : ` ${index < lines.length - 1 ? line.trim() : line.trimLeft()}`
      )
    ),
    '*/'
  ];
}

function printComment(commentPath, options) {
  const comment = commentPath.getValue();

  switch (comment.type) {
    case 'BlockComment': {
      if (isIndentableBlockComment(comment)) {
        const printed = printIndentableBlockComment(comment);
        // We need to prevent an edge case of a previous trailing comment
        // printed as a `lineSuffix` which causes the comments to be
        // interleaved. See https://github.com/prettier/prettier/issues/4412
        if (
          comment.trailing &&
          !hasNewline(options.originalText, options.locStart(comment), {
            backwards: true
          })
        ) {
          return [hardline, printed];
        }
        return printed;
      }

      return `/*${comment.raw}*/`;
    }
    case 'LineComment':
      return `//${comment.raw.trimRight()}`;
    default:
      throw new Error(`Not a comment: ${JSON.stringify(comment)}`);
  }
}

module.exports = printComment;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MotorLogico.Hilos;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;

/**
 *
 * @author Usuario
 */
public class HiloMovimiento extends Thread {

    JPanel Pan;

    public HiloMovimiento(JPanel Pan1) {
        this.Pan = Pan1;
    }
    int a = (995 - 330) / 2, b = 20, ac = 330, dc = 430;
    boolean aaa = true;

    public void run() {
        for (int i = 150; i <= 600; i++) {
            i++;
            Pan.setBounds(i, b, ac, dc);
            try {
                Thread.sleep(1);
            } catch (InterruptedException ex) {
                Logger.getLogger(HiloMovimiento.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for (int i = 600; i >= a; i--) {
            i--;
            Pan.setBounds(i, b, ac, dc);
            try {
                Thread.sleep(1);
            } catch (InterruptedException ex) {
                Logger.getLogger(HiloMovimiento.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}


text:
//
//  DDAlertView.m
//  DDAlertView
//
//  Created by Alex on 16/8/1.
//  Copyright © 2016年 Alex. All rights reserved.
//

#import "DDAlertView.h"

@interface DDAlertView ()

/**
 *  title
 */
@property (weak, nonatomic) IBOutlet UILabel *titleLbl;
/**
 *  Mseeage
 */
@property (weak, nonatomic) IBOutlet UILabel *messageLbl;
/**
 *  取消按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
/**
 *  确认按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *sureButton;
/**
 *  单独一个按钮View
 */
@property (weak, nonatomic) IBOutlet UIView *singleView;
/**
 *  单独一个按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *singleButton;
/**
 *  centerView
 */
@property (weak, nonatomic) IBOutlet UIView *centerView;
/**
 *  centerView 高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *centerViewHeightConstraint;

@end

@implementation DDAlertView

+ (instancetype)sharedInstance
{
    static DDAlertView *_customAlertView;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_customAlertView == nil) {
            _customAlertView = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"DDAlertView" owner:self options:nil] lastObject];
        }
    });
    return _customAlertView;
}

- (void)setCenterView
{
    self.centerView.layer.masksToBounds = YES;
    self.centerView.layer.cornerRadius = 6.f;
}

#pragma mark -
#pragma mark -  两个按钮用
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message okBtnTitle:(NSString *)okBtnTitle cancelBtnTitle:(NSString *)cancelBtnTitle  sureBlock:(SureBlock)sureBlock cancelBlock:(CancelBlock)cancelBlock
{

    self.sureBlock = sureBlock;
    self.cancelBlock = cancelBlock;

    [self setCenterView];

    [self updateCenterViewHeight:message];

    self.singleView.hidden = YES;

    self.titleLbl.text = title;
    self.messageLbl.text = message;
    [self.sureButton setTitle:okBtnTitle forState:UIControlStateNormal];
    [self.cancelButton setTitle:cancelBtnTitle forState:UIControlStateNormal];

    [self addWndow];
}

#pragma mark -
#pragma mark -  单独一个按钮的时候用
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message singleBtnTitle:(NSString *)singleBtnTitle  singleBlock:(SingleBlock)singleBlock
{
    self.singleBlock = singleBlock;

    [self setCenterView];

    [self updateCenterViewHeight:message];

    self.singleView.hidden = NO;

    self.titleLbl.text = title;
    self.messageLbl.text = message;
    [self.singleButton setTitle:singleBtnTitle forState:UIControlStateNormal];

    [self addWndow];
}

#pragma mark -
#pragma mark - add window
- (void)addWndow
{
    self.backgroundColor = [UIColor colorWithWhite:.1 alpha:.3];

    UIWindow *window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    window.windowLevel = UIWindowLevelNormal;
    self.frame = [[UIScreen mainScreen] bounds];
    [window addSubview:self];

}

#pragma mark -
#pragma mark - 取消按钮点击事件
- (IBAction)cancelBtnClicked:(id)sender {

    [self alertDismiss];
    if (self.cancelBlock != nil) {
        self.cancelBlock();
    }
}

#pragma mark -
#pragma mark - 确定按钮点击事件
- (IBAction)sureBtnClicked:(id)sender {
    [self alertDismiss];
    if (self.sureBlock != nil) {
        self.sureBlock();
    }
}

#pragma mark -
#pragma mark - 一个按钮点击事件
- (IBAction)singleBtnClicked:(id)sender {
    [self alertDismiss];
    if (self.singleBlock != nil) {
        self.singleBlock();
    }
}

#pragma mark -
#pragma mark -  对话框消失
- (void)alertDismiss {
    [self removeFromSuperview];
}

#pragma mark -
#pragma mark -  设置Title Color
- (void)setTitleColorWithColor:(UIColor *)color
{
    self.titleLbl.textColor = color;
}

#pragma mark -
#pragma mark -  设置 Message Color
- (void)setMessageColorWithColor:(UIColor *)color
{
    self.messageLbl.textColor = color;
}

#pragma mark -
#pragma mark -  更新CenterView高度
- (void)updateCenterViewHeight:(NSString *)msg
{
    self.centerViewHeightConstraint.constant = [self getMsgWidth:msg].height + 120;
}

#pragma mark -
#pragma mark -  获取Message的Size
- (CGSize)getMsgWidth:(NSString *)title
{
    CGRect bounds = [[UIScreen mainScreen] bounds];
    CGFloat labelWidth = bounds.size.width - 40*2 - 8*2;
    CGSize titleSize = [title boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleLbl.font} context:nil].size;

    return titleSize;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
require 'minitest_helper'

describe 'shared locks' do
  def supported?
    %i[mysql2 jdbcmysql].exclude?(env_db)
  end

  class SharedTestWorker
    def initialize(shared)
      @shared = shared

      @locked = nil
      @cleanup = false
      @thread = Thread.new { work }
    end

    def locked?
      sleep 0.01 while @locked.nil? && @thread.alive?
      @locked
    end

    def cleanup!
      @cleanup = true
      @thread.join
      raise if @thread.status.nil?
    end

    private

    def work
      ActiveRecord::Base.connection_pool.with_connection do
        Tag.with_advisory_lock('test', timeout_seconds: 0, shared: @shared) do
          @locked = true
          sleep 0.01 until @cleanup
        end
        @locked = false
        sleep 0.01 until @cleanup
      end
    end
  end

  it 'does not allow two exclusive locks' do
    one = SharedTestWorker.new(false)
    assert_predicate(one, :locked?)

    two = SharedTestWorker.new(false)
    refute(two.locked?)

    one.cleanup!
    two.cleanup!
  end

  describe 'not supported' do
    before do
      skip if supported?
    end

    it 'raises an error when attempting to use a shared lock' do
      one = SharedTestWorker.new(true)
      assert_nil(one.locked?)

      exception = assert_raises(ArgumentError) do
        one.cleanup!
      end

      assert_match(/#{Regexp.escape('not supported')}/, exception.message)
    end
  end

  describe 'supported' do
    before do
      skip unless supported?
    end

    it 'does allow two shared locks' do
      one = SharedTestWorker.new(true)
      assert_predicate(one, :locked?)

      two = SharedTestWorker.new(true)
      assert_predicate(two, :locked?)

      one.cleanup!
      two.cleanup!
    end

    it 'does not allow exclusive lock with shared lock' do
      one = SharedTestWorker.new(true)
      assert_predicate(one, :locked?)

      two = SharedTestWorker.new(false)
      refute(two.locked?)

      three = SharedTestWorker.new(true)
      assert_predicate(three, :locked?)

      one.cleanup!
      two.cleanup!
      three.cleanup!
    end

    it 'does not allow shared lock with exclusive lock' do
      one = SharedTestWorker.new(false)
      assert_predicate(one, :locked?)

      two = SharedTestWorker.new(true)
      refute(two.locked?)

      one.cleanup!
      two.cleanup!
    end

    describe 'PostgreSQL' do
      before do
        skip unless env_db == :postgresql
      end

      def pg_lock_modes
        ActiveRecord::Base.connection.select_values("SELECT mode FROM pg_locks WHERE locktype = 'advisory';")
      end

      it 'allows shared lock to be upgraded to an exclusive lock' do
        assert_empty(pg_lock_modes)
        Tag.with_advisory_lock 'test', shared: true do
          assert_equal(%w[ShareLock], pg_lock_modes)
          Tag.with_advisory_lock 'test', shared: false do
            assert_equal(%w[ShareLock ExclusiveLock], pg_lock_modes)
          end
        end
        assert_empty(pg_lock_modes)
      end
    end
  end
end


text:
define(
    [
        'react',
        'jquery',
    ],
    function(React,$){
    	var ContainerFive = React.createClass({
    		render: function(){
                var style = {
                    height: '250px'
                };
                //style="overflow: hidden; width: auto; height: 250px;"
    			return (

                                <button className="btn btn-primary btn-sm daterange pull-right" data-toggle="tooltip" title="Date range">

                                </button>
                                <button className="btn btn-primary btn-sm pull-right" data-widget="collapse" data-toggle="tooltip" title="Collapse">

                                </button>

                                Visitors

    			)
    		}
    	})

    	return ContainerFive;
    }
)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?=$title?></title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="stylesheet" type="text/css" href="<?=base_url();?>assets/template/style.css" />

ComproUsados La Plata

<?=anchor('products', 'Home');?>

Portafolio

Nosotros

Contactenos

        <?php if($total_items=$this->cart->total_items()):?>
<?=anchor('products/cart', 'Carrito - '.$total_items);?>
 <?php endif; ?>


text:
#include "config.h"

#include "platform/graphics/OpaqueRectTrackingContentLayerDelegate.h"

#include "platform/EventTracer.h"
#include "platform/geometry/IntRect.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/transforms/AffineTransform.h"
#include "public/platform/WebFloatRect.h"
#include "public/platform/WebRect.h"

using blink::WebFloatRect;
using blink::WebRect;

namespace WebCore {

OpaqueRectTrackingContentLayerDelegate::OpaqueRectTrackingContentLayerDelegate(GraphicsContextPainter* painter)
    : m_painter(painter)
    , m_opaque(false)
{
}

OpaqueRectTrackingContentLayerDelegate::~OpaqueRectTrackingContentLayerDelegate()
{
}

void OpaqueRectTrackingContentLayerDelegate::paintContents(SkCanvas* canvas, const WebRect& clip, bool canPaintLCDText, WebFloatRect& opaque)
{
    static const unsigned char* annotationsEnabled = 0;
    if (UNLIKELY(!annotationsEnabled))
        annotationsEnabled = EventTracer::getTraceCategoryEnabledFlag(TRACE_DISABLED_BY_DEFAULT("blink.graphics_context_annotations"));

    GraphicsContext context(canvas);
    context.setTrackOpaqueRegion(!m_opaque);
    context.setCertainlyOpaque(m_opaque);
    context.setShouldSmoothFonts(canPaintLCDText);

    if (*annotationsEnabled)
        context.setAnnotationMode(AnnotateAll);

    // Record transform prior to painting, as all opaque tracking will be
    // relative to this current value.
    AffineTransform canvasToContentTransform = context.getCTM().inverse();

    m_painter->paint(context, clip);

    // Transform tracked opaque paints back to our layer's content space.
    ASSERT(canvasToContentTransform.isInvertible());
    ASSERT(canvasToContentTransform.preservesAxisAlignment());
    opaque = canvasToContentTransform.mapRect(context.opaqueRegion().asRect());
}

}


text:
require 'helper'
require 'user'
require 'fetcher'
require 'json'

describe Sunrize::User do
  before do
    @redis = Redis.new
    @redis.del 'sunrize:osahyoun'
  end

  it 'should respond appropriately when user not found' do
    response = Sunrize::User.find('osahyoun')
    response.should == {:status => '404', :message => "User was not found."}
  end

  it "should know if a user does not exists" do
    Sunrize::User.exists?('iDoNotExist').should == false
  end

  it "should know if a user exists" do
    stub_get('osahyoun')
    Sunrize::Fetcher.fetch('osahyoun')
    Sunrize::User.exists?('osahyoun').should == true
  end

  it 'should return user data when user is found' do
    stub_get('osahyoun')
    Sunrize::Fetcher.new('osahyoun').save
    user = Sunrize::User.find('osahyoun')

    fixture_stats['osahyoun'].each do |key, val|
      if key == :courses
        user[key.to_s].first.should == val.first
      else
        user[key.to_s].should == val.to_s
      end
    end
  end
end


text:
<template>
    <canvas class="hide" id="canvas" width.bind="width" height.bind="height"></canvas>
</template>


text:
  Chalmazel est
       un village
       localisé dans le département de Loire en Rhône-Alpes. On dénombrait 469 habitants en 2008.

Le parc d'habitations, à Chalmazel, se décomposait en 2011 en 113 appartements et 369 maisons soit
 un marché relativement équilibré.

À coté de Chalmazel sont localisées les communes de
Sauvain à 5 km, 413 habitants,
La Côte-en-Couzan située à 7 km, 71 habitants,
Saint-Didier-sur-Rochefort localisée à 9 km, 422 habitants,
La Valla-sur-Rochefort située à 6 km, 130 habitants,
Saint-Bonnet-le-Courreau localisée à 8 km, 729 habitants,
Palogneux localisée à 6 km, 52 habitants,
 entre autres. De plus, Chalmazel est située à seulement 19 km de Montbrison.

La commune offre de multiples  équipements sportifs, elle propose entre autres deux terrains de tennis, un domaine skiable, un terrain de sport et deux boucles de randonnée.

Si vous pensez demenager à Chalmazel, vous pourrez facilement trouver une maison à acheter.


text:
//
//  SLViewController.m
//  ZWar_for_SpriteKit
//
//  Created by bindiry on 13-9-19.
//  Copyright (c) 2013年 bindiry. All rights reserved.
//

#import "SLViewController.h"
#import "SLMyScene.h"

@implementation SLViewController

- (void)viewDidAppear:(BOOL)animated
{
    /**
     为了使之后的工作轻松一些,我们可以选择在初始的view显示完成,尺寸通过rotation计算完毕之后再添加新的Scene,这样得到的Scene的尺寸将是宽480(或者568)高320的size。如果在appear之前就使用bounds.size添加的话,将得到宽320 高480(568)的size,会很麻烦。
     所以将ViewController.m中的-viewDidLoad:方法全部替换成下面的-viewDidAppear:。
     */
    [super viewDidAppear:animated];

    // Configure the view
    SKView *skView = (SKView *)self.view;
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;

    // Create and configure the scene
    SKScene *scene = [SLMyScene sceneWithSize:skView.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;

    // Present the scene
    [skView presentScene:scene];
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {
        return UIInterfaceOrientationMaskAll;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

@end


text:
<?php

namespace Lyrixx\Twitter\Exception;

/**
 * ApiServerException
 *
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 */
class ApiServerException extends \RuntimeException implements ExceptionInterface
{
}