text:
craftEd.controller('RatingController', ['$scope', '$http', '$location', '$state',function($scope, $http, $location, $state) {

  // $scope.$on("$ionicView.enter", function(){
  //   console.log("hi!")
  //   $state.go($state.current, {reload: true, inherit: false});
  // })

  var config = {
    headers: {
      'content-type': 'application/json'
    }
  }

  var beerId = $state.params.beerId;

  var tokens = {
    headers: {
      "access-token": window.sessionStorage.token,
      "token-type": "Bearer",
      "client": window.sessionStorage.client,
      "expiry": window.sessionStorage.expiry,
      "uid": window.sessionStorage.uid
    }
  };

  var tokensConfig = {
    headers: {
      'content-type': 'application/json',
      "access-token": window.sessionStorage.token,
      "token-type": "Bearer",
      "client": window.sessionStorage.client,
      "expiry": window.sessionStorage.expiry,
      "uid": window.sessionStorage.uid
    }
  };

  $http.get(rootUrl + '/users/:user_id/beer_types/' + beerId + '/tried_beer_ratings/new', tokensConfig)
    .then(function(response){
      $scope.allTags= response.data

      $scope.selection = [];

      $scope.toggleSelection = function toggleSelection(tag) {
        var idx = $scope.selection.indexOf(tag.id);
        var flavorSelector = angular.element(document.querySelector('tag-select-box'));
        if (idx > -1) {
            $scope.selection.splice(idx, 1);
            document.getElementById("tag-label-" + tag.id).className = " tag ng-binding"
          }

        else {
          $scope.selection.push(tag.id);
          document.getElementById("tag-label-" + tag.id).className += " selected"
        }
      };
    });

  $scope.submitRating = function(){
    $scope.selection.push($scope.allTags.mainType.id);
    data = {tagIds: $scope.selection, comment: $scope.comment, rating: $scope.rating};
    $http.post(rootUrl +'/users/:user_id/tried_beer_ratings', data, tokens)
      .then(function(response){
      $state.go('app.info');

    })
  }

}]);

redpajama_set_name: RedPajamaGithub


text:
@implementation UITextField (LclExtension)

+ (instancetype)lcl_textFieldWithPlaceHolder:(NSString *)placeHolder fontSize:(CGFloat)fontSize color:(UIColor *)color imageName:(NSString *)imageName {

    UITextField *txtFld = [[self alloc] init];
    txtFld.placeholder = placeHolder;
    txtFld.textAlignment = NSTextAlignmentLeft;
    txtFld.textColor = color;

    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:placeHolder attributes:@{
                                                                                NSForegroundColorAttributeName : color,NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}
                                      ];
    txtFld.attributedPlaceholder = str;

    txtFld.font = [UIFont systemFontOfSize:fontSize];

    if (imageName.length > 0) {

        txtFld.leftViewMode = UITextFieldViewModeAlways;
        UIImage *img = [UIImage imageNamed:imageName];
        //        img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

        UIImageView *imgV = [[UIImageView alloc] init];
        //        imgV.tintColor = [UIColor lcl_colorWithHex:0xffffff];
        imgV.image = img;

        txtFld.leftView = imgV;
    }

    txtFld.clearButtonMode = UITextFieldViewModeAlways;

    return txtFld;
}

@end


text:
<?php
$label_col_sm_size = 3;
$posted = Arr::filter_keys($val->validated(), array(conf('csrf_token_key', 'security')), true);
?>

<?php echo __('message_send_confirm_following_contents'); ?>

<?php echo form_open(false, false, array('action' => 'contact/send'), $posted); ?>
<?php
if ($confs = conf('contact.fields.pre', 'contact'))
{
	foreach ($confs as $name => $props)
	{
		$value = $name == 'category' ? t('contact.fields.pre.category.options.'.$posted[$name]) : $posted[$name];
		echo form_text($value, Site_Form::get_label($val, $name), $label_col_sm_size);
	}
}
?>

	<?php echo form_text($posted['body'], Site_Form::get_label($val, 'body'), $label_col_sm_size, false, null, true); ?>

<?php
if ($confs = conf('contact.fields.post', 'contact'))
{
	foreach ($confs as $name => $props)
	{
		echo form_text($posted[$name], Site_Form::get_label($val, $name), $label_col_sm_size);
	}
}
?>
	<?php echo form_button('form.do_send', 'submit', 'submit', array('class' => 'btn btn-default btn-primary'), $label_col_sm_size); ?>
<?php echo form_close(); ?>

<?php echo form_open(false, false, array('action' => 'contact'), $posted); ?>
	<?php //echo Form::hidden('password', $input['password'], array('dont_prep' => true)); ?>
	<?php echo form_button('form.back', 'submit', 'submit_back', array('class' => 'btn btn-default'), $label_col_sm_size); ?>
<?php echo form_close(); ?>


text:
    This app uses a controller and service to make RESTful calls to
    my blog (running on a remote Drupal CMS), and retrieves either a list of all published posts or a post from that list. Angular promises are used to handle return values, and strict contextual escaping is used on individual post content.

The parent controller stores the list in its scope, and a child controller processes the specific post. The blog domain is prepended to URLs for all images hosted on that domain. Some older articles have different styles.

GitHub Repo

	<button type="button" class="btn btn-primary">Blog List</button>


text:
namespace RecommendationSystem.Naive.MostCommonRating
{
    public class MostCommonRatingModel : IMostCommonRatingModel
    {
        public float MostCommonRating { get; set; }

        public MostCommonRatingModel(float mostCommonRating)
        {
            MostCommonRating = mostCommonRating;
        }
    }
}


text:
/* globals module */
/**
 * @module baasicArticleFilesRouteService
 * @description Baasic Article Files Route Service provides Baasic route templates which can be expanded to Baasic REST URIs. Various services can use Baasic Article Files Route Service to obtain needed routes while other routes will be obtained through HAL. By convention, all route services use the same function names as their corresponding services.
*/
(function (angular, module, undefined) {
    'use strict';
    module.service('baasicArticleFilesRouteService', ['baasicUriTemplateService',
        function (uriTemplateService) {
            return {
                /**
                * Parses find route which can be expanded with additional options. Supported items are:
                * - `searchQuery` - A string referencing file properties using the phrase search.
                * - `page` - A value used to set the page number, i.e. to retrieve certain file subset from the storage.
                * - `rpp` - A value used to limit the size of result set per page.
                * - `sort` - A string used to set the file property to sort the result collection by.
				* - `embed` - Comma separated list of resources to be contained within the current representation.
                * @method
                * @example
baasicArticleFilesRouteService.find.expand(
    {searchQuery: '<search-phrase>'}
);
                **/
                find: uriTemplateService.parse('article-files/{?searchQuery,page,rpp,sort,embed,fields}'),

                /**
                * Parses get route; this route should be expanded with the Id of the file resource.
                * @method
                * @example
baasicArticleFilesRouteService.get.expand(
    {id: '<file-id>'}
);
                **/
                get: uriTemplateService.parse('article-files/{id}/{?embed,fields}'),

                /**
                * Parses link route; this URI template does not expose any additional options.
                * @method
                * @example baasicArticleFilesRouteService.link.expand({});
                **/
                link: uriTemplateService.parse('article-files/link'),

                streams: {
                    /**
                    * Parses get route; this route should be expanded with id of desired file stream. Additional supported items are:
                    * - `width` - width of desired derived image.
                    * - `height` - height of desired derived image.
                    * @method streams.get
                    * @example
baasicArticleFilesRouteService.streams.get.expand(
    {id: '<filename>'}
);
                    **/
                    get: uriTemplateService.parse('article-file-streams/{id}/{?width,height}'),

                    /**
                    * Parses create route; this route should be expanded with the filename which indicates where the stream will be saved.
                    * @method streams.create
                    * @example
baasicArticleFilesRouteService.streams.create.expand(
    {filename: '<filename>'}
);
                    **/
                    create: uriTemplateService.parse('article-file-streams/{filename}/{?articleId}'),

                    /**
                    * Parses update route; this route should be expanded with the id of the previously saved resource. Additional supported items are:
                    * - `width` - width of derived image to update.
                    * - `height` - height of derived image to update.
                    * @method streams.update
                    * @example
baasicArticleFilesRouteService.streams.update.expand(
    {id: '<filename>'}
);
                    **/
                    update: uriTemplateService.parse('article-file-streams/{id}/{?width,height}')

                },

                batch: {
                    /**
                    * Parses unlink route; this URI template does not expose any additional options.
                    * @method batch.unlink
                    * @example baasicArticleFilesRouteService.batch.unlink.expand({});
                    **/
                    unlink: uriTemplateService.parse('article-files/batch/unlink'),

                    /**
                    * Parses update route; this URI template does not expose any additional options.
                    * @method batch.update
                    * @example baasicArticleFilesRouteService.batch.update.expand({});
                    **/
                    update: uriTemplateService.parse('article-files/batch'),

                    /**
                    * Parses update route; this URI template does not expose any additional options.
                    * @method batch.link
                    * @example baasicArticleFilesRouteService.batch.link.expand({});
                    **/
                    link: uriTemplateService.parse('article-files/batch/link')
                },

                /**
                * Parses and expands URI templates based on [RFC6570](http://tools.ietf.org/html/rfc6570) specifications. For more information please visit the project [GitHub](https://github.com/Baasic/uritemplate-js) page.
                * @method
                * @example
baasicArticleFilesRouteService.parse(
	'<route>/{?embed,fields,options}'
).expand(
	{embed: '<embedded-resource>'}
);
                **/
                parse: uriTemplateService.parse
            };
        }]);
} (angular, module));
/**
 * @overview
 ***Notes:**
 - Refer to the [REST API documentation](https://github.com/Baasic/baasic-rest-api/wiki) for detailed information about available Baasic REST API end-points.
 - [URI Template](https://github.com/Baasic/uritemplate-js) syntax enables expanding the Baasic route templates to Baasic REST URIs providing it with an object that contains URI parameters.
 - All end-point objects are transformed by the associated route service.
*/


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using peer;
using ServerExperiment;

namespace socketSrv
{

    class Server : IDisposable
    {
        public List<commandMessage> serverQueue;  // = new Queue<commandMessage>();
		public List<commandMessage> serverMsgList = new List<commandMessage>();
        private int numConnections;                     // the maximum number of connections the sample is designed to handle simultaneously
        private int receiveBufferSize;                  // buffer size to use for each socket I/O operation
        BufferManager bufferManager;                    // represents a large reusable set of buffers for all socket operations
        const int opsToPreAlloc = 2;                    // read, write (don't alloc buffer space for accepts)
        Socket listenSocket;                            // the socket used to listen for incoming connection requests
        SocketAsyncEventArgsStack asyncSocketStack;     // stack of reusable SocketAsyncEventArgs objects for write, read and accept socket operations
        int numConnectedSockets;                        // the total number of clients connected to the server
        Semaphore maxNumberAcceptedClients;
        public List<peerInstance> peerList;
		public List<SocketAsyncEventArgs> myAsyncList = new List<SocketAsyncEventArgs>();
        public int serverPort;

        public Server(int numConns, int receiveSize)
        {
            numConnectedSockets = 0;
            numConnections = numConns;
            receiveBufferSize = receiveSize;
            bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc, receiveBufferSize, numConnections);
            asyncSocketStack = new SocketAsyncEventArgsStack(numConnections);
            maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);
            peerList = new List<peerInstance>();
            serverPort = 0;
			serverQueue = new List<commandMessage>();
			//commandMessage m = new commandMessage();
			//serverQueue.Enqueue(m);
			//m = serverQueue.Dequeue();

        }

        public void Dispose()
        {
            this.Dispose();
            GC.SuppressFinalize(this);
        }

        public bool isServerMessage()
        {
            bool returnBool = false;
            if (serverQueue.Count > 0)
                returnBool = true;

            return returnBool;
        }

		public List<commandMessage> returnServerQueue()
		{
//			List<commandMessage> tempQueue = new List<commandMessage>();
//			tempQueue = serverQueue;
//
//			if (serverQueue.Count > 1)
//			{
//
//				//lock(serverQueue)
//				//{
//				serverQueue.Clear();
//				//}
//			}

			if (serverQueue.Count > 1)
			{

				//lock(serverQueue)
				//{
				serverQueue.Clear();
				//}
			}

			return serverQueue;
		}

        public void Init()
        {
            // Allocates one large byte buffer which all I/O operations use a piece of.  This gaurds
            // against memory fragmentation
             bufferManager.initBuffers();

            // preallocate pool of SocketAsyncEventArgs objects
            SocketAsyncEventArgs socketEventArg;

            for (int i = 0; i < numConnections; i++)
            {
                //Pre-allocate a set of reusable SocketAsyncEventArgs
                socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SendRecieve_Completed);
                socketEventArg.UserToken = new AsyncUserToken();
                socketEventArg.SendPacketsSendSize = 1500;

                // assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
                bufferManager.assignBuffer(socketEventArg);

                // add SocketAsyncEventArg to the pool
                asyncSocketStack.Push(socketEventArg);
            }

        }

        public void Start(IPEndPoint localEndPoint)
        {
            listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.Bind(localEndPoint);

            listenSocket.Listen(20);

            StartAccept(null);

            Console.WriteLine("Starting server for p2p network on port {0}\n", localEndPoint.Port);

        }

        public void StartAccept(SocketAsyncEventArgs acceptEventArg)
        {
            if (acceptEventArg == null)
            {
                acceptEventArg = new SocketAsyncEventArgs();
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
            }
            else
            {
                // socket must be cleared since the context object is being reused
                acceptEventArg.AcceptSocket = null;
            }

            maxNumberAcceptedClients.WaitOne();

            bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
            if (!willRaiseEvent)
            {
                ProcessAccept(acceptEventArg);
            }
        }

        void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
        {
            ProcessAccept(e);
        }

        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            Interlocked.Increment(ref numConnectedSockets);
            Console.WriteLine("Client connection accepted. There are {0} clients connected to the server",
                numConnectedSockets);

            SocketAsyncEventArgs socketEventArgs = asyncSocketStack.Pop();
			myAsyncList.Add(socketEventArgs);

            ((AsyncUserToken)socketEventArgs.UserToken).Socket = e.AcceptSocket;

            IPEndPoint iep = (IPEndPoint)e.AcceptSocket.RemoteEndPoint;
            Console.WriteLine("New Peer is {0}", iep.Address);

            bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(socketEventArgs);

            if (!willRaiseEvent)
            {
                ProcessReceive(socketEventArgs);
            }

            // Accept the next connection request
            StartAccept(e);
        }

        void SendRecieve_Completed(object sender, SocketAsyncEventArgs e)
        {
            //if (e.RemoteEndPoint != null)
            //{
                switch (e.LastOperation)
                {
                    case SocketAsyncOperation.Receive:
                        ProcessReceive(e);
                        break;
                    case SocketAsyncOperation.Send:
                        ProcessSend(e);
                        break;
                    default:
                        throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                }
            //}

        }

        //member function for parsing command messages.
        private commandMessage parseCommandMessage(byte[] buf, int bufBytes)
        {
            commandMessage returnMsg = new commandMessage();
            byte[] msgLen = new byte[4];

            Int32 bufferCnt = 0;

            System.Buffer.BlockCopy(buf, bufferCnt, msgLen, 0, msgLen.Length);
            int messageLength = BitConverter.ToInt32(msgLen, 0);
            bufferCnt += msgLen.Length;

            byte[] addressBytes = new byte[4];
            byte[] portBytes = new byte[sizeof(Int32)];
            byte[] cmdBytes = new byte[sizeof(Int32)];

            System.Buffer.BlockCopy(buf, bufferCnt, addressBytes, 0, addressBytes.Length);
            bufferCnt += addressBytes.Length;

            System.Buffer.BlockCopy(buf, bufferCnt, portBytes, 0, portBytes.Length);
            bufferCnt += portBytes.Length;

            System.Buffer.BlockCopy(buf, bufferCnt, cmdBytes, 0, cmdBytes.Length);
            bufferCnt += cmdBytes.Length;

            returnMsg.peerIP = new IPAddress(addressBytes);
            returnMsg.port = BitConverter.ToInt32(portBytes, 0);
            returnMsg.command = BitConverter.ToInt32(cmdBytes, 0);

            switch (returnMsg.command)
            {
                case 2:
                    byte[] filesize = new byte[4];
                    byte[] fileNameSize = new byte[4];
                    byte[] fileNameBytes = new byte[75];

                    System.Buffer.BlockCopy(buf, bufferCnt, filesize, 0, filesize.Length);
                    bufferCnt += filesize.Length;

                    System.Buffer.BlockCopy(buf, bufferCnt, fileNameSize, 0, fileNameSize.Length);
                    bufferCnt += fileNameSize.Length;
                    int fileLen = BitConverter.ToInt32(fileNameSize, 0);

                    System.Buffer.BlockCopy(buf, bufferCnt, fileNameBytes, 0, fileLen);
                    bufferCnt += fileNameSize.Length;

					UTF8Encoding utf8 = new UTF8Encoding();
                    returnMsg.fileName = utf8.GetString(fileNameBytes, 0, fileLen);
					//serverQueue.Enqueue(returnMsg);

                    break;
            }

            return returnMsg;
        }

        private commandMessage createCommandMessage(Int32 peerIndex, Int32 msgInt)
        {
            commandMessage returnMsg = new commandMessage();
            returnMsg.peerIP = peerList[peerIndex].peerIP;
            returnMsg.port = peerList[peerIndex].peerPort;
            returnMsg.command = msgInt;

            return returnMsg;
        }

        private void ProcessReceive(SocketAsyncEventArgs e)
        {

            if ((e.BytesTransferred == 0) && (e.RemoteEndPoint == null))
            {
                //socket went away.  Break from function
                CloseClientSocket(e);
                return;
            }

            Random randomNumberGenerator = new Random();

            // check if the remote host closed the connection
            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            byte[] myBuffer = new byte[1500];
            System.Buffer.BlockCopy(e.Buffer, e.Offset, myBuffer, 0, e.Count);

            commandMessage msg = parseCommandMessage(myBuffer, e.BytesTransferred);
			//this.serverQueue.Enqueue(msg);
			//serverQueue.Add(msg);

            int peerNumber;
            //create peer variable to send back to client
            commandMessage replyMsg = new commandMessage();

            //bug bug - do a real calc here
            int clientMsgStreamLength = 16;

            //copy to byte array
            byte[] intBytes = BitConverter.GetBytes(clientMsgStreamLength);
            byte[] addressBytes = new byte[4];
            byte[] portBytes = new byte[4];
            byte[] cmdBytes = new byte[4];

            switch (msg.command)
            {
                case 1:
                    peerInstance newPeer = new peerInstance();

                    newPeer.peerIP = msg.peerIP;
                    newPeer.peerPort = msg.port;

                    if (peerList.Count < 2)
                        peerNumber = 0;
                    else
                        peerNumber = randomNumberGenerator.Next(peerList.Count);

                    //add the peer to peerList
                    peerList.Add(new peerInstance());
                    int newPeerCnt = peerList.Count - 1;

                    peerList[newPeerCnt].peerIP = newPeer.peerIP;
                    peerList[newPeerCnt].peerPort = newPeer.peerPort;
                    peerList[newPeerCnt].asyncSocketEvent = e;

                    Console.WriteLine("Peer is connected to {0} at port {1}", peerList[newPeerCnt].peerIP, peerList[newPeerCnt].peerPort);

                    intBytes = BitConverter.GetBytes(16);
                    addressBytes = peerList[peerNumber].peerIP.GetAddressBytes();
				    portBytes = BitConverter.GetBytes(peerList[peerNumber].peerPort);
					cmdBytes = BitConverter.GetBytes(0);

					System.Buffer.BlockCopy(intBytes, 0, myBuffer, 0, 4);  //prepends length to buffer
                    System.Buffer.BlockCopy(addressBytes, 0, myBuffer, 4, addressBytes.Length);
                    System.Buffer.BlockCopy(portBytes, 0, myBuffer, 4 + addressBytes.Length, portBytes.Length);
                    System.Buffer.BlockCopy(cmdBytes, 0, myBuffer, 4 + addressBytes.Length + portBytes.Length, cmdBytes.Length);
                    System.Buffer.BlockCopy(myBuffer, 0, e.Buffer, e.Offset, myBuffer.Length);
                    break;

                case 0:
                    replyMsg = msg;
                    replyMsg.command = 0;

                    intBytes = BitConverter.GetBytes(16);
                    addressBytes = replyMsg.peerIP.GetAddressBytes();
				    portBytes = BitConverter.GetBytes(replyMsg.port);
					cmdBytes = BitConverter.GetBytes(replyMsg.command);

					System.Buffer.BlockCopy(intBytes, 0, myBuffer, 0, 4);  //prepends length to buffer
                    System.Buffer.BlockCopy(addressBytes, 0, myBuffer, 4, addressBytes.Length);
                    System.Buffer.BlockCopy(portBytes, 0, myBuffer, 4 + addressBytes.Length, portBytes.Length);
                    System.Buffer.BlockCopy(cmdBytes, 0, myBuffer, 4 + addressBytes.Length + portBytes.Length, cmdBytes.Length);
                    System.Buffer.BlockCopy(myBuffer, 0, e.Buffer, e.Offset, myBuffer.Length);
                    break;
                case 2:
	                Console.WriteLine("Received GET cmd for {0} from {1}.  Reply on {2}\n",
	                                  msg.fileName, msg.peerIP, msg.port);

	                //need to send msg to peer
                    string fileDir = Program.p2p.getFileDir();
                    msg.fileName = fileDir + msg.fileName;
                    int fileNum = Program.p2p.fileLocal(msg.fileName);
                    if (fileNum != int.MaxValue)
                    {
                        fileTransport g = new fileTransport();
                        g.sendFile(msg);
                    }
                    else
                    {
                        //need to broadcast to all server clients
                        //replyMsg = msg;

                        //intBytes = BitConverter.GetBytes(16);
                        //addressBytes = replyMsg.peerIP.GetAddressBytes();
                        //portBytes = BitConverter.GetBytes(replyMsg.port);
                        //cmdBytes = BitConverter.GetBytes(replyMsg.command);

                        //System.Buffer.BlockCopy(intBytes, 0, myBuffer, 0, 4);  //prepends length to buffer
                        //System.Buffer.BlockCopy(addressBytes, 0, myBuffer, 4, addressBytes.Length);
                        //System.Buffer.BlockCopy(portBytes, 0, myBuffer, 4 + addressBytes.Length, portBytes.Length);
                        //System.Buffer.BlockCopy(cmdBytes, 0, myBuffer, 4 + addressBytes.Length + portBytes.Length, cmdBytes.Length);

                        AsyncUserToken relayToken;   // = (AsyncUserToken)e.UserToken;
                        int msgLen = e.BytesTransferred;
                        for (int i = 0; i < myAsyncList.Count; i++)
                        {
                            //don't send to peer who you got it from.  write that IF BUGBUG
                            System.Buffer.BlockCopy(myBuffer, 0, myAsyncList[i].Buffer, myAsyncList[i].Offset, msgLen);
                            relayToken = (AsyncUserToken)myAsyncList[i].UserToken;
                            IPEndPoint iep = (IPEndPoint)relayToken.Socket.RemoteEndPoint;
                            IPAddress ip = (IPAddress)iep.Address;
                            //IPAddress.Equals()
                            if (ip.Address != msg.peerIP.Address)
                            {
                                //if (myAsyncList[i].BytesTransferred > 0 && myAsyncList[i].SocketError == SocketError.Success)
                                if (myAsyncList[i].SocketError == SocketError.Success)
                                {
                                    relayToken.Socket.Send(myBuffer, msgLen, SocketFlags.None);
                                    //bool willRaiseEvent = token.Socket.SendAsync(myAsyncList[i]);

                                    //if (!willRaiseEvent)
                                    //{
                                    //    ProcessSend(myAsyncList[i]);
                                    //}

                                }
                                else
                                {
                                    CloseClientSocket(myAsyncList[i]);
                                }
                            }
                        }
                    }
					//serverQueue.Add(msg);
	                break;
            }

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                bool willRaiseEvent = token.Socket.SendAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessSend(e);
                }

            }
            else
            {
                CloseClientSocket(e);
            }
        }

        private void ProcessSend(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                AsyncUserToken token = (AsyncUserToken)e.UserToken;

                // read the next block of data send from the client
                bool willRaiseEvent = token.Socket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessReceive(e);
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }

        private void CloseClientSocket(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = e.UserToken as AsyncUserToken;

            IPEndPoint iep = (IPEndPoint)token.Socket.RemoteEndPoint;
            //token.m_socket.RemoteEndPoint.Address  & token.m_socket.RemoteEndPoint.Port is what need to be removed from peerList
            for (int i = 0; i < peerList.Count;i++ )
            {
                if (peerList[i].peerIP == iep.Address)
                {
                    Console.WriteLine("Peer {0} has quit", iep.Address);
                    peerList.RemoveAt(i);
                }
            }

            try
            {
                token.Socket.Shutdown(SocketShutdown.Send);
            }
                // throws if client process has already closed
             catch (Exception) { }
            token.Socket.Close();

            // decrement the counter keeping track of the total number of clients connected to the server
            Interlocked.Decrement(ref numConnectedSockets);
            maxNumberAcceptedClients.Release();
            Console.WriteLine("There are {0} clients connected to the server", numConnectedSockets);

			for (int i=0;i<myAsyncList.Count;i++)
			{
				if (myAsyncList[i] == e)
					myAsyncList.RemoveAt(i);
			}

            // Free the SocketAsyncEventArg so they can be reused by another client
            bufferManager.freeBuffer(e);
            asyncSocketStack.Push(e);
        }

		public void SendCmd(commandMessage cmd)
		{
			byte [] buffer = new byte[1500];
			byte [] cmdBytes = new byte[4];
			byte [] msgLenBytes = new byte[4];
			byte [] addressBytes = new byte[4];
			byte [] portBytes = new byte[4];
            byte[] fileNameSizeBytes = new byte[4];
            byte[] fileNameBytes = new byte[75];
            byte[] fileSizeBytes = new byte[4];

			//Console.WriteLine("Sent request to client machine(s)\n");
			cmdBytes = BitConverter.GetBytes(cmd.command);
			//msgLenBytes = BitConverter.GetBytes(16);
			addressBytes = cmd.peerIP.GetAddressBytes();
			portBytes = BitConverter.GetBytes(cmd.port);
            fileSizeBytes = BitConverter.GetBytes(0);

            int byteCnt = 4;
			//System.Buffer.BlockCopy(msgLenBytes,0,buffer,0,4);
            System.Buffer.BlockCopy(addressBytes, 0, buffer, byteCnt, addressBytes.Length);
            byteCnt += addressBytes.Length;

            System.Buffer.BlockCopy(portBytes, 0, buffer, byteCnt, portBytes.Length);
            byteCnt += portBytes.Length;

            System.Buffer.BlockCopy(cmdBytes, 0, buffer, byteCnt, cmdBytes.Length);
            byteCnt += cmdBytes.Length;

            System.Buffer.BlockCopy(fileSizeBytes, 0, buffer, byteCnt, fileSizeBytes.Length);
            byteCnt += fileSizeBytes.Length;

            UTF8Encoding utf8 = new UTF8Encoding();
            int fileNameSize = utf8.GetByteCount(cmd.fileName);

            int fileNameLen = utf8.GetByteCount(cmd.fileName);
            fileNameSizeBytes = BitConverter.GetBytes(fileNameLen);
            System.Buffer.BlockCopy(fileNameSizeBytes, 0, buffer, byteCnt, fileNameSizeBytes.Length);
            byteCnt += fileNameSizeBytes.Length;

            fileNameBytes = utf8.GetBytes(cmd.fileName);
            System.Buffer.BlockCopy(fileNameBytes, 0, buffer, byteCnt, fileNameLen);

            int msgLen = byteCnt + fileNameLen;
            msgLenBytes = BitConverter.GetBytes(msgLen);
            System.Buffer.BlockCopy(msgLenBytes, 0, buffer, 0, msgLenBytes.Length);

			AsyncUserToken token;

			for (int i=0;i<myAsyncList.Count;i++)
			{
                System.Buffer.BlockCopy(buffer, 0, myAsyncList[i].Buffer, myAsyncList[i].Offset, msgLen);
				token = (AsyncUserToken)myAsyncList[i].UserToken;

                IPEndPoint iep = (IPEndPoint)token.Socket.RemoteEndPoint;
                IPAddress ip = iep.Address;

                if (cmd.peerIP.Address != ip.Address)
                {
                    if (myAsyncList[i].SocketError == SocketError.Success)
                    {
                        token.Socket.Send(buffer, msgLen, SocketFlags.None);
                    }
                    else
                    {
                        CloseClientSocket(myAsyncList[i]);
                    }
                }
			}

			return;
		}

    }
}


text:
Vamos a instalar el emulador QEMU y además unos cuantos paquetes recomendados más:

```
sudo apt-get install qemu-kvm qemu virt-manager virt-viewer libvirt-bin
```

![eje01_img01](https://dl.dropboxusercontent.com/s/pe9c6w1zhn3zq65/eje01_img01.png)

# Bajar una distribución de Linux (p.ej. Debian).
La distribución a descargar es **Lubuntu**, una versión de Ubuntu con el escritorio _LXDE_ que es muy ligero; además, será la versión para arquitecturas de _32 bits_ (i386), para que entre todo luego sea menos pesado emular el sistema.

```
wget http://cdimage.ubuntu.com/lubuntu/releases/15.10/release/lubuntu-15.10-desktop-i386.iso
```

![eje02_img01](https://dl.dropboxusercontent.com/s/r6yb2cpsupg251l/eje02_img01.png)

# Crear un disco virtualizado para QEMU.
Ahora creamos la imagen del disco duro virtual que vamos a usar con el emulador. El formato del disco será **QCOW2** y con una capacidad de **20GB**.

```
qemu-img create -f qcow2 lubuntu.img 20G
```

![eje03_img01](https://dl.dropboxusercontent.com/s/mrvcvg0bju253g7/eje03_img01.png)

# Instalar Linux en dicho disco.
Creamos una máquina virtual en la que instalar la versión de Lubuntu que hemos descargado. Tenemos que indicar que vamos a usar el disco duro virtual que hemos creado en el paso anterior (`lubuntu.img`), la imagen de instalación (`lubuntu-15.10-desktop-i386.iso`) y la cantidad de memoria RAM que le vamos a asignar a la máquina, que serán **2GB** en este caso. Es importante también tener en cuenta que si no activamos **KVM** (`-enable-kvm`) la emulación será mucho más lenta.

```
qemu-system-x86_64 -enable-kvm -hda lubuntu.img -boot d -cdrom lubuntu-15.10-desktop-i386.iso -m 2G -name lubuntu
```

![eje04_img01](https://dl.dropboxusercontent.com/s/ax2cbztcduaersw/eje04_img01.png)

Otra imagen:

![eje04_img02](https://dl.dropboxusercontent.com/s/x9lom98vieassou/eje04_img02.png)

Y otra imagen:

![eje04_img03](https://dl.dropboxusercontent.com/s/668bwuzuw27uafd/eje04_img03.png)

# Ejecutar la máquina instalada para interaccionar con ella con su interfaz gráfica.

Una vez que el sistema está instalado, podremos arrancar la imagen para acceder al interfaz gráfico del sistema.

```
qemu-system-x86_64 -enable-kvm -boot order=c -drive file=lubuntu.img,if=virtio -m 2G -name lubuntu
```

![eje05_img01](https://dl.dropboxusercontent.com/s/02t4fiibnmw8yl6/eje05_img01.png)

Aquí podemos ver el sistema ya arrancado:

![eje05_img02](https://dl.dropboxusercontent.com/s/tqds66tmlqjdueg/eje05_img02.png)

# Ejecutar la máquina instalada sin interfaz gráfica, y entrar usando un cliente VNC.

Para ejecutar la máquina virtual sin interfaz gráfica tenemos que arrancarla dentro de un **servidor VNC** (opción `-vnc :1`). Esta vez no se abrirá ninguna ventana al ejecutar la orden.

```
qemu-system-x86_64 -enable-kvm -boot order=c -drive file=lubuntu.img,if=virtio -m 2G -name lubuntu -vnc :1
```

![eje06_img01](https://dl.dropboxusercontent.com/s/awxz6jx5iik54rv/eje06_img01.png)

Para conectarnos al servidor VNC de la máquina virtual necesitaremos instalar en nuestro sistema local un **cliente VNC** como puede ser **VNC Viewer**, lo que vamos a hacer desde otro terminal.

```
sudo apt-get install vncviewer
```

![eje06_img02](https://dl.dropboxusercontent.com/s/ani8fk3bhhp659c/eje06_img02.png)

También necesitaremos conocer la dirección IP de la máquina virtual, para ello consultamos la información de la interfaz **virbr0**, que es la interfaz NAT por defecto para máquinas de este sistema.

```
ifconfig virbr0
```

![eje06_img03](https://dl.dropboxusercontent.com/s/7fgjnzddjzlkwe7/eje06_img03.png)

Por último, solo nos queda conectarnos a la máquina a través de VNC indicando la IP de la máquina y el puerto de escucha VNC por defecto, **5901**.

```
vncviewer 192.168.122.1:5901
```
![eje06_img04](https://dl.dropboxusercontent.com/s/qczkex4qi13nf2i/eje06_img04.png)

# Instalar Apache2 o nginx y probar que sirve páginas web (acceder desde el host a la IP del servidor virtualizado, bien con cURL o con un navegador).

En esta ocasión desde el interior de la máquina virtual, instalremos **nginx**.

```
sudo apt-get install nginx
```

![eje07_img01](https://dl.dropboxusercontent.com/s/xjfw8k35f397c0y/eje07_img01.png)

Una vez instalado, comprobamos que está funcionando correctamente.

```
sudo service nginx status
```

![eje07_img02](https://dl.dropboxusercontent.com/s/e5jkv5w22mhzwuj/eje07_img02.png)

Por el método que tiene _QEMU_ de gestionar las interconexiones entre sistema locales y virtuales, para que ahora podamos conectarnos desde nuestro sistema al servidor que acabamos de instalar es necesario **redirigir** un puerto en nuestro sistema local a un puerto en el sistema virtual; como es un servidor web, usará el puerto _80_ por defecto, así que vamos a redirigir ese puerto a nuestro puerto local _80_. Esto se hace con la opción `-redir tcp:80::80`, además como el puerto 80 es un puerto reservado del sistema, tendremos que ejecutar la máquina virtual con permisos de **superusuario** en este caso.

```
sudo qemu-system-x86_64 -enable-kvm -boot order=c -drive file=lubuntu.img,if=virtio -m 2G -name lubuntu -redir tcp:80::80
```

![eje07_img03](https://dl.dropboxusercontent.com/s/yy86b0rpe21b56y/eje07_img03.png)