text:
#include "util.hpp"
#include "stack.hpp"
#include "tcp-server.hpp"

/**
 * @brief A TCP, epoll-based, IPv4 server constructor.
 * @param new_port The port number the server's socket will bind to.
 * @param new_max_connections The maximum number of connections *each thread* can handle.
 * Also the listen backlog.
 * @param new_name An arbitrary name for debugging purposes.
 *
 * This is the essential networking server code. Architecturally, each thread calls epoll_wait() and
 * waits for either a mutexed server fd to accept a new connection, a connected fd to indicate there is data to read,
 * or for a connected fd to timeout via timerfd. Each thread manages its own set of connected fds, timeout fds, and
 * is able to accept new connections because epoll_wait is thread safe for reused fds and there is a mutex.
 * @see EpollServer::accept_mutex
 *
 * @bug There lies a type of race condition within a single thread where a timeout and a read event can both trigger.
 * In some cases I believe this is harmless, in other cases I wouldn't be suprised if some memory leaks or other
 * unexpected behavior occurs. Need to research or reevaluate how epoll errors should be treated. EDIT: Resolved?
 * This was solved by using EPOLL_MOD_DEL on the timed-out client's id.
 * @bug EpollServer::start_event does nothing. EDIT: Resolved. A pipe is created to write event data to, and read from
 * in epoll where the broadcast occurs.
 * @bug There is a condition within the kernel where not all data sent to write() is written.
 * This is completely unaccounted for, but I havent hit it yet.
 */
EpollServer::EpollServer(uint16_t new_port, size_t new_max_connections, std::string new_name)
:name(new_name), port(new_port),
max_connections(new_max_connections),
timeout(10),
sockaddr_length(sizeof(this->accept_client)),
running(true){
	if((this->server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		perror("socket");
		throw std::runtime_error(this->name + " socket");
	}
	Util::set_non_blocking(this->server_fd);

	if(pipe2(this->broadcast_pipe, O_DIRECT | O_NONBLOCK) < 0){
		perror("pipe2");
		throw std::runtime_error(this->name + " pipe2");
	}

/*
	The setsockopt() call below is unnecessary, but allows for quicker development.
	With this, the server can be stopped and restarted on the same port immediately.
*/
	int opt = 1;
	if(setsockopt(this->server_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&opt), sizeof(opt)) < 0){
		perror("setsockopt SO_REUSEADDR");
		throw std::runtime_error(this->name + " setsockopt SO_REUSEADDR");
	}

	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(port);
	if(bind(this->server_fd, reinterpret_cast<struct sockaddr*>(&server_addr), sizeof(server_addr)) < 0){
		perror("bind");
		throw std::runtime_error(this->name + " bind");
	}
	if(listen(this->server_fd, static_cast<int>(this->max_connections)) < 0){
		perror("listen");
		throw std::runtime_error(this->name + " listen");
	}
}

/**
 * @brief The base function for closing a client. Important for the PrivateEpollServer implementation.
 *
 * @param fd The fd that is closing.
 * @param callback The thread-specific callback. *I think* this is only necessary because of thread-specific variables.
 */
void EpollServer::close_client(int* fd, std::function<void(int*)> callback){
	callback(fd);
}

ssize_t EpollServer::send(int fd, std::string data){
	//return this->send(fd, data.c_str(), static_cast<size_t>(data.length()));
	if(this->send(fd, data.c_str(), data.length())){
		return -1;
	}
	return static_cast<ssize_t>(data.length());
}

/**
 * @brief The base send function that should be used by all implementers.
 *
 * @param fd The fd to write to.
 * @param data the data to write.
 * @param data_length the length of the data that *should* be written.
 *
 * @return true on error.
 */
bool EpollServer::send(int fd, const char* data, size_t data_length){
	ssize_t len;
	//PRINT("SEND ON TCP")
	if((len = write(fd, data, data_length)) < 0){
		perror("write");
		ERROR("send")
		return true;
	}
	if(static_cast<size_t>(len) != data_length){
		ERROR("NOT ALL THE DATA WAS SENT TO " << fd)
	}
	this->write_counter[fd]++;
	return false;
}

/**
 * @brief The base receive function that @see EpollServer::run_thread calls.
 *
 * @param fd The fd which has data to read.
 * @param data The character array data will be read to.
 * @param data_length The number of bytes read.
 *
 * @return Negative on error, zero on nothing to read, and positive for successful read.
 */
ssize_t EpollServer::recv(int fd, char* data, size_t data_length){
	return this->recv(fd, data, data_length, this->on_read);
}

ssize_t EpollServer::recv(int fd, char* data, size_t data_length,
std::function<ssize_t(int, char*, size_t)> callback){
	ssize_t len;
	if((len = read(fd, data, data_length)) < 0){
		if(errno != EWOULDBLOCK && errno != EAGAIN){
			perror("read");
			ERROR(this->name << " on " << fd)
			return -1;
		}
		return 0;
	}else if(len == 0){
		return -2;
	}else{
		data[len] = 0;
		return callback(fd, data, static_cast<size_t>(len));
	}
}

/**
 * @brief The base continuation function for accepting a connection.
 *
 * @return true If the fd should actually be closed.
 *
 * This is only *necessary* for @see PrivateEpollServer::accept_continuation.
 */
bool EpollServer::accept_continuation(int*){
	return false;
}

/**
 * Protects any messing with the broadcasting pipe.
 * Use this to broadcast some data to all connected fds!
 *
 * @return The write-end of an internal broadcasting pipe, where epoll uses the read-end.
 */
int EpollServer::broadcast_fd(){
	return this->broadcast_pipe[1];
}

/// Sets the timeout. This is dynamic, yet not unique per connection.
void EpollServer::set_timeout(time_t seconds){
	this->timeout = seconds;
}

/**
 * @brief The essential threaded epoll server function. Starts via std::thread.
 *
 * @param thread_id The id of the thread. Necessary for potential events.
 */
void EpollServer::run_thread(unsigned int thread_id){
	int num_fds, num_timeouts, new_fd, the_fd, timer_fd, i, j, epoll_fd, timeout_epoll_fd;
	unsigned long num_connections = 0;
	char packet[PACKET_LIMIT + 32];
	ssize_t len;
	struct itimerspec timer_spec;

	//struct timeval recv_timeout;

	struct epoll_event new_event;
	struct epoll_event* client_events = new struct epoll_event[this->max_connections + 4];
						// + 1 for server_fd
						// + 1 for timeout_epoll_fd
						// + 1 for broadcast_pipe[0]
						// + 1 for fun
	struct epoll_event* timeout_events = new struct epoll_event[this->max_connections + 1];

	std::unordered_map<int /* timer fd */, int /* client fd */> timer_to_client_map;
	std::unordered_map<int /* client fd */, int /* timer fd */> client_to_timer_map;
	char client_detail[INET_ADDRSTRLEN];

	// Broken pipes will make SSL_write (or any write, actually) return with an error instead of interrupting the program.
	signal(SIGPIPE, SIG_IGN);

	if((epoll_fd = epoll_create1(0)) < 0){
		perror("epoll_create1");
		throw std::runtime_error(this->name + " epoll_create1");
	}

	// Add server_fd
	memset(&new_event, 0, sizeof(new_event));
	new_event.events = EVENTS;
	new_event.data.fd = this->server_fd;
	if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, this->server_fd, &new_event) < 0){
		perror("epoll_ctl");
		throw std::runtime_error(this->name + " epoll_ctl");
	}

	if((timeout_epoll_fd = epoll_create1(0)) < 0){
		perror("epoll_create1 timeout");
		throw std::runtime_error(this->name + " epoll_create1 timeout");
	}

	// Add timeout_epoll_fd
	memset(&new_event, 0, sizeof(new_event));
	new_event.events = EVENTS;
	new_event.data.fd = timeout_epoll_fd;
	if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, timeout_epoll_fd, &new_event) < 0){
		perror("epoll_ctl timeout");
		throw std::runtime_error(this->name + " epoll_ctl timeout");
	}

	// Add broadcast_pipe[0]
	memset(&new_event, 0, sizeof(new_event));
	new_event.events = EVENTS;
	new_event.data.fd = this->broadcast_pipe[0];
	if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, this->broadcast_pipe[0], &new_event) < 0){
		perror("epoll_ctl timeout broadcast");
		throw std::runtime_error(this->name + " epoll_ctl broadcast");
	}

	std::function<void(int*)> close_client_callback = [&](int* fd){
		if(close(*fd) < 0){
			perror("close");
		}
		DEBUG(this->name << ": " << *fd << " done on thread " << thread_id)
		if(this->on_disconnect != nullptr){
			this->on_disconnect(*fd);
		}
		if(num_connections >= this->max_connections){
			new_event.events = EVENTS;
			new_event.data.fd = this->server_fd;
			if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, this->server_fd, &new_event) < 0){
				perror("epoll_ctl add server");
			}
		}
		num_connections--;
	};

	while(this->running){
		if((num_fds = epoll_wait(epoll_fd, client_events, static_cast<int>(this->max_connections + 2), 10000)) < 0){
			if(errno == EINTR){
				DEBUG("EINTR!t:" << thread_id)
				continue;
			}
			perror("epoll_wait");
			this->running = false;
			continue;
		}
		if(num_fds == 0){
			//DEBUG("EPOLL_WAIT TIMEOUT")
			continue;
		}
		for(i = 0; i < num_fds; ++i){
			the_fd = client_events[i].data.fd;
			if(client_events[i].events & EPOLLERR){
				PRINT("EPOLLERR: " << the_fd)
			}else if(client_events[i].events & EPOLLHUP){
				PRINT("EPOLLHUP: " << the_fd)
			}else if(!(client_events[i].events & EPOLLIN)){
				PRINT("EPOLLIN: " << the_fd)
			}
			if((client_events[i].events & EPOLLERR) ||
			(client_events[i].events & EPOLLHUP) ||
			(!(client_events[i].events & EPOLLIN))){
				timer_fd = client_to_timer_map[the_fd];
				client_to_timer_map.erase(the_fd);
				timer_to_client_map.erase(timer_fd);
				ERROR(the_fd << " and timer " << timer_fd << " thread " << thread_id)
				if(close(timer_fd) < 0){
					perror("close timer_fd on error");
				}
				this->close_client(&the_fd, close_client_callback);
				continue;
			}
			if(the_fd == timeout_epoll_fd){
				if((num_timeouts = epoll_wait(timeout_epoll_fd, timeout_events, static_cast<int>(this->max_connections), 1000)) < 0){
					perror("epoll_wait timeout");
					continue;
				}else if(num_timeouts > 0){
					for(j = 0; j < num_timeouts; ++j){
						timer_fd = timeout_events[j].data.fd;
						new_fd = timer_to_client_map[timer_fd];
						timer_to_client_map.erase(timer_fd);
						client_to_timer_map.erase(new_fd);
						DEBUG(this->name << ": " << timer_fd << " timed out on " << new_fd)
						if(close(timer_fd) < 0){
							perror("close timer_fd on timeout");
							continue;
						}
						if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, new_fd, nullptr) < 0){
							perror("epoll_ctl del timedout fd");
						}
						this->close_client(&new_fd, close_client_callback);
					}
				}else{
					ERROR("NO TIMEOUTS WHY DID EVENT FIRE?")
				}
				client_events[i].events = EVENTS;
				client_events[i].data.fd = timeout_epoll_fd;
				if(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, timeout_epoll_fd, &client_events[i]) < 0){
					perror("epoll_ctl mod timeout");
				}
			}else if(the_fd == this->broadcast_pipe[0]){
				/*
					This is an implementation of broadcasting within epoll.	The read-end of EpollServer::broadcast_pipe is added to epoll,
					so when	an implementation calls EpollServer::send(EpollServer::broadcast_fd(), data, data_length)
					(which writes to broadcast_pipe[1]), each thread will receive a new event landing here. Data
					is first read from the read end of the pipe, and then written to each currently tracked client fd. Broadcasted.
				*/
				if((len = read(this->broadcast_pipe[0], packet, PACKET_LIMIT)) <= 0){
					ERROR("I really hope this doesn't happen.")
				}
				packet[len] = 0;
				for(auto iter = client_to_timer_map.begin(); iter != client_to_timer_map.end(); ++iter){
					// Throw away send errors?
					if(this->send(iter->first, packet, static_cast<size_t>(len))){
						ERROR("failed to broadcast to " << iter->first)
					}
				}
				client_events[i].events = EVENTS;
				client_events[i].data.fd = this->broadcast_pipe[0];
				if(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, this->broadcast_pipe[0], &client_events[i]) < 0){
					perror("epoll_ctl mod broadcast");
				}
			}else if(the_fd == this->server_fd){
				if(this->accept_mutex.try_lock()){
					while(num_connections < this->max_connections){
						if((new_fd = accept(this->server_fd, reinterpret_cast<struct sockaddr*>(&this->accept_client), &this->sockaddr_length)) < 0){
							if(errno != EWOULDBLOCK && errno != EAGAIN){
								perror("accept");
								running = false;
							}else{
								#if defined(DO_DEBUG)
									perror("accept nonblock");
								#endif
							}
							break;
						}else{
							if(inet_ntop(AF_INET, &this->accept_client.sin_addr.s_addr, client_detail, sizeof(client_detail)) != nullptr){
								PRINT(this->name << ": Connection from " << client_detail << " on " << new_fd << " thread " << thread_id)
								this->fd_to_details_map[new_fd] = std::string(client_detail);
							}else{
								perror("inet_ntop!");
								this->fd_to_details_map[new_fd] = "NULL";
							}
							Util::set_non_blocking(new_fd);
							if(this->accept_continuation(&new_fd)){
								DEBUG("accept continuation failed " << new_fd)
								this->close_client(&new_fd, [&](int* fd){
									close(*fd);
								});
								break;
							}
							new_event.events = EVENTS;
							new_event.data.fd = new_fd;
							if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, new_fd, &new_event) < 0){
								perror("epoll_ctl add client");
								this->close_client(&new_fd, [&](int* fd){
									close(*fd);
								});
								break;
							}else{
								if((timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK)) < 0){
									perror("timerfd_create");
								}else{
									timer_spec.it_interval.tv_sec = 0;
									timer_spec.it_interval.tv_nsec = 0;
									timer_spec.it_value.tv_sec = this->timeout;
									timer_spec.it_value.tv_nsec = 0;
									if(timerfd_settime(timer_fd, 0, &timer_spec, nullptr) < 0){
										perror("timerfd_settime");
									}else{
										timer_to_client_map[timer_fd] = new_fd;
										client_to_timer_map[new_fd] = timer_fd;
										new_event.events = EVENTS;
										new_event.data.fd = timer_fd;
										DEBUG(this->name << ": new timer fd " << timer_fd << " on " << new_fd << " thread " << thread_id)
										if(epoll_ctl(timeout_epoll_fd, EPOLL_CTL_ADD, timer_fd, &new_event) < 0){
											perror("epoll_ctl timer add");
										}
									}
								}
								this->read_counter[new_fd] = 0;
								this->write_counter[new_fd] = 0;
								if(this->on_connect != nullptr){
									this->on_connect(new_fd);
								}
								num_connections++;
							}
						}
					}
					if(num_connections < this->max_connections){
						client_events[i].events = EVENTS;
						client_events[i].data.fd = this->server_fd;
						if(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, this->server_fd, &client_events[i]) < 0){
							perror("epoll_ctl mod server");
						}
					}else{
						if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, this->server_fd, &client_events[i]) < 0){
							perror("epoll_ctl del server");
						}
					}
					this->accept_mutex.unlock();
				}
			}else{
				timer_fd = client_to_timer_map[the_fd];
				timer_spec.it_interval.tv_sec = 0;
				timer_spec.it_interval.tv_nsec = 0;
				timer_spec.it_value.tv_sec = this->timeout;
				timer_spec.it_value.tv_nsec = 0;
				if(timerfd_settime(timer_fd, 0, &timer_spec, nullptr) < 0){
					PRINT("timerfd_setting error " << the_fd << " and timer " << timer_fd)
					perror("timerfd_settime reset");
				}else if((len = this->recv(the_fd, packet, PACKET_LIMIT)) < 0){
					timer_to_client_map.erase(timer_fd);
					client_to_timer_map.erase(the_fd);
					PRINT(this->name << ": " << the_fd << " and timer " << timer_fd << " done.")
					if(close(timer_fd) < 0){
						perror("close timer_fd");
					}
					this->close_client(&the_fd, close_client_callback);
				}else if(len >= PACKET_LIMIT){
					ERROR("OVERFLOAT more to read uh oh!")
					DEBUG(len << "|||" << packet << "|||")
				}else if(len == 0){
					PRINT("RECEIVE ZERO?!")
				}else{
					client_events[i].events = EVENTS;
					client_events[i].data.fd = the_fd;
					if(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, the_fd, &client_events[i]) < 0){
						perror("epoll_ctl mod client");
					}
				}
			}
		}
	}

	delete[] client_events;
	delete[] timeout_events;
}

/**
 * @brief Starts the server.
 *
 * @param returning If this is true, the function will return after spinning some threads.
 * @param new_num_threads Creates this many threads. If *returning* is true, the number of threads that start will not change.
 *
 * E.g. server.run(true, 2), starts 2 threads, but continues.
 * server.run(false, 3) starts 3 threads, but one of those threads is *this* thread.
 */
void EpollServer::run(bool returning, unsigned int new_num_threads){
	this->num_threads = new_num_threads;
	if(this->num_threads <= 0){
		this->num_threads = 1;
	}

	PRINT(this->name << " listening on " << this->port << " with " << this->num_threads << " thread(s).")

	unsigned int total = this->num_threads;
	if(!returning){
		total--;
	}

	for(unsigned int i = 0; i < total; ++i){
		std::thread next(&EpollServer::run_thread, this, i);
		next.detach();
	}

	if(returning){
		return;
	}

	this->run_thread(total);

	DEBUG("RUN END " << name)
}

EpollServer::~EpollServer(){
	DEBUG("DELETE EPOLL: " << name)
	for(auto iter = this->threads.begin(); iter != this->threads.end(); ++iter){
		(*iter)->join();
		delete (*iter);
		DEBUG("THREAD JOINED AND DELETED")
	}
}


text:
mainPath{1}='/data_store/human/raw_data'
mainPath{2}='/data_store/human/prcsd_data'
mainPath{3}='/data_store/human/raw_data/TDTbackup'
folderNames={'HilbAA_70to150_8band','HilbReal_4to200_40band','HilbImag_4to200_40band'}
folderNames={'RawHTK','Videos','HilbImag_4to200_40band'}

 x=1

for i=1
    cd(mainPath{i})
    patients=dir;
    for p=4:length(patients)
        if ~patients(p).isdir
            continue
        end

        cd([mainPath{i} filesep patients(p).name])
        blocks=dir;
        for b=3:length(blocks)
            if ~blocks(b).isdir
                continue
            end
            cd([mainPath{i} filesep patients(p).name filesep blocks(b).name])
            contents=dir;
            for c=3:length(contents)

                if ~contents(c).isdir
                    continue
                end
                col=find(strcmp(contents(c).name,folderNames));
                %col=3;

                if isempty(col)
                    continue
                end
                cd([mainPath{i} filesep patients(p).name filesep blocks(b).name filesep contents(c).name])
                folder=dir;
                allContents{x,1}=patients(p).name;
                allContents{x,2}=blocks(b).name;
                allContents{x,col+2}=sum([folder.bytes])/1.074e+9;
            end
            x=x+1;
        end
    end
end
%%
mainPath{1}='/data_store/human/raw_data'
mainPath{2}='/data_store/human/prcsd_data'
mainPath{3}='/data_store/human/raw_data/TDTbackup'
folderNames={'HilbAA_70to150_8band','HilbReal_4to200_40band','HilbImag_4to200_40band'}
 x=1

for i=3
    cd(mainPath{i})
    patients=dir;
    for p=4:length(patients)
        if ~patients(p).isdir
            continue
        end
        cd([mainPath{i} filesep patients(p).name])
        blocks=dir;
        for b=3:length(blocks)
            if ~blocks(b).isdir
                continue
            end
            cd([mainPath{i} filesep patients(p).name filesep blocks(b).name])
            contents=dir;
            for c=4:length(contents)

                if ~contents(c).isdir
                %    continue
                end
                %col=find(strcmp(contents(c).name,folderNames));
                col=3;

                if isempty(col)
                %    continue
                end
                %cd([mainPath{i} filesep patients(p).name filesep blocks(b).name filesep contents(c).name])
                folder=dir;
                allContents{x,1}=patients(p).name;
                allContents{x,2}=blocks(b).name;
                allContents{x,col+2}=sum([contents.bytes])/1.074e+9;
            end
            x=x+1;
        end
    end
end

%%
clear D
i=1
D.patients=[]
for j=1:length(allContents)
    idx=find(strcmp(vertcat(D.patients),allContents(j,1)))
    if isempty(idx)
        D(i).patients=allContents(j,1)
        i=i+1;
    else
        idx2=find(strcmp(D(idx).patients,allContents(:,1)))
        D(idx).blocks=length(idx2);
        D(idx).sizePrcsd=sum([allContents{idx2,3:5}])
    end
end
%%
close all
folder='sizePrcsd'
allS=[D.(folder)]
bar(sort(allS,'descend'))
set(gca,'XTick',1:length(allS))
notEmpty=find(~cellfun(@isempty,{D.(folder)}))
[~,sortidx]=sort(allS/sum(allS),'descend')
set(gca,'XTickLabel',[D(notEmpty(sortidx)).patients])
% for t=1:28
%     text(t,[D(notEmpty(sortidx(t))).(folder)]+5,int2str([D(notEmpty(sortidx(t))).blocks]),'FontSize',20)
% end
ylabel('GB')
set(gca,'FontSize',12)
xlabel('Subjects')
%%
col=5
idx=find(~cellfun(@isempty,allContents(:,col)))
sum(cell2mat(allContents(idx,col)))/length(idx)

sum(cell2mat(allContents(idx,col)))

redpajama_set_name: RedPajamaGithub


text:
module ComparisonHelper
  def build_commit_hash(message)
    {
      :sha => "sha",
      :commit => {
        :message => message
      },
      :author => {
        :login => "login",
        :html_url => "https://github.com/login"
      },
      :html_url => "https://github.com/org/repo/commit/sha"
    }
  end
end


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

using System.ComponentModel;
using Xunit;

namespace System.DirectoryServices.ActiveDirectory.Tests
{
    public class ActiveDirectoryInterSiteTransportTests
    {
        [Fact]
        public void FindByTransportType_NullContext_ThrowsArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException>("context", () => ActiveDirectoryInterSiteTransport.FindByTransportType(null, ActiveDirectoryTransportType.Rpc));
        }

        [Fact]
        [OuterLoop]
        [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Getting information about domain is denied inside App")]
        [ActiveIssue("https://github.com/dotnet/corefx/issues/21553", TargetFrameworkMonikers.UapAot)]
        public void FindByTransportType_ForestNoDomainAssociatedWithoutName_ThrowsActiveDirectoryOperationException()
        {
            var context = new DirectoryContext(DirectoryContextType.Forest);
            if (!PlatformDetection.IsDomainJoinedMachine)
            {
                Assert.Throws<ActiveDirectoryOperationException>(() => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
            }
        }

        [Fact]
        public void FindByTransportType_ForestNoDomainAssociatedWithName_ThrowsActiveDirectoryOperationException()
        {
            var context = new DirectoryContext(DirectoryContextType.Forest, "server:port");
            AssertExtensions.Throws<ArgumentException>("context", () => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
        }

        [Fact]
        [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
        public void FindByTransportType_ForestNoDomainAssociatedWithName_ThrowsActiveDirectoryOperationException_NoUap()
        {
            // Domain joined machines will not throw on the ActiveDirectoryInterSiteTransport.FindByTransportType call.
            if (!PlatformDetection.IsDomainJoinedMachine)
            {
                var context = new DirectoryContext(DirectoryContextType.Forest, "\0");
                AssertExtensions.Throws<ArgumentException>("context", () => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
            }
        }

        [Fact]
        public void FindByTransportType_DomainNoDomainAssociatedWithoutName_ThrowsArgumentException()
        {
            var context = new DirectoryContext(DirectoryContextType.Domain);
            AssertExtensions.Throws<ArgumentException>("context", () => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
        }

        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
        [OuterLoop("Takes too long on domain joined machines")]
        [InlineData(DirectoryContextType.ApplicationPartition)]
        [InlineData(DirectoryContextType.DirectoryServer)]
        [InlineData(DirectoryContextType.Domain)]
        [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Access to common path is denied inside App")]
        public void FindByTransportType_InvalidContextTypeWithName(DirectoryContextType type)
        {
            var context = new DirectoryContext(type, "Name");
            Exception exception = Record.Exception(() => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
            Assert.NotNull(exception);
            Assert.True(exception is ArgumentException ||
                        exception is ActiveDirectoryOperationException,
                        $"We got unrecognized exception {exception}");
        }

        [Fact]
        [OuterLoop]
        [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Getting information about domain is denied inside App")]
        [ActiveIssue("https://github.com/dotnet/corefx/issues/21553", TargetFrameworkMonikers.UapAot)]
        public void FindByTransportType_ConfigurationSetTypeWithName_Throws()
        {
            var context = new DirectoryContext(DirectoryContextType.ConfigurationSet, "Name");
            Assert.Throws<ActiveDirectoryOperationException>(() => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
        }

        [Theory]
        [InlineData(ActiveDirectoryTransportType.Rpc - 1)]
        [InlineData(ActiveDirectoryTransportType.Smtp + 1)]
        public void FindByTransportType_InvalidTransport_ThrowsInvalidEnumArgumentException(ActiveDirectoryTransportType transport)
        {
            var context = new DirectoryContext(DirectoryContextType.ConfigurationSet, "Name");
            AssertExtensions.Throws<InvalidEnumArgumentException>("value", () => ActiveDirectoryInterSiteTransport.FindByTransportType(context, transport));
        }
    }
}


text:
<?php

namespace Feedtags\ApplicationBundle\Model;

use JMS\Serializer\Annotation as Serialize;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class FeedInputModel
 *
 * @package Feedtags\ApplicationBundle\Model
 */
class FeedInputModel
{
    /**
     * Feed URL
     *
     * @var string
     *
     * @Serialize\Type("string")
     * @Serialize\SerializedName("url")
     *
     * @Assert\Length(max = "255")
     * @Assert\Url
     * @Assert\NotNull
     */
    protected $url;

    /**
     * @param string $url
     */
    public function __construct($url)
    {
        $this->url = $url;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }
}


text:
import { expect } from "chai";
import { AmbientableNode, ClassDeclaration, ModuleDeclaration, Node } from "../../../../compiler";
import { AmbientableNodeStructure } from "../../../../structures";
import { getInfoFromText } from "../../testHelpers";

describe(nameof(AmbientableNode), () => {
    describe("navigation", () => {
        const { sourceFile: mainSourceFile } = getInfoFromText("declare var ambientedVar; var myExplicitVar: string;");
        const statements = mainSourceFile.getVariableStatements();
        const ambientedStatement = statements[0];
        const notAmbientedStatement = statements[1];

        describe(nameof<AmbientableNode>(n => n.hasDeclareKeyword), () => {
            it("should have a declare keyword when it has one", () => {
                expect(ambientedStatement.hasDeclareKeyword()).to.be.true;
            });

            it("should not have an declare keyword when it doesn't have one", () => {
                expect(notAmbientedStatement.hasDeclareKeyword()).to.be.false;
            });
        });

        describe(nameof<AmbientableNode>(n => n.getDeclareKeyword), () => {
            it("should have an declare keyword when it has one", () => {
                expect(ambientedStatement.getDeclareKeyword()!.getText()).to.equal("declare");
            });

            it("should not have an declare keyword when it doesn't have one", () => {
                expect(notAmbientedStatement.getDeclareKeyword()).to.be.undefined;
            });
        });

        describe(nameof<AmbientableNode>(n => n.getDeclareKeywordOrThrow), () => {
            it("should have an declare keyword when it has one", () => {
                expect(ambientedStatement.getDeclareKeywordOrThrow().getText()).to.equal("declare");
            });

            it("should not have an declare keyword when it doesn't have one", () => {
                expect(() => notAmbientedStatement.getDeclareKeywordOrThrow()).to.throw();
            });
        });

        describe(nameof<AmbientableNode>(n => n.isAmbient), () => {
            function doTest(text: string, expectedValue: boolean) {
                const { firstChild } = getInfoFromText<AmbientableNode & Node>(text);
                expect(firstChild.isAmbient()).to.equal(expectedValue);
            }
            it("should not be ambient when not", () => {
                doTest("class Identifier {}", false);
            });

            it("should be ambient when it has a declare keyword", () => {
                doTest("declare class Identifier {}", true);
            });

            it("should be ambient when it's in a declaration file", () => {
                const { firstChild } = getInfoFromText<ClassDeclaration>("class Identifier {}", { isDefinitionFile: true });
                expect(firstChild.isAmbient()).to.be.true;
            });

            it("should be ambient when it's parent is ambient", () => {
                const { firstChild } = getInfoFromText<ModuleDeclaration>("declare namespace Identifier { class Identifier {} }");
                const innerClass = firstChild.getClasses()[0];
                expect(innerClass.isAmbient()).to.be.true;
            });

            it("should always be ambient for interfaces", () => {
                doTest("interface Identifier {}", true);
            });

            it("should always be ambient for type aliases", () => {
                doTest("type Identifier = string;", true);
            });
        });
    });

    describe(nameof<AmbientableNode>(n => n.setHasDeclareKeyword), () => {
        function doTest(text: string, value: boolean, expected: string) {
            const { firstChild, sourceFile } = getInfoFromText<AmbientableNode & Node>(text);
            firstChild.setHasDeclareKeyword(value);
            expect(sourceFile.getFullText()).to.equal(expected);
        }

        it("should add declare keyword when setting it to true", () => {
            doTest("class MyClass { }", true, "declare class MyClass { }");
        });

        it("should remove declare keyword when setting it to false", () => {
            doTest("declare class MyClass { }", false, "class MyClass { }");
        });

        it("should add to a function declaration that has an export keyword and js doc", () => {
            // this is a weird situation where the jsdoc pos is 4, but the export keyword's syntax list is 0 (maybe it's a ts compiler bug?)
            doTest("    /** Testing*/export function identifier { }", true, "    /** Testing*/export declare function identifier { }");
        });
    });

    describe(nameof<ClassDeclaration>(n => n.getStructure), () => {
        function doTest(startingCode: string, hasDeclareKeyword: boolean) {
            const { firstChild, sourceFile } = getInfoFromText<ClassDeclaration>(startingCode);
            expect(firstChild.getStructure().hasDeclareKeyword).to.equal(hasDeclareKeyword);
        }

        it("should get when has declare keyword", () => {
            doTest("declare class MyClass {}", true);
        });

        it("should get when no declare keyword", () => {
            doTest("class MyClass {}", false);
        });
    });

    describe(nameof<ClassDeclaration>(n => n.set), () => {
        function doTest(startingCode: string, structure: AmbientableNodeStructure, expectedCode: string) {
            const { firstChild, sourceFile } = getInfoFromText<ClassDeclaration>(startingCode);
            firstChild.set(structure);
            expect(firstChild.getText()).to.equal(expectedCode);
        }

        it("should not modify when not set and structure empty", () => {
            doTest("class MyClass {}", {}, "class MyClass {}");
        });

        it("should not modify when set and structure empty", () => {
            doTest("declare class MyClass {}", {}, "declare class MyClass {}");
        });

        it("should modify when setting true", () => {
            doTest("class MyClass {}", { hasDeclareKeyword: true }, "declare class MyClass {}");
        });
    });
});


text:
namespace media {

// Layer on top of VideoCaptureDeviceFactory that translates device descriptors
// to string identifiers and consolidates and caches device descriptors and
// supported formats into VideoCaptureDeviceInfos.
class CAPTURE_EXPORT VideoCaptureSystemImpl : public VideoCaptureSystem {
 public:
  explicit VideoCaptureSystemImpl(
      std::unique_ptr<VideoCaptureDeviceFactory> factory);
  ~VideoCaptureSystemImpl() override;

  void GetDeviceInfosAsync(DeviceInfoCallback result_callback) override;
  std::unique_ptr<VideoCaptureDevice> CreateDevice(
      const std::string& device_id) override;

 private:
  using DeviceEnumQueue = std::list<DeviceInfoCallback>;

  // Returns nullptr if no descriptor found.
  const VideoCaptureDeviceInfo* LookupDeviceInfoFromId(
      const std::string& device_id);

  void ProcessDeviceInfoRequest();
  void DeviceInfosReady(
      std::unique_ptr<VideoCaptureDeviceDescriptors> descriptors);

  const std::unique_ptr<VideoCaptureDeviceFactory> factory_;
  std::vector<VideoCaptureDeviceInfo> devices_info_cache_;
  DeviceEnumQueue device_enum_request_queue_;

  base::ThreadChecker thread_checker_;
};

}  // namespace media

#endif  // MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_SYSTEM_IMPL_H_


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <title>为基于 xulrunner 的内嵌 Gecko 程序启用 Profile — </title>
    <link rel="stylesheet" href="/assets/vendor/primer-css/css/primer.css">
    <link rel="stylesheet" href="/assets/vendor/primer-markdown/dist/user-content.min.css">
    <link rel="stylesheet" href="/assets/vendor/octicons/octicons/octicons.css">
    <link rel="stylesheet" href="/assets/css/components/collection.css">
    <link rel="stylesheet" href="/assets/css/components/repo-card.css">
    <link rel="stylesheet" href="/assets/css/sections/repo-list.css">
    <link rel="stylesheet" href="/assets/css/sections/mini-repo-list.css">
    <link rel="stylesheet" href="/assets/css/components/boxed-group.css">
    <link rel="stylesheet" href="/assets/css/globals/common.css">
    <link rel="stylesheet" href="/assets/vendor/share.js/dist/css/share.min.css">
    <link rel="stylesheet" href="/assets/css/globals/responsive.css">
    <link rel="stylesheet" href="/assets/css/posts/index.css">

    <link rel="alternate" type="application/atom+xml" title="" href="">
    <link rel="shortcut icon" href="/favicon.ico">

    <meta property="og:title" content="为基于 xulrunner 的内嵌 Gecko 程序启用 Profile">

    <meta name="keywords" content="Gecko, Profile">
    <meta name="og:keywords" content="Gecko, Profile">

    <meta name="description" content="Mozilla 自带的 Profile 支持实际上是非常给力的,看看 %appdata%/Mozilla/Firefox 下的文件就能知道,这里存放着许多的信息,它们提供了很多东西,例如:">
    <meta name="og:description" content="Mozilla 自带的 Profile 支持实际上是非常给力的,看看 %appdata%/Mozilla/Firefox 下的文件就能知道,这里存放着许多的信息,它们提供了很多东西,例如:">

    <meta property="og:url" content="/gecko/2012/06/19/gecko-use-profile.html">
    <meta property="og:site_name" content="">
    <meta property="og:type" content="article">
    <meta property="og:locale" content="zh_CN" />

    <meta property="article:published_time" content="2012-06-19">

            <button class="collapsed mobile-visible" type="button" onclick="toggleMenu();">

            </button>

为基于 xulrunner 的内嵌 Gecko 程序启用 Profile

             2012/06/19

            Gecko

Mozilla 自带的 Profile 支持实际上是非常给力的,看看 %appdata%/Mozilla/Firefox 下的文件就能知道,这里存放着许多的信息,它们提供了很多东西,例如:

可以通过 Profiles/…default/chrome 下的 userchrome.css 文件来定制自己的 firefox 外观,比如用 #appmenu-button { display:none !important;} 这样一句就可以去掉 firefox 左上角难看的按钮菜单

安装的 extensions,Addon 放在这里

证书相关、组件列表、cookie、插件列表等等都可以在这里找到

等等等等。

合理利用这些文件和信息我们可以在自己内嵌 Gecko 的程序里方便地做一些事情而不用自己去操作和维护一些配置项和数据。

在自己编译完 xulrunner-1.9.2 后尚能找到编译好的 profdirserviceprovidersa_s.lib 来用于 WinEmbed 工程的移植,最近编译了 xulrunner-10.0.2 后发现就没这么幸运了,没有生成这个东东。在头疼了一番后决定自己做一个工程来生成它。根据 xulrunner 源码 mozilla-release/profile/dirserviceprovider 下的几个 makefile 来做就可以了。

直接讲过程吧。

一、编译出需要的 Lib 文件

新建一个 Win32 静态 Lib 空工程,将 mozilla-release/profile/dirserviceprovider 目录下的几个 .h 和 .cpp 文件都添加进工程,将 path/to/xulrunner-10.0.2-sdk/include 添加到工程的附加包含目录,为工程添加预处理器定义 XP_WIN 和 XPCOM_GLUE 这两项。如果一切顺利的话这时候你已经可以顺利地编译出这个 lib 文件了。在 http://download.csdn.net/detail/mzlogin/4382847 可以下载到我的 Demo 工程,如果想编译,需要将上面所讲的 path/to/xulrunner-10.0.2-sdk/include 修改成你本机上 xulrunner sdk 的相应路径。

二、将 Lib 链接进自己内嵌 Gecko 的程序

自写一个启用 profile 的函数,我这里直接使用 WinEmbed 例子里提供的 StartupProfile 函数:

nsresult StartupProfile()
{
    nsCOMPtr<nsIFile> appDataDir;
    nsresult rv = NS_GetSpecialDirectory(NS_APP_APPLICATION_REGISTRY_DIR, getter_AddRefs(appDataDir));
    if (NS_FAILED(rv))
      return rv;

    appDataDir->AppendNative(nsCString("MozillaDemo"));
    nsCOMPtr<nsILocalFile> localAppDataDir(do_QueryInterface(appDataDir));

    nsCOMPtr<nsProfileDirServiceProvider> locProvider;
    NS_NewProfileDirServiceProvider(PR_TRUE, getter_AddRefs(locProvider));
    if (!locProvider)
      return NS_ERROR_FAILURE;

    rv = locProvider->Register();
    if (NS_FAILED(rv))
      return rv;

    return locProvider->SetProfileDir(localAppDataDir);
}

其中的"MozillaDemo"即是你的 profile 文件夹的名字,可以根据你的喜好改动,在这里会是 %appdata%/Mozilla/MozillaDemo

在初始化 Gecko 运行环境的过程里调用完 XRE_InitEmbedding2 之后,添加

if (NS_FAILED(StartupProfile())) {
    result = 8;
}
else {

在此文件开始添加

#include "nsAppDirectoryServiceDefs.h"
#include "nsDirectoryServiceDefs.h"
#include "nsProfileDirServiceProvider.h"

在合适的地方添加

#pragma comment(lib, "编译出的 lib")

顺利的话,就大功告成了,运行一个你的内嵌 Gecko 程序然后去 %appdata%/Mozilla/MozillaDemo 看看吧~有图有真相哦。

Search

    <input type="text" id="search_box" placeholder="Search">
    <button class="btn btn-default" id="site_search_do"></button>

<link rel="stylesheet" type="text/css" href="/assets/css/modules/sidebar-search.css">

Post Directory

                    © 2015

                    TOP

                    TOP

    <link rel="stylesheet" href="/assets/css/globals/prism.css">


text:
import React from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import styles from './IndexPage.css';
import logo from '../assets/logo.jpg';
import moment from 'moment';

const IndexPage = (props) => {

  const { dispatch, posts } = props;
  const postPage = posts.postPage;

  const postList = [];
  for (var index in postPage.data) {
    postList.push(

        <Link to={"/posts/" + postPage.data[index].id}>

{postPage.data[index].title}

        </Link>

{moment.unix(postPage.data[index].createTime / 1000).format('YYYY-MM-D')}

    );
  }

  return (

Here is my teenyverse !

            {postList}

<Link className={styles.loadmore} to="/posts">More</Link>

  );
}

function mapStateToProps(state) {
  return { ...state };
}

export default connect(mapStateToProps)(IndexPage);


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

#ifndef WASP_BINARY_MACROS_H_
#define WASP_BINARY_MACROS_H_

#include "wasp/base/concat.h"
#include "wasp/base/errors.h"
#include "wasp/base/errors_context_guard.h"
#include "wasp/base/span.h"

#define WASP_TRY_READ(var, call) \
  auto opt_##var = call;         \
  if (!opt_##var) {              \
    return nullopt;              \
  }                              \
  auto var = *opt_##var /* No semicolon. */

#define WASP_TRY_READ_CONTEXT(var, call, desc)             \
  ErrorsContextGuard guard_##var(ctx.errors, *data, desc); \
  WASP_TRY_READ(var, call);                                \
  guard_##var.PopContext() /* No semicolon. */

#define WASP_TRY_DECODE(out_var, in_var_at, Type, name)           \
  auto out_var##opt = encoding::Type::Decode(in_var_at);          \
  if (!out_var##opt) {                                            \
    ctx.errors.OnError(in_var_at.loc(),                           \
                       concat("Unknown " name ": ", *in_var_at)); \
    return nullopt;                                               \
  }                                                               \
  auto out_var = At { in_var_at.loc(), *out_var##opt } /* No semicolon. */

#define WASP_TRY_DECODE_FEATURES(out_var, in_var_at, Type, name, features) \
  auto out_var##opt = encoding::Type::Decode(in_var_at, features);         \
  if (!out_var##opt) {                                                     \
    ctx.errors.OnError(in_var_at.loc(),                                    \
                       concat("Unknown " name ": ", *in_var_at));          \
    return nullopt;                                                        \
  }                                                                        \
  auto out_var = At { in_var_at.loc(), *out_var##opt } /* No semicolon. */

#endif  // WASP_BINARY_MACROS_H_


text:
// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
//           (c) 2005, 2006 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
  var options = Object.extend({
    pointerX: 0,
    pointerY: 0,
    buttons:  0,
    ctrlKey:  false,
    altKey:   false,
    shiftKey: false,
    metaKey:  false
  }, arguments[2] || {});
  var oEvent = document.createEvent("MouseEvents");
  oEvent.initMouseEvent(eventName, true, true, document.defaultView,
    options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));

  if(this.mark) Element.remove(this.mark);
  this.mark = document.createElement('div');
  this.mark.appendChild(document.createTextNode(" "));
  document.body.appendChild(this.mark);
  this.mark.style.position = 'absolute';
  this.mark.style.top = options.pointerY + "px";
  this.mark.style.left = options.pointerX + "px";
  this.mark.style.width = "5px";
  this.mark.style.height = "5px;";
  this.mark.style.borderTop = "1px solid red;"
  this.mark.style.borderLeft = "1px solid red;"

  if(this.step)
    alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));

  $(element).dispatchEvent(oEvent);
};

// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
  var options = Object.extend({
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    keyCode: 0,
    charCode: 0
  }, arguments[2] || {});

  var oEvent = document.createEvent("KeyEvents");
  oEvent.initKeyEvent(eventName, true, true, window,
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
    options.keyCode, options.charCode );
  $(element).dispatchEvent(oEvent);
};

Event.simulateKeys = function(element, command) {
  for(var i=0; i<command.length; i++) {
    Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
  }
};

var Test = {}
Test.Unit = {};

// security exception workaround
Test.Unit.inspect = Object.inspect;

Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
  initialize: function(log) {
    this.log = $(log);
    if (this.log) {
      this._createLogTable();
    }
  },
  start: function(testName) {
    if (!this.log) return;
    this.testName = testName;
    this.lastLogLine = document.createElement('tr');
    this.statusCell = document.createElement('td');
    this.nameCell = document.createElement('td');
    this.nameCell.className = "nameCell";
    this.nameCell.appendChild(document.createTextNode(testName));
    this.messageCell = document.createElement('td');
    this.lastLogLine.appendChild(this.statusCell);
    this.lastLogLine.appendChild(this.nameCell);
    this.lastLogLine.appendChild(this.messageCell);
    this.loglines.appendChild(this.lastLogLine);
  },
  finish: function(status, summary) {
    if (!this.log) return;
    this.lastLogLine.className = status;
    this.statusCell.innerHTML = status;
    this.messageCell.innerHTML = this._toHTML(summary);
    this.addLinksToResults();
  },
  message: function(message) {
    if (!this.log) return;
    this.messageCell.innerHTML = this._toHTML(message);
  },
  summary: function(summary) {
    if (!this.log) return;
    this.logsummary.innerHTML = this._toHTML(summary);
  },
  _createLogTable: function() {
    this.log.innerHTML =
    '

' +
    '
' +
    '

Status	Test	Message

' +
    '

' +
    '
';
    this.logsummary = $('logsummary')
    this.loglines = $('loglines');
  },
  _toHTML: function(txt) {
    return txt.escapeHTML().replace(/\n/g,"
");
  },
  addLinksToResults: function(){
    $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
      td.title = "Run only this test"
      Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
    });
    $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
      td.title = "Run all tests"
      Event.observe(td, 'click', function(){ window.location.search = "";});
    });
  }
}

Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
  initialize: function(testcases) {
    this.options = Object.extend({
      testLog: 'testlog'
    }, arguments[1] || {});
    this.options.resultsURL = this.parseResultsURLQueryParameter();
    this.options.tests      = this.parseTestsQueryParameter();
    if (this.options.testLog) {
      this.options.testLog = $(this.options.testLog) || null;
    }
    if(this.options.tests) {
      this.tests = [];
      for(var i = 0; i < this.options.tests.length; i++) {
        if(/^test/.test(this.options.tests[i])) {
          this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
        }
      }
    } else {
      if (this.options.test) {
        this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
      } else {
        this.tests = [];
        for(var testcase in testcases) {
          if(/^test/.test(testcase)) {
            this.tests.push(
               new Test.Unit.Testcase(
                 this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
                 testcases[testcase], testcases["setup"], testcases["teardown"]
               ));
          }
        }
      }
    }
    this.currentTest = 0;
    this.logger = new Test.Unit.Logger(this.options.testLog);
    setTimeout(this.runTests.bind(this), 1000);
  },
  parseResultsURLQueryParameter: function() {
    return window.location.search.parseQuery()["resultsURL"];
  },
  parseTestsQueryParameter: function(){
    if (window.location.search.parseQuery()["tests"]){
        return window.location.search.parseQuery()["tests"].split(',');
    };
  },
  // Returns:
  //  "ERROR" if there was an error,
  //  "FAILURE" if there was a failure, or
  //  "SUCCESS" if there was neither
  getResult: function() {
    var hasFailure = false;
    for(var i=0;i<this.tests.length;i++) {
      if (this.tests[i].errors > 0) {
        return "ERROR";
      }
      if (this.tests[i].failures > 0) {
        hasFailure = true;
      }
    }
    if (hasFailure) {
      return "FAILURE";
    } else {
      return "SUCCESS";
    }
  },
  postResults: function() {
    if (this.options.resultsURL) {
      new Ajax.Request(this.options.resultsURL,
        { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
    }
  },
  runTests: function() {
    var test = this.tests[this.currentTest];
    if (!test) {
      // finished!
      this.postResults();
      this.logger.summary(this.summary());
      return;
    }
    if(!test.isWaiting) {
      this.logger.start(test.name);
    }
    test.run();
    if(test.isWaiting) {
      this.logger.message("Waiting for " + test.timeToWait + "ms");
      setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
    } else {
      this.logger.finish(test.status(), test.summary());
      this.currentTest++;
      // tail recursive, hopefully the browser will skip the stackframe
      this.runTests();
    }
  },
  summary: function() {
    var assertions = 0;
    var failures = 0;
    var errors = 0;
    var messages = [];
    for(var i=0;i<this.tests.length;i++) {
      assertions +=   this.tests[i].assertions;
      failures   +=   this.tests[i].failures;
      errors     +=   this.tests[i].errors;
    }
    return (
      (this.options.context ? this.options.context + ': ': '') +
      this.tests.length + " tests, " +
      assertions + " assertions, " +
      failures   + " failures, " +
      errors     + " errors");
  }
}

Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
  initialize: function() {
    this.assertions = 0;
    this.failures   = 0;
    this.errors     = 0;
    this.messages   = [];
  },
  summary: function() {
    return (
      this.assertions + " assertions, " +
      this.failures   + " failures, " +
      this.errors     + " errors" + "\n" +
      this.messages.join("\n"));
  },
  pass: function() {
    this.assertions++;
  },
  fail: function(message) {
    this.failures++;
    this.messages.push("Failure: " + message);
  },
  info: function(message) {
    this.messages.push("Info: " + message);
  },
  error: function(error) {
    this.errors++;
    this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
  },
  status: function() {
    if (this.failures > 0) return 'failed';
    if (this.errors > 0) return 'error';
    return 'passed';
  },
  assert: function(expression) {
    var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
    try { expression ? this.pass() :
      this.fail(message); }
    catch(e) { this.error(e); }
  },
  assertEqual: function(expected, actual) {
    var message = arguments[2] || "assertEqual";
    try { (expected == actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertInspect: function(expected, actual) {
    var message = arguments[2] || "assertInspect";
    try { (expected == actual.inspect()) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertEnumEqual: function(expected, actual) {
    var message = arguments[2] || "assertEnumEqual";
    try { $A(expected).length == $A(actual).length &&
      expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
        this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
          ', actual ' + Test.Unit.inspect(actual)); }
    catch(e) { this.error(e); }
  },
  assertNotEqual: function(expected, actual) {
    var message = arguments[2] || "assertNotEqual";
    try { (expected != actual) ? this.pass() :
      this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertIdentical: function(expected, actual) {
    var message = arguments[2] || "assertIdentical";
    try { (expected === actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNotIdentical: function(expected, actual) {
    var message = arguments[2] || "assertNotIdentical";
    try { !(expected === actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNull: function(obj) {
    var message = arguments[1] || 'assertNull'
    try { (obj==null) ? this.pass() :
      this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
    catch(e) { this.error(e); }
  },
  assertMatch: function(expected, actual) {
    var message = arguments[2] || 'assertMatch';
    var regex = new RegExp(expected);
    try { (regex.exec(actual)) ? this.pass() :
      this.fail(message + ' : regex: "' +  Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertHidden: function(element) {
    var message = arguments[1] || 'assertHidden';
    this.assertEqual("none", element.style.display, message);
  },
  assertNotNull: function(object) {
    var message = arguments[1] || 'assertNotNull';
    this.assert(object != null, message);
  },
  assertType: function(expected, actual) {
    var message = arguments[2] || 'assertType';
    try {
      (actual.constructor == expected) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + (actual.constructor) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNotOfType: function(expected, actual) {
    var message = arguments[2] || 'assertNotOfType';
    try {
      (actual.constructor != expected) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
        '", actual "' + (actual.constructor) + '"'); }
    catch(e) { this.error(e); }
  },
  assertInstanceOf: function(expected, actual) {
    var message = arguments[2] || 'assertInstanceOf';
    try {
      (actual instanceof expected) ? this.pass() :
      this.fail(message + ": object was not an instance of the expected type"); }
    catch(e) { this.error(e); }
  },
  assertNotInstanceOf: function(expected, actual) {
    var message = arguments[2] || 'assertNotInstanceOf';
    try {
      !(actual instanceof expected) ? this.pass() :
      this.fail(message + ": object was an instance of the not expected type"); }
    catch(e) { this.error(e); }
  },
  assertRespondsTo: function(method, obj) {
    var message = arguments[2] || 'assertRespondsTo';
    try {
      (obj[method] && typeof obj[method] == 'function') ? this.pass() :
      this.fail(message + ": object doesn't respond to [" + method + "]"); }
    catch(e) { this.error(e); }
  },
  assertReturnsTrue: function(method, obj) {
    var message = arguments[2] || 'assertReturnsTrue';
    try {
      var m = obj[method];
      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
      m() ? this.pass() :
      this.fail(message + ": method returned false"); }
    catch(e) { this.error(e); }
  },
  assertReturnsFalse: function(method, obj) {
    var message = arguments[2] || 'assertReturnsFalse';
    try {
      var m = obj[method];
      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
      !m() ? this.pass() :
      this.fail(message + ": method returned true"); }
    catch(e) { this.error(e); }
  },
  assertRaise: function(exceptionName, method) {
    var message = arguments[2] || 'assertRaise';
    try {
      method();
      this.fail(message + ": exception expected but none was raised"); }
    catch(e) {
      ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
    }
  },
  assertElementsMatch: function() {
    var expressions = $A(arguments), elements = $A(expressions.shift());
    if (elements.length != expressions.length) {
      this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
      return false;
    }
    elements.zip(expressions).all(function(pair, index) {
      var element = $(pair.first()), expression = pair.last();
      if (element.match(expression)) return true;
      this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
    }.bind(this)) && this.pass();
  },
  assertElementMatches: function(element, expression) {
    this.assertElementsMatch([element], expression);
  },
  benchmark: function(operation, iterations) {
    var startAt = new Date();
    (iterations || 1).times(operation);
    var timeTaken = ((new Date())-startAt);
    this.info((arguments[2] || 'Operation') + ' finished ' +
       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
    return timeTaken;
  },
  _isVisible: function(element) {
    element = $(element);
    if(!element.parentNode) return true;
    this.assertNotNull(element);
    if(element.style && Element.getStyle(element, 'display') == 'none')
      return false;

    return this._isVisible(element.parentNode);
  },
  assertNotVisible: function(element) {
    this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
  },
  assertVisible: function(element) {
    this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
  },
  benchmark: function(operation, iterations) {
    var startAt = new Date();
    (iterations || 1).times(operation);
    var timeTaken = ((new Date())-startAt);
    this.info((arguments[2] || 'Operation') + ' finished ' +
       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
    return timeTaken;
  }
}

Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
  initialize: function(name, test, setup, teardown) {
    Test.Unit.Assertions.prototype.initialize.bind(this)();
    this.name           = name;

    if(typeof test == 'string') {
      test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
      test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
      this.test = function() {
        eval('with(this){'+test+'}');
      }
    } else {
      this.test = test || function() {};
    }

    this.setup          = setup || function() {};
    this.teardown       = teardown || function() {};
    this.isWaiting      = false;
    this.timeToWait     = 1000;
  },
  wait: function(time, nextPart) {
    this.isWaiting = true;
    this.test = nextPart;
    this.timeToWait = time;
  },
  run: function() {
    try {
      try {
        if (!this.isWaiting) this.setup.bind(this)();
        this.isWaiting = false;
        this.test.bind(this)();
      } finally {
        if(!this.isWaiting) {
          this.teardown.bind(this)();
        }
      }
    }
    catch(e) { this.error(e); }
  }
});

// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/

Test.setupBDDExtensionMethods = function(){
  var METHODMAP = {
    shouldEqual:     'assertEqual',
    shouldNotEqual:  'assertNotEqual',
    shouldEqualEnum: 'assertEnumEqual',
    shouldBeA:       'assertType',
    shouldNotBeA:    'assertNotOfType',
    shouldBeAn:      'assertType',
    shouldNotBeAn:   'assertNotOfType',
    shouldBeNull:    'assertNull',
    shouldNotBeNull: 'assertNotNull',

    shouldBe:        'assertReturnsTrue',
    shouldNotBe:     'assertReturnsFalse',
    shouldRespondTo: 'assertRespondsTo'
  };
  Test.BDDMethods = {};
  for(m in METHODMAP) {
    Test.BDDMethods[m] = eval(
      'function(){'+
      'var args = $A(arguments);'+
      'var scope = args.shift();'+
      'scope.'+METHODMAP[m]+'.apply(scope,(args || []).concat([this])); }');
  }
  [Array.prototype, String.prototype, Number.prototype].each(
    function(p){ Object.extend(p, Test.BDDMethods) }
  );
}

Test.context = function(name, spec, log){
  Test.setupBDDExtensionMethods();

  var compiledSpec = {};
  var titles = {};
  for(specName in spec) {
    switch(specName){
      case "setup":
      case "teardown":
        compiledSpec[specName] = spec[specName];
        break;
      default:
        var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
        var body = spec[specName].toString().split('\n').slice(1);
        if(/^\{/.test(body[0])) body = body.slice(1);
        body.pop();
        body = body.map(function(statement){
          return statement.strip()
        });
        compiledSpec[testName] = body.join('\n');
        titles[testName] = specName;
    }
  }
  new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
};


text:
/****************************************************************************************
** Superclass of all other classes that define Features. It is required from classes that
** inherit from Features to implement the virtual methods getActiveFeaturesIndices and
** getNumberOfFeatures, which are operations specific to the kind of selected features.
** It already implements getCompleteFeatureVector, which can be used if someone needs the
** complete feature vector. This is not an efficient approach.
**
** TODO: Right now this class only deals with binary features, it may be necessary to
**       further extend such approach.
**
** Author: Marlos C. Machado
***************************************************************************************/

#ifndef ALE_INTERFACE_H
#define ALE_INTERFACE_H
#include <ale_interface.hpp>
#endif

class Features{
	private:

	public:
		/**
 		* This method was created to allow optimizations in codes that use such features.
 		* Since several feature definitions generate sparse feature vectors it is much
 		* better to just iterate over the active features. This method allows it by
 		* providing a vector with the indices of active features. Recall we assume the
 		* features to be binary. Each implementation of a feature needs to instantiate this
 		* method.
 		*
 		* REMARKS: - It is necessary to provide both the screen and the ram as one may
 		* want to use both data to generate features.
 		*          - To avoid return huge vectors, this method is void and the appropriate
 		* vector is returned trough a parameter passed by reference
 		*
 		* TODO: If one intends to use non-binary features this class is not suitable.
 		*
 		* @param ALEScreen &screen is the current game screen that one may use to extract features.
 		* @param ALERAM &ram is the current game RAM that one may use to extract features.
 		* @param vector<int>& features an empy vector that will be filled with the requested information,
 		*        therefore it must be passed by reference.
 		*
 		* @return nothing since one will receive the requested data by the last parameter, by reference.
 		*/
		virtual void getActiveFeaturesIndices(const ALEScreen &screen, const ALERAM &ram, std::vector<int>& features) = 0;
		/**
 		* It 'returns' a binary vector containing 1's where the feature is active. Ideally this
 		* method will never be used as iterating over all features is far less efficient than
 		* iterating over the set of active features.
 		*
 		* REMARKS: - It is necessary to provide both the screen and the ram as one may
 		* want to use both data to generate features.
 		*          - To avoid return huge vectors, this method is void and the appropriate
 		* vector is returned trough a parameter passed by reference
 		*
 		* TODO: If one intends to use non-binary features this class is not suitable.
 		*
 		* @param ALEScreen &screen is the current game screen that one may use to extract features.
 		* @param ALERAM &ram is the current game RAM that one may use to extract features.
 		* @param vector<bool>& features an empy vector that will be filled with the requested information,
 		*        therefore it must be passed by reference. Its i-th position is TRUE if the i-th feature is active.
 		* @return nothing since one will receive the requested data by the last parameter, by reference.
 		*/
		void getCompleteFeatureVector(const ALEScreen &screen, const ALERAM &ram, std::vector<bool>& features);
		/**
 		* This pure virtual method must be implemented by every class inhereting from this one.
 		* It returns the number of features existent in the defined representation. It is the total size,
 		* not necessarily the number of features active or anything similar. Notice it does not even
 		* has access to the feature vector.
 		*
 		* @param none
 		* @return integer representing the number of features of a given representation.
 		*/
		virtual int getNumberOfFeatures() = 0;
		/**
		* Destructor, not necessary in this class.
		*/
		virtual ~Features();
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PublishConfigData" autoUpload="Always" serverName="localhost" persistUploadOnCheckin="false" autoUploadExternalChanges="true">
    <serverData>
      <paths name="localhost">
        <serverdata>
          <mappings>
            <mapping deploy="/" local="$PROJECT_DIR$" web="/" />
          </mappings>
        </serverdata>
      </paths>
    </serverData>
    <option name="myAutoUpload" value="ALWAYS" />
  </component>
</project>


text:
package resumeonline.commons.exeception;

public final class PropertyNotFound
    extends
    ApplicationRuntimeException {

    private static final long serialVersionUID = 2224442095254416154L;

    public PropertyNotFound(
        final String file,
        final String name) {
        super(String.format("Property [%s] not found in file [%s]", name, file));
    }
}


text:
package org.jetbrains.plugins.scala.codeInspection.scalastyle

import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.vfs.{VfsUtil, VirtualFile}
import org.jetbrains.plugins.scala.codeInspection.ScalaInspectionTestBase

class ScalastyleTest extends ScalaInspectionTestBase {

  val config =
    <scalastyle commentFilter="enabled">
      <name>Scalastyle standard configuration</name>
      <check level="warning" class="org.scalastyle.scalariform.ClassNamesChecker" enabled="true">
        <parameters>
          <parameter name="regex">[A-Z][A-Za-z]*</parameter>
        </parameters>
      </check>
    </scalastyle>

  val configString = config.toString()

  override protected val classOfInspection: Class[_ <: LocalInspectionTool] =
    classOf[ScalastyleCodeInspection]

  override protected val description = "Class name does not match the regular expression '[A-Z][A-Za-z]*'."

  private def setup(): Unit = {
    myFixture.addFileToProject("scalastyle-config.xml", configString)
  }

  def test_ok(): Unit = {
    setup()

    checkTextHasNoErrors(
      """
        |class Test
      """.stripMargin
    )
  }

  def test(): Unit = {
    setup()

    checkTextHasError(
      s"""
         |${START}class test$END
      """.stripMargin
    )
  }

  def testFallback(): Unit = {
    def getOrCreateFile(dir: VirtualFile, file: String): VirtualFile =
      Option(dir.findChild(file)).getOrElse(dir.createChildData(this, file))

    WriteAction.runAndWait { () =>
      val baseDir = VfsUtil.createDirectoryIfMissing(getProject.getBasePath)
      val file = getOrCreateFile(baseDir, "scalastyle-config.xml")
      VfsUtil.saveText(file, configString)
    }

    checkTextHasError(
      s"""
         |${START}class test$END
      """.stripMargin
    )
  }
}


text:
var app = app || {};

app.commentView = (function () {
    function CommentView(selector, data) {
        var defer = Q.defer();

        $.get('templates/comment-view.html', function (template) {
            var temp = Handlebars.compile(template);
            var html = temp(data);
            $(selector).html(html);
        }).success(function (data) {
            defer.resolve(data);
        }).error(function (error) {
            defer.reject(error);
        });
        return defer.promise;
    }

    return {
        load: function (selectors, data) {
            return new CommentView(selectors, data);
        }
    }
}());


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;

namespace _073_093_LINQ___Aggregate_Operators
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            LinqSamples samples = new LinqSamples();

            //Comment or uncomment the method calls below to run or not

            samples.Linq73(); // This sample uses Count to get the number of unique prime factors of 300
            //samples.Linq74(); // This sample uses Count to get the number of odd ints in the array
            //samples.Linq76(); // This sample uses Count to return a list of customers and how many orders each has

            //samples.Linq77(); // This sample uses Count to return a list of categories and how many products each has
            //samples.Linq78(); // This sample uses Sum to add all the numbers in an array
            //samples.Linq79(); // This sample uses Sum to get the total number of characters of all words in the array

            //samples.Linq80(); // This sample uses Sum to get the total units in stock for each product category
            //samples.Linq81(); // This sample uses Min to get the lowest number in an array
            //samples.Linq82(); // This sample uses Min to get the length of the shortest word in an array

            //samples.Linq83(); // This sample uses Min to get the cheapest price among each category's products
            //samples.Linq84(); // This sample uses Min to get the products with the lowest price in each category

            //samples.Linq85(); // This sample uses Max to get the highest number in an array. Note that the method
            // returns a single value

            //samples.Linq86(); // This sample uses Max to get the length of the longest word in an array
            //samples.Linq87(); // This sample uses Max to get the most expensive price among each category's products
            //samples.Linq88(); // This sample uses Max to get the products with the most expensive price in each category

            //samples.Linq89(); // This sample uses Average to get the average of all numbers in an array
            //samples.Linq90(); // This sample uses Average to get the average length of the words in the array
            //samples.Linq91(); // This sample uses Average to get the average price of each category's products

            //samples.Linq92(); // This sample uses Aggregate to create a running product on the array that calculates
            // the total product of all elements

            //samples.Linq93(); // This sample uses Aggregate to create a running account balance that subtracts each
            // withdrawal from the initial balance of 100, as long as the balance never drops below 0

            Console.ReadKey();
        }

        public class Product
        {
            public int ProductID { get; set; }
            public string ProductName { get; set; }
            public string Category { get; set; }
            public decimal UnitPrice { get; set; }
            public int UnitsInStock { get; set; }
        }

        public class Order
        {
            public int OrderID { get; set; }
            public DateTime OrderDate { get; set; }
            public decimal Total { get; set; }
        }

        public class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string Address { get; set; }
            public string City { get; set; }
            public string Region { get; set; }
            public string PostalCode { get; set; }
            public string Country { get; set; }
            public string Phone { get; set; }
            public string Fax { get; set; }
            public Order[] Orders { get; set; }
        }

        private class LinqSamples
        {
            private List<Product> productList;
            private List<Customer> customerList;

            [Category("Aggregate Operators")]
            [Description("This sample uses Count to get the number of unique prime factors of 300.")]
            public void Linq73()
            {
                int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };

                int uniqueFactors = primeFactorsOf300.Distinct().Count();

                Console.WriteLine("There are {0} unique prime factors of 300.", uniqueFactors);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Count to get the number of odd ints in the array.")]
            public void Linq74()
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                int oddNumbers = numbers.Count(n => n % 2 == 1);

                Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Count to return a list of customers and how many orders each has.")]
            public void Linq76()
            {
                List<Customer> customers = GetCustomerList();

                var orderCounts =
                    from cust in customers
                    select new { cust.CustomerID, OrderCount = cust.Orders.Count() };

                ObjectDumper.Write(orderCounts);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Count to return a list of categories and how many products each has.")]
            public void Linq77()
            {
                List<Product> products = GetProductList();

                var categoryCounts =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    select new { Category = prodGroup.Key, ProductCount = prodGroup.Count() };

                ObjectDumper.Write(categoryCounts);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Sum to add all the numbers in an array.")]
            public void Linq78()
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                double numSum = numbers.Sum();

                Console.WriteLine("The sum of the numbers is {0}.", numSum);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Sum to get the total number of characters of all words in the array.")]
            public void Linq79()
            {
                string[] words = { "cherry", "apple", "blueberry" };

                double totalChars = words.Sum(w => w.Length);

                Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Sum to get the total units in stock for each product category.")]
            public void Linq80()
            {
                List<Product> products = GetProductList();

                var categories =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    select new { Category = prodGroup.Key, TotalUnitsInStock = prodGroup.Sum(p => p.UnitsInStock) };

                ObjectDumper.Write(categories);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Min to get the lowest number in an array.")]
            public void Linq81()
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                int minNum = numbers.Min();

                Console.WriteLine("The minimum number is {0}.", minNum);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Min to get the length of the shortest word in an array.")]
            public void Linq82()
            {
                string[] words = { "cherry", "apple", "blueberry" };

                int shortestWord = words.Min(w => w.Length);

                Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Min to get the cheapest price among each category's products.")]
            public void Linq83()
            {
                List<Product> products = GetProductList();

                var categories =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    select new { Category = prodGroup.Key, CheapestPrice = prodGroup.Min(p => p.UnitPrice) };

                ObjectDumper.Write(categories);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Min to get the products with the lowest price in each category.")]
            public void Linq84()
            {
                List<Product> products = GetProductList();

                var categories =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    let minPrice = prodGroup.Min(p => p.UnitPrice)
                    select new { Category = prodGroup.Key, CheapestProducts = prodGroup.Where(p => p.UnitPrice == minPrice) };

                ObjectDumper.Write(categories, 1);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Max to get the highest number in an array. Note that the method returns a single value.")]
            public void Linq85()
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                int maxNum = numbers.Max();

                Console.WriteLine("The maximum number is {0}.", maxNum);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Max to get the length of the longest word in an array.")]
            public void Linq86()
            {
                string[] words = { "cherry", "apple", "blueberry" };

                int longestLength = words.Max(w => w.Length);

                Console.WriteLine("The longest word is {0} characters long.", longestLength);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Max to get the most expensive price among each category's products.")]
            public void Linq87()
            {
                List<Product> products = GetProductList();

                var categories =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    select new { Category = prodGroup.Key, MostExpensivePrice = prodGroup.Max(p => p.UnitPrice) };

                ObjectDumper.Write(categories);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Max to get the products with the most expensive price in each category.")]
            public void Linq88()
            {
                List<Product> products = GetProductList();

                var categories =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    let maxPrice = prodGroup.Max(p => p.UnitPrice)
                    select new { Category = prodGroup.Key, MostExpensiveProducts = prodGroup.Where(p => p.UnitPrice == maxPrice) };

                ObjectDumper.Write(categories, 1);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Average to get the average of all numbers in an array.")]
            public void Linq89()
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                double averageNum = numbers.Average();

                Console.WriteLine("The average number is {0}.", averageNum);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Average to get the average length of the words in the array.")]
            public void Linq90()
            {
                string[] words = { "cherry", "apple", "blueberry" };

                double averageLength = words.Average(w => w.Length);

                Console.WriteLine("The average word length is {0} characters.", averageLength);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Average to get the average price of each category's products.")]
            public void Linq91()
            {
                List<Product> products = GetProductList();

                var categories =
                    from prod in products
                    group prod by prod.Category into prodGroup
                    select new { Category = prodGroup.Key, AveragePrice = prodGroup.Average(p => p.UnitPrice) };

                ObjectDumper.Write(categories);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Aggregate to create a running product on the array that calculates the total product of all elements.")]
            public void Linq92()
            {
                double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

                double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);

                Console.WriteLine("Total product of all numbers: {0}", product);
            }

            [Category("Aggregate Operators")]
            [Description("This sample uses Aggregate to create a running account balance that subtracts each withdrawal from the initial balance of 100, as long as the balance never drops below 0.")]
            public void Linq93()
            {
                double startBalance = 100.0;

                int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };

                double endBalance =
                    attemptedWithdrawals.Aggregate(startBalance,
                        (balance, nextWithdrawal) =>
                            ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));

                Console.WriteLine("Ending balance: {0}", endBalance);
            }

            public List<Product> GetProductList()
            {
                if (productList == null)
                    createLists();

                return productList;
            }

            public List<Customer> GetCustomerList()
            {
                if (customerList == null)
                    createLists();

                return customerList;
            }

            private void createLists()
            {
                // Product data created in-memory using collection initializer:
                productList =
                    new List<Product> {
                    new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 },
                    new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 },
                    new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 },
                    new Product { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53 },
                    new Product { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0 },
                    new Product { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", UnitPrice = 25.0000M, UnitsInStock = 120 },
                    new Product { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", UnitPrice = 30.0000M, UnitsInStock = 15 },
                    new Product { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", UnitPrice = 40.0000M, UnitsInStock = 6 },
                    new Product { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", UnitPrice = 97.0000M, UnitsInStock = 29 },
                    new Product { ProductID = 10, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 31 },
                    new Product { ProductID = 11, ProductName = "Queso Cabrales", Category = "Dairy Products", UnitPrice = 21.0000M, UnitsInStock = 22 },
                    new Product { ProductID = 12, ProductName = "Queso Manchego La Pastora", Category = "Dairy Products", UnitPrice = 38.0000M, UnitsInStock = 86 },
                    new Product { ProductID = 13, ProductName = "Konbu", Category = "Seafood", UnitPrice = 6.0000M, UnitsInStock = 24 },
                    new Product { ProductID = 14, ProductName = "Tofu", Category = "Produce", UnitPrice = 23.2500M, UnitsInStock = 35 },
                    new Product { ProductID = 15, ProductName = "Genen Shouyu", Category = "Condiments", UnitPrice = 15.5000M, UnitsInStock = 39 },
                    new Product { ProductID = 16, ProductName = "Pavlova", Category = "Confections", UnitPrice = 17.4500M, UnitsInStock = 29 },
                    new Product { ProductID = 17, ProductName = "Alice Mutton", Category = "Meat/Poultry", UnitPrice = 39.0000M, UnitsInStock = 0 },
                    new Product { ProductID = 18, ProductName = "Carnarvon Tigers", Category = "Seafood", UnitPrice = 62.5000M, UnitsInStock = 42 },
                    new Product { ProductID = 19, ProductName = "Teatime Chocolate Biscuits", Category = "Confections", UnitPrice = 9.2000M, UnitsInStock = 25 },
                    new Product { ProductID = 20, ProductName = "Sir Rodney's Marmalade", Category = "Confections", UnitPrice = 81.0000M, UnitsInStock = 40 },
                    new Product { ProductID = 21, ProductName = "Sir Rodney's Scones", Category = "Confections", UnitPrice = 10.0000M, UnitsInStock = 3 },
                    new Product { ProductID = 22, ProductName = "Gustaf's Knäckebröd", Category = "Grains/Cereals", UnitPrice = 21.0000M, UnitsInStock = 104 },
                    new Product { ProductID = 23, ProductName = "Tunnbröd", Category = "Grains/Cereals", UnitPrice = 9.0000M, UnitsInStock = 61 },
                    new Product { ProductID = 24, ProductName = "Guaraná Fantástica", Category = "Beverages", UnitPrice = 4.5000M, UnitsInStock = 20 },
                    new Product { ProductID = 25, ProductName = "NuNuCa Nuß-Nougat-Creme", Category = "Confections", UnitPrice = 14.0000M, UnitsInStock = 76 },
                    new Product { ProductID = 26, ProductName = "Gumbär Gummibärchen", Category = "Confections", UnitPrice = 31.2300M, UnitsInStock = 15 },
                    new Product { ProductID = 27, ProductName = "Schoggi Schokolade", Category = "Confections", UnitPrice = 43.9000M, UnitsInStock = 49 },
                    new Product { ProductID = 28, ProductName = "Rössle Sauerkraut", Category = "Produce", UnitPrice = 45.6000M, UnitsInStock = 26 },
                    new Product { ProductID = 29, ProductName = "Thüringer Rostbratwurst", Category = "Meat/Poultry", UnitPrice = 123.7900M, UnitsInStock = 0 },
                    new Product { ProductID = 30, ProductName = "Nord-Ost Matjeshering", Category = "Seafood", UnitPrice = 25.8900M, UnitsInStock = 10 },
                    new Product { ProductID = 31, ProductName = "Gorgonzola Telino", Category = "Dairy Products", UnitPrice = 12.5000M, UnitsInStock = 0 },
                    new Product { ProductID = 32, ProductName = "Mascarpone Fabioli", Category = "Dairy Products", UnitPrice = 32.0000M, UnitsInStock = 9 },
                    new Product { ProductID = 33, ProductName = "Geitost", Category = "Dairy Products", UnitPrice = 2.5000M, UnitsInStock = 112 },
                    new Product { ProductID = 34, ProductName = "Sasquatch Ale", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 111 },
                    new Product { ProductID = 35, ProductName = "Steeleye Stout", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 20 },
                    new Product { ProductID = 36, ProductName = "Inlagd Sill", Category = "Seafood", UnitPrice = 19.0000M, UnitsInStock = 112 },
                    new Product { ProductID = 37, ProductName = "Gravad lax", Category = "Seafood", UnitPrice = 26.0000M, UnitsInStock = 11 },
                    new Product { ProductID = 38, ProductName = "Côte de Blaye", Category = "Beverages", UnitPrice = 263.5000M, UnitsInStock = 17 },
                    new Product { ProductID = 39, ProductName = "Chartreuse verte", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 69 },
                    new Product { ProductID = 40, ProductName = "Boston Crab Meat", Category = "Seafood", UnitPrice = 18.4000M, UnitsInStock = 123 },
                    new Product { ProductID = 41, ProductName = "Jack's New England Clam Chowder", Category = "Seafood", UnitPrice = 9.6500M, UnitsInStock = 85 },
                    new Product { ProductID = 42, ProductName = "Singaporean Hokkien Fried Mee", Category = "Grains/Cereals", UnitPrice = 14.0000M, UnitsInStock = 26 },
                    new Product { ProductID = 43, ProductName = "Ipoh Coffee", Category = "Beverages", UnitPrice = 46.0000M, UnitsInStock = 17 },
                    new Product { ProductID = 44, ProductName = "Gula Malacca", Category = "Condiments", UnitPrice = 19.4500M, UnitsInStock = 27 },
                    new Product { ProductID = 45, ProductName = "Rogede sild", Category = "Seafood", UnitPrice = 9.5000M, UnitsInStock = 5 },
                    new Product { ProductID = 46, ProductName = "Spegesild", Category = "Seafood", UnitPrice = 12.0000M, UnitsInStock = 95 },
                    new Product { ProductID = 47, ProductName = "Zaanse koeken", Category = "Confections", UnitPrice = 9.5000M, UnitsInStock = 36 },
                    new Product { ProductID = 48, ProductName = "Chocolade", Category = "Confections", UnitPrice = 12.7500M, UnitsInStock = 15 },
                    new Product { ProductID = 49, ProductName = "Maxilaku", Category = "Confections", UnitPrice = 20.0000M, UnitsInStock = 10 },
                    new Product { ProductID = 50, ProductName = "Valkoinen suklaa", Category = "Confections", UnitPrice = 16.2500M, UnitsInStock = 65 },
                    new Product { ProductID = 51, ProductName = "Manjimup Dried Apples", Category = "Produce", UnitPrice = 53.0000M, UnitsInStock = 20 },
                    new Product { ProductID = 52, ProductName = "Filo Mix", Category = "Grains/Cereals", UnitPrice = 7.0000M, UnitsInStock = 38 },
                    new Product { ProductID = 53, ProductName = "Perth Pasties", Category = "Meat/Poultry", UnitPrice = 32.8000M, UnitsInStock = 0 },
                    new Product { ProductID = 54, ProductName = "Tourtière", Category = "Meat/Poultry", UnitPrice = 7.4500M, UnitsInStock = 21 },
                    new Product { ProductID = 55, ProductName = "Pâté chinois", Category = "Meat/Poultry", UnitPrice = 24.0000M, UnitsInStock = 115 },
                    new Product { ProductID = 56, ProductName = "Gnocchi di nonna Alice", Category = "Grains/Cereals", UnitPrice = 38.0000M, UnitsInStock = 21 },
                    new Product { ProductID = 57, ProductName = "Ravioli Angelo", Category = "Grains/Cereals", UnitPrice = 19.5000M, UnitsInStock = 36 },
                    new Product { ProductID = 58, ProductName = "Escargots de Bourgogne", Category = "Seafood", UnitPrice = 13.2500M, UnitsInStock = 62 },
                    new Product { ProductID = 59, ProductName = "Raclette Courdavault", Category = "Dairy Products", UnitPrice = 55.0000M, UnitsInStock = 79 },
                    new Product { ProductID = 60, ProductName = "Camembert Pierrot", Category = "Dairy Products", UnitPrice = 34.0000M, UnitsInStock = 19 },
                    new Product { ProductID = 61, ProductName = "Sirop d'érable", Category = "Condiments", UnitPrice = 28.5000M, UnitsInStock = 113 },
                    new Product { ProductID = 62, ProductName = "Tarte au sucre", Category = "Confections", UnitPrice = 49.3000M, UnitsInStock = 17 },
                    new Product { ProductID = 63, ProductName = "Vegie-spread", Category = "Condiments", UnitPrice = 43.9000M, UnitsInStock = 24 },
                    new Product { ProductID = 64, ProductName = "Wimmers gute Semmelknödel", Category = "Grains/Cereals", UnitPrice = 33.2500M, UnitsInStock = 22 },
                    new Product { ProductID = 65, ProductName = "Louisiana Fiery Hot Pepper Sauce", Category = "Condiments", UnitPrice = 21.0500M, UnitsInStock = 76 },
                    new Product { ProductID = 66, ProductName = "Louisiana Hot Spiced Okra", Category = "Condiments", UnitPrice = 17.0000M, UnitsInStock = 4 },
                    new Product { ProductID = 67, ProductName = "Laughing Lumberjack Lager", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 52 },
                    new Product { ProductID = 68, ProductName = "Scottish Longbreads", Category = "Confections", UnitPrice = 12.5000M, UnitsInStock = 6 },
                    new Product { ProductID = 69, ProductName = "Gudbrandsdalsost", Category = "Dairy Products", UnitPrice = 36.0000M, UnitsInStock = 26 },
                    new Product { ProductID = 70, ProductName = "Outback Lager", Category = "Beverages", UnitPrice = 15.0000M, UnitsInStock = 15 },
                    new Product { ProductID = 71, ProductName = "Flotemysost", Category = "Dairy Products", UnitPrice = 21.5000M, UnitsInStock = 26 },
                    new Product { ProductID = 72, ProductName = "Mozzarella di Giovanni", Category = "Dairy Products", UnitPrice = 34.8000M, UnitsInStock = 14 },
                    new Product { ProductID = 73, ProductName = "Röd Kaviar", Category = "Seafood", UnitPrice = 15.0000M, UnitsInStock = 101 },
                    new Product { ProductID = 74, ProductName = "Longlife Tofu", Category = "Produce", UnitPrice = 10.0000M, UnitsInStock = 4 },
                    new Product { ProductID = 75, ProductName = "Rhönbräu Klosterbier", Category = "Beverages", UnitPrice = 7.7500M, UnitsInStock = 125 },
                    new Product { ProductID = 76, ProductName = "Lakkalikööri", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 57 },
                    new Product { ProductID = 77, ProductName = "Original Frankfurter grüne Soße", Category = "Condiments", UnitPrice = 13.0000M, UnitsInStock = 32 }
                };

                // Customer/Order data read into memory from XML file using XLinq:
                customerList = (
                    from e in XDocument.Load("Customers.xml").
                              Root.Elements("customer")
                    select new Customer
                    {
                        CustomerID = (string)e.Element("id"),
                        CompanyName = (string)e.Element("name"),
                        Address = (string)e.Element("address"),
                        City = (string)e.Element("city"),
                        Region = (string)e.Element("region"),
                        PostalCode = (string)e.Element("postalcode"),
                        Country = (string)e.Element("country"),
                        Phone = (string)e.Element("phone"),
                        Fax = (string)e.Element("fax"),
                        Orders = (
                            from o in e.Elements("orders").Elements("order")
                            select new Order
                            {
                                OrderID = (int)o.Element("id"),
                                OrderDate = (DateTime)o.Element("orderdate"),
                                Total = (decimal)o.Element("total")
                            })
                            .ToArray()
                    })
                    .ToList();
            }
        }
    }
}


text:
package fish

object MixedLanguageDependent {
  final val poem = List(JavaSource.line, ScalaSource.line).mkString("\n")
}