text:
package mud.foe;

import java.util.Arrays;
import java.util.Calendar;
import java.util.EnumSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;

import mud.Constants;
import mud.ObjectFlag;
import mud.colors.Colors;
import mud.foe.misc.Device;
import mud.foe.misc.File;
import mud.foe.misc.FileSystem;
import mud.foe.misc.IODevice;
import mud.foe.misc.Port;
import mud.foe.misc.User;
import mud.foe.misc.Module;
import mud.objects.Thing;
import mud.utils.Pair;
import mud.utils.Time;
import mud.utils.Utils;
import mud.utils.LoginData;

public class Terminal extends Thing implements IODevice {
	// power state:  NO_POWER, POWER, POWER_OFF
	// login state:  LOGGED_IN, LOGGED_OUT, GET_USER, GET_PASS
	// usable state: USABLE, LOCKOUT, BROKEN

	public enum Power { NO_POWER, POWER_OFF, POWER_ON };
	public enum Login { LOGGED_IN, LOGGED_OUT, GET_USER, GET_PASS, LOCKOUT};
	public enum Use { USABLE, BROKEN };

	/* the states above are pseudo-independent. Obviously usable/broken
	 * is a world level hardware state that effects whether the device
	 * can ever be used, while the power states indicate whether the device
	 * has power OR if, having power, the device is on or off. If the
	 * device is usable, has power, and is ON then the login state comes in to
	 * play. If the login state is knocked into lockout (which is a persistent
	 * value/state independent of power) the device will become entirely unusable
	 * unless it is reset in some fashion.
	 *
	 * The power being ON or OFF means that there is power available. Somehow cutting power
	 * will force the terminal into NO power so that a power connect will have to be noticed somehow
	 * before it can be turned on again
	 */

	//enum Screens { HACK, LOGIN, PROMPT };

	private int id = 0; // device ids

	private Power power_state = Power.POWER_OFF;
	private Login login_state = Login.LOGGED_OUT;
	private Use usable_state = Use.USABLE;

	// Hardware
	private List<Port> ports;          // all ports
	private Map<Device, Port> devices; // no null values

	// Firmware/Software?
	private FileSystem fs;
	private Map<String, User> users;   // no null values

	//private Time localTime;

	// I/O
	private Queue<String> input;
	private Queue<String> output;

	// Screen
	private Queue<String> screen_buffer;
	private int screen_height = 25;

	// user data
	private String current_user = "";
	private String current_dir = "/";

	// meta-state for controlling execution/thread
	private boolean running;
	private boolean paused;

	private boolean startup = true;

	private boolean initialized = false;

	// misc?
	private LoginData ldat;

	private String input_state = "";
	private Pair<String> action = null;
	//private String data = "";

	private static String OVERRIDE = "CMC-ARE-AWESOME"; // hard coded back door...

	/*
	 * Relevant to their use in a game, running should mean that the terminal
	 * is powered on and so on, whereas paused should mean that the terminal is not
	 * presently in use but is only relevant if running is TRUE.
	 */
	public Terminal(final String tName) {
		super(tName, "");
	}

	public Terminal(final String tName, final String tDesc) {
		// TODO would like initial power state to be on, but this conflicts with powerOn()...
		this(tName, tDesc, Power.POWER_OFF, Login.LOGGED_OUT, Use.USABLE);
	}

	public Terminal(final String tName, final String tDesc, final Power tPState, final Login tLState, final Use tUState) {
		super(tName, tDesc);

		this.thing_type = FOEThingTypes.TERMINAL;

		this.ldat = new LoginData(Constants.USERNAME);

		if(tPState != null) this.power_state = tPState;
		else                this.power_state = Power.POWER_OFF;

		if(tLState != null) this.login_state = tLState;
		else                this.login_state = Login.LOGGED_OUT;

		if(tUState != null) this.usable_state = tUState;
		else                this.usable_state = Use.USABLE;
	}

	public Terminal(final int dbref, final String name, final EnumSet<ObjectFlag> flags, final String description, final int location) {
		super(dbref, name, flags, description, location);
	}

	static public void main(String[] args) {
		final Terminal term = new mud.foe.Terminal("Terminal", "A Stable-Tec terminal, old pre-war technology whose durability is plain to see. On the screen, passively glowing green text indicates that it awaits input.");

		term.init();
		term.powerOn();

		Scanner s = new Scanner(System.in);

		//

		while( !term.isPaused() ) {
			term.exec();

			String line = term.read();

			while(line != null) {
				System.out.print( line );

				line = term.read();
			}

			if( term.isPaused() ) {
				System.out.println("Stopped using terminal.");
			}

			if( s.hasNextLine() ) {
				term.write( s.nextLine() );
			}
		}

		//

		s.close();
	}

	// removed setPowerState(...), the only problem I might encounter is the notion
	// of supplying power to a formerly unpowered terminal

	public Power getPowerState() {
		return this.power_state;
	}

	// remove setLoginState(...) as nothing external should need to change this

	public Login getLoginState() {
		return this.login_state;
	}

	/* connect <device> to <port> */
	public boolean connect(final Device device) {
		if( hasPort( device.getDeviceType() ) ) {
			if( !isDeviceConnected( device ) ) {
				devices.put(device, getPort( device.getDeviceType() ));
			}
		}

		return false;
	}

	/* disconnect <device> */
	public void disconnect(final Device device) {
		if( isDeviceConnected( device ) ) {
			devices.remove( device );
		}
	}

	public boolean isDeviceConnected( Device device ) {
		return devices.containsKey( device );
	}

	private Port getPort(final DeviceType deviceType) {
		for(final Port port : ports) {
			if( port.getPortType() == deviceType ) {
				if( !devices.containsValue(port) ) return port;
			}
		}

		return null;
	}

	private boolean hasPort(final DeviceType deviceType) {
		boolean hasPort = false;

		if( getPort(deviceType) != null ) hasPort = true;

		return hasPort;
	}

	/* called to enumerate what devices are connected */
	private void scanPorts() {
		if( ports.size() != 0 ) {
			if( devices.size() != 0 ) {
				for(final Device dev : devices.keySet()) {
					System.out.println(devices.get( dev ) + " : " + dev);
				}
			}
			else System.out.println("No Connected Devices");
		}
		else System.out.println("No Ports");

	}

	/*public List<String> getScreen() {
		return Arrays.asList( (String[]) screen_buffer.toArray() );
	}*/

	public void setPaused(boolean value) {
		this.paused = value;
	}

	public boolean isPaused() {
		return this.paused;
	}

	public void init() {
		if( !this.initialized ) {
			// initialize port list and device map
			this.ports = new LinkedList<Port>();
			this.devices = new Hashtable<Device, Port>();

			this.fs = new FileSystem();

			this.fs.newDir("/bin");
			this.fs.newDir("/boot");
			this.fs.newDir("/dev");
			this.fs.newDir("/lib");
			this.fs.newDir("/mnt");
			this.fs.newDir("/opt");
			this.fs.newDir("/users");
			this.fs.newDir("/root");
			this.fs.newDir("/sbin");
			this.fs.newDir("/system");
			this.fs.newDir("/tmp");

			// TODO fix kludge, write code inserts a / in between dir and filename which borks a file called '/'
			String[] data = new String[] {
					"/bin", "/boot", "/dev", "/lib", "/mnt",
					"/opt", "/users", "/root", "/sbin", "/system",
					"/tmp" };

			this.fs.write("/", data, 'a');

			this.users = new Hashtable<String, User>();

			// initialize input and output
			this.input = new LinkedList<String>();
			this.output = new LinkedList<String>();

			//
			this.screen_buffer = new LinkedList<String>();

			// add users
			addUser("admin", OVERRIDE);

			this.users.get("admin").setPerm(4);

			this.initialized = true;

			// TODO running/paused should dependent on power state and use state...
			// start running, not paused
			this.running = true;
			this.paused = true;

			System.out.println("Terminal Initialized!");
		}
	}

	public void exec() {
		System.out.println("Terminal.exec");

		if( this.running && !this.paused ) {
			// if both input and output streams aren't null
			if( this.input != null && this.output != null ) {
				int code = -1;
				String s = "";

				synchronized(input) {
					// read a line of input
					s = input.poll();

					// if it's valid, process input and get result
					if( s != null ) {
						writeToScreen(s + "\n");

						code = processInput(s);
					}
				}

				synchronized(output) {
					if( !this.screen_buffer.isEmpty() ) {
						// get a line of output
						s = this.screen_buffer.poll();

						// if it's valid, output it and grab the next line
						while( s != null ) {
							output.add(s);

							s = this.screen_buffer.poll();
						}
					}
				}

				if( code == 0 ) this.paused = true; // this.running = false;
			}
		}
	}

	public String powerOn() {
		// TODO need to rework the logic below and maybe move the screen writes somewhere else
		String report = "no power";

		if( !(this.power_state == Power.NO_POWER) ) {
			if( this.power_state == Power.POWER_OFF ) {
				if( this.usable_state == Use.USABLE ) {
					this.power_state = Power.POWER_ON;

					System.out.println("Terminal On and Usable!");

					//set initial screen data
					writeToScreen( Utils.center( "STABLE-TEC INDUSTRIES UNIFIED OPERATING SYSTEM", 80 ) );
					writeToScreen( Utils.center( "COPYRIGHT 1015-1020 STABLE-TEC INDUSTRIES", 80 ) );
					writeToScreen( "" );

					if( login_state == Login.LOGGED_OUT ) {
						writeToScreen( "User?> " );
						login_state = Login.GET_USER;
					}

					report = "usable";
				}
				else report = "unusable";
			}
			else report = "power on";
		}

		return report;
	}

	public String powerOff() {
		String report = "no power";

		if( !(this.power_state == Power.NO_POWER) ) {
			if( this.power_state == Power.POWER_ON ) {
				if( this.usable_state == Use.USABLE ) {
					this.login_state = Login.LOGGED_OUT;

					writeToScreen("Powering Down...");

					this.power_state = Power.POWER_OFF;

					report = "usable";
				}

				report = "unusable";
			}
			else report = "power off";
		}

		return report;
	}

	/* Terminal Interaction Stuff */

	private int processInput(final String input) {
		/*
		 * -- commands
		 * cd     change current directory
		 * copy   copy a file
		 * delete delete a file
		 * done   stop using the terminal (META)
		 * help   print help information
		 * ls     list files
		 * mkdir  make a new directory
		 * logout logout of the current user
		 * pwd    print working directory
		 * time   show the current time
		 * date?  show the current date
		 * view   print a file out to the console
		 */
		String[] args = input.split(" ");

		String cmd = "";
		String arg = "";

		if( args.length > 1 ) {
			cmd = args[0];
			arg = Utils.join( Arrays.asList(args).subList(1, args.length), " ");
		}
		else cmd = input;

		int code = 1;

		if( login_state == Login.GET_USER ) {
			// store input as user
			ldat.username = input;

			writeToScreen( "Password?> " );

			login_state = Login.GET_PASS;
		}
		else if( login_state == Login.GET_PASS ) {
			// store input as password
			ldat.password = input;

			if( login( ldat.username, ldat.password ) ) {
				writeToScreen("Logged in as \'" + ldat.username + "\'.\n" );
				writeToScreen( "TERM> ");

				login_state = Login.LOGGED_IN;
			}
			else {
				writeToScreen( "" );
				writeToScreen( "No such user." );
				writeToScreen( "" );

				writeToScreen( "User?> " );

				login_state = Login.GET_USER;
			}
		}
		else if( login_state == Login.LOGGED_IN ) {
			if( input_state == "confirm" ) {
				if( input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes") ) {
					doAction(action);
					action = null;
					input_state = "";
				}
				else if( input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no") ) {
					action = null;
					input_state = "";
				}
			}
			else if( cmd.equalsIgnoreCase("cd") ) {
				String new_dir = "";

				if( arg.equals("~") )          new_dir = "/users/" + current_user + "/";
				else if( arg.equals("..") ) {
					int n = current_dir.lastIndexOf('/');

					// path: /users/stormy/stuff
					// cd ..

					if( n!= -1 ) new_dir = current_dir.substring(0, n);
				}
				else if( arg.startsWith("/") ) new_dir = arg;
				else                           new_dir = current_dir + "/" + arg;

				if( fs.hasDir(new_dir) ) {
					current_dir = new_dir;
					writeToScreen( "Changed directory to " + current_dir );
				}
				else writeToScreen( "Invalid Directory." );
			}
			else if ( cmd.equalsIgnoreCase("new") ) {
				// commence edit session?
				// create a new file?
			}
			else if( cmd.equalsIgnoreCase("copy") ) { // ex. copy admin userguide test
				final String[] params = arg.split(",");

				if( params.length == 3 ) {
					fs.copyFile(params[0], params[1], params[2]);
					writeToScreen( "'" + params[1] + "' copied to " + params[2] + " from " + params[0] + "." );
				}
				else {
					writeToScreen("COPY: Error, insufficient parameters.");
				}
			}
			else if( cmd.equalsIgnoreCase("delete") ) {
				String[] params = arg.split(",");

				if( params.length == 2 ) {
					fs.deleteFile(params[0], params[1]);
					writeToScreen( "file deleted ('" + params[1] + "')" );
				}
				else if( params.length == 1) {
					fs.deleteFile(current_dir, params[1]);
					writeToScreen( "'" + params[1] + "' deleted." );
				}
			}
			else if( cmd.equalsIgnoreCase("done") ) {
				return 0;
			}
			else if ( cmd.equalsIgnoreCase("help") ) {
				/*
				 * commands:
				 * cd, copy, delete, done, help, logout, ls, mkdir, pwd, time, view, clear
				 * adduser, deluser, modperm, perms, users
				 */
				//writeToScreen( "Commands" );
				writeToScreen( "" + Colors.YELLOW );
				writeToScreen( "Commands\n" );
				writeToScreen( "" + Colors.WHITE );
				writeToScreen( "\t cd, copy, delete, done, help, logout, ls, mkdir, pwd, time, view\n" );

				if( users.get(current_user).getPerm() == 4 ) {
					writeToScreen( "\t adduser, deluser, modperm, perms, users\n" );
				}
			}
			else if( cmd.equalsIgnoreCase("ls") ) {
				if( !arg.equals("") ) {
					if( arg.equals("-v") ) {
						/*String[] dirs = fs.getDirectoryNames(current_dir).split(" ");
					for(String dirName : dirs) {
						writeToScreen( "D " + dirName);
					}*/
						final File dir = this.fs.getDirectory(current_dir);

						for(final String fileName : dir.getContents()) {
							final File file = this.fs.getFile(current_dir, fileName);

							if( file.isDir ) writeToScreen( "D " + fileName + "\n" );
							else             writeToScreen( "F " + fileName + "\n" );
						}
					}
				}
				else writeToScreen( fs.getDirectoryNames(current_dir) );
			}
			else if ( cmd.equalsIgnoreCase("clear") ) {
				clearScreen();
			}
			else if( cmd.equalsIgnoreCase("mkdir") ) {
				/*boolean newDirCreated = fs.newDir(arg);

				if( newDirCreated ) {
					writeToScreen( "Created new directory: " + arg );
				}*/

				int error = fs.newDir(current_dir + "/" + arg);

				if( error == 0 ) {
					writeToScreen( "Created new directory: " + arg );
				}
				else {
					writeToScreen( "Error!" );
				}
			}
			else if( cmd.equalsIgnoreCase("logout") ) {
				writeToScreen( "Logging out... " );

				login_state = Terminal.Login.LOGGED_OUT;

				writeToScreen( "Logged out." );

				writeToScreen( "\n" );

				writeToScreen( Utils.center( "STABLE-TEC INDUSTRIES UNIFIED OPERATING SYSTEM", 80 ) );
				writeToScreen( Utils.center( "COPYRIGHT 1015-1020 STABLE-TEC INDUSTRIES", 80 ) );
				writeToScreen( "" );

				writeToScreen( "User?> " );

				login_state = Login.GET_USER;
			}
			else if( cmd.equalsIgnoreCase("pwd") ) {
				if( !current_dir.equals("/") ) {
					writeToScreen( current_dir );
				}
				else writeToScreen("/");
			}
			else if( input.equalsIgnoreCase("time") ) {
				writeToScreen( getTime().toString() );
			}
			else if( cmd.equalsIgnoreCase("view") ) {
				if( fs.hasFile(current_dir, arg) ) {
					writeToScreen("Displaying File...");

					final File file = fs.getFile(current_dir, arg);

					for(final String str : file.getContents()) {
						writeToScreen( str );
					}
				}
				else writeToScreen( "No such file." );
			}
			else if( users.get(current_user).getPerm() == 4 ) {
				// ADMIN commands
				if( cmd.equalsIgnoreCase("adduser") ) {
					requestAction("add_user", arg);
					return code;
				}
				else if( cmd.equalsIgnoreCase("deluser") ) {
					if( !arg.contains(" ") ) {
						requestAction("delete_user", arg);
						return code;
					}
				}
				else if( cmd.equalsIgnoreCase("modperm") ) {
					if( !arg.contains(" ") ) {
						requestAction("modify_user_perms", arg);
						return code;
					}
				}
				else if( cmd.equalsIgnoreCase("perms") ) {
					User user = users.get(arg);

					if( user != null ) {
						writeToScreen(user.getName() + " has permissions " + user.getPerm());
					}
					else {
						writeToScreen("No such user!");
					}

					return code;
				}
				else if( cmd.equalsIgnoreCase("users") ) {
					for(final User user : users.values()) {
						writeToScreen(user.getName() + "\n");
					}

					return code;
				}
			}

			writeToScreen( "\n" + getPrompt() );
		}

		return code;
	}

	private void requestAction(final String actionKey, final String actionParams) {
		switch(actionKey) {
		case "add_user":
			String newUser = actionParams.split(" ")[0];
			writeToScreen( String.format("CONFIRM adding user '%s' (yes/no)?", newUser) );
			input_state = "confirm";
			action = new Pair<String>(actionKey, actionParams);
			break;
		case "delete_user":
			writeToScreen("* WARNING: deleting user will destroy all their files, irreversably. *");
			writeToScreen("CONFIRM deleting user 'Stormy' (yes/no)?");
			input_state = "confirm";
			action = new Pair<String>(actionKey, actionParams);
			break;
		case "modify_user_perms":
			writeToScreen("CONFIRM modifying user permissions for Stormy (yes/no)?");
			input_state = "confirm";
			action = new Pair<String>(actionKey, actionParams);
			break;
		}
	}

	private void doAction(final Pair<String> action) {
		switch(action.one) {
		case "add_user":
			final String[] temp = action.two.split(" ");

			if( temp.length == 2 ) {
				if( addUser(temp[0], temp[1]) ) {
					writeToScreen("ADDUSER: Added user '" + temp[0] + "' with password '" + temp[1] + "'.");
				}
				else {
					writeToScreen("ADDUSER: Error, that user already exists!");
				}
			}
			else writeToScreen("ADDUSER: Error, missing parameter.");

			break;
		case "delete_user":
			if( deleteUser(action.two, users.get(action.two).getPassword()) ) {
				writeToScreen("DELUSER: Deleted user '" + action.two + "'.");
			}
			else {
				writeToScreen("DELUSER: Error, no such user!");
			}

			break;
		case "modify_user_perms":
			final String[] temp1 = action.two.split(" ");

			if( temp1.length == 2 ) {
				final User user = users.get(temp1[0]);

				if( user != null ) {
					final Integer oldPerm = user.getPerm();
					final Integer newPerm = Utils.toInt(temp1[0], oldPerm);

					if( newPerm != oldPerm ) {
						user.setPerm( newPerm );
						writeToScreen("MODPERM: Permissions changed to " + user.getPerm() + " for user '" + user.getName() + "'.");
					}
					else {
						writeToScreen("MODPERM: Error, new permissions same as old permissions, no changes made.");
					}
				}
				else {
					writeToScreen("MODPERM: Error, no such user!");
				}
			}
			else writeToScreen("MODPERM: Error, missing parameter.");

			break;
		}
	}

	/**
	 * getTime
	 *
	 * get a brand new time object that holds the current time
	 *
	 * NOTES:
	 * - includes hours, minutes, and seconds
	 * - only holds the exact time when called, does not do any counting or do anything else
	 * - this is the "real world" time not the GAME time.
	 *
	 * @return
	 */
	private Time getTime() {
		// get current data
		Calendar rightNow = Calendar.getInstance();

		// get the hour, minute, and second
		int hour = rightNow.get(Calendar.HOUR);
		int minute = rightNow.get(Calendar.MINUTE);
		int second = rightNow.get(Calendar.SECOND);

		// return a new time object with the current time
		return new Time(hour, minute, second);
	}

	private void writeToScreen(final String line) {
		/*if( screen_buffer.size() < screen_height ) {
			screen_buffer.add(line);
		}
		else {
			screen_buffer.poll();    // toss out an old line?
			screen_buffer.add(line);
		}*/

		this.screen_buffer.add(line);
	}

	private void clearScreen() {
		this.screen_buffer.clear();
	}

	/**
	 * Add a user to the terminal (ADMIN privileges required)
	 * @param username
	 * @param password
	 */
	private boolean addUser(final String username, final String password) {
		return addUser(username, password, 0);
	}

	private boolean addUser(final String username, final String password, final Integer permission) {
		boolean success = false;

		// if such a user does not exist already
		if( !this.users.containsKey(username) ) {
			final User user = new User(username, password, permission);

			// put the username and password in the users table
			this.users.put(username, user);

			// initialize user space
			initUser(username);

			success = true;
		}

		return success;
	}

	private boolean deleteUser(final String username, final String password) {
		boolean success = false;

		if( this.users.containsKey(username) ) {
			if( this.users.get(username).getPassword().equals( password ) ) {
				this.users.remove(username);

				success = true;
			}
		}

		return success;
	}

	private void initUser(final String username) {
		if( this.users.containsKey(username) ) {
			this.fs.newDir("/users/" + username);
			this.fs.write("/users", new String[] { username }, 'a');

			String path = "/users/" + username;

			this.fs.newFile(path + "/" + "user_guide", new String[]{ "Using your new Stable-Tec terminal" });
			this.fs.write(path, new String[] { "user_guide" }, 'a');
		}
	}

	private boolean login(final String user, final String pass) {
		if( this.users.containsKey(user) ) {
			if( this.users.get(user).getPassword().equals( pass ) ) {
				this.login_state = Login.LOGGED_IN;

				this.current_user = user;
				this.current_dir = "/users/" + user;

				return true;
			}
		}

		return false;
	}

	private String getPrompt() {
		String prompt = "";

		// if the terminal is ON and USABLE
		if( checkStatus(Power.POWER_ON, Use.USABLE) ) {
			switch( this.login_state ) {
			case LOGGED_IN: prompt = "TERM> "; break;
			case LOGGED_OUT:
				switch( this.login_state ) {
				case GET_USER: prompt = "User?> "; break;
				case GET_PASS: prompt = "Pass?> "; break;
				default:       prompt = "";        break;
				}
			default:        prompt = "> ";     break;
			}
		}

		return prompt;
	}

	// add to the above 'turn off', 'reset'
	// turn off: power off the terminal
	// reset: reset the terminal

	public boolean checkStatus(final Power state1, final Use state2) {
		return this.power_state == state1 && this.usable_state == state2;
	}

	/* Interfaces - Implemented Methods */

	@Override
	public String getDeviceName() {
		return "Stable-Tec Terminal";
	}

	@Override
	public DeviceType getDeviceType() {
		return DeviceType.TERMINAL;
	}

	@Override
	/**
	 * Write a line to the terminal input.
	 *
	 * @param string
	 */
	public void write(final String string) {
		this.input.add(string);
	}

	@Override
	/**
	 * Read a line of terminal output.
	 *
	 * @return
	 */
	public String read() {
		return output.poll();
	}

	@Override
	public String toString() {
		return getName();
	}
}


text:
/**

 @Name: laydate皮肤:mj
 @Author:mlive@live.cn
 @Site:https://github.com/majunbao

**/

.laydate-icon {
  border: 1px solid #C6C6C6;
  background-image: url(icon.png)
}

.laydate_body .laydate_box,
.laydate_body .laydate_ym,
.laydate_body .laydate_ym .laydate_yms,
.laydate_body .laydate_table,
.laydate_body .laydate_table td,
.laydate_body .laydate_bottom #laydate_hms,
.laydate_body .laydate_time,
.laydate_body .laydate_bottom .laydate_btn a {
  /* border:1px solid #ccc; */
}

.laydate_body .laydate_y .laydate_yms a,
.laydate_body .laydate_choose,
.laydate_body .laydate_table thead,
.laydate_body .laydate_bottom .laydte_hsmtex {
  /* background-color:#F6F6F6; */
}

.laydate_body .laydate_box,
.laydate_body .laydate_ym .laydate_yms,
.laydate_body .laydate_time {
  box-shadow: 2px 2px 5px rgba(0, 0, 0, .1);
}

.laydate_body .laydate_box {
  background-color: #fff;
  color: #333;
  border: 1px solid #E3E3E3;
  margin-top: 2px;
}

.laydate_body .laydate_box input {
  color: #333;
}

.laydate_body .laydate_box a,
.laydate_body .laydate_box a:hover {
  color: #333;
}

.laydate_body .laydate_box a:hover {
  color: #666;
}

.laydate_body .laydate_click {
  background-color: #00AAFC !important;
  color: #fff !important;
}

.laydate_body .laydate_top {
  /*border-top:1px solid #C6C6C6;*/
}

.laydate_body .laydate_ym .laydate_yms {
  border: 1px solid #C6C6C6;
  background-color: #fff;
}

.laydate_body .laydate_y .laydate_yms a {
  border-bottom: 1px solid #C6C6C6;
}

.laydate_body .laydate_y .laydate_yms .laydate_chdown {
  border-top: 1px solid #C6C6C6;
  border-bottom: none;
}

.laydate_body .laydate_choose {
  /* border-left:1px solid #C6C6C6; */
}

.laydate_body .laydate_chprev {
  border-left: none;
  /* border-right:1px solid #C6C6C6; */
}

.laydate_body .laydate_choose:hover,
.laydate_body .laydate_y .laydate_yms a:hover {
  background-color: #fff;
}

.laydate_body .laydate_chtop cite {
  border-bottom-color: #666;
}

.laydate_body .laydate_chdown cite,
.laydate_body .laydate_ym label {
  border-top-color: #666;
}

.laydate_body .laydate_chprev cite {
  border-right-style: solid;
  border-right-color: #666;
}

.laydate_body .laydate_chnext cite {
  border-left-style: solid;
  border-left-color: #666;
}

.laydate_body .laydate_table td {
  border: none;
  height: 21px!important;
  line-height: 21px!important;
  /*background-color: #F5F5F5;*/
  color: #333;
}

.laydate_body .laydate_table .laydate_nothis {
  color: #999;
  background-color: #fff;
}
.laydate_body .laydate_box .laydate_void {
  color: #eee!important;
  /*text-decoration:line-through;*/
}

.laydate_body .laydate_box .laydate_void:hover {
  background-color: #fff!important

}
.laydate_body .laydate_table thead {
  height: 21px!important;
  line-height: 21px!important;
}

.laydate_body .laydate_table thead th {
  /*border-bottom:1px solid #ccc;*/
}

.laydate_body .laydate_bottom {
  /* border-bottom:1px solid #C6C6C6; */
}

.laydate_body .laydate_bottom #laydate_hms {
  background-color: #fff;
}

.laydate_body .laydate_time {
  background-color: #fff;
}

.laydate_body .laydate_bottom .laydate_sj {
  border-right: 1px solid #C6C6C6;
  background-color: #F6F6F6;
}

.laydate_body .laydate_bottom input {
  background-color: #fff;
}

.laydate_body .laydate_bottom .laydte_hsmtex {
  border-bottom: 1px solid #C6C6C6;
}

.laydate_body .laydate_bottom .laydate_btn {
  /* border-right:1px solid #C6C6C6; */
}

.laydate_body .laydate_bottom .laydate_v {
  color: #999
}

.laydate_body .laydate_bottom .laydate_btn a {
  border-right: none;
  background-color: #F6F6F6;
}

.laydate_body .laydate_bottom .laydate_btn a:hover {
  color: #000;
  background-color: #fff;
}

.laydate_body .laydate_m .laydate_yms span:hover,
.laydate_body .laydate_y .laydate_yms ul li:hover,
.laydate_body .laydate_table td:hover,
.laydate_body .laydate_time .laydate_hmsno span:hover {
  background-color: #F3F3F3
}

redpajama_set_name: RedPajamaGithub


text:
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/** @class FIRAuthCredential
    @brief Represents a credential.
 */
NS_SWIFT_NAME(AuthCredential)
@interface FIRAuthCredential : NSObject

/** @property provider
    @brief Gets the name of the identity provider for the credential.
 */
@property(nonatomic, copy, readonly) NSString *provider;

/** @fn init
    @brief This is an abstract base class. Concrete instances should be created via factory
        methods available in the various authentication provider libraries (like the Facebook
        provider or the Google provider libraries.)
 */
- (instancetype)init NS_UNAVAILABLE;

// Only used for testing.
- (instancetype)initWithProvider:(NSString *)provider NS_DESIGNATED_INITIALIZER;

@end

NS_ASSUME_NONNULL_END


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

<title>Using as: MIPS NaN Encodings</title>

<meta name="description" content="Using as: MIPS NaN Encodings">
<meta name="keywords" content="Using as: MIPS NaN Encodings">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="MIPS_002dDependent.html#MIPS_002dDependent" rel="up" title="MIPS-Dependent">
<link href="MIPS-Option-Stack.html#MIPS-Option-Stack" rel="next" title="MIPS Option Stack">
<link href="MIPS-insn.html#MIPS-insn" rel="prev" title="MIPS insn">

Next: MIPS Option Stack, Previous: MIPS insn, Up: MIPS-Dependent   [Contents][Index]

9.27.9 Directives to record which NaN encoding is being used

The IEEE 754 floating-point standard defines two types of not-a-number
(NaN) data: “signalling” NaNs and “quiet” NaNs.  The original version
of the standard did not specify how these two types should be
distinguished.  Most implementations followed the i387 model, in which
the first bit of the significand is set for quiet NaNs and clear for
signalling NaNs.  However, the original MIPS implementation assigned the
opposite meaning to the bit, so that it was set for signalling NaNs and
clear for quiet NaNs.

The 2008 revision of the standard formally suggested the i387 choice
and as from Sep 2012 the current release of the MIPS architecture
therefore optionally supports that form.  Code that uses one NaN encoding
would usually be incompatible with code that uses the other NaN encoding,
so MIPS ELF objects have a flag (EF_MIPS_NAN2008) to record which
encoding is being used.

Assembly files can use the .nan directive to select between the
two encodings.  ‘<samp>.nan 2008</samp>’ says that the assembly file uses the
IEEE 754-2008 encoding while ‘<samp>.nan legacy</samp>’ says that the file uses
the original MIPS encoding.  If several .nan directives are given,
the final setting is the one that is used.

The command-line options <samp>-mnan=legacy</samp> and <samp>-mnan=2008</samp>
can be used instead of ‘<samp>.nan legacy</samp>’ and ‘<samp>.nan 2008</samp>’
respectively.  However, any .nan directive overrides the
command-line setting.

‘<samp>.nan legacy</samp>’ is the default if no .nan directive or
<samp>-mnan</samp> option is given.

Note that GNU as does not produce NaNs itself and
therefore these directives do not affect code generation.  They simply
control the setting of the EF_MIPS_NAN2008 flag.

Traditional MIPS assemblers do not support these directives.

Next: MIPS Option Stack, Previous: MIPS insn, Up: MIPS-Dependent   [Contents][Index]


text:
import schema

def soft_schema(**kwargs):
    """
        soft_schema(k1=schema1, k2=schema2, ...)

    Returns a schema for dicts having the keys k1, k2, ... and possibly other
    string keys not explicitly stated. The schema for the values is the one
    provided (i.e. schema for k2 is Schema(schema2)). Other keys have
    Schema(object).

    If one of the inner schemas given is a dict, it's interpreted as a soft
    dictionary schema too.
    """

    def _transform(d):
        result = d.copy()
        for k, v in result.items():
            if isinstance(v, dict):
                result[k] = _transform(v)
        result[schema.Optional(str)] = object
        return result

    return schema.Schema(_transform(kwargs))

class Feature(object):
    """
    Feature instances represent a single feature. This class is never
    instantiated as is; you build an instance using make_feature on a
    decorated function, or you define a subclass and instantiate that.

    The instance has a callable interface, taking a data point and
    returning a feature value. The typical use case is overriding the
    `_evaluate` method and leaving the standard `__call__` in place
    (which wraps `_evaluate` adding input and output validation)

    Besides the `__call__` methods, the following class attributes are
    available:

     * `input_schema` is a `schema.Schema` object for validating
       inputs. This can be overriden in subclasses or as an instance
       attribute
     * `output_schema` is a `schema.Schema` object for validating
       output. This can be overriden in subclasses or as an instance
       attribute
     * `InputValueError` is an exception class raised when input fails
       to validate; it is a subclass of `ValueError`
     * `OutputValueError` is an exception class raised when output
       fails to validate; it is a subclass of `ValueError`
    """

    input_schema = schema.Schema(object)
    output_schema = schema.Schema(object)

    class InputValueError(ValueError):
        pass

    class OutputValueError(ValueError):
        pass

    @property
    def name(self):
        """A human readable name to be used in reports and error messages"""
        return getattr(self, "_name", type(self).__name__)

    def __call__(self, data_point):
        """Validate intput, evaluate, and validate result"""
        try:
            data_point = self.input_schema.validate(data_point)
        except schema.SchemaError as e:
            raise self.InputValueError(e)
        result = self._evaluate(data_point)
        try:
            return self.output_schema.validate(result)
        except schema.SchemaError as e:
            raise self.OutputValueError(e)

    def _evaluate(self, data_point):
        """Override this to provide your own evaluation function"""
        raise NotImplemented

# Extensions for schema of other objects
class ObjectSchema(schema.Schema):
    """
    ObjectSchema(attr1=schema1, attr2=schema2, ...) is a schema.Schema-like
    class providing validation for the fields of a python object. To validate,
    the object must have attr1, attr2, ... as attributes, and each attribute
    must validate with the corresponding schema.

    Note that schema1, schema2, ... do not need to be a schema, they can be any
    valid value useful for building is schema (i.e., you can use `int` instead
    of `schema.Schema(int)`

    """

    def __init__(self, **kwargs):
        self.attrs = kwargs

    def __repr__(self):
        attributes = ("%s=%s" % (n, repr(s)) for (n, s) in sorted(self.attrs.items()))
        return '%s(%s)' % (type(self).__name__, ', '.join(attributes))

    def validate(self, data):
        """
        Check that data has all the attributes specified, and validate each
        attribute with the schema provided on construction
        """
        for a, s in self.attrs.items():
            s = schema.Schema(s)
            try:
                value = getattr(data, a)
            except AttributeError:
                raise schema.SchemaError(" Missing attribute %r" % a, [])
            try:
                new_value = s.validate(value)
            except schema.SchemaError as e:
                raise schema.SchemaError(
                    "Invalid value for attribute %r: %s" % (a, e), [])
            setattr(data, a, new_value)
        return data

# Simple API
def make_feature(f):
    """
    Given a function f: data point -> feature that computes a feature, upgrade
    it to a feature instance.
    Returns f if f is already a Feature instance
    """
    if not callable(f):
        raise TypeError("f must be callable")
    if isinstance(f, Feature):
        return f
    result = Feature()
    result._evaluate = f
    result._name = getattr(f, "_feature_name", f.__name__)
    input_schema = getattr(f, "_input_schema", None)
    output_schema = getattr(f, "_output_schema", None)
    if input_schema is not None:
        result.input_schema = input_schema
    if output_schema is not None:
        result.output_schema = output_schema
    return result

def _build_schema(*args, **kwargs):
    # Helper to build schema form the arguments of input_schema & output_schema
    args = list(args)
    for i, a in enumerate(args):
        # Dictionaries are "softened"
        if isinstance(a, dict):
            args[i] = soft_schema(**a)
    if kwargs:
        for k, a in kwargs.items():
            if isinstance(a, dict):
                args[k] = soft_schema(**a)
        # if there are kwargs, add an objectschema to the condition
        args.append(ObjectSchema(**kwargs))
    return schema.Schema(schema.And(*args))

def input_schema(*args, **kwargs):
    """
    @input_schema(s1, s2, ..., attr1=as1, attr2=as2, ...)
    def f(data_point): ...

    Annotate the schema for validating the data_point that f receives.

    s1, s2, ... are anything that allows building a schema, and are considered
    as conditions to "and" with each other (i.e., to validate, all s1, s2, ...
    must validate). If keyword arguments are specified, the keyword names must
    be attributes of the data points, and the value of each of those attributes
    is validated with the corresponding schema (i.e., as1 is used to validate
    data_point.attr1, etc.)

    If any of the schemas used is a dictionary, the semantics of that schema
    is modified to allow additional keys besides the ones specified explicitly
    """
    def decorate(f):
        f._input_schema = _build_schema(*args, **kwargs)
        return f
    return decorate

def output_schema(*args, **kwargs):
    """
    @output_schema(s1, s2, ..., attr1=as1, attr2=as2, ...)
    def f(data_point): ...

    Annotate the schema for validating the result of f.

    s1, s2, ... are anything that allows building a schema, and are considered
    as conditions to "and" with each other (i.e., to validate, all s1, s2, ...
    must validate). If keyword arguments are specified, the keyword names must
    be attributes of the result, and the value of each of those attributes
    is validated with the corresponding schema (i.e., as1 is used to validate
    f(data_point).attr1, etc.)

    If any of the schemas used is a dictionary, the semantics of that schema
    is modified to allow additional keys besides the ones specified explicitly
    """
    def decorate(f):
        f._output_schema = _build_schema(*args, **kwargs)
        return f
    return decorate

def feature_name(name):
    """
    @feature_name("name")
    def f(...): ...

    Annotate the name to be used when describing f as a feature. The default
    name when this decorator is used is the function name itself, but you can
    define any custom string here if you want to disambiguate or be more
    specific. The name provided will be used in some reports and error
    messages.
    """
    def decorate(f):
        f._feature_name = name
        return f
    return decorate


text:
<!--

    Licensed to Jasig under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Jasig licenses this file to you 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.

-->

<Context path="/ContentManagementPortlet" debug="5"
				reloadable="true" crossContext="true">

	<WatchedResource>WEB-INF/web.xml</WatchedResource>

	<!--
		Configure a content repository at the specified path and home directory.
		This is set according to JackRabbit Deployment Model 1.

		See:
		http://jackrabbit.apache.org/deployment-models.html

	-->

	<Resource name="jcr/repository"
	          auth="Container"
	          type="javax.jcr.Repository"
	          factory="org.apache.jackrabbit.core.jndi.BindableRepositoryFactory"
	          configFilePath="${jcr.repository.config.file}"
	          repHomeDir="${jcr.repository.path}">
	</Resource>

</Context>


text:
from magma import *
from loam.boards.icestick import IceStick, Counter
import os
if os.path.exists('pipeline.py'):
    from pipeline import Pipeline
else:
    from modules import Pipeline

icestick = IceStick()
icestick.Clock.on()
icestick.D1.on()
icestick.D2.on()
icestick.D3.on()
icestick.D4.on()
icestick.D5.on()

main = icestick.main()

# decrease the frequency to avoid timing violation
counter = Counter(4)
pipeline = Pipeline()
wire(counter.O[-1], pipeline.CLK)
wire(pipeline.O[:4], bits([main.D1, main.D2, main.D3, main.D4]))
# light 5 indicates the end of prediction
wire(pipeline.D, main.D5)

EndCircuit()


text:
/**
 * This product currently only contains code developed by authors
 * of specific components, as identified by the source code files.
 *
 * Since product implements StAX API, it has dependencies to StAX API
 * classes.
 *
 * For additional credits (generally to people who reported problems)
 * see CREDITS file.
 */
package org.knowm.datasets.cifar10;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Cifar database file containing entries that can represent image or label data. Extends the standard random access file with methods for navigating
 * over the entries. The file format is basically idx with specific header information. This includes a magic number for determining the type of
 * stored entries, count of entries.
 */
public abstract class CifarDbFile extends RandomAccessFile {

  private final int count = 10000; // number of images in each Cifar data file

  /**
   * Creates new instance and reads the header information.
   *
   * @param name the system-dependent filename
   * @param mode the access mode
   * @throws IOException
   * @throws FileNotFoundException
   * @see RandomAccessFile
   */
  public CifarDbFile(String name, String mode) throws IOException, FileNotFoundException {

    super(name, mode);
    // count = readInt();
  }

  public abstract int getHeaderSize();

  /**
   * Number of bytes for each entry.
   *
   * @return int
   */
  public abstract int getEntryLength();

  /**
   * The current entry index.
   *
   * @return long
   * @throws IOException
   */
  public long getCurrentIndex() throws IOException {

    return (getFilePointer() - getHeaderSize()) / getEntryLength() + 1;
  }

  /**
   * Set the required current entry index.
   *
   * @param curr the entry index
   */
  public void setCurrentIndex(long curr) {

    try {
      if (curr < 0 || curr > count) {
        throw new RuntimeException(curr + " is not in the range 0 to " + count);
      }
      seek((curr - 1) * getEntryLength());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Move to the next entry.
   *
   * @throws IOException
   */
  public void next() throws IOException {

    if (getCurrentIndex() < count) {
      skipBytes(getEntryLength());
    }
  }

  /**
   * Move to the previous entry.
   *
   * @throws IOException
   */
  public void prev() throws IOException {

    if (getCurrentIndex() > 0) {
      seek(getFilePointer() - getEntryLength());
    }
  }

  public int getCount() {

    return count;
  }
}


text:
.. ALF documentation master file, created by
   sphinx-quickstart on Wed Jan 18 13:21:53 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

############################
ALF developer documentation
############################

.. topic:: Abstract

   This module provides an API for software developers, testers, and security
   researchers to implement a plugin for fuzzing with ALF. This API is intended to
   provide a rich set of capabilities for template mutation and fault detection,
   allowing the user to interface their project to the ALF distributed fuzzing
   cloud quickly and easily.

Contents
========

.. toctree::
   :maxdepth: 4

   api.rst
   alf.rst
   alf.debug.rst
   alf.fuzz.rst


text:
REBUILD="false"
FILENAME=""

while getopts ":f:b" opt; do
  case $opt in
    f)
      FILENAME="$OPTARG"
    ;;
    b)
      REBUILD="true"
    ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

DT_COLLECTOR_LOG_PATH_ON_HOST=${DT_COLLECTOR_LOG_PATH_ON_HOST:-"/tmp/log/dynatrace/collectors/dtcollector"}

mkdir -p ${DT_COLLECTOR_LOG_PATH_ON_HOST}

OWNER=$(stat -c '%U' ${DT_COLLECTOR_LOG_PATH_ON_HOST})
if [ "${OWNER}" != "${USER}" ] ; then
    echo "Directory has invalid ownership set to '${OWNER}', change it to current user or remove it: ${DT_COLLECTOR_LOG_PATH_ON_HOST}" >&2
    echo "Aborting..." >&2
    exit 1
fi

PARAMS=""
if [ ! -z "$FILENAME" ] ; then
    PARAMS="$PARAMS -f $FILENAME"
fi
PARAMS="$PARAMS up -d"
if [ "$REBUILD" = "true" ] ; then
    PARAMS="$PARAMS --build"
fi

docker-compose ${PARAMS}


text:
html{
  height: 100%;
}

body{
  display: none;
  background-image: url('../img/greyscale-network.png');
  background-repeat: no-repeat;
  -webkit-background-size:cover;
  -moz-background-size:cover;
  -o-background-size:cover;
  background-size:cover;
  background-position:center;
  height: 100%;
  margin: 0px;
}

.container{
  max-height: 100%;
  top: 33%;
}

.login{
  background: rgba(255,255,255,0.7);
  box-shadow: 0px 0px 16px rgba(255,255,255,0.5);
  display: inline-block;
  border: 1px solid #E1E1E1;
  border-radius: 4px;
  padding: 10px;
}

.github-logo{
  height: 100px;
  width: 100px;
  display: block;
  margin: 0 auto;
}

.github-auth{
  border: 1px solid #888;
  display: inline-block;
  margin-top: 10px;
  -webkit-transition: background 0.4s linear;
  -moz-transition: background 0.4s linear;
  -ms-transition: background 0.4s linear;
  -o-transition: background 0.4s linear;
  transition: background 0.4s linear;
}

.github-auth:hover{
  background-color: rgba(225, 225, 225, 0.9);
}


text:
/**
 * Helps IE run the fake XDomainRequest. By defining global functions, IE allows
 * them to be overwritten at a later point. If these are not defined like
 * this, overwriting them will result in anything from an exception to browser
 * crash.
 *
 * If you don't require fake XDR to work in IE, don't include this file.
 */
function XDomainRequest() {}

// Reassign the original function. Now its writable attribute
// should be true. Hackish, I know, but it works.
XDomainRequest = sinon.xdr.XDomainRequest || undefined;


text:
package ch.raffael.contracts.processor.cel.ast;

import java.util.Collections;
import java.util.List;

import com.google.common.base.Objects;

import ch.raffael.contracts.NotNull;
import ch.raffael.contracts.processor.cel.Position;

/**
 * @author Raffael Herzog
 */
public class Finally extends AstNode {

    private final AstNode expression;

    public Finally(Position position, AstNode expression) {
        super(position);
        this.expression = expression;
    }

    public AstNode getExpression() {
        return expression;
    }

    @NotNull
    @Override
    protected List<AstNode> children() {
        return Collections.singletonList(expression);
    }

    @Override
    protected void doAccept(AstVisitor visitor) {
        visitor.visit(this);
    }

    @Override
    public int hashCode() {
        return 31 * super.hashCode() + Objects.hashCode(expression);
    }

    @Override
    public boolean equals(Object obj) {
        if ( this == obj ) {
            return true;
        }
        if ( obj == null || getClass() != obj.getClass() ) {
            return false;
        }
        if ( !super.equals(obj) ) {
            return false;
        }
        final Finally other = (Finally)obj;
        return Objects.equal(this.expression, other.expression);
    }

    @Override
    protected void toString(Objects.ToStringHelper toString) {
        toString.addValue(expression);
    }
}


text:
module Calculations
  module V3
    module Steps
      module SelectAssociationSanctioned
        def self.calculate!(calculator)
          calculator.unrejected_source_results.each do |source_result|
            if calculator.rules.association.nil?
              raise ArgumentError, "Rules#association sanctioned_by must be present"
            end

            if calculator.rules.association_sanctioned_only? && calculator.rules.association != source_result.event.sanctioned_by
              source_result.reject :sanctioned_by
            end
          end

          calculator.event_categories
        end
      end
    end
  end
end


text:
<?php

namespace App\Validation\Rules\SubdivisionCode;

use App\Validation\Rules\AbstractSearcher;

/**
 * Validator for Syria subdivision code.
 *
 * ISO 3166-1 alpha-2: SY
 *
 * @link http://www.geonames.org/SY/administrative-division-syria.html
 */
class SySubdivisionCode extends AbstractSearcher
{
    public $haystack = [
        'DI', // Dimashq
        'DR', // Dara
        'DY', // Dayr az Zawr
        'HA', // Al Hasakah
        'HI', // Hims
        'HL', // Halab
        'HM', // Hamah
        'ID', // Idlib
        'LA', // Al Ladhiqiyah
        'QU', // Al Qunaytirah
        'RA', // Ar Raqqah
        'RD', // Rif Dimashq
        'SU', // As Suwayda
        'TA', // Tartus
    ];

    public $compareIdentical = true;
}


text:
package cs.ualberta.octoaskt12;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkChecker extends CreateQuestionActivity {
	private Context context;

	// checks for the availability of the network connection
	// returns a boolean

	public NetworkChecker(Context context) {
		this.context = context.getApplicationContext();
	}

	public Boolean isAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();

		if (ni == null)
			return false;
		else {
			return true;
		}
	}
}


text:
require "test_helper"

describe Restfolia do

  it ".url" do
    ep = Restfolia.at("http://fakeurl.com")
    ep.must_be_instance_of(Restfolia::EntryPoint)
  end

end


text:
<base-page>

[[i18n('criticalErrorTitleText')]]

      <iron-icon icon="shimless-icon:warning" class="warning-icon small-icon">
      </iron-icon>

[[i18n('criticalErrorMessageText')]]

[[statusString_]]

      <cr-button id="rebootButton" class="action-button"
          on-click="onRebootButtonClicked_" disabled="[[allButtonsDisabled]]">
        [[i18n('criticalErrorRebootText')]]
      </cr-button>
      <cr-button id="exitToLoginButton"
          on-click="onExitToLoginButtonClicked_"
          disabled="[[allButtonsDisabled]]">
        [[i18n('criticalErrorExitText')]]
      </cr-button>

</base-page>


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | If the response is successful or not | [optional]
**data** | [**SubRole**](SubRole.md) |  | [optional]
**additionalData** | [**GetRoleAllOfAdditionalData**](GetRoleAllOfAdditionalData.md) |  | [optional]


text:
//*****************************************************************************
// Luke Hsiao
// 29 April 2015
// Interface for button driver
//*****************************************************************************

#ifndef BUTTONS_H_
#define BUTTONS_H_

#include <stdint.h>
#include <stdlib.h>

// Status Values
#define BUTTONS_INIT_STATUS_OK 1
#define BUTTONS_INIT_STATUS_FAIL 0
#define BUTTONS_SET 1
#define BUTTONS_NOT_SET 0

// Values for working with GPIO Tristate
#define BUTTONS_VALUE_OFFSET 0
#define BUTTONS_TRISTATE_OFFSET 4
#define BUTTONS_TRISTATE_SET_AS_INPUT 0xF

// Button Mask Values
#define BUTTONS_BTN0_MASK       0x1
#define BUTTONS_BTN1_MASK       0x2
#define BUTTONS_BTN2_MASK       0x4
#define BUTTONS_BTN3_MASK       0x8
#define BUTTONS_ALL_BTNS_ON     0xF
#define BUTTONS_BOTTOM_4_BITS   0xF

#define BUTTONS_TEXT_SIZE 2 // Set text size to 2

// Initializes the button driver software and hardware.
// Returns one of the defined status values:
//    - BUTTONS_INIT_STATUS_OK
//    - BUTTONS_INIT_STATUS_FAIL
int buttons_init();

// Returns the current value of all 4 buttons as the lower 4 bits of the
// returned value.
// bit3 = BTN3, bit2 = BTN2, bit1 = BTN1, bit0 = BTN0.
int32_t buttons_read();

// Runs a test of the buttons.
// As you push the buttons, graphics and messages will be written to the LCD
// panel. The test will until all 4 pushbuttons are simultaneously pressed.
void buttons_runTest();

#endif /* BUTTONS_H_ */


text:
'''

 ====================================================================
 Copyright (c) 2018 Barry A Scott.  All rights reserved.

 This software is licensed as described in the file LICENSE.txt,
 which you should have received as part of this distribution.

 ====================================================================

    wb_p4_preferences.py

'''
import wb_dialog_bases

def getAllPreferenceTabs( app ):
    return [P4PreferencesTab( app )]

def setupPreferences( scheme_nodes ):
    pass

class P4PreferencesTab(wb_dialog_bases.WbTabBase):
    def __init__( self, app ):
        super().__init__( app, T_('P4') )

        self.addRow( T_('P4 Program'), T_('Using built-in p4python client') )

    def savePreferences( self ):
        pass


text:
namespace web_app {

class ExternallyManagedAppManagerImplBrowserTest : public InProcessBrowserTest {
 protected:
  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();
    // Allow different origins to be handled by the embedded_test_server.
    host_resolver()->AddRule("*", "127.0.0.1");
    os_hooks_suppress_ =
        OsIntegrationManager::ScopedSuppressOsHooksForTesting();
    web_app::test::WaitUntilReady(
        web_app::WebAppProvider::GetForTest(profile()));
  }

  Profile* profile() { return browser()->profile(); }

  WebAppRegistrar& registrar() {
    return WebAppProvider::GetForTest(profile())->registrar();
  }

  ExternallyManagedAppManager& externally_managed_app_manager() {
    return WebAppProvider::GetForTest(profile())
        ->externally_managed_app_manager();
  }

  void InstallApp(ExternalInstallOptions install_options) {
    result_code_ =
        ExternallyManagedAppManagerInstall(profile(), install_options);
  }

  void CheckServiceWorkerStatus(const GURL& url,
                                content::ServiceWorkerCapability status) {
    base::RunLoop run_loop;
    std::unique_ptr<content::WebContents> web_contents =
        content::WebContents::Create(
            content::WebContents::CreateParams(profile()));
    content::ServiceWorkerContext* service_worker_context =
        web_contents->GetBrowserContext()
            ->GetStoragePartition(web_contents->GetSiteInstance())
            ->GetServiceWorkerContext();
    service_worker_context->CheckHasServiceWorker(
        url, blink::StorageKey(url::Origin::Create(url)),
        base::BindLambdaForTesting(
            [&run_loop, status](content::ServiceWorkerCapability capability) {
              CHECK_EQ(status, capability);
              run_loop.Quit();
            }));
    run_loop.Run();
  }

  absl::optional<InstallResultCode> result_code_;

 private:
  ScopedOsHooksSuppress os_hooks_suppress_;
};

// Basic integration test to make sure the whole flow works. Each step in the
// flow is unit tested separately.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       InstallSucceeds) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url(embedded_test_server()->GetURL("/banners/manifest_test_page.html"));
  InstallApp(CreateInstallOptions(url));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  absl::optional<AppId> app_id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs()).LookupAppId(url);
  EXPECT_TRUE(app_id.has_value());
  EXPECT_EQ("Manifest test app", registrar().GetAppShortName(app_id.value()));
}

// If install URL redirects, install should still succeed.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       InstallSucceedsWithRedirect) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL start_url =
      embedded_test_server()->GetURL("/banners/manifest_test_page.html");
  GURL install_url =
      embedded_test_server()->GetURL("/server-redirect?" + start_url.spec());
  InstallApp(CreateInstallOptions(install_url));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  absl::optional<AppId> app_id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs())
          .LookupAppId(install_url);
  EXPECT_TRUE(app_id.has_value());
  EXPECT_EQ("Manifest test app", registrar().GetAppShortName(app_id.value()));
  // Same AppID should be in the registrar using start_url from the manifest.
  EXPECT_TRUE(registrar().IsLocallyInstalled(start_url));
  absl::optional<AppId> opt_app_id =
      registrar().FindAppWithUrlInScope(start_url);
  EXPECT_TRUE(opt_app_id.has_value());
  EXPECT_EQ(*opt_app_id, app_id);
}

// If install URL redirects, install should still succeed.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       InstallSucceedsWithRedirectNoManifest) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL final_url =
      embedded_test_server()->GetURL("/banners/no_manifest_test_page.html");
  GURL install_url =
      embedded_test_server()->GetURL("/server-redirect?" + final_url.spec());
  InstallApp(CreateInstallOptions(install_url));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  absl::optional<AppId> app_id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs())
          .LookupAppId(install_url);
  EXPECT_TRUE(app_id.has_value());
  EXPECT_EQ("Web app banner test page",
            registrar().GetAppShortName(app_id.value()));
  // Same AppID should be in the registrar using install_url.
  EXPECT_TRUE(registrar().IsLocallyInstalled(install_url));
  absl::optional<AppId> opt_app_id =
      registrar().FindAppWithUrlInScope(install_url);
  ASSERT_TRUE(opt_app_id.has_value());
  EXPECT_EQ(*opt_app_id, app_id);
  EXPECT_EQ(registrar().GetAppStartUrl(*opt_app_id), install_url);
}

// Installing a placeholder app with shortcuts should succeed.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       PlaceholderInstallSucceedsWithShortcuts) {
  ASSERT_TRUE(embedded_test_server()->Start());

  GURL final_url = embedded_test_server()->GetURL(
      "other.origin.com", "/banners/manifest_test_page.html");
  // Add a redirect to a different origin, so a placeholder is installed.
  GURL url(
      embedded_test_server()->GetURL("/server-redirect?" + final_url.spec()));

  ExternalInstallOptions options = CreateInstallOptions(url);
  options.install_placeholder = true;
  options.add_to_applications_menu = true;
  options.add_to_desktop = true;
  InstallApp(options);

  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  absl::optional<AppId> app_id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs()).LookupAppId(url);
  ASSERT_TRUE(app_id.has_value());
  EXPECT_TRUE(registrar().IsPlaceholderApp(app_id.value()));
}

// Installing a placeholder app with shortcuts should succeed.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       PlaceholderInstallSucceedsWithCustomName) {
  ASSERT_TRUE(embedded_test_server()->Start());

  GURL final_url = embedded_test_server()->GetURL(
      "other.origin.com", "/banners/manifest_test_page.html");
  // Add a redirect to a different origin, so a placeholder is installed.
  GURL url(
      embedded_test_server()->GetURL("/server-redirect?" + final_url.spec()));
  const std::string CUSTOM_NAME = "CUSTOM_NAME";

  ExternalInstallOptions options = CreateInstallOptions(url);
  options.install_placeholder = true;
  options.add_to_applications_menu = true;
  options.add_to_desktop = true;
  options.placeholder_name = CUSTOM_NAME;
  InstallApp(options);

  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  absl::optional<AppId> app_id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs()).LookupAppId(url);
  ASSERT_TRUE(app_id.has_value());
  EXPECT_TRUE(registrar().IsPlaceholderApp(app_id.value()));
  EXPECT_EQ(CUSTOM_NAME, registrar().GetAppById(app_id.value())->name());
}

// Tests that the browser doesn't crash if it gets shutdown with a pending
// installation.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       ShutdownWithPendingInstallation) {
  ASSERT_TRUE(embedded_test_server()->Start());

  ExternalInstallOptions install_options = CreateInstallOptions(
      embedded_test_server()->GetURL("/banners/manifest_test_page.html"));

  // Start an installation but don't wait for it to finish.
  WebAppProvider::GetForTest(profile())
      ->externally_managed_app_manager()
      .Install(std::move(install_options), base::DoNothing());

  // The browser should shutdown cleanly even if there is a pending
  // installation.
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       BypassServiceWorkerCheck) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url(embedded_test_server()->GetURL(
      "/banners/manifest_no_service_worker.html"));

  ExternalInstallOptions install_options = CreateInstallOptions(url);
  install_options.bypass_service_worker_check = true;
  InstallApp(std::move(install_options));
  absl::optional<AppId> app_id = registrar().FindAppWithUrlInScope(url);
  EXPECT_TRUE(app_id.has_value());
  EXPECT_TRUE(registrar().GetAppScopeInternal(*app_id).has_value());
  EXPECT_EQ("Manifest test app", registrar().GetAppShortName(*app_id));
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       PerformServiceWorkerCheck) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url(embedded_test_server()->GetURL(
      "/banners/manifest_no_service_worker.html"));
  ExternalInstallOptions install_options = CreateInstallOptions(url);
  InstallApp(std::move(install_options));
  absl::optional<AppId> app_id = registrar().FindAppWithUrlInScope(url);
  EXPECT_TRUE(app_id.has_value());
  EXPECT_TRUE(registrar().GetAppScopeInternal(app_id.value()).has_value());
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       ForceReinstall) {
  ASSERT_TRUE(embedded_test_server()->Start());
  absl::optional<AppId> app_id;
  {
    GURL url(embedded_test_server()->GetURL(
        "/banners/"
        "manifest_test_page.html?manifest=manifest_short_name_only.json"));
    ExternalInstallOptions install_options = CreateInstallOptions(url);
    install_options.force_reinstall = true;
    InstallApp(std::move(install_options));

    app_id = registrar().FindAppWithUrlInScope(url);
    EXPECT_TRUE(app_id.has_value());
    EXPECT_EQ("Manifest", registrar().GetAppShortName(app_id.value()));
  }
  {
    GURL url(
        embedded_test_server()->GetURL("/banners/manifest_test_page.html"));
    ExternalInstallOptions install_options = CreateInstallOptions(url);
    install_options.force_reinstall = true;
    InstallApp(std::move(install_options));

    absl::optional<AppId> new_app_id = registrar().FindAppWithUrlInScope(url);
    EXPECT_TRUE(new_app_id.has_value());
    EXPECT_EQ(new_app_id, app_id);
    EXPECT_EQ("Manifest test app",
              registrar().GetAppShortName(new_app_id.value()));
  }
}

// Test that adding a manifest that points to a chrome:// URL does not actually
// install a web app that points to a chrome:// URL.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       InstallChromeURLFails) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url(embedded_test_server()->GetURL(
      "/banners/manifest_test_page.html?manifest=manifest_chrome_url.json"));
  InstallApp(CreateInstallOptions(url));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  absl::optional<AppId> app_id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs()).LookupAppId(url);
  ASSERT_TRUE(app_id.has_value());

  // The installer falls back to installing a web app of the original URL.
  EXPECT_EQ(url, registrar().GetAppStartUrl(app_id.value()));
  EXPECT_NE(app_id,
            registrar().FindAppWithUrlInScope(GURL("chrome://settings")));
}

// Test that adding a web app without a manifest while using the
// |require_manifest| flag fails.
IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       RequireManifestFailsIfNoManifest) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url(
      embedded_test_server()->GetURL("/banners/no_manifest_test_page.html"));
  ExternalInstallOptions install_options = CreateInstallOptions(url);
  install_options.require_manifest = true;
  InstallApp(std::move(install_options));

  EXPECT_EQ(InstallResultCode::kNotValidManifestForWebApp,
            result_code_.value());
  absl::optional<AppId> id =
      ExternallyInstalledWebAppPrefs(profile()->GetPrefs()).LookupAppId(url);
  ASSERT_FALSE(id.has_value());
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       RegistrationSucceeds) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Delay service worker registration to second load to simulate it not loading
  // during the initial install pass.
  GURL install_url(embedded_test_server()->GetURL(
      "/web_apps/service_worker_on_second_load.html"));

  ExternalInstallOptions install_options = CreateInstallOptions(install_url);
  install_options.bypass_service_worker_check = true;
  InstallApp(std::move(install_options));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  WebAppRegistrationWaiter(&externally_managed_app_manager())
      .AwaitNextRegistration(install_url, RegistrationResultCode::kSuccess);
  CheckServiceWorkerStatus(
      install_url,
      content::ServiceWorkerCapability::SERVICE_WORKER_WITH_FETCH_HANDLER);
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       RegistrationAlternateUrlSucceeds) {
  ASSERT_TRUE(embedded_test_server()->Start());

  GURL install_url(
      embedded_test_server()->GetURL("/web_apps/no_service_worker.html"));
  GURL registration_url =
      embedded_test_server()->GetURL("/web_apps/basic.html");

  ExternalInstallOptions install_options = CreateInstallOptions(install_url);
  install_options.bypass_service_worker_check = true;
  install_options.service_worker_registration_url = registration_url;
  InstallApp(std::move(install_options));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  WebAppRegistrationWaiter(&externally_managed_app_manager())
      .AwaitNextRegistration(registration_url,
                             RegistrationResultCode::kSuccess);
  CheckServiceWorkerStatus(
      install_url,
      content::ServiceWorkerCapability::SERVICE_WORKER_WITH_FETCH_HANDLER);
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       RegistrationSkipped) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Delay service worker registration to second load to simulate it not loading
  // during the initial install pass.
  GURL install_url(embedded_test_server()->GetURL(
      "/web_apps/service_worker_on_second_load.html"));

  ExternalInstallOptions install_options = CreateInstallOptions(install_url);
  install_options.bypass_service_worker_check = true;
  install_options.load_and_await_service_worker_registration = false;
  WebAppRegistrationWaiter waiter(&externally_managed_app_manager());
  InstallApp(std::move(install_options));
  waiter.AwaitRegistrationsComplete();

  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  CheckServiceWorkerStatus(install_url,
                           content::ServiceWorkerCapability::NO_SERVICE_WORKER);
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       AlreadyRegistered) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Ensure service worker registered for http://embedded_test_server/web_apps/.
  // We don't need to be installing a web app here but it's convenient just to
  // await the service worker registration.
  {
    GURL install_url(embedded_test_server()->GetURL("/web_apps/basic.html"));
    ExternalInstallOptions install_options = CreateInstallOptions(install_url);
    install_options.force_reinstall = true;
    InstallApp(std::move(install_options));
    EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
    WebAppRegistrationWaiter(&externally_managed_app_manager())
        .AwaitNextNonFailedRegistration(install_url);
    CheckServiceWorkerStatus(
        embedded_test_server()->GetURL("/web_apps/basic.html"),
        content::ServiceWorkerCapability::SERVICE_WORKER_WITH_FETCH_HANDLER);
  }

  // With the service worker registered we install a page that doesn't register
  // a service worker to check that the existing service worker is seen by our
  // service worker registration step.
  {
    GURL install_url(
        embedded_test_server()->GetURL("/web_apps/no_service_worker.html"));
    ExternalInstallOptions install_options = CreateInstallOptions(install_url);
    install_options.force_reinstall = true;
    install_options.bypass_service_worker_check = true;
    InstallApp(std::move(install_options));
    EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
    WebAppRegistrationWaiter(&externally_managed_app_manager())
        .AwaitNextRegistration(install_url,
                               RegistrationResultCode::kAlreadyRegistered);
  }
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       CannotFetchManifest) {
  // With a flaky network connection, clients may request an app whose manifest
  // cannot currently be retrieved. The app display mode is then assumed to be
  // 'browser'.
  ASSERT_TRUE(embedded_test_server()->Start());
  const GURL app_url(embedded_test_server()->GetURL(
      "/banners/manifest_test_page.html?manifest=does_not_exist.json"));

  std::vector<ExternalInstallOptions> desired_apps_install_options;
  {
    ExternalInstallOptions install_options(
        app_url, DisplayMode::kStandalone,
        ExternalInstallSource::kExternalPolicy);
    install_options.add_to_applications_menu = false;
    install_options.add_to_desktop = false;
    install_options.add_to_quick_launch_bar = false;
    install_options.require_manifest = false;
    desired_apps_install_options.push_back(std::move(install_options));
  }

  base::RunLoop run_loop;
  externally_managed_app_manager().SynchronizeInstalledApps(
      std::move(desired_apps_install_options),
      ExternalInstallSource::kExternalPolicy,
      base::BindLambdaForTesting(
          [&run_loop, &app_url](
              std::map<GURL, ExternallyManagedAppManager::InstallResult>
                  install_results,
              std::map<GURL, bool> uninstall_results) {
            EXPECT_TRUE(uninstall_results.empty());
            EXPECT_EQ(install_results.size(), 1U);
            EXPECT_EQ(install_results[app_url].code,
                      InstallResultCode::kSuccessNewInstall);
            run_loop.Quit();
          }));
  run_loop.Run();

  absl::optional<AppId> app_id = registrar().FindAppWithUrlInScope(app_url);
  DCHECK(app_id.has_value());
  EXPECT_EQ(registrar().GetAppDisplayMode(*app_id), DisplayMode::kBrowser);
  EXPECT_EQ(registrar().GetAppUserDisplayMode(*app_id),
            DisplayMode::kStandalone);
  EXPECT_EQ(registrar().GetAppEffectiveDisplayMode(*app_id),
            DisplayMode::kMinimalUi);
  EXPECT_FALSE(registrar().GetAppThemeColor(*app_id).has_value());
}

IN_PROC_BROWSER_TEST_F(ExternallyManagedAppManagerImplBrowserTest,
                       RegistrationTimeout) {
  ASSERT_TRUE(embedded_test_server()->Start());
  ExternallyManagedAppRegistrationTask::SetTimeoutForTesting(0);
  GURL url(embedded_test_server()->GetURL(
      "/banners/manifest_no_service_worker.html"));
  CheckServiceWorkerStatus(url,
                           content::ServiceWorkerCapability::NO_SERVICE_WORKER);

  ExternalInstallOptions install_options = CreateInstallOptions(url);
  install_options.bypass_service_worker_check = true;
  InstallApp(std::move(install_options));
  EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result_code_.value());
  WebAppRegistrationWaiter(&externally_managed_app_manager())
      .AwaitNextRegistration(url, RegistrationResultCode::kTimeout);
}

}  // namespace web_app


text:
package org.apache.flink.runtime.rest.messages.job.savepoints;

import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.util.Preconditions;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Response to the triggering of a savepoint.
 */
public class SavepointTriggerResponseBody implements ResponseBody {

	private static final String FIELD_NAME_STATUS = "status";

	private static final String FIELD_NAME_LOCATION = "location";

	private static final String FIELD_NAME_REQUEST_ID = "request-id";

	@JsonProperty(FIELD_NAME_STATUS)
	public final String status;

	@JsonProperty(FIELD_NAME_LOCATION)
	public final String location;

	@JsonProperty(FIELD_NAME_REQUEST_ID)
	public final String requestId;

	@JsonCreator
	public SavepointTriggerResponseBody(
			@JsonProperty(FIELD_NAME_STATUS) String status,
			@JsonProperty(FIELD_NAME_LOCATION) String location,
			@JsonProperty(FIELD_NAME_REQUEST_ID) String requestId) {
		this.status = status;
		this.location = Preconditions.checkNotNull(location);
		this.requestId = requestId;
	}

	@Override
	public int hashCode() {
		return 79 * location.hashCode();
	}

	@Override
	public boolean equals(Object object) {
		if (object instanceof SavepointTriggerResponseBody) {
			SavepointTriggerResponseBody other = (SavepointTriggerResponseBody) object;
			return this.location.equals(other.location);
		}
		return false;
	}
}


text:
CSAPEX_REGISTER_CLASS(csapex::WaldBoostTrainer, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

WaldBoostTrainer::WaldBoostTrainer()
{
}

void WaldBoostTrainer::setup(NodeModifier& modifier)
{
    CollectionNode<connection_types::FeaturesMessage>::setup(modifier);
}

void WaldBoostTrainer::setupParameters(Parameterizable& parameters)
{
    CollectionNode<connection_types::FeaturesMessage>::setupParameters(parameters);
    parameters.addParameter(param::factory::declareFileOutputPath("/waldboost/path", param::ParameterDescription("File to write boosted classifier to."), "", "*.yaml *.tar.gz"), path_);
    parameters.addParameter(param::factory::declareRange("/waldboost/classifier_count", 1, 4096, 100, 1), weak_count_);
}

bool WaldBoostTrainer::processCollection(std::vector<FeaturesMessage>& collection)
{
    std::size_t step = collection.front().value.size();
    std::map<int, std::vector<std::size_t>> indices;

    const std::size_t size = collection.size();
    for (std::size_t i = 0; i < size; ++i) {
        const FeaturesMessage& fm = collection[i];
        if (fm.value.size() != step)
            throw std::runtime_error("All descriptors must have the same length!");
        if (fm.classification != 1 && fm.classification != -1)
            throw std::runtime_error("Only class labels supported are '-1' and '1'!");
        indices[fm.classification].push_back(i);
    }

    const std::vector<std::size_t>& positive_indices = indices[1];
    const std::vector<std::size_t>& negative_indices = indices[-1];

    const std::size_t positive_size = positive_indices.size();
    const std::size_t negative_size = negative_indices.size();

    cv::Mat positive_samples(positive_size, step, CV_32FC1, cv::Scalar());
    cv::Mat negative_samples(negative_size, step, CV_32FC1, cv::Scalar());

    for (std::size_t i = 0; i < positive_size; ++i) {
        const std::vector<float>& sample = collection[positive_indices[i]].value;
        for (std::size_t j = 0; j < step; ++j) {
            positive_samples.at<float>(i, j) = sample[j];
        }
    }

    for (std::size_t i = 0; i < negative_size; ++i) {
        const std::vector<float>& sample = collection[negative_indices[i]].value;
        for (std::size_t j = 0; j < step; ++j) {
            negative_samples.at<float>(i, j) = sample[j];
        }
    }

    cv::transpose(positive_samples, positive_samples);
    cv::transpose(negative_samples, negative_samples);

    cv::WaldBoost wb;
    wb.reset(weak_count_);
    std::cout << "[WaldBoost]: Started training with " << collection.size() << " samples!" << std::endl;
    wb.train(positive_samples, negative_samples);
    wb.save(path_);
    std::cout << "[WaldBoost]: Finished training!" << std::endl;

    return true;
}


text:
/*phpjs - https://github.com/kvz/phpjs

   Apparently some of us can't remember if we are programming
   in Javascript or PHP:)  This file will allow us to have some of
   the php functions available when needed.  To reduce bloat,
   each phpjs function must be manually added to this file as
   deemed necessary.

   HTML usage before the code that needs it!
    <!-- Some PHP to Javascript converted functions -->
    <script src="js/phpjs.js"></script>

*/

function isset() {
  //https://github.com/kvz/phpjs/blob/master/functions/var/isset.js
  //  discuss at: http://phpjs.org/functions/isset/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: FremyCompany
  // improved by: Onno Marsman
  // improved by: Rafal Kukawski
  //   example 1: isset( undefined, true);
  //   returns 1: false
  //   example 2: isset( 'Kevin van Zonneveld' );
  //   returns 2: true

  var a = arguments,
    l = a.length,
    i = 0,
    undef;

  if (l === 0) {
    throw new Error('Empty isset');
  }

  while (i !== l) {
    if (a[i] === undef || a[i] === null) {
      return false;
    }
    i++;
  }
  return true;
}//end isset


text:
1 - Raspberry Pi 3 - Model B - ARMv8 with 1G RAM with Raspbian operating system in a 8GB SD card
1 - USB WiFi (802.11b/g/n) Module with Antenna for Raspberry Pi
1 - MCP3008 - 8-Channel 10-Bit ADC With SPI Interface
1 - Perma-Proto HAT for Pi  with GPIO header
1 - AH3761 High sensitivity hall effect lacth
1 - Mini DC/DC Step-Down (Buck) Converter - 5V @ 1A output - TSR12450
7 - 10k resistors
2 - 1k resistors
1 - red led
1 - green led
1 - 12 pin header
4 - header jumpers
4 - pair of screw in terminal blocks
1 - Deep cycle Battery with at least 10AH 12v
1 - Pelycan box with capacity to hold the datalogger and battery

![alt tag](https://github.com/UCHIC/WaterMonitor/blob/master/doc/images/MCP3008__to_RPI.png)
![alt tag](https://github.com/UCHIC/WaterMonitor/blob/master/doc/images/AGGIEWATER_PORTS.png)


text:
namespace ProjectType
{
    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using Microsoft.VisualStudio.Shell;

    /// <summary>
    /// This class implements the package exposed by this assembly.
    /// </summary>
    /// <remarks>
    /// This package is required if you want to define adds custom commands (ctmenu)
    /// or localized resources for the strings that appear in the New Project and Open Project dialogs.
    /// Creating project extensions or project types does not actually require a VSPackage.
    /// </remarks>
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [Description("A custom project type based on CPS")]
    [Guid(VsPackage.PackageGuid)]
    public sealed class VsPackage : Package
    {
        /// <summary>
        /// The GUID for this package.
        /// </summary>
        public const string PackageGuid = "13250a5c-fd10-402e-8245-42fcbda817d0";

        /// <summary>
        /// The GUID for this project type.  It is unique with the project file extension and
        /// appears under the VS registry hive's Projects key.
        /// </summary>
        public const string ProjectTypeGuid = "ebf4485d-77a0-4075-b805-e3a3b705cdf6";

        /// <summary>
        /// The file extension of this project type.  No preceding period.
        /// </summary>
        public const string ProjectExtension = "mccproj";

        /// <summary>
        /// The default namespace this project compiles with, so that manifest
        /// resource names can be calculated for embedded resources.
        /// </summary>
        internal const string DefaultNamespace = "ProjectType";
    }
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.CSharp.Completion.Providers
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery

Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
    <ExportCompletionProvider(NameOf(PreprocessorCompletionProvider), LanguageNames.VisualBasic)>
    <ExtensionOrder(After:=NameOf(SymbolCompletionProvider))>
    <[Shared]>
    Friend Class PreprocessorCompletionProvider
        Inherits AbstractPreprocessorCompletionProvider

        <ImportingConstructor>
        <Obsolete(MefConstruction.ImportingConstructorMessage, True)>
        Public Sub New()
        End Sub

        Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
            Return IsDefaultTriggerCharacterOrParen(text, characterPosition, options)
        End Function

        Friend Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CommonTriggerCharsAndParen

        Protected Overrides Async Function CreateContextAsync(Workspace As Workspace, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext)
            Return Await VisualBasicSyntaxContext.CreateContextAsync(Workspace, semanticModel, position, cancellationToken).ConfigureAwait(False)
        End Function
    End Class
End Namespace


text:
using System;
using System.Windows.Forms;

namespace BizHawk.Client.EmuHawk
{
	public class SmartTextBoxControl : TextBox
	{
		public SmartTextBoxControl()
		{
			ReadOnly = true;
		}
		protected override void OnKeyDown(KeyEventArgs e)
		{
			base.Text = e.KeyCode.ToString();
			OnTextChanged(new EventArgs());
		}

		protected override void OnKeyPress(KeyPressEventArgs e)
		{

		}

		protected override void OnKeyUp(KeyEventArgs e)
		{
		}

		public override string Text
		{
			get { return base.Text; }
			set { }
		}

	}
}


text:
namespace ManagedBass.DirectX8
{
    /// <summary>
    /// DX8 Compressor Effect (Windows only).
    /// </summary>
    public sealed class DXCompressorEffect : Effect<DXCompressorParameters>
    {
        /// <summary>
        /// Output gain of signal in dB after compression, in the range from -60 to 60. The default value is 0 dB.
        /// </summary>
        public double Gain
        {
            get => Parameters.fGain;
            set
            {
                Parameters.fGain = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Time in ms before compression reaches its full value, in the range from 0.01 to 500. The default value is 10 ms.
        /// </summary>
        public double Attack
        {
            get => Parameters.fAttack;
            set
            {
                Parameters.fAttack = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Time (speed) in ms at which compression is stopped after input drops below <see cref="Threshold"/>, in the range from 50 to 3000. The default value is 200 ms.
        /// </summary>
        public double Release
        {
            get => Parameters.fRelease;
            set
            {
                Parameters.fRelease = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Point at which compression begins, in dB, in the range from -60 to 0. The default value is -20 dB.
        /// </summary>
        public double Threshold
        {
            get => Parameters.fThreshold;
            set
            {
                Parameters.fThreshold = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Compression ratio, in the range from 1 to 100. The default value is 3, which means 3:1 compression.
        /// </summary>
        public double Ratio
        {
            get => Parameters.fRatio;
            set
            {
                Parameters.fRatio = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Time in ms after <see cref="Threshold"/> is reached before attack phase is started, in milliseconds, in the range from 0 to 4. The default value is 4 ms.
        /// </summary>
        public double Predelay
        {
            get => Parameters.fPredelay;
            set
            {
                Parameters.fPredelay = (float)value;

                OnPropertyChanged();
            }
        }
    }
}


text:
import matplotlib.pyplot as plt
import librosa
import numpy as np
import subprocess

from krotos.magnatagatune import Dataset

d = Dataset()
batch = d.human_examine(10)

for s, tags, mp3_path in batch:
    p = subprocess.Popen(['vlc', mp3_path])

    plt.clf()
    librosa.display.specshow(s, hop_length=1024, x_axis='mel', y_axis='time')
    plt.colorbar(format='%1.3f')

    plt.title(', '.join(tags) or 'No tags')

    plt.show()

    p.kill()


text:
Package.describe({
    summary: "Simple quick filter"
});

Package.on_use(function(api, where) {
    api.use(['underscore', 'simple-schema', 'collection2', 'publish-counts', 'subs-manager', 'meteor',
        'standard-app-packages'
    ], ['client', 'server']);

    api.add_files('lib/quick-filter-server.js', 'server');
    api.add_files('lib/quick-filter-client.js', 'client');
});


text:
'use strict';

// Flags: --expose-internals

require('../common');
const stream = require('stream');
const REPL = require('internal/repl');
const assert = require('assert');
const inspect = require('util').inspect;

const tests = [
  {
    env: {},
    expected: { terminal: true, useColors: true }
  },
  {
    env: { NODE_DISABLE_COLORS: '1' },
    expected: { terminal: true, useColors: false }
  },
  {
    env: { NODE_NO_READLINE: '1' },
    expected: { terminal: false, useColors: false }
  },
  {
    env: { TERM: 'dumb' },
    expected: { terminal: true, useColors: false }
  },
  {
    env: { NODE_NO_READLINE: '1', NODE_DISABLE_COLORS: '1' },
    expected: { terminal: false, useColors: false }
  },
  {
    env: { NODE_NO_READLINE: '0' },
    expected: { terminal: true, useColors: true }
  }
];

function run(test) {
  const env = test.env;
  const expected = test.expected;

  const opts = {
    terminal: true,
    input: new stream.Readable({ read() {} }),
    output: new stream.Writable({ write() {} })
  };

  Object.assign(process.env, env);

  REPL.createInternalRepl(process.env, opts, function(err, repl) {
    assert.ifError(err);

    assert.strictEqual(repl.terminal, expected.terminal,
                       `Expected ${inspect(expected)} with ${inspect(env)}`);
    assert.strictEqual(repl.useColors, expected.useColors,
                       `Expected ${inspect(expected)} with ${inspect(env)}`);
    for (const key of Object.keys(env)) {
      delete process.env[key];
    }
    repl.close();
  });
}

tests.forEach(run);


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Tests\Aggregation\Stage;

use Doctrine\ODM\MongoDB\Aggregation\Stage\Sort;
use Doctrine\ODM\MongoDB\Tests\Aggregation\AggregationTestTrait;
use Doctrine\ODM\MongoDB\Tests\BaseTest;

class SortTest extends BaseTest
{
    use AggregationTestTrait;

    /**
     * @dataProvider provideSortOptions
     */
    public function testSortStage($expectedSort, $field, $order = null)
    {
        $sortStage = new Sort($this->getTestAggregationBuilder(), $field, $order);

        $this->assertSame(['$sort' => $expectedSort], $sortStage->getExpression());
    }

    /**
     * @dataProvider provideSortOptions
     */
    public function testSortFromBuilder($expectedSort, $field, $order = null)
    {
        $builder = $this->getTestAggregationBuilder();
        $builder->sort($field, $order);

        $this->assertSame([['$sort' => $expectedSort]], $builder->getPipeline());
    }

    public static function provideSortOptions()
    {
        return [
            'singleFieldSeparated' => [
                ['field' => -1],
                'field',
                'desc',
            ],
            'singleFieldCombined' => [
                ['field' => -1],
                ['field' => 'desc'],
            ],
            'multipleFields' => [
                ['field' => -1, 'otherField' => 1],
                ['field' => 'desc', 'otherField' => 'asc'],
            ],
            'sortMeta' => [
                ['field' => ['$meta' => 'textScore'], 'invalidField' => -1],
                ['field' => 'textScore', 'invalidField' => 'nonExistingMetaField'],
            ],
        ];
    }
}


text:
using kmlxsd::XsdElementVector;
using kmlxsd::XsdFile;
using std::cerr;
using std::cout;
using std::endl;
using std::vector;

int main(int argc, char** argv) {
  if (argc != 2) {
    cerr << "usage: " << argv[0] << " file.xsd" << endl;
    return 1;
  }

  const char* xsd_pathname = argv[1];

  std::string xsd_data;
  if (!kmlbase::File::ReadFileToString(xsd_pathname, &xsd_data)) {
    cerr << "read failed " << xsd_pathname << endl;
    return 1;
  }

  std::string errors;
  boost::scoped_ptr<XsdFile> xsd_file(
      XsdFile::CreateFromParse(xsd_data, &errors));
  if (!xsd_file.get()) {
    cerr << "parse failed " << errors;
    return 1;
  }

  kmlxsd::XsdTypeVector types;
  xsd_file->GetAllTypes(&types);
  for (size_t i = 0; i < types.size(); ++i) {
    cout << types[i]->get_name() << endl;
  }

  return 0;
}


text:
<!DOCTYPE html>

 If you are registered, Please Loin.

 If you are new, please register yourself First.

Login

Register


text:
import unittest

import httpretty

from u2fval_client.client import (
    Client,
)
from u2fval_client.exc import (
    BadAuthException,
    BadInputException,
    ServerUnreachableException,
    InvalidResponseException,
    U2fValClientException,
)

@httpretty.activate
class TestClient(unittest.TestCase):
    def setUp(self):
        self.client = Client('https://example')

    def test_endpoint_sanitised(self):
        self.assertEqual('https://example/', self.client._endpoint)

    def test_get_trusted_facets(self):
        httpretty.register_uri('GET', 'https://example/',
                               body='{}')
        self.assertEqual(self.client.get_trusted_facets(), {})

    def test_get_trusted_facets_empty_response_body(self):
        httpretty.register_uri('GET', 'https://example/',
                               body='')
        self.assertRaises(InvalidResponseException,
                          self.client.get_trusted_facets)

    def test_get_trusted_facets_error_code(self):
        httpretty.register_uri('GET', 'https://example/',
                               body='{"errorCode": 10}',
                               status=400)
        self.assertRaises(BadInputException, self.client.get_trusted_facets)

    def test_get_trusted_facets_unauthorized(self):
        httpretty.register_uri('GET', 'https://example/', status=401)
        self.assertRaises(BadAuthException, self.client.get_trusted_facets)

    def test_get_trusted_facets_not_found(self):
        httpretty.register_uri('GET', 'https://example/', status=404)
        self.assertRaises(U2fValClientException, self.client.get_trusted_facets)

    def test_get_trusted_facets_internal_server_error(self):
        httpretty.register_uri('GET', 'https://example/', status=500)
        self.assertRaises(U2fValClientException, self.client.get_trusted_facets)

    def test_get_trusted_facets_server_unreachable(self):
        # Intentionally has no httpretty mock registered
        self.assertRaises(ServerUnreachableException,
                          self.client.get_trusted_facets)

    def test_list_devices(self):
        httpretty.register_uri('GET', 'https://example/black_knight/',
                               body='{}')
        self.assertEqual(self.client.list_devices('black_knight'), {})

    def test_register_begin(self):
        httpretty.register_uri('GET', 'https://example/black_knight/register',
                               body='{}')
        self.assertEqual(self.client.register_begin('black_knight'), {})

    def test_register_complete(self):
        httpretty.register_uri('POST', 'https://example/black_knight/register',
                               body='{}')
        self.assertEqual(self.client.register_complete('black_knight', '{}'),
                         {})
        req = httpretty.last_request()
        self.assertEqual(req.parsed_body, {'registerResponse': {}})

    def test_unregister(self):
        httpretty.register_uri('DELETE', 'https://example/black_knight/abc123',
                               body='', status=204)
        self.assertIsNone(self.client.unregister('black_knight', 'abc123'))

    def test_auth_begin(self):
        httpretty.register_uri('GET', 'https://example/black_knight/sign',
                               body='{}')
        self.assertEqual(self.client.auth_begin('black_knight'), {})

    def test_auth_complete(self):
        httpretty.register_uri('POST', 'https://example/black_knight/sign',
                               body='{}')
        self.assertEqual(self.client.auth_complete('black_knight', '{}'), {})
        req = httpretty.last_request()
        self.assertEqual(req.parsed_body, {'signResponse': {}})


text:
{% extends "mdpage/root.html" %}
{% block title %}
    {% block mdpage_title %}(untitled){% endblock mdpage_title %}
{% endblock title %}
{% block extra_head %}{{ block.super }}
    {% block mdpage_extra_head %}{% endblock mdpage_extra_head %}
{% endblock extra_head %}
{% block main_content %}
    {% block mdpage_navbar %}

        {% if mdp_type.description %}
        {{ mdp_type.description }}
        {% endif %}

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                {% if user.is_authenticated %}

                    New

                {% endif %}

            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-primary my-2 my-sm-0" type="submit">Go</button>
            </form>

    {% endblock mdpage_navbar %}
    {% block mdpage_messages %}
    {% if messages %}
    {% for message in messages %}

{{ message }}

    {% endfor %}
    {% endif %}
    {% endblock mdpage_messages %}
    {% block mdpage_content %}{% endblock mdpage_content%}
    {% block mdpage_extra_body %}{% endblock mdpage_extra_body %}
{% endblock %}


text:
+++
title = "Note on Feb 3 EDT 2017 at 12:47"
publishdate = 2017-02-03T17:47:23+00:00
draft = false
syndicated = [ 'https://twitter.com/chrisjohndeluca/status/827574217432502300?s=20' ]
+++

RT @GeorgeTakei: Trump was quick to condemn the Louvre attack. But he stayed pretty quiet over the mosque shooting in Montreal. That speaks…


text:
//
// このファイルは、JavaTM Architecture for XML Binding(JAXB) Reference Implementation、v2.2.8-b130911.1802によって生成されました
// http://java.sun.com/xml/jaxbを参照してください
// ソース・スキーマの再コンパイル時にこのファイルの変更は失われます。
// 生成日: 2015.08.24 時間 02:38:24 AM JST
//

package com.eitax.recall.rest.ebay.shopping.xsd;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 * 				The Timestamp field indicates the official eBay system time in GMT.
 * 				The value returned represents the date and time when eBay processed the request.
 * 				The value is in the ISO 8601 date-time format (YYYY-MM-DDTHH:MM:SS.SSSZ).
 *
 *
 *
GeteBayTimeResponseType complex typeのJavaクラス。
 *
 *
次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
 *
 *

 * <complexType name="GeteBayTimeResponseType">
 *   <complexContent>
 *     <extension base="{urn:ebay:apis:eBLBaseComponents}AbstractResponseType">
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GeteBayTimeResponseType")
public class GeteBayTimeResponseType
    extends AbstractResponseType
{

}