text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using MyAccounts.Business.AccountOperations;
using MyAccounts.Business.IO;
using MyAccounts.Business.Managers;
using MyAccounts.Business.Managers.Imports;
using MyAccounts.NetStandard.Input;
using MyAccounts.NetStandard.Projections;
using Operations.Classification.WpfUi.Managers.Accounts.Models;

namespace Operations.Classification.WpfUi.Managers.Imports
{
    public class ImportsManagerViewModel : ViewModelBase
    {
        private readonly BusyIndicatorViewModel _busyIndicator;
        private readonly IImportManager _importManager;
        private readonly OpenFileDialog _ofd;

        private AccountViewModel _currentAccount;

        private ImportEditorViewModel _editor;
        private List<ImportCommandGridModel> _imports;

        public ImportsManagerViewModel(BusyIndicatorViewModel busyIndicator, IFileSystem fileSystem, IImportManager importManager)
        {
            _busyIndicator = busyIndicator;
            _importManager = importManager;
            Fs = fileSystem;

            ReplayImportsCommand = new RelayCommand(ReplayImports);
            BeginImportCommand = new RelayCommand(BeginNewImport);
            BeginEditImportsCommand = new AsyncCommand(BeginEditImport);
            CommitEditCommand = new AsyncCommand(CommitEdit);
            CancelEditCommand = new RelayCommand(CancelEdit);
            SelectFilesToImportCommand = new RelayCommand(SelectFilesToImport);
            DeleteImportsCommand = new AsyncCommand(DeleteImports);
            MessengerInstance.Register<AccountViewModel>(this, OnAccountViewModelReceived);
            SelectedImports = new ObservableCollection<ImportCommandGridModel>();

            _ofd = new OpenFileDialog
            {
                Multiselect = true,
                Filter = "csv files (*.csv)|*.csv|All Files (*.*)|*.*"
            };
        }

        public List<ImportCommandGridModel> Imports
        {
            get => _imports;
            private set
            {
                if (Set(nameof(Imports), ref _imports, value))
                {
                    SelectedImports.Clear();
                }
            }
        }

        public ObservableCollection<ImportCommandGridModel> SelectedImports { get; }

        public bool IsEditing => Editor != null;

        public bool IsNew => Editor?.IsNew == true;

        public RelayCommand BeginImportCommand { get; }

        public RelayCommand SelectFilesToImportCommand { get; }

        public AsyncCommand BeginEditImportsCommand { get; }

        public RelayCommand ReplayImportsCommand { get; }

        public AsyncCommand CommitEditCommand { get; }

        public RelayCommand CancelEditCommand { get; }

        public AsyncCommand DeleteImportsCommand { get; }

        public ImportEditorViewModel Editor
        {
            get => _editor;
            set
            {
                if (Set(() => Editor, ref _editor, value))
                {
                    RaisePropertyChanged(() => IsEditing);
                    RaisePropertyChanged(() => IsNew);
                }
            }
        }

        private IFileSystem Fs { get; }

        private void OnAccountViewModelReceived(AccountViewModel currentAccount)
        {
            _currentAccount = currentAccount;
            RefreshImports();
        }

        private void RefreshImports()
        {
            Imports = _currentAccount?.Imports;
        }

        private void BeginNewImport()
        {
            if (IsEditing)
            {
                throw new InvalidOperationException("An import is already in progress");
            }

            var editor = new ImportEditorViewModel();
            editor.BeginEdit();
            SetupEditorCommands(editor);
            Editor = editor;
        }

        private async Task BeginEditImport()
        {
            if (IsEditing)
            {
                throw new InvalidOperationException("An import found to be in progress");
            }

            var selection = SelectedImports.Select(i => i.Id).ToArray();
            if (selection.Length > 0)
            {
                var importCommands = await _importManager.Get(_currentAccount.Id, selection);
                var editor = importCommands[0].Map().To<ImportEditorViewModel>();
                editor.Ids = selection;

                editor.BeginEdit();

                if (importCommands.Count > 1)
                {
                    editor.SourceName = string.Join(";", SelectedImports.Select(i => i.SourceName));
                    editor.IsSourceNameReadOnly = true;
                    foreach (var importCommand in importCommands)
                    {
                        editor.UpdateMixedState(importCommand, nameof(importCommand.SourceName));
                    }
                }

                SetupEditorCommands(editor);
                Editor = editor;
            }
        }

        private async Task CommitEdit()
        {
            if (!IsEditing)
            {
                throw new InvalidOperationException("no edit in progress, nothing to commit");
            }

            bool datachanged = false;
            if (IsNew)
            {
                using (_busyIndicator.EncapsulateActiveJobDescription(this, "finalizing import"))
                {
                    datachanged = await SaveNewImport();
                }
            }
            else if (Editor.IsDirty())
            {
                using (_busyIndicator.EncapsulateActiveJobDescription(this, "committing changes"))
                {
                    datachanged = await SaveExistingImport();
                }
            }

            Editor.EndEdit();
            Editor = null;

            if (datachanged)
            {
                MessengerInstance.Send(new AccountImportDataChanged(_currentAccount.Id));
            }
        }

        private void ReplayImports()
        {
            MessengerInstance.Send(new AccountImportDataChanged(_currentAccount.Id));
        }

        private async Task<bool> SaveExistingImport()
        {
            if (Editor.IsNew)
            {
                throw new InvalidOperationException("import id must be known");
            }

            var importId = Editor.Ids;
            var importCommands = await _importManager.Get(_currentAccount.Id, importId);
            foreach (var importCommand in importCommands)
            {
                var toSkip = Editor.IsSourceNameReadOnly ? new[] { nameof(ImportCommand.SourceName) } : new string[0];
                Editor.FillFromDirtyProperties(importCommand, toSkip);
            }

            var saved = await _importManager.Replace(importCommands);
            return saved;
        }

        private async Task<bool> SaveNewImport()
        {
            var paths = Editor.FilePaths.Split(',');
            var files = new HashSet<string>();
            foreach (var path in paths)
            {
                if (Fs.IsDirectoy(path))
                {
                    var dirFiles = Fs.DirectoryGetFiles(path, "*.csv");
                    foreach (var dirFile in dirFiles)
                    {
                        files.Add(dirFile);
                    }
                }
                else if (Fs.FileExists(path))
                {
                    files.Add(path);
                }
            }

            var account = _currentAccount;
            var someImportSucceeded = false;
            var sourceKind = Editor.SourceKind;
            if (account != null)
            {
                foreach (var file in files)
                {
                    using (var fs = Fs.FileOpenRead(file))
                    {
                        var importCommand = new ImportCommand(account.Id, Path.GetFileName(file), sourceKind);
                        Editor.FillFromDirtyProperties(importCommand);
                        if (await _importManager.RequestImportExecution(importCommand, fs))
                        {
                            someImportSucceeded = true;
                        }
                    }
                }
            }

            return someImportSucceeded;
        }

        private void CancelEdit()
        {
            if (!IsEditing)
            {
                throw new InvalidOperationException("no edit in progress, nothing to cancel");
            }

            Editor.CancelEdit();
            Editor = null;
        }

        private async Task DeleteImports()
        {
            var selection = SelectedImports;
            if (selection.Count > 0)
            {
                var idSet = new HashSet<Guid>(selection.Select(a => a.Id));
                await _importManager.DeleteImports(_currentAccount.Id, idSet);

                var imports = _currentAccount.Imports.Where(i => !idSet.Contains(i.Id)).ToList();
                _currentAccount.Imports = imports;

                RefreshImports();
            }
        }

        private void SelectFilesToImport()
        {
            if (string.IsNullOrEmpty(_ofd.InitialDirectory))
            {
                _ofd.InitialDirectory = Properties.Settings.Default.WorkingFolder;
            }

            if (_ofd.ShowDialog() == true)
            {
                Editor.FilePaths = string.Join(",", _ofd.FileNames);
            }
        }

        private void SetupEditorCommands(ImportEditorViewModel editor)
        {
            editor.CommitCommand = new AsyncCommand(CommitEdit);
            editor.ResetDefaultSourceKindMetadataCommand = new RelayCommand(ResetDefaultSourceKindMetadataCommand);

            if (editor.IsNew)
            {
                editor.SelectFilesToImportCommand = SelectFilesToImportCommand;
            }
        }

        private void ResetDefaultSourceKindMetadataCommand()
        {
            var sourceKind = Editor.SourceKind;
            var fsmd = FileStructureMetadataFactory.CreateDefault(sourceKind);
            fsmd.Map().To(Editor);
        }
    }
}


text:
<?php
	$CI =& get_instance();
	$CI->load->library('session');

	if($CI->session->flashdata('delete_success_message')==1)
	echo "

 Your data has been successfully deleted from the database.

";

	if($CI->session->flashdata('delete_error_message')==1)
	echo "

 Your data has been failed to delete from the database.

";

?>

redpajama_set_name: RedPajamaGithub


text:
// $Id$
#ifndef ALIHLTTPCRAWCLUSTER_H
#define ALIHLTTPCRAWCLUSTER_H

#include "Rtypes.h"

/**
 * @struct AliHLTTPCRawCluster
 * Primitive data of a TPC cluster in raw coordinates. The plan is to store the
 * data in a compressed format by limiting the resolution of the float values.
 * @ingroup alihlt_tpc_datastructs
 */
struct AliHLTTPCRawCluster {
  AliHLTTPCRawCluster()
    : fPadRow(0)
    , fPad(0.)
    , fTime(0.)
    , fSigmaPad2(0.)
    , fSigmaTime2(0.)
    , fCharge(0)
    , fQMax(0)
    , fFlags(0)
  {}

  AliHLTTPCRawCluster(short PadRow,
		      float Pad,
		      float Time,
		      float SigmaPad2,
		      float SigmaTime2,
		      unsigned short Charge,
		      unsigned short QMax,
		      unsigned short Flags
		      )
    : fPadRow(PadRow)
    , fPad(Pad)
    , fTime(Time)
    , fSigmaPad2(SigmaPad2)
    , fSigmaTime2(SigmaTime2)
    , fCharge(Charge)
    , fQMax(QMax)
    , fFlags(Flags)
  {}

  AliHLTTPCRawCluster(const AliHLTTPCRawCluster& other)
    : fPadRow(other.fPadRow)
    , fPad(other.fPad)
    , fTime(other.fTime)
    , fSigmaPad2(other.fSigmaPad2)
    , fSigmaTime2(other.fSigmaTime2)
    , fCharge(other.fCharge)
    , fQMax(other.fQMax)
    , fFlags(other.fFlags)
  {}

  AliHLTTPCRawCluster& operator=(const AliHLTTPCRawCluster& other) {
    if (this==&other) return *this;
    this->~AliHLTTPCRawCluster();
    new (this) AliHLTTPCRawCluster(other);
    return *this;
  }

  void Clear() {
    this->~AliHLTTPCRawCluster();
    new (this) AliHLTTPCRawCluster;
  }

  short fPadRow;
  unsigned short fFlags; //Flags: (1 << 0): Split in pad direction
                         //       (1 << 1): Split in time direction
                         //       (1 << 2): Edge Cluster
                         //During cluster merging, flags are OR'd
  float fPad;
  float fTime;
  float fSigmaPad2;
  float fSigmaTime2;
  unsigned short fCharge;
  unsigned short fQMax;

  Int_t   GetPadRow()  const {return fPadRow;}
  Float_t GetPad()     const {return fPad;}
  Float_t GetTime()    const {return fTime;}
  Float_t GetSigmaPad2() const {return fSigmaPad2;}
  Float_t GetSigmaTime2() const {return fSigmaTime2;}
  Int_t   GetCharge()  const {return fCharge;}
  Int_t   GetQMax()    const {return fQMax;}
  Bool_t  GetFlagSplitPad() const {return (fFlags & (1 << 0));}
  Bool_t  GetFlagSplitTime() const {return (fFlags & (1 << 1));}
  Bool_t  GetFlagSplitAny() const {return (fFlags & 3);}
  Bool_t  GetFlagEdge() const {return (fFlags & (1 << 2));}
  unsigned short GetFlags() const {return(fFlags);}

  void SetPadRow(Short_t padrow)  {fPadRow=padrow;}
  void SetPad(Float_t pad)     {fPad=pad;}
  void SetTime(Float_t time)    {fTime=time;}
  void SetSigmaPad2(Float_t sigmaPad2) {fSigmaPad2=sigmaPad2;}
  void SetSigmaTime2(Float_t sigmaTime2) {fSigmaTime2=sigmaTime2;}
  void SetCharge(UShort_t charge)  {fCharge=charge;}
  void SetQMax(UShort_t qmax)    {fQMax=qmax;}

  void ClearFlags() {fFlags = 0;}
  void SetFlags(unsigned short flags) {fFlags = flags;}
  void SetFlagSplitPad() {fFlags |= (1 << 0);}
  void SetFlagSplitTime() {fFlags |= (1 << 1);}
  void SetFlagEdge() {fFlags |= (1 << 2);}
};
typedef struct AliHLTTPCRawCluster AliHLTTPCRawCluster;

struct AliHLTTPCRawClusterData
{
  UInt_t fVersion; // version number
  UInt_t fCount;   // number of clusters
#if defined(__HP_aCC) || defined(__DECCXX) || defined(__SUNPRO_CC)
  AliHLTTPCRawCluster  fClusters[1]; // array of clusters
#else
  AliHLTTPCRawCluster  fClusters[0]; // array of clusters
#endif
};
typedef struct AliHLTTPCRawClusterData AliHLTTPCRawClusterData;

#endif


text:
.. _arch_overview_conn_pool:

Connection pooling
==================

For HTTP traffic, Envoy supports abstract connection pools that are layered on top of the underlying
wire protocol (HTTP/1.1 or HTTP/2). The utilizing filter code does not need to be aware of whether
the underlying protocol supports true multiplexing or not. In practice the underlying
implementations have the following high level properties:

HTTP/1.1
--------

The HTTP/1.1 connection pool acquires connections as needed to an upstream host (up to the circuit
breaking limit). Requests are bound to connections as they become available, either because a
connection is done processing a previous request or because a new connection is ready to receive its
first request. The HTTP/1.1 connection pool does not make use of pipelining so that only a single
downstream request must be reset if the upstream connection is severed.

HTTP/2
------

The HTTP/2 connection pool multiplexes multiple requests over a single connection, up to the limits
imposed by :ref:`max concurrent streams <envoy_api_field_core.Http2ProtocolOptions.max_concurrent_streams>`
and :ref:`max requests per connection <envoy_api_field_Cluster.max_requests_per_connection>`.
The HTTP/2 connection pool establishes only as many connections as are needed to serve the current
requests. With no limits, this will be only a single connection. If a GOAWAY frame is received or
if the connection reaches the maximum stream limit, the connection pool will drain the existing one.
New connections are established anytime there is a pending request without a connection that it can
be dispatched to (up to circuit breaker limits for connections).
HTTP/2 is the preferred communication protocol as connections rarely if ever get severed.

.. _arch_overview_conn_pool_health_checking:

Health checking interactions
----------------------------

If Envoy is configured for either active or passive :ref:`health checking
<arch_overview_health_checking>`, all connection pool connections will be closed on behalf of a host
that transitions from a available state to an unavailable state. If the host reenters the load
balancing rotation it will create fresh connections which will maximize the chance of working
around a bad flow (due to ECMP route or something else).


text:
package com.imc.mobile.android;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.StrictMode;
import android.text.Html;

public class ServerUtility {
	public static int returnPostCount(String PrevCheckedDate)
	{
		int NumOfPostsFound =0;
		try
		{
			PrevCheckedDate = PrevCheckedDate.replace('/', '-');
			//Strict mode
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);

			 DefaultHttpClient httpClient = new DefaultHttpClient();
	         HttpEntity httpEntity = null;
	         HttpResponse httpResponse = null;
	         String Url = String.format(ConstUtilities.getNumberOfPosts, PrevCheckedDate);
	         HttpGet httpGet = new HttpGet(Url);

	         httpResponse = httpClient.execute(httpGet);
	         httpEntity = httpResponse.getEntity();
	         String response = EntityUtils.toString(httpEntity);

	         JSONObject jObj = new JSONObject(response);
	         NumOfPostsFound = jObj.getInt(ConstUtilities.Node_Found);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();

		}

		return NumOfPostsFound;
	}
	public static boolean setZillaLike(String PostID)
	{
		String URL = "http://www.indianmomsconnect.com/?json=set_zilla_likes&id=" + PostID;
		try
		{
			//Strict mode
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);

			 DefaultHttpClient httpClient = new DefaultHttpClient();
	         HttpEntity httpEntity = null;
	         HttpResponse httpResponse = null;
	         HttpGet httpGet = new HttpGet(URL);
	         httpResponse = httpClient.execute(httpGet);

	         httpEntity = httpResponse.getEntity();
	         String response = EntityUtils.toString(httpEntity);

	         JSONObject jObj = new JSONObject(response);
	         String Status = jObj.getString("status");
	         if(Status.equalsIgnoreCase("ok"))
	         {
	        	 return true;
	         }
	         else
	         {
	        	 return false;
	         }
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			return false;

		}

	}

	public static boolean postComment(String PostID,String UserName,String UserEmail,String Comment)
	{
		try {
			UserName = URLEncoder.encode(UserName, "utf-8");
			UserEmail = URLEncoder.encode(UserEmail, "utf-8");
			Comment = URLEncoder.encode(Comment, "utf-8");

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String URL = "http://www.indianmomsconnect.com/api/submit_comment?post_id=" + PostID + "&name=" + UserName + "&email=" + UserEmail + "&content=" + Comment;
		try
		{
			//Strict mode
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);

			 DefaultHttpClient httpClient = new DefaultHttpClient();
	         HttpEntity httpEntity = null;
	         HttpResponse httpResponse = null;
	         HttpPut httpput = new HttpPut(URL);
	         httpResponse = httpClient.execute(httpput);
	         httpEntity = httpResponse.getEntity();
	         String response = EntityUtils.toString(httpEntity);

	         JSONObject jObj = new JSONObject(response);
	         String Status = jObj.getString("status");
	         if(Status.equalsIgnoreCase("ok"))
	         {
	        	 return true;
	         }
	         else
	         {
	        	 return false;
	         }
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			return false;

		}

	}

	@SuppressWarnings("null")
	public static ArrayList<HashMap<String,Object>> returnIMCPosts()
	{
		JSONArray posts = null;
		//Array list of post lists
		ArrayList<HashMap<String,Object>> postLists = null;
		IMCPost _post = new IMCPost();
		try
		{

	    DefaultHttpClient httpClient = new DefaultHttpClient();
	    HttpEntity httpEntity = null;
	    HttpResponse httpResponse = null;
	    HttpGet httpGet = new HttpGet(ConstUtilities.getPosts);

	    httpResponse = httpClient.execute(httpGet);
	    httpEntity = httpResponse.getEntity();
	    String response = EntityUtils.toString(httpEntity);

	    JSONObject jObj = new JSONObject(response);

	    posts = jObj.getJSONArray(ConstUtilities.Node_Posts);
	    for (int i=0;i<posts.length();i++)
	    {
	    JSONObject singleObj = posts.getJSONObject(i);
	    //Title Data Cleaning
	    String tempTitle = singleObj.getString(ConstUtilities.Node_Title);
	    tempTitle = UtilFunctions.stringCleanup(tempTitle);
	   // tempTitle = URLDecoder.decode(tempTitle,"UTF-8");
	    //tempTitle = tempTitle.replaceAll( "[\\u202C\\u202A]", "" );
	    _post.Title = Html.fromHtml(Html.fromHtml((String) tempTitle).toString());
	    String excerptData = singleObj.getString(ConstUtilities.Node_Excerpt);
	    excerptData = UtilFunctions.stringCleanup(excerptData);
	   /* excerptData = URLDecoder.decode(excerptData, "UTF-8");
	    excerptData = excerptData.replaceAll( "[\\u202C\\u202A]", "" );*/
	    _post.Excerpt = Html.fromHtml(Html.fromHtml((String) excerptData).toString());
	    _post.Image = singleObj.getString(ConstUtilities.Node_Image).toString();
	    _post.LikeCount = "Likes: " + singleObj.getString(ConstUtilities.Node_LikeCnt);
	    _post.PostID = singleObj.getString(ConstUtilities.Node_ID);
	    _post.CommentCount = "Comments: " + singleObj.getString(ConstUtilities.Node_CommentCnt);
	    _post.dateposted = singleObj.getString(ConstUtilities.Node_Date);
	   // _post.Content = singleObj.getString(ConstUtilities.Node_Content);
	    JSONObject authorObj  = singleObj.getJSONObject(ConstUtilities.Node_Author);
	    _post.Author = authorObj.getString("name").toString();

	    HashMap<String,Object> post = new HashMap<String,Object>();
	    post.put(ConstUtilities.Node_Title, _post.Title);
	    post.put(ConstUtilities.Node_Excerpt, _post.Excerpt);
	    post.put(ConstUtilities.Node_Image, _post.Image);
	    post.put(ConstUtilities.Node_LikeCnt, _post.LikeCount);
	    post.put(ConstUtilities.Node_CommentCnt, _post.CommentCount);
	    post.put(ConstUtilities.Node_ID, _post.PostID);
	    post.put(ConstUtilities.Node_Date, _post.dateposted);
	    post.put(ConstUtilities.Node_Content, _post.Content);
	    post.put(ConstUtilities.Node_Author,_post.Author);

	    postLists.add(post);
	    }

		}

		catch(Exception ex)
		{
			ex.printStackTrace();

		}
		return postLists;
	}

}


text:
Two definitions of Machine Learning are offered. Arthur Samuel described it as: "the field of study that gives computers the ability to learn without being explicitly programmed." This is an older, informal definition.

Tom Mitchell provides a more modern definition: "A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E."

Example: playing checkers.

E = the experience of playing many games of checkers

T = the task of playing checkers.

P = the probability that the program will win the next game.

In general, any machine learning problem can be assigned to one of two broad classifications:

Supervised learning and Unsupervised learning.

## Supervised Learning

In supervised learning, we are given a data set and already know what our correct output should look like, having the idea that there is a relationship between the input and the output.

Supervised learning problems are categorized into "regression" and "classification" problems. In a regression problem, we are trying to predict results within a continuous output, meaning that we are trying to map input variables to some continuous function. In a classification problem, we are instead trying to predict results in a discrete output. In other words, we are trying to map input variables into discrete categories.

Example 1:

Given data about the size of houses on the real estate market, try to predict their price. Price as a function of size is a continuous output, so this is a regression problem.

We could turn this example into a classification problem by instead making our output about whether the house "sells for more or less than the asking price." Here we are classifying the houses based on price into two discrete categories.

Example 2:

(a) Regression - Given a picture of a person, we have to predict their age on the basis of the given picture

(b) Classification - Given a patient with a tumor, we have to predict whether the tumor is malignant or benign.

##Unsupervised Learning

Unsupervised learning allows us to approach problems with little or no idea what our results should look like. We can derive structure from data where we don't necessarily know the effect of the variables.

We can derive this structure by clustering the data based on relationships among the variables in the data.

With unsupervised learning there is no feedback based on the prediction results.

Example:

Clustering: Take a collection of 1,000,000 different genes, and find a way to automatically group these genes into groups that are somehow similar or related by different variables, such as lifespan, location, roles, and so on.

Non-clustering: The "Cocktail Party Algorithm", allows you to find structure in a chaotic environment. (i.e. identifying individual voices and music from a mesh of sounds at a cocktail party).

### Wish List

* Learn Octave


text:
use std::fmt;
use RosalindResult;
use constants::FASTA_LABEL_SYMBOL;

/// This structure contains info about the string with the highest GC content
#[allow(non_snake_case)]
#[derive(PartialEq, Debug)]
pub struct GCcontent {
  pub string_id: String,
  pub gc_content: f32
}

impl fmt::Display for GCcontent {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}\n{}", self.string_id, self.gc_content)
  }
}

/// This function calculates gc content of given DNA string
///
/// ## Examples
/// ```
/// use rosalind::gc::*;
///
/// assert_eq!(gc_content("").unwrap(), 0f32);
/// assert_eq!(gc_content("AGCTATAG").unwrap(), 37.5f32);
/// ```
pub fn gc_content(dna: &str) -> RosalindResult<f32> {
  let dna_len = dna.len();
  if dna_len == 0 { return Ok(0f32); }

  let gc_counter: f32 = dna.chars().fold(0f32, |mut counter, nucleotide| {
    match nucleotide {
      'G' | 'C' => counter += 1f32,
      _ => {},
    }
    counter
  });

  let gc: f32 = gc_counter * 100f32 / (dna_len as f32);
  Ok(gc)
}

/// This function calculates best gc content in the given dataset and
/// returns ID of the string with the highest GC content and GC content
///
/// ## Examples
/// ```
/// use rosalind::gc::*;
///
/// let dataset = ">Rosalind_6404
///   CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
///   TCCCACTAATAATTCTGAGG
///   >Rosalind_5959
///   CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
///   ATATCCATTTGTCAGCAGACACGC
///   >Rosalind_0808
///   CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
///   TGGGAACCTGCGGGCAGTAGGTGGAAT";
///
/// assert_eq!(best_gc_content_in_dataset(dataset).unwrap(),
///   GCcontent {string_id: "Rosalind_0808".to_string(), gc_content: 60.919540f32});
/// ```
// TODO: refactor - use utils:parse_fasta_dataset
pub fn best_gc_content_in_dataset(dataset: &str) -> RosalindResult<GCcontent> {
  let mut best_gc_label = "".to_string();
  let mut best_gc_content = 0f32;
  let mut current_gc_content: f32;
  let mut dna_string = "".to_string();

  for mut dataset_line in dataset.lines().rev() {
    dataset_line = dataset_line.trim();
    let first_symbol = dataset_line.chars().nth(0).unwrap();

    if first_symbol == FASTA_LABEL_SYMBOL {
      current_gc_content = gc_content(&dna_string).unwrap();

      if current_gc_content > best_gc_content {
        best_gc_label = dataset_line[1..].to_string();
        best_gc_content = current_gc_content;
      }

      dna_string = "".to_string();
    } else {
      dna_string = dna_string + dataset_line;
    }
  }

  Ok(GCcontent {string_id: best_gc_label, gc_content: best_gc_content})
}

#[cfg(test)]
mod tests {
  use super::gc_content;
  use super::best_gc_content_in_dataset;
  use super::GCcontent;

  #[test]
  fn it_should_return_0_for_empty_dna_string() {
    assert_eq!(gc_content("").unwrap(), 0f32);
  }

  #[test]
  fn it_should_calculate_gc_content_of_dna() {
    assert_eq!(gc_content("AGCTATAG").unwrap(), 37.5f32);
  }

  #[test]
  fn it_should_calculate_best_gc_content() {
    let dataset = ">Rosalind_6404
      CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
      TCCCACTAATAATTCTGAGG
      >Rosalind_5959
      CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
      ATATCCATTTGTCAGCAGACACGC
      >Rosalind_0808
      CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
      TGGGAACCTGCGGGCAGTAGGTGGAAT";

    assert_eq!(best_gc_content_in_dataset(dataset).unwrap(),
      GCcontent {string_id: "Rosalind_0808".to_string(), gc_content: 60.919540f32});
  }

  #[test]
  fn it_should_format_gc_content() {
    let gc_content = GCcontent {string_id: "Rosalind_0808".to_string(), gc_content: 123.45f32};
    assert_eq!(gc_content.to_string(), "Rosalind_0808\n123.45");
  }
}


text:
namespace safe_browsing {

class SandboxedZipAnalyzerTest : public ::testing::Test {
 protected:
  // Constants for validating the data reported by the analyzer.
  struct BinaryData {
    const char* file_basename;
    ClientDownloadRequest_DownloadType download_type;
    const uint8_t* sha256_digest;
    int64_t length;
    bool is_signed;
  };

  // A helper that provides a SandboxedZipAnalyzer::ResultCallback that will
  // store a copy of an analyzer's results and then run a closure.
  class ResultsGetter {
   public:
    ResultsGetter(const base::Closure& quit_closure,
                  zip_analyzer::Results* results)
        : quit_closure_(quit_closure),
          results_(results) {
      DCHECK(results);
      results->success = false;
    }

    SandboxedZipAnalyzer::ResultCallback GetCallback() {
      return base::Bind(&ResultsGetter::OnZipAnalyzerResults,
                        base::Unretained(this));
    }

   private:
    void OnZipAnalyzerResults(const zip_analyzer::Results& results) {
      *results_ = results;
      quit_closure_.Run();
    }

    base::Closure quit_closure_;
    zip_analyzer::Results* results_;
    DISALLOW_COPY_AND_ASSIGN(ResultsGetter);
  };

  SandboxedZipAnalyzerTest()
      : browser_thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}

  void SetUp() override {
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &dir_test_data_));
    dir_test_data_ = dir_test_data_.AppendASCII("safe_browsing");
    dir_test_data_ = dir_test_data_.AppendASCII("download_protection");
  }

  // Runs a sandboxed zip analyzer on |file_path|, writing its results into
  // |results|.
  void RunAnalyzer(const base::FilePath& file_path,
                   zip_analyzer::Results* results) {
    DCHECK(results);
    base::RunLoop run_loop;
    ResultsGetter results_getter(run_loop.QuitClosure(), results);
    scoped_refptr<SandboxedZipAnalyzer> analyzer(
        new SandboxedZipAnalyzer(file_path, results_getter.GetCallback()));
    analyzer->Start();
    run_loop.Run();
  }

#if defined(OS_WIN)
  void ExpectPEHeaders(const BinaryData& data,
                       const ClientDownloadRequest_ArchivedBinary& binary) {
    ASSERT_EQ(data.is_signed, binary.has_signature());
    if (data.is_signed) {
      ASSERT_LT(0, binary.signature().signed_data_size());
      ASSERT_NE(0U, binary.signature().signed_data(0).size());
    }
    ASSERT_TRUE(binary.has_image_headers());
    ASSERT_TRUE(binary.image_headers().has_pe_headers());
    EXPECT_TRUE(binary.image_headers().pe_headers().has_dos_header());
    EXPECT_TRUE(binary.image_headers().pe_headers().has_file_header());
    EXPECT_TRUE(binary.image_headers().pe_headers().has_optional_headers32());
    EXPECT_FALSE(binary.image_headers().pe_headers().has_optional_headers64());
  }
#endif

  // Verifies expectations about a binary found by the analyzer.
  void ExpectBinary(const BinaryData& data,
                    const ClientDownloadRequest_ArchivedBinary& binary) {
    ASSERT_TRUE(binary.has_file_basename());
    EXPECT_EQ(data.file_basename, binary.file_basename());
    ASSERT_TRUE(binary.has_download_type());
    EXPECT_EQ(data.download_type, binary.download_type());
    ASSERT_TRUE(binary.has_digests());
    ASSERT_TRUE(binary.digests().has_sha256());
    EXPECT_EQ(std::string(data.sha256_digest,
                          data.sha256_digest + crypto::kSHA256Length),
              binary.digests().sha256());
    EXPECT_FALSE(binary.digests().has_sha1());
    EXPECT_FALSE(binary.digests().has_md5());
    ASSERT_TRUE(binary.has_length());
    EXPECT_EQ(data.length, binary.length());
#if defined(OS_WIN)
    // ExtractImageFeatures only implemented for Windows, and only works on PE
    // files.
    if (binary.file_basename().find(".exe") != std::string::npos) {
      ExpectPEHeaders(data, binary);
      return;
    }
#endif  // OS_WIN
    ASSERT_FALSE(binary.has_signature());
    ASSERT_FALSE(binary.has_image_headers());
  }

  static const uint8_t kUnsignedDigest[];
  static const uint8_t kSignedDigest[];
  static const uint8_t kJSEFileDigest[];
  static const BinaryData kUnsignedExe;
  static const BinaryData kSignedExe;
  static const BinaryData kJSEFile;

  base::FilePath dir_test_data_;
  content::TestBrowserThreadBundle browser_thread_bundle_;
  content::InProcessUtilityThreadHelper utility_thread_helper_;
};

// static
const uint8_t SandboxedZipAnalyzerTest::kUnsignedDigest[] = {
    0x1e, 0x95, 0x4d, 0x9c, 0xe0, 0x38, 0x9e, 0x2b, 0xa7, 0x44, 0x72,
    0x16, 0xf2, 0x17, 0x61, 0xf9, 0x8d, 0x1e, 0x65, 0x40, 0xc2, 0xab,
    0xec, 0xdb, 0xec, 0xff, 0x57, 0x0e, 0x36, 0xc4, 0x93, 0xdb};
const uint8_t SandboxedZipAnalyzerTest::kSignedDigest[] = {
    0xe1, 0x1f, 0xfa, 0x0c, 0x9f, 0x25, 0x23, 0x44, 0x53, 0xa9, 0xed,
    0xd1, 0xcb, 0x25, 0x1d, 0x46, 0x10, 0x7f, 0x34, 0xb5, 0x36, 0xad,
    0x74, 0x64, 0x2a, 0x85, 0x84, 0xac, 0xa8, 0xc1, 0xa8, 0xce};
const uint8_t SandboxedZipAnalyzerTest::kJSEFileDigest[] = {
    0x58, 0x91, 0xb5, 0xb5, 0x22, 0xd5, 0xdf, 0x08, 0x6d, 0x0f, 0xf0,
    0xb1, 0x10, 0xfb, 0xd9, 0xd2, 0x1b, 0xb4, 0xfc, 0x71, 0x63, 0xaf,
    0x34, 0xd0, 0x82, 0x86, 0xa2, 0xe8, 0x46, 0xf6, 0xbe, 0x03};
const SandboxedZipAnalyzerTest::BinaryData
    SandboxedZipAnalyzerTest::kUnsignedExe = {
  "unsigned.exe",
  ClientDownloadRequest_DownloadType_WIN_EXECUTABLE,
  &kUnsignedDigest[0],
  36864,
  false,  // !is_signed
};
const SandboxedZipAnalyzerTest::BinaryData
    SandboxedZipAnalyzerTest::kSignedExe = {
  "signed.exe",
  ClientDownloadRequest_DownloadType_WIN_EXECUTABLE,
  &kSignedDigest[0],
  37768,
  true,  // is_signed
};
const SandboxedZipAnalyzerTest::BinaryData SandboxedZipAnalyzerTest::kJSEFile =
    {
        "hello.jse",
        ClientDownloadRequest_DownloadType_WIN_EXECUTABLE,
        &kJSEFileDigest[0],
        6,
        false,  // is_signed
};

TEST_F(SandboxedZipAnalyzerTest, NoBinaries) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_no_binaries.zip"), &results);
  ASSERT_TRUE(results.success);
  EXPECT_FALSE(results.has_executable);
  EXPECT_FALSE(results.has_archive);
  EXPECT_EQ(0, results.archived_binary.size());
}

TEST_F(SandboxedZipAnalyzerTest, OneUnsignedBinary) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_one_unsigned_binary.zip"),
              &results);
  ASSERT_TRUE(results.success);
  EXPECT_TRUE(results.has_executable);
  EXPECT_FALSE(results.has_archive);
  ASSERT_EQ(1, results.archived_binary.size());
  ExpectBinary(kUnsignedExe, results.archived_binary.Get(0));
}

TEST_F(SandboxedZipAnalyzerTest, TwoBinariesOneSigned) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_two_binaries_one_signed.zip"),
              &results);
  ASSERT_TRUE(results.success);
  EXPECT_TRUE(results.has_executable);
  EXPECT_FALSE(results.has_archive);
  ASSERT_EQ(2, results.archived_binary.size());
  ExpectBinary(kUnsignedExe, results.archived_binary.Get(0));
  ExpectBinary(kSignedExe, results.archived_binary.Get(1));
}

TEST_F(SandboxedZipAnalyzerTest, ZippedArchiveNoBinaries) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_archive_no_binaries.zip"),
              &results);
  ASSERT_TRUE(results.success);
  EXPECT_FALSE(results.has_executable);
  EXPECT_TRUE(results.has_archive);
  EXPECT_EQ(0, results.archived_binary.size());
  ASSERT_EQ(1u, results.archived_archive_filenames.size());
  EXPECT_EQ(FILE_PATH_LITERAL("hello.zip"),
            results.archived_archive_filenames[0].value());
}

TEST_F(SandboxedZipAnalyzerTest, ZippedRarArchiveNoBinaries) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_rar_archive_no_binaries.zip"),
              &results);
  ASSERT_TRUE(results.success);
  EXPECT_FALSE(results.has_executable);
  EXPECT_TRUE(results.has_archive);
  EXPECT_EQ(0, results.archived_binary.size());
  ASSERT_EQ(1u, results.archived_archive_filenames.size());
  EXPECT_EQ(FILE_PATH_LITERAL("hello.rar"),
            results.archived_archive_filenames[0].value());
}

TEST_F(SandboxedZipAnalyzerTest, ZippedArchiveAndBinaries) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_archive_and_binaries.zip"),
              &results);
  ASSERT_TRUE(results.success);
  EXPECT_TRUE(results.has_executable);
  EXPECT_TRUE(results.has_archive);
  ASSERT_EQ(1, results.archived_binary.size());
  ExpectBinary(kSignedExe, results.archived_binary.Get(0));
  ASSERT_EQ(1u, results.archived_archive_filenames.size());
  EXPECT_EQ(FILE_PATH_LITERAL("hello.7z"),
            results.archived_archive_filenames[0].value());
}

TEST_F(SandboxedZipAnalyzerTest,
       ZippedArchiveAndBinariesWithTrailingSpaceAndPeriodChars) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_two_binaries_one_archive_"
                                         "trailing_space_and_period_chars.zip"),
              &results);
  ASSERT_TRUE(results.success);
  EXPECT_TRUE(results.has_executable);
  EXPECT_TRUE(results.has_archive);
  ASSERT_EQ(2, results.archived_binary.size());

  BinaryData SignedExe = kSignedExe;
  SignedExe.file_basename = "signed.exe ";
  BinaryData UnsignedExe = kUnsignedExe;
  UnsignedExe.file_basename = "unsigned.exe.";
  ExpectBinary(SignedExe, results.archived_binary.Get(0));
  ExpectBinary(UnsignedExe, results.archived_binary.Get(1));
  ASSERT_EQ(1u, results.archived_archive_filenames.size());
  EXPECT_EQ(FILE_PATH_LITERAL("zipfile_no_binaries.zip  .  . "),
            results.archived_archive_filenames[0].value());
}

TEST_F(SandboxedZipAnalyzerTest, ZippedJSEFile) {
  zip_analyzer::Results results;
  RunAnalyzer(dir_test_data_.AppendASCII("zipfile_one_jse_file.zip"), &results);
  ASSERT_TRUE(results.success);
  EXPECT_TRUE(results.has_executable);
  EXPECT_FALSE(results.has_archive);
  ASSERT_EQ(1, results.archived_binary.size());
  ExpectBinary(kJSEFile, results.archived_binary.Get(0));
  EXPECT_TRUE(results.archived_archive_filenames.empty());
}

}  // namespace safe_browsing


text:
//
//  DHService.h
//  DeviceHiveFramework
//
//  Created by Kiselev Maxim on 1/10/13.
//  Copyright (c) 2013 DataArt Apps. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 Completion block which is used and invoked in context of the service operation if this operation succeeds.
 @param response Response object provided by the server.
 */
typedef void (^DHServiceSuccessCompletionBlock)(id response);

/**
 Completion block which is used and invoked in context of the service operation if this operation fails.
 @param error An instance of NSError describing the error.
 */
typedef void (^DHServiceFailureCompletionBlock)(NSError *error);

/**
 `DHService` protocol defines common interface for Device Hive services: client and device.
 */
@protocol DHService <NSObject>

/**
 Get meta-information of the current API. Returns `DHApiInfo` instance as a result.
 @param success Success completion block.
 @param failure Failure completion block.
 */
- (void)getApiInfoWithSuccess:(DHServiceSuccessCompletionBlock)success
                      failure:(DHServiceFailureCompletionBlock)failure;

/**
 Cancel all queued requests.
 */
- (void)cancelAllServiceRequests;

@end


text:
function db_set(ICAw, fld, val, rs)

% ICAw_set allows for introducing controlled (safe) changes to
% the ICAw structure
%
% ICAw_set(ICAw, fld, val)

conflict_matrix = db_check_conflict(db, rs, field);

% different GUI options for different conflicts

% current "recompute and compare" options would be:
% - for rejections --> moving them from the previous
%   state of the database to the current by an operation
%   like:
%    > compare % or sample coverage and mark
% - for ICA --> comparing previous components with current
%   (if they exist) and moving component labels.


text:
module Flint

  def self.declare(*args)
    Sass::Script::Functions.declare(*args)
  end

  #
  # Use ruby functions
  #
  # @return {Bool}
  #
  def flint_use_ruby()
    Sass::Script::Bool.new(true)
  end

  #
  # Fetch value from map
  #
  # @param {Map}     map  - map to fetch value from
  # @param {ArgList} keys - list of keys to traverse
  #
  # @return {*}
  #
  def flint_ruby_map_fetch(map, *keys)
    assert_type map, :Map, :map

    result = map
    keys.each { |key| result.nil? ? break : result = result.to_h.fetch(key, nil) }

    unless result.nil?
      result
    else
      Sass::Script::Bool.new(false)
    end
  end
  declare :flint_ruby_map_fetch, :args => [:map, :keys], :var_args => true

  #
  # Joins all elements of list with passed glue
  #
  # @param {List}   list
  # @param {String} glue
  #
  # @return {String}
  #
  def flint_ruby_list_to_str(list, glue)
    assert_type list, :List, :list
    assert_type glue, :String, :glue

    arr = list.to_a.flatten.map { |item| item.value }

    Sass::Script::String.new(arr.join(glue.value))
  end
  declare :flint_ruby_list_to_str, :args => [:list, :glue]

  #
  # Turn string into a flat list
  #
  # @param {String} string    - string to operate on
  # @param {String} separator - item to find which separates substrings
  # @param {String} ignore    - removes remaining string beyond item
  #
  # @return {List}
  #
  def flint_ruby_str_to_list(string, separator, ignore)
    assert_type string, :String, :string
    assert_type separator, :String, :separator
    assert_type ignore, :String, :ignore

    # Remove everything after ignore, split with separator
    items = string.value[/[^#{ignore}]+/].split(separator.value)

    if items.count == 1
      Sass::Script::String.new(items[0], :comma)
    else
      Sass::Script::List.new(items.map { |i| Sass::Script::String.new(i) }, :comma)
    end
  end
  declare :flint_ruby_str_to_list, :args => [:string, :separator, :ignore]

  #
  # Replace substring with string
  #
  # @param {String} string  - string that contains substring
  # @param {String} find    - substring to replace
  # @param {String} replace - new string to replace sub with
  #
  # @return {String}
  #
  def flint_ruby_str_replace(string, find, replace)
    assert_type string, :String, :string
    assert_type find, :String, :find
    assert_type replace, :String, :replace

    Sass::Script::String.new(string.value.gsub(find.value, replace.value))
  end
  declare :flint_ruby_str_replace, :args => [:string, :find, :replace]

end


text:
package z.rethink.ql;

public class Options implements ToJson {
    @Override
    public void toJson(StringBuilder builder) {
        //TODO
    }
}


text:
class Dist:

    def __init__(self, feed):
        self.feed = feed

    def _to_attr_items(self, post, attr):
        attr_items = ''
        if isinstance(getattr(post, attr), str):
            attr_items = [getattr(post, attr)]
        if isinstance(getattr(post, attr), unicode):
            attr_items = [getattr(post, attr)]
        elif isinstance(getattr(post, attr), list):
            attr_items = getattr(post, attr)
        else:
            attr_items [str(getattr(post, attr))]
        return attr_items

    def _distribution(self, attr='author', attr_processor=None):
        if not attr_processor:
            attr_processor = self._to_attr_items
        authmap = {}
        for post in self.feed:
            attr_items = attr_processor(post, attr)
            for attr_item in attr_items:
                authmap[attr_item] = authmap.get(attr_item, 0) + 1
        return authmap

    def _2d_distribution(self, attr1='date', attr2='author', attr_processor=None):
        if not attr_processor:
            attr_processor = self._to_attr_items
        authmap = {}
        for post in self.feed:
            authmap[getattr(post, attr1)] = authmap.get(getattr(post, attr1), {})
            attr_items = attr_processor(post, attr2)
            for attr_item in attr_items:
                authmap[getattr(post, attr1)][attr_item] = authmap[getattr(post, attr1)].get(attr_item, 0) + 1
        return authmap

    def _time_distribution(self, attr='author', attr_processor=None):
        return self._2d_distribution(attr1='date', attr2=attr, attr_processor=None)


text:
package commands

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	"github.com/bryanl/doit"
	"github.com/digitalocean/godo"
	"github.com/stretchr/testify/assert"
)

var (
	testKey     = godo.Key{ID: 1, Fingerprint: "fingerprint"}
	testKeyList = []godo.Key{testKey}
)

func TestKeysList(t *testing.T) {
	didList := false

	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			ListFn: func(opts *godo.ListOptions) ([]godo.Key, *godo.Response, error) {
				didList = true

				resp := &godo.Response{
					Links: &godo.Links{
						Pages: &godo.Pages{},
					},
				}

				return testKeyList, resp, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		RunKeyList(ns, ioutil.Discard)
		assert.True(t, didList)
	})
}

func TestKeysGetByID(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			GetByIDFn: func(id int) (*godo.Key, *godo.Response, error) {
				assert.Equal(t, id, testKey.ID)
				return &testKey, nil, nil
			},
			GetByFingerprintFn: func(_ string) (*godo.Key, *godo.Response, error) {
				t.Error("should not request by fingerprint")
				return nil, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKey, "1")

		RunKeyGet(ns, ioutil.Discard)
	})
}

func TestKeysGetByFingerprint(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			GetByFingerprintFn: func(fingerprint string) (*godo.Key, *godo.Response, error) {
				assert.Equal(t, fingerprint, testKey.Fingerprint)
				return &testKey, nil, nil
			},
			GetByIDFn: func(_ int) (*godo.Key, *godo.Response, error) {
				t.Error("should not request by id")
				return nil, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKey, testKey.Fingerprint)

		RunKeyGet(ns, ioutil.Discard)
	})
}

func TestKeysCreate(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			CreateFn: func(req *godo.KeyCreateRequest) (*godo.Key, *godo.Response, error) {
				expected := &godo.KeyCreateRequest{
					Name:      "the key",
					PublicKey: "fingerprint",
				}
				assert.Equal(t, req, expected)
				return &testKey, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKeyName, "the key")
		c.Set(ns, doit.ArgKeyPublicKey, "fingerprint")

		RunKeyCreate(ns, ioutil.Discard)
	})
}

func TestKeysDeleteByID(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			DeleteByIDFn: func(id int) (*godo.Response, error) {
				assert.Equal(t, id, 1)
				return nil, nil
			},
			DeleteByFingerprintFn: func(fingerprint string) (*godo.Response, error) {
				t.Errorf("should not call fingerprint")
				return nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKey, "1")

		RunKeyDelete(ns, ioutil.Discard)
	})
}

func TestKeysDeleteByFingerprint(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			DeleteByFingerprintFn: func(fingerprint string) (*godo.Response, error) {
				assert.Equal(t, fingerprint, "fingerprint")
				return nil, nil
			},
			DeleteByIDFn: func(_ int) (*godo.Response, error) {
				t.Errorf("should not call id")
				return nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKey, "fingerprint")

		RunKeyDelete(ns, ioutil.Discard)
	})

}

func TestKeysUpdateByID(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			UpdateByIDFn: func(id int, req *godo.KeyUpdateRequest) (*godo.Key, *godo.Response, error) {
				expected := &godo.KeyUpdateRequest{
					Name: "the key",
				}
				assert.Equal(t, req, expected)
				assert.Equal(t, id, 1)
				return &testKey, nil, nil
			},
			UpdateByFingerprintFn: func(_ string, _ *godo.KeyUpdateRequest) (*godo.Key, *godo.Response, error) {
				t.Error("should update by id")
				return nil, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKey, "1")
		c.Set(ns, doit.ArgKeyName, "the key")

		RunKeyUpdate(ns, ioutil.Discard)
	})

}

func TestKeysUpdateByFingerprint(t *testing.T) {
	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			UpdateByFingerprintFn: func(fingerprint string, req *godo.KeyUpdateRequest) (*godo.Key, *godo.Response, error) {
				expected := &godo.KeyUpdateRequest{
					Name: "the key",
				}
				assert.Equal(t, req, expected)
				assert.Equal(t, fingerprint, "fingerprint")
				return &testKey, nil, nil
			},
			UpdateByIDFn: func(_ int, _ *godo.KeyUpdateRequest) (*godo.Key, *godo.Response, error) {
				t.Error("should update by fingerprint")
				return nil, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKey, "fingerprint")
		c.Set(ns, doit.ArgKeyName, "the key")

		RunKeyUpdate(ns, ioutil.Discard)
	})

}

func TestSSHPublicKeyImport(t *testing.T) {
	pubkey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn6eZ8ve0ha04rPRZuoPXK1AQ/h21qslWCzoDcOciXn5OcyafkZw+31k/afaBTeW62D8fXd8e/1xWbFfp/2GqmslYpNCTPrtpNhsE8I0yKjJ8FxX9FfsCOu/Sv83dWgSpiT7pNWVKarZjW9KdKKRQljq1i+H5pX3r5Q9I1v+66mYTe7qsKGas9KWy0vkGoNSqmTCl+d+Y0286chtqBqBjSCUCI8oLKPnJB86Lj344tFGmzDIsJKXMVHTL0dF8n3u6iWN4qiRU+JvkoIkI3v0JvyZXxhR2uPIS1yUAY2GC+2O5mfxydJQzBdtag5Uw8Y7H5yYR1gar/h16bAy5XzRvp testkey"
	path := filepath.Join(os.TempDir(), "key.pub")
	err := ioutil.WriteFile(path, []byte(pubkey), 0600)
	assert.NoError(t, err)
	defer os.Remove(path)

	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			CreateFn: func(req *godo.KeyCreateRequest) (*godo.Key, *godo.Response, error) {
				expected := &godo.KeyCreateRequest{
					Name:      "testkey",
					PublicKey: pubkey,
				}
				assert.Equal(t, req, expected)
				return &testKey, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKeyPublicKey, "fingerprint")
		c.Set(ns, doit.ArgKeyPublicKeyFile, path)

		RunKeyImport(ns, ioutil.Discard)
	})

}

func TestSSHPublicKeyImportWithName(t *testing.T) {
	pubkey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn6eZ8ve0ha04rPRZuoPXK1AQ/h21qslWCzoDcOciXn5OcyafkZw+31k/afaBTeW62D8fXd8e/1xWbFfp/2GqmslYpNCTPrtpNhsE8I0yKjJ8FxX9FfsCOu/Sv83dWgSpiT7pNWVKarZjW9KdKKRQljq1i+H5pX3r5Q9I1v+66mYTe7qsKGas9KWy0vkGoNSqmTCl+d+Y0286chtqBqBjSCUCI8oLKPnJB86Lj344tFGmzDIsJKXMVHTL0dF8n3u6iWN4qiRU+JvkoIkI3v0JvyZXxhR2uPIS1yUAY2GC+2O5mfxydJQzBdtag5Uw8Y7H5yYR1gar/h16bAy5XzRvp testkey"
	path := filepath.Join(os.TempDir(), "key.pub")
	err := ioutil.WriteFile(path, []byte(pubkey), 0600)
	assert.NoError(t, err)
	defer os.Remove(path)

	client := &godo.Client{
		Keys: &doit.KeysServiceMock{
			CreateFn: func(req *godo.KeyCreateRequest) (*godo.Key, *godo.Response, error) {
				expected := &godo.KeyCreateRequest{
					Name:      "custom",
					PublicKey: pubkey,
				}
				assert.Equal(t, req, expected)
				return &testKey, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgKeyName, "custom")
		c.Set(ns, doit.ArgKeyPublicKeyFile, path)

		RunKeyImport(ns, ioutil.Discard)
	})
}


text:
// Code generated by protoc-gen-go.
// source: c2s/controlview.proto
// DO NOT EDIT!

/*
Package c2s is a generated protocol buffer package.

It is generated from these files:
	c2s/controlview.proto

It has these top-level messages:
	Controlview
*/
package c2s

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

type Controlview struct {
	Viewid           *int32 `protobuf:"varint,1,req,name=viewid" json:"viewid,omitempty"`
	Op               *int32 `protobuf:"varint,2,req,name=op" json:"op,omitempty"`
	XXX_unrecognized []byte `json:"-"`
}

func (m *Controlview) Reset()         { *m = Controlview{} }
func (m *Controlview) String() string { return proto.CompactTextString(m) }
func (*Controlview) ProtoMessage()    {}

func (m *Controlview) GetViewid() int32 {
	if m != nil && m.Viewid != nil {
		return *m.Viewid
	}
	return 0
}

func (m *Controlview) GetOp() int32 {
	if m != nil && m.Op != nil {
		return *m.Op
	}
	return 0
}


text:
package ru.silverhammer.processor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GroupId {

	String value();

}


text:
from __future__ import annotations

import sys

import pytest

@pytest.fixture(autouse=True)
def no_warnings(recwarn):
    yield
    warnings = tuple(
        warning for warning in recwarn
        # python2 + pypy warn:
        # ImportWarning: Not importing directory '...' missing __init__.py
        if not (
            isinstance(warning.message, ImportWarning) and
            str(warning.message).startswith('Not importing directory ') and
            str(warning.message).endswith(' missing __init__.py')
        )
    )
    assert len(warnings) == 0

@pytest.fixture
def in_tmpdir(tmpdir):
    with tmpdir.as_cwd():
        yield tmpdir

@pytest.fixture
def no_empty_path():
    # Some of our tests check things based on their pwd where things aren't
    # necessarily importable.  Let's make them not actually importable.
    empty_in_path = '' in sys.path
    if empty_in_path:  # pragma: no cover (depends on running conditions)
        # We're going to assume it is at the beginning
        sys.path.remove('')
        yield
        sys.path.insert(0, '')
    else:  # pragma: no cover (depend on running conditions)
        # noop
        yield


text:
from unittest import mock

from oslo_config import cfg

from mistral.service import coordination
from mistral.tests.unit import base

class ServiceCoordinatorTest(base.BaseTest):
    def test_start(self):
        cfg.CONF.set_default(
            'backend_url',
            'zake://',
            'coordination'
        )

        coordinator = coordination.ServiceCoordinator('fake_id')
        coordinator.start()

        self.assertTrue(coordinator.is_active())

    def test_start_without_backend(self):
        cfg.CONF.set_default('backend_url', None, 'coordination')

        coordinator = coordination.ServiceCoordinator()
        coordinator.start()

        self.assertFalse(coordinator.is_active())

    def test_stop_not_active(self):
        cfg.CONF.set_default('backend_url', None, 'coordination')

        coordinator = coordination.ServiceCoordinator()
        coordinator.start()

        coordinator.stop()

        self.assertFalse(coordinator.is_active())

    def test_stop(self):
        cfg.CONF.set_default(
            'backend_url',
            'zake://',
            'coordination'
        )

        coordinator = coordination.ServiceCoordinator()
        coordinator.start()

        coordinator.stop()

        self.assertFalse(coordinator.is_active())

    def test_join_group_not_active(self):
        cfg.CONF.set_default('backend_url', None, 'coordination')

        coordinator = coordination.ServiceCoordinator()
        coordinator.start()

        coordinator.join_group('fake_group')
        members = coordinator.get_members('fake_group')

        self.assertFalse(coordinator.is_active())

        self.assertEqual(0, len(members))

    def test_join_group_and_get_members(self):
        cfg.CONF.set_default(
            'backend_url',
            'zake://',
            'coordination'
        )

        coordinator = coordination.ServiceCoordinator(my_id='fake_id')
        coordinator.start()

        coordinator.join_group('fake_group')
        members = coordinator.get_members('fake_group')

        self.assertEqual(1, len(members))
        self.assertCountEqual(('fake_id'.encode("latin-1"),), members)

    def test_join_group_and_leave_group(self):
        cfg.CONF.set_default(
            'backend_url',
            'zake://',
            'coordination'
        )

        coordinator = coordination.ServiceCoordinator(my_id='fake_id')
        coordinator.start()

        coordinator.join_group('fake_group')
        members_before = coordinator.get_members('fake_group')

        coordinator.leave_group('fake_group')
        members_after = coordinator.get_members('fake_group')

        self.assertEqual(1, len(members_before))
        self.assertEqual(set(['fake_id'.encode("latin-1")]), members_before)

        self.assertEqual(0, len(members_after))
        self.assertEqual(set([]), members_after)

class ServiceTest(base.BaseTest):
    def setUp(self):
        super(ServiceTest, self).setUp()

        # Re-initialize the global service coordinator object, in order to use
        # new coordination configuration.
        coordination.cleanup_service_coordinator()

    @mock.patch('mistral_lib.utils.get_process_identifier',
                return_value='fake_id')
    def test_register_membership(self, mock_get_identifier):
        cfg.CONF.set_default('backend_url', 'zake://', 'coordination')

        srv = coordination.Service('fake_group')
        srv.register_membership()

        self.addCleanup(srv.stop)

        srv_coordinator = coordination.get_service_coordinator()

        self.assertIsNotNone(srv_coordinator)
        self.assertTrue(srv_coordinator.is_active())

        members = srv_coordinator.get_members('fake_group')

        mock_get_identifier.assert_called_once_with()
        self.assertEqual(set(['fake_id'.encode("latin-1")]), members)


text:
<component name="libraryTable">
  <library name="Maven: org.apache.hadoop:hadoop-annotations:2.5.2">
    <CLASSES>
      <root url="jar://$USER_HOME$/maven/repo/org/apache/hadoop/hadoop-annotations/2.5.2/hadoop-annotations-2.5.2.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/maven/repo/org/apache/hadoop/hadoop-annotations/2.5.2/hadoop-annotations-2.5.2-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/maven/repo/org/apache/hadoop/hadoop-annotations/2.5.2/hadoop-annotations-2.5.2-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
#include "m2.h"

M2_EL_FN_DEF(m2_el_vsb_fn)
{
  switch(fn_arg->msg)
  {
    case M2_EL_MSG_IS_READ_ONLY:
      return 1; /* if this is ever replaced, then it should default to r1 */
    case M2_EL_MSG_GET_HEIGHT:
      return m2_el_slbase_calc_height(fn_arg->element);
    case M2_EL_MSG_GET_WIDTH:
      return m2_el_slbase_calc_width(fn_arg->element);
#ifdef M2_EL_MSG_DBG_SHOW
    case M2_EL_MSG_DBG_SHOW:
      {
	uint8_t width, height;
	m2_pos_p b = (m2_pos_p)(fn_arg->data);
	width = m2_el_slbase_calc_width((fn_arg->element));
	height = m2_el_slbase_calc_height((fn_arg->element));
	printf("sb w:%d h:%d arg:%d x:%d y:%d len:%d\n", width, height,
	    (fn_arg->arg), b->x, b->y, m2_el_slbase_get_len(fn_arg->element));
      }
      return 0;
#endif
      case M2_EL_MSG_SHOW:

	/* MSG_SHOW: parent is drawn before the sub elements */
	/* adjust top element to total size, if required */
	m2_el_slbase_adjust_top_to_cnt(fn_arg->element);
	{
	  m2_pos_p b = (m2_pos_p)(fn_arg->data);
	  m2_gfx_draw_vertical_scroll_bar(b->x, b->y,
	    m2_el_slbase_calc_width(fn_arg->element),
	    m2_el_slbase_calc_height(fn_arg->element),
	    m2_el_slbase_get_len(fn_arg->element),
	    m2_el_slbase_get_top(fn_arg->element),
	    m2_el_slbase_get_visible_lines(fn_arg->element));
	}
	break;
  }
  return m2_el_fnfmt_fn(fn_arg);
}

/*
  calculate pixel height of the slider.
  visible = number of visible lines
  height = total height of the scroll bar in pixel
  total = total number of lines

  h = visible * height / total

  this is a support procedure for the graphics handler
*/
uint8_t m2_utl_sb_get_slider_height(uint8_t height, uint8_t total, uint8_t visible)
{
  uint16_t tmp;
  uint8_t slider;
  /*
  if ( top+visible > total )
  {
    visible = total;
    visible -= top;
  }
  */
  if ( total <= visible )
    return height;

  tmp = height;
  tmp *= visible;
  tmp /= total;
  slider = tmp;
  if ( slider == 0 )
    slider++;
  /*
  if ( visible < total )
    if ( sbh == height )
      sbh--;
  */
  return slider;
}

/*
  calculate the slider pixel position

  height = total height of the scroll bar in pixel
  slider = slider height, returned from m2_utl_sb_get_slider_height()
  visible = number of visible lines
  total = total number of lines
  top = topmost visible line

  position = top*(height-slider)/(total-visible)

  this is a support procedure for the graphics handler
*/
uint8_t m2_utl_sb_get_slider_position(uint8_t height, uint8_t slider, uint8_t total, uint8_t visible, uint8_t top)
{
  uint16_t pos;
  if ( total <= visible )
    return 0;
  height -= slider;
  total -= visible;
  pos = top;
  pos *= height;
  pos /= total;
  return pos;
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Olea lindleyi Wall.

### Remarks
null


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>LABjs tests (LABjs with preloading #12a)</title>

LABjs tests (LABjs with preloading #12a)

test 12a

test 12b

test 12c

test 12d

test 12e

test 12f

test 12g

<form name="log_form">
<textarea id="load_log" name="load_log" cols="80" rows="10"></textarea>
</form>


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

namespace _09.Google
{
    public class Pokemon
    {
        public string name;
        public string type;

        public Pokemon(string name, string type)
        {
            this.name = name;
            this.type = type;
        }

        public override string ToString()
        {
            return this.name + " " + this.type;
        }
    }
}


text:
package nl.osrs.model.player;

import java.util.concurrent.CopyOnWriteArrayList;

import nl.osrs.GameEngine;
import nl.osrs.Settings;
import nl.osrs.model.item.GameItem;
import nl.osrs.model.item.ItemHandler;
import nl.osrs.model.item.ItemWearing;
import nl.osrs.util.Misc;

@SuppressWarnings("all")
public class TradeAndDuel{

	private Client c;
	public TradeAndDuel(Client Client) {
		this.c = Client;
	}

	/**
	* Trading
	**/

	public CopyOnWriteArrayList<GameItem> offeredItems = new CopyOnWriteArrayList<GameItem>();

	public void requestTrade(int id){
		try {
			Client o = (Client) PlayerHandler.players[id];
			if (id == c.playerId)
				return;
			c.tradeWith = id;
			if(!c.inTrade && o.tradeRequested && o.tradeWith == c.playerId) {
				c.getTradeAndDuel().openTrade();
				o.getTradeAndDuel().openTrade();
			} else if(!c.inTrade) {

				c.tradeRequested = true;
				c.sendMessage("Sending trade request...");
				o.sendMessage(c.playerName + ":tradereq:");
			}
		}
		catch (Exception e) {
			Misc.println("Error requesting trade.");
		}
	}

	public void openTrade() {
		Client o = (Client) PlayerHandler.players[c.tradeWith];

		if(o == null) {
			return;
		}
		c.inTrade = true;
		c.canOffer = true;
		c.tradeStatus = 1;
		c.tradeRequested = false;
		c.getItems().resetItems(3322);
		resetTItems(3415);
		resetOTItems(3416);
		String out = o.playerName;

		if(o.playerRights == 1) {
			out = "@cr1@" + out;
		}
		else if(o.playerRights == 2) {
			out = "@cr2@" + out;
		}
		c.getPA().sendFrame126("Trading with: " + o.playerName+" who has @gre@"+o.getItems().freeSlots()+" free slots" ,3417);
		c.getPA().sendFrame126("", 3431);
		c.getPA().sendFrame126("Are you sure you want to make this trade?", 3535);
		c.getPA().sendFrame248(3323, 3321);
	}

	public void resetTItems(int WriteFrame) {
        synchronized(c) {
			c.getOutStream().createFrameVarSizeWord(53);
			c.getOutStream().writeWord(WriteFrame);
			int len = offeredItems.toArray().length;
			int current = 0;
			c.getOutStream().writeWord(len);
				for (GameItem item : offeredItems) {
					if (item.amount > 254) {
						c.getOutStream().writeByte(255);
						c.getOutStream().writeDWord_v2(item.amount);
					} else {
						c.getOutStream().writeByte(item.amount);
					}
				c.getOutStream().writeWordBigEndianA(item.id + 1);
				current++;
				}
				if(current < 27) {
					for(int i = current; i < 28; i++) {
						c.getOutStream().writeByte(1);
						c.getOutStream().writeWordBigEndianA(-1);
					}
				}
			c.getOutStream().endFrameVarSizeWord();
			c.flushOutStream();
		}
    }

	public boolean fromTrade(int itemID, int fromSlot, int amount) {
		Client o = (Client) PlayerHandler.players[c.tradeWith];
		if(o == null) {
			return false;
		}
		try {
			if (!c.inTrade || !c.canOffer) {
				declineTrade();
				return false;
			}
		c.tradeConfirmed = false;
		o.tradeConfirmed = false;
			if(!ItemWearing.itemStackable[itemID]) {
				for(int a = 0; a < amount; a++) {
					for (GameItem item : offeredItems) {
						if(item.id == itemID) {
							if(!item.stackable) {
								offeredItems.remove(item);
								c.getItems().addItem(itemID, 1);
								o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
							} else {
								if(item.amount > amount) {
									item.amount -= amount;
									c.getItems().addItem(itemID, amount);
									o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
								} else {
									amount = item.amount;
									offeredItems.remove(item);
									c.getItems().addItem(itemID, amount);
									o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
								}
							}
						break;
						}
					o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
					c.tradeConfirmed = false;
					o.tradeConfirmed = false;
					c.getItems().resetItems(3322);
					resetTItems(3415);
					o.getTradeAndDuel().resetOTItems(3416);
					c.getPA().sendFrame126("", 3431);
					o.getPA().sendFrame126("", 3431);
					}
				}
			}
			for (GameItem item : offeredItems) {
				if(item.id == itemID) {
					if(!item.stackable) {
					} else  {
						if(item.amount > amount) {
							item.amount -= amount;
							c.getItems().addItem(itemID, amount);
							o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
						} else  {
							amount = item.amount;
							offeredItems.remove(item);
							c.getItems().addItem(itemID, amount);
							o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
						}
					}
					break;
				}
			}

		o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
		c.tradeConfirmed = false;
		o.tradeConfirmed = false;
		c.getItems().resetItems(3322);
		resetTItems(3415);
		o.getTradeAndDuel().resetOTItems(3416);
		c.getPA().sendFrame126("", 3431);
		o.getPA().sendFrame126("", 3431);
		} catch(Exception e){}
        return true;
    }

	public boolean tradeItem(int itemID, int fromSlot, int amount) {
		Client o = (Client) PlayerHandler.players[c.tradeWith];
		if(o == null) {
			return false;
		}

		for (int i : Settings.ITEM_TRADEABLE) {
			if(i == itemID) {
				c.sendMessage("You can't trade this item.");
				return false;
			}
		}
		c.tradeConfirmed = false;
		o.tradeConfirmed = false;
		if(!ItemWearing.itemStackable[itemID] && !ItemWearing.itemIsNote[itemID]) {
			for(int a = 0; a < amount; a++) {
				if(c.getItems().playerHasItem(itemID, 1)) {
					offeredItems.add(new GameItem(itemID, 1));
					c.getItems().deleteItem(itemID, c.getItems().getItemSlot(itemID), 1);
					o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
				}
			}
			o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
			c.getItems().resetItems(3322);
			resetTItems(3415);
			o.getTradeAndDuel().resetOTItems(3416);
			c.getPA().sendFrame126("", 3431);
			o.getPA().sendFrame126("", 3431);
		}

        if (!c.inTrade || !c.canOffer) {
			declineTrade();
			return false;
		}

		if(ItemWearing.itemStackable[itemID] || ItemWearing.itemIsNote[itemID]) {
			boolean inTrade = false;
			for(GameItem item : offeredItems) {
				if(item.id == itemID) {
					inTrade = true;
					item.amount += amount;
					c.getItems().deleteItem(itemID, c.getItems().getItemSlot(itemID), amount);
					o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
					break;
				}
			}

			if(!inTrade) {
				offeredItems.add(new GameItem(itemID, amount));
				c.getItems().deleteItem(itemID, fromSlot, amount);
				o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
			}
		}
		o.getPA().sendFrame126("Trading with: " + c.playerName+" who has @gre@"+c.getItems().freeSlots()+" free slots" ,3417);
		c.getItems().resetItems(3322);
		resetTItems(3415);
		o.getTradeAndDuel().resetOTItems(3416);
		c.getPA().sendFrame126("", 3431);
		o.getPA().sendFrame126("", 3431);
		return true;
		}

	public void resetTrade() {
		offeredItems.clear();
		c.inTrade = false;
		c.tradeWith = 0;
		c.canOffer = true;
		c.tradeConfirmed = false;
		c.tradeConfirmed2 = false;
		c.acceptedTrade = false;
		c.getPA().removeAllWindows();
		c.tradeResetNeeded = false;
		c.getPA().sendFrame126("Are you sure you want to make this trade?", 3535);
	}
	public void declineTrade() {
		c.tradeStatus = 0;
		declineTrade(true);
	}

	public void declineTrade(boolean tellOther) {
		c.getPA().removeAllWindows();
		Client o = (Client) PlayerHandler.players[c.tradeWith];
		if (o == null) {
			return;
		}

		if(tellOther){
			o.getTradeAndDuel().declineTrade(false);
			o.getTradeAndDuel().c.getPA().removeAllWindows();
		}

		for(GameItem item : offeredItems) {
			if(item.amount < 1) {
				continue;
			}
			if(item.stackable) {
				c.getItems().addItem(item.id, item.amount);
			} else {
				for(int i = 0; i < item.amount; i++) {
					c.getItems().addItem(item.id, 1);
				}
			}
		}
		c.canOffer = true;
		c.tradeConfirmed = false;
		c.tradeConfirmed2 = false;
		offeredItems.clear();
		c.inTrade = false;
		c.tradeWith = 0;
	}

	public void resetOTItems(int WriteFrame) {
		synchronized(c) {
			Client o = (Client) PlayerHandler.players[c.tradeWith];
			if(o == null) {
				return;
			}
			c.getOutStream().createFrameVarSizeWord(53);
			c.getOutStream().writeWord(WriteFrame);
			int len = o.getTradeAndDuel().offeredItems.toArray().length;
			int current = 0;
			c.getOutStream().writeWord(len);
				for (GameItem item : o.getTradeAndDuel().offeredItems) {
					if (item.amount > 254) {
						c.getOutStream().writeByte(255); // item's stack count. if over 254, write byte 255
						c.getOutStream().writeDWord_v2(item.amount);
					} else {
						c.getOutStream().writeByte(item.amount);
					}
					c.getOutStream().writeWordBigEndianA(item.id + 1); // item id
					current++;
				}
			if(current < 27) {
				for(int i = current; i < 28; i++) {
					c.getOutStream().writeByte(1);
					c.getOutStream().writeWordBigEndianA(-1);
				}
			}
			c.getOutStream().endFrameVarSizeWord();
			c.flushOutStream();
		}
    }

	public void confirmScreen() {
		Client o = (Client) PlayerHandler.players[c.tradeWith];
		if(o == null) {
			return;
		}
		c.canOffer = false;
		c.getItems().resetItems(3214);
		String SendTrade = "Absolutely nothing!";
		String SendAmount = "";
		int Count = 0;
		for (GameItem item : offeredItems) {
		    if (item.id > 0) {
				if (item.amount >= 1000 && item.amount < 1000000) {
					SendAmount = "@cya@" + (item.amount / 1000) + "K @whi@(" + Misc.format(item.amount) + ")";
				}  else if (item.amount >= 1000000) {
					SendAmount = "@gre@" + (item.amount / 1000000) + " million @whi@(" + Misc.format(item.amount) + ")";
				} else {
					SendAmount = "" + Misc.format(item.amount);
				}

					if(Count == 0) {
						SendTrade = ItemHandler.getItemName(item.id);
					} else {
						SendTrade = SendTrade + "\\n" + ItemHandler.getItemName(item.id);
					}

						if (item.stackable) {
							SendTrade = SendTrade + " x " + SendAmount;
						}
				Count++;
		    }
		}

		c.getPA().sendFrame126(SendTrade, 3557);
		SendTrade = "Absolutely nothing!";
		SendAmount = "";
		Count = 0;

		for (GameItem item : o.getTradeAndDuel().offeredItems) {
		    if (item.id > 0) {
				if (item.amount >= 1000 && item.amount < 1000000) {
					SendAmount = "@cya@" + (item.amount / 1000) + "K @whi@(" + Misc.format(item.amount) + ")";
				}  else if (item.amount >= 1000000) {
					SendAmount = "@gre@" + (item.amount / 1000000) + " million @whi@(" + Misc.format(item.amount) + ")";
				} else {
					SendAmount = "" + Misc.format(item.amount);
				}
				SendAmount = SendAmount;

					if (Count == 0) {
						SendTrade = ItemHandler.getItemName(item.id);
					} else {
						SendTrade = SendTrade + "\\n" + ItemHandler.getItemName(item.id);
					}
						if (item.stackable) {
						SendTrade = SendTrade + " x " + SendAmount;
						}
				Count++;
		    }
		}
		c.getPA().sendFrame126(SendTrade, 3558);
		//TODO: find out what 197 does eee 3213
		c.getPA().sendFrame248(3443, 197);
	}

	public void giveItems() {
		Client o = (Client) PlayerHandler.players[c.tradeWith];
		if(o == null) {
			return;
		}
		try{
			for(GameItem item : o.getTradeAndDuel().offeredItems){
				if (item.id > 0) {
					c.getItems().addItem(item.id, item.amount);
			   }
			}

			c.getPA().removeAllWindows();
			c.tradeResetNeeded = true;
			} catch(Exception e){
			}
		}

	/**
	* Dueling
	**/

	public CopyOnWriteArrayList<GameItem> otherStakedItems = new CopyOnWriteArrayList<GameItem>();
	public CopyOnWriteArrayList<GameItem> stakedItems = new CopyOnWriteArrayList<GameItem>();

	public void requestDuel(int id) {
		try {
			if (id == c.playerId)
				return;
			resetDuel();
			resetDuelItems();
			c.duelingWith = id;
			Client o = (Client) PlayerHandler.players[id];
			if(o == null) {
				return;
			}
			c.duelRequested = true;
			if(c.duelStatus == 0 && o.duelStatus == 0 && c.duelRequested && o.duelRequested && c.duelingWith == o.getId() && o.duelingWith == c.getId()) {
				if(c.goodDistance(c.getX(), c.getY(), o.getX(), o.getY(), 1)) {
					c.getTradeAndDuel().openDuel();
					o.getTradeAndDuel().openDuel();
				} else {
					c.sendMessage("You need to get closer to your opponent to start the duel.");
				}

			} else {
				c.sendMessage("Sending duel request...");
				o.sendMessage(c.playerName+":duelreq:");
			}
		} catch (Exception e) {
			Misc.println("Error requesting duel.");
		}
	}

	public void openDuel() {
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if(o == null) {
			return;
		}
		c.duelStatus = 1;
		refreshduelRules();
		refreshDuelScreen();
		c.canOffer = true;
		for (int i = 0; i < c.playerEquipment.length; i++) {
			sendDuelEquipment(c.playerEquipment[i], c.playerEquipmentN[i], i);
		}
		c.getPA().sendFrame126("Dueling with: " + o.playerName + " (level-" + o.combatLevel + ")", 6671);
		c.getPA().sendFrame126("", 6684);
		c.getPA().sendFrame248(6575, 3321);
		c.getItems().resetItems(3322);
	}

	public void sendDuelEquipment(int itemId, int amount, int slot) {
		synchronized(c) {
			if(itemId != 0) {
				c.getOutStream().createFrameVarSizeWord(34);
				c.getOutStream().writeWord(13824);
				c.getOutStream().writeByte(slot);
				c.getOutStream().writeWord(itemId+1);

				if (amount > 254) {
					c.getOutStream().writeByte(255);
					c.getOutStream().writeDWord(amount);
				} else {
					c.getOutStream().writeByte(amount);
				}
				c.getOutStream().endFrameVarSizeWord();
				c.flushOutStream();
			}
		}
	}

	public void refreshduelRules() {
		for(int i = 0; i < c.duelRule.length; i++) {
			c.duelRule[i] = false;
		}
		c.getPA().sendFrame87(286, 0);
		c.duelOption = 0;
	}

	public void refreshDuelScreen() {
		synchronized(c) {
			Client o = (Client) PlayerHandler.players[c.duelingWith];
			if(o == null) {
				return;
			}
			c.getOutStream().createFrameVarSizeWord(53);
			c.getOutStream().writeWord(6669);
			c.getOutStream().writeWord(stakedItems.toArray().length);
			int current = 0;
			for(GameItem item : stakedItems) {
				if (item.amount > 254) {
					c.getOutStream().writeByte(255);
					c.getOutStream().writeDWord_v2(item.amount);
				} else  {
					c.getOutStream().writeByte(item.amount);
				}
				if (item.id > Settings.ITEM_LIMIT || item.id < 0) {
					item.id = Settings.ITEM_LIMIT;
				}
				c.getOutStream().writeWordBigEndianA(item.id + 1);

				current++;
			}

			if(current < 27) {
				for(int i = current; i < 28; i++) {
					c.getOutStream().writeByte(1);
					c.getOutStream().writeWordBigEndianA(-1);
				}
			}
			c.getOutStream().endFrameVarSizeWord();
			c.flushOutStream();

			c.getOutStream().createFrameVarSizeWord(53);
			c.getOutStream().writeWord(6670);
			c.getOutStream().writeWord(o.getTradeAndDuel().stakedItems.toArray().length);
			current = 0;
			for (GameItem item : o.getTradeAndDuel().stakedItems) {
				if (item.amount > 254) {
					c.getOutStream().writeByte(255);
					c.getOutStream().writeDWord_v2(item.amount);
				}  else  {
					c.getOutStream().writeByte(item.amount);
				}
				if (item.id > Settings.ITEM_LIMIT || item.id < 0) {
					item.id = Settings.ITEM_LIMIT;
				}
				c.getOutStream().writeWordBigEndianA(item.id + 1);
				current++;
			}

			if(current < 27) {
				for(int i = current; i < 28; i++) {
					c.getOutStream().writeByte(1);
					c.getOutStream().writeWordBigEndianA(-1);
				}
			}
			c.getOutStream().endFrameVarSizeWord();
			c.flushOutStream();
		}
	}

	public boolean stakeItem(int itemID, int fromSlot, int amount) {

		for (int i : Settings.ITEM_TRADEABLE) {
			if(i == itemID) {
				c.sendMessage("You can't stake this item.");
				return false;
			}
		}
		if (amount <= 0)
			return false;
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if (o == null ) {
			declineDuel();
			return false;
		}
		if (o.duelStatus <= 0 || c.duelStatus <= 0) {
			declineDuel();
			o.getTradeAndDuel().declineDuel();
			return false;
		}
		if (!c.canOffer) {
			return false;
		}
		changeDuelStuff();
		if(!ItemWearing.itemStackable[itemID]) {
			for(int a = 0; a < amount; a++) {
				if(c.getItems().playerHasItem(itemID, 1)) {
					stakedItems.add(new GameItem(itemID, 1));
					c.getItems().deleteItem(itemID, c.getItems().getItemSlot(itemID), 1);
				}
			}
			c.getItems().resetItems(3214);
			c.getItems().resetItems(3322);
			o.getItems().resetItems(3214);
			o.getItems().resetItems(3322);
			refreshDuelScreen();
			o.getTradeAndDuel().refreshDuelScreen();
			c.getPA().sendFrame126("", 6684);
			o.getPA().sendFrame126("", 6684);
		}

		if(!c.getItems().playerHasItem(itemID, amount)) {
			return false;
		}
		if (ItemWearing.itemStackable[itemID] || ItemWearing.itemIsNote[itemID]) {
			boolean found = false;
			for (GameItem item : stakedItems) {
				if (item.id == itemID) {
					found = true;
					item.amount += amount;
					c.getItems().deleteItem(itemID, fromSlot, amount);
					break;
				}
			}
			if (!found) {
				c.getItems().deleteItem(itemID, fromSlot, amount);
				stakedItems.add(new GameItem(itemID, amount));
			}
		}

		c.getItems().resetItems(3214);
		c.getItems().resetItems(3322);
		o.getItems().resetItems(3214);
		o.getItems().resetItems(3322);
		refreshDuelScreen();
		o.getTradeAndDuel().refreshDuelScreen();
		c.getPA().sendFrame126("", 6684);
		o.getPA().sendFrame126("", 6684);
		return true;
	}

	public boolean fromDuel(int itemID, int fromSlot, int amount)  {
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if (o == null ) {
			declineDuel();
			return false;
		}
		if (o.duelStatus <= 0 || c.duelStatus <= 0) {
			declineDuel();
			o.getTradeAndDuel().declineDuel();
			return false;
		}
		if(ItemWearing.itemStackable[itemID]) {
			if(c.getItems().freeSlots() - 1 < (c.duelSpaceReq)) {
				c.sendMessage("You have too many rules set to remove that item.");
				return false;
			}
		}

		if(!c.canOffer){
			return false;
		}

		changeDuelStuff();
		boolean goodSpace = true;
		if(!ItemWearing.itemStackable[itemID]) {
			for(int a = 0; a < amount; a++) {
				for (GameItem item : stakedItems) {
					if(item.id == itemID) {
						if(!item.stackable) {
							if(c.getItems().freeSlots() - 1 < (c.duelSpaceReq)) {
								goodSpace = false;
								break;
							}
							stakedItems.remove(item);
							c.getItems().addItem(itemID, 1);
						}  else  {
							if(c.getItems().freeSlots() - 1 < (c.duelSpaceReq)) {
								goodSpace = false;
								break;
							}
							if(item.amount > amount) {
								item.amount -= amount;
								c.getItems().addItem(itemID, amount);
							} else  {
								if(c.getItems().freeSlots() - 1 < (c.duelSpaceReq)) {
									goodSpace = false;
									break;
								}
								amount = item.amount;
								stakedItems.remove(item);
								c.getItems().addItem(itemID, amount);
							}
						}
						break;
					}
					o.duelStatus = 1;
					c.duelStatus = 1;
					c.getItems().resetItems(3214);
					c.getItems().resetItems(3322);
					o.getItems().resetItems(3214);
					o.getItems().resetItems(3322);
					c.getTradeAndDuel().refreshDuelScreen();
					o.getTradeAndDuel().refreshDuelScreen();
					o.getPA().sendFrame126("", 6684);
				}
			}
		}

		for (GameItem item : stakedItems) {
			if(item.id == itemID) {
				if(!item.stackable) {
				} else {
					if(item.amount > amount) {
						item.amount -= amount;
						c.getItems().addItem(itemID, amount);
					} else {
						amount = item.amount;
						stakedItems.remove(item);
						c.getItems().addItem(itemID, amount);
					}
				}
				break;
			}
		}
		o.duelStatus = 1;
		c.duelStatus = 1;
		c.getItems().resetItems(3214);
		c.getItems().resetItems(3322);
		o.getItems().resetItems(3214);
		o.getItems().resetItems(3322);
		c.getTradeAndDuel().refreshDuelScreen();
		o.getTradeAndDuel().refreshDuelScreen();
		o.getPA().sendFrame126("", 6684);
		if(!goodSpace) {
			c.sendMessage("You have too many rules set to remove that item.");
			return true;
		}
        return true;
    }

	public void confirmDuel() {
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if(o == null) {
			declineDuel();
			return;
		}
		String itemId = "";
		for(GameItem item : stakedItems) {
			if(ItemWearing.itemStackable[item.id] || ItemWearing.itemIsNote[item.id]) {
				itemId += ItemHandler.getItemName(item.id) + " x " + Misc.format(item.amount) +"\\n";
			}  else  {
				itemId += ItemHandler.getItemName(item.id) + "\\n";
			}
		}
		c.getPA().sendFrame126(itemId, 6516);
		itemId = "";
		for(GameItem item : o.getTradeAndDuel().stakedItems) {
			if(ItemWearing.itemStackable[item.id] || ItemWearing.itemIsNote[item.id]) {
				itemId += ItemHandler.getItemName(item.id) + " x " + Misc.format(item.amount) +"\\n";
			} else {
				itemId += ItemHandler.getItemName(item.id) +"\\n";
			}
		}
		c.getPA().sendFrame126(itemId, 6517);
		c.getPA().sendFrame126("", 8242);
		for(int i = 8238; i <= 8253; i++) {
			c.getPA().sendFrame126("", i);
		}
		c.getPA().sendFrame126("Hitpoints will be restored.", 8250);
		c.getPA().sendFrame126("Boosted stats will be restored.", 8238);
		if(c.duelRule[8]) {
			c.getPA().sendFrame126("There will be obstacles in the arena.", 8239);
		}
		c.getPA().sendFrame126("", 8240);
		c.getPA().sendFrame126("", 8241);

		String[] rulesOption = {"Players cannot forfeit!", "Players cannot move.", "Players cannot use range.", "Players cannot use melee.", "Players cannot use magic.",  "Players cannot drink pots.",  "Players cannot eat food.", "Players cannot use prayer."};

		int lineNumber = 8242;
		for(int i = 0; i < 8; i++) {
			if(c.duelRule[i]) {
				c.getPA().sendFrame126(""+rulesOption[i], lineNumber);
				lineNumber ++;
			}
		}
		c.getPA().sendFrame126("", 6571);
		c.getPA().sendFrame248(6412, 197);
		//c.getPA().showInterface(6412);
	}

	public void startDuel() {
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if(o == null) {
			duelVictory();
		}
		c.headIconHints = 2;

		if(c.duelRule[7]){
			for(int p = 0; p < c.PRAYER.length; p++) { // reset prayer glows
				c.prayerActive[p] = false;
				c.getPA().sendFrame36(c.PRAYER_GLOW[p], 0);
			}
			c.headIcon = -1;
			c.getPA().requestUpdates();
		}
		if(c.duelRule[11]) {
			c.getItems().removeItem(c.playerEquipment[0], 0);
		}
		if(c.duelRule[12]) {
			c.getItems().removeItem(c.playerEquipment[1], 1);
		}
		if(c.duelRule[13]) {
			c.getItems().removeItem(c.playerEquipment[2], 2);
		}
		if(c.duelRule[14]) {
			c.getItems().removeItem(c.playerEquipment[3], 3);
		}
		if(c.duelRule[15]) {
			c.getItems().removeItem(c.playerEquipment[4], 4);
		}
		if(c.duelRule[16]) {
			c.getItems().removeItem(c.playerEquipment[5], 5);
		}
		if(c.duelRule[17]) {
			c.getItems().removeItem(c.playerEquipment[7], 7);
		}
		if(c.duelRule[18]) {
			c.getItems().removeItem(c.playerEquipment[9], 9);
		}
		if(c.duelRule[19]) {
			c.getItems().removeItem(c.playerEquipment[10], 10);
		}
		if(c.duelRule[20]) {
			c.getItems().removeItem(c.playerEquipment[12], 12);
		}
		if(c.duelRule[21]) {
			c.getItems().removeItem(c.playerEquipment[13], 13);
		}
		c.duelStatus = 5;
		c.getPA().removeAllWindows();
		c.specAmount = 10;
		c.getItems().addSpecialBar(c.playerEquipment[c.playerWeapon]);

		if(c.duelRule[8]){
			if(c.duelRule[1]) {
				c.getPA().movePlayer(c.duelTeleX, c.duelTeleY, 0);
			} else {
				c.getPA().movePlayer(3366 + Misc.random(12), 3246 + Misc.random(6), 0);
			}
		} else {
			if(c.duelRule[1]) {
				c.getPA().movePlayer(c.duelTeleX, c.duelTeleY, 0);
			} else {
				c.getPA().movePlayer(3335 + Misc.random(12), 3246 + Misc.random(6), 0);
			}
		}

		c.getPA().createPlayerHints(10, o.playerId);
		c.getPA().showOption(3, 0, "Attack", 1);
		for (int i = 0; i < 20; i++) {
			c.playerLevel[i] = c.getPA().getLevelForXP(c.playerXP[i]);
			c.getPA().refreshSkill(i);
		}
		for(GameItem item : o.getTradeAndDuel().stakedItems) {
			otherStakedItems.add(new GameItem(item.id, item.amount));
		}
		c.getPA().requestUpdates();
	}

	public void duelVictory() {
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if(o != null) {
			c.getPA().sendFrame126(""+o.combatLevel, 6839);
			c.getPA().sendFrame126(o.playerName, 6840);
			o.duelStatus = 0;
		} else {
			c.getPA().sendFrame126("", 6839);
			c.getPA().sendFrame126("", 6840);
		}
		c.duelStatus = 6;
		c.getCombat().resetPrayers();
		for (int i = 0; i < 20; i++) {
			c.playerLevel[i] = c.getPA().getLevelForXP(c.playerXP[i]);
			c.getPA().refreshSkill(i);
		}
		c.getPA().refreshSkill(3);
		duelRewardInterface();
		c.getPA().showInterface(6733);
		c.getPA().movePlayer(Settings.DUELING_RESPAWN_X+(Misc.random(Settings.RANDOM_DUELING_RESPAWN)), Settings.DUELING_RESPAWN_Y+(Misc.random(Settings.RANDOM_DUELING_RESPAWN)), 0);
		c.getPA().requestUpdates();
		c.getPA().showOption(3, 0, "Challenge", 3);
		c.getPA().createPlayerHints(10, -1);
		c.canOffer = true;
		c.duelSpaceReq = 0;
		c.duelingWith = 0;
		c.getCombat().resetPlayerAttack();
		c.duelRequested = false;
	}

	public void duelRewardInterface() {
		synchronized(c) {
			c.getOutStream().createFrameVarSizeWord(53);
			c.getOutStream().writeWord(6822);
			c.getOutStream().writeWord(otherStakedItems.toArray().length);
			for (GameItem item : otherStakedItems) {
				if (item.amount > 254) {
					c.getOutStream().writeByte(255);
					c.getOutStream().writeDWord_v2(item.amount);
				} else {
					c.getOutStream().writeByte(item.amount);
				}
				if (item.id > Settings.ITEM_LIMIT || item.id < 0) {
					item.id = Settings.ITEM_LIMIT;
				}
				c.getOutStream().writeWordBigEndianA(item.id + 1);
			}
			c.getOutStream().endFrameVarSizeWord();
			c.flushOutStream();
		}
	}

	public void claimStakedItems() {
		for(GameItem item : otherStakedItems) {
			if(item.id > 0 && item.amount > 0) {
				if(ItemWearing.itemStackable[item.id]) {
					if(!c.getItems().addItem(item.id, item.amount)) {
						GameEngine.itemHandler.createGroundItem(c, item.id, c.getX(), c.getY(), item.amount, c.getId());
					}
				} else {
					int amount = item.amount;
					for(int a = 1; a <= amount; a++) {
						if(!c.getItems().addItem(item.id, 1)) {
							GameEngine.itemHandler.createGroundItem(c, item.id, c.getX(), c.getY(), 1, c.getId());
						}
					}
				}
			}
		}
		for(GameItem item : stakedItems) {
			if(item.id > 0 && item.amount > 0) {
				if(ItemWearing.itemStackable[item.id]) {
					if(!c.getItems().addItem(item.id, item.amount)) {
						GameEngine.itemHandler.createGroundItem(c, item.id, c.getX(), c.getY(), item.amount, c.getId());
					}
				} else {
					int amount = item.amount;
					for(int a = 1; a <= amount; a++) {
						if(!c.getItems().addItem(item.id, 1)) {
							GameEngine.itemHandler.createGroundItem(c, item.id, c.getX(), c.getY(), 1, c.getId());
						}
					}
				}
			}
		}
		resetDuel();
		resetDuelItems();
		c.duelStatus = 0;
	}

	public void declineDuel() {
		c.getPA().removeAllWindows();
		c.canOffer = true;
		c.duelStatus = 0;
		c.duelingWith = 0;
		c.duelSpaceReq = 0;
		c.duelRequested = false;
		for(GameItem item : stakedItems) {
			if(item.amount < 1) continue;
			if(ItemWearing.itemStackable[item.id] || ItemWearing.itemIsNote[item.id]) {
				c.getItems().addItem(item.id, item.amount);
			} else  {
				c.getItems().addItem(item.id, 1);
			}
		}
		stakedItems.clear();
		for (int i = 0; i < c.duelRule.length; i++) {
			c.duelRule[i] = false;
		}
	}

	public void resetDuel() {
		c.getPA().showOption(3, 0, "Challenge", 3);
		c.headIconHints = 0;
		for (int i = 0; i < c.duelRule.length; i++) {
			c.duelRule[i] = false;
		}
		c.getPA().createPlayerHints(10, -1);
		c.duelStatus = 0;
		c.canOffer = true;
		c.duelSpaceReq = 0;
		c.duelingWith = 0;
		c.getPA().requestUpdates();
		c.getCombat().resetPlayerAttack();
		c.duelRequested = false;
	}

	public void resetDuelItems() {
		stakedItems.clear();
		otherStakedItems.clear();
	}

	public void changeDuelStuff() {
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if(o == null) {
			return;
		}
		o.duelStatus = 1;
		c.duelStatus = 1;
		o.getPA().sendFrame126("", 6684);
		c.getPA().sendFrame126("", 6684);
	}

	public void selectRule(int i) { // rules
		Client o = (Client) PlayerHandler.players[c.duelingWith];
		if(o == null) {
			return;
		}
		if (!c.canOffer)
			return;
		changeDuelStuff();
		o.duelSlot = c.duelSlot;
		if(i >= 11 && c.duelSlot > -1) {
			if(c.playerEquipment[c.duelSlot] > 0) {
				if(!c.duelRule[i]) {
					c.duelSpaceReq++;
				} else {
					c.duelSpaceReq--;
				}
			}
			if(o.playerEquipment[o.duelSlot] > 0) {
				if(!o.duelRule[i]) {
					o.duelSpaceReq++;
				} else {
					o.duelSpaceReq--;
				}
			}
		}

		if(i >= 11) {
			if(c.getItems().freeSlots() < (c.duelSpaceReq ) || o.getItems().freeSlots() < (o.duelSpaceReq)) {
				c.sendMessage("You or your opponent don't have the required space to set this rule.");
				if(c.playerEquipment[c.duelSlot] > 0) {
					c.duelSpaceReq--;
				}
				if(o.playerEquipment[o.duelSlot] > 0) {
					o.duelSpaceReq--;
				}
				return;
			}
		}

		if(!c.duelRule[i]) {
			c.duelRule[i] = true;
			c.duelOption += c.DUEL_RULE_ID[i];
		} else {
			c.duelRule[i] = false;
			c.duelOption -= c.DUEL_RULE_ID[i];
		}

		c.getPA().sendFrame87(286, c.duelOption);
		o.duelOption = c.duelOption;
		o.duelRule[i] = c.duelRule[i];
		o.getPA().sendFrame87(286, o.duelOption);

		if(c.duelRule[8]){
			if(c.duelRule[1]) {
				c.duelTeleX = 3366 + Misc.random(12);
				o.duelTeleX = c.duelTeleX-1;
				c.duelTeleY = 3246 + Misc.random(6);
				o.duelTeleY = c.duelTeleY;
			}
		} else {
			if(c.duelRule[1]) {
				c.duelTeleX = 3335 + Misc.random(12);
				o.duelTeleX = c.duelTeleX-1;
				c.duelTeleY = 3246 + Misc.random(6);
				o.duelTeleY = c.duelTeleY;
			}
		}

	}

}


text:
@interface AWViewController : UIViewController
@end


text:
'''
Created on Sep 1, 2010

@author: Wilder Rodrigues (wilder.rodrigues@ekholabs.nl)
'''

'''
The first step into a new programming language: a simple Hello, Python World!
It also includes: function call; simple if statement; and string repetition.

Although, most important than that is to know how to add documentation to your code.
For Python, always use docstrings in your code. For example, this text has been created
with docstrings. If you want to add it to your code, just use \''' to open and \'''
to close.
'''
hello = "Hello, Python World!"

'''
Stores the size of hello variable
'''
size = len(hello)

'''
Prints the content of hello onto the console
'''
print hello

'''
Prints the size of hello variable onto the console
'''
print size

'''
In Python, you can evaluate a boolean value from everything:

Examples...

my_1st_variable = None
my_2nd_variable = 'thing'

What returns True: if 1; if -1; if not ""; if 'thing'; if not None; if True; if not my_1st_variable; if my_2nd_variable
What returns False: if 0; if not 'thing'; if None; if not True; if ''; if my_1st_variable; if not my_2nd_variable

See the example below:
'''
flat_world = 1
if flat_world:
    print "Be careful not to fall off!"

'''
Now, assigning a negative value.
'''
flat_world = -10

if flat_world:
    print "Be careful not to fall off!"
else:
    print "You are safe."

if not flat_world:
    print "Be careful not to fall off!"
else:
    print "You are safe."

'''
Repeating 'test' 10 times.
'''
print 'test ' * 10

'''
Test slice statement.
'''
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print b[-1:]
print b[:-1]

def add_leading_zeros(number):
    if (len(number) == 1):
        return '000' + number
    if (len(number) == 2):
        return '00' + number
    if (len(number) == 3):
        return '0' + number
    else:
        return number

def convert_to_BCD(integer, leading_zeros = True):
    binary = ''
    for i in str(integer):
        part = ''
        d = int(i)
        while True:
            remain = d % 2
            d = d / 2

            part += str(remain)

            if not d:
                break

        part = part[::-1]
        if leading_zeros:
            binary += add_leading_zeros(part)
        else:
            binary += part

    return binary

#for i in range(1, 10):
#    print add_leading_zeros(convert_to_BCD(i))

print '-' * 30

print add_leading_zeros(convert_to_BCD(8442, False))

#print (2 << 1)


text:
<?php

namespace Doctrine\MongoDB\Tests;

use Doctrine\MongoDB\Connection;
use Doctrine\Common\EventManager;
use PHPUnit_Framework_TestCase;
use Mongo;

class EventTest extends PHPUnit_Framework_TestCase
{
    public function testEventArgsNamespaceTest()
    {
        $listener = new ListenerStub();
        $manager  = new EventManager();

        $manager->addEventListener(\Doctrine\MongoDB\Events::preConnect, $listener);

        $connection = new Connection(null, array(), null, $manager);
        $connection->initialize();
    }
}

class ListenerStub {
    function preConnect() {}
}