text:
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;

namespace S11Context
{

    /// <summary>
    /// График выполнения лекарственных назначений (Процедурный лист
    /// </summary>
    [Table(Name = @"s11.DrugDestinationSchedule")]
    public partial class DrugDestinationSchedule : INotifyPropertyChanging, INotifyPropertyChanged
    {

        private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(System.String.Empty);

        private int _Id;

        private System.DateTime _TakeDatetime;

        private int _ActionId;

        private double _TakeDose;

        private string _TakeDuration;

        private sbyte _Status;

        private System.Nullable<int> _ExecPersonId;

        private string _Note;

        private string _CancelReason = @"";

        private System.Nullable<int> _NomenclatureId;

        private bool _Deleted;

        private EntityRef<Action> _Action;

        private EntityRef<RbStockNomenclature> _RbStockNomenclature;

        private EntityRef<Person> _Person;

        #region Extensibility Method Definitions
        partial void OnLoaded();
        partial void OnValidate(System.Data.Linq.ChangeAction action);
        partial void OnCreated();
        partial void OnIdChanging(int value);
        partial void OnIdChanged();
        partial void OnTakeDatetimeChanging(System.DateTime value);
        partial void OnTakeDatetimeChanged();
        partial void OnActionIdChanging(int value);
        partial void OnActionIdChanged();
        partial void OnTakeDoseChanging(double value);
        partial void OnTakeDoseChanged();
        partial void OnTakeDurationChanging(string value);
        partial void OnTakeDurationChanged();
        partial void OnStatusChanging(sbyte value);
        partial void OnStatusChanged();
        partial void OnExecPersonIdChanging(System.Nullable<int> value);
        partial void OnExecPersonIdChanged();
        partial void OnNoteChanging(string value);
        partial void OnNoteChanged();
        partial void OnCancelReasonChanging(string value);
        partial void OnCancelReasonChanged();
        partial void OnNomenclatureIdChanging(System.Nullable<int> value);
        partial void OnNomenclatureIdChanged();
        partial void OnDeletedChanging(bool value);
        partial void OnDeletedChanged();
        #endregion

        public DrugDestinationSchedule()
        {
            this._Action  = default(EntityRef<Action>);
            this._RbStockNomenclature  = default(EntityRef<RbStockNomenclature>);
            this._Person  = default(EntityRef<Person>);
            OnCreated();
        }

        /// <summary>
        /// There are no comments for Id in the schema.
        /// </summary>
        [Column(Name = @"id", Storage = "_Id", AutoSync = AutoSync.OnInsert, CanBeNull = false, DbType = "INT(10) NOT NULL AUTO_INCREMENT", IsDbGenerated = true, IsPrimaryKey = true)]
        public int Id
        {
            get
            {
                return this._Id;
            }
            set
            {
                if (this._Id != value)
                {
                    this.OnIdChanging(value);
                    this.SendPropertyChanging();
                    this._Id = value;
                    this.SendPropertyChanged("Id");
                    this.OnIdChanged();
                }
            }
        }

        /// <summary>
        /// Дата и время приема
        /// </summary>
        [Column(Name = @"takeDatetime", Storage = "_TakeDatetime", CanBeNull = false, DbType = "DATETIME NOT NULL")]
        public System.DateTime TakeDatetime
        {
            get
            {
                return this._TakeDatetime;
            }
            set
            {
                if (this._TakeDatetime != value)
                {
                    this.OnTakeDatetimeChanging(value);
                    this.SendPropertyChanging();
                    this._TakeDatetime = value;
                    this.SendPropertyChanged("TakeDatetime");
                    this.OnTakeDatetimeChanged();
                }
            }
        }

        /// <summary>
        /// Ссылка на назначение {Action}
        /// </summary>
        [Column(Name = @"action_id", Storage = "_ActionId", CanBeNull = false, DbType = "INT(10) NOT NULL")]
        public int ActionId
        {
            get
            {
                return this._ActionId;
            }
            set
            {
                if (this._ActionId != value)
                {
                    if (this._Action.HasLoadedOrAssignedValue)
                    {
                        throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
                    }

                    this.OnActionIdChanging(value);
                    this.SendPropertyChanging();
                    this._ActionId = value;
                    this.SendPropertyChanged("ActionId");
                    this.OnActionIdChanged();
                }
            }
        }

        /// <summary>
        /// Доза приёма
        /// </summary>
        [Column(Name = @"takeDose", Storage = "_TakeDose", CanBeNull = false, DbType = "DOUBLE(22) NOT NULL")]
        public double TakeDose
        {
            get
            {
                return this._TakeDose;
            }
            set
            {
                if (this._TakeDose != value)
                {
                    this.OnTakeDoseChanging(value);
                    this.SendPropertyChanging();
                    this._TakeDose = value;
                    this.SendPropertyChanged("TakeDose");
                    this.OnTakeDoseChanged();
                }
            }
        }

        /// <summary>
        /// There are no comments for TakeDuration in the schema.
        /// </summary>
        [Column(Name = @"takeDuration", Storage = "_TakeDuration", CanBeNull = false, DbType = "VARCHAR(255) NOT NULL")]
        public string TakeDuration
        {
            get
            {
                return this._TakeDuration;
            }
            set
            {
                if (this._TakeDuration != value)
                {
                    this.OnTakeDurationChanging(value);
                    this.SendPropertyChanging();
                    this._TakeDuration = value;
                    this.SendPropertyChanged("TakeDuration");
                    this.OnTakeDurationChanged();
                }
            }
        }

        /// <summary>
        /// Статус(0-еще не выполнено,1-выполнено,2-отмена)
        /// </summary>
        [Column(Name = @"status", Storage = "_Status", CanBeNull = false, DbType = "TINYINT(4) NOT NULL")]
        public sbyte Status
        {
            get
            {
                return this._Status;
            }
            set
            {
                if (this._Status != value)
                {
                    this.OnStatusChanging(value);
                    this.SendPropertyChanging();
                    this._Status = value;
                    this.SendPropertyChanged("Status");
                    this.OnStatusChanged();
                }
            }
        }

        /// <summary>
        /// Медсестра, выполнившая действие
        /// </summary>
        [Column(Name = @"execPerson_id", Storage = "_ExecPersonId", DbType = "INT(10)")]
        public System.Nullable<int> ExecPersonId
        {
            get
            {
                return this._ExecPersonId;
            }
            set
            {
                if (this._ExecPersonId != value)
                {
                    if (this._Person.HasLoadedOrAssignedValue)
                    {
                        throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
                    }

                    this.OnExecPersonIdChanging(value);
                    this.SendPropertyChanging();
                    this._ExecPersonId = value;
                    this.SendPropertyChanged("ExecPersonId");
                    this.OnExecPersonIdChanged();
                }
            }
        }

        /// <summary>
        /// Отметка о невыполнении
        /// </summary>
        [Column(Name = @"note", Storage = "_Note", CanBeNull = false, DbType = "VARCHAR(255) NOT NULL")]
        public string Note
        {
            get
            {
                return this._Note;
            }
            set
            {
                if (this._Note != value)
                {
                    this.OnNoteChanging(value);
                    this.SendPropertyChanging();
                    this._Note = value;
                    this.SendPropertyChanged("Note");
                    this.OnNoteChanged();
                }
            }
        }

        /// <summary>
        /// There are no comments for CancelReason in the schema.
        /// </summary>
        [Column(Name = @"cancel_reason", Storage = "_CancelReason", CanBeNull = false, DbType = "VARCHAR(255) NOT NULL")]
        public string CancelReason
        {
            get
            {
                return this._CancelReason;
            }
            set
            {
                if (this._CancelReason != value)
                {
                    this.OnCancelReasonChanging(value);
                    this.SendPropertyChanging();
                    this._CancelReason = value;
                    this.SendPropertyChanged("CancelReason");
                    this.OnCancelReasonChanged();
                }
            }
        }

        /// <summary>
        /// Ссылка на номенклатурное наименование лекарственного средства.
        /// </summary>
        [Column(Name = @"nomenclature_id", Storage = "_NomenclatureId", DbType = "INT(10)")]
        public System.Nullable<int> NomenclatureId
        {
            get
            {
                return this._NomenclatureId;
            }
            set
            {
                if (this._NomenclatureId != value)
                {
                    if (this._RbStockNomenclature.HasLoadedOrAssignedValue)
                    {
                        throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
                    }

                    this.OnNomenclatureIdChanging(value);
                    this.SendPropertyChanging();
                    this._NomenclatureId = value;
                    this.SendPropertyChanged("NomenclatureId");
                    this.OnNomenclatureIdChanged();
                }
            }
        }

        /// <summary>
        /// Удалённые приёмы
        /// </summary>
        [Column(Name = @"deleted", Storage = "_Deleted", CanBeNull = false, DbType = "TINYINT(1) NOT NULL")]
        public bool Deleted
        {
            get
            {
                return this._Deleted;
            }
            set
            {
                if (this._Deleted != value)
                {
                    this.OnDeletedChanging(value);
                    this.SendPropertyChanging();
                    this._Deleted = value;
                    this.SendPropertyChanged("Deleted");
                    this.OnDeletedChanged();
                }
            }
        }

        /// <summary>
        /// There are no comments for Action in the schema.
        /// </summary>
        [Devart.Data.Linq.Mapping.Association(Name="Action_DrugDestinationSchedule", Storage="_Action", ThisKey="ActionId", IsForeignKey=true)]
        public Action Action
        {
            get
            {
                return this._Action.Entity;
            }
            set
            {
                Action previousValue = this._Action.Entity;
                if ((previousValue != value) || (this._Action.HasLoadedOrAssignedValue == false))
                {
                    this.SendPropertyChanging();
                    if (previousValue != null)
                    {
                        this._Action.Entity = null;
                        previousValue.DrugDestinationSchedules.Remove(this);
                    }
                    this._Action.Entity = value;
                    if (value != null)
                    {
                        this._ActionId = value.Id;
                        value.DrugDestinationSchedules.Add(this);
                    }
                    else
                    {
                        this._ActionId = default(int);
                    }
                    this.SendPropertyChanged("Action");
                }
            }
        }

        /// <summary>
        /// There are no comments for RbStockNomenclature in the schema.
        /// </summary>
        [Devart.Data.Linq.Mapping.Association(Name="RbStockNomenclature_DrugDestinationSchedule", Storage="_RbStockNomenclature", ThisKey="NomenclatureId", IsForeignKey=true)]
        public RbStockNomenclature RbStockNomenclature
        {
            get
            {
                return this._RbStockNomenclature.Entity;
            }
            set
            {
                RbStockNomenclature previousValue = this._RbStockNomenclature.Entity;
                if ((previousValue != value) || (this._RbStockNomenclature.HasLoadedOrAssignedValue == false))
                {
                    this.SendPropertyChanging();
                    if (previousValue != null)
                    {
                        this._RbStockNomenclature.Entity = null;
                        previousValue.DrugDestinationSchedules.Remove(this);
                    }
                    this._RbStockNomenclature.Entity = value;
                    if (value != null)
                    {
                        this._NomenclatureId = value.Id;
                        value.DrugDestinationSchedules.Add(this);
                    }
                    else
                    {
                        this._NomenclatureId = default(System.Nullable<int>);
                    }
                    this.SendPropertyChanged("RbStockNomenclature");
                }
            }
        }

        /// <summary>
        /// There are no comments for Person in the schema.
        /// </summary>
        [Devart.Data.Linq.Mapping.Association(Name="Person_DrugDestinationSchedule", Storage="_Person", ThisKey="ExecPersonId", IsForeignKey=true)]
        public Person Person
        {
            get
            {
                return this._Person.Entity;
            }
            set
            {
                Person previousValue = this._Person.Entity;
                if ((previousValue != value) || (this._Person.HasLoadedOrAssignedValue == false))
                {
                    this.SendPropertyChanging();
                    if (previousValue != null)
                    {
                        this._Person.Entity = null;
                        previousValue.DrugDestinationSchedules.Remove(this);
                    }
                    this._Person.Entity = value;
                    if (value != null)
                    {
                        this._ExecPersonId = value.Id;
                        value.DrugDestinationSchedules.Add(this);
                    }
                    else
                    {
                        this._ExecPersonId = default(System.Nullable<int>);
                    }
                    this.SendPropertyChanged("Person");
                }
            }
        }

        public event PropertyChangingEventHandler PropertyChanging;

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void SendPropertyChanging()
        {
            if (this.PropertyChanging != null)
                this.PropertyChanging(this, emptyChangingEventArgs);
        }

        protected virtual void SendPropertyChanging(System.String propertyName)
        {
            if (this.PropertyChanging != null)
                this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }

        protected virtual void SendPropertyChanged(System.String propertyName)
        {
             if (this.PropertyChanged != null)
                 this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}


text:
package net.qiujuer.sample.constraintlayout;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_done);
    }
}

redpajama_set_name: RedPajamaGithub


text:
@extends('layouts.master-admin')
@section('title', 'Editar Administrador')
@section('description', 'Administradores Empleo Abierto del Gobierno del Estado de Puebla')
@section('bodyclass', 'users')
@section('breadcrumb', 'layouts.breadcrumb')
@section('breadcrumb_a', 'user-update')

@section('content')

Editar Administrador

	{!! Form::model($admin, ['url' => "dashboard/administrador/editar/{$admin->id}", "class" => "form-horizontal"]) !!}

	  Nombre
	  {{Form::text('name', null, ["class" => "form-control"])}}
	  @if($errors->has('name'))
	    {{$errors->first('name')}}
	  @endif

	  Correo
	  {{Form::text('email', null, ["class" => "form-control"])}}
	  @if($errors->has('email'))
	    {{$errors->first('email')}}
	  @endif

	  Contraseña
	  {{Form::password('password', ['class' => 'form-control'])}}
	  @if($errors->has('password'))
	    {{$errors->first('password')}}
	  @endif

{{Form::submit('Actualizar', ['class' => 'btn'])}}

	{!! Form::close() !!}

@endsection


text:
package com.hazelcast.partition;

import com.hazelcast.cluster.Member;

import javax.annotation.Nonnull;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * PartitionService allows you to query {@link Partition}s and attach/detach {@link MigrationListener}s to listen to partition
 * migration events.
 *

 * The methods on the PartitionService are thread-safe.
 *
 * @see Partition
 * @see MigrationListener
 * @see PartitionLostListener
 */
public interface PartitionService {

    /**
     * Returns a set containing all the {@link Partition}s in the cluster.
     *
     * @return all partitions in the cluster
     */
    Set<Partition> getPartitions();

    /**
     * Returns the partition that the given key belongs to.
     *
     * @param key the given key
     * @return the partition that the given key belongs to
     */
    Partition getPartition(@Nonnull Object key);

    /**
     * Adds a MigrationListener.
     *

     * The addMigrationListener returns a register ID. This ID is needed to remove the MigrationListener using the
     * {@link #removeMigrationListener(UUID)} method.
     *

     * There is no check for duplicate registrations, so if you register the listener twice, it will get events twice.
     *
     * @param migrationListener the added MigrationListener
     * @return returns the registration ID for the MigrationListener
     * @throws java.lang.NullPointerException if migrationListener is {@code null}
     * @throws UnsupportedOperationException  if this operation isn't supported. For example on the client side it isn't possible
     *                                        to add a MigrationListener
     * @see #removeMigrationListener(UUID)
     */
    UUID addMigrationListener(MigrationListener migrationListener);

    /**
     * Removes a MigrationListener.
     *

     * If the same MigrationListener is registered multiple times, it needs to be removed multiple times.
     *

     * This method can safely be called multiple times for the same registration ID; every subsequent call is just ignored.
     *
     * @param registrationId the registration ID of the listener to remove
     * @return {@code true} if the listener is removed, {@code false} otherwise
     * @throws java.lang.NullPointerException if registration ID is {@code null}
     * @throws UnsupportedOperationException  if this operation isn't supported, e.g. on the client side it isn't possible
     *                                        to add/remove a MigrationListener
     * @see #addMigrationListener(MigrationListener)
     */
    boolean removeMigrationListener(UUID registrationId);

    /**
     * Adds a PartitionLostListener.
     *

     * The addPartitionLostListener returns a registration ID. This ID is needed to remove the PartitionLostListener using the
     * {@link #removePartitionLostListener(UUID)} method.
     *

     * There is no check for duplicate registrations, so if you register the listener twice, it will get events twice.
     * IMPORTANT: Please @see com.hazelcast.partition.PartitionLostListener for weaknesses
     *
     * @param partitionLostListener the added PartitionLostListener
     * @return returns the registration ID for the PartitionLostListener
     * @throws java.lang.NullPointerException if partitionLostListener is {@code null}
     * @see #removePartitionLostListener(UUID)
     */
    UUID addPartitionLostListener(PartitionLostListener partitionLostListener);

    /**
     * Removes a PartitionLostListener.
     *

     * If the same PartitionLostListener is registered multiple times, it needs to be removed multiple times.
     *

     * This method can safely be called multiple times for the same registration ID; every subsequent call is just ignored.
     *
     * @param registrationId the registration ID of the listener to remove
     * @return {@code true} if the listener is removed, {@code false} otherwise
     * @throws java.lang.NullPointerException if registration ID is {@code null}
     * @see #addPartitionLostListener(PartitionLostListener)
     */
    boolean removePartitionLostListener(UUID registrationId);

    /**
     * Checks whether the cluster is in a safe state.
     *

     * Safe state means; there are no partitions being migrated and all backups are in sync
     * when this method is called.
     *
     * @return {@code true} if there are no partitions being migrated and all backups are in sync, {@code false} otherwise
     * @since 3.3
     */
    boolean isClusterSafe();

    /**
     * Checks whether the given member is in safe state.
     *

     * Safe state means; all backups of partitions currently owned by the member are in sync when this method is called.
     *
     * @param member the cluster member to query
     * @return {@code true} if the member is in a safe state, {@code false} otherwise
     * @since 3.3
     */
    boolean isMemberSafe(Member member);

    /**
     * Checks whether local member is in safe state.
     *

     * Safe state means; all backups of partitions currently owned by local member are in sync when this method is called.
     *
     * @since 3.3
     */
    boolean isLocalMemberSafe();

    /**
     * Force the local member to be safe by checking and syncing partitions owned by the local member
     * with at least one of the backups.
     *
     * @param timeout the time limit for checking/syncing with the backup
     * @param unit    the unit of time for timeout
     * @since 3.3
     */
    boolean forceLocalMemberToBeSafe(long timeout, TimeUnit unit);
}


text:
include!(concat!(env!("OUT_DIR"), "/generated/generated.rs"));

pub fn say_hello_from_crate() {
    assert_eq!(run_some_generated_code(), 42);
    #[cfg(is_new_rustc)]
    println!("Is new rustc!");
    #[cfg(is_old_rustc)]
    println!("Is old rustc!");
    #[cfg(is_android)]
    println!("Is android!");
    #[cfg(is_mac)]
    println!("Is darwin!");
    #[cfg(has_feature_a)]
    println!("Has feature A!");
    #[cfg(not(has_feature_a))]
    panic!("Wasn't passed feature a");
    #[cfg(not(has_feature_b))]
    #[cfg(test_a_and_b)]
    panic!("Wasn't passed feature b");
    #[cfg(has_feature_b)]
    #[cfg(not(test_a_and_b))]
    panic!("Was passed feature b");
}

#[cfg(test)]
mod tests {
    /// Test features are passed through from BUILD.gn correctly. This test is the target1
    /// configuration.
    #[test]
    #[cfg(test_a_and_b)]
    fn test_features_passed_target1() {
        #[cfg(not(has_feature_a))]
        panic!("Wasn't passed feature a");
        #[cfg(not(has_feature_b))]
        panic!("Wasn't passed feature b");
    }

    /// This tests the target2 configuration is passed through correctly.
    #[test]
    #[cfg(not(test_a_and_b))]
    fn test_features_passed_target2() {
        #[cfg(not(has_feature_a))]
        panic!("Wasn't passed feature a");
        #[cfg(has_feature_b)]
        panic!("Was passed feature b");
    }

    #[test]
    fn test_generated_code_works() {
        assert_eq!(crate::run_some_generated_code(), 42);
    }
}


text:
--TEST--
Send a request and display the URL we requested.

--FILE--
<?php
	require_once dirname(__FILE__) . '/../requestcore.class.php';
	$http = new RequestCore();
	$http->set_request_url('http://github.com/skyzyx/requestcore/raw/master/_tests/test_request.txt');
	$http->send_request();

	var_dump($http->response_info['url']);

	/*#block:["require_once"]*/
?>

--EXPECT--
string(71) "http://github.com/skyzyx/requestcore/raw/master/_tests/test_request.txt"


text:
cask :v1 => 'sourcetree' do
  if MacOS.release <= :snow_leopard
    version '1.8.1'
    sha256 '37a42f2d83940cc7e1fbd573a70c3c74a44134c956ac3305f6b153935dc01b80'
  else
    version '2.0.5.2'
    sha256 '106531ed0087403020a2ba07efaaf1ce297734eb62e2a0eaea8cd5f88e18e7cb'
  end

  # atlassian.com is the official download host per the vendor homepage
  url "https://downloads.atlassian.com/software/sourcetree/SourceTree_#{version}.dmg"
  appcast 'http://www.sourcetreeapp.com/update/SparkleAppcast.xml',
          :sha256 => 'b43e0ea95de46d2c270cdbf9765e03ec3f13606cbf0bab5bcd3da0424ce2cff3'
  name 'SourceTree'
  homepage 'http://www.sourcetreeapp.com/'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
  tags :vendor => 'Atlassian'

  app 'SourceTree.app'
  binary 'SourceTree.app/Contents/Resources/stree'

  uninstall :launchctl => 'com.atlassian.SourceTreePrivilegedHelper2'

  zap :delete => [
                  '~/Library/Application Support/SourceTree',
                  '~/Library/Caches/com.torusknot.SourceTreeNotMAS',
                 ]

  caveats do
    files_in_usr_local
  end
end


text:
#include <hadesmem/write.hpp>
#include <hadesmem/write.hpp>

#include <hadesmem/process.hpp>

struct non_string_type
{
};

void TestWriteStringFail()
{
  hadesmem::Process const process(::GetCurrentProcessId());

  hadesmem::WriteString(process, nullptr, non_string_type());
}

int main()
{
  TestWriteStringFail();
}


text:
var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var employeeSchema = new Schema({
	nombre         : String,
	apellido       : String,
  email          : String,
  password       : String
});

employeeSchema.static("list", function(cb){
   this.find({}, function(err, r){
        cb(r);
   });
});

employeeSchema.static("delete", function(id, cb){
  console.log(id)
   this.remove({_id:id}, function(err, r){
        cb(r);
   });
});

employeeSchema.static("getOne", function(id, cb){
   this.find({_id:id}, function(err, r){
        cb(r);
   });
});

employeeSchema.static("searcher", function(value, cb){

  console.log("searcher method on employee")

  var query = this.find({ });

  query = query.or([{ nombre: value }, { apellido: value }, { email: value }, { password: value }]);

  //console.log(query)

  cb(query)

});

employeeSchema.static("edit", function(id, parametros, cb) {
   this.findOne({_id:id}, function(err, r) {
        r.nombre    = parametros.nombre;
        r.apellido  = parametros.apellido;
        r.email     = parametros.email;

        r.save(function(err, al){
            cb(al);
        });
   });
});

//TODO: Terminar
employeeSchema.static("buscarPorNombre", function(name, cb){
   this.find({nombre:name}, function(err, r){
        cb(r);
   });
});

module.exports = mongoose.model('Employees', employeeSchema);


text:
#include "includes.h"

#include "common.h"
#include "wpa_supplicant_i.h"

int main(int argc, char *argv[])
{
	struct wpa_interface iface;
	int exitcode = 0;
	struct wpa_params params;
	struct wpa_global *global;

	memset(&params, 0, sizeof(params));
	params.wpa_debug_level = MSG_INFO;

	global = wpa_supplicant_init(&params);
	if (global == NULL)
		return -1;

	memset(&iface, 0, sizeof(iface));
	/* TODO: set interface parameters */

	if (wpa_supplicant_add_iface(global, &iface, NULL) == NULL)
		exitcode = -1;

	if (exitcode == 0)
		exitcode = wpa_supplicant_run(global);

	wpa_supplicant_deinit(global);

	return exitcode;
}


text:
var ARTICLES_URL = window.location.href;
var ARTICLE_AUTHOR_URL = '/api/articles/author/';

var GroupedArticles = React.createClass({displayName: "GroupedArticles",
	getInitialState: function () {
		return {
			approvedArticles: [],
			pendingArticles: [],
			bannedArticles: []
		};
	},
	componentDidMount: function () {
		$.ajax({
			url: this.props.url,
			dataType: 'json',
			cache: false,
			success: function (groupedArticles) {
				alert(JSON.stringify(groupedArticles));
				this.setState({
					approvedArticles: groupedArticles.approvedArticles,
					pendingArticles: groupedArticles.pendingArticles,
					bannedArticles: groupedArticles.bannedArticles
				});
			}.bind(this),
			error: function (xhr, status, err) {
				console.error(this.props.url, status, err.toString());
			}.bind(this)
		});
	},
	render: function () {
		return (
			React.createElement("div", null,
				React.createElement("ul", {className: "nav nav-tabs"},
					React.createElement("li", {className: "active"}, React.createElement("a", {href: "#approved", "data-toggle": "tab", "aria-expanded": "true"}, "Approved")),
					React.createElement("li", null, React.createElement("a", {href: "#pending", "data-toggle": "tab", "aria-expanded": "false"}, "Pending")),
					React.createElement("li", null, React.createElement("a", {href: "#banned", "data-toggle": "tab", "aria-expanded": "false"}, "Banned"))
				),
				React.createElement("div", {className: "tab-content"},
					React.createElement("div", {className: "tab-pane fade active in", id: "approved"},
						React.createElement(ArticleList, {articles: this.state.approvedArticles, ellipsize: "250"})
					),
					React.createElement("div", {className: "tab-pane fade", id: "pending"},
						React.createElement(ArticleList, {articles: this.state.pendingArticles, ellipsize: "250"})
					),
					React.createElement("div", {className: "tab-pane fade", id: "banned"},
						React.createElement(ArticleList, {articles: this.state.bannedArticles, ellipsize: "250"})
					)
				)
			)
		);
	}
});

React.render(React.createElement(GroupedArticles, {url: ARTICLES_URL}), document.getElementById('target'));


text:
#!/usr/bin/env node

/**
 * @file This script is used to inline assertions into the README.md documents.
 */
"use strict";

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _glob = _interopRequireDefault(require("glob"));

var _lodash = _interopRequireDefault(require("lodash"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const formatCodeSnippet = setup => {
  const paragraphs = [];

  if (setup.options) {
    paragraphs.push('// Options: ' + JSON.stringify(setup.options));
  }

  if (setup.settings) {
    paragraphs.push('// Settings: ' + JSON.stringify(setup.settings));
  }

  paragraphs.push(setup.code);

  if (setup.errors) {
    for (const message of setup.errors) {
      paragraphs.push('// Message: ' + message.message);
    }
  }

  if (setup.rules) {
    paragraphs.push('// Additional rules: ' + JSON.stringify(setup.rules));
  }

  return paragraphs.join('\n');
};

const getAssertions = () => {
  const assertionFiles = _glob.default.sync(_path.default.resolve(__dirname, '../../tests/rules/assertions/*.js'));

  const assertionNames = _lodash.default.map(assertionFiles, filePath => {
    return _path.default.basename(filePath, '.js');
  });

  const assertionCodes = _lodash.default.map(assertionFiles, filePath => {
    // eslint-disable-next-line import/no-dynamic-require
    const codes = require(filePath);

    return {
      invalid: _lodash.default.map(codes.invalid, formatCodeSnippet),
      valid: _lodash.default.map(codes.valid, formatCodeSnippet)
    };
  });

  return _lodash.default.zipObject(assertionNames, assertionCodes);
};

const updateDocuments = assertions => {
  const readmeDocumentPath = _path.default.join(__dirname, '../../README.md');

  let documentBody;
  documentBody = _fs.default.readFileSync(readmeDocumentPath, 'utf8');
  documentBody = documentBody.replace(/<!-- assertions ([a-z]+?) -->/ugi, assertionsBlock => {
    let exampleBody;
    const ruleName = assertionsBlock.match(/assertions ([a-z]+)/ui)[1];
    const ruleAssertions = assertions[ruleName];

    if (!ruleAssertions) {
      throw new Error('No assertions available for rule "' + ruleName + '".');
    }

    exampleBody = '';

    if (ruleAssertions.invalid.length) {
      exampleBody += 'The following patterns are considered problems:\n\n```js\n' + ruleAssertions.invalid.join('\n\n') + '\n```\n\n';
    }

    if (ruleAssertions.valid.length) {
      exampleBody += 'The following patterns are not considered problems:\n\n```js\n' + ruleAssertions.valid.join('\n\n') + '\n```\n\n';
    }

    return exampleBody;
  });

  _fs.default.writeFileSync(readmeDocumentPath, documentBody);
};

updateDocuments(getAssertions());


text:
// RegistryContextMenu.cpp

#include "StdAfx.h"

#include "../../../Common/StringConvert.h"

#include "../../../Windows/Registry.h"

#include "RegistryContextMenu.h"

using namespace NWindows;
using namespace NRegistry;

#ifndef UNDER_CE

// does extension can work, if Approved is removed ?
// CLISID (and Approved ?) items are separated for 32-bit and 64-bit code.
// shellex items shared by 32-bit and 64-bit code?

static LPCTSTR k_Clsid = TEXT("{23170F69-40C1-278A-1000-000100020000}");
static LPCTSTR k_ShellExtName = TEXT("EcoZip Shell Extension");

static LPCTSTR k_Approved = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved");
static LPCTSTR k_Inproc = TEXT("InprocServer32");

static LPCTSTR k_KeyPostfix_ContextMenu = TEXT("\\shellex\\ContextMenuHandlers\\EcoZip");
static LPCTSTR k_KeyPostfix_DragDrop    = TEXT("\\shellex\\DragDropHandlers\\EcoZip");

static LPCTSTR k_KeyName_File      = TEXT("*");
static LPCTSTR k_KeyName_Folder    = TEXT("Folder");
static LPCTSTR k_KeyName_Directory = TEXT("Directory");
static LPCTSTR k_KeyName_Drive     = TEXT("Drive");

static LPCTSTR const k_shellex_Prefixes[] =
{
  k_KeyName_File,
  k_KeyName_Folder,
  k_KeyName_Directory,
  k_KeyName_Drive
};

static const bool k_shellex_Statuses[2][4] =
{
  { true, true, true, false },
  { false, false, true, true }
};

// can we use static RegDeleteKeyExW in _WIN64 mode?
// is it supported by Windows 2003 x64?

/*
#ifdef _WIN64

#define INIT_REG_WOW

#else
*/

typedef WINADVAPI LONG (APIENTRY *Func_RegDeleteKeyExW)(HKEY hKey, LPCWSTR lpSubKey, REGSAM samDesired, DWORD Reserved);
static Func_RegDeleteKeyExW func_RegDeleteKeyExW;

static void Init_RegDeleteKeyExW()
{
  if (!func_RegDeleteKeyExW)
    func_RegDeleteKeyExW = (Func_RegDeleteKeyExW)
      GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW");
}

#define INIT_REG_WOW if (wow != 0) Init_RegDeleteKeyExW();

// #endif

static LONG MyRegistry_DeleteKey(HKEY parentKey, LPCTSTR name, UInt32 wow)
{
  if (wow == 0)
    return RegDeleteKey(parentKey, name);

  /*
  #ifdef _WIN64
    return RegDeleteKeyExW
  #else
  */
    if (!func_RegDeleteKeyExW)
      return E_NOTIMPL;
    return func_RegDeleteKeyExW
  // #endif
      (parentKey, GetUnicodeString(name), wow, 0);
}

static LONG MyRegistry_DeleteKey_HKCR(LPCTSTR name, UInt32 wow)
{
  return MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, name, wow);
}

// static NSynchronization::CCriticalSection g_CS;

static CSysString Get_ContextMenuHandler_KeyName(const CSysString &keyName)
  { return (keyName + k_KeyPostfix_ContextMenu); }

/*
static CSysString Get_DragDropHandler_KeyName(const CSysString &keyName)
  { return (keyName + k_KeyPostfix_DragDrop); }
*/

static bool CheckHandlerCommon(const CSysString &keyName, UInt32 wow)
{
  CKey key;
  if (key.Open(HKEY_CLASSES_ROOT, keyName, KEY_READ | wow) != ERROR_SUCCESS)
    return false;
  CSysString value;
  if (key.QueryValue(NULL, value) != ERROR_SUCCESS)
    return false;
  return StringsAreEqualNoCase_Ascii(value, k_Clsid);
}

bool CheckContextMenuHandler(const UString &path, UInt32 wow)
{
  // NSynchronization::CCriticalSectionLock lock(g_CS);

  CSysString s = TEXT("CLSID\\");
  s += k_Clsid;
  s.AddAscii("\\InprocServer32");

  {
    NRegistry::CKey key;
    if (key.Open(HKEY_CLASSES_ROOT, s, KEY_READ | wow) != ERROR_SUCCESS)
      return false;
    UString regPath;
    if (key.QueryValue(NULL, regPath) != ERROR_SUCCESS)
      return false;
    if (!path.IsEqualTo_NoCase(regPath))
      return false;
  }

  return
       CheckHandlerCommon(Get_ContextMenuHandler_KeyName(k_KeyName_File), wow);
  /*
    && CheckHandlerCommon(Get_ContextMenuHandler_KeyName(k_KeyName_Directory), wow)
    // && CheckHandlerCommon(Get_ContextMenuHandler_KeyName(k_KeyName_Folder))

    && CheckHandlerCommon(Get_DragDropHandler_KeyName(k_KeyName_Directory), wow)
    && CheckHandlerCommon(Get_DragDropHandler_KeyName(k_KeyName_Drive), wow);
  */
}

static LONG MyCreateKey(CKey &key, HKEY parentKey, LPCTSTR keyName, UInt32 wow)
{
  return key.Create(parentKey, keyName, REG_NONE,
      REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS | wow);
}

LONG SetContextMenuHandler(bool setMode, const UString &path, UInt32 wow)
{
  // NSynchronization::CCriticalSectionLock lock(g_CS);

  INIT_REG_WOW

  LONG res;

  {
  CSysString s = TEXT("CLSID\\");
  s += k_Clsid;

  if (setMode)
  {
    {
      CKey key;
      res = MyCreateKey(key, HKEY_CLASSES_ROOT, s, wow);
      if (res == ERROR_SUCCESS)
      {
        key.SetValue(NULL, k_ShellExtName);
        CKey keyInproc;
        res = MyCreateKey(keyInproc, key, k_Inproc, wow);
        if (res == ERROR_SUCCESS)
        {
          res = keyInproc.SetValue(NULL, path);
          keyInproc.SetValue(TEXT("ThreadingModel"), TEXT("Apartment"));
        }
      }
    }

    {
      CKey key;
      if (MyCreateKey(key, HKEY_LOCAL_MACHINE, k_Approved, wow) == ERROR_SUCCESS)
        key.SetValue(k_Clsid, k_ShellExtName);
    }
  }
  else
  {
    CSysString s2 = s;
    s2.AddAscii("\\InprocServer32");

    MyRegistry_DeleteKey_HKCR(s2, wow);
    res = MyRegistry_DeleteKey_HKCR(s, wow);
  }
  }

  // shellex items probably are shared beween 32-bit and 64-bit apps. So we don't delete items for delete operation.
  if (setMode)
  for (unsigned i = 0; i < 2; i++)
  {
    for (unsigned k = 0; k < ARRAY_SIZE(k_shellex_Prefixes); k++)
    {
      CSysString s = k_shellex_Prefixes[k];
      s += (i == 0 ? k_KeyPostfix_ContextMenu : k_KeyPostfix_DragDrop);
      if (k_shellex_Statuses[i][k])
      {
        CKey key;
        MyCreateKey(key, HKEY_CLASSES_ROOT, s, wow);
        key.SetValue(NULL, k_Clsid);
      }
      else
        MyRegistry_DeleteKey_HKCR(s, wow);
    }
  }

  return res;
}

#endif


text:
var mongoose = require('mongoose'),
  ImageData = mongoose.model('ImageMetaData');

module.exports.imageData = function(key) {
  var imageData = new ImageData({
    key: key
  });

  imageData.save();

  return imageData;
};


text:
using System;
using System.Reflection;

namespace Serialization {
    //Using reflection to get and set properties so there is no
    //JIT compiliation
    public class GetSetGeneric : GetSet {
        public GetSetGeneric(PropertyInfo info) {
            Name = info.Name;
            Info = info;
            CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
            var customAttrs = info.GetCustomAttributes(typeof(Specialist), true);
            if (customAttrs.Length > 0) {
                var specialist = (Specialist)customAttrs[0];
                Get = (o) => UnitySerializer.Specialists[specialist.Type].Serialize(info.GetValue(o, null));
                Set = (o, v) => info.SetValue(o, UnitySerializer.Specialists[specialist.Type].Deserialize(v), null);
            }
            else {
                var getMethod = info.GetGetMethod(true);
                var setMethod = info.GetSetMethod(true);
                if (getMethod == null) {
                    Get = (o) => {
                        return info.GetValue(o, null);
                    };
                    Set = (o, v) => {
                        info.SetValue(o, v, null);

                    };
                    return;
                }

                IsStatic = getMethod.IsStatic;
                Get = (o) => {
                    return getMethod.FastInvoke(o, null);
                    //return getMethod.Invoke (o, null);
                };
                Set = (o, v) => {
                    try {
                        setMethod.FastInvoke(o, new[] { v });
                    }
                    catch (Exception e) {
                        Radical.LogWarning(string.Format("When setting {0} to {1} found {2}:", o != null ? o.ToString() : "null", v != null ? v.ToString() : "null", e.ToString()));
                    }
                };
            }
        }

        public GetSetGeneric(FieldInfo info) {
            Name = info.Name;
            FieldInfo = info;
            var customAttrs = info.GetCustomAttributes(typeof(Specialist), true);
            if (customAttrs.Length > 0) {
                var specialist = (Specialist)customAttrs[0];
                Get = (o) => UnitySerializer.Specialists[specialist.Type].Serialize(info.GetValue(o));
                Set = (o, v) => info.SetValue(o, UnitySerializer.Specialists[specialist.Type].Deserialize(v));
            }
            else {
                Get = info.GetValue;
                Set = info.SetValue;
            }
            IsStatic = info.IsStatic;
            CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;

            return;
        }

        public GetSetGeneric(Type t, string name) {
            Name = name;
            var p = t.GetProperty(name);
            if (p == null) {
                FieldInfo = t.GetField(Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                Get = FieldInfo.GetValue;
                Set = FieldInfo.SetValue;
                IsStatic = FieldInfo.IsStatic;
                CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;

                return;
            }
            Info = p;
            CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
            var getMethod = p.GetGetMethod(true);
            var setMethod = p.GetSetMethod(true);
            IsStatic = getMethod.IsStatic;
            Get = (o) => getMethod.Invoke(!IsStatic ? o : null, null);
            Set = (o, v) => setMethod.Invoke(!IsStatic ? o : null, new[] { v });
        }
    }
}


text:
[//]: # (@@author A0139523E)
# Developer Guide

* [Introduction](#introduction)
* [Setting Up](#setting-up)
* [Design](#design)
* [Implementation](#implementation)
* [Testing](#testing)
* [Dev Ops](#dev-ops)
* [Appendix A: User Stories](#appendix-a--user-stories)
* [Appendix B: Use Cases](#appendix-b--use-cases)
* [Appendix C: Non Functional Requirements](#appendix-c--non-functional-requirements)
* [Appendix D: Glossary](#appendix-d--glossary)
* [Appendix E : Product Survey](#appendix-e--product-survey)

## Introduction
Hard2Do is a to-do list software designed for the users who have the need to manage his to-do list by simply typing on keyboard and enter command.

## Setting up

#### Prerequisites

1. **JDK `1.8.0_60`**  or later

    > Having any Java 8 version is not enough.

    This app will not work with earlier versions of Java 8.

2. **Eclipse** IDE
3. **e(fx)clipse** plugin for Eclipse (Do the steps 2 onwards given in
   [this page](http://www.eclipse.org/efxclipse/install.html#for-the-ambitious))
4. **Buildship Gradle Integration** plugin from the Eclipse Marketplace

#### Importing the project into Eclipse

0. Fork this repo, and clone the fork to your computer
1. Open Eclipse (Note: Ensure you have installed the **e(fx)clipse** and **buildship** plugins as given
   in the prerequisites above)
2. Click `File` > `Import`
3. Click `Gradle` > `Gradle Project` > `Next` > `Next`
4. Click `Browse`, then locate the project's directory
5. Click `Finish`

  > * If you are asked whether to 'keep' or 'overwrite' config files, choose to 'keep'.
  > * Depending on your connection speed and server load, it can even take up to 30 minutes for the set up to finish
      (This is because Gradle downloads library files from servers during the project set up process)
  > * If Eclipse auto-changed any settings files during the import process, you can discard those changes.

## Design

### Architecture

The **_Architecture Diagram_** given above explains the high-level design of the App.
Given below is a quick overview of each component.

`Main` has only one class called [`MainApp`](../src/main/java/seedu/address/MainApp.java). It is responsible for,
* At app launch: Initialing the components in the correct sequence, and connecting them up with each other.
* At shut down: Shutting down the components and invoking cleanup method where necessary.

[**`Commons`**](#common-classes) represents a collection of classes used by multiple other components.
Two of those classes play important roles at the architecture level.
* `EventsCentre` : This class (written using [Google's Event Bus library](https://github.com/google/guava/wiki/EventBusExplained))
  is used by components to communicate with other components using events (i.e. a form of Event Driven design)
* `LogsCenter` : This class is used by many classes to write log messages to the App's log file.

The rest of the App consists of four components.
* [**`UI`**](#ui-component) : Presents the UI of the App.
* [**`Logic`**](#logic-component) : Distribute the commands from the user.
* [**`Model`**](#model-component) : Holds the data of the App in-memory.
* [**`Storage`**](#storage-component) : Reads data from, and writes data to, the hard disk.

Each of the four components
* Defines its _API_ in an `interface` with the same name as the Component.
* Exposes its functionality using a `{Component Name}Manager` class.

For example, the `Logic` component (see the class diagram given below) defines it's API in the `Logic.java`
interface and exposes its functionality using the `LogicManager.java` class.

The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the
command `delete 1`.

>Note how the `Model` simply raises a `TaskManagerChangedEvent` when the Task Manager data are changed,
 instead of asking the `Storage` to save the updates to the hard disk.

The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates
being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time.

> Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having
  to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct
  coupling between components.

The sections below give more details of each component.

### UI component

**API** : [`Ui.java`](../src/main/java/seedu/address/ui/Ui.java)

The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `TaskListPanel`,
`StatusBarFooter`, `BrowserPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class
and they can be loaded using the `UiPartLoader`.

The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files
 that are in the `src/main/resources/view` folder.

 For example, the layout of the [`MainWindow`](../src/main/java/seedu/address/ui/MainWindow.java) is specified in
 [`MainWindow.fxml`](../src/main/resources/view/MainWindow.fxml)

The `UI` component,
* Executes user commands using the `Logic` component.
* Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change.
* Responds to events raised from various parts of the App and updates the UI accordingly.

### Logic component

**API** : [`Logic.java`](../src/main/java/seedu/address/logic/Logic.java)

1. `Logic` uses the `Parser` class to parse the user command, this results in a `Command` object which is executed by the `LogicManager`.
3. The command execution can affect the `Model` (e.g. adding a task) and/or raise events. The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`.

Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute("delete 1")`
 API call.

### Model component

**API** : [`Model.java`](../src/main/java/seedu/address/model/Model.java)

The `Model`,
* Stores a `UserPref` object that represents the user's preferences.
* Stores the Task Manager data.
* Exposes a `UnmodifiableObservableList<ReadOnlyTask>` that can be 'observed' e.g. the UI can be bound to this list
  so that the UI automatically updates when the data in the list change.
* Does not depend on any of the other three components.

[//]: # (@@author A0147989B)
### Storage component

**API** : [`Storage.java`](../src/main/java/seedu/address/storage/Storage.java)

The `Storage` component,
* Saves `UserPref` objects in json format and read it back.
* Saves the task manager data in xml format and read it back.

### Common classes

Classes used by multiple components are in the `*.commons` package.

## Implementation

### Logging

We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels
and logging destinations.

* The logging level can be controlled using the `logLevel` setting in the configuration file
  (See [Configuration](#configuration))
* The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to
  the specified logging level
* Currently log messages are output through: `Console` and to a `.log` file.

**Logging Levels**

* `SEVERE` : Detected critical problem which may possibly cause the termination of the application
* `WARNING` : Detected problem, the program will continue, but with caution
* `INFO` : Show the information of the noteworthy actions by the App
* `FINE` : Show the information of the actions by the app which may be useful in debugging
  e.g. print the actual list instead of just its size

### Configuration

Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file
(default: `config.json`):

## Testing

Tests can be found in the `./src/test/java` folder.

**Tests using Eclipse**:
> If you are not using a recent Eclipse version (i.e. _Neon_ or later), enable assertions in JUnit tests
  as described [here](http://stackoverflow.com/questions/2522897/eclipse-junit-ea-vm-option).

* To run all tests, right-click on the `src/test/java` folder and choose
  `Run as` > `JUnit Test`
* To run a subset of tests, right-click on a test package, test class, or a test and choose
  to run as a JUnit test.

**Tests using Gradle**:

See [UsingGradle.md](UsingGradle.md) for how to run tests using Gradle.

We have two types of tests:

1. **GUI Tests** - These are _System Tests_ that test the entire App by simulating user actions on the GUI.
   These are in the `guitests` package.

2. **Non-GUI Tests** - These are tests not involving the GUI. They include,
   1. _Unit tests_ targeting the lowest level methods/classes.

      e.g. `hard2do.taskmanager.commons.UrlUtilTest`
   2. _Integration tests_ that are checking the integration of multiple code units
     (those code units are assumed to be working).

      e.g. `hard2do.taskmanager.storage.StorageManagerTest`
   3. Hybrids of unit and integration tests. These tests are checking multiple code units as well as
      how they are connected together.

      e.g. `hard2do.taskmanager.logic.LogicManagerTest`

**Headless GUI Testing** :
Thanks to the [TestFX](https://github.com/TestFX/TestFX) library we use,
 our GUI tests can be run in the headless mode.
 In the headless mode, GUI tests do not show up on the screen.
 That means the developer can do other things on the Computer while the tests are running.

 See [UsingGradle.md](UsingGradle.md#running-tests) to learn how to run tests in headless mode.

## Dev Ops

### Build Automation

See [UsingGradle.md](UsingGradle.md) to learn how to use Gradle for build automation.

### Continuous Integration

We use [Travis CI](https://travis-ci.org/) to perform _Continuous Integration_ on our projects.
See [UsingTravis.md](UsingTravis.md) for more details.

### Making a Release

Here are the steps to create a new release.

 1. Generate a JAR file [using Gradle](UsingGradle.md#creating-the-jar-file).
 2. Tag the repo with the version number. e.g. `v0.1`
 2. [Create a new release using GitHub](https://help.github.com/articles/creating-releases/)
    and upload the JAR file you created.

### Managing Dependencies

A project often depends on third-party libraries. For example, Task Manager depends on the
[Jackson library](http://wiki.fasterxml.com/JacksonHome) for XML parsing. Managing these _dependencies_
can be automated using Gradle. For example, Gradle can download the dependencies automatically, which
is better than these alternatives.

a. Include those libraries in the repo (this bloats the repo size)

b. Require developers to download those libraries manually (this creates extra work for developers)

## Appendix A : User Stories

Priorities: High (must have) - `* * *`, Medium (nice to have)  - `* *`,  Low (unlikely to have) - `*`

Priority | As a ... | I want to ... | So that I can...
-------- | :-------- | :--------- | :-----------
`* * *` | user | add a new to-do item | keep track of tasks to be done
`* * *` | user | clear all appointments | start afresh easily
`* * *` | new user | see usage instructions | refer to instructions when I forget how to use the App
`* * *` | user | delete a to-do | remove entries that I no longer need
`* * *` | user | edit a to-do | change my schedule
`* * *` | user | find a to-do by word | locate details of to-dos without having to go through the entire list
`* * *` | user | find a to-do by its tag | locate details of my to-dos based on tags assigned
`* * *` | user | add a tag to a to-do | label my to-dos by the same tag so it is easily found
`* * *` | user | delete a tag from a to-do | change tags assigned to the to-dos
`* * *` | user | mark to-do as done | keep track of completed tasks
`* * *` | user | undo actions taken | fix mistakes in my schedule
`* * *` | user | list all my to-dos | view all to-dos that have been added
`* * *` | user | list all the to-dos that are marked as done | refer to what to-dos have been done`
`* * *` | user | list all the to-dos that are marked as undone | refer to what to-dos have not been done
`* * *` | user | list all the to-dos that are marked as important | refer to what to-dos should be done first
`* * *` | user | change the priority of my to-do | focus on the to-dos which have been labelled more important
`* * *` | user | be able to load my task manager from a saved state | go back to a previous state if needed
`* * *` | user | be able to save a copy of my task manager | go back to a previous state if needed
`* * *` | user | select to-dos in the list with just commands | view its details without using a mouse
`* * *` | user | exit the app with just commands | close the app without using a mouse
`* * *` | new user | see usage instructions | refer to instructions when I forget how to use the App
`* *` | user | be reminded of the appointment | stop worry about deadlines
`* *` | user | save email as to-do | save time re-writing and scheduling task
`* *` | user | use it offline | use it anywhere
`*` | user | share my to-do-list with others | discover if there are clashes
`*` | user | list events within a time frame | be aware of upcoming events
`*` | user with many to-dos in the task manager | sort to-dos by importance | decide which item to do first

## Appendix B : Use Cases

(For all use cases below, the **System** is the `TaskManager` and the **Actor** is the `user`, unless specified otherwise)

#### Use case: Add task

**MSS**

1. User requests to add tasks
2. TaskManger adds tasks to its data
Use case ends.

**Extensions**

2a. An invalid command is entered
> 2a1. User is shown the correct format with an example
  Use case resumes at step 1

2b. Adding a duplicate task
> 2b1. User is notified that task already exists
  Use case resumes at step 1

#### Use case: Delete task

**MSS**

1. User requests to list tasks
2. TaskManager shows a list of tasks
3. User requests to delete a specific task in the list
4. TaskManager deletes the task

Use case ends.

**Extensions**

2a. The list is empty

> Use case ends

3a. The given index is invalid

> 3a1. TaskManager shows an error message

  Use case resumes at step 2

#### Use case : Find tasks

**MSS**

1. User requests to find tasks with specific keywords
2. TaskManager returns a list of tasks with all matching keywords
Use case ends

**Extensions**

1a. No keywords were inputted
> TaskManager shows an error message

  Use case resumes at step 1

#### Use case : List all tasks

**MSS**

1. User requests to list all tasks
2. TaskManager shows all tasks added
Use case ends

**Extensions**

2a. The list is empty

> Use case ends

#### Use case : Mark As Done

**MSS**

1. User requests to list all undone tasks
2. TaskManager shows a list of all undone tasks
3. User requests to mark specific task as done
4. TaskManager marks the task as done

Use case ends.

**Extensions**

2a. The list is empty

> Use case ends

3a. The given index is invalid

> 3a1. TaskManager shows an error message

  Use case resumes at step 2

4a. The task has already been marked as done

> Use case ends

## Appendix C : Non Functional Requirements

1. Should work on any [mainstream OS](#mainstream-os) as long as it has Java `1.8.0_60` or higher installed.
2. Should be able to hold up to 1000 tasks.
3. Should come with automated unit tests and open source code.
4. Should favor DOS style commands over Unix-style commands.

## Appendix D : Glossary

##### Mainstream OS

> Windows, Linux, Unix, OS-X

##### Private contact detail

> A contact detail that is not meant to be shared with others

[//]: # (@@author A0141054W)

## Appendix E : Product Survey

#### Wunderlist
* Pros:
~~~~
User Interface(UI) is responsive and effective
Mail-to list function is very convenient
~~~~
* Cons:
~~~~
Wunderlist cannot sync with google calendar
WunderList cannot show calendar style
~~~~

#### Todoist
* Pros:
~~~~
UI is responsive and effective
Todoist can automatically identify the time for to-do
Todoist can instantly recognise short-hand like "tmr" "tues"
Todoist have Mail-to list function
~~~~
* Cons:
~~~~
Todoist cannot sync with google calendar
Todoist cannot see calendar style
~~~~

#### Google Calendar
* Pros:
~~~~
UI is the most responsive and effective
Google Calendar have Mail-to list function
Google Calendar can also sync well with other calendars
~~~~
* Cons:
~~~~
Google Calendar requires too much work needed to add an item
~~~~


text:
require 'yaml'
require 'envyable/loader'
require 'envyable/version'
require 'envyable/railtie' if defined?(Rails)

# Public: A simple yaml to ENV loader.
module Envyable
  # Public: load the yaml file from path and set the variables in the given
  # environment to the ENV.
  #
  # path        - a Pathname or String that describes where the yaml file
  #               resides.
  # environment - a String describing the environment from which to load the
  #               variables (default: development).
  #
  # Examples
  #
  #   Envyable.load('config/env.yml')
  #
  #   Envyable.load('config/application.yml', 'production')
  #
  # Returns nothing.
  def self.load(path, environment = 'development')
    Loader.new(path).load(environment)
  end
end


text:
import * as program from 'commander';
import * as path from 'path';
import { createNgPackage, NgPackagrCliArguments } from './../lib/ng-packagr';

const DEFAULT_PROJECT_PATH = path.resolve(process.cwd(), 'ng-package.json');

function parseProjectPath(parsed: string): string {
  return parsed || DEFAULT_PROJECT_PATH;
}

program
  .name('ng-packagr')
  .option(
    '-p, --project <path>',
    'Path to the \'ng-package.json\' or \'package.json\' file.',
    parseProjectPath,
    DEFAULT_PROJECT_PATH)
  .parse(process.argv);

const cliArguments: any = program;

createNgPackage(cliArguments as NgPackagrCliArguments)
  .catch((err) => process.exit(111));


text:
using HsArtExtractor.Util;

namespace HsArtExtractor.Unity.Extract
{
	internal interface IExtractor
	{
		void Extract(ObjectData data, string dir);
	}
}


text:
#include "fileRenamed.h"

#include "messages.pb.h"

#include <sstream>
#include <system_error>

namespace one {
namespace messages {
namespace fuse {

FileRenamed::FileRenamed(std::unique_ptr<ProtocolServerMessage> serverMessage)
    : FuseResponse{serverMessage}
{
    if (!serverMessage->fuse_response().has_file_renamed())
        throw std::system_error{std::make_error_code(std::errc::protocol_error),
            "file_renamed field missing"};

    auto *fileRenamed =
        serverMessage->mutable_fuse_response()->mutable_file_renamed();

    fileRenamed->mutable_new_uuid()->swap(m_newUuid);

    for (auto &childEntry : *fileRenamed->mutable_child_entries()) {
        m_childEntries.emplace_back(FileRenamedEntry{childEntry});
    }
}

const std::string &FileRenamed::newUuid() const { return m_newUuid; }

const std::vector<FileRenamedEntry> &FileRenamed::childEntries() const
{
    return m_childEntries;
}

std::string FileRenamed::toString() const
{
    std::stringstream stream;
    stream << "type: 'FileRenamed', new uuid: " << m_newUuid
           << ", child entries: [";

    for (const auto &childEntry : m_childEntries)
        stream << childEntry.toString() << ", ";

    stream << "]";

    return stream.str();
}

} // namespace fuse
} // namespace messages
} // namespace one


text:
delete from partners ;
ALTER TABLE partners AUTO_INCREMENT=1 ;
insert into partners(partner_name,partner_image) values ('xeon','imgs/partner.jpg');
insert into partners(partner_name,partner_image) values ('xeon1','imgs/partner.jpg');
insert into partners(partner_name,partner_image) values ('xeon2','imgs/partner.jpg');
insert into partners(partner_name,partner_image) values ('xeon3','imgs/partner.jpg');
insert into partners(partner_name,partner_image) values ('xeon4','imgs/partner.jpg');


text:
package tool;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public abstract class CommandLineTool {
    String errorMessage = "";

    protected static String arg(String argument) {
        return "-" + argument;
    }

    public void printHelp() {
        System.out.println();
        System.out.println(getToolDescription());
        System.out.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getUsageString(), getCommandlineOptions());
    }

    protected CommandLine parseCommandLine(String[] args) throws ParseException {
        CommandLineParser parser = new GnuParser(); // replace with BasicParser when Apache commons-cli is released
        return parser.parse(getCommandlineOptions(), args);
    }

    public boolean isInteger(String value, int minValue, int maxValue) {
        try {
            int val = Integer.parseInt(value);
            return val >= minValue && val <= maxValue;
        } catch (NumberFormatException ignored) {
            return false;
        }
    }

    public int parseInt(String value) {
        return Integer.parseInt(value);
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public abstract String getUsageString();

    public abstract String getToolDescription();

    public abstract Options getCommandlineOptions();

    public abstract void run(CommandLine cmd);

    //public abstract String getStatusMessage(boolean runStatus);

}


text:
<?php

namespace Amplexor\XConnect\Request\File;

use Amplexor\XConnect\Request;

interface FileInterface
{
    /**
     * Create a File object based on the given request and save in file path.
     *
     * @param Request $request
     *   The request to create the file for.
     * @param string $directory
     *   The directory where to store the file.
     *
     * @return FileInterface
     */
    public static function create(Request $request, $directory);

    /**
     * Get the filePath of the created file.
     *
     * @return string
     *   The full path to the file representation of the request.
     */
    public function getPath();

    /**
     * Get the filename of the created file.
     *
     * @return string
     *   The file name of the file.
     */
    public function getFileName();

    /**
     * Get the directory name where the file is located.
     *
     * @return string
     *   The directory where the file is located.
     */
    public function getDirectory();
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<object name="SmphInvisibleFieldsLookup"
        connection="EidssConnectionString"
        generator="ObjectGenerator.xslt"
        xmlns="urn:schemas-bv:objectmodel">

  <storage>
    <get name="spSmphInvisibleFields_SelectLookup" type="lookuplist" />
  </storage>

  <tables>
    <table name="SmphInvisibleFieldsLookup">
    </table>
  </tables>

</object>


text:
#include <aws/connect/model/GetMetricDataRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Connect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetMetricDataRequest::GetMetricDataRequest() :
    m_instanceIdHasBeenSet(false),
    m_startTimeHasBeenSet(false),
    m_endTimeHasBeenSet(false),
    m_filtersHasBeenSet(false),
    m_groupingsHasBeenSet(false),
    m_historicalMetricsHasBeenSet(false),
    m_nextTokenHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false)
{
}

Aws::String GetMetricDataRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_startTimeHasBeenSet)
  {
   payload.WithDouble("StartTime", m_startTime.SecondsWithMSPrecision());
  }

  if(m_endTimeHasBeenSet)
  {
   payload.WithDouble("EndTime", m_endTime.SecondsWithMSPrecision());
  }

  if(m_filtersHasBeenSet)
  {
   payload.WithObject("Filters", m_filters.Jsonize());

  }

  if(m_groupingsHasBeenSet)
  {
   Array<JsonValue> groupingsJsonList(m_groupings.size());
   for(unsigned groupingsIndex = 0; groupingsIndex < groupingsJsonList.GetLength(); ++groupingsIndex)
   {
     groupingsJsonList[groupingsIndex].AsString(GroupingMapper::GetNameForGrouping(m_groupings[groupingsIndex]));
   }
   payload.WithArray("Groupings", std::move(groupingsJsonList));

  }

  if(m_historicalMetricsHasBeenSet)
  {
   Array<JsonValue> historicalMetricsJsonList(m_historicalMetrics.size());
   for(unsigned historicalMetricsIndex = 0; historicalMetricsIndex < historicalMetricsJsonList.GetLength(); ++historicalMetricsIndex)
   {
     historicalMetricsJsonList[historicalMetricsIndex].AsObject(m_historicalMetrics[historicalMetricsIndex].Jsonize());
   }
   payload.WithArray("HistoricalMetrics", std::move(historicalMetricsJsonList));

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  return payload.View().WriteReadable();
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = {
  data: function data() {
    return {
      pointer: 0,
      visibleElements: this.maxHeight / this.optionHeight
    };
  },

  props: {
    showPointer: {
      type: Boolean,
      default: true
    },
    optionHeight: {
      type: Number,
      default: 40
    }
  },
  computed: {
    pointerPosition: function pointerPosition() {
      return this.pointer * this.optionHeight;
    }
  },
  watch: {
    filteredOptions: function filteredOptions() {
      this.pointerAdjust();
    }
  },
  methods: {
    optionHighlight: function optionHighlight(index, option) {
      return {
        'multiselect__option--highlight': index === this.pointer && this.showPointer,
        'multiselect__option--selected': this.isSelected(option)
      };
    },
    addPointerElement: function addPointerElement() {
      var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Enter',
          key = _ref.key;

      if (this.filteredOptions.length > 0) {
        this.select(this.filteredOptions[this.pointer], key);
      }
      this.pointerReset();
    },
    pointerForward: function pointerForward() {
      if (this.pointer < this.filteredOptions.length - 1) {
        this.pointer++;

        if (this.$refs.list.scrollTop <= this.pointerPosition - this.visibleElements * this.optionHeight) {
          this.$refs.list.scrollTop = this.pointerPosition - (this.visibleElements - 1) * this.optionHeight;
        }

        if (this.filteredOptions[this.pointer].$isLabel) this.pointerForward();
      }
    },
    pointerBackward: function pointerBackward() {
      if (this.pointer > 0) {
        this.pointer--;

        if (this.$refs.list.scrollTop >= this.pointerPosition) {
          this.$refs.list.scrollTop = this.pointerPosition;
        }

        if (this.filteredOptions[this.pointer].$isLabel) this.pointerBackward();
      } else {
        if (this.filteredOptions[0].$isLabel) this.pointerForward();
      }
    },
    pointerReset: function pointerReset() {
      if (!this.closeOnSelect) return;
      this.pointer = 0;

      if (this.$refs.list) {
        this.$refs.list.scrollTop = 0;
      }
    },
    pointerAdjust: function pointerAdjust() {
      if (this.pointer >= this.filteredOptions.length - 1) {
        this.pointer = this.filteredOptions.length ? this.filteredOptions.length - 1 : 0;
      }
    },
    pointerSet: function pointerSet(index) {
      this.pointer = index;
    }
  }
};


text:
class HttpRouter
  module RouteHelper
    def path
      @route.path_for_generation
    end

    def path=(path)
      @original_path = path
      if path.respond_to?(:[]) and path[/[^\\]\*$/]
        @match_partially = true
        @path_for_generation = path[0..path.size - 2]
      else
        @path_for_generation = path
      end
    end

    def name(name = nil)
      if name
        self.name = name
        self
      else
        @name
      end
    end

    def add_default_values(hash)
      @default_values ||= {}
      @default_values.merge!(hash)
    end

    def add_match_with(matchers)
      @match_with ||= {}
      @match_with.merge!(matchers)
    end

    def add_other_host(hosts)
      (@other_hosts ||= []).concat(hosts)
    end

    def add_path(path)
      (@paths ||= []) << path
    end

    def add_request_method(methods)
      @request_methods ||= Set.new
      methods = [methods] unless methods.is_a?(Array)
      methods.each do |method|
        method = method.to_s.upcase
        unless Route::VALID_HTTP_VERBS.include?(method)
          raise ArgumentError, "Unsupported HTTP request method: #{method}"
        end
        @request_methods << method
      end
    end

    def process_opts(opts)
      if opts[:conditions]
        opts.merge!(opts[:conditions])
        opts.delete(:conditions)
      end
      opts.each do |k, v|
        if respond_to?(:"#{k}=")
          send(:"#{k}=", v)
        elsif respond_to?(:"add_#{k}")
          send(:"add_#{k}", v)
        else
          add_match_with(k => v)
        end
      end
    end

    def to(dest = nil, &dest_block)
      @dest = dest || dest_block || raise("you didn't specify a destination")
      if @dest.respond_to?(:url_mount=)
        urlmount = UrlMount.new(@path_for_generation, @default_values || {}) # TODO url mount should accept nil here.
        urlmount.url_mount = @router.url_mount if @router.url_mount
        @dest.url_mount = urlmount
      end
      self
    end

    # Creates helper methods for each supported HTTP verb.
    Route::VALID_HTTP_VERBS_WITHOUT_GET.each do |request_method|
      define_method(request_method.downcase) do
        add_request_method(request_method)
        self
      end
    end

    def get
      add_request_method("GET")
      add_request_method("HEAD")
      self
    end

    def redirect(path, status = 302)
      raise ArgumentError, "Status has to be an integer between 300 and 399" unless (300..399).include?(status)
      to { |env|
        params = env['router.params']
        response = ::Rack::Response.new
        response.redirect(eval(%|"#{path}"|), status)
        response.finish
      }
    end

    # Sets the destination of this route to serve static files from either a directory or a single file.
    def static(root)
      @match_partially = true if File.directory?(root)
      to File.directory?(root) ?
        ::Rack::File.new(root) :
        proc {|env|
          env['PATH_INFO'] = File.basename(root)
          ::Rack::File.new(File.dirname(root)).call(env)
        }
    end
  end
end


text:
using Chronos.ReorderableList.Internal;
using System;
using UnityEditor;
using UnityEngine;

namespace Chronos.ReorderableList {

	/// <summary>
	/// Reorderable list adaptor for serialized array property.
	/// </summary>
	/// <remarks>
	/// <para>This adaptor can be subclassed to add special logic to item height calculation.
	/// You may want to implement a custom adaptor class where specialised functionality
	/// is needed.</para>
	/// <para>List elements are <b>not</b> cloned using the <see cref="System.ICloneable"/>
	/// interface when using a <see cref="UnityEditor.SerializedProperty"/> to
	/// manipulate lists.</para>
	/// </remarks>
	public class SerializedPropertyAdaptor : IReorderableListAdaptor {

		private SerializedProperty _arrayProperty;

		/// <summary>
		/// Fixed height of each list item.
		/// </summary>
		/// <remarks>
		/// <para>Non-zero value overrides property drawer height calculation
		/// which is more efficient.</para>
		/// </remarks>
		public float FixedItemHeight;

		/// <summary>
		/// Gets element from list.
		/// </summary>
		/// <param name="index">Zero-based index of element.</param>
		/// <returns>
		/// Serialized property wrapper for array element.
		/// </returns>
		public SerializedProperty this[int index] {
			get { return _arrayProperty.GetArrayElementAtIndex(index); }
		}

		/// <summary>
		/// Gets the underlying serialized array property.
		/// </summary>
		public SerializedProperty arrayProperty {
			get { return _arrayProperty; }
		}

		#region Construction

		/// <summary>
		/// Initializes a new instance of <see cref="SerializedPropertyAdaptor"/>.
		/// </summary>
		/// <param name="arrayProperty">Serialized property for entire array.</param>
		/// <param name="fixedItemHeight">Non-zero height overrides property drawer height calculation.</param>
		public SerializedPropertyAdaptor(SerializedProperty arrayProperty, float fixedItemHeight) {
			if (arrayProperty == null)
				throw new ArgumentNullException("Array property was null.");
			if (!arrayProperty.isArray)
				throw new InvalidOperationException("Specified serialized propery is not an array.");

			this._arrayProperty = arrayProperty;
			this.FixedItemHeight = fixedItemHeight;
		}

		/// <summary>
		/// Initializes a new instance of <see cref="SerializedPropertyAdaptor"/>.
		/// </summary>
		/// <param name="arrayProperty">Serialized property for entire array.</param>
		public SerializedPropertyAdaptor(SerializedProperty arrayProperty) : this(arrayProperty, 0f) {
		}

		#endregion

		#region IReorderableListAdaptor - Implementation

		/// <inheritdoc/>
		public int Count {
			get { return _arrayProperty.arraySize; }
		}

		/// <inheritdoc/>
		public virtual bool CanDrag(int index) {
			return true;
		}
		/// <inheritdoc/>
		public virtual bool CanRemove(int index) {
			return true;
		}

		/// <inheritdoc/>
		public void Add() {
			int newIndex = _arrayProperty.arraySize;
			++_arrayProperty.arraySize;
			SerializedPropertyUtility.ResetValue(_arrayProperty.GetArrayElementAtIndex(newIndex));
		}
		/// <inheritdoc/>
		public void Insert(int index) {
			_arrayProperty.InsertArrayElementAtIndex(index);
			SerializedPropertyUtility.ResetValue(_arrayProperty.GetArrayElementAtIndex(index));
		}
		/// <inheritdoc/>
		public void Duplicate(int index) {
			_arrayProperty.InsertArrayElementAtIndex(index);
		}
		/// <inheritdoc/>
		public void Remove(int index) {
			// Unity doesn't remove element when it contains an object reference.
			var elementProperty = _arrayProperty.GetArrayElementAtIndex(index);
			if (elementProperty.propertyType == SerializedPropertyType.ObjectReference)
				elementProperty.objectReferenceValue = null;

			_arrayProperty.DeleteArrayElementAtIndex(index);
		}
		/// <inheritdoc/>
		public void Move(int sourceIndex, int destIndex) {
			if (destIndex > sourceIndex)
				--destIndex;
			_arrayProperty.MoveArrayElement(sourceIndex, destIndex);
		}
		/// <inheritdoc/>
		public void Clear() {
			_arrayProperty.ClearArray();
		}

		/// <inheritdoc/>
		public virtual void BeginGUI() {
		}

		/// <inheritdoc/>
		public virtual void EndGUI() {
		}

		/// <inheritdoc/>
		public virtual void DrawItemBackground(Rect position, int index) {
		}

		/// <inheritdoc/>
		public virtual void DrawItem(Rect position, int index) {
			EditorGUI.PropertyField(position, this[index], GUIContent.none, false);
		}

		/// <inheritdoc/>
		public virtual float GetItemHeight(int index) {
			return FixedItemHeight != 0f
				? FixedItemHeight
				: EditorGUI.GetPropertyHeight(this[index], GUIContent.none, false)
				;
		}

		#endregion

	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuccessLib.Framework
{
    public class ValidatableBase : BindableBase, INotifyDataErrorInfo
    {
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };

        protected override void SetPropertyChanged<T>(ref T field, T value, string propertyName)
        {
            base.SetPropertyChanged<T>(ref field, value, propertyName);
            ValidateProperty<T>(propertyName, value);
        }

        private Dictionary<string,List<string>> _errors = new Dictionary<string,List<string>>();
        public System.Collections.IEnumerable GetErrors(string propertyName)
        {
            if (_errors.ContainsKey(propertyName))
                return _errors[propertyName];

            return null;
        }

        public bool HasErrors
        {
            get {
                return _errors.Count > 0;
            }
        }

        private void ValidateProperty<T>(string propertyName, T value)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(this);
            context.MemberName = propertyName;
            Validator.TryValidateProperty(value, context, results);

            if(results.Any())
            {
                _errors[propertyName] = results.Select(p => p.ErrorMessage).ToList<string>();
            }
            else
            {
                _errors.Remove(propertyName);
            }
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
}


text:
package ee.tuleva.onboarding.user;

import ee.tuleva.onboarding.auth.principal.AuthenticatedPerson;
import ee.tuleva.onboarding.auth.principal.Person;
import ee.tuleva.onboarding.epis.EpisService;
import ee.tuleva.onboarding.epis.contact.ContactDetails;
import ee.tuleva.onboarding.epis.contact.ContactDetailsService;
import ee.tuleva.onboarding.error.ValidationErrorsException;
import ee.tuleva.onboarding.user.command.UpdateUserCommand;
import ee.tuleva.onboarding.user.response.UserResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import java.util.Optional;
import javax.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1")
@AllArgsConstructor
public class UserController {

  private final UserService userService;
  private final EpisService episService;
  private final ContactDetailsService contactDetailsService;

  @Operation(summary = "Get info about the current user")
  @GetMapping("/me")
  public UserResponse me(@AuthenticationPrincipal AuthenticatedPerson authenticatedPerson) {
    Long userId = authenticatedPerson.getUserId();
    User user = userService.getById(userId);
    ContactDetails contactDetails = episService.getContactDetails(authenticatedPerson);
    return UserResponse.from(user, contactDetails);
  }

  @GetMapping("/me/principal")
  public Person getPrincipal(@AuthenticationPrincipal AuthenticatedPerson authenticatedPerson) {
    return authenticatedPerson;
  }

  @Operation(summary = "Update the current user")
  @PatchMapping("/me")
  public UserResponse patchMe(
      @AuthenticationPrincipal AuthenticatedPerson authenticatedPerson,
      @Valid @RequestBody UpdateUserCommand cmd,
      @Parameter(hidden = true) Errors errors) {

    if (errors != null && errors.hasErrors()) {
      throw new ValidationErrorsException(errors);
    }

    User user =
        userService.updateUser(
            authenticatedPerson.getPersonalCode(),
            Optional.of(cmd.getEmail()),
            cmd.getPhoneNumber());

    if (cmd.getAddress() != null) {
      ContactDetails contactDetails =
          contactDetailsService.updateContactDetails(user, cmd.getAddress());
      return UserResponse.from(user, contactDetails);
    }

    return UserResponse.from(user);
  }
}


text:
<!doctype html>
<html lang="en"><head>
    <meta charset="utf-8">
    <title>陈杰辉写字的地方</title>
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="lib/font-awesome/css/font-awesome.css">

    <script src="lib/jquery-1.11.1.min.js" type="text/javascript"></script>

    <link rel="stylesheet" type="text/css" href="stylesheets/theme.css">
    <link rel="stylesheet" type="text/css" href="stylesheets/premium.css">

</head>
<body class=" theme-blue">

<!-- Demo page code -->

<script type="text/javascript">
    $(function() {
        var match = document.cookie.match(new RegExp('color=([^;]+)'));
        if(match) var color = match[1];
        if(color) {
            $('body').removeClass(function (index, css) {
                return (css.match (/\btheme-\S+/g) || []).join(' ')
            })
            $('body').addClass('theme-' + color);
        }

        $('[data-popover="true"]').popover({html: true});

    });
</script>
<style type="text/css">
    #line-chart {
        height:300px;
        width:800px;
        margin: 0px auto;
        margin-top: 1em;
    }
    .navbar-default .navbar-brand, .navbar-default .navbar-brand:hover {
        color: #fff;
    }
</style>

<script type="text/javascript">
    $(function() {
        var uls = $('.sidebar-nav > ul > *').clone();
        uls.addClass('visible-xs');
        $('#main-menu').append(uls.clone());
    });
</script>

<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../assets/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">

<!--[if lt IE 7 ]> <body class="ie ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie ie7 "> <![endif]-->
<!--[if IE 8 ]> <body class="ie ie8 "> <![endif]-->
<!--[if IE 9 ]> <body class="ie ie9 "> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->

<!--<![endif]-->

<?=$content;?>

</div>

<script src="lib/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript">
    $("[rel=tooltip]").tooltip();
    $(function() {
        $('.demo-cancel-click').click(function(){return false;});
    });
</script>

</body></html>


text:
<?php
/* @var $this yii\web\View */
/* @var $gallery Gallery */

use common\models\Gallery;
use frontend\utilities\FrontEndHelper;
use pavlinter\display\DisplayImage;
use yii\helpers\Html;

$this->title = Yii::$app->name . ': ' . $gallery->title;
$this->params['title'] = $gallery->title;
$this->params['description'] = $gallery->description;

echo '
';
echo '
';
foreach ( $gallery->imageGalleries as $imageGallery ) {
	/** @var \common\models\Image $image */
	$image = $imageGallery->image;
	$title = $image->getFileTitle( FrontEndHelper::getLanguageIdFromAcronym() );
	$thumbnail = DisplayImage::widget( [
		'width'    => \Yii::$app->params['galleryThumbnailSize'],
		'height'   => \Yii::$app->params['galleryThumbnailSize'],
		'options'  => [
			'class' => 'img-responsive hoverable',
			'title' => $title
		],
		'category' => 'all',
		'image'    => $image->filename
	] );
	echo Html::a($thumbnail, '@web/admin/' . Yii::$app->params['imageUploadDir'] . $image->filename, [
		'title' => $title,
		'data-description' => $image->getFileDescription( FrontEndHelper::getLanguageIdFromAcronym() ),
		'data-gallery' => true
	]);
}
echo '
';
echo '
';


text:
namespace OTAPI.Callbacks.Terraria
{
	internal static partial class WorldGen
	{
		internal static bool DropMeteor(ref int x, ref int y)
		{
			return Hooks.World.DropMeteor?.Invoke(ref x, ref y) != HookResult.Cancel;
		}
	}
}


text:
doublejumper
===

The first jump kills enemies. The double jump kills you. Landing on a second enemy after killing a first enemy by jumping is fatal.

Build and run
---
Run ```grunt && grunt connect```.

***
Copyright (C) 2014 Kevin Lee.

melonJS, [melonJS-boilerplate](https://github.com/melonjs/boilerplate), and this project are licensed under the [MIT License](http://www.opensource.org/licenses/mit-license.php)


text:
package org.apache.rya.periodic.notification.processor;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.rya.indexing.pcj.storage.PeriodicQueryResultStorage;
import org.apache.rya.periodic.notification.api.BindingSetRecord;
import org.apache.rya.periodic.notification.api.LifeCycle;
import org.apache.rya.periodic.notification.api.NodeBin;
import org.apache.rya.periodic.notification.notification.TimestampedNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Executor service that runs {@link TimestampedNotificationProcessor}s with basic
 * functionality for starting, stopping, and determining whether notification processors are
 * being executed.
 *
 */
public class NotificationProcessorExecutor implements LifeCycle {

    private static final Logger log = LoggerFactory.getLogger(NotificationProcessorExecutor.class);
    private final BlockingQueue<TimestampedNotification> notifications;

    /**
     * entries to delete from Fluo
     */
    private final BlockingQueue<NodeBin> bins;

    /**
     * query results to export
     */
    private final BlockingQueue<BindingSetRecord> bindingSets;
    private final PeriodicQueryResultStorage periodicStorage;
    private final List<TimestampedNotificationProcessor> processors;
    private final int numberThreads;
    private ExecutorService executor;
    private boolean running = false;

    /**
     * Creates NotificationProcessorExecutor.
     * @param periodicStorage - storage layer that periodic results are read from
     * @param notifications - notifications are pulled from this queue, and the timestamp indicates which bin of results to query for
     * @param bins - after notifications are processed, they are added to the bin to be deleted
     * @param bindingSets - results read from the storage layer to be exported
     * @param numberThreads - number of threads used for processing
     */
    public NotificationProcessorExecutor(final PeriodicQueryResultStorage periodicStorage, final BlockingQueue<TimestampedNotification> notifications,
            final BlockingQueue<NodeBin> bins, final BlockingQueue<BindingSetRecord> bindingSets, final int numberThreads) {
        this.notifications = Objects.requireNonNull(notifications);
        this.bins = Objects.requireNonNull(bins);
        this.bindingSets = Objects.requireNonNull(bindingSets);
        this.periodicStorage = periodicStorage;
        this.numberThreads = numberThreads;
        processors = new ArrayList<>();
    }

    @Override
    public void start() {
        if (!running) {
            executor = Executors.newFixedThreadPool(numberThreads);
            for (int threadNumber = 0; threadNumber < numberThreads; threadNumber++) {
                log.info("Creating processor for thread: {}", threadNumber);
                final TimestampedNotificationProcessor processor = TimestampedNotificationProcessor.builder().setBindingSets(bindingSets)
                        .setBins(bins).setPeriodicStorage(periodicStorage).setNotifications(notifications).setThreadNumber(threadNumber)
                        .build();
                processors.add(processor);
                executor.submit(processor);
            }
            running = true;
        }
    }

    @Override
    public void stop() {
        if (processors != null && processors.size() > 0) {
            processors.forEach(x -> x.shutdown());
        }
        if (executor != null) {
            executor.shutdown();
        }
        running = false;
        try {
            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                log.info("Timed out waiting for consumer threads to shut down, exiting uncleanly");
                executor.shutdownNow();
            }
        } catch (final InterruptedException e) {
            log.info("Interrupted during shutdown, exiting uncleanly");
        }
    }

    @Override
    public boolean currentlyRunning() {
        return running;
    }

}