text:
namespace device {

namespace {

void CopyToWebUString(blink::WebUChar* dest,
                      size_t dest_length,
                      base::string16 src) {
  static_assert(sizeof(base::string16::value_type) == sizeof(blink::WebUChar),
                "Mismatched string16/WebUChar size.");

  const size_t str_to_copy = std::min(src.size(), dest_length - 1);
  memcpy(dest, src.data(), str_to_copy * sizeof(base::string16::value_type));
  dest[str_to_copy] = 0;
}

}  // namespace

using namespace blink;

GvrGamepadDataFetcher::Factory::Factory(GvrDelegate* delegate,
                                        unsigned int display_id)
    : delegate_(delegate), display_id_(display_id) {}

GvrGamepadDataFetcher::Factory::~Factory() {}

std::unique_ptr<GamepadDataFetcher>
GvrGamepadDataFetcher::Factory::CreateDataFetcher() {
  if (!delegate_)
    return nullptr;
  return base::MakeUnique<GvrGamepadDataFetcher>(delegate_, display_id_);
}

GamepadSource GvrGamepadDataFetcher::Factory::source() {
  return GAMEPAD_SOURCE_GVR;
}

GvrGamepadDataFetcher::GvrGamepadDataFetcher(GvrDelegate* delegate,
                                             unsigned int display_id)
    : display_id_(display_id) {
  gvr::GvrApi* gvr_api = delegate->gvr_api();
  controller_api_.reset(new gvr::ControllerApi());
  int32_t options = gvr::ControllerApi::DefaultOptions();
  options |= GVR_CONTROLLER_ENABLE_GYRO;
  bool success = controller_api_->Init(options, gvr_api->GetContext());
  if (!success)
    controller_api_.reset(nullptr);

  // TODO(bajones): Monitor changes to the controller handedness.
  handedness_ = gvr_api->GetUserPrefs().GetControllerHandedness();
}

GvrGamepadDataFetcher::~GvrGamepadDataFetcher() {}

GamepadSource GvrGamepadDataFetcher::source() {
  return GAMEPAD_SOURCE_GVR;
}

void GvrGamepadDataFetcher::OnAddedToProvider() {
  PauseHint(false);
}

void GvrGamepadDataFetcher::GetGamepadData(bool devices_changed_hint) {
  if (!controller_api_)
    return;

  PadState* state = GetPadState(0);
  if (!state)
    return;

  WebGamepad& pad = state->data;
  if (state->active_state == GAMEPAD_NEWLY_ACTIVE) {
    // This is the first time we've seen this device, so do some one-time
    // initialization
    pad.connected = true;
    CopyToWebUString(pad.id, WebGamepad::idLengthCap,
                     base::UTF8ToUTF16("Daydream Controller"));
    CopyToWebUString(pad.mapping, WebGamepad::mappingLengthCap,
                     base::UTF8ToUTF16(""));
    pad.buttonsLength = 1;
    pad.axesLength = 2;

    pad.displayId = display_id_;

    pad.hand = (handedness_ == GVR_CONTROLLER_RIGHT_HANDED) ? GamepadHandRight
                                                            : GamepadHandLeft;
  }

  controller_state_.Update(*controller_api_);

  pad.timestamp = controller_state_.GetLastOrientationTimestamp();

  if (controller_state_.IsTouching()) {
    gvr_vec2f touch_position = controller_state_.GetTouchPos();
    pad.axes[0] = (touch_position.x * 2.0f) - 1.0f;
    pad.axes[1] = (touch_position.y * 2.0f) - 1.0f;
  } else {
    pad.axes[0] = 0.0f;
    pad.axes[1] = 0.0f;
  }

  pad.buttons[0].touched = controller_state_.IsTouching();
  pad.buttons[0].pressed =
      controller_state_.GetButtonState(GVR_CONTROLLER_BUTTON_CLICK);
  pad.buttons[0].value = pad.buttons[0].pressed ? 1.0f : 0.0f;

  pad.pose.notNull = true;
  pad.pose.hasOrientation = true;
  pad.pose.hasPosition = false;

  gvr_quatf orientation = controller_state_.GetOrientation();
  pad.pose.orientation.notNull = true;
  pad.pose.orientation.x = orientation.qx;
  pad.pose.orientation.y = orientation.qy;
  pad.pose.orientation.z = orientation.qz;
  pad.pose.orientation.w = orientation.qw;

  gvr_vec3f accel = controller_state_.GetAccel();
  pad.pose.linearAcceleration.notNull = true;
  pad.pose.linearAcceleration.x = accel.x;
  pad.pose.linearAcceleration.y = accel.y;
  pad.pose.linearAcceleration.z = accel.z;

  gvr_vec3f gyro = controller_state_.GetGyro();
  pad.pose.angularVelocity.notNull = true;
  pad.pose.angularVelocity.x = gyro.x;
  pad.pose.angularVelocity.y = gyro.y;
  pad.pose.angularVelocity.z = gyro.z;
}

void GvrGamepadDataFetcher::PauseHint(bool paused) {
  if (!controller_api_)
    return;

  if (paused) {
    controller_api_->Pause();
  } else {
    controller_api_->Resume();
  }
}

}  // namespace device


text:
from nussl import ml, datasets
import tempfile
from torch import optim
import numpy as np
import logging
import os
import torch

# uncomment if you want to see the trainer/engine logs
logging.basicConfig(
    format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d:%H:%M:%S',
    level=logging.INFO
)

fix_dir = 'tests/local/trainer'

def test_create_engine(mix_source_folder):
    # load dataset with transforms
    tfms = datasets.transforms.Compose([
        datasets.transforms.PhaseSensitiveSpectrumApproximation(),
        datasets.transforms.ToSeparationModel(),
        datasets.transforms.Cache(os.path.join(fix_dir, 'cache'))])
    dataset = datasets.MixSourceFolder(
        mix_source_folder, transform=tfms)

    # create the model, based on the first item in the dataset
    # second bit of the shape is the number of features
    n_features = dataset[0]['mix_magnitude'].shape[1]
    mi_config = ml.networks.builders.build_recurrent_mask_inference(
        n_features, 50, 2, True, 0.3, 2, 'softmax',
    )

    model = ml.SeparationModel(mi_config)
    # create optimizer
    optimizer = optim.Adam(model.parameters(), lr=1e-3)

    # dummy function for processing a batch through the model
    def train_batch(engine, data):
        loss = -engine.state.iteration
        return {'loss': loss}

    # building the training and validation engines and running them
    # the validation engine runs within the training engine run
    with tempfile.TemporaryDirectory() as tmpdir:
        _dir = fix_dir if fix_dir else tmpdir
        # _dir = tmpdir
        trainer, validator = ml.train.create_train_and_validation_engines(
            train_batch, train_batch
        )

        # add handlers to engine
        ml.train.add_stdout_handler(trainer, validator)
        ml.train.add_validate_and_checkpoint(_dir, model, optimizer, dataset,
                                             trainer, dataset, validator,
                                             save_by_epoch=1)
        ml.train.add_tensorboard_handler(_dir, trainer, every_iteration=True)
        ml.train.add_progress_bar_handler(trainer)

        # run engine
        trainer.run(dataset, max_epochs=3)

        assert os.path.exists(trainer.state.output_folder)
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'latest.model.pth'))
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'best.model.pth'))
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'latest.optimizer.pth'))
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'best.optimizer.pth'))

        for i in range(1, 4):
            assert os.path.exists(os.path.join(
                trainer.state.output_folder, 'checkpoints',
                f'epoch{i}.model.pth')
            )

        assert len(trainer.state.epoch_history['train/loss']) == 3
        assert len(trainer.state.iter_history['loss']) == 10

        # try resuming
        model_path = os.path.join(
            trainer.state.output_folder, 'checkpoints', 'latest.model.pth')
        optimizer_path = os.path.join(
            trainer.state.output_folder, 'checkpoints', 'latest.optimizer.pth')

        opt_state_dict = torch.load(
            optimizer_path, map_location=lambda storage, loc: storage)
        state_dict = torch.load(
            model_path, map_location=lambda storage, loc: storage)

        optimizer.load_state_dict(opt_state_dict)
        model.load_state_dict(state_dict['state_dict'])

        # make sure the cache got removed in saved transforms bc it's not a portable
        # transform
        for t in state_dict['metadata']['train_dataset']['transforms'].transforms:
            assert not isinstance(t, datasets.transforms.Cache)

        new_trainer, new_validator = (
            ml.train.create_train_and_validation_engines(train_batch)
        )

        # add handlers to engine
        ml.train.add_stdout_handler(new_trainer)
        ml.train.add_validate_and_checkpoint(
            trainer.state.output_folder, model, optimizer, dataset,
            new_trainer)
        ml.train.add_tensorboard_handler(
            trainer.state.output_folder, new_trainer)

        new_trainer.load_state_dict(state_dict['metadata']['trainer.state_dict'])
        assert new_trainer.state.epoch == trainer.state.epoch
        new_trainer.run(dataset, max_epochs=3)

def test_trainer_data_parallel(mix_source_folder):
    # load dataset with transforms
    tfms = datasets.transforms.Compose([
        datasets.transforms.PhaseSensitiveSpectrumApproximation(),
        datasets.transforms.ToSeparationModel()])
    dataset = datasets.MixSourceFolder(
        mix_source_folder, transform=tfms)

    # create the model, based on the first item in the dataset
    # second bit of the shape is the number of features
    n_features = dataset[0]['mix_magnitude'].shape[1]
    mi_config = ml.networks.builders.build_recurrent_mask_inference(
        n_features, 50, 2, True, 0.3, 2, 'softmax',
    )

    model = ml.SeparationModel(mi_config)
    model = torch.nn.DataParallel(model)
    # create optimizer
    optimizer = optim.Adam(model.parameters(), lr=1e-3)

    # dummy function for processing a batch through the model
    def train_batch(engine, data):
        loss = np.random.rand()
        return {'loss': loss}

    # building the training and validation engines and running them
    # the validation engine runs within the training engine run
    with tempfile.TemporaryDirectory() as tmpdir:
        _dir = fix_dir if fix_dir else tmpdir
        trainer, validator = ml.train.create_train_and_validation_engines(
            train_batch, train_batch
        )

        # add handlers to engine
        ml.train.add_stdout_handler(trainer, validator)
        ml.train.add_validate_and_checkpoint(_dir, model, optimizer, dataset,
                                             trainer, dataset, validator)
        ml.train.add_tensorboard_handler(_dir, trainer)

        # run engine
        trainer.run(dataset, max_epochs=3)

        assert os.path.exists(trainer.state.output_folder)
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'latest.model.pth'))
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'best.model.pth'))
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'latest.optimizer.pth'))
        assert os.path.exists(os.path.join(
            trainer.state.output_folder, 'checkpoints', 'best.optimizer.pth'))

        assert len(trainer.state.epoch_history['train/loss']) == 3
        assert len(trainer.state.iter_history['loss']) == 10

def test_cache_dataset(mix_source_folder):
    with tempfile.TemporaryDirectory() as tmpdir:
        tfms = datasets.transforms.Compose([
            datasets.transforms.PhaseSensitiveSpectrumApproximation(),
            datasets.transforms.ToSeparationModel(),
        ])
        chc = datasets.transforms.Cache(
            os.path.join(tmpdir, 'cache'), overwrite=True)

        # no cache
        dataset = datasets.MixSourceFolder(
            mix_source_folder,
            transform=tfms)
        outputs_a = []

        for i in range(len(dataset)):
            outputs_a.append(dataset[i])

        # now add a cache
        tfms.transforms.append(chc)
        dataset = datasets.MixSourceFolder(
            mix_source_folder,
            transform=tfms,
            cache_populated=False)
        assert (
                tfms.transforms[-1].cache.nchunks_initialized == 0)

        ml.train.cache_dataset(dataset)
        assert (
                tfms.transforms[-1].cache.nchunks_initialized == len(dataset))

        # now make sure the cached stuff matches
        dataset.cache_populated = True
        outputs_b = []

        for i in range(len(dataset)):
            outputs_b.append(dataset[i])

        for _data_a, _data_b in zip(outputs_a, outputs_b):
            for key in _data_a:
                if torch.is_tensor(_data_a[key]):
                    assert torch.allclose(_data_a[key], _data_b[key])
                else:
                    assert _data_a[key] == _data_b[key]

def test_cache_dataset_with_dataloader(mix_source_folder):
    with tempfile.TemporaryDirectory() as tmpdir:
        tfms = datasets.transforms.Compose([
            datasets.transforms.PhaseSensitiveSpectrumApproximation(),
            datasets.transforms.ToSeparationModel(),
            datasets.transforms.Cache(
                os.path.join(tmpdir, 'cache'), overwrite=True),
            datasets.transforms.GetExcerpt(400)
        ])
        dataset = datasets.MixSourceFolder(
            mix_source_folder,
            transform=tfms,
            cache_populated=False)

        dataloader = torch.utils.data.DataLoader(
            dataset, shuffle=True, batch_size=2)

        ml.train.cache_dataset(dataloader)

        assert (
                tfms.transforms[-2].cache.nchunks_initialized == len(dataset))

redpajama_set_name: RedPajamaGithub


text:
enum lureTypes {JIG, SPINNER, PLUG, FLY, SOFTPLASTIC};

// Declare product base class
class Lure {
    public:
        static std::unique_ptr<Lure> setLure(lureTypes type, const std::string& char1, const std::string& char2, const std::string& char3);
        virtual void getLure() = 0;
};

// Declare derived product classes
class FactoryJig : public Lure {
    public:
        FactoryJig(std::string characteristic1, std::string characteristic2, std::string characteristic3);
        void getLure();
    private:
        // Jig characteristics
        std::string weight, head_type, trailer_type;
};

class Spinner : public Lure {
    public:
        Spinner(std::string characteristic1, std::string characteristic2, std::string characteristic3);
        void getLure();
    private:
        // Spinner characteristics
        std::string weight, blade_type, blade_pattern;
};

class FactoryPlug : public Lure {
    public:
        FactoryPlug(std::string characteristic1, std::string characteristic2, std::string characteristic3);
        void getLure();
    private:
        // Plug characteristics
        std::string length, plug_type, color_pattern;
};

class FactoryFly : public Lure {
    public:
        FactoryFly(std::string characteristic1, std::string characteristic2, std::string characteristic3);
        void getLure();
    private:
        // Fly characteristics
        std::string length, tied_pattern, color_pattern;
};

class SoftPlastic : public Lure {
    public:
        SoftPlastic(std::string characteristic1, std::string characteristic2, std::string characteristic3);
        void getLure();
    private:
        // Soft plastic characteristics
        std::string length, style, color_pattern;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="48dp"
    android:layout_marginBottom="48dp"
    android:overScrollMode="ifContentScrolls">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:orientation="vertical">

        <TextView android:id="@android:id/message"
            style="?android:attr/textAppearanceSmall"
            android:layout_marginBottom="48dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="?android:attr/textColorSecondary" />

        <NumberPicker
            android:id="@+id/numberPicker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"/>

    </LinearLayout>

</ScrollView>


text:
// +build CargoEntities

package CargoEntities

type Message interface{
	/** Method of Message **/

	/**
	 * Return the type name of an entity
	 */
	GetTypeName() string

	/**
	 * Get an entity's uuid
	 * Each entity must have one uuid.
	 */
	GetUuid() string
	SetUuid(uuid string)

	/**
	 * Return the array of entity id's without it uuid.
	 */
	Ids() []interface{}

	/**
	 * Get an entity's parent UUID if it have a parent.
	 */
	GetParentUuid() string
	SetParentUuid(uuid string)

	/**
	 * Get an entity's parent pointer.
	 */
	 GetParent() interface{}

	/**
	 * The name of the relation with it parent.
	 */
	GetParentLnk() string
	SetParentLnk(string)

	/**
	 * Return the list of reference UUID:FieldName where that entity is referenced.
	 */
	GetReferenced() []string

	/**
	 * Set a reference
	 */
	SetReferenced(uuid string, field string)

	/**
	 * Remove a reference.
	 */
	RemoveReferenced(uuid string, field string)

	/**
	 * Return link to entity childs.
	 */
	GetChilds() []interface{}

	/**
	 * Return list of childs uuid.
	 */
	GetChildsUuid() []string

	/**
	 * Set a given field
	 */
	SetFieldValue(field string, value interface{}) error
	/**
	 * Return the value of a given field
	 */
	GetFieldValue(field string) interface{}

	/**
	 * Set the function GetEntityByUuid as a pointer. The entity manager can't
	 * be access by Entities package...
	 */
	SetEntityGetter(func(uuid string) (interface{}, error))

	/** Use it the set the entity on the cache. **/
	SetEntitySetter(fct func(entity interface{}))

	/** Use that function to generate the entity UUID**/
	SetUuidGenerator(fct func(entity interface{}) string)

	/**
	 * Return true if the entity need to be saved.
	 */
	IsNeedSave() bool

	/**
	 * Set the needsave value.
	 */
	SetNeedSave(needsave bool)

GetBody()string
SetBody(val string)

}


text:
package org.apache.batik.css.engine;

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * An interface for listeners of CSSNavigableDocument events.  The
 * events parallel the DOM events, but apply to the CSS view of
 * the tree rather than the actual DOM tree.
 *
 * @author Cameron McCormack
 * @version $Id$
 */
public interface CSSNavigableDocumentListener {

    /**
     * A node has been inserted into the CSSNavigableDocument tree.
     */
    void nodeInserted(Node newNode);

    /**
     * A node is about to be removed from the CSSNavigableDocument tree.
     */
    void nodeToBeRemoved(Node oldNode);

    /**
     * A subtree of the CSSNavigableDocument tree has been modified
     * in some way.
     */
    void subtreeModified(Node rootOfModifications);

    /**
     * Character data in the CSSNavigableDocument tree has been modified.
     */
    void characterDataModified(Node text);

    /**
     * An attribute has changed in the CSSNavigableDocument.
     */
    void attrModified(Element e, Attr attr, short attrChange,
                      String prevValue, String newValue);

    /**
     * The text of the override style declaration for this element has been
     * modified.
     */
    void overrideStyleTextChanged(CSSStylableElement e, String text);

    /**
     * A property in the override style declaration has been removed.
     */
    void overrideStylePropertyRemoved(CSSStylableElement e, String name);

    /**
     * A property in the override style declaration has been changed.
     */
    void overrideStylePropertyChanged(CSSStylableElement e, String name,
                                      String val, String prio);
}


text:
package måndag;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;

public class FrogGUI extends JFrame {

	private JPanel contentPane;
	private JTextField txtText;
	private Frog[] myFrogs;
	private ArrayList<Frog> FrogArmy = new ArrayList<Frog>();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FrogGUI frame = new FrogGUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public FrogGUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 693, 437);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		/*
		Frog frog1 = new Frog(12, "k3larra", 5);
		String frog1Name = frog1.getName();
		int frog1Age = frog1.getAge();
		int frog1Size = frog1.getSize();
		*/

		myFrogs = new Frog[3];

		myFrogs[0] = new Frog(34, "Bertil", 234);
		myFrogs[1] = new Frog(23, "Göran", 76);
		myFrogs[2] = new Frog(5, "Martin", 14);

		for (int i = 0; i < 100; i++){
			FrogArmy.add(new Frog(10, "grodsoldat", 20));
		}

		txtText = new JTextField();
		txtText.setText(frogNames);
		txtText.setBounds(137, 77, 367, 230);
		contentPane.add(txtText);
		txtText.setColumns(10);

		for(int i = 0; i < myFrogs.length; i++){
			frogNames = myFrogs[i].getName();
		}

	}
}


text:
package com.navercorp.pinpoint.plugin.akka.http.interceptor;

import akka.http.javadsl.server.Complete;
import com.navercorp.pinpoint.bootstrap.context.AsyncContext;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.common.trace.AnnotationKey;
import com.navercorp.pinpoint.plugin.akka.http.AkkaHttpConstants;
import scala.Option;
import scala.concurrent.Future;
import scala.util.Failure;
import scala.util.Success;

public class RequestContextImplCompleteInterceptor extends AsyncContextSpanEventEndPointInterceptor {

    public RequestContextImplCompleteInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
        super(traceContext, methodDescriptor);
    }

    @Override
    protected void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
    }

    @Override
    protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
        try {
            if (result instanceof Future && ((Future) result).isCompleted()) {
                Option value = ((Future) result).value();
                if (value == null) {
                    return;
                }

                Object routeResult = value.get();
                if (routeResult instanceof Success) {
                    Object success = ((Success) routeResult).get();
                    if (success instanceof Complete) {
                        akka.http.javadsl.model.HttpResponse response = ((Complete) success).getResponse();
                        if (response == null) {
                            return;
                        }
                        akka.http.javadsl.model.StatusCode status = response.status();
                        if (status == null) {
                            return;
                        }
                        recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, status.intValue());
                    }
                } else if (routeResult instanceof Failure) {
                    Throwable failure = ((Failure) routeResult).exception();
                    recorder.recordException(failure);
                }
            }
        } finally {
            recorder.recordApi(methodDescriptor);
            recorder.recordServiceType(AkkaHttpConstants.AKKA_HTTP_SERVER_INTERNAL);
            recorder.recordException(throwable);
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Other Classes: Class  EncodingInfo
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.xml.serialize

Class  EncodingInfo

java.lang.Object
  |
  +--org.apache.xml.serialize.EncodingInfo

Deprecated. This class was deprecated in Xerces 2.9.0. It is recommended
 that new applications use the DOM Level 3 LSSerializer or JAXP's Transformation
 API for XML (TrAX) for serializing XML. See the Xerces documentation for more
 information.

public class EncodingInfo
extends java.lang.Object

This class represents an encoding.

Version:
$Id: EncodingInfo.java 699892 2008-09-28 21:08:27Z mrglavas $

Constructor Summary

EncodingInfo(java.lang.String ianaName,
             java.lang.String javaName,
             int lastPrintable)

          Deprecated. Creates new EncodingInfo instance.

Method Summary

 java.lang.String
getIANAName()

          Deprecated. Returns a MIME charset name of this encoding.

 java.io.Writer
getWriter(java.io.OutputStream output)

          Deprecated. Returns a writer for this encoding based on
 an output stream.

 boolean
isPrintable(char ch)

          Deprecated. Checks whether the specified character is printable or not in this encoding.

static void
testJavaEncodingName(java.lang.String name)

          Deprecated.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

EncodingInfo

public EncodingInfo(java.lang.String ianaName,
                    java.lang.String javaName,
                    int lastPrintable)

Deprecated.
Creates new EncodingInfo instance.

Method Detail

getIANAName

public java.lang.String getIANAName()

Deprecated.
Returns a MIME charset name of this encoding.

getWriter

public java.io.Writer getWriter(java.io.OutputStream output)
                         throws java.io.UnsupportedEncodingException

Deprecated.
Returns a writer for this encoding based on
 an output stream.

Returns:
A suitable writer
Throws:
java.io.UnsupportedEncodingException - There is no convertor
  to support this encoding

isPrintable

public boolean isPrintable(char ch)

Deprecated.
Checks whether the specified character is printable or not in this encoding.

Parameters:
ch - a code point (0-0x10ffff)

testJavaEncodingName

public static void testJavaEncodingName(java.lang.String name)
                                 throws java.io.UnsupportedEncodingException

Deprecated.

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
set -x
set -e

# deactivate circleci virtualenv and setup a miniconda env instead
if [[ `type -t deactivate` ]]; then
    deactivate
fi

wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \
     -O miniconda.sh
chmod +x miniconda.sh && ./miniconda.sh -b -p $MINICONDA_PATH
export PATH="$MINICONDA_PATH/bin:$PATH"
conda update --yes --quiet conda

conda create -n $CONDA_ENV_NAME --yes --quiet python=3
source activate $CONDA_ENV_NAME

conda install --yes --quiet pip numpy sphinx=1.6.3 matplotlib pillow dask distributed
pip install sphinx-gallery numpydoc lz4

python setup.py develop

make doc 2>&1


text:
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NBitcoin.Formatters
{
    internal abstract class RawFormatter
    {
        public Network Network { get; set; }

        protected RawFormatter(Network network)
        {
            this.Network = network;
        }

        protected abstract void BuildTransaction(JObject json, Transaction tx);
        protected abstract void WriteTransaction(JsonTextWriter writer, Transaction tx);

        public Transaction ParseJson(string str)
        {
            JObject obj = JObject.Parse(str);

            return Parse(obj);
        }

        [Obsolete("Use RawFormatter.ParseJson method instead")]
        public Transaction Parse(string str)
        {
            JObject obj = JObject.Parse(str);
            return Parse(obj);
        }

        public Transaction Parse(JObject obj)
        {
            var tx = new Transaction();
            BuildTransaction(obj, tx);
            return tx;
        }

        protected void WritePropertyValue<TValue>(JsonWriter writer, string name, TValue value)
        {
            writer.WritePropertyName(name);
            writer.WriteValue(value);
        }

        public string ToString(Transaction transaction)
        {
            var strWriter = new StringWriter();
            var jsonWriter = new JsonTextWriter(strWriter);
            jsonWriter.Formatting = Formatting.Indented;

            jsonWriter.WriteStartObject();
            WriteTransaction(jsonWriter, transaction);
            jsonWriter.WriteEndObject();

            jsonWriter.Flush();
            return strWriter.ToString();
        }
    }
}


text:
package com.gl.fsm2.core;

import com.gl.fsm2.core.state.State;
import com.gl.fsm2.core.transition.Transition;

public abstract class TransitionCalculator {

	public TransitionCalculator() {
		super();
	}

	public abstract Transition calculate(StateContext ctx);

	public Transition findTransition(State state, String transitionCode) {
		Transition t = state.findTransition(transitionCode);
		if(t == null) {
			throw new IllegalStateException("None potential transition found for "+state + " - "+transitionCode);
		}

		return t;
	}

}


text:
<?php

// Initialize mno_settings variable
$mno_settings = new MnoSettings();

// Require Config files
require MAESTRANO_ROOT . '/app/config/1_app.php';
require MAESTRANO_ROOT . '/app/config/2_maestrano.php';

// Configure Maestrano Service
MaestranoService::configure($mno_settings);


text:
<?php

namespace Alius\Database\MySQL;

use Alius\Database\Exceptions;
use PHPUnit\Framework\TestCase;

class DecimalColumnTest extends TestCase
{
    public function testDecimal()
    {
        $column = new DecimalColumn('foo', 10, 2);
        $this->assertSame('foo', $column->getName());
        $this->assertSame('decimal', $column->getType());
        $this->assertSame(10, $column->getPrecision());
        $this->assertSame(2, $column->getScale());
        $this->assertSame(false, $column->isUnsigned());
        $this->assertSame(false, $column->isNullable());
        $this->assertSame(false, $column->hasDefault());
        $this->assertSame(null, $column->getDefault());
        $this->assertSame(false, $column->hasComment());
        $this->assertSame('', $column->getComment());
        $this->assertSame('`foo` decimal(10,2) NOT NULL', $column->buildCreate());
        $this->assertSame('DROP COLUMN `foo`', $column->buildDrop());
        $this->assertSame('ADD COLUMN `foo` decimal(10,2) NOT NULL', $column->buildAdd());
        $this->assertSame('ADD COLUMN `foo` decimal(10,2) NOT NULL AFTER `bar`', $column->buildAdd(Column::int('bar')));
        $this->assertSame('CHANGE COLUMN `bar` `foo` decimal(10,2) NOT NULL', $column->buildChange(Column::int('bar')));

        // unsigned
        $column = new DecimalColumn('foo', 10, 2);
        $column->setUnsigned();
        $this->assertSame(true, $column->isUnsigned());
        $this->assertSame('`foo` decimal(10,2) UNSIGNED NOT NULL', $column->buildCreate());

        // unsigned + nullable
        $column->setNullable();
        $this->assertSame('`foo` decimal(10,2) UNSIGNED', $column->buildCreate());

        // unsigned + nullable + default
        $column->setDefault(1);
        $this->assertSame('`foo` decimal(10,2) UNSIGNED DEFAULT "1.00"', $column->buildCreate());

        // unsigned + nullable + default + comment
        $column->setComment('foobar');
        $this->assertSame('`foo` decimal(10,2) UNSIGNED DEFAULT "1.00" COMMENT "foobar"', $column->buildCreate());

        // unsigned + default
        $column = new DecimalColumn('foo', 10, 2);
        $column->setUnsigned()->setDefault(1);
        $this->assertSame('`foo` decimal(10,2) UNSIGNED NOT NULL DEFAULT "1.00"', $column->buildCreate());

        // unsigned + default + comment
        $column->setComment('foobar');
        $this->assertSame('`foo` decimal(10,2) UNSIGNED NOT NULL DEFAULT "1.00" COMMENT "foobar"', $column->buildCreate());

        // unsigned + comment
        $column = new DecimalColumn('foo', 10, 2);
        $column->setUnsigned()->setComment('foobar');
        $this->assertSame('`foo` decimal(10,2) UNSIGNED NOT NULL COMMENT "foobar"', $column->buildCreate());

        // nullable
        $column = new DecimalColumn('foo', 10, 2);
        $column->setNullable();
        $this->assertSame(true, $column->isNullable());
        $this->assertSame('`foo` decimal(10,2)', $column->buildCreate());

        // nullable + default
        $column->setDefault(1);
        $this->assertSame('`foo` decimal(10,2) DEFAULT "1.00"', $column->buildCreate());

        // nullable + default + comment
        $column->setComment('foobar');
        $this->assertSame('`foo` decimal(10,2) DEFAULT "1.00" COMMENT "foobar"', $column->buildCreate());

        // nullable + comment
        $column = new DecimalColumn('foo', 10, 2);
        $column->setNullable()->setComment('foobar');
        $this->assertSame('`foo` decimal(10,2) COMMENT "foobar"', $column->buildCreate());

        // default
        $column = new DecimalColumn('foo', 10, 4);
        $column->setDefault(1.12345);
        $this->assertSame(1.12345, $column->getDefault());
        $this->assertSame('`foo` decimal(10,4) NOT NULL DEFAULT "1.1235"', $column->buildCreate());

        $column = new DecimalColumn('foo', 10, 4);
        $column->setDefault(1);
        $this->assertSame(true, $column->hasDefault());
        $this->assertSame(1.0, $column->getDefault());
        $this->assertSame('`foo` decimal(10,4) NOT NULL DEFAULT "1.0000"', $column->buildCreate());

        // default + comment
        $column->setComment('foobar');
        $this->assertSame('`foo` decimal(10,4) NOT NULL DEFAULT "1.0000" COMMENT "foobar"', $column->buildCreate());

        // comment
        $column = new DecimalColumn('foo', 10, 2);
        $column->setComment('foobar');
        $this->assertSame(true, $column->hasComment());
        $this->assertSame('foobar', $column->getComment());
        $this->assertSame('`foo` decimal(10,2) NOT NULL COMMENT "foobar"', $column->buildCreate());
    }

    public function testCheck()
    {
        $column = new DecimalColumn('foo', 10, 2);
        $this->assertSame(null, $column->check(null));
        $this->assertSame(null, $column->check(''));

        $this->assertSame(1.0, $column->check(true));
        $this->assertSame(1.0, $column->check(1.0));
        $this->assertSame(1.0, $column->check(1));
        $this->assertSame(1.0, $column->check('1'));
    }

    public function testPrecisionAndScale()
    {
        for ($precision = 1; $precision <= 65; $precision++) {
            for ($scale = 0; $scale <= 30; $scale++) {
                if ($precision > $scale) {
                    $column = new DecimalColumn('foo', $precision, $scale);
                    $this->assertSame($precision, $column->getPrecision());
                    $this->assertSame($scale, $column->getScale());
                    $this->assertSame(sprintf('`foo` decimal(%d,%d) NOT NULL', $precision, $scale), $column->buildCreate());
                }
            }
        }
    }

    public function testPrecisionMin()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_PRECISION);

        $column = new DecimalColumn('foo', 0, 0);
    }

    public function testPrecisionMax()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_PRECISION);

        $column = new DecimalColumn('foo', 66, 0);
    }

    public function testScaleMin()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_SCALE);

        $column = new DecimalColumn('foo', 65, -1);
    }

    public function testScaleMax()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_SCALE);

        $column = new DecimalColumn('foo', 65, 31);
    }

    public function testScaleLargerThanPrecision()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_SCALE_MAX);

        $column = new DecimalColumn('foo', 10, 11);
    }

    public function testCheckSignedMin()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_VALUE_MIN);

        $column = new DecimalColumn('foo', 10, 2);
        $this->assertSame(-100000000.0, $column->getMin());
        $column->check(-100000000);
    }

    public function testCheckSignedMax()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_VALUE_MAX);

        $column = new DecimalColumn('foo', 10, 2);
        $this->assertSame(100000000.0, $column->getMax());
        $column->check(100000000);
    }

    public function testCheckNotFloat()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_VALUE);

        $column = new DecimalColumn('foo', 10, 2);
        $column->check('bar');
    }

    public function testDefaultSignedMin()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_VALUE_MIN);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setDefault(-100000000);
    }

    public function testDefaultSignedMax()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_VALUE_MAX);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setDefault(100000000);
    }

    public function testDefaultNotFloat()
    {
        $this->expectException(Exceptions\SchemaException::class);
        $this->expectExceptionCode(Exceptions\SchemaException::COLUMN_FLOAT_INVALID_VALUE);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setDefault('bar');
    }

    public function testSetNullableImmutable()
    {
        $this->expectException(Exceptions\LogicException::class);
        $this->expectExceptionCode(Exceptions\LogicException::IMMUTABLE);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setImmutable();
        $column->setNullable();
    }

    public function testSetDefaultImmutable()
    {
        $this->expectException(Exceptions\LogicException::class);
        $this->expectExceptionCode(Exceptions\LogicException::IMMUTABLE);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setImmutable();
        $column->setDefault('bar');
    }

    public function testSetCommentImmutable()
    {
        $this->expectException(Exceptions\LogicException::class);
        $this->expectExceptionCode(Exceptions\LogicException::IMMUTABLE);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setImmutable();
        $column->setComment('bar');
    }

    public function testSetUnsignedImmutable()
    {
        $this->expectException(Exceptions\LogicException::class);
        $this->expectExceptionCode(Exceptions\LogicException::IMMUTABLE);

        $column = new DecimalColumn('foo', 10, 2);
        $column->setImmutable();
        $column->setUnsigned();
    }
}


text:
export class KeyUpEventArgs implements nullstone.IEventArgs {

    public KeyUp: number;

    constructor (keyUp: number) {
        Object.defineProperty(this, 'KeyUp', { value: keyUp, writable: false });
    }
}


text:
<?php

namespace AirSim\Bundle\SocialNetworkBundle\Controller;

use AirSim\Bundle\CoreBundle\Security\PrivilegeChecker;
use AirSim\Bundle\CoreBundle\Services\FileService;
use AirSim\Bundle\CoreBundle\Services\WallService;
use AirSim\Bundle\SocialNetworkBundle\Utils\ResponseBuilder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Response;

use AirSim\Bundle\CoreBundle\Services\PhotoService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AirSim\Bundle\CoreBundle\Services\UserService;
use AirSim\Bundle\CoreBundle\Tools\Constants;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class UserController extends Controller
{
    public function userAction($username)
    {
        $LOG = $this->get('logger');
        $LOG->info('userAction executed in UserController');

        $request = $this->get('request_stack')->getCurrentRequest();
        $session = $request->getSession();
        $sessionData = $session->get('sessionData');
        $userId = $session->get('sessionData')['userInfo']['id'];

        $userService = UserService::getInstance();
        $contactId = $userService->getUserIdByUsername($username);
        $userCompleteData = $userService->getUserData($contactId);
        $lastContacts = $userService->getUserFriends($contactId, null, Constants::LAST_CONTACTS_LIMIT);

        $privilegeChecker = PrivilegeChecker::getInstance();
        $userPrivileges = $privilegeChecker->getUserPrivileges($userId, $contactId);

        $photosService = PhotoService::getInstance();
        $lastPhotos = $photosService->getUserPhotos($contactId, null, Constants::LAST_PHOTOS_LIMIT);

        $wallService = WallService::getInstance();
        $wallRecords = $wallService->getWallRecords($contactId, 0, Constants::WALL_RECORDS_LIMIT);

        $randomContacts = $userService->getUserFriends($contactId, null, Constants::RANDOM_CONTACTS_LIMIT, true);

        return $this->render('AirSimSocialNetworkBundle:blue/User:user.html.twig', array('userData' => $userCompleteData,
            'lastContacts' => $lastContacts, 'lastPhotos' => $lastPhotos, 'wallRecords' => $wallRecords,
            'randomContacts' => $randomContacts, 'userPrivileges' => $userPrivileges));
    }

    /* ***** AJAX Calls ***** */
    public function getPhotoDataAction()
    {
        $LOG = $this->get('logger');
        $LOG->info('getPhotoDataAction executed in UserController');

        $error = '';
        $success = true;
        $response = '';

        $request = $this->get('request_stack')->getCurrentRequest();
        $session = $request->getSession();
        $sessionData = $session->get('sessionData');
        $photoId = $request->get('photoId');
        $userId = $session->get('sessionData')['userInfo']['id'];

        $photosService = PhotoService::getInstance();
        $photoDTO = $photosService->getPhotoDTO($photoId, null, Constants::PHOTO_COMMENTS_LIMIT, $userId);

        $response = array('success' => $success, 'error' => $error, 'data' => array("photoData" => $photoDTO->expose()));

        return new Response(json_encode($response));
    }

    public function addWallRecordAction()
    {
        $LOG = $this->get('logger');
        $LOG->info('addWallRecord executed in UserController');

        $error = '';
        $success = true;
        $response = '';

        $request = $this->get('request_stack')->getCurrentRequest();
        $session = $request->getSession();
        $sessionData = $session->get('sessionData');
        $page = $request->get('page');
        $receiverId = $request->get('receiverId');
        $authorId = $session->get('sessionData')['userInfo']['id'];
        $text = $request->get('text');
        $attachedPictures = $request->get('attachedPictures');

        $wallService = WallService::getInstance();
        $addedWallRecord = $wallService->addWallRecord($receiverId, $authorId, $text, $attachedPictures);

        // TODO: Add localization
        $notificationInfo = 'User %s %s has sent you a message!';
        $notificationInfoFormatted = sprintf($notificationInfo, $sessionData['userInfo']['firstName'],
            $sessionData['userInfo']['lastName']);

        $eventData = array
        (
            'success' => $success,
            'page' => $page,
            'event' => 'addWallRecord',
            'messageText' => $text,
            'recordDate' => $addedWallRecord['wallRecord']->getDateAdded()->format('d/m/Y'),
            'recordTime' => $addedWallRecord['wallRecord']->getDateAdded()->format('H:i'),
            'newWallRecordId' => $addedWallRecord['wallRecord']->getWallRecId(),
            'wallRecordPictures' => $addedWallRecord['wallRecordPictures'],
            'notificationInfo' => $notificationInfoFormatted
        );

        $response = ResponseBuilder::BuildResponse(null, null, $receiverId, null, $eventData, $session->get('sessionData'));

        return new Response(json_encode($response));

    }

    public function uploadTmpImagesAction()
    {
        $success = true;
        $error = '';
        $imagesValidFormats = explode(', ', Constants::IMAGES_VALID_FORMATS);

        $request = $this->get('request_stack')->getCurrentRequest();
        $receiverId = $request->get('receiverId');

        $picturesToBeUploaded = $request->files->get('wall_record_attached_images');
        $uploadedPictures = array();
        if(sizeof($picturesToBeUploaded) > 0)
        {
            $fileService = FileService::getInstance();
            $uploadedPictures = $fileService->uploadFiles($picturesToBeUploaded, $imagesValidFormats, Constants::TMP_FILES_DIRECTORY_PATH,
                $receiverId);
        }

        $response = array
        (
            'success' => $success,
            'uploadedPictures' => $uploadedPictures
        );

        return new Response(json_encode($response));
    }

    public function deleteTmpImageAction()
    {
        $success = true;
        $error = '';

        $request = $this->get('request_stack')->getCurrentRequest();
        $pictureToBeDeleted = $request->get('imageToDelete');

        $fileService = FileService::getInstance();
        $fileService->deleteFile(Constants::TMP_FILES_DIRECTORY_PATH.$pictureToBeDeleted);

        $response = array
        (
            'success' => $success
        );

        return new Response(json_encode($response));
    }

    public function likeDislikeWallRecordAction()
    {
        $success = true;
        $error = '';
        $response = '';

        $request = $this->get('request_stack')->getCurrentRequest();
        $session = $request->getSession();
        $sessionData = $session->get('sessionData');
        $page = $request->get('page');
        $action = $request->get('action');
        $receiverId = $request->get('receiverId');
        $wallRecordId = $request->get('wallRecordId');
        $senderId = $session->get('sessionData')['userInfo']['id'];

        $wallService = WallService::getInstance();
        $likeData = $wallService->likeDislikeWallRecord($wallRecordId, $senderId, $action);

        // TODO: Add localization
        $likedOrDisliked = $likeData['hasLiked'] ? 'liked' : 'disliked';
        $notificationInfo = 'User %s %s has '.$likedOrDisliked.' your wall record!';
        $notificationInfoFormatted = sprintf($notificationInfo, $sessionData['userInfo']['firstName'],
            $sessionData['userInfo']['lastName']);

        $eventData = array
        (
            'success' => $success,
            'page' => $page,
            'event' => 'likeDislikeWallRecord',
            'messageText' => '',
            'hasLiked' => $likeData['hasLiked'],
            'hasRecord' => $likeData['hasRecord'],
            'likeStatus' => $likeData['likeStatus'],
            'wallRecordId' => $wallRecordId,
            'notificationInfo' => $notificationInfoFormatted
        );

        $response = ResponseBuilder::BuildResponse(null, null, $receiverId, null, $eventData, $session->get('sessionData'));

        return new Response(json_encode($response));
    }

    public function replyToWallRecordAction()
    {
        $success = true;
        $error = '';
        $response = '';

        $request = $this->get('request_stack')->getCurrentRequest();
        $session = $request->getSession();
        $sessionData = $session->get('sessionData');
        $page = $request->get('page');
        $receiverId = $request->get('receiverId');
        $wallRecordId = $request->get('wallRecordId');
        $parentReplyId = $request->get('parentReplyId');
        $replyText = $request->get('replyText');
        $senderId = $session->get('sessionData')['userInfo']['id'];

        $wallService = WallService::getInstance();
        $wallRecordReply = $wallService->replyToWallRecord($wallRecordId, $parentReplyId, $senderId, $replyText);

        // TODO: Add localization
        $notificationInfo = 'User %s %s has commented your wall record!';
        $notificationInfoFormatted = sprintf($notificationInfo, $sessionData['userInfo']['firstName'],
            $sessionData['userInfo']['lastName']);

        $eventData = array
        (
            'success' => $success,
            'page' => $page,
            'event' => 'replyToWallRecord',
            'messageText' => $replyText,
            'wallRecordReplyId' => $wallRecordReply->getReplyId(),
            'wallRecordId' => $wallRecordId,
            'notificationInfo' => $notificationInfoFormatted
        );

        $response = ResponseBuilder::BuildResponse(null, null, $receiverId, null, $eventData, $session->get('sessionData'));

        return new Response(json_encode($response));
    }

    public function ratePhotoAction()
    {
        $success = true;
        $error = '';
        $response = '';

        $request = $this->get('request_stack')->getCurrentRequest();
        $session = $request->getSession();
        $sessionData = $session->get('sessionData');
        $page = $request->get('page');
        $receiverId = $request->get('receiverId');
        $rating = $request->get('rating');
        $photoId = $request->get('photoId');
        $senderId = $session->get('sessionData')['userInfo']['id'];

        $photoService = PhotoService::getInstance();
        $photoService->ratePicture($photoId, $senderId, $rating);
        $averageRating = $photoService->getPictureAverageRating($photoId);

        // TODO: Add localization
        $notificationInfo = 'User %s %s has rated your photo!';
        $notificationInfoFormatted = sprintf($notificationInfo, $sessionData['userInfo']['firstName'],
            $sessionData['userInfo']['lastName']);

        $eventData = array
        (
            'success' => $success,
            'page' => $page,
            'event' => 'ratePhoto',
            'messageText' => '',
            'photoId' => $photoId,
            'averageRating' => $averageRating,
            'notificationInfo' => $notificationInfoFormatted
        );

        $response = ResponseBuilder::BuildResponse(null, null, $receiverId, null, $eventData, $session->get('sessionData'));

        return new Response(json_encode($response));
    }

    public function getUserDataAction()
    {

    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>libguac: guac_stream Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libguac
    0.9.8

Main Page

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Fields

Data Fields

guac_stream Struct Reference

Represents a single stream within the Guacamole protocol.
 More...

Data Fields

int 	index

 	The index of this stream.

void * 	data

 	Arbitrary data associated with this stream.

guac_client_ack_handler * 	ack_handler

 	Handler for ack events sent by the Guacamole web-client.  More...

guac_client_blob_handler * 	blob_handler

 	Handler for blob events sent by the Guacamole web-client.  More...

guac_client_end_handler * 	end_handler

 	Handler for stream end events sent by the Guacamole web-client.  More...

Detailed Description

Represents a single stream within the Guacamole protocol.

Field Documentation

          guac_client_ack_handler* guac_stream::ack_handler

Handler for ack events sent by the Guacamole web-client.

The handler takes a guac_stream which contains the stream index and will persist through the duration of the transfer, a string containing the error or status message, and a status code.

Example:

int ack_handler(guac_client* client, guac_stream* stream,

        char* error, guac_protocol_status status);

int some_function(guac_client* client) {

    guac_stream* stream = guac_client_alloc_stream(client);

    stream->ack_handler = ack_handler;

    guac_protocol_send_clipboard(client->socket,

        stream, "text/plain");

}

          guac_client_blob_handler* guac_stream::blob_handler

Handler for blob events sent by the Guacamole web-client.

The handler takes a guac_stream which contains the stream index and will persist through the duration of the transfer, an arbitrary buffer containing the blob, and the length of the blob.

Example:

int blob_handler(guac_client* client, guac_stream* stream,

        void* data, int length);

int my_clipboard_handler(guac_client* client, guac_stream* stream,

        char* mimetype) {

    stream->blob_handler = blob_handler;

}

          guac_client_end_handler* guac_stream::end_handler

Handler for stream end events sent by the Guacamole web-client.

The handler takes only a guac_stream which contains the stream index. This guac_stream will be disposed of immediately after this event is finished.

Example:

int end_handler(guac_client* client, guac_stream* stream);

int my_clipboard_handler(guac_client* client, guac_stream* stream,

        char* mimetype) {

    stream->end_handler = end_handler;

}

The documentation for this struct was generated from the following file:

guacamole/stream.h

<address class="footer">
Generated on Tue Sep 8 2015 22:32:39 for libguac by

 1.8.9.1
</address>


text:
"""Extract information from alignment objects.

In order to try and avoid huge alignment objects with tons of functions,
functions which return summary type information about alignments should
be put into classes in this module.

classes:
o SummaryInfo
o PSSM
"""

# standard library
import math
import sys

# biopython modules
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
from Bio.SubsMat import FreqTable

# Expected random distributions for 20-letter protein, and
# for 4-letter nucleotide alphabets
Protein20Random = 0.05
Nucleotide4Random = 0.25
class SummaryInfo(object):
    """Calculate summary info about the alignment.

    This class should be used to caclculate information summarizing the
    results of an alignment. This may either be straight consensus info
    or more complicated things.
    """
    def __init__(self, alignment):
        """Initialize with the alignment to calculate information on.
           ic_vector attribute. A dictionary. Keys: column numbers. Values:
        """
        self.alignment = alignment
        self.ic_vector = {}

    def dumb_consensus(self, threshold = .7, ambiguous = "X",
                       consensus_alpha = None, require_multiple = 0):
        """Output a fast consensus sequence of the alignment.

        This doesn't do anything fancy at all. It will just go through the
        sequence residue by residue and count up the number of each type
        of residue (ie. A or G or T or C for DNA) in all sequences in the
        alignment. If the percentage of the most common residue type is
        greater then the passed threshold, then we will add that residue type,
        otherwise an ambiguous character will be added.

        This could be made a lot fancier (ie. to take a substitution matrix
        into account), but it just meant for a quick and dirty consensus.

        Arguments:
        o threshold - The threshold value that is required to add a particular
        atom.
        o ambiguous - The ambiguous character to be added when the threshold is
        not reached.
        o consensus_alpha - The alphabet to return for the consensus sequence.
        If this is None, then we will try to guess the alphabet.
        o require_multiple - If set as 1, this will require that more than
        1 sequence be part of an alignment to put it in the consensus (ie.
        not just 1 sequence and gaps).
        """
        # Iddo Friedberg, 1-JUL-2004: changed ambiguous default to "X"
        consensus = ''

        # find the length of the consensus we are creating
        con_len = self.alignment.get_alignment_length()

        # go through each seq item
        for n in range(con_len):
            # keep track of the counts of the different atoms we get
            atom_dict = {}
            num_atoms = 0

            for record in self.alignment._records:
                # make sure we haven't run past the end of any sequences
                # if they are of different lengths
                if n < len(record.seq):
                    if record.seq[n] != '-' and record.seq[n] != '.':
                        if record.seq[n] not in atom_dict:
                            atom_dict[record.seq[n]] = 1
                        else:
                            atom_dict[record.seq[n]] += 1

                        num_atoms = num_atoms + 1

            max_atoms = []
            max_size = 0

            for atom in atom_dict:
                if atom_dict[atom] > max_size:
                    max_atoms = [atom]
                    max_size = atom_dict[atom]
                elif atom_dict[atom] == max_size:
                    max_atoms.append(atom)

            if require_multiple and num_atoms == 1:
                consensus += ambiguous
            elif (len(max_atoms) == 1) and ((float(max_size)/float(num_atoms))
                                         >= threshold):
                consensus += max_atoms[0]
            else:
                consensus += ambiguous

        # we need to guess a consensus alphabet if one isn't specified
        if consensus_alpha is None:
            consensus_alpha = self._guess_consensus_alphabet(ambiguous)

        return Seq(consensus, consensus_alpha)

    def gap_consensus(self, threshold = .7, ambiguous = "X",
                       consensus_alpha = None, require_multiple = 0):
        """Same as dumb_consensus(), but allows gap on the output.

        Things to do: Let the user define that with only one gap, the result
        character in consensus is gap. Let the user select gap character, now
        it takes the same is input.
        """
        # Iddo Friedberg, 1-JUL-2004: changed ambiguous default to "X"
        consensus = ''

        # find the length of the consensus we are creating
        con_len = self.alignment.get_alignment_length()

        # go through each seq item
        for n in range(con_len):
            # keep track of the counts of the different atoms we get
            atom_dict = {}
            num_atoms = 0

            for record in self.alignment._records:
                # make sure we haven't run past the end of any sequences
                # if they are of different lengths
                if n < len(record.seq):
                    if record.seq[n] not in atom_dict:
                        atom_dict[record.seq[n]] = 1
                    else:
                        atom_dict[record.seq[n]] += 1

                    num_atoms += 1

            max_atoms = []
            max_size = 0

            for atom in atom_dict:
                if atom_dict[atom] > max_size:
                    max_atoms = [atom]
                    max_size = atom_dict[atom]
                elif atom_dict[atom] == max_size:
                    max_atoms.append(atom)

            if require_multiple and num_atoms == 1:
                consensus += ambiguous
            elif (len(max_atoms) == 1) and ((float(max_size)/float(num_atoms))
                                         >= threshold):
                consensus += max_atoms[0]
            else:
                consensus += ambiguous

        # we need to guess a consensus alphabet if one isn't specified
        if consensus_alpha is None:
            #TODO - Should we make this into a Gapped alphabet?
            consensus_alpha = self._guess_consensus_alphabet(ambiguous)

        return Seq(consensus, consensus_alpha)

    def _guess_consensus_alphabet(self, ambiguous):
        """Pick an (ungapped) alphabet for an alignment consesus sequence.

        This just looks at the sequences we have, checks their type, and
        returns as appropriate type which seems to make sense with the
        sequences we've got.
        """
        #Start with the (un-gapped version of) the alignment alphabet
        a = Alphabet._get_base_alphabet(self.alignment._alphabet)

        #Now check its compatible with all the rest of the sequences
        for record in self.alignment:
            #Get the (un-gapped version of) the sequence's alphabet
            alt =  Alphabet._get_base_alphabet(record.seq.alphabet)
            if not isinstance(alt, a.__class__):
                raise ValueError \
                ("Alignment contains a sequence with an incompatible alphabet.")

        #Check the ambiguous character we are going to use in the consensus
        #is in the alphabet's list of valid letters (if defined).
        if hasattr(a, "letters") and a.letters is not None \
        and ambiguous not in a.letters:
            #We'll need to pick a more generic alphabet...
            if isinstance(a, IUPAC.IUPACUnambiguousDNA):
                if ambiguous in IUPAC.IUPACUnambiguousDNA().letters:
                    a = IUPAC.IUPACUnambiguousDNA()
                else:
                    a = Alphabet.generic_dna
            elif isinstance(a, IUPAC.IUPACUnambiguousRNA):
                if ambiguous in IUPAC.IUPACUnambiguousRNA().letters:
                    a = IUPAC.IUPACUnambiguousRNA()
                else:
                    a = Alphabet.generic_rna
            elif isinstance(a, IUPAC.IUPACProtein):
                if ambiguous in IUPAC.ExtendedIUPACProtein().letters:
                    a = IUPAC.ExtendedIUPACProtein()
                else:
                    a = Alphabet.generic_protein
            else:
                a = Alphabet.single_letter_alphabet
        return a

    def replacement_dictionary(self, skip_chars = []):
        """Generate a replacement dictionary to plug into a substitution matrix

        This should look at an alignment, and be able to generate the number
        of substitutions of different residues for each other in the
        aligned object.

        Will then return a dictionary with this information:
        {('A', 'C') : 10, ('C', 'A') : 12, ('G', 'C') : 15 ....}

        This also treats weighted sequences. The following example shows how
        we calculate the replacement dictionary. Given the following
        multiple sequence alignments:

        GTATC  0.5
        AT--C  0.8
        CTGTC  1.0

        For the first column we have:
        ('A', 'G') : 0.5 * 0.8 = 0.4
        ('C', 'G') : 0.5 * 1.0 = 0.5
        ('A', 'C') : 0.8 * 1.0 = 0.8

        We then continue this for all of the columns in the alignment, summing
        the information for each substitution in each column, until we end
        up with the replacement dictionary.

        Arguments:
        o skip_chars - A list of characters to skip when creating the dictionary.
        For instance, you might have Xs (screened stuff) or Ns, and not want
        to include the ambiguity characters in the dictionary.
        """
        # get a starting dictionary based on the alphabet of the alignment
        rep_dict, skip_items = self._get_base_replacements(skip_chars)

        # iterate through each record
        for rec_num1 in range(len(self.alignment._records)):
            # iterate through each record from one beyond the current record
            # to the end of the list of records
            for rec_num2 in range(rec_num1 + 1, len(self.alignment._records)):
                # for each pair of records, compare the sequences and add
                # the pertinent info to the dictionary
                rep_dict = self._pair_replacement(
                    self.alignment._records[rec_num1].seq,
                    self.alignment._records[rec_num2].seq,
                    self.alignment._records[rec_num1].annotations.get('weight',1.0),
                    self.alignment._records[rec_num2].annotations.get('weight',1.0),
                    rep_dict, skip_items)

        return rep_dict

    def _pair_replacement(self, seq1, seq2, weight1, weight2,
                          start_dict, ignore_chars):
        """Compare two sequences and generate info on the replacements seen.

        Arguments:
        o seq1, seq2 - The two sequences to compare.
        o weight1, weight2 - The relative weights of seq1 and seq2.
        o start_dict - The dictionary containing the starting replacement
        info that we will modify.
        o ignore_chars - A list of characters to ignore when calculating
        replacements (ie. '-').

        Returns:
        o A replacment dictionary which is modified from initial_dict with
        the information from the sequence comparison.
        """
        # loop through each residue in the sequences
        for residue_num in range(len(seq1)):
            residue1 = seq1[residue_num]
            try:
                residue2 = seq2[residue_num]
            # if seq2 is shorter, then we just stop looking at replacements
            # and return the information
            except IndexError:
                return start_dict

            # if the two residues are characters we want to count
            if (residue1 not in ignore_chars) and (residue2 not in ignore_chars):
                try:
                    # add info about the replacement to the dictionary,
                    # modified by the sequence weights
                    start_dict[(residue1, residue2)] += weight1 * weight2

                # if we get a key error, then we've got a problem with alphabets
                except KeyError:
                    raise ValueError("Residues %s, %s not found in alphabet %s"
                                     % (residue1, residue2,
                                        self.alignment._alphabet))

        return start_dict

    def _get_all_letters(self):
        """Returns a string containing the expected letters in the alignment."""
        all_letters = self.alignment._alphabet.letters
        if all_letters is None \
        or (isinstance(self.alignment._alphabet, Alphabet.Gapped) \
        and all_letters == self.alignment._alphabet.gap_char):
            #We are dealing with a generic alphabet class where the
            #letters are not defined!  We must build a list of the
            #letters used...
            set_letters = set()
            for record in self.alignment:
                #Note the built in set does not have a union_update
                #which was provided by the sets module's Set
                set_letters = set_letters.union(record.seq)
            list_letters = list(set_letters)
            list_letters.sort()
            all_letters = "".join(list_letters)
        return all_letters

    def _get_base_replacements(self, skip_items = []):
        """Get a zeroed dictonary of all possible letter combinations.

        This looks at the type of alphabet and gets the letters for it.
        It then creates a dictionary with all possible combinations of these
        letters as keys (ie. ('A', 'G')) and sets the values as zero.

        Returns:
        o The base dictionary created
        o A list of alphabet items to skip when filling the dictionary.Right
        now the only thing I can imagine in this list is gap characters, but
        maybe X's or something else might be useful later. This will also
        include any characters that are specified to be skipped.
        """
        base_dictionary = {}
        all_letters = self._get_all_letters()

        # if we have a gapped alphabet we need to find the gap character
        # and drop it out
        if isinstance(self.alignment._alphabet, Alphabet.Gapped):
            skip_items.append(self.alignment._alphabet.gap_char)
            all_letters = all_letters.replace(self.alignment._alphabet.gap_char,'')

        # now create the dictionary
        for first_letter in all_letters:
            for second_letter in all_letters:
                if (first_letter not in skip_items and
                    second_letter not in skip_items):
                    base_dictionary[(first_letter, second_letter)] = 0

        return base_dictionary, skip_items

    def pos_specific_score_matrix(self, axis_seq = None,
                                  chars_to_ignore = []):
        """Create a position specific score matrix object for the alignment.

        This creates a position specific score matrix (pssm) which is an
        alternative method to look at a consensus sequence.

        Arguments:
        o chars_to_ignore - A listing of all characters not to include in
        the pssm.  If the alignment alphabet declares a gap character,
        then it will be excluded automatically.
        o axis_seq - An optional argument specifying the sequence to
        put on the axis of the PSSM. This should be a Seq object. If nothing
        is specified, the consensus sequence, calculated with default
        parameters, will be used.

        Returns:
        o A PSSM (position specific score matrix) object.
        """
        # determine all of the letters we have to deal with
        all_letters = self._get_all_letters()
        assert all_letters

        if not isinstance(chars_to_ignore, list):
            raise TypeError("chars_to_ignore should be a list.")

        # if we have a gap char, add it to stuff to ignore
        if isinstance(self.alignment._alphabet, Alphabet.Gapped):
            chars_to_ignore.append(self.alignment._alphabet.gap_char)

        for char in chars_to_ignore:
            all_letters = all_letters.replace(char, '')

        if axis_seq:
            left_seq = axis_seq
            assert len(axis_seq) == self.alignment.get_alignment_length()
        else:
            left_seq = self.dumb_consensus()

        pssm_info = []
        # now start looping through all of the sequences and getting info
        for residue_num in range(len(left_seq)):
            score_dict = self._get_base_letters(all_letters)
            for record in self.alignment._records:
                try:
                    this_residue = record.seq[residue_num]
                # if we hit an index error we've run out of sequence and
                # should not add new residues
                except IndexError:
                    this_residue = None

                if this_residue and this_residue not in chars_to_ignore:
                    weight = record.annotations.get('weight', 1.0)
                    try:
                        score_dict[this_residue] += weight
                    # if we get a KeyError then we have an alphabet problem
                    except KeyError:
                        raise ValueError("Residue %s not found in alphabet %s"
                                     % (this_residue,
                                        self.alignment._alphabet))

            pssm_info.append((left_seq[residue_num],
                              score_dict))

        return PSSM(pssm_info)

    def _get_base_letters(self, letters):
        """Create a zeroed dictionary with all of the specified letters.
        """
        base_info = {}
        for letter in letters:
            base_info[letter] = 0

        return base_info

    def information_content(self, start = 0,
                            end = None,
                            e_freq_table = None, log_base = 2,
                            chars_to_ignore = []):
        """Calculate the information content for each residue along an alignment.

        Arguments:
        o start, end - The starting an ending points to calculate the
        information content. These points should be relative to the first
        sequence in the alignment, starting at zero (ie. even if the 'real'
        first position in the seq is 203 in the initial sequence, for
        the info content, we need to use zero). This defaults to the entire
        length of the first sequence.
        o e_freq_table - A FreqTable object specifying the expected frequencies
        for each letter in the alphabet we are using (e.g. {'G' : 0.4,
        'C' : 0.4, 'T' : 0.1, 'A' : 0.1}). Gap characters should not be
        included, since these should not have expected frequencies.
        o log_base - The base of the logathrim to use in calculating the
        information content. This defaults to 2 so the info is in bits.
        o chars_to_ignore - A listing of characterw which should be ignored
        in calculating the info content.

        Returns:
        o A number representing the info content for the specified region.

        Please see the Biopython manual for more information on how information
        content is calculated.
        """
        # if no end was specified, then we default to the end of the sequence
        if end is None:
            end = len(self.alignment._records[0].seq)

        if start < 0 or end > len(self.alignment._records[0].seq):
            raise ValueError \
                  ("Start (%s) and end (%s) are not in the range %s to %s"
                   % (start, end, 0, len(self.alignment._records[0].seq)))
        # determine random expected frequencies, if necessary
        random_expected = None
        if not e_freq_table:
            #TODO - What about ambiguous alphabets?
            base_alpha = Alphabet._get_base_alphabet(self.alignment._alphabet)
            if isinstance(base_alpha, Alphabet.ProteinAlphabet):
                random_expected = Protein20Random
            elif isinstance(base_alpha, Alphabet.NucleotideAlphabet):
                random_expected = Nucleotide4Random
            else:
                errstr = "Error in alphabet: not Nucleotide or Protein, "
                errstr += "supply expected frequencies"
                raise ValueError(errstr)
            del base_alpha
        elif not isinstance(e_freq_table, FreqTable.FreqTable):
            raise ValueError("e_freq_table should be a FreqTable object")

        # determine all of the letters we have to deal with
        all_letters = self._get_all_letters()
        for char in chars_to_ignore:
            all_letters = all_letters.replace(char, '')

        info_content = {}
        for residue_num in range(start, end):
            freq_dict = self._get_letter_freqs(residue_num,
                                               self.alignment._records,
                                               all_letters, chars_to_ignore)
            # print freq_dict,
            column_score = self._get_column_info_content(freq_dict,
                                                         e_freq_table,
                                                         log_base,
                                                         random_expected)

            info_content[residue_num] = column_score
        # sum up the score
        total_info = sum(info_content.itervalues())
        # fill in the ic_vector member: holds IC for each column
        for i in info_content:
            self.ic_vector[i] = info_content[i]
        return total_info

    def _get_letter_freqs(self, residue_num, all_records, letters, to_ignore):
        """Determine the frequency of specific letters in the alignment.

        Arguments:
        o residue_num - The number of the column we are getting frequencies
        from.
        o all_records - All of the SeqRecords in the alignment.
        o letters - The letters we are interested in getting the frequency
        for.
        o to_ignore - Letters we are specifically supposed to ignore.

        This will calculate the frequencies of each of the specified letters
        in the alignment at the given frequency, and return this as a
        dictionary where the keys are the letters and the values are the
        frequencies.
        """
        freq_info = self._get_base_letters(letters)

        total_count = 0
        # collect the count info into the dictionary for all the records
        for record in all_records:
            try:
                if record.seq[residue_num] not in to_ignore:
                    weight = record.annotations.get('weight',1.0)
                    freq_info[record.seq[residue_num]] += weight
                    total_count += weight
            # getting a key error means we've got a problem with the alphabet
            except KeyError:
                raise ValueError("Residue %s not found in alphabet %s"
                                 % (record.seq[residue_num],
                                    self.alignment._alphabet))

        if total_count == 0:
            # This column must be entirely ignored characters
            for letter in freq_info:
                assert freq_info[letter] == 0
                #TODO - Map this to NA or NaN?
        else:
            # now convert the counts into frequencies
            for letter in freq_info:
                freq_info[letter] = freq_info[letter] / total_count

        return freq_info

    def _get_column_info_content(self, obs_freq, e_freq_table, log_base,
                                 random_expected):
        """Calculate the information content for a column.

        Arguments:
        o obs_freq - The frequencies observed for each letter in the column.
        o e_freq_table - An optional argument specifying the expected
        frequencies for each letter. This is a SubsMat.FreqTable instance.
        o log_base - The base of the logathrim to use in calculating the
        info content.
        """
        try:
            gap_char = self.alignment._alphabet.gap_char
        except AttributeError:
            #The alphabet doesn't declare a gap - there could be none
            #in the sequence... or just a vague alphabet.
            gap_char = "-" #Safe?

        if e_freq_table:
            if not isinstance(e_freq_table, FreqTable.FreqTable):
                raise ValueError("e_freq_table should be a FreqTable object")
            # check the expected freq information to make sure it is good
            for key in obs_freq:
                if (key != gap_char and key not in e_freq_table):
                    raise ValueError("Expected frequency letters %s "
                                     "do not match observed %s" \
                                     % (e_freq_table.keys(),
                                        obs_freq.keys() - [gap_char]))

        total_info = 0.0

        for letter in obs_freq:
            inner_log = 0.0
            # if we have expected frequencies, modify the log value by them
            # gap characters do not have expected frequencies, so they
            # should just be the observed frequency.
            if letter != gap_char:
                if e_freq_table:
                    inner_log = obs_freq[letter] / e_freq_table[letter]
                else:
                    inner_log = obs_freq[letter] / random_expected
            # if the observed frequency is zero, we don't add any info to the
            # total information content
            if inner_log > 0:
                letter_info = (obs_freq[letter] *
                               math.log(inner_log) / math.log(log_base))
                total_info += letter_info
        return total_info

    def get_column(self,col):
        return self.alignment.get_column(col)

class PSSM(object):
    """Represent a position specific score matrix.

    This class is meant to make it easy to access the info within a PSSM
    and also make it easy to print out the information in a nice table.

    Let's say you had an alignment like this:
    GTATC
    AT--C
    CTGTC

    The position specific score matrix (when printed) looks like:

      G A T C
    G 1 1 0 1
    T 0 0 3 0
    A 1 1 0 0
    T 0 0 2 0
    C 0 0 0 3

    You can access a single element of the PSSM using the following:

    your_pssm[sequence_number][residue_count_name]

    For instance, to get the 'T' residue for the second element in the
    above alignment you would need to do:

    your_pssm[1]['T']
    """
    def __init__(self, pssm):
        """Initialize with pssm data to represent.

        The pssm passed should be a list with the following structure:

        list[0] - The letter of the residue being represented (for instance,
        from the example above, the first few list[0]s would be GTAT...
        list[1] - A dictionary with the letter substitutions and counts.
        """
        self.pssm = pssm

    def __getitem__(self, pos):
        return self.pssm[pos][1]

    def __str__(self):
        out = " "
        all_residues = self.pssm[0][1].keys()
        all_residues.sort()

        # first print out the top header
        for res in all_residues:
            out += "   %s" % res
        out += "\n"

        # for each item, write out the substitutions
        for item in self.pssm:
            out += "%s " % item[0]
            for res in all_residues:
                out += " %.1f" % item[1][res]

            out += "\n"
        return out

    def get_residue(self, pos):
        """Return the residue letter at the specified position.
        """
        return self.pssm[pos][0]

def print_info_content(summary_info,fout=None,rep_record=0):
    """ Three column output: position, aa in representative sequence,
        ic_vector value"""
    fout = fout or sys.stdout
    if not summary_info.ic_vector:
        summary_info.information_content()
    rep_sequence = summary_info.alignment._records[rep_record].seq
    positions = summary_info.ic_vector.keys()
    positions.sort()
    for pos in positions:
        fout.write("%d %s %.3f\n" % (pos, rep_sequence[pos],
                   summary_info.ic_vector[pos]))

if __name__ == "__main__":
    print "Quick test"
    from Bio import AlignIO
    from Bio.Align.Generic import Alignment

    filename = "../../Tests/GFF/multi.fna"
    format = "fasta"
    expected = FreqTable.FreqTable({"A":0.25,"G":0.25,"T":0.25,"C":0.25},
                                   FreqTable.FREQ,
                                   IUPAC.unambiguous_dna)

    alignment = AlignIO.read(open(filename), format)
    for record in alignment:
        print record.seq.tostring()
    print "="*alignment.get_alignment_length()

    summary = SummaryInfo(alignment)
    consensus = summary.dumb_consensus(ambiguous="N")
    print consensus
    consensus = summary.gap_consensus(ambiguous="N")
    print consensus
    print
    print summary.pos_specific_score_matrix(chars_to_ignore=['-'],
                                            axis_seq=consensus)
    print
    #Have a generic alphabet, without a declared gap char, so must tell
    #provide the frequencies and chars to ignore explicitly.
    print summary.information_content(e_freq_table=expected,
                                      chars_to_ignore=['-'])
    print
    print "Trying a protein sequence with gaps and stops"

    alpha = Alphabet.HasStopCodon(Alphabet.Gapped(Alphabet.generic_protein, "-"), "*")
    a = Alignment(alpha)
    a.add_sequence("ID001", "MHQAIFIYQIGYP*LKSGYIQSIRSPEYDNW-")
    a.add_sequence("ID002", "MH--IFIYQIGYAYLKSGYIQSIRSPEY-NW*")
    a.add_sequence("ID003", "MHQAIFIYQIGYPYLKSGYIQSIRSPEYDNW*")
    print a
    print "="*a.get_alignment_length()

    s = SummaryInfo(a)
    c = s.dumb_consensus(ambiguous="X")
    print c
    c = s.gap_consensus(ambiguous="X")
    print c
    print
    print s.pos_specific_score_matrix(chars_to_ignore=['-', '*'], axis_seq=c)

    print s.information_content(chars_to_ignore=['-', '*'])

    print "Done"


text:
import time
from typing import List

from src.classes.dto.Block import Block
from src.classes.BlockChainValidator import BlockChainValidator
from src.classes.dto.Transaction import Transaction

class BlockChain(object):
    def __init__(self):
        self.chain: List[Block] = []
        self.new_transactions: List[Transaction] = []
        # Creat 1st block
        self.new_block(100, 1)

    def new_block(self, proof, previous_hash=None) -> Block:
        """
        Creates a new Block and adds it to the chain
        :param proof:
        :param previous_hash:
        :return:
        """
        block = Block(len(self.chain) + 1, proof, self.new_transactions, str(time.time()),
                      previous_hash or self.last_block.hash())
        self.new_transactions = []
        self.chain.append(block)
        return block

    def new_transaction(self, sender, recipient, amount) -> int:
        """
        Adds a new transaction to the list of transactions
        :param sender:
        :param recipient:
        :param amount:
        :return:int
        """
        self.new_transactions.append(Transaction(sender, recipient, amount))
        return self.last_block.index + 1

    @property
    def last_block(self) -> Block:
        """
        Returns the last Block in the chain
        """
        return self.chain[-1]