text:
package net.sf.taverna.t2.workbench.cagrid;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;

import net.sf.taverna.cagrid.activity.config.CaGridConfiguration;

/**
 * Panel with options to configure CDActivity.
 *
 * @author Wei Tan
 *
 */
@SuppressWarnings("serial")
public class CDSAndTransferConfDialog extends JDialog {

	private boolean needCDS;
	private boolean needUpload;
	private boolean needTransfer;

	private String caGridName;
	private String party;

	private int delegationLifetime;
	private int delegationPathLength;
	private int issuedCredentialLifetime;
	private int issuedCredentialPathLength;

	private String fileToUpload;
	public String getFileToUpload() {
		return fileToUpload;
	}

	public void setFileToUpload(String fileToUpload) {
		this.fileToUpload = fileToUpload;
	}

	private JTextField jtfFileName;

	private JTextField jtfParty;
	private JTextField jtfDelegationLifetime;
	private JTextField jtfDelegationPathLength;
	private JTextField jtfIssuedCredentialLifetime;
	private JTextField jtfIssuedCredentialPathLength;

	JComboBox caGridList;

	//TODO change it to 1.4

	public static String PRODUCTION_CAGRID_NAME =  "NCI Production CaGrid 1.3";
	public static String PARTY_STRING = "/O=caBIG/OU=caGrid/OU=LOA1/OU=Services/CN=bridled.ci.uchicago.edu";
	//public static String PARTY_STRING = "/O=caBIG/OU=caGrid/OU=Services/CN=cagrid-fqp.nci.nih.gov";

	public CDSAndTransferConfDialog(WFProperties wfp) {

		super((Frame)null, "Configuration for Credential Delegation and caGrid Transfer (if any)", true);
		//are CDS and transfer needed?
		this.needCDS = wfp.needSecurity;
		this.needUpload = wfp.needTransfer == wfp.TRANSFER_UPLOAD_ONLY|| wfp.needTransfer== wfp.TRANSFER_BOTH;
		this.needTransfer = !(wfp.needTransfer == wfp.TRANSFER_NONE);
		//get caGrid Name list from caGrid configuration
		CaGridConfiguration configuration = CaGridConfiguration.getInstance();
		HashSet<String> caGridNamesSet = new HashSet<String>(configuration.getDefaultPropertyMap().keySet());
		caGridNamesSet.addAll(configuration.getKeys());
		String[] caGridNamesStrings =  new String [caGridNamesSet.size()];
		caGridNamesStrings = (String[]) caGridNamesSet.toArray(caGridNamesStrings);
		caGridList = new JComboBox(caGridNamesStrings);
		caGridList.setSelectedItem(PRODUCTION_CAGRID_NAME);
		initComponents();
	}

	public void setDelegationPathLength(int delegationPathLength) {
		this.delegationPathLength = delegationPathLength;
	}

	public int getDelegationPathLength() {
		return delegationPathLength;
	}

	private void initComponents() {

		delegationLifetime = 4;
		delegationPathLength = 1;
		issuedCredentialLifetime = 1;
		issuedCredentialPathLength = 0;

		JPanel configurationPanel = new JPanel();
		configurationPanel.setBorder(new CompoundBorder(new EmptyBorder(10,10,10,10), new EtchedBorder(EtchedBorder.LOWERED)));
		configurationPanel.setLayout(new GridBagLayout());

		GridBagConstraints c = new GridBagConstraints();

		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 2;
		c.weightx = 1.0;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.HORIZONTAL;
		JPanel instructionsPanel = new JPanel();
		instructionsPanel.setLayout(new BoxLayout(instructionsPanel, BoxLayout.Y_AXIS));
		JLabel instructions = new JLabel(
				"Configure the CDS and caTransfer Properties here");
		instructions.setBorder(new EmptyBorder(5,5,10,5));
		instructions.setFont(new Font(null, Font.PLAIN, 11));
		instructionsPanel.add(instructions);
		configurationPanel.add(instructionsPanel, c);

		c.gridwidth = 1;

		c.gridx = 0;
		c.gridy = 1;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;
		JLabel jlCaGrid = new JLabel("CaGrid Name");
		jlCaGrid.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(jlCaGrid, c);
		jlCaGrid.setEnabled(needCDS||needTransfer);

		c.gridx = 1;
		c.gridy = 1;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(caGridList, c);
		caGridList.setEnabled(needCDS||needTransfer);

		c.gridx = 0;
		c.gridy = 2;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;
		JLabel jlParty = new JLabel("Party Delegated To");
		jlParty.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(jlParty, c);
		jlParty.setEnabled(needCDS);

		jtfParty = new JTextField(40);
		jtfParty.setText(PARTY_STRING);
		c.gridx = 1;
		c.gridy = 2;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(jtfParty, c);
		jtfParty.setEnabled(needCDS);

		jtfDelegationLifetime = new JTextField(35);
		jtfDelegationLifetime.setText(String.valueOf(delegationLifetime));

		c.gridx = 0;
		c.gridy = 3;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;
		JLabel jlDelegationLifetime = new JLabel("Delegation Lifetime (hr)");
		jlDelegationLifetime.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(jlDelegationLifetime, c);
		jlDelegationLifetime.setEnabled(needCDS);

		c.gridx = 1;
		c.gridy = 3;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(jtfDelegationLifetime, c);
		jtfDelegationLifetime.setEnabled(needCDS);

		c.gridx = 0;
		c.gridy = 4;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;
		JLabel jlDelegationPathLength = new JLabel("Delegation PathLength");
		jlParty.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(jlDelegationPathLength, c);
		jlDelegationPathLength.setEnabled(needCDS);

		jtfDelegationPathLength = new JTextField(35);
		jtfDelegationPathLength.setText(String.valueOf(delegationPathLength));

		c.gridx = 1;
		c.gridy = 4;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(jtfDelegationPathLength, c);
		jtfDelegationPathLength.setEnabled(needCDS);

		//issuedCredentialLifetime

		jtfIssuedCredentialLifetime = new JTextField(35);
		jtfIssuedCredentialLifetime.setText(String.valueOf(issuedCredentialLifetime));
		c.gridx = 0;
		c.gridy = 5;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;
		JLabel jlIssuedCredentialLifetime = new JLabel("IssuedCredential Lifetime (hr)");
		jlParty.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(jlIssuedCredentialLifetime, c);
		jlIssuedCredentialLifetime.setEnabled(needCDS);

		c.gridx = 1;
		c.gridy = 5;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(jtfIssuedCredentialLifetime, c);
		jtfIssuedCredentialLifetime.setEnabled(needCDS);

		//issuedCredentialPathLength
		jtfIssuedCredentialPathLength = new JTextField(35);
		jtfIssuedCredentialPathLength.setText(String.valueOf(issuedCredentialPathLength));
		c.gridx = 0;
		c.gridy = 6;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;
		JLabel jlIssuedCredentialPathLength = new JLabel("IssuedCredential PathLength");
		jlParty.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(jlIssuedCredentialPathLength, c);
		jlIssuedCredentialPathLength.setEnabled(needCDS);

		c.gridx = 1;
		c.gridy = 6;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(jtfIssuedCredentialPathLength, c);
		jtfIssuedCredentialPathLength.setEnabled(needCDS);

		//file upload

		c.gridx = 0;
		c.gridy = 7;
		c.ipadx = 5;
		c.anchor = GridBagConstraints.EAST;
		c.weightx = 0.0;
		c.fill = GridBagConstraints.NONE;

		JButton openButton = new JButton("Upload a File...");

		openButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				openPressed();
			}
		});

		//JLabel jlFileUpload = new JLabel("File To Upload");
		openButton.setBorder(new EmptyBorder(5,5,5,5));
		configurationPanel.add(openButton, c);
		openButton.setEnabled(needUpload);

		jtfFileName = new JTextField(35);
		c.gridx = 1;
		c.gridy = 7;
		c.ipadx = 0;
		c.anchor = GridBagConstraints.WEST;
		c.weightx = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		configurationPanel.add(jtfFileName, c);
		jtfFileName.setEnabled(needUpload);

		// Buttons
		c.gridx = 0;
		c.gridy = 8;
		c.gridwidth = 2;
		c.weightx = 1.0;
		c.anchor = GridBagConstraints.CENTER;
		c.fill = GridBagConstraints.NONE;
		JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JButton okButton = new JButton("OK");
		okButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				okPressed();
			}
		});
		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				cancelPressed();
			}
		});
		buttonsPanel.add(okButton);
		buttonsPanel.add(cancelButton);
		configurationPanel.add(buttonsPanel, c);

		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(configurationPanel, BorderLayout.CENTER);

	}

	 /**
     * Upload a File button pressed or otherwise activated.
     */
    private void openPressed()
    {
    	JFileChooser fc = new JFileChooser();
    	int returnVal = fc.showOpenDialog(CDSAndTransferConfDialog.this);

         if (returnVal == JFileChooser.APPROVE_OPTION) {
             File file = fc.getSelectedFile();
             //This is where a real application would open the file.
             fileToUpload = file.getPath();
             jtfFileName.setText(fileToUpload);
         }

    }

    /**
     * OK button pressed or otherwise activated.
     */
    private void okPressed()
    {
    	caGridName = (String) caGridList.getSelectedItem();
    	party = jtfParty.getText();
    	delegationLifetime = Integer.valueOf(jtfDelegationLifetime.getText());
    	delegationPathLength = Integer.valueOf(jtfDelegationPathLength.getText());
    	issuedCredentialLifetime = Integer.valueOf(jtfIssuedCredentialLifetime.getText());
    	issuedCredentialPathLength = Integer.valueOf(jtfIssuedCredentialPathLength.getText());
    	fileToUpload = jtfFileName.getText();
        closeDialog();
    }

	/**
     * Cancel button pressed or otherwise activated.
     */
    private void cancelPressed()
    {
    	// Set all fields to null to indicate that cancel button was pressed

        closeDialog();
    }

    /**
     * Close the dialog.
     */
    private void closeDialog()
    {
        setVisible(false);
        dispose();
    }

	public void setIssuedCredentialLifetime(int issuedCredentialLifetime) {
		this.issuedCredentialLifetime = issuedCredentialLifetime;
	}

	public int getIssuedCredentialLifetime() {
		return issuedCredentialLifetime;
	}

	public void setIssuedCredentialPathLength(int issuedCredentialPathLength) {
		this.issuedCredentialPathLength = issuedCredentialPathLength;
	}

	public int getIssuedCredentialPathLength() {
		return issuedCredentialPathLength;
	}

	public void setCaGridName(String caGridName) {
		this.caGridName = caGridName;
	}

	public String getCaGridName() {
		return caGridName;
	}

	public int getDelegationLifetime() {
		return delegationLifetime;
	}

	public void setDelegationLifetime(int delegationLifetime) {
		this.delegationLifetime = delegationLifetime;
	}
	public String getParty() {
		return party;
	}

	public void setParty(String party) {
		this.party = party;
	}

}


text:
package com.sparta.is.init;

import com.sparta.is.core.tileentity.TileEntityIS;
import com.sparta.is.tileentity.TileEntityISUnitStation;
import com.sparta.is.tileentity.TileEntityItemDisplay;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ModTileEntities
{
    private static final List<TileEntityIS> TILE_ENTITIES = new ArrayList<>();

    public static final TileEntityIS unitStation = new TileEntityISUnitStation();
    public static final TileEntityItemDisplay itemDisplay = new TileEntityItemDisplay();

    private ModTileEntities() {}

    public static void register(TileEntityIS tileEntityIS) { TILE_ENTITIES.add(tileEntityIS); }

    public static Collection<TileEntityIS> getTileEntities() { return TILE_ENTITIES; }

}

redpajama_set_name: RedPajamaGithub


text:
function dUpsilonS = lfmvpGradientSigmaUpsilonMatrix(gamma, sigma2, ...
    t1, t2, mode)

% LFMVPGRADIENTSIGMAUPSILONMATRIX Gradient of upsilon matrix vp wrt sigma
% FORMAT
% DESC computes the gradient of a portion of the LFMVP kernel.
% ARG gamma : Gamma value for system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% ARG t2 : second time input (number of time points x 1).
% ARG mode : operation mode, according to the derivative (mode 0,
% derivative wrt t1, mode 1 derivative wrt t2)
% RETURN upsilon : result of this subcomponent of the kernel for the given values.
%
% COPYRIGHT : Mauricio A. Alvarez, 2010
%
% SEEALSO : lfmvpComputeUpsilonMatrix.m

% KERN

gridt1 = repmat(t1, 1, length(t2));
gridt2 = repmat(t2', length(t1), 1);
timeGrid = gridt1 - gridt2;

dUpsilon = lfmGradientSigmaUpsilonMatrix(gamma, sigma2, t1, t2);

if mode == 0
    dUpsilonS = -gamma*dUpsilon-(2/(sqrt(pi)*sigma2))*(1-2*(timeGrid.^2)/sigma2).* ...
       exp(-(timeGrid.^2)./sigma2);
else
    dUpsilonS = gamma*dUpsilon+(2/(sqrt(pi)*sigma2))*(1-2*(timeGrid.^2)/sigma2).* ...
       exp(-(timeGrid.^2)./sigma2) - (2/(sqrt(pi)*sigma2))*...
       exp(-gamma*t1)*((1-2*t2.^2/sigma2).*exp(-(t2.^2)/sigma2)).';
end


text:
piggyphoto
==========

Python bindings for libgphoto2.

This is a very rough proof of concept. Feel free to play with it and add improvements.

Usage
-----

You have to install [libgphoto2](http://www.gphoto.org/proj/libgphoto2/). It should work with any version, from the one prepackaged in Ubuntu to the latest SVN checkout. In theory, of course :)

    import piggyphoto

    C = piggyphoto.camera()
    print C.abilities
    C.capture_preview('preview.jpg')
    C.capture_image('image.jpg')

Enjoy!


text:
Hem

Våra API:er

{{vm.apiName}} {{vm.apiVersion}}

Hem

Mina Sidor

Prenumerationer

{{vm.apiName}} {{vm.apiVersion}}

{{vm.apiName}} {{vm.apiVersion}}

            Version:

{{vm.api.version}}

            Status:

{{vm.api.status}}

            Utgivare:

{{vm.api.provider}}

             Logga in för att kunna prenumerera på detta API!
             Det är inte möjligt att prenumerera på detta API!

             Det är inte möjligt att prenumerera på detta API!

                Du har inga registrerade applikationer.

Skapa en applikation först, skapa sedan en prenumeration här!

 0">
                Applikationer som prenumererar på detta API

{{entries.name}}

 0">
                <form name="addSubscriptionForm" ng-submit="vm.addSubscription()" role="form" class="ng-pristine ng-invalid ng-invalid-required">
                    <input type="hidden" name="apiId" ng-model="vm.apiId" value="{{vm.apiId}}" />

                        Applikation
                        <select name="application" id="application" ng-model="vm.selectedApplicationId" class="form-control" required>
              <option ng-repeat="entry in vm.applications" value="{{entry.id}}">{{entry.name}}</option>
            </select>
                        Applikation är obligatoriskt

                        <button type="submit" ng-disabled="addSubscriptionForm.$invalid || vm.dataLoadingAddSubscription" class="btn btn-primary" disabled="disabled">Skapa prenumeration</button>
                        Ångra

                </form>

                    Översikt

                    Dokumentation

                    API-konsol

                    Ladda ner klient

Beskrivning

URL

https://api.vasttrafik.se{{vm.api.context}}

 0">

                                Namn
                                Dokument

                                Typ
                                Beskrivning

                                    Namn:
                                    {{doc.name}}
                                    {{doc.name}}

                                    Typ:
                                    {{doc.type.type}}
                                    {{doc.type.otherType}}

                                    Beskrivning:
                                    {{doc.summary}}

                                    {{doc.name}}

                                    {{doc.name}}

                                    {{doc.type.type}}

                                    {{doc.type.otherType}}

                                    {{doc.summary}}

 0)" class="alert alert-warning" role="alert">
                         Det finns inga dokument associerade till detta API!

                        Ange access token

                            Authorization: Bearer
                            <input type="text" class="form-control" id="requestHeader" ng-model="user.accessToken" aria-describedby="basic-addon3">

Ladda ner klient-stubb för detta API för specificerat programspråk

                             Dessa klienter innehåller ingen kod för OAuth 2 autentisering. Detta måste implementeras i klienterna för att fungera.

                                    {{vm.clientOptions[$index].text}}
                                    {{vm.clientOptions[$index + vm.getClientOptionsCeilingNumber()].text}}
                                    {{vm.clientOptions[$index + vm.getClientOptionsCeilingNumber()*2].text}}

Det är för närvarande inte möjligt att ladda ner klient-stubb för detta API, försök gärna senare igen.


text:
module Azure::ARM::Scheduler
  module Models
    #
    # Model object.
    #
    #
    class JobDefinition

      include MsRestAzure

      # @return [String] Gets the job resource identifier.
      attr_accessor :id

      # @return [String] Gets the job resource type.
      attr_accessor :type

      # @return [String] Gets the job resource name.
      attr_accessor :name

      # @return [JobProperties] Gets or sets the job properties.
      attr_accessor :properties

      #
      # Mapper for JobDefinition class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          required: false,
          serialized_name: 'JobDefinition',
          type: {
            name: 'Composite',
            class_name: 'JobDefinition',
            model_properties: {
              id: {
                required: false,
                read_only: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              type: {
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              name: {
                required: false,
                read_only: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              properties: {
                required: false,
                serialized_name: 'properties',
                type: {
                  name: 'Composite',
                  class_name: 'JobProperties'
                }
              }
            }
          }
        }
      end
    end
  end
end


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

namespace PowersOfTwo
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int x = 1;
            for (var i = 0; i <= n; i++)
            {
                Console.WriteLine(x);
                x *= 2;
            }
        }
    }
}


text:
[![Build Status](https://travis-ci.org/ava-project/sdk.svg?branch=master)](https://travis-ci.org/ava-project/sdk)

Useful function for AVA project

## Install

You can install it with pip :

```bash
$ sudo python3 -m pip install --upgrade git+https://github.com/ava-project/sdk
```

## Run tests

```bash
$ ./runtests.sh
```

## Usage

#### Config file

You can validate a plugin config file with

```python
from avasdk.validate_plugin import validate_plugin

validate_plugin(config)
```

`config` is a dictionary


text:
namespace MvcApp.Data
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    using MvcApp.Data.Models;

    public interface IMvcAppDbContext
    {
        IDbSet<User> Users { get; set; }
        IDbSet<Movie> Movies { get; set; }
        IDbSet<MaleActor> MaleActors { get; set; }

        IDbSet<FemaleActor> FemaleActors { get; set; }
        IDbSet<Director> Directors { get; set; }
        IDbSet<Studio> Studios { get; set; }

        DbSet<TEntity> Set<TEntity>() where TEntity : class;

        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

        void Dispose();

        int SaveChanges();
    }
}


text:
Compiled on 2014/11/12 by lost_RD of the LOVE2D.org forums

Thread: https://love2d.org/forums/viewtopic.php?f=5&t=79113

This pack claims no copyright over any code in the modules folder.
All modules are copyright to their respective owners.
That said, all code is FOSS. Enjoy!

##To-do

- Build functions for loading assets from directory structures in resources folder using love-loader
- Establish entity management system

##Changelog

v0.2:
- added callback file functionality to module-loader
- included various modules
 - babel
 - gamera
 - Gspot
 - lovenoise
 - lume
 - lurker
 - TLbind (deactivated in favour of Controllers, may be removed in a future version)
- integrated more modules
 - babel
 - Controllers
 - lurker
- created resources folder, added a language (en-UK)
- created docs folder, filled with READMEs from repos

v0.1:
- created module-loader.lua
- included various modules
 - cas
 - coil
 - Controllers
 - cron
 - flux
 - glove
 - inspect
 - lady
 - loader
 - lovedebug
 - loveplot
 - middleclass
 - mlib
 - PROBE
 - richtext
 - sfxr
 - stateful
 - TEsound
 - xboxlove (inactive)
- created main.lua
- integrated some modules into the framework
 - module-loader
 - lovedebug
 - loveplot
 - PROBE
 - richtext
 - coil
 - flux


text:
module('ui/CarouselPane');

(function() {

	function resetTestDiv() {
		var testdiv = document.getElementById('testElmsContainer0');
		if (testdiv) {
			testdiv.innerHTML = '';
		}
		else {
			testdiv = document.createElement('div');
			testdiv.id = 'testElmsContainer0';
			document.body.appendChild(testdiv);
		}

		testdiv.innerHTML = '
1 one
'
		+ '
2 two
'
		+ '
3 three
';
	}

	test('ui/CarouselPane:API', 16, function() {
		equal(typeof glow.ui, 'object', 'glow.ui is defined.');
		equal(typeof glow.ui.CarouselPane, 'function', 'glow.ui.CarouselPane is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype._init, 'function', 'glow.ui.CarouselPane#_init is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype._build, 'function', 'glow.ui.CarouselPane#_build is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype._bind, 'function', 'glow.ui.CarouselPane#_bind is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.destroy, 'function', 'glow.ui.CarouselPane#destroy is defined.');

 		equal(typeof glow.ui.CarouselPane.prototype.updateUi, 'function', 'glow.ui.CarouselPane#updateUi is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.moveStart, 'function', 'glow.ui.CarouselPane#moveStart is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.moveStop, 'function', 'glow.ui.CarouselPane#moveStop is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.spotlightIndexes, 'function', 'glow.ui.CarouselPane#spotlightIndexes is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.spotlightItems, 'function', 'glow.ui.CarouselPane#spotlightItems is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.moveTo, 'function', 'glow.ui.CarouselPane#moveTo is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.moveBy, 'function', 'glow.ui.CarouselPane#moveBy is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.next, 'function', 'glow.ui.CarouselPane#next is defined.');
 		equal(typeof glow.ui.CarouselPane.prototype.prev, 'function', 'glow.ui.CarouselPane#prev is defined.');

 		equal(typeof glow.ui.CarouselPane._getSpot, 'function', 'CarouselPane._getSpot is defined.');
 	});

 	test('ui/CarouselPane:constructor', 1, function() {
 		var myCarouselPane = new glow.ui.CarouselPane();
 		equal(typeof myCarouselPane, 'object', 'glow.ui.CarouselPane instance is defined with no options.');
	});

	test('ui/CarouselPane:constructorOptions', 1, function() {
 		var myCarouselPane = new glow.ui.CarouselPane('dontExist');
 		equal(typeof myCarouselPane, 'object', 'glow.ui.CarouselPane instance is defined with invalid selector.');
 	});

	test('ui/CarouselPane:noitems', 3, function() {
 		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');
 		equal(typeof myCarouselPane.items, 'object', 'glow.ui.CarouselPane#items is defined when no elements.');
 		equal(myCarouselPane.items.length, 0, 'glow.ui.CarouselPane#items length is 0 when no elements.');
 		equal(myCarouselPane._spot.capacity, 0, 'myCarouselPane._spot.capacity is 0 when no elements.');
		myCarouselPane.destroy();
	});

	test('ui/CarouselPane:items', 2, function() {
		resetTestDiv();
 		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');
 		equal(typeof myCarouselPane.items, 'object', 'glow.ui.CarouselPane#items is defined.');
 		equal(myCarouselPane.items.length, 3, 'glow.ui.CarouselPane#items length is 3.');

 		myCarouselPane.destroy();
	});

	test('ui/CarouselPane:classes', 1, function() {
 		resetTestDiv();

 		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');

		var classes = [];
		for (var i = 0, leni = myCarouselPane.items.length; i < leni; i++) {
			classes.push(myCarouselPane.items[i].className);
		}
		classes = classes.join(', ');

		equal(classes, 'carousel-item, carousel-item, carousel-item', 'glow.ui.CarouselPane items have the class name "carousel-item".');

		myCarouselPane.destroy();
	});

 	test('ui/CarouselPane:_index', 1, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');
  		equal(myCarouselPane._index, 0, 'glow.ui.CarouselPane#_index is 0.');
  		myCarouselPane.destroy();
  	});

  	test('ui/CarouselPane:_getSpot', 5, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');
  		glow('#testElmsContainer0').css('width', 150);
  		var spot = glow.ui.CarouselPane._getSpot(
  			glow('#testElmsContainer0').width(),
  			glow('#testElmsContainer0 div')
  		);
  		equal(1, spot.capacity, 'glow.ui.CarouselPane._getSpot()#capacity is 1 when parent element width is 150.');
  		equal(spot.offset.left+spot.offset.right+spot.width, glow('#testElmsContainer0').width(), 'glow.ui.CarouselPane._getSpot()#offset.left + #width + #offset.right sums to be the parent elements width.');

  		equal(spot.offset.left, 25, 'glow.ui.CarouselPane._getSpot()#offset.left is correct.');
  		equal(spot.offset.right, 25, 'glow.ui.CarouselPane._getSpot()#offset.right is correct.');
  		equal(spot.width, 100, 'glow.ui.CarouselPane._getSpot()#offset.right is correct.');

  		myCarouselPane.destroy();
  	});

  	test('ui/CarouselPane:opts.page:gap', 1, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 2, step: 2, page: true});
  		equal(myCarouselPane._gap.count, 1, 'with page true the gap is 1.');
  		myCarouselPane.destroy();
  	});

  	test('ui/CarouselPane:opts:defaults', 6, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');

  		equal(typeof myCarouselPane._opts, 'object', 'glow.ui.CarouselPane#_opts is defined.');
  		equal(myCarouselPane._opts.duration, 0.2, 'glow.ui.CarouselPane#_opts.duration defaults to 0.2.');
  		equal(myCarouselPane._opts.tween, 'easeBoth', 'glow.ui.CarouselPane#_opts.tween defaults to "easeBoth".');
  		equal(myCarouselPane._opts.step, 1, 'glow.ui.CarouselPane#_opts.step defaults to 1.');
  		equal(myCarouselPane._opts.loop, false, 'glow.ui.CarouselPane#_opts.loop defaults to false.');
  		equal(myCarouselPane._opts.page, false, 'glow.ui.CarouselPane#_opts.page defaults to false.');

  		myCarouselPane.destroy();
  	});

  	test('ui/CarouselPane:opts.spotlight:tooLarge', 1, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 4});
  		glow('#testElmsContainer0').css('width', 500);

  		equal(myCarouselPane._spot.capacity, 3, 'glow.ui.CarouselPane#_spot.capacity is maxes out at items.length even when opts.spotlight is set larger.');

  		myCarouselPane.destroy();
  	});

  	test('ui/CarouselPane:_spot.capacity:tooLargeNoOpt', 1, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');
  		glow('#testElmsContainer0').css('width', 500);

  		equal(myCarouselPane._spot.capacity, 3, 'glow.ui.CarouselPane#_spot.capacity is same as items.length even when carousel pane width is larger.');

  		myCarouselPane.destroy();
  	});

  	test('ui/CarouselPane:spotlightIndexes:Nonlooping', 1, function() {
  		resetTestDiv();
  		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0');
  		var indexes = myCarouselPane.spotlightIndexes();

  		same(indexes, [0, 1, 2], 'glow.ui.CarouselPane#spotlightIndexes is [0, 1, 2] when looping is off.');
  		myCarouselPane.destroy();
  	});

   	test('ui/CarouselPane:spotlightIndexes:Looping', 1, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {loop: true});
   		var indexes = myCarouselPane.spotlightIndexes();
   		same(indexes, [0, 1, 2], 'glow.ui.CarouselPane indexes is [0, 1] when looping is on.');
   		myCarouselPane.destroy();
   	});

   	test('ui/CarouselPane:moveBy:AboveMax', 2, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 2, step: 2});

   		same(myCarouselPane.spotlightIndexes(), [0, 1], 'Before next glow.ui.CarouselPane indexes is [0, 1].');
   		stop(5000);
   		myCarouselPane.moveBy(99);
   		setTimeout(
   			function() {
   				same(myCarouselPane.spotlightIndexes(), [1, 2], 'After moveBy above max glow.ui.CarouselPane indexes is at max [1, 2].');
   				start();
   				myCarouselPane.destroy();
   			},
   			500
   		);
   	});

   	test('ui/CarouselPane:moveBy:OutOfStep:NoPage', 2, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 2, step: 2});

   		same(myCarouselPane.spotlightIndexes(), [0, 1], 'Before next glow.ui.CarouselPane indexes is [0, 1].');
   		stop(5000);
   		myCarouselPane.moveTo(1);
   		setTimeout(
   			function() {
   				same(myCarouselPane.spotlightIndexes(), [1, 2], 'After moveBy out of step, without page glow.ui.CarouselPane indexes is [1, 2].');
   				start();
   				myCarouselPane.destroy();
   			},
   			500
   		);
   	});

   	test('ui/CarouselPane:moveBy:OutOfStep:WithPage', 2, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 2, step: 2, page: true});

   		same(myCarouselPane.spotlightIndexes(), [0, 1], 'Before next glow.ui.CarouselPane indexes is [0, 1].');
   		stop(5000);
   		myCarouselPane.moveTo(2);
   		setTimeout(
   			function() {
   				same(myCarouselPane.spotlightIndexes(), [2], 'After moveBy out of step, with page glow.ui.CarouselPane indexes is [2].');
   				start();
   				myCarouselPane.destroy();
   			},
   			500
   		);
   	});

   	test('ui/CarouselPane:moveBy:AboveMax:withPaging', 2, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 2, step: 2, page: true});

   		same(myCarouselPane.spotlightIndexes(), [0, 1], 'Before moveBy above max with paging indexes is [0, 1].');
   		stop(5000);
   		myCarouselPane.moveBy(99);
   		setTimeout(
   			function() {
   				same(myCarouselPane.spotlightIndexes(), [2], 'After moveBy above max with paging, the pages are preserved, indexes is [2].');
   				start();
   				myCarouselPane.destroy();
   			},
   			500
   		);
   	});

   	test('ui/CarouselPane:moveBy:BelowMin', 2, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 1});

   		same(myCarouselPane.spotlightIndexes(), [0], 'Before next glow.ui.CarouselPane indexes is [0].');
   		stop(5000);
   		myCarouselPane.moveBy(-99);
   		setTimeout(
   			function() {
   				same(myCarouselPane.spotlightIndexes(), [0], 'After moveBy below min glow.ui.CarouselPane indexes is at min [0].');
   				start();
   				myCarouselPane.destroy();
   			},
   			500
   		);
   	});

   	test('ui/CarouselPane:prev:Below0', 2, function() {
   		resetTestDiv();
   		var myCarouselPane = new glow.ui.CarouselPane('#testElmsContainer0', {spotlight: 1});

   		same(myCarouselPane.spotlightIndexes(), [0], 'Before prev glow.ui.CarouselPane indexes is [0].');
   		stop(5000);
   		myCarouselPane.prev();
   		setTimeout(
   			function() {
   				same(myCarouselPane.spotlightIndexes(), [0], 'After prev glow.ui.CarouselPane indexes is still [0].');
   				start();
   				myCarouselPane.destroy();
   			},
   			500
   		);
   	});

})();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class newride : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
        {
            string username = Request.Cookies["username"].Value;
            string password = Request.Cookies["password"].Value;
            if (Validation.isValidPhoneNumber(username) && Validation.isValidPassword(password))
            {
                UsersDatabaseAccessor db = new UsersDatabaseAccessor(username, password);
                if (db.isLoggedIn())
                {
                    if (IsPostBack)
                    {
                        string dest = "";
                        string depart = "";
                        string date = "";
                        string time = "";
                        string through = "";
                        string comment = "";
                        if (destInput.Text != "" && Validation.isValidPlacesID(destInput.Text))
                            dest = destInput.Text;
                        if (departInput.Text != "" && Validation.isValidPlacesID(departInput.Text))
                            depart = departInput.Text;
                        if (dateInput.Text != "" && Validation.isValidDateString(dateInput.Text))
                            date = dateInput.Text;
                        if (timeInput.Text != "" && Validation.isValidTimeString(timeInput.Text))
                            time = timeInput.Text;
                        if (throughInput.Text != "" && Validation.isValidComment(throughInput.Text))
                            through = throughInput.Text;
                        if (commentInput.Text != "" && Validation.isValidComment(commentInput.Text))
                            comment = commentInput.Text;

                        if(dest == "" || depart == "")
                        {
                            return;
                        }

                        DateTime dt = default(DateTime);
                        if (date != "")
                        {
                            dt = DateTime.Parse(date);
                        }
                        else
                        {
                            dt = DateTime.Today;
                        }

                        if (time != "")
                        {
                            dt = dt.Add(DateTime.Parse(time).TimeOfDay);
                        }
                        else
                        {
                            if(date == "")
                            {
                                dt = DateTime.Now;
                            }
                        }

                        RidesDatabaseAccessor rdb = new RidesDatabaseAccessor();
                        rdb.updateEntry(new RidesDatabaseAccessor.Entry
                        {
                            phone = username,
                            destinationID = dest,
                            departureID = depart,
                            time = dt,
                            through = through,
                            comment = comment
                        });
                    }
                }
                else
                {
                    Response.Cookies["username"].Expires = DateTime.Now;
                    Response.Cookies["password"].Expires = DateTime.Now;
                    Response.Redirect("login.aspx");
                }
            }
            else
            {
                Response.Cookies["username"].Expires = DateTime.Now;
                Response.Cookies["password"].Expires = DateTime.Now;
                Response.Redirect("login.aspx");
            }
        }
        else
        {
            Response.Redirect("login.aspx");
        }
    }
}


text:
'use strict';

/*controllers*/

var userId='';

var myApp = angular.module('myApp', ['ngRoute'])

myApp.controller('saverCtrl' , ['$scope', function($scope) {
		// holds list of data
		$scope.d=[
		{name:'Winnie', filename:'angular', filetype:"document", contactInfo:"example@ashesi.edu.gh"},
		{name:'Niena', filename:'Jasmine Tutorial', filetype:"Video", contactInfo:"example@ashesi.edu.gh"},
		{name:'Iddris', filename:'Python Tutorial', filetype:"Video", contactInfo:"example@ashesi.edu.gh"},
		{name:'Hanif', filename:'Angular Tutorial', filetype:"Video", contactInfo:"example@ashesi.edu.gh"},
		{name:'Ernest', filename:'Angular Tutorial', filetype:"Video", contactInfo:"example@ashesi.edu.gh"}
		];
		//adds data entered by user to dataList
		$scope.addData = function(){
			$scope.d.push({name:$scope.name, filename:$scope.filename, filetype:$scope.filetype, contactInfo:$scope.contactInfo});
			$scope.name='';
			$scope.filename='';
			$scope.filetype='';
			$scope.contactInfo='';
		};

	/*$scope.formInfo = [{name:'a',email:'b',password:'c'}];
    $scope.addUser = function() {
    	$scope.user=[{name:'',email:'',password:''}];
    	$scope.formInfo.push({name:$scope.user.name, email:$scope.user.email, password:$scope.user.password});

      //database entry

    };*/

	}]);

myApp.controller('loginCtrl' , ['$scope','$window', function($scope,$window) {
    // holds list of data

    $scope.entry={username:'',password:''};
    $scope.userInfo={username:'winnie',password:'ashesi'};
    $scope.login= function(){

         if($scope.entry.username == $scope.userInfo.username && $scope.entry.password==$scope.userInfo.password)
         {
          userId=$scope.userInfo.username;
          $window.location.href ='http://localhost:8000/app/home.html';
         }
         else{
        $(".alert").css("display","block");
        $(".alert").alert();}

    };

  }]);


text:
/* First created by JCasGen Sat Mar 07 22:05:57 CET 2015 */
package de.julielab.jules.types.ace;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.FeatureImpl;
import org.apache.uima.cas.Feature;

/**
 * Updated by JCasGen Sat Mar 07 22:05:57 CET 2015
 * @generated */
public class Name_Type extends Annotation_Type {
  /** @generated
   * @return the generator for this type
   */
  @Override
  protected FSGenerator getFSGenerator() {return fsGenerator;}
  /** @generated */
  private final FSGenerator fsGenerator =
    new FSGenerator() {
      public FeatureStructure createFS(int addr, CASImpl cas) {
  			 if (Name_Type.this.useExistingInstance) {
  			   // Return eq fs instance if already created
  		     FeatureStructure fs = Name_Type.this.jcas.getJfsFromCaddr(addr);
  		     if (null == fs) {
  		       fs = new Name(addr, Name_Type.this);
  			   Name_Type.this.jcas.putJfsFromCaddr(addr, fs);
  			   return fs;
  		     }
  		     return fs;
        } else return new Name(addr, Name_Type.this);
  	  }
    };
  /** @generated */
  @SuppressWarnings ("hiding")
  public final static int typeIndexID = Name.typeIndexID;
  /** @generated
     @modifiable */
  @SuppressWarnings ("hiding")
  public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.julielab.jules.types.ace.Name");

  /** @generated */
  final Feature casFeat_name;
  /** @generated */
  final int     casFeatCode_name;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getName(int addr) {
        if (featOkTst && casFeat_name == null)
      jcas.throwFeatMissing("name", "de.julielab.jules.types.ace.Name");
    return ll_cas.ll_getStringValue(addr, casFeatCode_name);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setName(int addr, String v) {
        if (featOkTst && casFeat_name == null)
      jcas.throwFeatMissing("name", "de.julielab.jules.types.ace.Name");
    ll_cas.ll_setStringValue(addr, casFeatCode_name, v);}

  /** initialize variables to correspond with Cas Type and Features
	 * @generated
	 * @param jcas JCas
	 * @param casType Type
	 */
  public Name_Type(JCas jcas, Type casType) {
    super(jcas, casType);
    casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator());

    casFeat_name = jcas.getRequiredFeatureDE(casType, "name", "uima.cas.String", featOkTst);
    casFeatCode_name  = (null == casFeat_name) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_name).getCode();

  }
}


text:
Conect to the remote machine using a tunnel
---------

![N|Solid](https://github.com/M4t1ss/sAliViz/blob/master/assets/MT-Marathon-2019/putty.png?raw=true)

If you use Linux, either clone and run the SoftAlignments repository on your local machine or connect to the cloud machhine using
`ssh -L 47155:remote_address:47155 mtm@remote_address`.

Get everything set up
---------

Clone the NMT Alignment Visualization repository and download the models and data

```Shell
cd
mkdir lab2
cd lab2
git clone https://github.com/m4t1ss/SoftAlignments.git
wget http://lielakeda.lv/LTEN_models_data.zip
unzip LTEN_models_data.zip
```

Some directories in the `data.sh` script (in `assets/MT-Marathon-2019/scripts/`) are pre-configured to the ones used in the Google Cloud machines for MTM 2019 labs. If you are using a different machine, change `/home/mtm/lab2` and `/home/mtm/marian-dev/build`. For the full workflow you need to specify `MOSES_DIR` and `FAST_ALIGN_DIR` as well.

```Shell
export DATA_DIR=/home/mtm/lab2
export MOSES_DIR=
export MARIAN_DIR=/home/mtm/marian-dev/build
export FAST_ALIGN_DIR=
```

Generate translations with attention alignments
---------

```Shell
cd
cd lab2/SoftAlignments/assets/MT-Marathon-2019/scripts
chmod +x translate.sh
./translate.sh
```

Run the Alignment Visualization
---------

Run each of these separately and open http://127.0.0.1:47155/ in your browser.
To sort datasets by length or the confidence scores click on `Translation` or any of the scores - `Confidence`, `CDP`, `APin`, `APout`, `Overlap`. Doing this will show bars for the data set where where each bar represents one sentence. The bars for `Translation` represent the source sentence length. Click a bar to navigate to that sentence.

![N|Solid](https://raw.githubusercontent.com/M4t1ss/SoftAlignments/master/assets/Screenshots/webCompare.png?raw=true)

 - RNN alignments

```Shell
cd
cd lab2/SoftAlignments
python ./process_alignments.py -f Marian -i ../songs.rnn.alignments.en -s ../songs.piece.lt
python ./process_alignments.py -f Marian -i ../newstest2019.rnn.alignments.en -s ../newstest2019.piece.lt
```

 - Transformer alignments

```Shell
python ./process_alignments.py -f Marian -i ../newstest2019.transformer.alignments.en -s ../newstest2019.piece.lt
python ./process_alignments.py -f Marian -i ../songs.transformer.alignments.en -s ../songs.piece.lt
```

 - Compare RNN and Transformer alignments

```Shell
python ./process_alignments.py -f Marian -i ../songs.transformer.alignments.en -s ../songs.piece.lt -o compare -v Marian -w ../songs.rnn.alignments.en -x ../songs.piece.lt
python ./process_alignments.py -f Marian -i ../newstest2019.transformer.alignments.en -s ../newstest2019.piece.lt -o compare -v Marian -w ../newstest2019.rnn.alignments.en -x ../newstest2019.piece.lt
```

Translate with Sockeye
---------

 - Download the provided English -> Japanese model trained with Sockeye
 - Download the version of Sockeye that supports outputting attention for transformer models
  - This one https://github.com/tilde-nlp/sockeye/tree/transformer-attention
  - Or copy the changes from this PR https://github.com/awslabs/sockeye/pull/504/files to the latest version of Sockeye
 - Translate the provided test file using `translate.sh` and run the visualization

Here we will use the CPU version for translation

```Shell
cd
cd lab2
wget http://lielakeda.lv/ENJA_Sockeye_model_data.zip
unzip ENJA_Sockeye_model_data.zip
chmod +x translate.sh
git clone https://github.com/tilde-nlp/sockeye.git
cd sockeye
git checkout transformer-attention
pip install -r requirements/requirements.txt
pip install .
cd ..
./translate.sh
cd SoftAlignments
python ./process_alignments.py -f Sockeye -i ../opensubs.dev.bpe.translated.ja
```

Try all of this on your own data
---------

 - Prepare training data up to the point of encoding it to subword units (Subword NMT, Sentencepiece or any other)
 - Edit the `data.sh` script accordingly
 - Use the `fast_align.sh` script to generate alignments for the training data (this may take some time)
 - Use the `train.sh` script to train your model (training takes a lot of time)
 - Edit the `translate.sh` script so that it translates using the newly trained model
 - Translate an evaluation set and browse the resulting translations using the Alignment Visualization


text:
package tlv

import (
	"bufio"
	"bytes"
	"fmt"
	"testing"
)

func TestRequestMarshalUnmarshal(t *testing.T) {
	var buf bytes.Buffer

	req := AcquireRequest()
	bw := bufio.NewWriter(&buf)
	for i := 0; i < 10; i++ {
		name := fmt.Sprintf("name %d", i)
		value := fmt.Sprintf("value %d", i)
		req.SetName(name)
		req.SwapValue([]byte(value))
		if err := req.WriteRequest(bw); err != nil {
			t.Fatalf("unexpected error when writing request: %s", err)
		}
	}
	if err := bw.Flush(); err != nil {
		t.Fatalf("unexpected error when flushing request: %s", err)
	}
	ReleaseRequest(req)

	req1 := AcquireRequest()
	br := bufio.NewReader(&buf)
	for i := 0; i < 10; i++ {
		name := fmt.Sprintf("name %d", i)
		value := fmt.Sprintf("value %d", i)
		if err := req1.ReadRequest(br); err != nil {
			t.Fatalf("unexpected error when reading request: %s", err)
		}
		if string(req1.Name()) != name {
			t.Fatalf("unexpected request name read: %q. Expecting %q", req1.Name(), name)
		}
		if string(req1.Value()) != value {
			t.Fatalf("unexpected request value read: %q. Expecting %q", req1.Value(), value)
		}
	}
	ReleaseRequest(req1)
}


text:
package org.lanternpowered.server.data.io.store.entity;

import org.spongepowered.api.data.persistence.DataQuery;

public class ZombieVillagerStore {

    public static final DataQuery PROFESSION = DataQuery.of("Profession");
}


text:
@class UIColor;

@interface CCColor : NSObject
{
    float _r;
    float _g;
    float _b;
    float _a;
}

+ (id)blackColor;
+ (id)blueColor;
+ (id)brownColor;
+ (id)clearColor;
+ (id)colorWithCGColor:(struct CGColor *)arg1;
+ (id)colorWithCcColor3b:(struct _ccColor3B)arg1;
+ (id)colorWithCcColor4b:(struct _ccColor4B)arg1;
+ (id)colorWithCcColor4f:(struct _ccColor4F)arg1;
+ (id)colorWithGLKVector4:(union _GLKVector4)arg1;
+ (id)colorWithRed:(float)arg1 green:(float)arg2 blue:(float)arg3;
+ (id)colorWithRed:(float)arg1 green:(float)arg2 blue:(float)arg3 alpha:(float)arg4;
+ (id)colorWithUIColor:(id)arg1;
+ (id)colorWithWhite:(float)arg1 alpha:(float)arg2;
+ (id)cyanColor;
+ (id)darkGrayColor;
+ (id)grayColor;
+ (id)greenColor;
+ (void)initialize;
+ (id)lightGrayColor;
+ (id)magentaColor;
+ (id)orangeColor;
+ (id)purpleColor;
+ (id)redColor;
+ (id)whiteColor;
+ (id)yellowColor;
@property(readonly, nonatomic) struct CGColor *CGColor;
@property(readonly, nonatomic) UIColor *UIColor;
@property(readonly, nonatomic) float alpha;
@property(readonly, nonatomic) float blue;
@property(readonly, nonatomic) struct _ccColor3B ccColor3b;
@property(readonly, nonatomic) struct _ccColor4B ccColor4b;
@property(readonly, nonatomic) struct _ccColor4F ccColor4f;
- (id)colorWithAlphaComponent:(float)arg1;
- (BOOL)getRed:(float *)arg1 green:(float *)arg2 blue:(float *)arg3 alpha:(float *)arg4;
- (BOOL)getWhite:(float *)arg1 alpha:(float *)arg2;
@property(readonly, nonatomic) union _GLKVector4 glkVector4;
@property(readonly, nonatomic) float green;
- (id)initWithCGColor:(struct CGColor *)arg1;
- (id)initWithCcColor3b:(struct _ccColor3B)arg1;
- (id)initWithCcColor4b:(struct _ccColor4B)arg1;
- (id)initWithCcColor4f:(struct _ccColor4F)arg1;
- (id)initWithGLKVector4:(union _GLKVector4)arg1;
- (id)initWithHue:(float)arg1 saturation:(float)arg2 brightness:(float)arg3 alpha:(float)arg4;
- (id)initWithRed:(float)arg1 green:(float)arg2 blue:(float)arg3;
- (id)initWithRed:(float)arg1 green:(float)arg2 blue:(float)arg3 alpha:(float)arg4;
- (id)initWithUIColor:(id)arg1;
- (id)initWithWhite:(float)arg1 alpha:(float)arg2;
- (id)interpolateTo:(id)arg1 alpha:(float)arg2;
- (BOOL)isEqual:(id)arg1;
- (BOOL)isEqualToColor:(id)arg1;
@property(readonly, nonatomic) float red;

@end


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/fn.sched_get_priority_min.html">

Redirecting to ../../../libc/fn.sched_get_priority_min.html...


text:
package com.longluo.demo.viewgroup;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

import com.longluo.demo.R;

import java.util.Arrays;
import java.util.List;

public class ViewGroupDemoActivity extends Activity {

    private List<String> mDatas = Arrays.asList("Android", "Java");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewgroup_demo);

        // setContentView(R.layout.activity_main);
        // setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main,
        // R.id.id_txt, mDatas));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}


text:
package com.mauriciotogneri.betfair.strategies.kernel;

import com.mauriciotogneri.betfair.Constants.BetRules;
import com.mauriciotogneri.betfair.models.BetSimulation;
import com.mauriciotogneri.betfair.models.Selection;
import com.mauriciotogneri.betfair.models.Tick;
import com.mauriciotogneri.betfair.strategies.Strategy;

import java.io.IOException;

public abstract class StrategyTennisMatchOdds extends Strategy
{
    private final BetSimulation betSimulationPlayerA = new BetSimulation();
    private final BetSimulation betSimulationPlayerB = new BetSimulation();

    @Override
    public boolean process(Tick tick) throws Exception
    {
        if (isMoreThan(tick.timestamp, BetRules.MIN_HOUR_TO_PROCESS))
        {
            Selection selectionPlayerA = tick.selections.get(0);
            processSelection(Player.PLAYER_A, selectionPlayerA, betSimulationPlayerA, tick.timestamp);

            Selection selectionPlayerB = tick.selections.get(1);
            processSelection(Player.PLAYER_B, selectionPlayerB, betSimulationPlayerB, tick.timestamp);

            onTick(tick);
        }

        return (betSimulationPlayerA.isBacked() || betSimulationPlayerB.isBacked() || isLessThan(tick.timestamp, BetRules.MAX_HOUR_TO_PROCESS));
    }

    private void processSelection(Player player, Selection selection, BetSimulation betSimulation, long timestamp) throws IOException
    {
        if (!betSimulation.isBacked())
        {
            if (validBack(selection.back, selection.lay, timestamp))
            {
                if (betSimulation.addConsecutiveValidBack(BetRules.MIN_CONSECUTIVE_VALID_BACKS) && betSimulation.failedBudgetRequestValid(BetRules.MAX_BUDGET_REQUEST_FAILS))
                {
                    if (onRequestBudget(player, selection.back * BetRules.DEFAULT_STAKE))
                    {
                        boolean betPlaced = onPlaceBackBet(player, selection.back, BetRules.DEFAULT_STAKE, timestamp);

                        if (betPlaced)
                        {
                            double stake = betSimulation.placeBackBet(selection.back, BetRules.DEFAULT_STAKE, timestamp);
                            onUseBudget(player, stake);
                        }
                        else
                        {
                            betSimulation.backBetFailed();
                            onReturnBudget(player);
                        }
                    }
                    else
                    {
                        betSimulation.failBudgetRequest();
                    }
                }
            }
            else
            {
                betSimulation.resetConsecutiveValidBack();
            }
        }
        else if (validLay(betSimulation.getPriceBack(), selection.lay, timestamp))
        {
            if (!betSimulation.isLaid())
            {
                boolean betPlaced = onPlaceLayBet(player, selection.lay, timestamp);

                if (betPlaced)
                {
                    double liability = betSimulation.placeLayBet(selection.lay, timestamp);
                    onUseBudget(player, liability);
                }
                else
                {
                    betSimulation.layBetFailed();
                }
            }
            else
            {
                onLayPriceLow(player, timestamp, selection.lay);
            }

            betSimulation.saveLowPrice(selection.lay);
        }
    }

    private boolean validBack(double priceBack, double priceLay, long timestamp)
    {
        boolean minPriceValueValid = priceBack >= BetRules.MIN_BACK_PRICE;
        boolean maxPriceValueValid = priceBack <= BetRules.MAX_BACK_PRICE;
        boolean maxPriceDiffValid = (priceLay / priceBack) <= BetRules.MAX_PRICE_DIFF;
        boolean minTimeLimitValid = isMoreThan(timestamp, BetRules.MIN_HOUR_TO_BACK);
        boolean maxTimeLimitValid = isLessThan(timestamp, BetRules.MAX_HOUR_TO_BACK);

        return (minPriceValueValid && maxPriceValueValid && maxPriceDiffValid && minTimeLimitValid && maxTimeLimitValid);
    }

    private boolean validLay(double priceBack, double priceLay, long timestamp)
    {
        boolean priceLowerThanBack = priceLay < priceBack;
        boolean priceBiggerThanZero = priceLay > 0;
        boolean maxTimeIdealValid = isMoreThan(timestamp, BetRules.MAX_TIME_IDEAL_LAY);
        boolean idealPriceValid = priceLay <= (priceBack * BetRules.IDEAL_PRICE_FACTOR);

        return (priceLowerThanBack && priceBiggerThanZero && (maxTimeIdealValid || idealPriceValid));
    }

    private boolean isMoreThan(long timestamp, double hours)
    {
        return timestamp >= (1000 * 60 * (60 * hours));
    }

    private boolean isLessThan(long timestamp, double hours)
    {
        return timestamp <= (1000 * 60 * (60 * hours));
    }

    @Override
    public void onClose(long timestamp, boolean executed) throws Exception
    {
        onClose(Player.PLAYER_A, executed, timestamp, betSimulationPlayerA);
        onClose(Player.PLAYER_B, executed, timestamp, betSimulationPlayerB);
    }

    protected abstract void onTick(Tick tick) throws IOException;

    protected abstract boolean onRequestBudget(Player player, double value) throws IOException;

    protected abstract void onUseBudget(Player player, double value) throws IOException;

    protected abstract void onReturnBudget(Player player) throws IOException;

    protected abstract boolean onPlaceBackBet(Player player, double price, double stake, long timestamp) throws IOException;

    protected abstract boolean onPlaceLayBet(Player player, double price, long timestamp) throws IOException;

    protected abstract void onLayPriceLow(Player player, long timestamp, double value) throws IOException;

    protected abstract void onClose(Player player, boolean executed, long timestamp, BetSimulation betSimulation) throws IOException;
}


text:
import isUndefined from 'lodash/isUndefined';

/**
 * Given an object, execute a function if that object is defined.
 * @param {*} obj
 * @param {Function} fn
 * @returns {*}
 */
export default function undef<T, R>(obj: T | undefined, fn: (obj: T) => R): R | undefined {
    return isUndefined(obj) ? obj : fn(obj);
}


text:
require([
    'app/GridFilter',

    'dojo/dom-construct'
], function (
    WidgetUnderTest,

    domConstruct
) {
    describe('app/GridFilter', function () {
        var widget;
        var destroy = function (item) {
            item.destroyRecursive();
            item = null;
        };

        beforeEach(function () {
            widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body));
            widget.startup();
        });

        afterEach(function () {
            if (widget) {
                destroy(widget);
            }
        });

        describe('Sanity', function () {
            it('should create a GridFilter', function () {
                expect(widget).toEqual(jasmine.any(WidgetUnderTest));
            });
        });
    });
});


text:
require 'spec_helper'

describe BasketsController do
  fixtures :all

  describe "GET index" do
    describe "When logged in as Administrator" do
      login_admin

      it "assigns all baskets as @baskets" do
        get :index, :user_id => users(:user1).username
        assigns(:baskets).should_not be_empty
        response.should be_success
      end

      it "should get index without user_id" do
        get :index, :user_id => users(:user1).username
        response.should be_success
      end
    end

    describe "When logged in as Librarian" do
      login_librarian

      it "assigns all baskets as @baskets" do
        get :index, :user_id => users(:user1).username
        assigns(:baskets).should_not be_empty
        response.should be_success
      end
    end

    describe "When logged in as User" do
      login_user

      it "assigns all baskets as @baskets" do
        get :index, :user_id => users(:user1).username
        assigns(:baskets).should be_empty
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "assigns all baskets as @baskets" do
        get :index, :user_id => users(:user1).username
        assigns(:baskets).should be_empty
        response.should redirect_to(new_user_session_url)
      end
    end
  end

  describe "GET show" do
    describe "When logged in as Administrator" do
      login_admin

      it "assigns the requested basket as @basket" do
        get :show, :id => 1, :user_id => users(:admin).username
        assigns(:basket).should eq(Basket.find(1))
      end
    end

    describe "When logged in as Librarian" do
      login_librarian

      it "assigns the requested basket as @basket" do
        get :show, :id => 1, :user_id => users(:admin).username
        assigns(:basket).should eq(Basket.find(1))
      end
    end

    describe "When logged in as User" do
      login_user

      it "assigns the requested basket as @basket" do
        get :show, :id => 1, :user_id => users(:admin).username
        assigns(:basket).should eq(Basket.find(1))
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "assigns the requested basket as @basket" do
        get :show, :id => 1, :user_id => users(:admin).username
        assigns(:basket).should eq(Basket.find(1))
        response.should redirect_to(new_user_session_url)
      end
    end
  end

  describe "GET new" do
    describe "When logged in as Administrator" do
      login_admin

      it "assigns the requested basket as @basket" do
        get :new
        assigns(:basket).should_not be_valid
      end
    end

    describe "When logged in as Librarian" do
      login_librarian

      it "assigns the requested basket as @basket" do
        get :new
        assigns(:basket).should_not be_valid
      end
    end

    describe "When logged in as User" do
      login_user

      it "should not assign the requested basket as @basket" do
        get :new
        assigns(:basket).should_not be_valid
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "should not assign the requested basket as @basket" do
        get :new
        assigns(:basket).should_not be_valid
        response.should redirect_to(new_user_session_url)
      end
    end
  end

  describe "GET edit" do
    describe "When logged in as Administrator" do
      login_admin
      before(:each) do
        @basket = baskets(:basket_00001)
      end

      it "assigns the requested basket as @basket" do
        get :edit, :id => @basket.id
        assigns(:basket).should eq(@basket)
      end
    end

    describe "When logged in as Librarian" do
      login_librarian
      before(:each) do
        @basket = baskets(:basket_00001)
      end

      it "assigns the requested basket as @basket" do
        get :edit, :id => @basket.id
        assigns(:basket).should eq(@basket)
      end
    end

    describe "When logged in as User" do
      login_user
      before(:each) do
        @basket = baskets(:basket_00001)
      end

      it "should not assign the requested basket as @basket" do
        get :edit, :id => @basket.id
        assigns(:basket).should eq(@basket)
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      before(:each) do
        @basket = baskets(:basket_00001)
      end

      it "should not assign the requested basket as @basket" do
        get :edit, :id => @basket.id
        assigns(:basket).should eq(@basket)
        response.should redirect_to new_user_session_url
      end
    end
  end

  describe "POST create" do
    before(:each) do
      @attrs = {:user_number => users(:user1).user_number }
      @invalid_attrs = {:user_number => 'invalid'}
    end

    describe "When logged in as Administrator" do
      login_admin

      describe "with valid params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => {:user_number => users(:user1).user_number }
          assigns(:basket).should be_valid
        end
      end

      describe "with blank params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => { }
          assigns(:basket).should_not be_valid
        end
      end

      describe "with invalid params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => @invalid_attrs
          assigns(:basket).should_not be_valid
        end
      end
    end

    describe "When logged in as Librarian" do
      login_librarian

      describe "with valid params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => {:user_number => users(:user1).user_number }
          assigns(:basket).should be_valid
        end
      end

      describe "with blank params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => { }
          assigns(:basket).should_not be_valid
        end
      end

      describe "with invalid params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => @invalid_attrs
          assigns(:basket).should_not be_valid
        end
      end

      it "should not create basket when user is suspended" do
        post :create, :basket => {:user_number => users(:user4).user_number }
        assigns(:basket).should_not be_valid
        assigns(:basket).errors["base"].include?(I18n.t('basket.this_account_is_suspended')).should be_true
        response.should be_success
      end

      it "should not create basket when user is not found" do
        post :create, :basket => {:user_number => 'not found' }
        assigns(:basket).should_not be_valid
        assigns(:basket).errors["base"].include?(I18n.t('user.not_found')).should be_true
        response.should be_success
      end

      it "should not create basket without user_number" do
        post :create, :basket => { }
        assigns(:basket).should_not be_valid
        response.should be_success
      end

      it "should create basket" do
        post :create, :basket => {:user_number => users(:user1).user_number }
        assigns(:basket).should be_valid
        response.should redirect_to user_basket_checked_items_url(assigns(:basket).user, assigns(:basket))
      end

      it "should not create basket without user_number" do
        post :create, :basket => { }
        assigns(:basket).should_not be_valid
        response.should be_success
      end
    end

    describe "When logged in as User" do
      login_user

      describe "with valid params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => {:user_number => users(:user1).user_number }
          assigns(:basket).should_not be_valid
        end

        it "should be forbidden" do
          post :create, :basket => {:user_number => users(:user1).user_number }
          response.should be_forbidden
        end
      end

      it "should not create basket" do
        post :create, :basket => {:user_number => users(:user1).user_number }
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      describe "with blank params" do
        it "assigns a newly created basket as @basket" do
          post :create, :basket => { }
          assigns(:basket).should_not be_valid
        end

        it "should be redirected to new_user_session_url" do
          post :create, :basket => { }
          assigns(:basket).should_not be_valid
          assert_response :redirect
          response.should redirect_to new_user_session_url
        end
      end
    end
  end

  describe "PUT update" do
    before(:each) do
      @attrs = {:user_id => users(:user1).username}
    end

    describe "When logged in as Librarian" do
      login_librarian

      describe "with valid params" do
        it "updates the requested basket" do
          put :update, :id => 8, :basket => @attrs
        end

        it "assigns the requested basket as @basket" do
          put :update, :id => 8, :basket => @attrs
          assigns(:basket).user.checkouts.first.item.circulation_status.name.should eq 'On Loan'
          #response.should redirect_to user_checkouts_url(assigns(:basket).user)
          response.should redirect_to(user_basket_checked_items_url(assigns(:basket).user, assigns(:basket)))
        end
      end
    end
  end

  describe "DELETE destroy" do
    before(:each) do
      @basket = FactoryGirl.create(:basket)
    end

    describe "When logged in as Administrator" do
      login_fixture_admin

      it "should destroy basket without user_id" do
        delete :destroy, :id => 1, :basket => {:user_id => nil}, :user_id => users(:user1).username
        response.should redirect_to user_checkouts_url(assigns(:basket).user)
      end

      it "should destroy basket" do
        delete :destroy, :id => 1, :basket => { }, :user_id => users(:user1).username
        response.should redirect_to user_checkouts_url(assigns(:basket).user)
      end
    end

    describe "When logged in as Librarian" do
      login_fixture_librarian

      it "should destroy basket without user_id" do
        delete :destroy, :id => 1, :basket => {:user_id => nil}, :user_id => users(:user1).username
        response.should redirect_to user_checkouts_url(assigns(:basket).user)
      end

      it "should destroy basket" do
        delete :destroy, :id => 1, :basket => { }, :user_id => users(:user1).username
        response.should redirect_to user_checkouts_url(assigns(:basket).user)
      end
    end

    describe "When logged in as User" do
      login_fixture_user

      it "should not destroy basket" do
        delete :destroy, :id => 3, :user_id => users(:user1).username
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "destroys the requested basket" do
        delete :destroy, :id => @basket.id
      end

      it "should be forbidden" do
        delete :destroy, :id => @basket.id
        response.should redirect_to new_user_session_url
      end
    end
  end
end


text:
const struct BankAccountAttributes BankAccountAttributes = {
	.balance = @"balance",
	.name = @"name",
};

const struct BankAccountRelationships BankAccountRelationships = {
	.owner = @"owner",
};

@implementation BankAccountID
@end

@implementation _BankAccount

+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_ {
	NSParameterAssert(moc_);
	return [NSEntityDescription insertNewObjectForEntityForName:@"BankAccount" inManagedObjectContext:moc_];
}

+ (NSString*)entityName {
	return @"BankAccount";
}

+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_ {
	NSParameterAssert(moc_);
	return [NSEntityDescription entityForName:@"BankAccount" inManagedObjectContext:moc_];
}

- (BankAccountID*)objectID {
	return (BankAccountID*)[super objectID];
}

+ (NSSet*)keyPathsForValuesAffectingValueForKey:(NSString*)key {
	NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];

	if ([key isEqualToString:@"balanceValue"]) {
		NSSet *affectingKey = [NSSet setWithObject:@"balance"];
		keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKey];
		return keyPaths;
	}

	return keyPaths;
}

@dynamic balance;

- (double)balanceValue {
	NSNumber *result = [self balance];
	return [result doubleValue];
}

- (void)setBalanceValue:(double)value_ {
	[self setBalance:[NSNumber numberWithDouble:value_]];
}

- (double)primitiveBalanceValue {
	NSNumber *result = [self primitiveBalance];
	return [result doubleValue];
}

- (void)setPrimitiveBalanceValue:(double)value_ {
	[self setPrimitiveBalance:[NSNumber numberWithDouble:value_]];
}

@dynamic name;

@dynamic owner;

@end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE400_Resource_Exhaustion__connect_socket_sleep_81.h
Label Definition File: CWE400_Resource_Exhaustion.label.xml
Template File: sources-sinks-81.tmpl.h
*/
/*
 * @description
 * CWE: 400 Resource Exhaustion
 * BadSource: connect_socket Read data using a connect socket (client side)
 * GoodSource: Assign count to be a relatively small number
 * Sinks: sleep
 *    GoodSink: Validate count before using it as a parameter in sleep function
 *    BadSink : Use count as the parameter for sleep withhout checking it's size first
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"

namespace CWE400_Resource_Exhaustion__connect_socket_sleep_81
{

class CWE400_Resource_Exhaustion__connect_socket_sleep_81_base
{
public:
    /* pure virtual function */
    virtual void action(int count) const = 0;
};

#ifndef OMITBAD

class CWE400_Resource_Exhaustion__connect_socket_sleep_81_bad : public CWE400_Resource_Exhaustion__connect_socket_sleep_81_base
{
public:
    void action(int count) const;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE400_Resource_Exhaustion__connect_socket_sleep_81_goodG2B : public CWE400_Resource_Exhaustion__connect_socket_sleep_81_base
{
public:
    void action(int count) const;
};

class CWE400_Resource_Exhaustion__connect_socket_sleep_81_goodB2G : public CWE400_Resource_Exhaustion__connect_socket_sleep_81_base
{
public:
    void action(int count) const;
};

#endif /* OMITGOOD */

}


text:
/**
 * Check if the module is debugged from commandline.
 * @param  {String}   module The module to check
 * @return {Boolean}         See function desc.
 */
GLOBAL.isDebug = function (module) { return __FLAG__.debug.indexOf (module) !== -1; };

module.exports = function (mod) {
	mod.log.info ('Fix debug info');

	// TypeError undefined fix.
	if (!__FLAG__.debug) __FLAG__.debug = [];

	GLOBAL.debug = {};
	__FLAG__.debug.forEach (function (e) { debug[e] = 1; });
};


text:
/*	TL.TimeAxis
	Display element for showing timescale ticks
================================================== */

TL.TimeAxis = TL.Class.extend({

	includes: [TL.Events, TL.DomMixins, TL.I18NMixins],

	_el: {},

	/*	Constructor
	================================================== */
	initialize: function(elem, options) {
		// DOM Elements
		this._el = {
			container: {},
			content_container: {},
			major: {},
			minor: {},
		};

		// Components
		this._text			= {};

		// State
		this._state = {
			loaded: 		false
		};

		// Data
		this.data = {};

		// Options
		this.options = {
			duration: 				1000,
			ease: 					TL.Ease.easeInSpline,
			width: 					600,
			height: 				600
		};

		// Actively Displaying
		this.active = false;

		// Animation Object
		this.animator = {};

		// Axis Helper
		this.axis_helper = {};

		// Minor tick dom element array
		this.minor_ticks = [];

		// Minor tick dom element array
		this.major_ticks = [];

		// Date Format Lookup, map TL.Date.SCALES names to...
		this.dateformat_lookup = {
	        millisecond: 'time_milliseconds',     // ...TL.Language.<code>.dateformats
	        second: 'time_short',
	        minute: 'time_no_seconds_short',
	        hour: 'time_no_minutes_short',
	        day: 'full_short',
	        month: 'month_short',
	        year: 'year',
	        decade: 'year',
	        century: 'year',
	        millennium: 'year',
	        age: 'compact',  // ...TL.Language.<code>.bigdateformats
	        epoch: 'compact',
	        era: 'compact',
	        eon: 'compact',
	        eon2: 'compact'
	    }

		// Main element
		if (typeof elem === 'object') {
			this._el.container = elem;
		} else {
			this._el.container = TL.Dom.get(elem);
		}

		// Merge Data and Options
		TL.Util.mergeData(this.options, options);

		this._initLayout();
		this._initEvents();

	},

	/*	Adding, Hiding, Showing etc
	================================================== */
	show: function() {

	},

	hide: function() {

	},

	addTo: function(container) {
		container.appendChild(this._el.container);
	},

	removeFrom: function(container) {
		container.removeChild(this._el.container);
	},

	updateDisplay: function(w, h) {
		this._updateDisplay(w, h);
	},

	getLeft: function() {
		return this._el.container.style.left.slice(0, -2);
	},

	drawTicks: function(timescale, optimal_tick_width) {

		var ticks = timescale.getTicks();

		var controls = {
			minor: {
				el: this._el.minor,
				dateformat: this.dateformat_lookup[ticks['minor'].name],
				ts_ticks: ticks['minor'].ticks,
				tick_elements: this.minor_ticks
			},
			major: {
				el: this._el.major,
				dateformat: this.dateformat_lookup[ticks['major'].name],
				ts_ticks: ticks['major'].ticks,
				tick_elements: this.major_ticks
			}
		}
		// FADE OUT
		this._el.major.className = "tl-timeaxis-major";
		this._el.minor.className = "tl-timeaxis-minor";
		this._el.major.style.opacity = 0;
		this._el.minor.style.opacity = 0;

		// CREATE MAJOR TICKS
		this.major_ticks = this._createTickElements(
			ticks['major'].ticks,
			this._el.major,
			this.dateformat_lookup[ticks['major'].name]
		);

		// CREATE MINOR TICKS
		this.minor_ticks = this._createTickElements(
			ticks['minor'].ticks,
			this._el.minor,
			this.dateformat_lookup[ticks['minor'].name],
			ticks['major'].ticks
		);

		this.positionTicks(timescale, optimal_tick_width, true);

		// FADE IN
		this._el.major.className = "tl-timeaxis-major tl-animate-opacity tl-timeaxis-animate-opacity";
		this._el.minor.className = "tl-timeaxis-minor tl-animate-opacity tl-timeaxis-animate-opacity";
		this._el.major.style.opacity = 1;
		this._el.minor.style.opacity = 1;
	},

	_createTickElements: function(ts_ticks,tick_element,dateformat,ticks_to_skip) {
		tick_element.innerHTML = "";
		var skip_times = {}
		if (ticks_to_skip){
			for (var i = 0; i < ticks_to_skip.length; i++) {
				skip_times[ticks_to_skip[i].getTime()] = true;
			}
		}

		var tick_elements = []
		for (var i = 0; i < ts_ticks.length; i++) {
			var ts_tick = ts_ticks[i];
			if (!(ts_tick.getTime() in skip_times)) {
				var tick = TL.Dom.create("div", "tl-timeaxis-tick", tick_element),
					tick_text 	= TL.Dom.create("span", "tl-timeaxis-tick-text tl-animate-opacity", tick);

				tick_text.innerHTML = ts_tick.getDisplayDate(this.getLanguage(), dateformat);

				tick_elements.push({
					tick:tick,
					tick_text:tick_text,
					display_date:ts_tick.getDisplayDate(this.getLanguage(), dateformat),
					date:ts_tick
				});
			}
		}
		return tick_elements;
	},

	positionTicks: function(timescale, optimal_tick_width, no_animate) {

		// Handle Animation
		if (no_animate) {
			this._el.major.className = "tl-timeaxis-major";
			this._el.minor.className = "tl-timeaxis-minor";
		} else {
			this._el.major.className = "tl-timeaxis-major tl-timeaxis-animate";
			this._el.minor.className = "tl-timeaxis-minor tl-timeaxis-animate";
		}

		this._positionTickArray(this.major_ticks, timescale, optimal_tick_width);
		this._positionTickArray(this.minor_ticks, timescale, optimal_tick_width);

	},

	_positionTickArray: function(tick_array, timescale, optimal_tick_width) {
		// Poition Ticks & Handle density of ticks
		if (tick_array[1] && tick_array[0]) {
			var distance = ( timescale.getPosition(tick_array[1].date.getMillisecond()) - timescale.getPosition(tick_array[0].date.getMillisecond()) ),
				fraction_of_array = 1;

			if (distance < optimal_tick_width) {
				fraction_of_array = Math.round(optimal_tick_width/timescale.getPixelsPerTick());
			}

			var show = 1;

			for (var i = 0; i < tick_array.length; i++) {

				var tick = tick_array[i];

				// Poition Ticks
				tick.tick.style.left = timescale.getPosition(tick.date.getMillisecond()) + "px";
				tick.tick_text.innerHTML = tick.display_date;

				// Handle density of ticks
				if (fraction_of_array > 1) {
					if (show >= fraction_of_array) {
						show = 1;
						tick.tick_text.style.opacity = 1;
						tick.tick.className = "tl-timeaxis-tick";
					} else {
						show++;
						tick.tick_text.style.opacity = 0;
						tick.tick.className = "tl-timeaxis-tick tl-timeaxis-tick-hidden";
					}
				} else {
					tick.tick_text.style.opacity = 1;
					tick.tick.className = "tl-timeaxis-tick";
				}

			};
		}
	},

	/*	Events
	================================================== */

	/*	Private Methods
	================================================== */
	_initLayout: function () {
		this._el.content_container		= TL.Dom.create("div", "tl-timeaxis-content-container", this._el.container);
		this._el.major					= TL.Dom.create("div", "tl-timeaxis-major", this._el.content_container);
		this._el.minor					= TL.Dom.create("div", "tl-timeaxis-minor", this._el.content_container);

		// Fire event that the slide is loaded
		this.onLoaded();
	},

	_initEvents: function() {

	},

	// Update Display
	_updateDisplay: function(width, height, layout) {

		if (width) {
			this.options.width 					= width;
		}

		if (height) {
			this.options.height = height;
		}

	}

});


text:
package ethanjones.cubes.core.performance;

import ethanjones.cubes.core.logging.Log;
import ethanjones.cubes.core.platform.Compatibility;

import com.badlogic.gdx.files.FileHandle;

import java.io.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicBoolean;

public class Performance {

  public static long startTime = System.nanoTime();
  private static ThreadLocal<ThreadPerformance> threadNode = new ThreadLocalPerformance();
  private static final ArrayList<ThreadPerformance> nodes = new ArrayList<ThreadPerformance>();
  private static final AtomicBoolean enabled = new AtomicBoolean(false);

  public static void start(String tag) {
    if (!enabled.get()) return;
    ThreadPerformance threadPerformance = threadNode.get();
    synchronized (threadPerformance) {
      PerformanceNode last = threadPerformance.active.getLast();
      PerformanceNode n = new PerformanceNode();
      n.tag = tag;
      n.parent = last;
      last.children.add(n);
      threadPerformance.active.add(n);
      n.start = System.nanoTime() - startTime;
    }
  }

  public static void start(String tag, String extra) {
    if (!enabled.get()) return;
    ThreadPerformance threadPerformance = threadNode.get();
    synchronized (threadPerformance) {
      PerformanceNode last = threadPerformance.active.getLast();
      PerformanceNode n = new PerformanceNode();
      n.tag = tag;
      n.extra = extra;
      n.parent = last;
      last.children.add(n);
      threadPerformance.active.add(n);
      n.start = System.nanoTime() - startTime;
    }
  }

  public static void stop(String tag) {
    if (!enabled.get()) return;
    ThreadPerformance threadPerformance = threadNode.get();
    synchronized (threadPerformance) {
      PerformanceNode last = threadPerformance.active.getLast();
      if (last.tag.equals(tag) && !(last instanceof ThreadPerformance)) {
        last.end = System.nanoTime() - startTime;
        threadPerformance.active.remove(last);
      } else {
        Log.error("Performance: stopping tag '" + tag + "' when the last tag is '" + last.tag + "'");
        PerformanceNode node = null;
        for (PerformanceNode performanceNode : threadPerformance.active) {
          if (performanceNode.tag.equals(tag)) {
            node = performanceNode;
            break;
          }
        }
        if (node == null) {
          Log.error("Performance: tag '" + tag + "' was never started");
          return;
        }
        ArrayDeque<PerformanceNode> d = new ArrayDeque<PerformanceNode>();
        d.add(node);
        while (d.size() > 0) {
          PerformanceNode n = d.removeFirst();
          if (n.end == 0) {
            n.end = System.nanoTime() - startTime;
            threadPerformance.active.remove(n);
            d.addAll(n.children);
          }
        }
      }
    }
  }

  public static synchronized void startTracking() {
    synchronized (nodes) {
      startTime = System.nanoTime();
      enabled.set(true);
      Log.warning("Started performance tracking");
    }
  }

  public static synchronized void stopTracking() {
    enabled.set(false);
    synchronized (nodes) {
      for (ThreadPerformance node : nodes) {
        synchronized (node) {
          Iterator<PerformanceNode> iterator = node.active.iterator();
          while (iterator.hasNext()) {
            iterator.next().end = System.nanoTime() - startTime;
            iterator.remove();
          }
        }
      }
    }
    Log.warning("Stopped performance tracking");
  }

  public static synchronized void toggleTracking() {
    if (enabled.get()) {
      stopTracking();
      FileHandle dir = Compatibility.get().getBaseFolder().child("performance");
      Compatibility.get().nomedia(dir);
      dir.mkdirs();
      final long time = System.currentTimeMillis();
      final File saveFile = dir.child(time + ".cbpf").file();
      final ArrayList<ThreadPerformance> saveNodes;
      synchronized (nodes) {
        saveNodes = new ArrayList<ThreadPerformance>(nodes);
        nodes.clear();
      }

      Thread thread = new Thread("PerformanceWrite" + time) {
        @Override
        public void run() {
          try {
            save(saveFile, saveNodes);
            PerformanceAnalysis.run(saveFile);
            Log.info("Saved performance analysis information '" + saveFile.getAbsolutePath() + ".txt'");
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      };
      thread.setDaemon(false);
      thread.setPriority(Thread.MIN_PRIORITY);
      thread.start();
    } else {
      clear();
      startTracking();
    }
  }

  public static synchronized void clear() {
    if (enabled.get()) return;
    synchronized (nodes) {
      nodes.clear();
      threadNode = new ThreadLocalPerformance();
    }
  }

  public static synchronized void save(File file,  ArrayList<ThreadPerformance> nodes) throws IOException {
    if (!file.exists()) file.createNewFile();
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(file);
      dataOutputStream = new DataOutputStream(new BufferedOutputStream(fileOutputStream));
      dataOutputStream.writeByte(0xEE);
      dataOutputStream.writeByte(0xCE);
      synchronized (nodes) {
        for (ThreadPerformance threadN : nodes) {
          dataOutputStream.writeByte(0x00);
          write(threadN, dataOutputStream);
        }
      }
      dataOutputStream.writeByte(0xFF);
    } finally {
      if (dataOutputStream != null) {
        try {
          dataOutputStream.flush();
        } catch (Exception ignored) {

        }
      }
      if (fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch (Exception ignored) {

        }
      }
    }
    Log.info("Saved performance information '" + file.getAbsolutePath() + "'");
  }

  private static void write(PerformanceNode node, DataOutputStream dataOutputStream) throws IOException {
    dataOutputStream.writeUTF(node.tag);
    dataOutputStream.writeUTF(node.extra);
    dataOutputStream.writeLong(node.start);
    dataOutputStream.writeLong(node.end);
    for (PerformanceNode child : node.children) {
      dataOutputStream.writeByte(0x00);
      write(child, dataOutputStream);
    }
    dataOutputStream.writeByte(0xFF);
  }

  public static class PerformanceNode {
    String tag;
    String extra = "";
    long start;
    long end;
    PerformanceNode parent = null;
    ArrayList<PerformanceNode> children = new ArrayList<PerformanceNode>();
  }

  public static class ThreadPerformance extends PerformanceNode {
    LinkedList<PerformanceNode> active = new LinkedList<PerformanceNode>() {{
      add(ThreadPerformance.this);
    }};
  }

  public static class ThreadLocalPerformance extends ThreadLocal<ThreadPerformance> {
    @Override
    protected ThreadPerformance initialValue() {
      ThreadPerformance threadPerformance = new ThreadPerformance();
      threadPerformance.tag = Thread.currentThread().getName() + "|" + Thread.currentThread().getId();
      threadPerformance.start = System.nanoTime() - startTime;
      synchronized (nodes) {
        nodes.add(threadPerformance);
      }
      return threadPerformance;
    }
  }
}


text:
Small prototyping area based on 1.27mm hole pitch, mostly geared to SMD components. Side connectors are suitable for headers for pluggin into breadboard/generic proto boards.
## TODO's
Still some things need to be done:
* schematic entry (Done)
* PCB layout (Done)
* Review with one night in between (Done)
* Produce at [OSHPARK](https://oshpark.com/) (In progress)
* Assemble (TODO)
* Test & characterise (TODO)
* update Readme.md with pictures and BOM (TODO)
## BOM
Add your own creativity! :-)
## Pictures
Some examples coming soon


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false">
    <testsuites>
        <testsuite name="Package Test Suite">
            <directory suffix=".php">./tests/</directory>
        </testsuite>
    </testsuites>
    <php>
        <env name="APP_KEY" value="AckfSECXIvnK5r28GVIWUAxmbBSjTsmF"/>
    </php>
</phpunit>


text:
<?php
/**
 * Internet utility functions.
 *
 * @since 1.0
 * @package Components
 * @author Konstantinos Filios <konfilios@gmail.com>
 */
class CBInet
{
	/**
	 * Tests if a test IPv4 address matches the an IPv4 range given in CIDR format.
	 *
	 * @link http://stackoverflow.com/a/594134/1289270
	 * @param string $testIpHuman E.g. "192.168.254.23"
	 * @param string $targetCidr E.g. "140.25.16.0/20"
	 * @return boolean
	 */
	static public function matchesCidrIp4($testIpHuman, $targetCidr)
	{
		// Extract subnet ip from number of digits for mask
		list ($targetSubnetHuman, $targetMaskBits) = explode('/', $targetCidr);

		// Convert human representations to longs
		$testLongIp = ip2long($testIpHuman);
		$targetLongSubnet = ip2long($targetSubnetHuman);
		$targetLongMask = -1 << (32 - $targetMaskBits);

		// Get properly padded, masked representations of test and target ip addresses
		$maskedTestLongIp = ($testLongIp & $targetLongMask);
		$maskedTargetLongSubnet = ($targetLongSubnet & $targetLongMask);

		// Compare
		return ($maskedTestLongIp == $maskedTargetLongSubnet);
	}

	/**
	 * Tests if a test IPv6 address matches the an IPv6 range given in CIDR format.
	 *
	 * @link http://stackoverflow.com/a/7951507/1289270
	 * @param string $testIpHuman E.g. "21DA:00D3:0001:2F3B:02AC:00FF:FE28:9C5A"
	 * @param string $targetCidr E.g. "21DA:00D3:0000:2F3B::/64"
	 * @return boolean
	 */
	static public function matchesCidrIp6($testIpHuman, $targetCidr)
	{
		// Extract subnet ip from number of digits for mask
		list($targetSubnetHuman, $targetMaskBitsDecString) = explode('/',$targetCidr);

		// Convert human representations to equally padded binary strings
		$testIpBinString = self::ipHumanToIpBinString($testIpHuman);
		$targetSubnetBinString = self::ipHumanToIpBinString($targetSubnetHuman);

		// Test only first $targetMaskBitsDecString bits
		$maskedTestIpBinString = substr($testIpBinString, 0, $targetMaskBitsDecString);
		$maskedTargetSubnetBinString = substr($targetSubnetBinString, 0, $targetMaskBitsDecString);

		return ($maskedTestIpBinString === $maskedTargetSubnetBinString);
	}

	/**
	 * Converts a human readable IP to a binary string representation using inet_pton.
	 *
	 * E.g.: IPv6 Address "21DA:00D3:0001:2F3B:02AC:00FF:FE28:9C5A" yields the binary string
	 * "00100001110110100000000011010011000000000000000100101111001110110000001010101100000000001111111111111110001010001001110001011010"
	 *
	 * @link http://stackoverflow.com/a/7951507/1289270
	 * @param string $ipHuman E.g. "21DA:00D3:0001:2F3B:02AC:00FF:FE28:9C5A"
	 * @return string
	 */
	static public function ipHumanToIpBinString($ipHuman)
	{
		// Convert human readable ip into a 128-bit (16-byte) binary (packed) value
		$packedIp = inet_pton($ipHuman);

		// Unpack into a string of 16 characters
		$unpackedIp = unpack('A16', $packedIp);

		// Split characters into an array of 16 character items
		$ipHexChars = str_split($unpackedIp[1]);

		$ipBinString = '';
		foreach ($ipHexChars as $ipHexChar) {
			// Get ordinal (decimal) value of ASCII character (ord)
			// transform it into a string of binary digits (decbin)
			// and pad it to the left with zeroes to make sure it always takes up 8 digits (str_pad)
		   $ipBinString .= str_pad(decbin(ord($ipHexChar)), 8, '0', STR_PAD_LEFT);
		}

		return $ipBinString;
	}
}