text:
/*************************************************************************
**                                                                      **
** Description                                                          **
**                                                                      **
** This class specifies the structure and properties of a 1-dimensional **
** block of simulated (or any other) data.  The data block is a row     **
** vector in RAM memory and has	an associated parameter set.  Functions **
** are provided for basic algebraic manipulations, specification of	**
** parameters, and general I/O.  Many external programs deal with data	**
** sets coupled to a block of parameters and this class allows users    **
** to more readily support I/O to these programs.  One example would be **
** the Felix module which provides functions for input/output of GAMMA  **
** data to/from the program Felix from Molecular Simulations (MSI),     **
** nee Biosym, nee Hare Research, Inc.                                  **
**                                                                      **
*************************************************************************/

#ifndef   block_1D_cc_			// Is file already included?
#  define block_1D_cc_ 1		// If no, then remember it
#  if defined(GAMPRAGMA)		// Using the GNU compiler?
#    pragma implementation		// This is the implementation
#  endif

#include <Deprecated/block_1D.h>	// Include class interface
#include <Basics/Gutils.h>		// Include GAMMA errors
#include <assert.h>
#include <iostream>
using namespace std;

// ----------------------------------------------------------------------------
// --------------------------- PRIVATE FUNCTIONS ------------------------------
// ----------------------------------------------------------------------------

// ____________________________________________________________________________
// i                      CLASS BLOCK_1D ERROR HANDLING
// ____________________________________________________________________________

void block_1D::Blk1DError(int eidx, int noret) const

	// Input		BLK 	: A 1D data block (this)
        //                      eidx    : Error index
        //                      noret   : Flag for linefeed (0=linefeed)
        // Output               none    : Error message output

/* The following error messages use the defaults set in the Gutils package

                Case                          Error Message

                (0)                     Program Aborting.....
                (9)                     Problems During Construction
                default                 Unknown Error                        */

  {
  std::string hdr("Block 1D");
  switch (eidx)
    {
    case 1:  GAMMAerror(hdr,"Mixing Blocks of Differing Dimensions",noret);	break;//(1)
    case 2:  GAMMAerror(hdr,"Problems With Block-Block Operation",noret);	break;//(2)
    case 5:  GAMMAerror(hdr,"Block Data Point NOT Accessible",noret);		break;//(5)
    case 6:  GAMMAerror(hdr,"Accessed Data Point EXCEEDS Block Size",noret);	break;//(6)
    case 50: GAMMAerror(hdr,"Error in Block-Block Addition",noret);		break;//(50)
    case 51: GAMMAerror(hdr,"Error in Block-Block Subtraction",noret);		break;//(51)
    default: GAMMAerror(hdr, eidx, noret); break;// Usually Unknown Error  (-1)
    }
  }

void block_1D::Blk1DError(int eidx, int i, int j, int noret) const

	// Input		BLK 	: A 1D data block (this)
	//                      eidx    : Error index
        //                      i,j     : Block indices
        //                      noret   : Flag for linefeed (0=linefeed)
        // Output               none    : Error message output

  {
  std::cout << "\nClass Block_1D: ";
  switch (eidx)
    {
    case 100:							// (100)
      std::cout << "Size = " << i << " and Current Point Accessed = " << j;
      break;
    case 101:							// (101)
      std::cout << "Block Data Size = " << i << " mixed with Block Data Size " << j;
      break;
    default:
      std::cout << "Unkown Error, number " << eidx;
    }
  if(!noret) std::cout << "\n";
  }

volatile void block_1D::Blk1DFatal(int eidx)

	// Input		BLK 	: A 1D data block (this)
        //                      eidx    : Error index
        // Output               none    : Error message output
        //                                Program execution stopped

  {
  Blk1DError(eidx,1);
  if(eidx) Blk1DError(0);
  GAMMAfatal();					// Clean exit from program
  }

// ----------------------------------------------------------------------------
// ---------------------------- PUBLIC FUNCTIONS ------------------------------
// ----------------------------------------------------------------------------

// ____________________________________________________________________________
// A                 CLASS BLOCK_1D CONSTRUCTION, DESTRUCTION
// ____________________________________________________________________________

block_1D::block_1D(int dim) : row_vector(dim,0), ParameterSet()

	// Input			dim  : integer
	// Output			none : creates an empty block_1D
	//				       of dimension specified by dim

  { set_defaults(1); }			// Set Block Parameter Defaults

// ____________________________________________________________________________
// B                  CLASS BLOCK_1D FUNCTIONS, BLOCK WITH BLOCK
// ____________________________________________________________________________

block_1D operator + (const block_1D &BLK1, const block_1D &BLK2)

	// Input		BLK1, BLK2 : two block_1Ds
	// Return		BLK        : block_1D which is the addition
        //	                             of the two input block_1Ds,
	//			             BLK =  BLK1 + BLK2

  {
  block_1D BLK(BLK1);				// Construct form BLK1
  BLK.block_1D::operator+= (BLK2);		// Add in BLK2
  return BLK;
  }

void block_1D::operator += (const block_1D &BLK2)

	// Input		BLK1 : a block_1D
	// Return		BLK  : block_1D which is the input
        //	                       input block_1D BLK1 added to itself
	//			       BLK = BLK + BLK1

  {
//                 First Attempt To Add the Data Values

  if(BLK2.elements())				// Add BLK2 data if exists
    {
    if(!elements()) row_vector::operator=(BLK2);// Data is BLK2 if BLK1 empty
    else					// If BLK2 & BLK1 have data
      {						// then
      if(Blk1DCheck(BLK2))		//   Insure dimensions match
        row_vector::operator+= (BLK2);		//   Add data vectors
      else
        {
        Blk1DError(2);			// error in BLK with BLK operation
        Blk1DFatal(50);			// fatality during BLK + BLK
        }
      }
    }
// sosi - kludge for gamma 4.0
//  ParameterSet::operator += (BLK2);			// add BLK2 parameters
  return;
  }

block_1D operator - (const block_1D &BLK1, const block_1D &BLK2)

	// Input		BLK1 : a data block_1D
	//			BLK2 : a data block_1D
	// Return		BLK  : block_1D which is the subtraction
        //	                       of the two input block_1Ds,
	//			       BLK = BLK1 - BLK2

  {
  block_1D BLK(BLK1);
  BLK.block_1D::operator-= (BLK2);
  return BLK;
  }

block_1D operator - (const block_1D &BLK1)

	// Input		BLK1  : a block_1D
	// Return		BLK   : block_1D which is the negative
  //	                of the input block_1D, BLK = - BLK1

  {
  block_1D BLK;

#ifdef _MSC_VER
	// *DCT* This call leads to infinite recursion and will not compile on windows.
	cout << "\nFATAL: Call to this deprecated funtion leads to infinite recursion.\n";
	assert(0);
#else
	BLK.row_vector::operator= (-BLK1);	// vector negation
  BLK.ParameterSet::operator= (BLK1);		// copy parameter set BLK1 into BLK
#endif

  return BLK;
  }

void block_1D::operator -= (const block_1D &BLK2)

	// Input		BLK1 : a block_1D
	// 			BLK2 : a block_1D
	// Return		none : block_1D BLK1 is modified to have
        //	                       input block_1D BLK2 added to itself
	//			       BLK1 = BLK1 - BLK2

  {
  if(BLK2.elements())				// if BLK1 has data
    {
    if(!elements())				// if BLK1 has no data
      row_vector::operator= (-BLK2);		// vector negation
    else
      {
      if(Blk1DCheck(BLK2))		// insure dimensions match
        row_vector::operator-= (BLK2);		// subtract vectors
      else
        {
        Blk1DError(2);			// error in BLK with BLK operation
        Blk1DFatal(51);			// fatality during BLK - BLK
        }
      }
    }
  }

void block_1D::operator = (const block_1D &BLK)

	// Input		this,BLK  : two block_1D
	// Return		copies BLK to this, and destroys the old
        //                      contents of this block_1D

  {
  row_vector::operator= (BLK);	// Copy BLK vector
  ParameterSet::operator= (BLK);	// Copy BLK parameter set
  }

void block_1D::operator = (const matrix &mx)
// sosi - dimension check needed?

	// Input		this,BLK  : two block_1D
	// Return		copies BLK to this, and destroys the old
        //                      contents of this block_1D

  {
  row_vector::operator= (mx);	// Copy BLK vector
  ParameterSet::operator= (ParameterSet());	// Copy BLK parameter set
  }

// ______________________________________________________________________
//                CLASS BLOCK_1D FUNCTIONS, BLOCK WITH SCALAR
// ______________________________________________________________________

block_1D operator * (const block_1D &BLK1, const complex &z)

	// Input		BLK1 : a data block
	//			z    : a complex number
	// Return		BLK  : a new data block which is the input
	//			       block multiplied by scalar z

  {
  block_1D BLK(BLK1);
  BLK *= z;
  return BLK;
  }				// Uses class row_vector

block_1D operator * (const block_1D &BLK1, double d)

	// Input		BLK1 : a data block
	//			z    : a complex number
	// Return		BLK  : a new data block which is the input
	//			       block multiplied by scalar z

  {
  block_1D BLK(BLK1);
  BLK *= d;
  return BLK;
  }				// Uses class row_vector

block_1D operator * (const complex &z, const block_1D &BLK1)

	// Input		BLK1 : a data block
	//			z    : a complex number
	// Return		BLK  : a new data block which is the input
	//			       block multiplied by scalar z

  {
  block_1D BLK(BLK1);
  BLK *= z;
  return BLK;
  }				// Uses class row_vector

block_1D operator * (double d, const block_1D &BLK1)

	// Input		BLK1 : a data block
	//			z    : a complex number
	// Return		BLK  : a new data block which is the input
	//			       block multiplied by scalar z

  {
  block_1D BLK(BLK1);
  BLK *= d;
  return BLK;
  } 				// Uses class row_vector

block_1D operator / (const block_1D &BLK1, const complex &z)

	// Input		BLK  : a data block
	//			z    : a complex number
	// Return		BLK1 : a new data block which is the input
	//			       block divided by scalar z

  {
  block_1D BLK(BLK1);
  BLK /= z;
  return BLK;
  }				// Uses class row_vector

// ______________________________________________________________________
//             CLASS BLOCK_1D FUNCTIONS, BLOCK WITH PARAMETER SET
// ______________________________________________________________________

//void operator += (block_1D &BLK, const ParameterSet &pset)

	// Input		BLK  : a data block
	//			pset : a parameter set
	// Return		none : the input data block is returned
	//			       with parameters from pset added

//  { (ParameterSet)BLK += pset;	}		// Add parameters in pset
// sosi: this does not work!, I don't know why yet.

// ______________________________________________________________________
//                  CLASS BLOCK_1D DATA SET FUNCTIONS
// ______________________________________________________________________

void product(block_1D &BLK1, const block_1D &BLK2)

	// Input		BLK1 : data block
	// 			BLK2 : data block
	// Return		none : BLK1 multiplied point by point by BLK2

  {
  BLK1 = block_1D(product((row_vector&)BLK1, (const row_vector&)BLK2));
//  block_1D BLKprod = block_1D(product((row_vector&)BLK1, (const row_vector&)BLK2));
//  BLK1.row_vector::operator= row_vector(BLKprod);
// sosi kludge
//  BLK1.ParameterSet::operator += ParameterSet(BLK2);	// add BLK2 parameters
  return;
  }

// ______________________________________________________________________
//                  CLASS BLOCK_1D PARAMETER SET FUNCTIONS
// ______________________________________________________________________

// *****************  Entire Parameter Set Manipulations ****************

void block_1D::set_defaults(int level)

	// Input		BLK  : data block(this)
	//			level: level to which defaults are set
	// Return		none : BLK parameter set defaults set

  {
  if(level == 0) clear();		// Zero entire parameter set
  std::string pname("Dim");
  std::string pstate("Data Set Dimension of Block");
  SinglePar par(pname, elements(), pstate);
  push_back(par);			// Add # dimension to pset
  }

// ______________________________________________________________________
//                        CLASS BLOCK_1D CHECKS
// ______________________________________________________________________

int block_1D::Blk1DCheck(int pt) const

  {
  if(pt >= elements())			// Insure point not beyond vector
    {
    Blk1DError(6);			// Point exceeds block data size
    Blk1DError(100, elements(), pt);
    return 0;
    }
  return 1;
  }

int block_1D::Blk1DCheck(const block_1D &BLK2) const

  {
  if(elements() != BLK2.elements())	// Dimension equivalence check
    {
    Blk1DError(1,1);			// Dimension mismatch
    Blk1DError(101, elements(), BLK2.elements());
    return 0;
    }
  return 1;
  }

// ____________________________________________________________________________
// i                      CLASS BLOCK_1D ERROR HANDLING
// ____________________________________________________________________________

void block_1D::write_pset(const std::string& filename) const

	// Input		BLK  : A 1D data block (this)
	//			file : Name of disk file to produce
	// Return		none : A file is produced on disk containing
	//			       the parameter set in BLK

  { ParameterSet::write(filename); }

std::ostream& operator << (std::ostream& ostr, const block_1D &BLK)

	// Input		BLK  : data block
	// Return		none : data contained in BLK sent
	//			       to output stream

  { return ostr << (const row_vector&)BLK; }

void print_pset(const block_1D &BLK)

	// Input		BLK  : data block
	// Return		none : parameter set contained in BLK sent
	//			       to standard I/O

  {
  std::cout << "\n\n\t\t\t\tCurrent Block_1D Parameter Set\n\n";
  std::cout << (const ParameterSet&)BLK;
  }

void print_dset(block_1D &BLK)

	// Input		BLK  : data block
	// Return		none : BLK data block is set to standard output

  {
  std::cout << "\n\n\t\t\t\tCurrent Block_1D Data Vector\n\n";
  int npts = BLK.elements();
  int pt = 0;
  int flag = 0;
  while (pt < npts)
    {
      std::cout << pt+1 << ".\t" << BLK(pt);
      flag = !flag;
      if (flag)
	std::cout << "\t";
      else
	std::cout << "\n";
      pt++;
    }
  }

#endif 							// Block_1D.cc


text:
igChart & igZoombar

        TRY IT OUT:

Scroll the chart with the scroll bar

Change the viewable area of the chart by dragging the handles inside the zoombar

This sample demonstrates how to link together the igDataChart and igZoomBar using Ignite UI Angular Wrappers components.

             Explore the Code

        <ig-data-chart [(options)]="options" [widgetId]='"datachart1"'></ig-data-chart>
        <ig-zoombar [(options)]="zoombarOptions" [widgetId]='"zoombar"'></ig-zoombar>

        <button type="button" class="btn btn-default" (click)="changeZB()">Change Zoombar Type</button>

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.bigtable.hbase.adapters.read;

import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.common.base.Function;
import com.google.common.base.Functions;

/**
 * Default implementation of {@link ReadHooks}.
 *
 * @author sduskis
 * @version $Id: $Id
 */
public class DefaultReadHooks implements ReadHooks {
  private Function<Query, Query> preSendHook = Functions.identity();
  /** {@inheritDoc} */
  @Override
  public void composePreSendHook(Function<Query, Query> newHook) {
    preSendHook = Functions.compose(newHook, preSendHook);
  }

  /** {@inheritDoc} */
  @Override
  public void applyPreSendHook(Query query) {
    preSendHook.apply(query);
  }
}


text:
<?php

namespace Platformsh\Cli;

use Platformsh\Cli\Helper\DrushHelper;
use Platformsh\Cli\Helper\FilesystemHelper;
use Platformsh\Cli\Helper\GitHelper;
use Platformsh\Cli\Helper\PlatformQuestionHelper;
use Platformsh\Cli\Helper\ShellHelper;
use Symfony\Component\Console\Application as ParentApplication;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Shell;

class Application extends ParentApplication
{

    /**
     * {@inheritdoc}
     */
    public function __construct()
    {
        parent::__construct('Platform.sh CLI', '2.0.2');

        $this->setDefaultTimezone();

        $this->addCommands($this->getCommands());

        $this->setDefaultCommand('welcome');
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultInputDefinition()
    {
        // We remove the confusing `--ansi` and `--no-ansi` options.
        return new InputDefinition(
          array(
            new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
            new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
            new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
            new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages'),
            new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
            new InputOption('--yes', '-y', InputOption::VALUE_NONE, 'Answer "yes" to all prompts'),
            new InputOption('--no', '-n', InputOption::VALUE_NONE, 'Answer "no" to all prompts'),
            new InputOption('--session-id', null, InputOption::VALUE_OPTIONAL, 'Specify the session ID'),
            new InputOption('--shell', '-s', InputOption::VALUE_NONE, 'Launch the shell'),
          )
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultHelperSet()
    {
        return new HelperSet(
          array(
            new FormatterHelper(),
            new PlatformQuestionHelper(),
            new FilesystemHelper(),
            new ShellHelper(),
            new DrushHelper(),
            new GitHelper(),
          )
        );
    }

    /**
     * @inheritdoc
     */
    protected function getDefaultCommands()
    {
        // Override the default commands to add a custom HelpCommand and
        // ListCommand.
        return array(new Command\HelpCommand(), new Command\ListCommand());
    }

    /**
     * @return \Symfony\Component\Console\Command\Command[]
     */
    protected function getCommands()
    {
        $commands = array();
        $commands[] = new Command\CompletionCommand();
        $commands[] = new Command\PlatformLogoutCommand();
        $commands[] = new Command\PlatformLoginCommand();
        $commands[] = new Command\DocsCommand();
        $commands[] = new Command\ProjectListCommand();
        $commands[] = new Command\DomainAddCommand();
        $commands[] = new Command\DomainDeleteCommand();
        $commands[] = new Command\DomainListCommand();
        $commands[] = new Command\EnvironmentActivateCommand();
        $commands[] = new Command\ActivityListCommand();
        $commands[] = new Command\ActivityLogCommand();
        $commands[] = new Command\EnvironmentBackupCommand();
        $commands[] = new Command\EnvironmentBranchCommand();
        $commands[] = new Command\EnvironmentCheckoutCommand();
        $commands[] = new Command\EnvironmentDeleteCommand();
        $commands[] = new Command\EnvironmentDrushCommand();
        $commands[] = new Command\EnvironmentHttpAccessCommand();
        $commands[] = new Command\EnvironmentListCommand();
        $commands[] = new Command\EnvironmentMetadataCommand();
        $commands[] = new Command\EnvironmentMergeCommand();
        $commands[] = new Command\EnvironmentRelationshipsCommand();
        $commands[] = new Command\EnvironmentRestoreCommand();
        $commands[] = new Command\EnvironmentRoutesCommand();
        $commands[] = new Command\EnvironmentSshCommand();
        $commands[] = new Command\EnvironmentSqlCommand();
        $commands[] = new Command\EnvironmentSqlDumpCommand();
        $commands[] = new Command\EnvironmentSynchronizeCommand();
        $commands[] = new Command\EnvironmentUrlCommand();
        $commands[] = new Command\EnvironmentVariableDeleteCommand();
        $commands[] = new Command\EnvironmentVariableGetCommand();
        $commands[] = new Command\EnvironmentVariableSetCommand();
        $commands[] = new Command\IntegrationAddCommand();
        $commands[] = new Command\IntegrationDeleteCommand();
        $commands[] = new Command\IntegrationGetCommand();
        $commands[] = new Command\IntegrationUpdateCommand();
        $commands[] = new Command\LocalBuildCommand();
        $commands[] = new Command\LocalCleanCommand();
        $commands[] = new Command\LocalDrushAliasesCommand();
        $commands[] = new Command\LocalDirCommand();
        $commands[] = new Command\ProjectGetCommand();
        $commands[] = new Command\LocalInitCommand();
        $commands[] = new Command\ProjectMetadataCommand();
        $commands[] = new Command\SshKeyAddCommand();
        $commands[] = new Command\SshKeyDeleteCommand();
        $commands[] = new Command\SshKeyListCommand();
        $commands[] = new Command\SubscriptionMetadataCommand();
        $commands[] = new Command\UserAddCommand();
        $commands[] = new Command\UserDeleteCommand();
        $commands[] = new Command\UserListCommand();
        $commands[] = new Command\UserRoleCommand();
        $commands[] = new Command\WelcomeCommand();
        $commands[] = new Command\WebCommand();

        return $commands;
    }

    /**
     * @inheritdoc
     */
    public function getHelp()
    {
        $messages = array(
          $this->getLongVersion(),
          '',
          '<comment>Global options:</comment>',
        );

        foreach ($this->getDefinition()
                      ->getOptions() as $option) {
            $messages[] = sprintf(
              '  %-29s %s %s',
              '<info>--' . $option->getName() . '</info>',
              $option->getShortcut() ? '<info>-' . $option->getShortcut() . '</info>' : '  ',
              $option->getDescription()
            );
        }

        return implode(PHP_EOL, $messages);
    }

    /**
     * {@inheritdoc}
     */
    public function doRun(InputInterface $input, OutputInterface $output)
    {
        // Set the input to non-interactive if the yes or no options are used.
        if ($input->hasParameterOption(array('--yes', '-y')) || $input->hasParameterOption(array('--no', '-n'))) {
            $input->setInteractive(false);
        } // Enable the shell.
        elseif ($input->hasParameterOption(array('--shell', '-s'))) {
            $shell = new Shell($this);
            $shell->run();

            return 0;
        }

        return parent::doRun($input, $output);
    }

    /**
     * Set the default timezone.
     *
     * PHP 5.4 has removed the autodetection of the system timezone,
     * so it needs to be done manually.
     * UTC is the fallback in case autodetection fails.
     */
    protected function setDefaultTimezone()
    {
        $timezone = 'UTC';
        if (is_link('/etc/localtime')) {
            // Mac OS X (and older Linuxes)
            // /etc/localtime is a symlink to the timezone in /usr/share/zoneinfo.
            $filename = readlink('/etc/localtime');
            if (strpos($filename, '/usr/share/zoneinfo/') === 0) {
                $timezone = substr($filename, 20);
            }
        } elseif (file_exists('/etc/timezone')) {
            // Ubuntu / Debian.
            $data = file_get_contents('/etc/timezone');
            if ($data) {
                $timezone = trim($data);
            }
        } elseif (file_exists('/etc/sysconfig/clock')) {
            // RHEL/CentOS
            $data = parse_ini_file('/etc/sysconfig/clock');
            if (!empty($data['ZONE'])) {
                $timezone = trim($data['ZONE']);
            }
        }

        date_default_timezone_set($timezone);
    }

}


text:
Catering all the statistics lovers of the European Youth Parliament

# Attention!
## This project is now continued inside of the eyp-developers organisation. You can find it here: https://github.com/eyp-developers/statistics
***
Welcome! We aim to provide a reusable GA Statistics app that can be used on any given session with any set of committees. It's completely open source and uses [Python](http://python.org) in conjunction with the [Django Web Framework](https://www.djangoproject.com/).

***

![example image ga_statistics](http://i.imgur.com/0jdlDRu.png "Example Image ga_statistics")

***

## Is `ga_statistics` ready to be used?

Yes, but you can still help to improve it! Contact @wolfskaempf or just start working on any of the [Issues](https://github.com/wolfskaempf/ga_statistics/issues) currently open and send a pull request when you're finished.

## What does it look like at the moment?

It is possible to add any set of committees which will be displayed in conjunction with the finished statistics modules. At the moment point resumes can be submitted to be displayed as part of the committees individual page. These are automatically updated as Chairs submit them.

You can view a more or less frequently updated version of the most recent commit [here](http://gastatistics.wiesenblu.me). You can log in to the admin interface [here](http://gastatistics.wiesenblu.me/admin). Username "tom" and password "a" will work.

## How To Use `ga_statistics` during your Session

To find more information on how to use `ga_statistics` during your session have a look at the wiki page on [How To Use GA Statistics](https://github.com/wolfskaempf/ga_statistics/wiki/How-To-Use-GA-Statistics).

## I would like this and that

Please feel free to share your ideas! We'd love to hear them! Just add them to the [Brainstorming](https://github.com/wolfskaempf/ga_statistics/wiki/brainstorming) wiki page.

## How to help make `ga_statistics` better
You can just start working on any of the open issued and send a pull request! If you don't know what that means, ask @wolfskaempf for help.

## I don't know how I got here, what is all of this?

If you don't know what the `EYP` (European Youth Parliament) is, read through our [Wikipedia Article](http://en.wikipedia.org/wiki/European_Youth_Parliament) or visit our [website](http://eypej.org).

Every time the people who are part of this organisation gather for a large event, a part of this event is called the `GA`. It stands for [General Assembly](http://en.wikipedia.org/wiki/General_assembly) and it's exactly that. During the `GA` the participants will discuss different topics in various manners. We designed `ga_statistics` to keep track of all of this data and make it nice and easy to collect and display it.


text: require 'profane'


text:
package org.springframework.jdbc.core;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor;
import org.springframework.util.Assert;

/**
 * Helper class that efficiently creates multiple {@link PreparedStatementCreator}
 * objects with different parameters based on a SQL statement and a single
 * set of parameter declarations.
 *
 * @author Rod Johnson
 * @author Thomas Risberg
 * @author Juergen Hoeller
 */
public class PreparedStatementCreatorFactory {

	/** The SQL, which won't change when the parameters change */
	private final String sql;

	/** List of SqlParameter objects. May not be null. */
	private final List declaredParameters;

	private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;

	private boolean updatableResults = false;

	private boolean returnGeneratedKeys = false;

	private String[] generatedKeysColumnNames = null;

	private NativeJdbcExtractor nativeJdbcExtractor;

	/**
	 * Create a new factory. Will need to add parameters via the
	 * {@link #addParameter} method or have no parameters.
	 */
	public PreparedStatementCreatorFactory(String sql) {
		this.sql = sql;
		this.declaredParameters = new LinkedList();
	}

	/**
	 * Create a new factory with the given SQL and JDBC types.
	 * @param sql SQL to execute
	 * @param types int array of JDBC types
	 */
	public PreparedStatementCreatorFactory(String sql, int[] types) {
		this.sql = sql;
		this.declaredParameters = SqlParameter.sqlTypesToAnonymousParameterList(types);
	}

	/**
	 * Create a new factory with the given SQL and parameters.
	 * @param sql SQL
	 * @param declaredParameters list of {@link SqlParameter} objects
	 * @see SqlParameter
	 */
	public PreparedStatementCreatorFactory(String sql, List declaredParameters) {
		this.sql = sql;
		this.declaredParameters = declaredParameters;
	}

	/**
	 * Add a new declared parameter.
	 *
Order of parameter addition is significant.
	 * @param param the parameter to add to the list of declared parameters
	 */
	public void addParameter(SqlParameter param) {
		this.declaredParameters.add(param);
	}

	/**
	 * Set whether to use prepared statements that return a specific type of ResultSet.
	 * @param resultSetType the ResultSet type
	 * @see java.sql.ResultSet#TYPE_FORWARD_ONLY
	 * @see java.sql.ResultSet#TYPE_SCROLL_INSENSITIVE
	 * @see java.sql.ResultSet#TYPE_SCROLL_SENSITIVE
	 */
	public void setResultSetType(int resultSetType) {
		this.resultSetType = resultSetType;
	}

	/**
	 * Set whether to use prepared statements capable of returning updatable ResultSets.
	 */
	public void setUpdatableResults(boolean updatableResults) {
		this.updatableResults = updatableResults;
	}

	/**
	 * Set whether prepared statements should be capable of returning auto-generated keys.
	 */
	public void setReturnGeneratedKeys(boolean returnGeneratedKeys) {
		this.returnGeneratedKeys = returnGeneratedKeys;
	}

	/**
	 * Set the column names of the auto-generated keys.
	 */
	public void setGeneratedKeysColumnNames(String[] names) {
		this.generatedKeysColumnNames = names;
	}

	/**
	 * Specify the NativeJdbcExtractor to use for unwrapping PreparedStatements, if any.
	 */
	public void setNativeJdbcExtractor(NativeJdbcExtractor nativeJdbcExtractor) {
		this.nativeJdbcExtractor = nativeJdbcExtractor;
	}

	/**
	 * Return a new PreparedStatementSetter for the given parameters.
	 * @param params list of parameters (may be null)
	 */
	public PreparedStatementSetter newPreparedStatementSetter(List params) {
		return new PreparedStatementCreatorImpl(params != null ? params : Collections.EMPTY_LIST);
	}

	/**
	 * Return a new PreparedStatementSetter for the given parameters.
	 * @param params the parameter array (may be null)
	 */
	public PreparedStatementSetter newPreparedStatementSetter(Object[] params) {
		return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.EMPTY_LIST);
	}

	/**
	 * Return a new PreparedStatementCreator for the given parameters.
	 * @param params list of parameters (may be null)
	 */
	public PreparedStatementCreator newPreparedStatementCreator(List params) {
		return new PreparedStatementCreatorImpl(params != null ? params : Collections.EMPTY_LIST);
	}

	/**
	 * Return a new PreparedStatementCreator for the given parameters.
	 * @param params the parameter array (may be null)
	 */
	public PreparedStatementCreator newPreparedStatementCreator(Object[] params) {
		return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.EMPTY_LIST);
	}

	/**
	 * Return a new PreparedStatementCreator for the given parameters.
	 * @param sqlToUse the actual SQL statement to use (if different from
	 * the factory's, for example because of named parameter expanding)
	 * @param params the parameter array (may be null)
	 */
	public PreparedStatementCreator newPreparedStatementCreator(String sqlToUse, Object[] params) {
		return new PreparedStatementCreatorImpl(
				sqlToUse, params != null ? Arrays.asList(params) : Collections.EMPTY_LIST);
	}

	/**
	 * PreparedStatementCreator implementation returned by this class.
	 */
	private class PreparedStatementCreatorImpl
			implements PreparedStatementCreator, PreparedStatementSetter, SqlProvider, ParameterDisposer {

		private final String actualSql;

		private final List parameters;

		public PreparedStatementCreatorImpl(List parameters) {
			this(sql, parameters);
		}

		public PreparedStatementCreatorImpl(String actualSql, List parameters) {
			this.actualSql = actualSql;
			Assert.notNull(parameters, "Parameters List must not be null");
			this.parameters = parameters;
			if (this.parameters.size() != declaredParameters.size()) {
				// account for named parameters being used multiple times
				Set names = new HashSet();
				for (int i = 0; i < parameters.size(); i++) {
					Object o = parameters.get(i);
					if (o instanceof SqlParameterValue) {
						names.add(((SqlParameterValue)o).getName());
					}
					else {
						names.add("Parameter #" + i);
					}
				}
				if (names.size() != declaredParameters.size()) {
					throw new InvalidDataAccessApiUsageException(
							"SQL [" + sql + "]: given " + names.size() +
							" parameters but expected " + declaredParameters.size());
				}
			}
		}

		public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
			PreparedStatement ps = null;
			if (generatedKeysColumnNames != null || returnGeneratedKeys) {
				try {
					if (generatedKeysColumnNames != null) {
						ps = con.prepareStatement(this.actualSql, generatedKeysColumnNames);
					}
					else {
						ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS);
					}
				}
				catch (AbstractMethodError ex) {
					throw new InvalidDataAccessResourceUsageException(
							"The JDBC driver is not compliant to JDBC 3.0 and thus " +
							"does not support retrieval of auto-generated keys", ex);
				}
			}
			else if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) {
				ps = con.prepareStatement(this.actualSql);
			}
			else {
				ps = con.prepareStatement(this.actualSql, resultSetType,
					updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY);
			}
			setValues(ps);
			return ps;
		}

		public void setValues(PreparedStatement ps) throws SQLException {
			// Determine PreparedStatement to pass to custom types.
			PreparedStatement psToUse = ps;
			if (nativeJdbcExtractor != null) {
				psToUse = nativeJdbcExtractor.getNativePreparedStatement(ps);
			}

			// Set arguments: Does nothing if there are no parameters.
			int sqlColIndx = 1;
			for (int i = 0; i < this.parameters.size(); i++) {
				Object in = this.parameters.get(i);
				SqlParameter declaredParameter = null;
				// SqlParameterValue overrides declared parameter metadata, in particular for
				// independence from the declared parameter position in case of named parameters.
				if (in instanceof SqlParameterValue) {
					SqlParameterValue paramValue = (SqlParameterValue) in;
					in = paramValue.getValue();
					declaredParameter = paramValue;
				}
				else {
					if (declaredParameters.size() <= i) {
						throw new InvalidDataAccessApiUsageException(
								"SQL [" + sql + "]: unable to access parameter number " + (i + 1) +
								" given only " + declaredParameters.size() + " parameters");

					}
					declaredParameter = (SqlParameter) declaredParameters.get(i);
				}
				if (in instanceof Collection && declaredParameter.getSqlType() != Types.ARRAY) {
					Collection entries = (Collection) in;
					for (Iterator it = entries.iterator(); it.hasNext();) {
						Object entry = it.next();
						if (entry instanceof Object[]) {
							Object[] valueArray = ((Object[])entry);
							for (int k = 0; k < valueArray.length; k++) {
								Object argValue = valueArray[k];
								StatementCreatorUtils.setParameterValue(psToUse, sqlColIndx++, declaredParameter, argValue);
							}
						}
						else {
							StatementCreatorUtils.setParameterValue(psToUse, sqlColIndx++, declaredParameter, entry);
						}
					}
				}
				else {
					StatementCreatorUtils.setParameterValue(psToUse, sqlColIndx++, declaredParameter, in);
				}
			}
		}

		public String getSql() {
			return sql;
		}

		public void cleanupParameters() {
			StatementCreatorUtils.cleanupParameters(this.parameters);
		}

		public String toString() {
			StringBuffer buf = new StringBuffer("PreparedStatementCreatorFactory.PreparedStatementCreatorImpl: sql=[");
			buf.append(sql).append("]; parameters=").append(this.parameters);
			return buf.toString();
		}
	}

}


text:
namespace ApiTemplate.IntegrationTest.Controllers
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using ApiTemplate.IntegrationTest.Fixtures;
    using Xunit;
    using Xunit.Abstractions;

    public class HealthCheckTest : CustomWebApplicationFactory<Startup>
    {
        private readonly HttpClient client;

        public HealthCheckTest(ITestOutputHelper testOutputHelper)
            : base(testOutputHelper) =>
            this.client = this.CreateClient();

        [Fact]
        public async Task GetStatus_Default_Returns200OkAsync()
        {
            var response = await this.client.GetAsync(new Uri("/status", UriKind.Relative)).ConfigureAwait(false);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }

        [Fact]
        public async Task GetStatusSelf_Default_Returns200OkAsync()
        {
            var response = await this.client.GetAsync(new Uri("/status/self", UriKind.Relative)).ConfigureAwait(false);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
}


text:
![screenshot](https://raw.github.com/jlord/sheetsee-pocket/gh-pages/ss-pocket-ss.png)

A website for your Pocket article archive. Fork-n-Go set up.

### Fork-n-Go

This repository only has a **gh-pages branch** with web files - that means as soon as you **fork** it, you have a live version yourself! You'd be able to visit it at `yourGitHubName.github.io/sheetsee-pocket`.

It would still be connected to my spreadsheet with my Pocket archive - but that's easy to change!

**Fork this!**

If you don't see your site, you may need to take [a few extra steps](https://help.github.com/articles/creating-pages-with-the-automatic-generator) to get gh-pages enables.

#### Use ifttt.com for Pocket -> Spreadsheet

If you don't have already have an account with both [Pocket](http://www.getpocket.com) (a read-it-later service) and [ifttt.com](http://www.ifttt.com) go ahead and create em. If you don't have a [Google](http://drive.google.com) account, get on that too.

![ifttt](https://raw.github.com/jlord/sheetsee-pocket/gh-pages/ifttt.png)

In ifttt.com set up [this recipe](https://ifttt.com/recipes/111549) that will take each article you archive on Pocket and add it to a row in a Google Spreadsheet.

_Now go read some things in your Pocket and archive 'em. You know, make the datas._

#### Set up Spreadsheet

Once you've got some entries, checkout your spreadsheet, change (or create if they're not in there automatically) the column headers to: **date, article, tags, url, excerpt**. Renaming won't break anything. Also, even though it's archiving an except, I'm not using in this project. But maybe you can find a neat way to use them?

While you're at your spreadsheet, you'll want to pusblish it to the web and get it's unique key. You'll find that by clicking **File > Publish to the Web**. Then click the "Start publishing" button.

![start publishing](https://raw.github.com/polotek/sheetsee-pocket/gh-pages/ss-publish-web.png)

It will then display the key in a window. Copy it!

![get key](https://raw.github.com/jllord/sheetsee-cache/master/img/key.png)

#### Paste Your Spreadsheet Key

Now, visit your fork of this repository. Click the `index.html` file, and then when that page loads, click Edit.

![ifttt](https://raw.github.com/jlord/sheetsee-pocket/gh-pages/indexedit.png)

Scroll to find **line 61** (or thereabouts), it looks like:

```javascript
    document.addEventListener('DOMContentLoaded', function() {
	  	var gData
	  	var URL = "0Ao5u1U6KYND7dFVkcnJRNUtHWUNKamxoRGg4ZzNiT3c"
			Tabletop.init( { key: URL, callback: showInfo, simpleSheet: true } )
    })
```
Paste your spreadsheet's key in the place of `0Ao5u1U6K...`

**At the bottom of the page, click Commit. You're done! Visit your site!**


text:
package net.java.sip.communicator.impl.protocol.sip;

import static net.java.sip.communicator.service.protocol.OperationSetBasicTelephony.*;
import gov.nist.javax.sip.header.*;

import java.net.*;
import java.text.*;
import java.util.*;

import javax.sip.*;
import javax.sip.address.*;
import javax.sip.address.URI;
import javax.sip.header.*;
import javax.sip.message.*;

import net.java.sip.communicator.impl.protocol.sip.sdp.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.Contact;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;

import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.MediaType; // disambiguate
import org.jitsi.service.neomedia.control.*;

/**
 * Our SIP implementation of the default CallPeer;
 *
 * @author Emil Ivov
 * @author Lubomir Marinov
 */
public class CallPeerSipImpl
    extends MediaAwareCallPeer<CallSipImpl,
                               CallPeerMediaHandlerSipImpl,
                               ProtocolProviderServiceSipImpl>
{
    /**
     * Our class logger.
     */
    private static final Logger logger
        = Logger.getLogger(CallPeerSipImpl.class);

    /**
     * The sub-type of the content carried by SIP INFO <tt>Requests</tt> for the
     * purposes of <tt>picture_fast_update</tt>.
     */
    static final String PICTURE_FAST_UPDATE_CONTENT_SUB_TYPE
        = "media_control+xml";

    /**
     * The sip address of this peer
     */
    private Address peerAddress = null;

    /**
     * The JAIN SIP dialog that has been created by the application for
     * communication with this call peer.
     */
    private Dialog jainSipDialog = null;

    /**
     * The SIP transaction that established this call. This was previously kept
     * in the jain-sip dialog but got deprecated there so we're now keeping it
     * here.
     */
    private Transaction latestInviteTransaction = null;

    /**
     * The jain sip provider instance that is responsible for sending and
     * receiving requests and responses related to this call peer.
     */
    private SipProvider jainSipProvider = null;

    /**
     * The transport address that we are using to address the peer or the
     * first one that we'll try when we next send them a message (could be the
     * address of our sip registrar).
     */
    private InetSocketAddress transportAddress = null;

    /**
     * A reference to the <tt>SipMessageFactory</tt> instance that we should
     * use when creating requests.
     */
    private final SipMessageFactory messageFactory;

    /**
     * The <tt>List</tt> of <tt>MethodProcessorListener</tt>s interested in how
     * this <tt>CallPeer</tt> processes SIP signaling.
     */
    private final List<MethodProcessorListener> methodProcessorListeners
        = new LinkedList<MethodProcessorListener>();

    /**
     * The indicator which determines whether the local peer may send
     * <tt>picture_fast_update</tt> to this remote peer (as part of the
     * execution of {@link #requestKeyFrame()}).
     */
    private boolean sendPictureFastUpdate
        = KeyFrameControl.KeyFrameRequester.SIGNALING.equals(
                SipActivator.getConfigurationService().getString(
                        KeyFrameControl.KeyFrameRequester.PREFERRED_PNAME,
                        KeyFrameControl.KeyFrameRequester.DEFAULT_PREFERRED));

    /**
     * Creates a new call peer with address <tt>peerAddress</tt>.
     *
     * @param peerAddress the JAIN SIP <tt>Address</tt> of the new call peer.
     * @param owningCall the call that contains this call peer.
     * @param containingTransaction the transaction that created the call peer.
     * @param sourceProvider the provider that the containingTransaction belongs
     * to.
     */
    public CallPeerSipImpl(Address     peerAddress,
                           CallSipImpl owningCall,
                           Transaction containingTransaction,
                           SipProvider sourceProvider)
    {
        super(owningCall);
        this.peerAddress = peerAddress;
        this.messageFactory = getProtocolProvider().getMessageFactory();

        super.setMediaHandler(
                new CallPeerMediaHandlerSipImpl(this)
                {
                    @Override
                    protected boolean requestKeyFrame()
                    {
                        return CallPeerSipImpl.this.requestKeyFrame();
                    }
                });

        setDialog(containingTransaction.getDialog());
        setLatestInviteTransaction(containingTransaction);
        setJainSipProvider(sourceProvider);
    }

    /**
     * Returns a String locator for that peer.
     *
     * @return the peer's address or phone number.
     */
    public String getAddress()
    {
        SipURI sipURI = (SipURI) peerAddress.getURI();

        return sipURI.getUser() + "@" + sipURI.getHost();
    }

    /**
     * Returns full URI of the address.
     *
     * @return full URI of the address
     */
    public String getURI()
    {
        return getPeerAddress().getURI().toString();
    }

    /**
     * Returns the address of the remote party (making sure that it corresponds
     * to the latest address we've received) and caches it.
     *
     * @return the most recent <tt>javax.sip.address.Address</tt> that we have
     * for the remote party.
     */
    public Address getPeerAddress()
    {
        Dialog dialog = getDialog();

        if (dialog != null)
        {
            Address remoteParty = dialog.getRemoteParty();

            if (remoteParty != null)
            {
                //update the address we've cached.
                peerAddress = remoteParty;
            }
        }
        return peerAddress;
    }

    /**
     * Returns a human readable name representing this peer.
     *
     * @return a String containing a name for that peer.
     */
    public String getDisplayName()
    {
        String displayName = getPeerAddress().getDisplayName();

        if(displayName == null)
        {
            Contact contact = getContact();

            if (contact != null)
                displayName = contact.getDisplayName();
            else
            {
                URI peerURI = getPeerAddress().getURI();
                if (peerURI instanceof SipURI)
                {
                    String userName = ((SipURI) peerURI).getUser();

                    if (userName != null && userName.length() > 0)
                        displayName = userName;
                }

                if (displayName == null)
                {
                    displayName = peerURI.toString();
                }
            }
        }

        if(displayName.startsWith("sip:"))
            displayName = displayName.substring(4);

        return displayName;
    }

    /**
     * Sets a human readable name representing this peer.
     *
     * @param displayName the peer's display name
     */
    public void setDisplayName(String displayName)
    {
        String oldName = getDisplayName();
        try
        {
            this.peerAddress.setDisplayName(displayName);
        }
        catch (ParseException ex)
        {
            //couldn't happen
            logger.error(ex.getMessage(), ex);
            throw new IllegalArgumentException(ex.getMessage());
        }

        //Fire the Event
        fireCallPeerChangeEvent(
                CallPeerChangeEvent.CALL_PEER_DISPLAY_NAME_CHANGE,
                oldName,
                displayName);
    }

    /**
     * Sets the JAIN SIP dialog that has been created by the application for
     * communication with this call peer.
     * @param dialog the JAIN SIP dialog that has been created by the
     * application for this call.
     */
    public void setDialog(Dialog dialog)
    {
        this.jainSipDialog = dialog;
    }

    /**
     * Returns the JAIN SIP dialog that has been created by the application for
     * communication with this call peer.
     *
     * @return the JAIN SIP dialog that has been created by the application for
     * communication with this call peer.
     */
    public Dialog getDialog()
    {
        return jainSipDialog;
    }

    /**
     * Sets the transaction instance that contains the INVITE which started
     * this call.
     *
     * @param transaction the Transaction that initiated this call.
     */
    public void setLatestInviteTransaction(Transaction transaction)
    {
        this.latestInviteTransaction = transaction;
    }

    /**
     * Returns the transaction instance that contains the INVITE which started
     * this call.
     *
     * @return the Transaction that initiated this call.
     */
    public Transaction getLatestInviteTransaction()
    {
        return latestInviteTransaction;
    }

    /**
     * Sets the jain sip provider instance that is responsible for sending and
     * receiving requests and responses related to this call peer.
     *
     * @param jainSipProvider the <tt>SipProvider</tt> that serves this call
     * peer.
     */
    public void setJainSipProvider(SipProvider jainSipProvider)
    {
        this.jainSipProvider = jainSipProvider;
    }

    /**
     * Returns the jain sip provider instance that is responsible for sending
     * and receiving requests and responses related to this call peer.
     *
     * @return the jain sip provider instance that is responsible for sending
     * and receiving requests and responses related to this call peer.
     */
    public SipProvider getJainSipProvider()
    {
        return jainSipProvider;
    }

    /**
     * The address that we have used to contact this peer. In cases
     * where no direct connection has been established with the peer,
     * this method will return the address that will be first tried when
     * connection is established (often the one used to connect with the
     * protocol server). The address may change during a session and
     *
     * @param transportAddress The address that we have used to contact this
     * peer.
     */
    public void setTransportAddress(InetSocketAddress transportAddress)
    {
        InetSocketAddress oldTransportAddress = this.transportAddress;
        this.transportAddress = transportAddress;

        this.fireCallPeerChangeEvent(
            CallPeerChangeEvent.CALL_PEER_TRANSPORT_ADDRESS_CHANGE,
                oldTransportAddress, transportAddress);
    }

    /**
     * Returns the contact corresponding to this peer or null if no
     * particular contact has been associated.
     * <p>
     * @return the <tt>Contact</tt> corresponding to this peer or null
     * if no particular contact has been associated.
     */
    public Contact getContact()
    {
        // if this peer has no call, most probably it means
        // its disconnected and no more in call
        // and we cannot obtain the contact
        if(getCall() == null)
            return null;

        ProtocolProviderService pps = getCall().getProtocolProvider();
        OperationSetPresenceSipImpl opSetPresence
            = (OperationSetPresenceSipImpl) pps
                .getOperationSet(OperationSetPresence.class);

        if(opSetPresence != null)
            return opSetPresence.resolveContactID(getAddress());
        else
            return null;
    }

    /**
     * Returns a URL pointing to a location with call control information for
     * this peer or <tt>null</tt> if no such URL is available for this
     * call peer.
     *
     * @return a URL link to a location with call information or a call control
     * web interface related to this peer or <tt>null</tt> if no such URL
     * is available.
     */
    @Override
    public URL getCallInfoURL()
    {
        return getMediaHandler().getCallInfoURL();
    }

    void processPictureFastUpdate(
            ClientTransaction clientTransaction,
            Response response)
    {
        /*
         * Disable the sending of picture_fast_update because it seems to be
         * unsupported by this remote peer.
         */
        if ((response.getStatusCode() != 200) && sendPictureFastUpdate)
            sendPictureFastUpdate = false;
    }

    boolean processPictureFastUpdate(
            ServerTransaction serverTransaction,
            Request request)
        throws OperationFailedException
    {
        CallPeerMediaHandlerSipImpl mediaHandler = getMediaHandler();
        boolean requested
            = (mediaHandler == null)
                ? false
                : mediaHandler.processKeyFrameRequest();

        Response response;

        try
        {
            response
                = getProtocolProvider().getMessageFactory().createResponse(
                        Response.OK,
                        request);
        }
        catch (ParseException pe)
        {
            throw new OperationFailedException(
                    "Failed to create OK Response.",
                    OperationFailedException.INTERNAL_ERROR,
                    pe);
        }

        if (!requested)
        {
            ContentType ct
                = new ContentType(
                        "application",
                        PICTURE_FAST_UPDATE_CONTENT_SUB_TYPE);
            String content
                = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
                    + "<media_control>\r\n"
                    + "<general_error>\r\n"
                    + "Failed to process picture_fast_update request.\r\n"
                    + "</general_error>\r\n"
                    + "</media_control>";

            try
            {
                response.setContent(content, ct);
            }
            catch (ParseException pe)
            {
                throw new OperationFailedException(
                        "Failed to set content of OK Response.",
                        OperationFailedException.INTERNAL_ERROR,
                        pe);
            }
        }

        try
        {
            serverTransaction.sendResponse(response);
        }
        catch (Exception e)
        {
            throw new OperationFailedException(
                    "Failed to send OK Response.",
                    OperationFailedException.INTERNAL_ERROR,
                    e);
        }

        return true;
    }

    /**
     * Reinitializes the media session of the <tt>CallPeer</tt> that this
     * INVITE request is destined to.
     *
     * @param serverTransaction a reference to the {@link ServerTransaction}
     * that contains the reINVITE request.
     */
    public void processReInvite(ServerTransaction serverTransaction)
    {
        Request invite = serverTransaction.getRequest();

        setLatestInviteTransaction(serverTransaction);

        // SDP description may be in ACKs - bug report Laurent Michel
        String sdpOffer = null;
        ContentLengthHeader cl = invite.getContentLength();
        if (cl != null && cl.getContentLength() > 0)
            sdpOffer = SdpUtils.getContentAsString(invite);

        Response response = null;
        try
        {
            response = messageFactory.createResponse(Response.OK, invite);

            processExtraHeaders(response);

            String sdpAnswer;
            if(sdpOffer != null)
                sdpAnswer = getMediaHandler().processOffer( sdpOffer );
            else
                sdpAnswer = getMediaHandler().createOffer();

            response.setContent( sdpAnswer, getProtocolProvider()
                .getHeaderFactory().createContentTypeHeader(
                                "application", "sdp"));

            if (logger.isTraceEnabled())
                logger.trace("will send an OK response: " + response);
            serverTransaction.sendResponse(response);
            if (logger.isDebugEnabled())
                logger.debug("OK response sent");
        }
        catch (Exception ex)//no need to distinguish among exceptions.
        {
            logger.error("Error while trying to send a response", ex);
            setState(CallPeerState.FAILED,
                "Internal Error: " + ex.getMessage());
            getProtocolProvider().sayErrorSilently(
                            serverTransaction, Response.SERVER_INTERNAL_ERROR);
            return;
        }

        reevalRemoteHoldStatus();

        fireRequestProcessed(invite, response);
    }

    /**
     * Sets the state of the corresponding call peer to DISCONNECTED and
     * sends an OK response.
     *
     * @param byeTran the ServerTransaction the the BYE request arrived in.
     */
    public void processBye(ServerTransaction byeTran)
    {
        Request byeRequest = byeTran.getRequest();
        // Send OK
        Response ok = null;
        try
        {
            ok = messageFactory.createResponse(Response.OK, byeRequest);
        }
        catch (ParseException ex)
        {
            logger.error("Error while trying to send a response to a bye", ex);
            /*
             * No need to let the user know about the error since it doesn't
             * affect them. And just as the comment on sendResponse bellow
             * says, this is not really a problem according to the RFC so we
             * should proceed with the execution bellow in order to gracefully
             * hangup the call.
             */
        }

        if (ok != null)
            try
            {
                byeTran.sendResponse(ok);
                if (logger.isDebugEnabled())
                    logger.debug("sent response " + ok);
            }
            catch (Exception ex)
            {
                /*
                 * This is not really a problem according to the RFC so just
                 * dump to stdout should someone be interested.
                 */
                logger.error("Failed to send an OK response to BYE request,"
                    + "exception was:\n", ex);
            }

        // change status
        boolean dialogIsAlive;
        try
        {
            dialogIsAlive = EventPackageUtils.processByeThenIsDialogAlive(
                            byeTran.getDialog());
        }
        catch (SipException ex)
        {
            dialogIsAlive = false;

            logger.error(
                "Failed to determine whether the dialog should stay alive.",ex);
        }

        //if the Dialog is still alive (i.e. we are in the middle of a xfer)
        //then only stop streaming, otherwise Disconnect.
        if (dialogIsAlive)
        {
            getMediaHandler().close();
        }
        else
        {
            ReasonHeader reasonHeader =
                    (ReasonHeader)byeRequest.getHeader(ReasonHeader.NAME);

            if(reasonHeader != null)
            {
                setState(
                        CallPeerState.DISCONNECTED,
                        reasonHeader.getText(),
                        reasonHeader.getCause());
            }
            else
                setState(CallPeerState.DISCONNECTED);
        }
    }

    /**
     * Sets the state of the specifies call peer as DISCONNECTED.
     *
     * @param serverTransaction the transaction that the cancel was received in.
     */
    public void processCancel(ServerTransaction serverTransaction)
    {
        // Cancels should be OK-ed and the initial transaction - terminated
        // (report and fix by Ranga)
        Request cancel = serverTransaction.getRequest();
        try
        {
            Response ok = messageFactory.createResponse(Response.OK, cancel);
            serverTransaction.sendResponse(ok);

            if (logger.isDebugEnabled())
                logger.debug("sent an ok response to a CANCEL request:\n" + ok);
        }
        catch (ParseException ex)
        {
            logAndFail("Failed to create an OK Response to a CANCEL.", ex);
            return;
        }
        catch (Exception ex)
        {
            logAndFail("Failed to send an OK Response to a CANCEL.", ex);
            return;
        }

        try
        {
            // stop the invite transaction as well
            Transaction tran = getLatestInviteTransaction();
            // should be server transaction and misplaced cancels should be
            // filtered by the stack but it doesn't hurt checking anyway
            if (!(tran instanceof ServerTransaction))
            {
                logger.error("Received a misplaced CANCEL request!");
                return;
            }

            ServerTransaction inviteTran = (ServerTransaction) tran;
            Request invite = getLatestInviteTransaction().getRequest();
            Response requestTerminated = messageFactory
                .createResponse(Response.REQUEST_TERMINATED, invite);

            inviteTran.sendResponse(requestTerminated);
            if (logger.isDebugEnabled())
                logger.debug("sent request terminated response:\n"
                    + requestTerminated);
        }
        catch (ParseException ex)
        {
            logger.error("Failed to create a REQUEST_TERMINATED Response to "
                + "an INVITE request.", ex);
        }
        catch (Exception ex)
        {
            logger.error("Failed to send an REQUEST_TERMINATED Response to "
                + "an INVITE request.", ex);
        }

        ReasonHeader reasonHeader =
                    (ReasonHeader)cancel.getHeader(ReasonHeader.NAME);

        if(reasonHeader != null)
        {
            setState(
                    CallPeerState.DISCONNECTED,
                    reasonHeader.getText(),
                    reasonHeader.getCause());
        }
        else
            setState(CallPeerState.DISCONNECTED);
    }

    /**
     * Updates the session description and sends the state of the corresponding
     * call peer to CONNECTED.
     *
     * @param serverTransaction the transaction that the ACK was received in.
     * @param ack the ACK <tt>Request</tt> we need to process
     */
    public void processAck(ServerTransaction serverTransaction, Request ack)
    {
        ContentLengthHeader contentLength = ack.getContentLength();
        if ((contentLength != null) && (contentLength.getContentLength() > 0))
        {
            try
            {
                getMediaHandler().processAnswer(
                                    SdpUtils.getContentAsString(ack));
            }
            catch (Exception exc)
            {
                logAndFail("There was an error parsing the SDP description of "
                            + getDisplayName() + "(" + getAddress() + ")", exc);
                return;
            }
        }

        // change status
        CallPeerState peerState = getState();
        if (!CallPeerState.isOnHold(peerState))
        {
            setState(CallPeerState.CONNECTED);
            getMediaHandler().start();

            // as its connected, set initial mute status,
            // corresponding call status
            // this would also unmute calls that were previously mute because
            // of early media.
            if(this.getCall() != null && isMute() != this.getCall().isMute())
                setMute(this.getCall().isMute());
        }
    }

    /**
     * Handles early media in 183 Session Progress responses. Retrieves the SDP
     * and makes sure that we start transmitting and playing early media that we
     * receive. Puts the call into a CONNECTING_WITH_EARLY_MEDIA state.
     *
     * @param tran the <tt>ClientTransaction</tt> that the response
     * arrived in.
     * @param response the 183 <tt>Response</tt> to process
     */
    public void processSessionProgress(ClientTransaction tran,
                                       Response          response)
    {
        if (response.getContentLength().getContentLength() == 0)
        {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring a 183 with no content");
            return;
        }

        ContentTypeHeader contentTypeHeader = (ContentTypeHeader) response
                .getHeader(ContentTypeHeader.NAME);

        if (!contentTypeHeader.getContentType().equalsIgnoreCase("application")
            || !contentTypeHeader.getContentSubType().equalsIgnoreCase("sdp"))
        {
            //This can happen when receiving early media for a second time.
            logger.warn("Ignoring invite 183 since call peer is "
                + "already exchanging early media.");
            return;
        }

        //handle media
        try
        {
            getMediaHandler().processAnswer(
                            SdpUtils.getContentAsString(response));
        }
        catch (Exception exc)
        {
            logAndFail("There was an error parsing the SDP description of "
                + getDisplayName() + "(" + getAddress() + ")", exc);
            return;
        }

        //change status
        setState(CallPeerState.CONNECTING_WITH_EARLY_MEDIA);
        getMediaHandler().start();

        // set the call on mute. we don't want the user to be heard unless they
        //know they are.
        setMute(true);
    }

    /**
     * Sets our state to CONNECTED, sends an ACK and processes the SDP
     * description in the <tt>ok</tt> <tt>Response</tt>.
     *
     * @param clientTransaction the <tt>ClientTransaction</tt> that the response
     * arrived in.
     * @param ok the OK <tt>Response</tt> to process
     */
    public void processInviteOK(ClientTransaction clientTransaction,
                                 Response         ok)
    {
        try
        {
            // Send the ACK. Do it now since we already got all the info we need
            // and processSdpAnswer() can take a while (patch by Michael Koch)
            getProtocolProvider().sendAck(clientTransaction);
        }
        catch (InvalidArgumentException ex)
        {
            // Shouldn't happen
            logAndFail("Error creating an ACK (CSeq?)", ex);
            return;
        }
        catch (SipException ex)
        {
            logAndFail("Failed to create ACK request!", ex);
            return;
        }

        try
        {
             //Process SDP unless we've just had an answer in a 18X response
            if (!CallPeerState.CONNECTING_WITH_EARLY_MEDIA.equals(getState()))
            {
                getMediaHandler()
                    .processAnswer(SdpUtils.getContentAsString(ok));
            }
        }
        //at this point we have already sent our ack so in addition to logging
        //an error we also need to hangup the call peer.
        catch (Exception exc)//Media or parse exception.
        {
            logger.error("There was an error parsing the SDP description of "
                + getDisplayName() + "(" + getAddress() + ")", exc);
            try
            {
                //we are connected from a SIP point of view (cause we sent our
                //ACK) so make sure we set the state accordingly or the hangup
                //method won't know how to end the call.
                setState(CallPeerState.CONNECTED,
                    "Error:" + exc.getLocalizedMessage());
                hangup();
            }
            catch (Exception e)
            {
                //handle in finally.
            }
            finally
            {
                logAndFail("Remote party sent a faulty session description.",
                        exc);
            }
            return;
        }

        // change status
        if (!CallPeerState.isOnHold(getState()))
        {
            setState(CallPeerState.CONNECTED);
            getMediaHandler().start();

            // as its connected, set initial mute status,
            // corresponding call status
            if (this.getCall() != null
                && isMute() != this.getCall().isMute())
            {
                setMute(this.getCall().isMute());
            }
        }

        fireResponseProcessed(ok, null);
    }

    /**
     * Sends a <tt>picture_fast_update</tt> SIP INFO request to this remote
     * peer.
     *
     * @throws OperationFailedException if anything goes wrong while sending the
     * <tt>picture_fast_update</tt> SIP INFO request to this remote peer
     */
    private void pictureFastUpdate()
        throws OperationFailedException
    {
        Request info
            = getProtocolProvider().getMessageFactory().createRequest(
                    getDialog(),
                    Request.INFO);

        //here we add the body
        ContentType ct
            = new ContentType(
                    "application",
                    PICTURE_FAST_UPDATE_CONTENT_SUB_TYPE);
        String content
            = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
                + "<media_control>\r\n"
                + "<vc_primitive>\r\n"
                + "<to_encoder>\r\n"
                + "<picture_fast_update/>\r\n"
                + "</to_encoder>\r\n"
                + "</vc_primitive>\r\n"
                + "</media_control>";

        ContentLength cl = new ContentLength(content.length());
        info.setContentLength(cl);

        try
        {
            info.setContent(content.getBytes(), ct);
        }
        catch (ParseException ex)
        {
            logger.error("Failed to construct the INFO request", ex);
            throw new OperationFailedException(
                    "Failed to construct a client the INFO request",
                    OperationFailedException.INTERNAL_ERROR,
                    ex);

        }
        //body ended
        ClientTransaction clientTransaction = null;
        try
        {
            clientTransaction
                = getJainSipProvider().getNewClientTransaction(info);
        }
        catch (TransactionUnavailableException ex)
        {
            logger.error(
                    "Failed to construct a client transaction from the INFO request",
                    ex);
            throw new OperationFailedException(
                    "Failed to construct a client transaction from the INFO request",
                    OperationFailedException.INTERNAL_ERROR,
                    ex);
        }

        try
        {
            if (getDialog().getState()
                == DialogState.TERMINATED)
            {
                //this is probably because the call has just ended, so don't
                //throw an exception. simply log and get lost.
                logger.warn(
                        "Trying to send a dtmf tone inside a "
                            + "TERMINATED dialog.");
                return;
            }

            getDialog().sendRequest(clientTransaction);
            if (logger.isDebugEnabled())
                logger.debug("sent request:\n" + info);
        }
        catch (SipException ex)
        {
            throw new OperationFailedException(
                    "Failed to send the INFO request",
                    OperationFailedException.NETWORK_FAILURE,
                    ex);
        }
    }

    /**
     * Ends the call with for this <tt>CallPeer</tt>. Depending on the state
     * of the peer the method would send a CANCEL, BYE, or BUSY_HERE message
     * and set the new state to DISCONNECTED.
     *
     * @throws OperationFailedException if we fail to terminate the call.
     */
    public void hangup()
        throws OperationFailedException
    {
        // By default we hang up by indicating no failure has happened.
        hangup(HANGUP_REASON_NORMAL_CLEARING, null);
    }

    /**
     * Ends the call with for this <tt>CallPeer</tt>. Depending on the state
     * of the peer the method would send a CANCEL, BYE, or BUSY_HERE message
     * and set the new state to DISCONNECTED.
     *
     * @param reasonCode indicates if the hangup is following to a call failure
     * or simply a disconnect indicate by the reason.
     * @param reason the reason of the hangup. If the hangup is due to a call
     * failure, then this string could indicate the reason of the failure
     *
     * @throws OperationFailedException if we fail to terminate the call.
     */
    public void hangup(int reasonCode, String reason)
        throws OperationFailedException
    {
        // do nothing if the call is already ended
        if (CallPeerState.DISCONNECTED.equals(getState())
            || CallPeerState.FAILED.equals(getState()))
        {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring a request to hangup a call peer "
                        + "that is already DISCONNECTED");
            return;
        }

        boolean failed = (reasonCode != HANGUP_REASON_NORMAL_CLEARING);

        CallPeerState peerState = getState();
        if (peerState.equals(CallPeerState.CONNECTED)
            || CallPeerState.isOnHold(peerState))
        {
            // if we fail to send the bye, lets close the call anyway
            try
            {
                boolean dialogIsAlive = sayBye(reasonCode, reason);
                if (!dialogIsAlive)
                {
                    setDisconnectedState(failed, reason);
                }
            }
            catch(Throwable ex)
            {
                logger.error(
                    "Error while trying to hangup, trying to handle!", ex);

                // make sure we end media if exception occurs
                setDisconnectedState(true, null);

                // if its the handled OperationFailedException, pass it
                if(ex instanceof OperationFailedException)
                    throw (OperationFailedException)ex;
            }
        }
        else if (CallPeerState.CONNECTING.equals(getState())
            || CallPeerState.CONNECTING_WITH_EARLY_MEDIA.equals(getState())
            || CallPeerState.ALERTING_REMOTE_SIDE.equals(getState()))
        {
            if (getLatestInviteTransaction() != null)
            {
                // Someone knows about us. Let's be polite and say we are
                // leaving
                sayCancel();
            }
            setDisconnectedState(failed, reason);
        }
        else if (peerState.equals(CallPeerState.INCOMING_CALL))
        {
            setDisconnectedState(failed, reason);
            sayBusyHere();
        }
        // For FAILED and BUSY we only need to update CALL_STATUS
        else if (peerState.equals(CallPeerState.BUSY))
        {
            setDisconnectedState(failed, reason);
        }
        else if (peerState.equals(CallPeerState.FAILED))
        {
            setDisconnectedState(failed, reason);
        }
        else
        {
            setDisconnectedState(failed, reason);
            logger.error("Could not determine call peer state!");
        }
    }

    /**
     * Sends a BUSY_HERE response to the peer represented by this instance.
     *
     * @throws OperationFailedException if we fail to create or send the
     * response
     */
    private void sayBusyHere()
        throws OperationFailedException
    {
        if (!(getLatestInviteTransaction() instanceof ServerTransaction))
        {
            logger.error("Cannot send BUSY_HERE in a client transaction");
            throw new OperationFailedException(
                "Cannot send BUSY_HERE in a client transaction",
                OperationFailedException.INTERNAL_ERROR);
        }

        Request request = getLatestInviteTransaction().getRequest();
        Response busyHere = null;
        try
        {
            busyHere = messageFactory.createResponse(
                                Response.BUSY_HERE, request);
        }
        catch (ParseException ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to create the BUSY_HERE response!",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
        }

        ServerTransaction serverTransaction =
            (ServerTransaction) getLatestInviteTransaction();

        try
        {
            serverTransaction.sendResponse(busyHere);
            if (logger.isDebugEnabled())
                logger.debug("sent response:\n" + busyHere);
        }
        catch (Exception ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to send the BUSY_HERE response",
                OperationFailedException.NETWORK_FAILURE, ex, logger);
        }
    }

    /**
     * Sends a Cancel request to the peer represented by this instance.
     *
     * @throws OperationFailedException we failed to construct or send the
     * CANCEL request.
     */
    private void sayCancel()
        throws OperationFailedException
    {
        if (getLatestInviteTransaction() instanceof ServerTransaction)
        {
            logger.error("Cannot cancel a server transaction");
            throw new OperationFailedException(
                "Cannot cancel a server transaction",
                OperationFailedException.INTERNAL_ERROR);
        }

        ClientTransaction clientTransaction =
            (ClientTransaction) getLatestInviteTransaction();
        try
        {
            Request cancel = clientTransaction.createCancel();
            ClientTransaction cancelTransaction =
                getJainSipProvider().getNewClientTransaction(
                    cancel);
            cancelTransaction.sendRequest();
            if (logger.isDebugEnabled())
                logger.debug("sent request:\n" + cancel);
        }
        catch (SipException ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to send the CANCEL request",
                OperationFailedException.NETWORK_FAILURE, ex, logger);
        }
    }

    /**
     * Sends a BYE request to <tt>callPeer</tt>.
     *
     * @return <tt>true</tt> if the <tt>Dialog</tt> should be considered
     * alive after sending the BYE request (e.g. when there're still active
     * subscriptions); <tt>false</tt>, otherwise
     *
     * @throws OperationFailedException if we failed constructing or sending a
     * SIP Message.
     */
    private boolean sayBye(int reasonCode, String reason)
        throws OperationFailedException
    {
        Dialog dialog = getDialog();

        Request bye = messageFactory.createRequest(dialog, Request.BYE);

        if(reasonCode != HANGUP_REASON_NORMAL_CLEARING && reason != null)
        {
            int sipCode = convertReasonCodeToSIPCode(reasonCode);

            if(sipCode != -1)
            {
                try
                {
                    // indicate reason for failure
                    // using Reason header rfc3326
                    ReasonHeader reasonHeader =
                        getProtocolProvider().getHeaderFactory()
                            .createReasonHeader(
                                "SIP",
                                sipCode,
                                reason);
                    bye.setHeader(reasonHeader);
                }
                catch(Throwable e)
                {
                    logger.error("Cannot set reason header", e);
                }
            }
        }

        getProtocolProvider().sendInDialogRequest(
                        getJainSipProvider(), bye, dialog);

        /*
         * Let subscriptions such as the ones associated with REFER requests
         * keep the dialog alive and correctly delete it when they are
         * terminated.
         */
        try
        {
            return EventPackageUtils.processByeThenIsDialogAlive(dialog);
        }
        catch (SipException ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to determine whether the dialog should stay alive.",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
            return false;
        }
    }

    /**
     * Converts the codes for hangup from OperationSetBasicTelephony one
     * to the sip codes.
     * @param reasonCode the reason code.
     * @return the sip code or -1 if not found.
     */
    private static int convertReasonCodeToSIPCode(int reasonCode)
    {
        switch(reasonCode)
        {
            case HANGUP_REASON_NORMAL_CLEARING :
                return Response.ACCEPTED;
            case HANGUP_REASON_ENCRYPTION_REQUIRED :
                return Response.SESSION_NOT_ACCEPTABLE;
            case HANGUP_REASON_TIMEOUT :
                return Response.REQUEST_TIMEOUT;
            case HANGUP_REASON_BUSY_HERE :
                return Response.BUSY_HERE;
            default : return -1;
        }
    }

    /**
     * Indicates a user request to answer an incoming call from this
     * <tt>CallPeer</tt>.
     *
     * Sends an OK response to <tt>callPeer</tt>. Make sure that the call
     * peer contains an SDP description when you call this method.
     *
     * @throws OperationFailedException if we fail to create or send the
     * response.
     */
    public synchronized void answer()
        throws OperationFailedException
    {
        Transaction transaction = getLatestInviteTransaction();

        if (transaction == null ||
            !(transaction instanceof ServerTransaction))
        {
            setState(CallPeerState.DISCONNECTED);
            throw new OperationFailedException(
                "Failed to extract a ServerTransaction "
                    + "from the call's associated dialog!",
                OperationFailedException.INTERNAL_ERROR);
        }

        CallPeerState peerState = getState();

        if (peerState.equals(CallPeerState.CONNECTED)
            || CallPeerState.isOnHold(peerState))
        {
            if (logger.isInfoEnabled())
                logger.info("Ignoring user request to answer a CallPeer "
                        + "that is already connected. CP:");
            return;
        }

        ServerTransaction serverTransaction = (ServerTransaction) transaction;
        Request invite = serverTransaction.getRequest();
        Response ok = null;
        try
        {
            ok = messageFactory.createResponse(Response.OK, invite);

            processExtraHeaders(ok);
        }
        catch (ParseException ex)
        {
            setState(CallPeerState.DISCONNECTED);
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to construct an OK response to an INVITE request",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
        }

        // Content
        ContentTypeHeader contentTypeHeader = null;
        try
        {
            // content type should be application/sdp (not applications)
            // reported by Oleg Shevchenko (Miratech)
            contentTypeHeader = getProtocolProvider().getHeaderFactory()
                .createContentTypeHeader("application", "sdp");
        }
        catch (ParseException ex)
        {
            // Shouldn't happen
            setState(CallPeerState.DISCONNECTED);
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to create a content type header for the OK response",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
        }

        // This is the sdp offer that came from the initial invite,
        // also that invite can have no offer.
        String sdpOffer = null;
        try
        {
            // extract the SDP description.
            // beware: SDP description may be in ACKs so it could be that
            // there's nothing here - bug report Laurent Michel
            ContentLengthHeader cl = invite.getContentLength();
            if (cl != null && cl.getContentLength() > 0)
            {
                sdpOffer = SdpUtils.getContentAsString(invite);
            }

            String sdp;
            // if the offer was in the invite create an SDP answer
            if ((sdpOffer != null) && (sdpOffer.length() > 0))
            {
                sdp = getMediaHandler().processOffer(sdpOffer);
            }
            // if there was no offer in the invite - create an offer
            else
            {
                sdp = getMediaHandler().createOffer();
            }
            ok.setContent(sdp, contentTypeHeader);
        }
        catch (Exception ex)
        {
            //log, the error and tell the remote party. do not throw an
            //exception as it would go to the stack and there's nothing it could
            //do with it.
            logger.error(
                "Failed to create an SDP description for an OK response "
                    + "to an INVITE request!", ex);
            getProtocolProvider().sayError(
                            serverTransaction, Response.NOT_ACCEPTABLE_HERE);

            //do not continue processing - we already canceled the peer here
            setState(CallPeerState.FAILED, ex.getMessage());

            return;
        }

        try
        {
            serverTransaction.sendResponse(ok);
            if (logger.isDebugEnabled())
                logger.debug("sent response\n" + ok);
        }
        catch (Exception ex)
        {
            setState(CallPeerState.DISCONNECTED);
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to send an OK response to an INVITE request",
                OperationFailedException.NETWORK_FAILURE, ex, logger);
        }

        fireRequestProcessed(invite, ok);

        // the ACK to our answer might already be processed before we get here
        if(CallPeerState.INCOMING_CALL.equals(getState()))
        {
            if(sdpOffer != null && sdpOffer.length() > 0)
                setState(CallPeerState.CONNECTING_INCOMING_CALL_WITH_MEDIA);
            else
                setState(CallPeerState.CONNECTING_INCOMING_CALL);
        }
    }

    /**
     * Puts the <tt>CallPeer</tt> represented by this instance on or off hold.
     *
     * @param onHold <tt>true</tt> to have the <tt>CallPeer</tt> put on hold;
     * <tt>false</tt>, otherwise
     *
     * @throws OperationFailedException if we fail to construct or send the
     * INVITE request putting the remote side on/off hold.
     */
    public void putOnHold(boolean onHold)
        throws OperationFailedException
    {
        CallPeerMediaHandlerSipImpl mediaHandler = getMediaHandler();

        mediaHandler.setLocallyOnHold(onHold);

        try
        {
            sendReInvite(mediaHandler.createOffer());
        }
        catch (Exception ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to create SDP offer to hold.",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
        }

        reevalLocalHoldStatus();
    }

    /**
     * Sends a reINVITE request to this <tt>CallPeer</tt> within its current
     * <tt>Dialog</tt>.
     *
     * @throws OperationFailedException if sending the reINVITE request fails
     */
    void sendReInvite()
        throws OperationFailedException
    {
        sendReInvite(getMediaHandler().createOffer());
    }

    /**
     * Sends a reINVITE request with a specific <tt>sdpOffer</tt> (description)
     * within the current <tt>Dialog</tt> with the call peer represented by
     * this instance.
     *
     * @param sdpOffer the offer that we'd like to use for the newly created
     * INVITE request.
     *
     * @throws OperationFailedException if sending the request fails for some
     * reason.
     */
    private void sendReInvite(String sdpOffer)
        throws OperationFailedException
    {
        Dialog dialog = getDialog();
        Request invite = messageFactory.createRequest(dialog, Request.INVITE);

        try
        {
            // Content-Type
            invite.setContent(
                    sdpOffer,
                    getProtocolProvider()
                        .getHeaderFactory()
                            .createContentTypeHeader("application", "sdp"));

            processExtraHeaders(invite);
        }
        catch (ParseException ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                    "Failed to parse SDP offer for the new invite.",
                    OperationFailedException.INTERNAL_ERROR,
                    ex,
                    logger);
        }

        getProtocolProvider().sendInDialogRequest(
                getJainSipProvider(), invite, dialog);
    }

    /**
     * Creates a <tt>CallPeerSipImpl</tt> from <tt>calleeAddress</tt> and sends
     * them an invite request. The invite request will be initialized according
     * to any relevant parameters in the <tt>cause</tt> message (if different
     * from <tt>null</tt>) that is the reason for creating this call.
     *
     * @throws OperationFailedException  with the corresponding code if we fail
     *  to create the call or in case we someone calls us mistakenly while we
     *  are actually wrapped around an invite transaction.
     */
    public void invite()
        throws OperationFailedException
    {
        try
        {
            ClientTransaction inviteTran
                = (ClientTransaction) getLatestInviteTransaction();
            Request invite = inviteTran.getRequest();

            // Content-Type
            ContentTypeHeader contentTypeHeader
                = getProtocolProvider()
                    .getHeaderFactory()
                        .createContentTypeHeader("application", "sdp");

            invite.setContent(
                    getMediaHandler().createOffer(),
                    contentTypeHeader);

            processExtraHeaders(invite);

            inviteTran.sendRequest();
            if (logger.isDebugEnabled())
                logger.debug("sent request:\n" + inviteTran.getRequest());
        }
        catch (Exception ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                    "An error occurred while sending invite request",
                    OperationFailedException.NETWORK_FAILURE,
                    ex,
                    logger);
        }
    }

    /**
     * A place where we can handle any headers we need for requests
     * and responses. Such a case is reflecting the focus state in contact
     * header.
     * @param message the SIP <tt>Message</tt> in which a header change
     * is to be reflected
     * @throws ParseException if modifying the specified SIP <tt>Message</tt> to
     * reflect the header change fails
     */
    protected void processExtraHeaders(javax.sip.message.Message message)
        throws ParseException
    {
        /*
         * If the local peer represented by the Call of this CallPeer is
         * acting as a conference focus, it must indicate it in its Contact
         * header.
         */
        reflectConferenceFocus(message);
    }

    /**
     * Reflects the value of the <tt>conferenceFocus</tt> property of the
     * <tt>Call</tt> of this <tt>CallPeer</tt> in the specified SIP
     * <tt>Message</tt>.
     *
     * @param message the SIP <tt>Message</tt> in which the value of the
     * <tt>conferenceFocus</tt> property of the <tt>Call</tt> of this
     * <tt>CallPeer</tt> is to be reflected
     * @throws ParseException if modifying the specified SIP <tt>Message</tt> to
     * reflect the <tt>conferenceFocus</tt> property of the <tt>Call</tt> of
     * this <tt>CallPeer</tt> fails
     */
    private void reflectConferenceFocus(javax.sip.message.Message message)
        throws ParseException
    {
        ContactHeader contactHeader
            = (ContactHeader) message.getHeader(ContactHeader.NAME);

        if (contactHeader != null)
        {
            // we must set the value of the parameter as null
            // in order to avoid wrong generation of the tag - ';isfocus='
            // as it must be ';isfocus'
            if (getCall().isConferenceFocus())
                contactHeader.setParameter("isfocus", null);
            else
                contactHeader.removeParameter("isfocus");
        }
    }
    /**
     * Registers a specific <tt>MethodProcessorListener</tt> with this
     * <tt>CallPeer</tt> so that it gets notified by this instance about the
     * processing of SIP signaling. If the specified <tt>listener</tt> is
     * already registered with this instance, does nothing
     *
     * @param listener the <tt>MethodProcessorListener</tt> to be registered
     * with this <tt>CallPeer</tt> so that it gets notified by this instance
     * about the processing of SIP signaling
     */
    void addMethodProcessorListener(MethodProcessorListener listener)
    {
        if (listener == null)
            throw new NullPointerException("listener");

        synchronized (methodProcessorListeners)
        {
            if (!methodProcessorListeners.contains(listener))
                methodProcessorListeners.add(listener);
        }
    }

    /**
     * Notifies the <tt>MethodProcessorListener</tt>s registered with this
     * <tt>CallPeer</tt> that it has processed a specific SIP <tt>Request</tt>
     * by sending a specific SIP <tt>Response</tt>.
     *
     * @param request the SIP <tt>Request</tt> processed by this
     * <tt>CallPeer</tt>
     * @param response the SIP <tt>Response</tt> this <tt>CallPeer</tt> sent as
     * part of its processing of the specified <tt>request</tt>
     */
    protected void fireRequestProcessed(Request request, Response response)
    {
        Iterable<MethodProcessorListener> listeners;

        synchronized (methodProcessorListeners)
        {
            listeners
                = new LinkedList<MethodProcessorListener>(
                        methodProcessorListeners);
        }

        for (MethodProcessorListener listener : listeners)
            listener.requestProcessed(this, request, response);
    }

    /**
     * Notifies the <tt>MethodProcessorListener</tt>s registered with this
     * <tt>CallPeer</tt> that it has processed a specific SIP <tt>Response</tt>
     * by sending a specific SIP <tt>Request</tt>.
     *
     * @param response the SIP <tt>Response</tt> processed by this
     * <tt>CallPeer</tt>
     * @param request the SIP <tt>Request</tt> this <tt>CallPeer</tt> sent as
     * part of its processing of the specified <tt>response</tt>
     */
    protected void fireResponseProcessed(Response response, Request request)
    {
        Iterable<MethodProcessorListener> listeners;

        synchronized (methodProcessorListeners)
        {
            listeners
                = new LinkedList<MethodProcessorListener>(
                        methodProcessorListeners);
        }

        for (MethodProcessorListener listener : listeners)
            listener.responseProcessed(this, response, request);
    }

    /**
     * Unregisters a specific <tt>MethodProcessorListener</tt> from this
     * <tt>CallPeer</tt> so that it no longer gets notified by this instance
     * about the processing of SIP signaling. If the specified <tt>listener</tt>
     * is not registered with this instance, does nothing.
     *
     * @param listener the <tt>MethodProcessorListener</tt> to be unregistered
     * from this <tt>CallPeer</tt> so that it no longer gets notified by this
     * instance about the processing of SIP signaling
     */
    void removeMethodProcessorListener(MethodProcessorListener listener)
    {
        if (listener != null)
            synchronized (methodProcessorListeners)
            {
                methodProcessorListeners.remove(listener);
            }
    }

    /**
     * Requests a (video) key frame from this remote peer of the associated.
     *
     * @return <tt>true</tt> if a key frame has indeed been requested from this
     * remote peer in response to the call; otherwise, <tt>false</tt>
     */
    private boolean requestKeyFrame()
    {
        boolean requested = false;

        if (sendPictureFastUpdate)
        {
            try
            {
                pictureFastUpdate();
                requested = true;
            }
            catch (OperationFailedException ofe)
            {
                /*
                 * Apart from logging, it does not seem like there are a lot of
                 * ways to handle it.
                 */
            }
        }
        return requested;
    }

    /**
     * Updates this call so that it would record a new transaction and dialog
     * that have been recreated because of a re-authentication.
     *
     * @param retryTran the new transaction
     */
    public void handleAuthenticationChallenge(ClientTransaction retryTran)
    {
        // There is a new dialog that will be started with this request. Get
        // that dialog and record it into the Call object for later use (by
        // BYEs for example).
        // if the request was BYE then we need to authorize it anyway even
        // if the call and the call peer are no longer there
        setDialog(retryTran.getDialog());
        setLatestInviteTransaction(retryTran);
        setJainSipProvider(jainSipProvider);
    }

    /**
     * Causes this CallPeer to enter either the DISCONNECTED or the FAILED
     * state.
     *
     * @param failed indicates if the disconnection is due to a failure
     * @param reason the reason of the disconnection
     */
    private void setDisconnectedState(boolean failed, String reason)
    {
        if (failed)
            setState(CallPeerState.FAILED, reason);
        else
            setState(CallPeerState.DISCONNECTED, reason);
    }

    /**
     * {@inheritDoc}
     */
    public String getEntity()
    {
        return AbstractOperationSetTelephonyConferencing
                .stripParametersFromAddress(getURI());
    }

    /**
     * {@inheritDoc}
     *
     * Uses the direction of the media stream as a fallback.
     * TODO: return the direction negotiated via SIP
     */
    @Override
    public MediaDirection getDirection(MediaType mediaType)
    {
        MediaStream stream = getMediaHandler().getStream(mediaType);
        if (stream != null)
        {
            MediaDirection direction = stream.getDirection();
            return direction == null
                    ? MediaDirection.INACTIVE
                    : direction;
        }

        return MediaDirection.INACTIVE;
    }
}