text:
package edu.mayo.ve.resources;

import com.google.gson.Gson;
import com.mongodb.*;
import edu.mayo.query.QueryCursorInterface;
import edu.mayo.query.QueryFactory;
import edu.mayo.security.CWEUtils;
import edu.mayo.util.Tokens;
import edu.mayo.ve.message.DisplayedFilterVariants;
import edu.mayo.ve.message.QuerryDownload;
import edu.mayo.util.MongoConnection;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: m102417
 * Date: 10/7/13
 * Time: 4:16 PM
 * To change this template use File | Settings | File Templates.
 */

@Path("/download/")
public class DownloadFile {
    MetaData meta = new MetaData();
    Mongo m = MongoConnection.getMongo();
    Gson gson = new Gson();

    @Context
    private javax.servlet.http.HttpServletResponse response;

    @POST
    @Produces("text/plain")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public StreamingOutput generateFile(final @FormParam("json") String json) throws Exception {
        QuerryDownload q = null;
        try {
            q = unmarshall(json);
            if(q == null) throw new Exception();
        } catch (Exception e){
            return failedInputMessage(json);
        }

        // set name of file, causes browser to always do "Save as..." dialog
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s.tsv\"", CWEUtils.neutralizeCRLF(getFileName(q.getWorkspace()))));

        final QuerryDownload finalQ = q;
        return new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try {
                    writeHeader(output, finalQ);
                    writeData(output,finalQ);
                    //output.write(json.getBytes());
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
    }

    private String getFileName(String workspace){
        DBObject db = meta.queryMeta(Tokens.KEY, workspace);
        String out = (String) db.get("alias");
        if(out == null){
            out = workspace;
        }
        if(out.length() <= 1){
            out = workspace;
        }
        return out;
    }

    public QuerryDownload unmarshall(String json){
        QuerryDownload q = gson.fromJson(json, QuerryDownload.class);
        return q;
    }

    public StreamingOutput failedInputMessage(final String json){
        return new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try {
                    output.write("The following json is not something the download interface understands: ".getBytes());
                    output.write(json.getBytes());
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
    }

    private void writeHeader(OutputStream output, final QuerryDownload q) throws IOException, WebApplicationException{
        // write the filters applied
        if(q.getDisplayFiltersApplied() != null && q.getDisplayFiltersApplied().size() > 0){
            output.write("##Filter\t#Variants\n".getBytes());
            for(DisplayedFilterVariants f : q.getDisplayFiltersApplied()){
                output.write("##".getBytes());
                output.write(f.getFilterText().getBytes());
                output.write("\t".getBytes());
                output.write(
                        new Integer(f.getNumberVariantsRemaining()).toString().getBytes()
                );
                output.write("\n".getBytes());
            }
        }

        // write the traditional header, describing each data row
        List<String> outFields = q.getDisplayFields();
        if(outFields.size() < q.getReturnFields().size()){
            outFields = q.getReturnFields();
        }
        output.write("#".getBytes());
        int i = 0;
        for(String header : outFields){
            output.write(header.getBytes());
            i++;
            if(i== q.getReturnFields().size()){
                output.write("\n".getBytes());
            }else{
                output.write("\t".getBytes());
            }
        }
    }

    private void writeData(OutputStream output, final QuerryDownload q) throws IOException, WebApplicationException, InterruptedException {
        int i = 0;
        DB db = MongoConnection.getDB();
        DBCollection col = db.getCollection(q.getWorkspace());
        //DBObject query = q.createQuery();
        //System.out.println(q.getCustomReturnSelect().toString());
        //DBCursor documents = col.find(query, q.getCustomReturnSelect());
        QueryFactory qfact = new QueryFactory();
        QueryCursorInterface documents = qfact.makeCursor(col,q);
        for( i = 0; documents.hasNext(); i++){
            DBObject next = documents.next();
            int j=0;
            for(String field : q.getReturnFields()){
                output.write(format(field, next).getBytes());
                j++;
                if(j== q.getReturnFields().size()){
                    output.write("\n".getBytes());
                }else{
                    output.write("\t".getBytes());
                }
            }
        }
    }

    public String format(String key, DBObject dbo){
        //System.out.println(key);
        //System.out.println(dbo.toString());
        //?? String newkey = key.replaceAll("\\.", "_");
        if(key.contains(".")){
            int start = key.indexOf(".");
            String prefix = key.substring(0,start); // usually INFO or FORMAT
            String suffix = key.substring(start+1); // sub-field under INFO or FORMAT

            if (dbo.containsField(prefix)) {
                return format(suffix, (DBObject) dbo.get(prefix));
            } else {
                // value is absent in ResultSet, fetch the proper formatting for NULL
                return formatPrimative(null);
            }
        }
        Object o = dbo.get(key);
        return formatPrimative(o);

    }

    public String formatPrimative(Object o){
        if(o == null){
            return ".";
        }
        if(o instanceof Boolean){
            Boolean value = (Boolean) o;
            return value.toString();
        }
        //System.out.println(o.getClass().toString());
        if(o instanceof String){
            String value = (String) o;
            return value;
        }
        if(o instanceof Integer){
            Integer value = (Integer) o;
            return value.toString();
        }
        if(o instanceof Double){
            Double value = (Double) o;
            return value.toString();
        }
        if(o instanceof BasicDBList){
            BasicDBList values = (BasicDBList) o;
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for(String s : values.keySet()){
                Object val = values.get(s);
                sb.append(formatPrimative(val));
                i++;
                if(i< values.keySet().size()){
                    sb.append(";");
                }
            }
            //System.out.println(sb.toString());
            return sb.toString();
        }
        if(o instanceof BasicDBObject){
            BasicDBObject value = (BasicDBObject) o;
            return o.toString();
        }
        return ".";
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }
}


text:
import { AttributeSelectorUpgradeData, VersionChanges } from '@angular/cdk/schematics';

export const attributeSelectors: VersionChanges<AttributeSelectorUpgradeData> = {};

redpajama_set_name: RedPajamaGithub


text:
package org.apache.webbeans.test.component.service;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;

import org.apache.webbeans.test.annotation.binding.Binding1;
import org.apache.webbeans.test.annotation.binding.Binding2;

@SessionScoped
public class TypedInjection implements Serializable
{
    @Inject @Binding1 @Binding2 ITyped2<String, Object> v = null;

    public ITyped2<String, Object> getV()
    {
        return v;
    }

}


text:
require "rails_helper"

describe RetentionSchedules::AddScheduleService do
  let(:user) { find_or_create :branston_user }

  let(:closed_offender_sar_complaint) {
    create(
      :offender_sar_complaint,
      :closed,
      :with_retention_schedule
    )
  }

  let(:other_related_complaints) {
    with_rs_cases = 3.times.map do
      create(
        :offender_sar_complaint,
        :closed,
        :with_retention_schedule,
        original_case: closed_offender_sar_complaint.original_case
      )
    end

    without_rs_cases = 2.times.map do
      create(
        :offender_sar_complaint,
        :closed,
        original_case: closed_offender_sar_complaint.original_case
      )
    end

    with_rs_cases + without_rs_cases
  }

  let(:other_related_open_complaints) {
    2.times.map do
      create(
        :offender_sar_complaint,
        :to_be_assessed,
        original_case: closed_offender_sar_complaint.original_case
      )
    end
  }

  let(:closed_offender_sar) {
    create(
      :offender_sar_case,
      :closed
    )
  }

  let(:closed_offender_sar_with_retention_schedule) {
    create(
      :offender_sar_case,
      :closed,
      :with_retention_schedule
    )
  }

  let(:mock_case) {
    instance_double(
      Case::SAR::Standard,
      offender_sar?: false,
      offender_sar_complaint?: false,
      last_transitioned_at: Date.today,
      closed?: true
    )
  }

  let(:mock_open_case) {
    instance_double(
      Case::SAR::Offender,
      offender_sar?: true,
      offender_sar_complaint?: false,
      last_transitioned_at: Date.today,
      closed?: false
    )
  }

  let(:expected_off_sar_erasure_date) {
    # defined as these in Settings.retention_timings.off_sars
    # and then referenced in service class
    (4.business_days.ago + 8.years + 6.months).to_date
  }

  before do
    # set up reverse links for original case
    original_case = closed_offender_sar_complaint.original_case
    original_case.linked_cases =
      [closed_offender_sar_complaint] +
      other_related_complaints +
      other_related_open_complaints
    original_case.save
  end

  describe 'what types of case service can act upon' do
    it 'cannot change cases other than offender sar or complaints' do
      service = described_class.new(
        kase: mock_case, user: user
      )

      service.call
      expect(service.result).to be(:invalid_case_type)
    end

    it 'cannot add retention schedules to open cases' do
      service = described_class.new(
        kase: mock_open_case, user: user
      )
      service.call

      expect(service.result).to be(:invalid_as_case_is_open)
      expect(service).not_to receive(:add_retention_schedule)
      expect(service).not_to receive(:add_retention_schedules)
    end
  end

  context 'when setting planned erasure dates on Offender SARs' do
    it 'sets the correct planned erasure date' do
      kase = closed_offender_sar

      service = described_class.new(
        kase: kase, user: user
      )
      service.call

      expected_date = kase.retention_schedule.planned_destruction_date

      expect(kase.retention_schedule).to be_a(RetentionSchedule)
      expect(expected_date).to match(expected_off_sar_erasure_date)

      check_last_transition(
        kase, "Destruction date set to #{expected_date.strftime('%d-%m-%Y')}"
      )
    end

    it 'sets the correct planned erasure date when an off sar already has a retention schedule' do
      retention_schedule = closed_offender_sar_with_retention_schedule.retention_schedule
      previous_date = retention_schedule.planned_destruction_date
      kase = closed_offender_sar_with_retention_schedule

      service = described_class.new(
        kase: kase, user: user
      )
      service.call

      expected_date = kase.retention_schedule.planned_destruction_date

      expect(service.result).to be(:success)
      expect(kase.retention_schedule).to eq(retention_schedule)
      expect(expected_date).to match(expected_off_sar_erasure_date)

      check_last_transition(
        kase, "Destruction date changed from #{previous_date.strftime('%d-%m-%Y')} to #{expected_date.strftime('%d-%m-%Y')}"
      )
    end
  end

  context 'for planned erasure dates on Offender SARs Complaints' do
    it 'sets them correctly for the complaint and the original case' do
      retention_schedule = closed_offender_sar_complaint.retention_schedule
      previous_date = retention_schedule.planned_destruction_date
      kase = closed_offender_sar_complaint
      original_kase = closed_offender_sar_complaint.original_case

      service = described_class.new(
        kase: kase, user: user
      )
      service.call

      expected_date = kase.retention_schedule.planned_destruction_date

      expected_original_kase_date = original_kase
        .retention_schedule
        .planned_destruction_date

      expect(kase.retention_schedule).to eq(retention_schedule)
      expect(original_kase.retention_schedule).not_to eq(retention_schedule)

      expect(expected_date).to match(expected_off_sar_erasure_date)
      expect(expected_original_kase_date).to match(expected_off_sar_erasure_date)

      check_last_transition(
        kase, "Destruction date changed from #{previous_date.strftime('%d-%m-%Y')} to #{expected_date.strftime('%d-%m-%Y')}"
      )
      check_last_transition(
        original_kase, "Destruction date set to #{expected_date.strftime('%d-%m-%Y')}"
      )
    end

    it 'sets them correctly on closed complaints related to the original case' do
      service = described_class.new(
        kase: closed_offender_sar_complaint, user: user
      )
      service.call

      expected_date = closed_offender_sar_complaint
        .retention_schedule
        .planned_destruction_date

      original_kase = closed_offender_sar_complaint.original_case

      ok_retention_schedule = original_kase.retention_schedule

      other_related_complaints.each do |related_complaint|
        related_original_case = related_complaint.original_case

        related_case_date = related_complaint
          .retention_schedule
          .planned_destruction_date

        expect(ok_retention_schedule).to_not be(related_complaint.retention_schedule)
        expect(expected_date).to match(related_case_date)
        expect(expected_off_sar_erasure_date).to match(related_case_date)
        expect(original_kase).to match(related_original_case)
      end

      other_related_open_complaints.each do |related_complaint|
        expect(related_complaint.retention_schedule).to be(nil)
      end
    end
  end

  def check_last_transition(kase, message)
    transition = kase.transitions.last

    expect(transition.event).to eq('annotate_system_retention_changes')
    expect(transition.acting_user).to eq(user)
    expect(transition.acting_team).to eq(user.teams.last)
    expect(transition.message).to eq(message)
  end
end


text:
using System;
using System.IO;
using System.Security;
using CommandLine;
using CommandLine.Text;

namespace Aliaser
{
	internal class Options
	{
		[Option('f', "file", Required = true, HelpText = "Alias file name.")]
		public string AliasFile { get; set; }

		[Option('v', "verbose", Required = false, DefaultValue = true, HelpText = "Prints all messages to the standard output.")]
		public bool Verbose { get; set; }

		[Option('e', "executable", Required = false, DefaultValue = "CMD.exe", HelpText = "The name of the executable to assign aliases to.")]
		public string ExecutableName { get; set; }

		[ParserState]
		public IParserState ParserState { get; set; }

		[HelpOption]
		public string GetUsage()
		{
			return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
		}
	}

	class Program
	{
		private static Options Options { get; set; }

		static void Main(string[] args)
		{
			if (!TryParseOptions(args)) return;

			string[] lines;
			if (!TryReadAliasFileLines(out lines)) return;

			for (var lineNumber = 0; lineNumber < lines.Length; lineNumber++)
			{
				var line = lines[lineNumber].Trim();

				Tuple<string, string> parsedLine;
				if (!TryParseLine(line, lineNumber, out parsedLine)) continue;

				var alias = parsedLine.Item1;
				var command = parsedLine.Item2;
				if (!WinApi.AddConsoleAlias(alias, command, Options.ExecutableName))
				{
					WriteLine("Failed to add alias '{0}' to the command '{1}'.", alias, command);
				}
				else
				{
					WriteLine("Successfully added alias '{0}' to the command '{1}'.", alias, command);
				}
			}
		}

		private static bool TryParseOptions(string[] args)
		{
			Options = new Options();
			if (!CommandLine.Parser.Default.ParseArguments(args, Options)) return false;

			if (!File.Exists(Options.AliasFile))
			{
				Console.WriteLine("The aliases file '{0}' could not be found.", Options.AliasFile);
				return false;
			}

			return true;
		}

		private static bool TryReadAliasFileLines(out string[] lines)
		{
			lines = null;
			try
			{
				lines = File.ReadAllLines(Options.AliasFile);
			}
			catch (Exception e)
			{
				if (e is UnauthorizedAccessException || e is SecurityException)
				{
					Console.WriteLine("Cannot read alias file. Application has no permissions required. Error message: {0}", e.Message);
					return false;
				}

				Console.WriteLine("Unhandled exception occured while reading alias file. Error message: {0}", e.Message);
				return false;
			}

			return true;
		}

		private static bool TryParseLine(string line, int lineNumber, out Tuple<string, string> parsedLine)
		{
			parsedLine = null;

			// If line starts with '#' character then it is treated as a comment, i.e. not processed.
			// If line is empty or whitespace string it is not processed.
			if (line.StartsWith("#") || string.IsNullOrEmpty(line)) return false;

			var firstSpaceCharacterIndex = line.IndexOf(' ');
			if (firstSpaceCharacterIndex < 0)
			{
				WriteLine("Invalid value at line {0}. Alias and associated command must be delimited with a one or more space characters. Line omitted.", lineNumber);
				return false;
			}

			var alias = line.Substring(0, firstSpaceCharacterIndex).Trim();
			var command = line.Substring(firstSpaceCharacterIndex).Trim();

			if (string.IsNullOrEmpty(command))
			{
				WriteLine("Invalid command at line {0}. Alias is present but command could not be an empty string. Line omitted.", lineNumber);
				return false;
			}

			parsedLine = new Tuple<string, string>(alias, command);

			return true;
		}

		private static void WriteLine(string format, params object[] arguments)
		{
			if (Options.Verbose)
			{
				Console.WriteLine(format, arguments);
			}
		}
	}
}


text:
namespace Vriska
{
  class WindowsSocket : public INativeSocket
  {
  public:
    WindowsSocket();
    ~WindowsSocket();

    bool	operator==(INativeSocket const & other) const;
    bool	operator!=(INativeSocket const & other) const;

  private:
    WindowsSocket(INativeSocket const & other);
    WindowsSocket const &	operator=(INativeSocket const & other);

  public:
    Error::Code	socket(std::string const & protocol = "TCP");
    Error::Code	connect(std::string const & host, unsigned int port);
    Error::Code	bind(unsigned int port, std::string const & host = "");
    Error::Code listen(unsigned int clients = INativeSocket::MaxClients);
    Error::Code	close();

    Error::Code	select(SocketSet& read, SocketSet& write, Time* timeout = NULL, bool* hasStdin = NULL);
    Error::Code	accept(INativeSocket** client);

    int		recv(void *buffer, size_t size);
    int		recvfrom(void *buffer, size_t size, INativeSocket** client);
    int		send(void const *buffer, size_t size);

  public:
    std::string	getIPAddress() const;
    std::string	getIPConnectedOn() const;
    unsigned int	getPort() const;

  private:
    static void	setSockets(SocketSet& set, fd_set& nset, SOCKET& max);
    static void	removeSockets(SocketSet& set, fd_set& nset);

  private:
    Mutex	_mutex;
    SOCKET	_sock;
    SOCKADDR_IN	_sa;
  };
}

#endif // !VRISKA_LIB_NETWORK_WINDOWSSOCKET_H_


text:
namespace chromeos {
namespace network_handler {

// None of these messages are user-facing, they should only appear in logs.
const char kDBusFailedError[] = "Error.DBusFailed";
const char kDBusFailedErrorMessage[] = "DBus call failed.";

// These are names of fields in the error data dictionary for ErrorCallback.
const char kErrorName[] = "errorName";
const char kErrorDetail[] = "errorDetail";
const char kDbusErrorName[] = "dbusErrorName";
const char kDbusErrorMessage[] = "dbusErrorMessage";
const char kPath[] = "path";

base::DictionaryValue* CreateErrorData(const std::string& service_path,
                                       const std::string& error_name,
                                       const std::string& error_detail) {
  return CreateDBusErrorData(service_path, error_name, error_detail, "", "");
}

base::DictionaryValue* CreateDBusErrorData(
    const std::string& path,
    const std::string& error_name,
    const std::string& error_detail,
    const std::string& dbus_error_name,
    const std::string& dbus_error_message) {
  base::DictionaryValue* error_data(new base::DictionaryValue);
  error_data->SetString(kErrorName, error_name);
  error_data->SetString(kErrorDetail, error_detail);
  error_data->SetString(kDbusErrorName, dbus_error_name);
  error_data->SetString(kDbusErrorMessage, dbus_error_message);
  if (!path.empty())
    error_data->SetString(kPath, path);
  return error_data;
}

void ShillErrorCallbackFunction(const std::string& error_name,
                                const std::string& path,
                                const ErrorCallback& error_callback,
                                const std::string& dbus_error_name,
                                const std::string& dbus_error_message) {
  std::string detail;
  if (!path.empty())
    detail += path + ": ";
  detail += dbus_error_name;
  if (!dbus_error_message.empty())
    detail += ": " + dbus_error_message;
  NET_LOG_ERROR(error_name, detail);

  if (error_callback.is_null())
    return;
  scoped_ptr<base::DictionaryValue> error_data(
      CreateDBusErrorData(path, error_name, detail,
                          dbus_error_name, dbus_error_message));
  error_callback.Run(error_name, error_data.Pass());
}

void GetPropertiesCallback(
    const network_handler::DictionaryResultCallback& callback,
    const network_handler::ErrorCallback& error_callback,
    const std::string& path,
    DBusMethodCallStatus call_status,
    const base::DictionaryValue& value) {
  if (call_status != DBUS_METHOD_CALL_SUCCESS) {
    scoped_ptr<base::DictionaryValue> error_data(
        network_handler::CreateErrorData(path,
                                         kDBusFailedError,
                                         kDBusFailedErrorMessage));
    NET_LOG_ERROR(
        base::StringPrintf("GetProperties failed. Status: %d", call_status),
        path);
    if (!error_callback.is_null())
      error_callback.Run(kDBusFailedError, error_data.Pass());
  } else if (!callback.is_null()) {
    callback.Run(path, value);
  }
}

}  // namespace network_handler
}  // namespace chromeos


text:
Return a list of repos.

### Synopsis

Return a list of repos. By default, hide system repos like pipeline metadata

```
pachctl list repo [flags]
```

### Options

```
      --all               include system repos of all types
      --full-timestamps   Return absolute timestamps (as opposed to the default, relative timestamps).
  -h, --help              help for repo
  -o, --output string     Output format when --raw is set: "json" or "yaml" (default "json")
      --raw               Disable pretty printing; serialize data structures to an encoding such as json or yaml
      --type string       only include repos of the given type
```

### Options inherited from parent commands

```
      --no-color   Turn off colors.
  -v, --verbose    Output verbose logs
```


text:
using MonoTouch.UIKit;
using System.Drawing;
using System;
using MonoTouch.Foundation;

namespace Hello_Universal
{
	public partial class Hello_UniversalViewController : UIViewController
	{
		public Hello_UniversalViewController (string nibName, NSBundle bundle) : base (nibName, bundle)
		{
		}

		public override void DidReceiveMemoryWarning ()
		{
			// Releases the view if it doesn't have a superview.
			base.DidReceiveMemoryWarning ();

			// Release any cached data, images, etc that aren't in use.
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			this.btnClickMe.TouchUpInside += (sender, e) => {
				this.lblOutput.Text = "Clicked @ " + DateTime.Now.ToShortTimeString();
			};
		}

		public override void ViewDidUnload ()
		{
			base.ViewDidUnload ();

			// Release any retained subviews of the main view.
			// e.g. this.myOutlet = null;
		}

		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			// Return true for supported orientations
			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) {
				return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
			} else {
				return true;
			}
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.pushq</groupId>
    <artifactId>soccero</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <build>
        <resources>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/java</directory>
                <includes>
                    <include>**</include>
                </includes>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <webXml>src/main/resources/webapp/WEB-INF/web.xml</webXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <phase>deploy</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <echo>deploying to server: ${deployment.server}</echo>
                                <taskdef classname="org.apache.tools.ant.taskdefs.optional.ssh.Scp" name="scp" />
                                <scp port="2213" file="${project.build.directory}/${project.artifactId}-${project.version}.war" password="${deployment.password}" todir="${deployment.userName}@${deployment.server}:/home/virgo/jetty/webapps/root.war" trust="true" verbose="true" />
                                <sshexec command="/home/virgo/jetty/bin/jetty.sh restart" port="2213" host="${deployment.server}" password="${deployment.password}" trust="true" username="${deployment.userName}"></sshexec>
                            </target>
                        </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>com.jcraft</groupId>
                        <artifactId>jsch</artifactId>
                        <version>0.1.25</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.ant</groupId>
                        <artifactId>ant-jsch</artifactId>
                        <version>1.7.1</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-template-velocity</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.0.2.v20130417</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>9.0.2.v20130417</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.5</version>
        </dependency>

    </dependencies>

</project>


text:
template <class T>
void test_is_trivially_copy_constructible()
{
    static_assert( std::is_trivially_copy_constructible<T>::value, "");
    static_assert( std::is_trivially_copy_constructible<const T>::value, "");
#if TEST_STD_VER > 14
    static_assert( std::is_trivially_copy_constructible_v<T>, "");
    static_assert( std::is_trivially_copy_constructible_v<const T>, "");
#endif
}

template <class T>
void test_has_not_trivial_copy_constructor()
{
    static_assert(!std::is_trivially_copy_constructible<T>::value, "");
    static_assert(!std::is_trivially_copy_constructible<const T>::value, "");
#if TEST_STD_VER > 14
    static_assert(!std::is_trivially_copy_constructible_v<T>, "");
    static_assert(!std::is_trivially_copy_constructible_v<const T>, "");
#endif
}

class Empty
{
};

class NotEmpty
{
public:
    virtual ~NotEmpty();
};

union Union {};

struct bit_zero
{
    int :  0;
};

class Abstract
{
public:
    virtual ~Abstract() = 0;
};

struct A
{
    A(const A&);
};

int main()
{
    test_has_not_trivial_copy_constructor<void>();
    test_has_not_trivial_copy_constructor<A>();
    test_has_not_trivial_copy_constructor<Abstract>();
    test_has_not_trivial_copy_constructor<NotEmpty>();

    test_is_trivially_copy_constructible<int&>();
    test_is_trivially_copy_constructible<Union>();
    test_is_trivially_copy_constructible<Empty>();
    test_is_trivially_copy_constructible<int>();
    test_is_trivially_copy_constructible<double>();
    test_is_trivially_copy_constructible<int*>();
    test_is_trivially_copy_constructible<const int*>();
    test_is_trivially_copy_constructible<bit_zero>();
}


text:
<?php

use OAuth\OAuth1\Signature\Signature;
use OAuth\OAuth1\Service\Twitter;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
use OAuth\Common\Http\Uri\Uri;

/**
 * Bootstrap the example
 */
require_once __DIR__ . '/bootstrap.php';

// We need to use a persistent storage to save the token, because oauth1 requires the token secret received before'
// the redirect (request token request) in the access token request.
$storage = new Session();

// Setup the credentials for the requests
$credentials = new Credentials(
    $servicesCredentials['twitter']['key'],
    $servicesCredentials['twitter']['secret'],
    $currentUri->getAbsoluteUri()
);

// Instantiate the twitter service using the credentials, http client and storage mechanism for the token
/** @var $twitterService Twitter */
$twitterService = $serviceFactory->createService('twitter', $credentials, $storage);

if( !empty( $_GET['oauth_token'] ) ) {
    $token = $storage->retrieveAccessToken();
    // This was a callback request from twitter, get the token
    $twitterService->requestAccessToken( $_GET['oauth_token'], $_GET['oauth_verifier'], $token->getRequestTokenSecret() );

    // Send a request now that we have access token
    $result = json_decode( $twitterService->request( 'account/verify_credentials.json') );

    echo 'result:
' . print_r($result, true) . '
';

} elseif( !empty($_GET['go'] ) && $_GET['go'] == 'go' ) {
    // extra request needed for oauth1 to request a request token :-)
    $token = $twitterService->requestRequestToken();

    $url = $twitterService->getAuthorizationUri(['oauth_token' => $token->getRequestToken()]);
    header('Location: ' . $url);
} else {
    $url = $currentUri->getRelativeUri() . '?go=go';
    echo "Login with Twitter!";
}


text:
import { IAuthorizeService } from './authorize'
import { ICircleService } from './circles'
import { ICommentService } from './comments'
import { ICommonService } from './common'
import { IImageGalleryService } from './imageGallery'
import { INotificationService } from './notifications'
import { IPostService } from './posts'
import { IUserService } from './users'
import { IVoteService } from './votes'
import { IStorageService } from './files'

export {
    IAuthorizeService,
    ICircleService,
    ICommentService,
    ICommonService,
    IImageGalleryService,
    INotificationService,
    IPostService,
    IUserService,
    IVoteService,
    IStorageService
}


text:
#ifndef _STRING_ITERATOR_H_
#define _STRING_ITERATOR_H_

#include <nds.h>

namespace WoopsiGfx {

	class WoopsiString;

	/**
	 * Class used to efficiently iterate over the characters in a WoopsiString
	 * object.  The WoopsiString is a Unicode string that uses the
	 * variable-width UTF-8 encoding to represent its characters.  This means
	 * that it is not possible to iterate over a WoopsiString in the same way
	 * that you would iterate over a char array.
	 */
	class StringIterator {
	public:

		/**
		 * Constructor.  Moves the iterator to the first character in the
		 * string.
		 * @param string Pointer to the string that will be iterated over.
		 */
		StringIterator(const WoopsiString* string);

		/**
		 * Destructor.
		 */
		inline ~StringIterator() { };

		/**
		 * Moves the iterator to the first character in the string.
		 */
		void moveToFirst();

		/**
		 * Moves the iterator to the last character in the string.
		 */
		void moveToLast();

		/**
		 * Move the iterator to the next character in the string.
		 * @return True if the iterator moved; false if not (indicates end of
		 * string).
		 */
		bool moveToNext();

		/**
		 * Move the iterator to the previous character in the string.
		 * @return True if the iterator moved; false if not (indicates start of
		 * string).
		 */
		bool moveToPrevious();

		/**
		 * Move the iterator to the specified index.
		 * @param index The index to move to.
		 * @return True if the iterator moved; false if not (indicates end of
		 * string).
		 */
		bool moveTo(s32 index);

		/**
		 * Get the current position of the iterator within the string.
		 * @return The current character index of the iterator.
		 */
		inline s32 getIndex() const { return _currentIndex; };

		/**
		 * Get the codepoint in the string at the iterator's current point.
		 * @return The current character in the string.
		 */
		u32 getCodePoint() const;

		/**
		 * Get the integer value represented by the sequence of digits at the
		 * current point.
		 * @param charCount If set to anything other than NULL, the pointer will
		 * be populated with the number of characters in the integer.  A value
		 * of 0 indicates that no digits were found at the current point.
		 * @return The integer value represented by the current string position.
		 */
		u32 getInteger(u32* charCount = NULL);

	protected:

		/**
		 * Get the size of the current codepoint in bytes.
		 * @return The size of the current codepoint.
		 */
		u8 getCodePointSize();

		/**
		 * Move forwards from the current index to the specified index.
		 * @param index The index to move to.
		 */
		void iterateForwardsTo(s32 index);

		/**
		 * Move backwards from the current index to the specified index.
		 * @param index The index to move to.
		 */
		void iterateBackwardsTo(s32 index);

	private:
		const WoopsiString* _string;		/**< String being iterated over. */
		const char* _currentChar;			/**< Pointer to the current position of the iterator. */
		s32 _currentIndex;					/**< Iterator's current index within the string. */
	};
}

#endif


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/ec2/model/PrincipalType.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes a principal.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API AllowedPrincipal
  {
  public:
    AllowedPrincipal();
    AllowedPrincipal(const Aws::Utils::Xml::XmlNode& xmlNode);
    AllowedPrincipal& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The type of principal.

     */
    inline const PrincipalType& GetPrincipalType() const{ return m_principalType; }

    /**
     *
The type of principal.

     */
    inline bool PrincipalTypeHasBeenSet() const { return m_principalTypeHasBeenSet; }

    /**
     *
The type of principal.

     */
    inline void SetPrincipalType(const PrincipalType& value) { m_principalTypeHasBeenSet = true; m_principalType = value; }

    /**
     *
The type of principal.

     */
    inline void SetPrincipalType(PrincipalType&& value) { m_principalTypeHasBeenSet = true; m_principalType = std::move(value); }

    /**
     *
The type of principal.

     */
    inline AllowedPrincipal& WithPrincipalType(const PrincipalType& value) { SetPrincipalType(value); return *this;}

    /**
     *
The type of principal.

     */
    inline AllowedPrincipal& WithPrincipalType(PrincipalType&& value) { SetPrincipalType(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline const Aws::String& GetPrincipal() const{ return m_principal; }

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline bool PrincipalHasBeenSet() const { return m_principalHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline void SetPrincipal(const Aws::String& value) { m_principalHasBeenSet = true; m_principal = value; }

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline void SetPrincipal(Aws::String&& value) { m_principalHasBeenSet = true; m_principal = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline void SetPrincipal(const char* value) { m_principalHasBeenSet = true; m_principal.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline AllowedPrincipal& WithPrincipal(const Aws::String& value) { SetPrincipal(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline AllowedPrincipal& WithPrincipal(Aws::String&& value) { SetPrincipal(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the principal.

     */
    inline AllowedPrincipal& WithPrincipal(const char* value) { SetPrincipal(value); return *this;}

  private:

    PrincipalType m_principalType;
    bool m_principalTypeHasBeenSet;

    Aws::String m_principal;
    bool m_principalHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
from pyjamas.ui.PopupPanel import PopupPanel
from pyjamas import Factory
from pyjamas.ui.HTML import HTML
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.Timer import Timer
from pyjamas import Window
from pyjamas import DOM

tooltip_hide_timer = None

class Tooltip(PopupPanel):
    def __init__(self, sender, offsetX, offsetY, contents,
                       show_delay, hide_delay, styleName, **kwargs):
        """ contents may be a text string or it may be a widget
        """
        PopupPanel.__init__(self, True, **kwargs)
        self.show_delay = show_delay
        self.hide_delay = hide_delay

        if isinstance(contents, basestring):
            contents = HTML(contents)
        self.add(contents)

        left = sender.getAbsoluteLeft() + offsetX
        top = sender.getAbsoluteTop() + offsetY

        self.setPopupPosition(left, top)
        self.setStyleName(styleName)

        if tooltip_hide_timer:
            self.tooltip_show_timer = Timer(1, self)
        else:
            self.tooltip_show_timer = Timer(self.show_delay, self)

    def onShowImpl(self, popup):
        width = self.getOffsetWidth()
        heigth = self.getOffsetHeight()
        w_width = Window.getClientWidth()
        w_heigth = Window.getClientHeight()
        if w_width > width and w_heigth > heigth:
            offset_x = self.getAbsoluteLeft()
            offset_y = self.getAbsoluteTop()
            element = self.getElement()
            if (offset_x + width) > w_width:
                offset_x = w_width - width
                DOM.setStyleAttribute(element, "left", "%dpx" % offset_x)
            if (offset_y + heigth) > w_heigth:
                offset_y = w_heigth - heigth
                DOM.setStyleAttribute(element, "top", "%dpx" % offset_y)

    def show(self):
        global tooltip_hide_timer

        # activate fast tooltips
        tooltip_hide_timer = Timer(self.hide_delay, self)
        PopupPanel.show(self)

    def hide(self, autoClosed=False):
        self.tooltip_show_timer.cancel()
        PopupPanel.hide(self, autoClosed)

    def onTimer(self, timer):
        global tooltip_hide_timer

        # deactivate fast tooltips on last timer
        if timer is tooltip_hide_timer:
            tooltip_hide_timer = None

        if timer is self.tooltip_show_timer:
            self.show()
        else:
            self.hide()

class TooltipListener:
    DEFAULT_TOOLTIP_STYLE = "TooltipPopup"
    DEFAULT_OFFSET_X = 10
    DEFAULT_OFFSET_Y = 35

    def __init__(self, text, show_delay = 1000, hide_delay = 5000, styleName = ""):
        if not styleName:
            styleName = self.DEFAULT_TOOLTIP_STYLE

        self.tooltip = None
        self.text = text
        self.styleName = styleName
        self.show_delay = show_delay
        self.hide_delay = hide_delay
        self.offsetX = self.DEFAULT_OFFSET_X
        self.offsetY = self.DEFAULT_OFFSET_Y

    def onMouseEnter(self, sender):
        self.hide()
        self.tooltip = Tooltip(sender, self.offsetX, self.offsetY, self.text, self.show_delay, self.hide_delay, self.styleName)

    def onMouseLeave(self, sender):
        self.hide()

    def onMouseMove(self, sender, x, y):
        pass

    def onMouseDown(self, sender, x, y):
        pass

    def onMouseUp(self, sender, x, y):
        pass

    def getStyleName(self):
        return self.styleName

    def setStyleName(self, styleName):
        self.styleName = styleName

    def getOffsetX(self):
        return self.offsetX

    def setOffsetX(self, offsetX):
        self.offsetX = offsetX

    def getOffsetY(self):
        return self.offsetY

    def setOffsetY(self, offsetY):
        self.offsetY = offsetY

    def hide(self):
        if self.tooltip is not None:
            self.tooltip.hide()

Factory.registerClass('pyjamas.ui.Tooltip', 'Tooltip', Tooltip)


text:
* 353 Add new custom property to allow "Add" label to be confgiered in Flat or Accordion views. Thanks to Rich Sharpe for suggesting
* 354 Fix bug with typeahead not working with very large source lists, see documentation for configuration change to use this new mode. Thanks to Ady Makombo for reporting
* 357 Resolve some markup confusion when using modals in different contexts. Thanks to L R Barker for suggesting
* 364 Fix bug with global search when accessing data from an external database. Thanks to Rich Sharpe for suggesting
* 368 Fix Detailed view so that it will immediately show changes after editing documents. Thanks to Rich Sharpe for suggesting
* 369 Add a new demo of using draggables in the Sampler application. Thanks to Steve Ives for suggesting
* 370 Fix bug with font file not loading correctly in Sampler reading card page. Thanks to Mike Amberg for reporting

##v1.5.1/ 2015-09-17
* 356 Fix a bug with saving content that contains a % sign. Thanks to Rich Sharpe for reporting

##v1.5.0/ 2015-08-10
* 335 Add support for two lines in Header title. Simply add a
tag. Thanks to Rich Sharpe for suggesting
* 338 Fix bug with display of slide in menu in portrait mode on the iPad. Thanks to Rich Sharpe for suggesting
* 339 Improve Android photo upload support in Sampler application. Thanks to Rich Sharpe for suggesting
* 347 Add switch to enable editmode when opening a document from FlatList. Thanks to Rich Sharpe for suggesting
* 348 We've upgraded to support the very latest version of Bootcards
* 351 Fix a bug in day and week calendar views where entries were not visible. Thanks to Telemanage for suggesting

##v1.4.2/ 2015-07-08
* 343 Fix bug with saving data to other database when using Unplugged client, thanks xpagesbeast for reporting
* 336/#321 Improve Cancel button operation when running edit mode in full screen, thanks Rich Sharpe for reporting
* 334 Fix bug with orientation change on tablets when displaying a full page document, thanks Rich Sharpe for reporting

##v1.4 / 2015-05-19
* Fix bug with selecting options from list in typeahead in iOS, thanks adymakombo for reporting
* Add support for data sources on a different server to the application database, thanks Klaus F Heine for reporting
* Fix bug with selecting options from list in typeahead in iOS, thanks adymakombo for reporting
* Improve flat view searching by allowing partial matches and offering typeahead options, thanks notesboy for reporting
* Better support double header bar from Bootcards, thanks sives for reporting
* Improve photo upload support to work on desktop and mobile browsers as well as Unplugged, thanks richsharpe for reporting
* Improved sampler code for mobile toggle switch, thanks richsharpe for reporting
* Allow UnpBootFormEdit control to be loaded full page and have cancel button return to previous page, thanks richsharpe for reporting
* Fix bug with dismissOnOk=false in Unplugged, thanks richsharpe for reporting
* Extend post save callback to pass in sufficient parameters to allow developer to reload flat list in place, thanks richsharpe for suggesting
* Add new presavecallback to allow custom validation to be performed before saving, thanks richsharpe for suggesting

##v1.3.1 / 2015-03-06
* Identify bug where max response size in Unplugged server prevented rich text editor from working properly, thanks edm00se, NeilEvans for help tracking it down
* Fix bug with showbuttons not working correctly in UnpBootFormEditor, thanks Reid Canavan
* Fix bug with UnpBootAccordionView not correctly handling ajaxload=no setting, thanks Reid Canavan
* Add version number to design elements, thanks David Henderson
* Make dialogs truly modal, user now has to click close or cancel, thanks ktatsuki and khsopro
* Fix toggle switch not working in some situations on the desktop, thanks Rich Sharpe

## v1.3.0 / 2015-01-20

* Fix a bug where the Add button in the accordion list was not working correctly, thanks [aysekai](https://github.com/ayesekai)
* Fix a bug where JS is not fired when a new document is created, thanks [Rich Sharpe](https://github.com/richsharpe)
* Add option to not open first document in list automatically, thanks [Rich Sharpe](https://github.com/richsharpe)
* Improve the functionality of the Login Control, thanks [Rich Sharpe](https://github.com/richsharpe)
* Fix bug with detailcolumn not displaying correctly in Accordion List control, thanks [Mitsuru Katoh](https://github.com/katoman) and [khsopro](https://github.com/khsopro)
* Fix bug with display of Flat View when rotating iPad from portrait to landscape, thanks [Rich Sharpe](https://github.com/richsharpe)
* Allow creation of new documents from header bar on desktop, thanks [Rich Sharpe](https://github.com/richsharpe)
* Fix bug with view icons not displaying correctly in the Accordion List, thanks [susinmn](https://github.com/susinmn)
* Callback support added to openDocument, editDocument and saveDocument events to allow developer to add post processing, thanks [Rich Sharpe](https://github.com/richsharpe)
* Fix bug with New Response button in Form Viewer control, thanks [Mitsuru Katoh](https://github.com/katoman)
* Added date picker for Firefox and IE desktop browsers (native pickers used elsewhere), thanks [Neil Evans](https://github.com/neilevans)
* Add drop down support for desktop header bar, thanks [Steve Ives](https://github.com/sives)

## v1.2.0 / 2014-11-17

* Add new UnpBootDetailedView control to support the Bootcards detailed list pattern
* Fix bug where page scrolled when scrolling slide in menu, thanks [Mark Leusink](https://github.com/markleusink)
* Fix bug where menu was transparent at bottom, thanks [Mark Leusink](https://github.com/markleusink)
* Improve save document process to update document summary in FlatView after saving
* Add new Login control for use with web applications
* Update UnpDialog callback to allow developer to choose whether dialog is closed automatically on OK, thanks [Martin Perrie](https://github.com/martinperrie)
* Update UnpDialog to allow developer to choose whether OK or cancel buttons are visible, thanks [Martin Perrie](https://github.com/martinperrie)
* Update Carousel Control to support captions for images in carousel, thanks [Ady Makombo](https://github.com/adymakombo)
* Allow custom buttons to be inserted in FormViewer header using a new editable area, thanks [Rich Sharpe](https://github.com/richsharpe)
* Update documentation to make clearer the requirement for FormViewer fields to be wrapped with h4 tags, thanks[Rich Sharpe](https://github.com/richsharpe)
* Upgrade version on Bootcards to v1.1, thanks [Mark Leusink](https://github.com/markleusink)
* Update XControls website to [xcontrols.org](http://xcontrols.org)
* Add support for runtime optimized CSS and JS which dramatically reduces page sizes for web applications, thanks [Mark Leusink](https://github.com/markleusink)

We do have one known issue with the A-Z Picker when using it in iOS and Unplugged (not Safari), there are situations where the list will disappear until the user touches their screen again. We're still investigating a solution to this issue.

## v1.1.1 / 2014-10-21

* UnpBootFlatView - white space on left of data in view when no icon is used
* Updated license files to take account of OFL for Font Awesome

## v1.1 / 2014-10-21

* fixed; issue with calendar entries in latest Firefox, thanks [Howard Greenberg](https://github.com/howardtlcc)
* UnpBootFiles Control * either doc is wrong or the files are not automatically populated when form is in an external DB, thanks [Rich Sharpe](https://github.com/richsharpe)
* Change sampler app menu layout
* Change Controls Group Name
* Github name
* No documnetation for the UnpPhotoUpload control, thanks [Rich Sharpe](https://github.com/richsharpe)
* Search using a desktop browser does not work, thanks [Howard Greenberg](https://github.com/howardtlcc)
* Categorized view on iPhone issue, thanks [Howard Greenberg](https://github.com/howardtlcc)
* Tablet - Rotate from Landscape to Portrait loses navigation, thanks [Reid Canavan](https://github.com/reidcanavan)
* unpBootAccordianView - Add button - Show option, thanks [Reid Canavan](https://github.com/reidcanavan)
* Rename TypographyEdit and TypographyRead controls
* AZ picker is cut off in landscape Mode
* Change UnpBootFormViewer to render std buttons on true/false not 'yes'/!'yes', thanks [Rich Sharpe](https://github.com/richsharpe)
* Icons not aligned correctly in lists


text:
using System;
using BACnet.Types;
using BACnet.Types.Schemas;

namespace BACnet.Ashrae
{
	public  partial class ConfirmedCOVNotificationRequest
	{
		public uint SubscriberProcessIdentifier { get; private set; }

		public ObjectId InitiatingDeviceIdentifier { get; private set; }

		public ObjectId MonitoredObjectIdentifier { get; private set; }

		public uint TimeRemaining { get; private set; }

		public ReadOnlyArray<PropertyValue> ListOfValues { get; private set; }

		public ConfirmedCOVNotificationRequest(uint subscriberProcessIdentifier, ObjectId initiatingDeviceIdentifier, ObjectId monitoredObjectIdentifier, uint timeRemaining, ReadOnlyArray<PropertyValue> listOfValues)
		{
			this.SubscriberProcessIdentifier = subscriberProcessIdentifier;
			this.InitiatingDeviceIdentifier = initiatingDeviceIdentifier;
			this.MonitoredObjectIdentifier = monitoredObjectIdentifier;
			this.TimeRemaining = timeRemaining;
			this.ListOfValues = listOfValues;
		}

		public static readonly ISchema Schema = new SequenceSchema(false,
			new FieldSchema("SubscriberProcessIdentifier", 0, Value<uint>.Schema),
			new FieldSchema("InitiatingDeviceIdentifier", 1, Value<ObjectId>.Schema),
			new FieldSchema("MonitoredObjectIdentifier", 2, Value<ObjectId>.Schema),
			new FieldSchema("TimeRemaining", 3, Value<uint>.Schema),
			new FieldSchema("ListOfValues", 4, Value<ReadOnlyArray<PropertyValue>>.Schema));

		public static ConfirmedCOVNotificationRequest Load(IValueStream stream)
		{
			stream.EnterSequence();
			var subscriberProcessIdentifier = Value<uint>.Load(stream);
			var initiatingDeviceIdentifier = Value<ObjectId>.Load(stream);
			var monitoredObjectIdentifier = Value<ObjectId>.Load(stream);
			var timeRemaining = Value<uint>.Load(stream);
			var listOfValues = Value<ReadOnlyArray<PropertyValue>>.Load(stream);
			stream.LeaveSequence();
			return new ConfirmedCOVNotificationRequest(subscriberProcessIdentifier, initiatingDeviceIdentifier, monitoredObjectIdentifier, timeRemaining, listOfValues);
		}

		public static void Save(IValueSink sink, ConfirmedCOVNotificationRequest value)
		{
			sink.EnterSequence();
			Value<uint>.Save(sink, value.SubscriberProcessIdentifier);
			Value<ObjectId>.Save(sink, value.InitiatingDeviceIdentifier);
			Value<ObjectId>.Save(sink, value.MonitoredObjectIdentifier);
			Value<uint>.Save(sink, value.TimeRemaining);
			Value<ReadOnlyArray<PropertyValue>>.Save(sink, value.ListOfValues);
			sink.LeaveSequence();
		}
	}
}


text:
IKinectManipulationCompletedEventArgs::get\_PointerDeviceType Method
====================================================================

Gets the device type of the input source.

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

public:
HRESULT get_PointerDeviceType(
         PointerDeviceType *value
)

#### Parameters

*value*
Type: PointerDeviceType
[out] The device type.

#### Return value

Type: HRESULT
Returns S\_OK if successful; otherwise, returns a failure code.

Requirements
============

**Header:** kinect.h
**Library:** TBD


text:
//IBoard.java

package de.htwg.battleship.model;

/**
 * IBoard is an Utility-Interface.
 *
 * @author Moritz Sauter (SauterMoritz@gmx.de)
 * @version 1.00
 * @since 2014-12-10
 */
public interface IBoard {

    /**
     * Method for adding a new Ship on the field.
     *
     * @param ship the ship that should be added.
     *
     * @return the number of ships that could be added after. returns -1 if the
     * field is already full.
     */
    int addShip(IShip ship);

    /**
     * Getter for the number of Ships.
     *
     * @return the number of ships that are current on the field as Integer.
     */
    int getShips();

    /**
     * Getter for the list of ships that are on the field.
     *
     * @return the list of ships as Ship[]-Array.
     */
    IShip[] getShipList();

    /**
     * Method to shoot on one Field.
     *
     * @param x x-Coordinate of the Field
     * @param y y-Coordinate of the Field
     */
    void shoot(int x, int y);

    /**
     * Getter if the Field is now hit.
     *
     * @param x x-Coordinate of the Field
     * @param y y-Coordinate of the Field
     *
     * @return boolean if the Field is hit
     */
    boolean isHit(int x, int y);

    /**
     * Getter for the whole boolean field.
     *
     * @return boolean[][] representing the whole field
     */
    boolean[][] getHitMap();

    /**
     * Setter for the boolean matrix. Should be used for restoring a game.
     */
    void restoreBoard(boolean[][] hitMap, IShip[] shipList);
}


text:
@protocol NICell;
@protocol NINibCellObject;
@class NICellObject;

@interface User: NSObject

@property(nonatomic, copy) NSString *name;
@property(nonatomic, assign) NSInteger age;

- (id)initWithName:(NSString *)name age:(NSInteger)age;

@end

@interface TestTableViewCellUserInfo : NSObject

@property(nonatomic, strong) User *user;

@end

@interface TestTableViewCell : UITableViewCell<NICell>

@property (nonatomic, strong)UILabel *contentLabel;

@property(nonatomic, strong) User *info;

+ (NICellObject *)createObject:(id)delegate userInfo:(id)userInfo;

@end


text:
package org.orekit.estimation.leastsquares;

import java.util.List;

import org.orekit.estimation.measurements.EstimatedMeasurement;
import org.orekit.estimation.measurements.ObservableSatellite;
import org.orekit.estimation.measurements.ObservedMeasurement;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.sampling.MultiSatStepHandler;
import org.orekit.propagation.sampling.OrekitStepInterpolator;
import org.orekit.time.AbsoluteDate;

/** {@link org.orekit.propagation.sampling.OrekitStepHandler Step handler} picking up
 * {@link ObservedMeasurement measurements}.
 * @author Luc Maisonobe
 * @since 8.0
 */
class MeasurementHandler implements MultiSatStepHandler {

    /** Least squares model. */
    private final AbstractBatchLSModel model;

    /** Underlying measurements. */
    private final List<PreCompensation> precompensated;

    /** Number of the next measurement. */
    private int number;

    /** Index of the next measurement component in the model. */
    private int index;

    /** Simple constructor.
     * @param model least squares model
     * @param precompensated underlying measurements
     */
    MeasurementHandler(final AbstractBatchLSModel model, final List<PreCompensation> precompensated) {
        this.model          = model;
        this.precompensated = precompensated;
    }

    /** {@inheritDoc} */
    @Override
    public void init(final List<SpacecraftState> initialStates, final AbsoluteDate target) {
        number = 0;
        index  = 0;
    }

    /** {@inheritDoc} */
    @Override
    public void handleStep(final List<OrekitStepInterpolator> interpolators) {

        while (number < precompensated.size()) {

            // Consider the next measurement to handle
            final PreCompensation next = precompensated.get(number);

            // Current state date for interpolator 0
            final AbsoluteDate currentDate = interpolators.get(0).getCurrentState().getDate();
            if (model.isForwardPropagation()  && next.getDate().compareTo(currentDate) > 0 ||
                !model.isForwardPropagation() && next.getDate().compareTo(currentDate) < 0) {
                return;
            }

            // get the observed measurement
            final ObservedMeasurement<?> observed = next.getMeasurement();

            // estimate the theoretical measurement
            final SpacecraftState[] states = new SpacecraftState[observed.getSatellites().size()];
            for (int i = 0; i < states.length; ++i) {
                final ObservableSatellite satellite = observed.getSatellites().get(i);
                states[i] = interpolators.get(satellite.getPropagatorIndex()).getInterpolatedState(next.getDate());
            }
            final EstimatedMeasurement<?> estimated = observed.estimate(model.getIterationsCount(),
                                                                        model.getEvaluationsCount(),
                                                                        states);

            // fetch the evaluated measurement to the estimator
            model.fetchEvaluatedMeasurement(index, estimated);

            // prepare handling of next measurement
            ++number;
            index += observed.getDimension();

        }

    }

}


text:
package org.kuali.kfs.module.purap.businessobject;

/**
 * Accounting line Business Object for a credit memo item line.
 */
public class CreditMemoAccount extends PurApAccountingLineBase {

    /**
     * Default constructor.
     */
    public CreditMemoAccount() {

    }

    /**
     * Constructs a Credit Memo Account object from an existing PurAp Accounting Line object.
     *
     * @param accountingLine the accounting line to copy from.
     */
    public CreditMemoAccount(PurApAccountingLineBase accountingLine) {
        super();

        setChartOfAccountsCode(accountingLine.getChartOfAccountsCode());
        setAccountNumber(accountingLine.getAccountNumber());
        setSubAccountNumber(accountingLine.getSubAccountNumber());
        setFinancialObjectCode(accountingLine.getFinancialObjectCode());
        setFinancialSubObjectCode(accountingLine.getFinancialSubObjectCode());
        setProjectCode(accountingLine.getProjectCode());
        setOrganizationReferenceId(accountingLine.getOrganizationReferenceId());
        setAmount(accountingLine.getAmount());
        setAccountLinePercent(accountingLine.getAccountLinePercent());
        this.setSequenceNumber(accountingLine.getSequenceNumber());
    }

    public CreditMemoItem getCreditMemoItem() {
        return super.getPurapItem();
    }

    /**
     * @deprecated
     */
    public void setCreditMemoItem(CreditMemoItem creditMemoItem) {
        super.setPurapItem(creditMemoItem);
    }
}


text:
<?php

namespace BoxConfig\BoxBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityManager;

class MachineType extends AbstractType
{
    protected $em;

    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {

        $builder
            ->add('name')
            ->add('description')
            ->add('hardware', 'entity', array(
                'class' => 'BoxConfig\ComponentBundle\Entity\Hardware',
                'choices' => $this->em->getRepository('BoxConfigComponentBundle:Hardware')->getSelectList()
                ))
            ->add('active', 'checkbox', array('required' => false))
        ;
    }

    public function getName()
    {
        return 'boxconfig_boxbundle_machinetype';
    }
}


text:
<?php

namespace Expidian\GlobalBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Expidian\GlobalBundle\Entity\Perfiles;
use Expidian\GlobalBundle\Entity\Usuarios;
use Expidian\GlobalBundle\Entity\Personas;
use Expidian\GlobalBundle\Entity\Paises;

/**
 * Description of UsuariosFixtures
 *
 * @author jgonza67
 */
class PersonasFixtures extends AbstractFixture implements OrderedFixtureInterface {

    public function load(ObjectManager $manager) {

        $pais_obj = $manager->find("ExpidianGlobalBundle:Paises",233);

        echo "(---";
        print_r($pais_obj);
        echo "---)";

        $nombres = array('José', 'María', 'Leonel', 'Gabriel', 'Ignacio', 'Daniel', 'Daniel', 'Ricardo', 'Rosbely', 'Andreina');
        $apellidos = array('Espinoza', 'Hernández', 'Perez', 'Pirela', 'Pulido','Vargas', 'Lozada', 'Mata', 'Silva', 'Bolívar');

        for ($i=0;$i<=35;$i++){
            $personas[$i] = new Personas();
            $persona_obj = $personas[$i];
            $aleatorio = mt_rand(0,9);
            $persona_obj->setNombre($nombres[$aleatorio]);
            $persona_obj->setApellido($apellidos[mt_rand(0,9)]);
            $persona_obj->setCedulaDeIdentidad('123456'.$i);
            $persona_obj->setNacionalidad('V');
            $persona_obj->setPais($pais_obj);
            $persona_obj->setEmail($nombres[$aleatorio].$i.'@hotmail.com');
            $persona_obj->setTelefono1('2125555555');
            $manager->persist($persona_obj);
            $this->addReference('persona-'.$i, $persona_obj);
        }

        $manager->flush();

    }

    public function getOrder() {
        return 1;
    }

}

?>


text:
<?php

namespace WioForms\DataRepository;

class WioFlowEntityData extends AbstractDataRepository
{
    public function getData($requiredFields)
    {
        global $queryBuilder;

        $this->data = $queryBuilder->table('wio_flow_entities')
            ->setFetchMode(\PDO::FETCH_ASSOC)
            ->where('wio_user_id', '=', $requiredFields['userId'])
            ->first();
        $this->setRepositoryFlags();

        return $this->data['id'];
    }
}


text:
Cerebral package with react and immutable store

## Requirements
It is required that you use a Webpack or Browserify setup. Read more at [The ultimate webpack setup](http://www.christianalfoni.com/articles/2015_04_19_The-ultimate-webpack-setup) for an example.

## Debugger
You can download the Chrome debugger [here](https://chrome.google.com/webstore/detail/cerebral-debugger/ddefoknoniaeoikpgneklcbjlipfedbb?hl=no).

## More info on Cerebral and video introduction
Cerebral main repo is located [here](https://github.com/christianalfoni/cerebral) and a video demonstration can be found [here](https://www.youtube.com/watch?v=xCIv4-Q2dtA).

## Video introduction
Watch a [video](https://www.youtube.com/watch?v=QG181MnRIXM) on how you can use this package.

## Install
`npm install cerebral-react-immutable-store`

## API
All examples are shown with ES6 syntax.

### Instantiate a Cerebral controller
*controller.js*
```js
import Controller from 'cerebral-react-immutable-store';
import request from 'superagent';

// The initial state of the application
const state = {
  isLoading: false,
  user: null,
  error: null
};

// Any default input you want each action to receive
const defaultInput = {
  utils: {
    request: request
  }
};

// Instantiate the controller
export default Controller(state, defaultInput);
```

*main.js*
```js
import React from 'react';
import AppComponent from './AppComponent.js';
import controller from './controller.js';

React.render(controller.injectInto(AppComponent), document.body);
```
With immutable-store you can also map state using functions, read more about that [here](https://github.com/christianalfoni/immutable-store#mapping-state).

### Creating signals
Creating actions are generic. It works the same way across all packages. Please read about actions at the [Cerebral Repo - Actions](https://github.com/christianalfoni/cerebral#how-to-get-started). You can also watch [a video on signals](https://www.youtube.com/watch?v=zkeBjGdn7uM) to get an overview of how it works.

Typically you would create your signals in the *main.js* file, but you can split them out as you see fit.

*main.js*
```js
import React from 'react';
import AppComponent from './AppComponent.js';
import controller from './controller.js';

import setLoading from './actions/setLoading.js';
import saveForm from './actions/saveForm.js';
import unsetLoading from './actions/unsetLoading.js';

controller.signal('formSubmitted', setLoading, [saveForm], unsetLoading);

React.render(controller.injectInto(AppComponent), document.body);
```

### Get state in components

#### Decorator
```js
import React from 'react';
import {Decorator as Cerebral} from 'cerebral-react-immutable-store';

@Cerebral({
  isLoading: ['isLoading'],
  user: ['user'],
  error: ['error']
})
class App extends React.Component {
  componentDidMount() {
    this.props.signals.appMounted();
  }
  render() {
    return (
      <div>
        {this.props.isLoading ? 'Loading...' : 'hello ' + this.props.user.name}
        {this.props.error ? this.props.error : null}
      </div>
    );
  }
}
```

#### Higher Order Component
```js
import React from 'react';
import {HOC} from 'cerebral-react-immutable-store';

class App extends React.Component {
  componentDidMount() {
    this.props.signals.appMounted();
  }
  render() {
    return (
      <div>
        {this.props.isLoading ? 'Loading...' : 'hello ' + this.props.user.name}
        {this.props.error ? this.props.error : null}
      </div>
    );
  }
}

App = HOC(App, {
  isLoading: ['isLoading'],
  user: ['user'],
  error: ['error']
});
```

#### Mixin
```js
import React from 'react';
import {Mixin} from 'cerebral-react-immutable-store';

const App = React.createClass({
  mixins: [Mixin],
  getStatePaths() {
    return {
      isLoading: ['isLoading'],
      user: ['user'],
      error: ['error']
    };
  },
  componentDidMount() {
    this.props.signals.appMounted();
  },
  render() {
    return (
      <div>
        {this.state.isLoading ? 'Loading...' : 'hello ' + this.state.user.name}
        {this.state.error ? this.state.error : null}
      </div>
    );
  }
});
```

### Recording
```js
import React from 'react';
import {Decorator as Cerebral} from 'cerebral-react-immutable-store';

@Cerebral()
class App extends React.Component {
  record() {
    this.props.recorder.record();
  }
  record() {
    this.props.recorder.stop();
  }
  play() {
    this.props.recorder.seek(0, true);
  }
  render() {
    return (
      <div>
        <button onClick={() => this.record()}>Record</button>
        <button onClick={() => this.stop()}>Stop</button>
        <button onClick={() => this.play()}>Play</button>
      </div>
    );
  }
}
```

### Listening to changes
You can manually listen to changes on the controller, in case you want to explore [reactive-router](https://github.com/christianalfoni/reactive-router) for example.

*main.js*
```js
...
const onChange = function (state) {
  state // New state
};
controller.eventEmitter.on('change', onChange);
controller.eventEmitter.removeListener('change', onChange);

// When debugger traverses state
controller.eventEmitter.on('remember', onChange);
controller.eventEmitter.removeListener('remember', onChange);
```

### Listening to errors
You can listen to errors in the controller. Now, Cerebral helps you a lot to avoid errors, but there are probably scenarios you did not consider. By using the error event you can indicate messages to the user and pass these detailed error messages to a backend service. This lets you quickly fix bugs in production.

*main.js*
```js
...
const onError = function (error) {
  controller.signals.errorOccured({error: error.message});
  myErrorService.post(error);
};
controller.eventEmitter.on('error', onError);
```


text:
'use strict';

// Define the `phoneList` module
angular.module('projectList', ['service.projectList']);

// Register `phoneList` component, along with its associated controller and template
angular.module('projectList').component('projectList', {
  templateUrl: 'view/project-list/project-list.template.html',
  controller: [
    'ProjectList', '$rootScope', '$location', '$http', '$sce', '$window',
    function ProjectListController(ProjectList, $rootScope, $location, $http, $sce, $window) {
      var self = this;
      this.projectList = [];
      this.orderProp = 'id';
      this.total_count = 0;
      this.offset = 0;
      this.limit = 10;

      if (!($rootScope.redmineConnectionString)) $location.url('/autorization');

      this.getProjectList = function () {
        if (!($rootScope.redmineConnectionString)) return;
        //var url = $rootScope.redmineConnectionString + 'projects.json?offset=0&limit=4&callback=JSON_CALLBACK';
        var url = $rootScope.redmineConnectionString + 'projects.json?offset=' + self.offset + '&limit=' + +self.limit;
        var c = $window.angular.callbacks.$$counter.toString(36);
        $window['angularcallbacks_' + c] = function (data) {
          $window.angular.callbacks['_' + c](data);
          delete $window['angularcallbacks_' + c];
        };
        $http.jsonp(url, {params: {callback: "JSON_CALLBACK"}}).then(function (response) {
          console.log(response);
          self.projectList = response.data.projects;
          self.total_count = response.data.total_count;
          self.offset = response.data.offset;
          self.limit = response.data.limit;
        });
      };
      this.getProjectList();

      this.prevPageClick = function () {
        //event.preventDefault();
        if(self.offset <= 0) return;
        self.offset -= self.limit;
        self.offset = self.offset > 0 ? self.offset : 0;
        this.getProjectList();
      }

      this.nextPageClick = function () {
        //event.preventDefault();
        if(self.offset >= self.total_count) return;
        self.offset += self.limit;
        self.offset = self.offset <= self.total_count ? self.offset : self.total_count;
        this.getProjectList();
      }

    }
  ]
});


text:
{% load sass_tags %}

    <title>Toga Web Sample Application</title>
    <link href="{% sass_src 'sass/css/site.scss' %}" rel="stylesheet" type="text/css" />

Toga Web Sample Application

      {% block content %}
      {% endblock %}


text:
<?php

namespace Theseus\Bundle\ApplicationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use JMS\SecurityExtraBundle\Annotation\Secure;

use Theseus\Bundle\CoreBundle\Entity\User;
use Theseus\Bundle\CoreBundle\Entity\Group;

/**
 * @package Theseus\Bundle\ApplicationBundle\Controller
 */
class MainController extends Controller
{
    /**
     * Display the home page
     *
     * @Secure(roles="ROLE_ADMIN")
     * @Route("/")
     */
    public function indexAction()
    {
        $user = $this->get('security.context')->getToken()->getUser();

        $array = [
            'test' => 245,
            'user' => $user
        ];

        return new JsonResponse($array);
    }
}


text: Sistema Login do curso de POO com Python3


text:
DynamicLevelCommand::DynamicLevelCommand()
{
	Requires(Robot::elevator);
	// Use Requires() here to declare subsystem dependencies
	// eg. Requires(chassis);
}

// Called just before this Command runs the first time
void DynamicLevelCommand::Initialize()
{

}

// Called repeatedly when this Command is scheduled to run
void DynamicLevelCommand::Execute()
{
	Robot::elevator->SetSetpointRelative(Robot::oi->manipulator->GetRawAxis(1) *-1 *Robot::elevator->kLevelInterval);
}

// Make this return true when this Command no longer needs to run execute()
bool DynamicLevelCommand::IsFinished()
{
	return true;
}

// Called once after isFinished returns true
void DynamicLevelCommand::End()
{

}

// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void DynamicLevelCommand::Interrupted()
{

}


text:
/**
 * $Id: tcpconnectiontf.h 15849 2009-01-04 12:09:57Z hua.huangrh $
 */

#ifndef TCPCONNECTIONTF_H_
#define TCPCONNECTIONTF_H_
#include <cppunit/extensions/HelperMacros.h>
#include <anet/anet.h>
#include <anet/serversocket.h>
#include <anet/tcpconnection.h>

namespace anet {
class ConnPacketFactory;
class DefaultPacketStreamer;
class DefaultPacketHandler;

class TCPCONNECTIONTF : public CppUnit::TestFixture {
    CPPUNIT_TEST_SUITE(TCPCONNECTIONTF);
    CPPUNIT_TEST(testLock);
    CPPUNIT_TEST(testWriteData);
    CPPUNIT_TEST(testReadData);
    CPPUNIT_TEST(testClose);
    CPPUNIT_TEST(testMemLeak);
    CPPUNIT_TEST(testReadMaliciousDataTooLarge);
    CPPUNIT_TEST(testReadMaliciousDataInfinitLoop);
    CPPUNIT_TEST_SUITE_END();
public:
    void setUp();
    void tearDown();
    void testWriteData();
    void testReadData();
    void testClose();
    void testLock();
    void testMemLeak();
    void testReadMaliciousDataTooLarge();
    void testReadMaliciousDataInfinitLoop();

    TCPCONNECTIONTF();
    ~TCPCONNECTIONTF();
private:
    int getListCountFromHead(IOComponent *);
    ConnPacketFactory *_factory;
    DefaultPacketStreamer *_streamer;
    DefaultPacketHandler *_handler;

    Transport *_transport;
    ServerSocket *_server;
    Socket *_accept;
    TCPConnection *_conn;
};
}

#endif /*TCPCONNECTIONTF_H_*/


text:
import datetime
from copy import deepcopy
from dateutil.relativedelta import relativedelta
from .models import Booking, Room, RequestedBooking
from dmutex.debug import CollisionException
from django.test import TestCase

class MetaClassOptions(TestCase):
    def setUp(self):
        now = datetime.datetime.now()
        self.room = Room.objects.create(name='Room')
        self.living_room = Room.objects.create(name='Living room', can_parallel=True)
        self.booking1 = Booking(start_time=datetime.datetime.now(),
                                end_time=now + relativedelta(days=1),
                                room=self.room)
        self.booking1.save()
        self.booking2 = Booking(start_time=datetime.datetime.now(),
                                end_time=now + relativedelta(days=1),
                                room=self.living_room)
        self.booking2.save()

    def test_duplicate_save(self):
        ### Normal room can't be re-booked
        self.booking1.id = None
        self.assertRaises(CollisionException, lambda: self.booking1.save())
        ### Living room can be re-booked
        booking3 = deepcopy(self.booking2)
        booking3.pk = None
        booking3.save()
        self.assertEqual(booking3.start_time, self.booking2.start_time)
        self.assertEqual(booking3.end_time, self.booking2.end_time)

    def test_delete(self):
        self.booking1.deleted_at = datetime.datetime.now()
        self.booking1.save()
        booking3 = deepcopy(self.booking1)
        booking3.id = None
        booking3.save()
        self.assertEqual(booking3.start_time, self.booking1.start_time)
        self.assertEqual(booking3.end_time, self.booking1.end_time)
        self.assertEqual(booking3.room, self.booking1.room)

    def test_collision_is_blank(self):
        start = datetime.datetime.now()
        end = start + relativedelta(days=1)
        rb1 = RequestedBooking(request='room', start_time=start, end_time=end)
        rb1.save()
        rb2 = deepcopy(rb1)
        rb2.pk = None
        rb2.save()
        self.assertEqual(rb1.start_time, rb2.start_time)
        self.assertEqual(rb1.end_time, rb2.end_time)
        self.assertNotEqual(rb1.pk, rb2.pk)
        rb1.room = Room.objects.get(pk=1)
        rb2.room = Room.objects.get(pk=1)
        rb1.save()
        self.assertRaises(CollisionException, lambda: rb2.save())


text:
package org.lwjgl.vulkan;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * See {@link VkSemaphoreSubmitInfo}.
 *
 *
Layout

 *
 *

 * struct VkSemaphoreSubmitInfoKHR {
 *     VkStructureType sType;
 *     void const * pNext;
 *     VkSemaphore semaphore;
 *     uint64_t value;
 *     VkPipelineStageFlags2 stageMask;
 *     uint32_t deviceIndex;
 * }

 */
public class VkSemaphoreSubmitInfoKHR extends VkSemaphoreSubmitInfo {

    /**
     * Creates a {@code VkSemaphoreSubmitInfoKHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public VkSemaphoreSubmitInfoKHR(ByteBuffer container) {
        super(container);
    }

    /** Sets the specified value to the {@code sType} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
    /** Sets the {@link VK13#VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO} value to the {@code sType} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR sType$Default() { return sType(VK13.VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO); }
    /** Sets the specified value to the {@code pNext} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; }
    /** Sets the specified value to the {@code semaphore} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR semaphore(@NativeType("VkSemaphore") long value) { nsemaphore(address(), value); return this; }
    /** Sets the specified value to the {@code value} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR value(@NativeType("uint64_t") long value) { nvalue(address(), value); return this; }
    /** Sets the specified value to the {@code stageMask} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR stageMask(@NativeType("VkPipelineStageFlags2") long value) { nstageMask(address(), value); return this; }
    /** Sets the specified value to the {@code deviceIndex} field. */
    @Override
    public VkSemaphoreSubmitInfoKHR deviceIndex(@NativeType("uint32_t") int value) { ndeviceIndex(address(), value); return this; }

    /** Initializes this struct with the specified values. */
    @Override
    public VkSemaphoreSubmitInfoKHR set(
        int sType,
        long pNext,
        long semaphore,
        long value,
        long stageMask,
        int deviceIndex
    ) {
        sType(sType);
        pNext(pNext);
        semaphore(semaphore);
        value(value);
        stageMask(stageMask);
        deviceIndex(deviceIndex);

        return this;
    }

    /**
     * Copies the specified struct data to this struct.
     *
     * @param src the source struct
     *
     * @return this struct
     */
    public VkSemaphoreSubmitInfoKHR set(VkSemaphoreSubmitInfoKHR src) {
        memCopy(src.address(), address(), SIZEOF);
        return this;
    }

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

    /** Returns a new {@code VkSemaphoreSubmitInfoKHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
    public static VkSemaphoreSubmitInfoKHR malloc() {
        return wrap(VkSemaphoreSubmitInfoKHR.class, nmemAllocChecked(SIZEOF));
    }

    /** Returns a new {@code VkSemaphoreSubmitInfoKHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
    public static VkSemaphoreSubmitInfoKHR calloc() {
        return wrap(VkSemaphoreSubmitInfoKHR.class, nmemCallocChecked(1, SIZEOF));
    }

    /** Returns a new {@code VkSemaphoreSubmitInfoKHR} instance allocated with {@link BufferUtils}. */
    public static VkSemaphoreSubmitInfoKHR create() {
        ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
        return wrap(VkSemaphoreSubmitInfoKHR.class, memAddress(container), container);
    }

    /** Returns a new {@code VkSemaphoreSubmitInfoKHR} instance for the specified memory address. */
    public static VkSemaphoreSubmitInfoKHR create(long address) {
        return wrap(VkSemaphoreSubmitInfoKHR.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VkSemaphoreSubmitInfoKHR createSafe(long address) {
        return address == NULL ? null : wrap(VkSemaphoreSubmitInfoKHR.class, address);
    }

    /**
     * Returns a new {@link VkSemaphoreSubmitInfoKHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreSubmitInfoKHR.Buffer malloc(int capacity) {
        return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
    }

    /**
     * Returns a new {@link VkSemaphoreSubmitInfoKHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreSubmitInfoKHR.Buffer calloc(int capacity) {
        return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
    }

    /**
     * Returns a new {@link VkSemaphoreSubmitInfoKHR.Buffer} instance allocated with {@link BufferUtils}.
     *
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreSubmitInfoKHR.Buffer create(int capacity) {
        ByteBuffer container = __create(capacity, SIZEOF);
        return wrap(Buffer.class, memAddress(container), capacity, container);
    }

    /**
     * Create a {@link VkSemaphoreSubmitInfoKHR.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreSubmitInfoKHR.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VkSemaphoreSubmitInfoKHR.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

    /**
     * Returns a new {@code VkSemaphoreSubmitInfoKHR} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack the stack from which to allocate
     */
    public static VkSemaphoreSubmitInfoKHR malloc(MemoryStack stack) {
        return wrap(VkSemaphoreSubmitInfoKHR.class, stack.nmalloc(ALIGNOF, SIZEOF));
    }

    /**
     * Returns a new {@code VkSemaphoreSubmitInfoKHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack the stack from which to allocate
     */
    public static VkSemaphoreSubmitInfoKHR calloc(MemoryStack stack) {
        return wrap(VkSemaphoreSubmitInfoKHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
    }

    /**
     * Returns a new {@link VkSemaphoreSubmitInfoKHR.Buffer} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreSubmitInfoKHR.Buffer malloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
    }

    /**
     * Returns a new {@link VkSemaphoreSubmitInfoKHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreSubmitInfoKHR.Buffer calloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
    }

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

    /** An array of {@link VkSemaphoreSubmitInfoKHR} structs. */
    public static class Buffer extends VkSemaphoreSubmitInfo.Buffer {

        private static final VkSemaphoreSubmitInfoKHR ELEMENT_FACTORY = VkSemaphoreSubmitInfoKHR.create(-1L);

        /**
         * Creates a new {@code VkSemaphoreSubmitInfoKHR.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link VkSemaphoreSubmitInfoKHR#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected VkSemaphoreSubmitInfoKHR getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** Sets the specified value to the {@code sType} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer sType(@NativeType("VkStructureType") int value) { VkSemaphoreSubmitInfoKHR.nsType(address(), value); return this; }
        /** Sets the {@link VK13#VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO} value to the {@code sType} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer sType$Default() { return sType(VK13.VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO); }
        /** Sets the specified value to the {@code pNext} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer pNext(@NativeType("void const *") long value) { VkSemaphoreSubmitInfoKHR.npNext(address(), value); return this; }
        /** Sets the specified value to the {@code semaphore} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer semaphore(@NativeType("VkSemaphore") long value) { VkSemaphoreSubmitInfoKHR.nsemaphore(address(), value); return this; }
        /** Sets the specified value to the {@code value} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer value(@NativeType("uint64_t") long value) { VkSemaphoreSubmitInfoKHR.nvalue(address(), value); return this; }
        /** Sets the specified value to the {@code stageMask} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer stageMask(@NativeType("VkPipelineStageFlags2") long value) { VkSemaphoreSubmitInfoKHR.nstageMask(address(), value); return this; }
        /** Sets the specified value to the {@code deviceIndex} field. */
        @Override
        public VkSemaphoreSubmitInfoKHR.Buffer deviceIndex(@NativeType("uint32_t") int value) { VkSemaphoreSubmitInfoKHR.ndeviceIndex(address(), value); return this; }

    }

}