text:
require "spec_helper"

describe Shamu::Entities::OpaqueId do

  describe ".opaque_iid" do
    it "encodes the entity path" do
      # Patients::Patient[1]
      expect( Shamu::Entities::OpaqueId.opaque_id( "Patients::Patient[1]" ) ).to eq "UGF0aWVudHM6OlBhdGllbnRbMV0"
    end
  end

  describe ".to_model_id" do
    it "gets the encoded id for a valid opaque id" do
      # Patients::Patient[1]
      expect( Shamu::Entities::OpaqueId.to_model_id( "UGF0aWVudHM6OlBhdGllbnRbMV0" ) ).to eq 1
    end

    it "gets the encoded id for a valid opaque id with mod 4 = 0" do
      expect( Shamu::Entities::OpaqueId.to_model_id( "RW50aXR5TG9va3VwU2VydmljZVNwZWNzOjpFeGFtcGxlWzVd" ) ).to eq 5
    end

    it "is int for raw ids" do
      expect( Shamu::Entities::OpaqueId.to_model_id( "23" ) ).to eq 23
    end
  end

  describe ".opaque_id?" do
    it "recognizes encoded ids" do
      expect( Shamu::Entities::OpaqueId.opaque_id?( "UGF0aWVudHM6OlBhdGllbnRbMV0" ) ).to be_truthy
    end

    it "does not recognize raw numbers" do
      expect( Shamu::Entities::OpaqueId.opaque_id?( "123" ) ).to be_falsy
    end
  end

end


text:
<?php
// src/Acme/FrontBundle/Controller/MailController.php

namespace Acme\FrontBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class MailController extends Controller
{

/**
 * @Route("/mail/send/{name}.{_format}", defaults={"_format"="html"}, requirements={"_format"="html|xml|json"}, name="_demo_hello")
 * @Template()
 */
    public function sendAction($jmeno, $email, $text){

            $message = \Swift_Message::newInstance()
                ->setSubject('Hello Email')
                ->setFrom($email)
                ->setTo('kozusnikjan@gmail.com')
                ->setBody(
            $this->renderView(
                'FrontBundle:Hello:email.html.php',
                array('jmeno' => $jmeno, 'text' => $text)
            )
        );
    $this->get('mailer')->send($message);

    return $this->render('acme_front_homepage');

    }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 *	Heavily based on the Rendering Hardware Interface pattern in UE4 by Epic Games
 *	I'm using this since I want to eventually go and build out the backend for DX11 and GL4/ES3, and it has very little overhead for abstracting the command list building
 *	Uses CRTP for static polymorphism to reduce overhead
 *	06/25/15 - Going to leave this until I am more familiar with DX12 and have an implementation using that.
 *			   Looked at the full UE4 implementation and it will take a while to put in commands/states for all of DX12
 */

#pragma once

#include <stdint.h>
#include "Math/Vector4.h"

namespace novus
{
	class RHIResource;
	class RHITexture;
	class RHITexture2D;
	class RHIPipelineState;
}

namespace novus
{

enum class ClearFlags : uint8_t
{
	Depth = 1,
	Stencil = 1 << 1,
};

class RHICommandListBase
{

public:
	//virtual ~RHICommandList() {}

	//virtual void ClearState(RHIPipelineState* state);

	//virtual void Close();

	//virtual void ClearDepthStencil(RHITexture2D* depthStencil, ClearFlags clearFlags, float clearDepth, uint8_t clearStencil) = 0;
	//virtual void ClearRenderTarget(RHITexture* renderTarget, const Vector4& clearColor);

	//virtual void ClearUnorderedAccessView(RHIResource* resource, const Vector4& value);
	//virtual void ClearUnorderedAccessView(RHIResource* resource, const Vector4u& value);

	//virtual void CopyBufferRegion(RHIResource* dstBuffer, uint64_t dstOffset, RHIResource* srcBuffer, uint64_t srcOffset, uint64_t byteCount);

private:

};

struct RHICommandBase
{
	RHICommandBase* Next;

	void(*ExecuteAndDestructPtr)(RHICommandListBase& commandList, RHICommandBase* command);

	inline RHICommandBase(void(*executeAndDestructPtr)(RHICommandListBase& commandList, RHICommandBase* command))
		:Next(nullptr),
		ExecuteAndDestructPtr(executeAndDestructPtr)
	{}

	inline void CallExecuteAndDestruct(RHICommandListBase& commandList)
	{
		ExecuteAndDestructPtr(commandList, this);
	}
};

template <typename TCmd>
struct RHICommand : public RHICommandBase
{
	inline RHICommand()
		:RHICommandBase(&ExecuteAndDestruct)
	{}

	static inline void ExecuteAndDestruct(RHICommandListBase& commandList, RHICommandBase* command)
	{
		TCmd *thisCmd = static_cast<TCmd*>(command);
		thisCmd->Execute(commandList);
		thisCmd->~TCmd();
	}
};

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.consultjr.mvc.service;

import com.google.gson.Gson;
import java.util.Date;
import java.util.List;
import org.consultjr.mvc.core.base.ApplicationService;
import org.consultjr.mvc.dao.SystemConfigDAO;
import org.consultjr.mvc.model.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Rafael
 */
@Service
@Transactional
public class SystemConfigService extends ApplicationService {

    @Autowired
    private SystemConfigDAO systemConfigDAO;

    public SystemConfigDAO getSystemConfigDAO() {
        return systemConfigDAO;
    }

    public void setSystemConfigDAO(SystemConfigDAO systemConfigDAO) {
        this.systemConfigDAO = systemConfigDAO;
    }

    @Transactional(readOnly = false)
    public void addConfig(SystemConfig sys) {
        getSystemConfigDAO().addConfig(sys);
    }

    @Transactional(readOnly = false)
    public void deleteConfig(SystemConfig sys) {
        getSystemConfigDAO().deleteConfig(sys);
    }

    @Transactional(readOnly = false)
    public void updateConfig(SystemConfig sys, int configID) {
        SystemConfig config = getConfigById(configID);

        config.setKey(sys.getKey());
        config.setValue(sys.getValue());
        config.setUpdated(new Date());

        getSystemConfigDAO().updateConfig(config);
    }

    @Transactional(readOnly = false)
    public SystemConfig getConfigById(int configID) {
        return getSystemConfigDAO().getConfigById(configID);
    }

    @Transactional(readOnly = false)
    public SystemConfig getConfigByKey(String configKey) {
        return getSystemConfigDAO().getConfigByKey(configKey);
    }

    @Transactional(readOnly = false)
    public List<SystemConfig> getConfigs() {
        return getSystemConfigDAO().getConfigs();
    }

    @Transactional
    public SystemConfig get(String key) {
        return this.getConfigByKey(key);
    }

    @Transactional
    public void set(String key, String value) {
        //TODO evolve to use Objects. Save straigh ahead to strings and serialize to other objects

        if (null != getConfigByKey(key)) {
            SystemConfig sys = getConfigByKey(key);
            sys.setValue(value);
            sys.setUpdated(new Date());
            updateConfig(sys, sys.getId());
        } /* else if (value.equals("")) {
         deleteConfig(getConfigByKey(key));
         }*/ else {
            addConfig(new SystemConfig(key, value));
        }
    }

    @Transactional
    public void saveJson(String key, Object o) {
        Gson gson = new Gson();

        String jsonSerializedObject = gson.toJson(o);

        this.set(key, jsonSerializedObject);
    }

    @Transactional
    public Object getJson(String key, Class targetClass) {
        Gson gson = new Gson();
        Object o = null;
        SystemConfig sc = this.get(key);

        if (null != sc) {
            o = gson.fromJson(sc.getValue(), targetClass);
        }

        return o;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.fop.pdf.PDFPage (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.pdf.PDFPage

Packages that use PDFPage

org.apache.fop.pdf
Classes for handling the low-level creation of PDF documents.

org.apache.fop.render.pdf
PDF Renderer

org.apache.fop.svg
Classes that add SVG support to FOP and SVG->PDF conversion for Batik.

Uses of PDFPage in org.apache.fop.pdf

Fields in org.apache.fop.pdf with type parameters of type PDFPage

protected  java.util.List<PDFPage>
PDFDocument.pageObjs

Methods in org.apache.fop.pdf that return PDFPage

 PDFPage
PDFFactory.makePage(PDFResources resources,
         int pageWidth,
         int pageHeight)

          Make a /Page object.

 PDFPage
PDFFactory.makePage(PDFResources resources,
         int pageWidth,
         int pageHeight,
         int pageIndex)

          Make a /Page object.

 PDFPage
PDFFactory.makePage(PDFResources resources,
         int pageIndex,
         java.awt.geom.Rectangle2D mediaBox,
         java.awt.geom.Rectangle2D cropBox,
         java.awt.geom.Rectangle2D bleedBox,
         java.awt.geom.Rectangle2D trimBox)

          Make a /Page object.

Methods in org.apache.fop.pdf with parameters of type PDFPage

 void
PDFRoot.addPage(PDFPage page)

          add a /Page object to the root /Pages object

 void
PDFPages.addPage(PDFPage page)

          add a /Page object.

 void
PDFDPart.addPage(PDFPage p)

 void
PDFFactory.makeDPart(PDFPage page,
          java.lang.String pageMasterName)

 void
PDFPages.notifyKidRegistered(PDFPage page)

          Use this method to notify the PDFPages object that a child page

 void
PDFStructElem.setPage(PDFPage page)

          Sets the page reference of this structure element.

Uses of PDFPage in org.apache.fop.render.pdf

Fields in org.apache.fop.render.pdf declared as PDFPage

 PDFPage
PDFSVGHandler.PDFInfo.pdfPage

          see PDF_PAGE

Methods in org.apache.fop.render.pdf that return PDFPage

 PDFPage
PDFRenderingContext.getPage()

          Returns the current PDF page.

Constructors in org.apache.fop.render.pdf with parameters of type PDFPage

PDFRenderingContext(FOUserAgent userAgent,
                    PDFContentGenerator generator,
                    PDFPage page,
                    FontInfo fontInfo)

          Main constructor.

Uses of PDFPage in org.apache.fop.svg

Methods in org.apache.fop.svg that return PDFPage

 PDFPage
PDFContext.getCurrentPage()

Methods in org.apache.fop.svg with parameters of type PDFPage

 void
PDFContext.setCurrentPage(PDFPage page)

          Sets the current page

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
package com.crozin.wykop.sdk.exception;

@SuppressWarnings("serial")
public class ApiException extends SdkException {
	public ApiException(String message) {
		super(message);
	}

	public ApiException(String message, Integer code) {
		super(message, code);
	}

	public ApiException(String message, Throwable cause) {
		super(message, cause);
	}
}


text:
{:new_window: target="_blank"}

# Preparazione dei volumi {{site.data.keyword.blockstorageshort}}
{: #preparing-block-storage-volume}

Ultimo aggiornamento: 29 luglio 2016
{: .last-updated}

  Dopo aver creato il tuo volume a averlo collegato a un server virtuale, devi montare e preparare il volume per poterlo utilizzare.

  **Nota**: i comandi pertinenti possono variare a seconda del sistema operativo specifico. Per ulteriori informazioni, consulta la documentazione sul sistema operativo. I seguenti passi sono stati verificati utilizzando un server virtuale CentOS.

  Per preparare un volume, attieniti a questa procedura:

1. Accedi al server virtuale.

ssh -i security_key_name.pem ibmcloud@xxx.xx.xx.xx

   **Nota:** per trovare l'ID utente, il nome della chiave di sicurezza e il tuo indirizzo IP pubblico predefiniti, visualizza la scheda della panoramica del server virtuale. L'ID utente predefinito è *ibmcloud*. Per informazioni sull'accesso al server virtuale utilizzando SSH, consulta [Accesso a un'istanza del server virtuale da un terminale Linux](../../virtualmachines/vm_manage_instances.html#vm_login).

2. Verifica che il volume sia collegato.

sudo su -

   **Nota:** se il comando *sudo su* non funziona per il tuo sistema operativo, utilizza *sudo* prima di ogni comando. Ad esempio, *sudo fdisk -l*.

fdisk -l

   Le informazioni sul volume vengono elencate alla fine del testo informativo. Ad esempio, *Disk /dev/vdb: 10.7 GB, 10737418240 bytes*.

3. Partizionamento del disco.

   a. Avvia fdisk e crea una nuova partizione.

fdisk /dev/vdb

   b. Immetti **n** per creare una nuova partizione.

   c. Immetti **p** per specificare la partizione primaria.

   d. Per creare una partizione, immetti **1**.

   e. A meno che tu non abbia dei requisiti specifici, seleziona i valori predefiniti nelle rimanenti richieste e premi Invio.

   f. Immetti **w** per scrivere nella partizione.

   g. Verifica che il nuovo disco sia stato creato.

fdisk -l

     **Nota:** il nome del nuovo disco è normalmente il nome della partizione su cui è stato creato, con l'aggiunta di un numero incrementale, come 1. Ad esempio, *vdb1*.

4. Formatta il volume.

   Devi formattare il volume in modo che archivi le informazioni. Questo esempio utilizza ext4; tuttavia, puoi utilizzare qualsiasi file system supportato.

mkfs -t ext4 /dev/vdb1

    **Nota:** il passo per scrivere le informazioni di account del file system e dei superblocchi può richiedere ulteriore tempo per il completamento. Quando il processo è terminato, visualizzerai *eseguito* come stato.

5. Monta il volume.

   a. Devi montare il volume per utilizzarlo.

mkdir -p /mnt/myvolume

mount /dev/vdb1 /mnt/myvolume

      dove *myvolume* è un nome cartella di tua scelta.

   b. Controlla che il tuo volume sia elencato e pronto.

df -h

6. (Facoltativo) Monta il volume in modo permanente.

   Potresti voler montare il volume in modo permanente, così da non dover ripetere il montaggio dopo un riavvio.

   a. Individua l'UUID per il tuo volume.

blkid

   b. Copia l'UUID elencato.

   c. Modifica le informazioni della tabella dei file system.

nano /etc/fstab

   d. Incolla la seguente riga, incluso il tuo UUID specifico, alla fine del file e salva.

UUID=xxxxxx /mnt/myvolume ext4 defaults  0 2

   e. Per verificare che il volume sia montato in modo permanente, riavvia il server virtuale.

reboot

  Quando il server virtuale è nuovamente in esecuzione, accedi al server virtuale e modifica le directory nella nuova cartella che hai creato. Ad esempio vai a **cd /mnt/myvolume**.

  Puoi ora utilizzare il volume.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Package org.apache.solr.common.util (Solr 5.0-2012-07-18_13-07-53 API)
</TITLE>

<META NAME="date" CONTENT="2012-07-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.apache.solr.common.util

Packages that use org.apache.solr.common.util

org.apache.solr.client.solrj

org.apache.solr.client.solrj.embedded

org.apache.solr.client.solrj.impl

org.apache.solr.client.solrj.request

org.apache.solr.client.solrj.response

org.apache.solr.client.solrj.util

org.apache.solr.common.params

org.apache.solr.common.util

org.apache.solr.core

org.apache.solr.handler

org.apache.solr.handler.admin

org.apache.solr.handler.clustering

org.apache.solr.handler.clustering.carrot2

org.apache.solr.handler.component

org.apache.solr.handler.dataimport

org.apache.solr.handler.extraction

org.apache.solr.handler.loader

org.apache.solr.highlight

org.apache.solr.logging

org.apache.solr.request

org.apache.solr.response

org.apache.solr.response.transform

org.apache.solr.search

org.apache.solr.search.grouping

org.apache.solr.search.grouping.distributed.shardresultserializer

org.apache.solr.servlet

org.apache.solr.spelling

org.apache.solr.spelling.suggest

org.apache.solr.spelling.suggest.fst

org.apache.solr.spelling.suggest.jaspell

org.apache.solr.spelling.suggest.tst

org.apache.solr.uima.processor

org.apache.solr.update

org.apache.solr.update.processor

org.apache.solr.util

org.apache.solr.util.plugin

Classes in org.apache.solr.common.util used by org.apache.solr.client.solrj

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.client.solrj.embedded

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.client.solrj.impl

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.client.solrj.request

ContentStream

Classes in org.apache.solr.common.util used by org.apache.solr.client.solrj.response

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.client.solrj.util

ContentStream

Classes in org.apache.solr.common.util used by org.apache.solr.common.params

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.common.util

ContentStream

ContentStreamBase

          Three concrete implementations for ContentStream - one for File/URL/String

FastInputStream

          Single threaded buffered InputStream
  Internal Solr use only, subject to change.

FastOutputStream

          Single threaded buffered OutputStream
  Internal Solr use only, subject to change.

JavaBinCodec

          The class is designed to optimaly serialize/deserialize any supported types in Solr response.

JavaBinCodec.ObjectResolver

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

SimpleOrderedMap

          SimpleOrderedMap is a NamedList where access by key is more
 important than maintaining order when it comes to representing the
 held data in other forms, as ResponseWriters normally do.

Classes in org.apache.solr.common.util used by org.apache.solr.core

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.handler

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.admin

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

SimpleOrderedMap

          SimpleOrderedMap is a NamedList where access by key is more
 important than maintaining order when it comes to representing the
 held data in other forms, as ResponseWriters normally do.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.clustering

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.clustering.carrot2

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.component

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

SimpleOrderedMap

          SimpleOrderedMap is a NamedList where access by key is more
 important than maintaining order when it comes to representing the
 held data in other forms, as ResponseWriters normally do.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.dataimport

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.extraction

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.handler.loader

ContentStream

Classes in org.apache.solr.common.util used by org.apache.solr.highlight

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.logging

SimpleOrderedMap

          SimpleOrderedMap is a NamedList where access by key is more
 important than maintaining order when it comes to representing the
 held data in other forms, as ResponseWriters normally do.

Classes in org.apache.solr.common.util used by org.apache.solr.request

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

SimpleOrderedMap

          SimpleOrderedMap is a NamedList where access by key is more
 important than maintaining order when it comes to representing the
 held data in other forms, as ResponseWriters normally do.

Classes in org.apache.solr.common.util used by org.apache.solr.response

JavaBinCodec

          The class is designed to optimaly serialize/deserialize any supported types in Solr response.

JavaBinCodec.ObjectResolver

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.response.transform

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.search

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.search.grouping

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.search.grouping.distributed.shardresultserializer

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.servlet

ContentStream

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.spelling

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.spelling.suggest

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.spelling.suggest.fst

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.spelling.suggest.jaspell

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.spelling.suggest.tst

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.uima.processor

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.update

FastInputStream

          Single threaded buffered InputStream
  Internal Solr use only, subject to change.

JavaBinCodec

          The class is designed to optimaly serialize/deserialize any supported types in Solr response.

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.update.processor

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

Classes in org.apache.solr.common.util used by org.apache.solr.util

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

SimpleOrderedMap

          SimpleOrderedMap is a NamedList where access by key is more
 important than maintaining order when it comes to representing the
 held data in other forms, as ResponseWriters normally do.

Classes in org.apache.solr.common.util used by org.apache.solr.util.plugin

NamedList

          A simple container class for modeling an ordered list of name/value pairs.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

          <address>Copyright © 2000-2012 Apache Software Foundation.  All Rights Reserved.</address>


text:
@protocol YSLContainerViewControllerDelegate <NSObject>

- (void)containerViewItemIndex:(NSInteger)index currentController:(UIViewController *)controller;

@end

@interface SegmentContainerController : ContainerBaseViewController

@property (nonatomic, weak) id <YSLContainerViewControllerDelegate> delegate;

@property (nonatomic, strong) UIScrollView *contentScrollView;
@property (nonatomic, strong, readonly) NSMutableArray *titles;
@property (nonatomic, strong) NSMutableArray *childControllers;

@property (nonatomic, strong) UIFont  *menuItemFont;
@property (nonatomic, strong) UIColor *menuItemTitleColor;
@property (nonatomic, strong) UIColor *menuItemSelectedTitleColor;
@property (nonatomic, strong) UIColor *menuBackGroudColor;
@property (nonatomic, strong) UIColor *menuIndicatorColor;

- (id)initWithControllers:(NSArray *)controllers
             currentIndex:(NSInteger)currentindex
             topBarHeight:(CGFloat)topBarHeight
     parentViewController:(UIViewController *)parentViewController;

- (void)selectedAtIndex:(NSInteger)index;

@end


text:
package com.github.autoscaler.api;

import com.hpe.caf.api.HealthReporter;

/**
 * Creates WorkloadAnalyser instances for a specific target and profile.
 */
public interface WorkloadAnalyserFactory extends HealthReporter
{
    /**
     * Instantiate a new WorkloadAnalyser for a specific target and profile.
     * @param scalingTarget the reference to the target used for analysing workloads
     * @param scalingProfile the name of the profile to use for scaling
     * @return a new WorkloadAnalyser instance for the given scaling target and profile
     */
    WorkloadAnalyser getAnalyser(String scalingTarget, String scalingProfile);
}


text:
using System;

namespace Ninjathulhu.Game.Common
{
    public class CombatStats : Component
    {
        public static string HitPointsPropertyName = "hit points";
        public int HitPoints;

        public override void Start()
        {
            object hitPoints = Entity.Properties.Get<CombatStats>(HitPointsPropertyName, 0);
            if (hitPoints != null) { HitPoints = Convert.ToInt32(hitPoints); }
        }
    }
}


text:
package com.github.rnewson.couchdb.lucene.couchdb;

import com.github.rnewson.couchdb.lucene.util.Analyzers;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.ScriptableObject;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class View {

    private static final String DEFAULT_ANALYZER = "standard";

    private static final String ANALYZER = "analyzer";

    private static final String INDEX = "index";

    private static final String DEFAULTS = "defaults";

    private final JSONObject json;

    private final String name;

    public View(final String name, final JSONObject json) {
        if (!json.has(INDEX)) {
            throw new IllegalArgumentException(json + " is not an index");
        }
        this.name = name;
        this.json = json;
    }

    public Analyzer getAnalyzer() throws JSONException {
        return Analyzers
                .getAnalyzer(json.optString(ANALYZER, DEFAULT_ANALYZER));
    }

    public ViewSettings getDefaultSettings() throws JSONException {
        return json.has(DEFAULTS) ? new ViewSettings(json
                .getJSONObject(DEFAULTS)) : ViewSettings.getDefaultSettings();
    }

    public String getFunction() throws JSONException {
        return trim(json.getString(INDEX));
    }

    public Function compileFunction(final Context context,
                                    ScriptableObject scope) throws JSONException {
        return context.compileFunction(scope, getFunction(), null, 0, null);
    }

    public String getDigest() {
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(toBytes(json.optString("analyzer")));
            md.update(toBytes(json.optString("defaults")));
            md.update(toBytes(json.optString("index")));
            return new BigInteger(1, md.digest()).toString(Character.MAX_RADIX);
        } catch (final NoSuchAlgorithmException e) {
            throw new Error("MD5 support missing.");
        }
    }

    private static byte[] toBytes(final String str) {
        if (str == null) {
            return new byte[0];
        }
        try {
            return str.getBytes("UTF-8");
        } catch (final UnsupportedEncodingException e) {
            throw new Error("UTF-8 support missing.");
        }
    }

    private String trim(final String fun) {
        String result = fun;
        result = StringUtils.trim(result);
        result = StringUtils.removeStart(result, "\"");
        result = StringUtils.removeEnd(result, "\"");
        return result;
    }

    @Override
    public int hashCode() {
        return getDigest().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof View)) {
            return false;
        }
        View other = (View) obj;
        return getDigest().equals(other.getDigest());
    }

    @Override
    public String toString() {
        return String.format("View[name=%s, digest=%s]", name, getDigest());
    }

}


text:
<!DOCTYPE html>

    <link rel="stylesheet" media="all" href="/smartanswers/application.css" />
    <link rel="stylesheet" media="print" href="/smartanswers/print.css" />
    <title>State Pension top up calculator - GOV.UK</title>

    <meta name="robots" content="noindex">

        State Pension top up calculator

      <form action="/state-pension-topup/y/1912-10-12" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" />

    What is your gender?

        <input type="radio" name="response" id="response_0" value="male" />
        Male

        <input type="radio" name="response" id="response_1" value="female" />
        Female

            <input type="hidden" name="next" value="1" />
            <button type="submit" class="medium button">Next step</button>

      </form>

            Previous answers

          Start again

  What is your date of birth?

    12 October 1912

      Change answer to "What is your date of birth?"

Last updated:  1 January 2015


text:
#ifndef SkTextMapStateProc_DEFINED
#define SkTextMapStateProc_DEFINED

#include "SkPoint.h"
#include "SkMatrix.h"

class SkTextMapStateProc {
public:
    SkTextMapStateProc(const SkMatrix& matrix, const SkPoint& offset, int scalarsPerPosition)
        : fMatrix(matrix)
        , fProc(matrix.getMapXYProc())
        , fOffset(offset)
        , fScaleX(fMatrix.getScaleX()) {
        SkASSERT(1 == scalarsPerPosition || 2 == scalarsPerPosition);
        if (1 == scalarsPerPosition) {
            unsigned mtype = fMatrix.getType();
            if (mtype & (SkMatrix::kAffine_Mask | SkMatrix::kPerspective_Mask)) {
                fMapCase = kX;
            } else {
                // Bake the matrix scale/translation components into fOffset,
                // to expedite proc computations.
                fOffset.set(SkScalarMul(offset.x(), fMatrix.getScaleX()) + fMatrix.getTranslateX(),
                            SkScalarMul(offset.y(), fMatrix.getScaleY()) + fMatrix.getTranslateY());

                if (mtype & SkMatrix::kScale_Mask) {
                    fMapCase = kOnlyScaleX;
                } else {
                    fMapCase = kOnlyTransX;
                }
            }
        } else {
            fMapCase = kXY;
        }
    }

    void operator()(const SkScalar pos[], SkPoint* loc) const;

private:
    const SkMatrix& fMatrix;
    enum {
        kXY,
        kOnlyScaleX,
        kOnlyTransX,
        kX
    } fMapCase;
    const SkMatrix::MapXYProc fProc;
    SkPoint  fOffset; // In kOnly* mode, this includes the matrix translation component.
    SkScalar fScaleX; // This is only used by kOnly... cases.
};

inline void SkTextMapStateProc::operator()(const SkScalar pos[], SkPoint* loc) const {
    switch(fMapCase) {
    case kXY:
        fProc(fMatrix, pos[0] + fOffset.x(), pos[1] + fOffset.y(), loc);
        break;
    case kOnlyScaleX:
        loc->set(SkScalarMul(fScaleX, *pos) + fOffset.x(), fOffset.y());
        break;
    case kOnlyTransX:
        loc->set(*pos + fOffset.x(), fOffset.y());
        break;
    default:
        SkASSERT(false);
    case kX:
        fProc(fMatrix, *pos + fOffset.x(), fOffset.y(), loc);
        break;
    }
}

#endif


text:
"""
pktgen_scheduler.py
---------
pktgen_scheduler talks with pktgen_servers, schedules
jobs and listens for statuses.
"""

import sys
import json
import code
import Queue
import struct
import socket
import logging
import argparse
import threading

import job_pb2
import status_pb2

IP = 'localhost'
PORT = 1800

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("pktgen_scheduler")

class Q(object):
    """
    Q is a multi-threaded job scheduler.
    """
    def __init__(self, ip, port, nodes_file, jobs_file):
        self.ip = ip
        self.port = port
        self.sock = None
        self.nodes = {}
        self.jobs = []
        if nodes_file:
            self.nodes = self.load_nodes(nodes_file)
        if jobs_file:
            self.jobs = self.load_jobs(jobs_file)

    def start(self):
        """
        Setup the socket, start all the jobs, and beginning listening
        for statuses.
        """
        logger.info('Starting job scheduler.')
        self.setup_socket()
        self.start_jobs()
        threading.Thread(target=self.listen).start()

    def start_jobs(self):
        """
        Start jobs on each node.
        """
        logger.info('Starting node jobs.')
        for node in set(self.nodes.values()):
            node.next_job()

    def add_job(self, node_id, job):
        """
        Add a job to a specific node.
        """
        if node_id in self.nodes:
            self.jobs.append(job)
            self.nodes[node_id].add_job(job)
            self.nodes[node_id].next_job() # run job if idle
        else:
            logger.error('Cannot add job to node %s as it does not exist.' % node_id)

    def add_node(self, node):
        """
        """
        if node.name not in self.nodes and node.ip not in self.nodes:
            self.nodes[node.name] = self.nodes[node.ip]  = node
        else:
            logger.error('Cannot add node %s as it already exists.' % node.addr())

    def listen(self, backlog=5):
        """
        Listen for status. If one comes in, just spin off a
        thread to handle it.
        """
        self.sock.listen(backlog)
        logger.info('Currently listening on (%s, %s) for any statuses.' % (str(self.ip), str(self.port)))
        while True:
            client_sock, client_addr = self.sock.accept()
            threading.Thread(target=self.handle_client,
                             args=(client_sock, client_addr)).start()

    def handle_client(self, sock, addr):
        """
        Handle status from client; for now, just see if the
        job successfully finished and move on the next job if
        it exists.
        """
        ip = str(addr[0])
        logger.info('Received status from ip %s.' % ip)

        if ip not in self.nodes:
            logger.error('Ip %s is not one of the nodes' % ip)
            sock.close()
            return

        try:
            status = self.read_status(sock)
            if status.type == status_pb2.Status.SUCCESS:
                logger.info('Node %s successfully completed job.' % self.nodes[ip].addr())
                self.nodes[ip].finish_current_job()
                self.nodes[ip].next_job()
            elif status.type == status_pb2.Status.FAIL:
                logger.info('Node %s failed to complete job.' % self.nodes[ip].addr())
            elif status.type == status_pb2.Status.STARTED:
                logger.info("Successfully started job on node %s." % self.nodes[ip].addr())
        except:
            logger.info('Failed to read status from node %s' % self.nodes[ip].addr())
            pass

        sock.close()

    def read_status(self, sock):
        """
        Read the status. The first 4 bytes represent the
        size of the status. The rest is read from the socket
        and then converted from string -> Status using protobuf.
        """
        len_buf = self.read_n_bytes(sock, 4)
        status_len = struct.unpack('>L', len_buf)[0]
        status_buf = self.read_n_bytes(sock, status_len)

        status = status_pb2.Status()
        status.ParseFromString(status_buf)

        return status

    def read_n_bytes(self, sock, n_bytes):
        """
        Simply read n bytes from the sock.
        """
        data = ''
        while n_bytes > 0:
            tmp_buf = sock.recv(n_bytes)
            if not tmp_buf:
                break
            data += tmp_buf
            n_bytes -= len(tmp_buf)
        return data

    def setup_socket(self):
        """
        Setup the sock on (self.ip, self.port).
        """
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.ip, self.port))
        logger.debug("Successfully setup listening socket.")

    def load_nodes(self, nodes_file):
        """
        Load all the nodes from nodes_file.
        """
        logger.info("Loading nodes file %s." % nodes_file)
        nodes = {}
        node_data = self.load_json(nodes_file)

        for node in node_data['nodes']:
            nodes[node['name']] = nodes[node['ip']]  \
                                = Node(node['name'], node['ip'])

        return nodes

    def load_jobs(self, jobs_file):
        """
        Load all the jobs from jobs_file.
        """
        logger.info("Loading jobs file %s." % jobs_file)
        jobs = []
        jobs_data = self.load_json(jobs_file)

        for job in jobs_data['jobs']:
            for node in job['nodes']:
                if node in self.nodes:
                    j = Job(job['priority'], job['data'])
                    self.nodes[node].add_job(j)
                    jobs.append(j)
                else:
                    logger.error("Node %s does not exist." % node)

        return jobs

    def load_json(self, json_file):
        """
        Convert json_file to dictionary.
        """
        with open(json_file, 'r') as json_data:
            return json.load(json_data)

    def stop(self):
        """
        Stop the Q job scheduler.
        """
        if self.sock:
            self.sock.close()

class Node(object):
    """
    Node represents a computer running pkt_server.c
    """
    # default port on nodes
    PORT = 1729

    def __init__(self, name, ip):
        self.name = name
        self.ip = ip
        self.port = Node.PORT
        self.sock = None
        self.pending_jobs = Queue.PriorityQueue()
        self.working_job = None # doesn't need to be queue (just consistency)
        self.completed_jobs = []

    def add_job(self, job):
        """
        Add a job to the pending jobs.
        """
        self.pending_jobs.put((job.priority, job))

    def next_job(self):
        """
        Move on the next job if currently idle.
        """
        # currently a working job, not ready
        if self.working_job:
            return

        try:
            # pop off next job
            priority, job = self.pending_jobs.get(False)
            # setup socket, send job, and close
            self.setup_socket()
            self.send_job(job)
            self.sock.close()
            # finish job and set working job
            self.pending_jobs.task_done()
            self.working_job = job
            logger.info("Successfully sent job to node %s." % self.addr())
        except Queue.Empty as e:
            logger.info("No pending jobs for node %s." % self.addr())
            pass
        except socket.error as e:
            logger.info("Failed to send job to %s." % self.addr())
            pass

    def send_job(self, job):
        """
        Send the serialized job to node.
        """
        sdata = job.pack() # pack the data
        length = struct.pack('>L', len(sdata)) # pack the length in 4 bytes
        self.sock.sendall(length + sdata) # send it off length + data

    def finish_current_job(self):
        """
        Mark the current job finished
        """
        if self.working_job:
            self.completed_jobs.append(self.working_job)
            self.working_job = None

    def setup_socket(self):
        """
        Setup sock on (self.ip, self.port).
        """
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.connect((self.ip, self.port))
        logger.debug("Successfully setup socket to node %s." % self.addr())

    def addr(self):
        """
        Just return node in (ip, port) format
        """
        return '(%s, %s)' % (str(self.ip), str(self.port))

class Job(object):
    """
    Represents a job to be passed to nodes.
    """
    def __init__(self, priority, data):
        self.priority = priority
        self.job = self.load_job(data)

    def load_job(self, data):
        """
        Load a job from data -> Job type from protobuf.
        """
        j = job_pb2.Job()
        for k, v in data.items():
            if hasattr(j, k):
                setattr(j, k, v)
        return j

    def pack(self):
        """
        Serialize Job to string to be sent to nodes.
        """
        return self.job.SerializeToString()

def main():

    q_ip = IP
    q_port = PORT
    q_nodes_file = q_jobs_file = None

    parser = argparse.ArgumentParser(
        description="pktgen_scheduler schedules jobs for pktgen_servers")

    parser.add_argument('-p', '--port', type=int, help='the port pktgen_scheduler will listen on')
    parser.add_argument('-n', '--nodes', type=str, help='nodes json file to load')
    parser.add_argument('-j', '--jobs', type=str, help='jobs json file to load')
    parser.add_argument('-i', '--interactive', action="store_true", help='interactive mode')

    args = parser.parse_args()

    if args.port:
        q_port = args.port

    if args.nodes:
        q_nodes_file = args.nodes

    if args.jobs:
        q_jobs_file = args.jobs

    q = Q(q_ip, q_port, q_nodes_file, q_jobs_file)
    q.start()

    if args.interactive:
        code.interact(local=dict(globals(), **locals()))

    # this is the equivalent to running 'python ./scheduler/pktgen_scheduler.py -n data/nodes.json -j data/jobs.json'
    # q = Q(IP, PORT)
    # q.add_node(Node('m0', '127.0.0.1'))
    # q.add_job('m0', Job(1, {
    #                             "m": 20,
    #                             "t": 30,
    #                             "w": 5,
    #                             "n": 15,
    #                             "s_min": 200,
    #                             "s_max": 800,
    #                             "r": True,
    #                             "l": True
    #                         }))
    # q.add_job('m0', Job(2, {
    #                             "m": 40,
    #                             "t": 30,
    #                             "w": 5,
    #                             "n": 15,
    #                             "s_min": 500,
    #                             "s_max": 0,
    #                             "r": True,
    #                             "l": False
    #                         }))
    # start the scheduler
    # q.start()

if __name__ == '__main__':
    main()


text:
from py_db import db

# Re-computes historical statistics for all NSBL players, and writes them to the db

db = db('NSBL')

def process():
    print "historical_stats_hitters_advanced"
    db.query("TRUNCATE TABLE `historical_stats_hitters_advanced`")
    db.query("TRUNCATE TABLE `historical_stats_pitchers_advanced`")

    hit_q = """
SELECT COALESCE(CONCAT(nm.right_fname, ' ', nm.right_lname), o.player_name) AS player_name
, GROUP_CONCAT(DISTINCT team_abb ORDER BY YEAR DESC SEPARATOR '/') AS teams
, MAX(YEAR) AS end_year
, MIN(YEAR) AS start_year
, COUNT(DISTINCT year) AS years
, SUM(w.pa) AS pa
, SUM(w.defense) AS defense
, SUM(w.position_adj) AS position_adj
, SUM(w.dWAR) AS dWAR
, SUM(o.park_wOBA*o.pa)/SUM(o.pa) AS park_wOBA
, SUM(o.OPS_plus*o.pa)/SUM(o.pa) AS OPS_plus
, SUM(o.wRC_plus*o.pa)/SUM(o.pa) AS wRC_plus
, SUM(o.rAA) as rAA
, SUM(w.oWAR) as oWAR
, SUM(w.replacement) as replacement
, SUM(w.WAR-w.defense/10) as "noD_WAR"
, SUM(w.WAR) as WAR
FROM processed_compWAR_offensive o
JOIN processed_WAR_hitters w USING (year, team_abb, player_name)
LEFT JOIN name_mapper nm ON (1
    AND o.player_name = nm.wrong_name
    AND (nm.start_year IS NULL OR nm.start_year <= o.year)
    AND (nm.end_year IS NULL OR nm.end_year >= o.year)
    AND (nm.position = '' OR nm.position = o.position)
    # AND (nm.rl_team = '' OR nm.rl_team = a.team_abb)
    AND (nm.nsbl_team = '' OR nm.nsbl_team = o.team_abb)
)
GROUP BY COALESCE(CONCAT(nm.right_fname, ' ', nm.right_lname), o.player_name)
"""

    hit_vals = db.query(hit_q)
    hit_table = "historical_stats_hitters_advanced"
    hit_keys = ['player_name','teams','end_year','start_year','years','pa','defense','position_adj','dWAR','park_wOBA','OPS_plus','wRC_plus','rAA','oWAR','replacement','noD_WAR', 'WAR']

    hit_entries = []
    for row in hit_vals:
        entry = {}
        for k, v in zip(hit_keys, row):
            entry[k] = v
        hit_entries.append(entry)

    print '\thitters'
    db.insertRowDict(hit_entries, hit_table, replace=True, insertMany=True, rid=0)
    db.conn.commit()

    pitch_q = """
SELECT COALESCE(CONCAT(nm.right_fname, ' ', nm.right_lname), o.player_name) AS player_name
, GROUP_CONCAT(DISTINCT team_abb ORDER BY YEAR DESC SEPARATOR '/') AS teams
, MAX(YEAR) AS end_year
, MIN(YEAR) AS start_year
, COUNT(DISTINCT year) AS years
, SUM(ip) AS ip
, SUM(k_9*ip)/SUM(ip) AS k_9
, SUM(bb_9*ip)/SUM(ip) AS bb_9
, SUM(k_bb*ip)/SUM(ip) AS k_bb
, SUM(hr_9*ip)/SUM(ip) AS hr_9
, SUM(FIP*ip)/SUM(ip) AS FIP
, SUM(park_FIP*ip)/SUM(ip) AS park_FIP
, SUM(FIP_minus*ip)/SUM(ip) AS FIP_minus
, SUM(FIP_WAR) AS FIP_WAR
, SUM(ERA*ip)/SUM(ip) AS ERA
, SUM(park_ERA*ip)/SUM(ip) AS park_ERA
, SUM(ERA_minus*ip)/SUM(ip) AS ERA_minus
, SUM(ERA_WAR) AS ERA_WAR
FROM processed_WAR_pitchers o
LEFT JOIN name_mapper nm ON (1
    AND o.player_name = nm.wrong_name
    AND (nm.start_year IS NULL OR nm.start_year <= o.year)
    AND (nm.end_year IS NULL OR nm.end_year >= o.year)
    AND (nm.position = '' OR nm.position = o.position)
    # AND (nm.rl_team = '' OR nm.rl_team = a.team_abb)
    AND (nm.nsbl_team = '' OR nm.nsbl_team = o.team_abb)
)
GROUP BY COALESCE(CONCAT(nm.right_fname, ' ', nm.right_lname), o.player_name)
"""
    pitch_vals = db.query(pitch_q)
    pitch_table = "historical_stats_pitchers_advanced"
    pitch_keys = ['player_name','teams','end_year','start_year','years','ip','k_9','bb_9','k_bb','hr_9','FIP','park_FIP','FIP_minus','FIP_WAR','ERA','park_ERA','ERA_minus','ERA_WAR']
    pitch_entries = []
    for row in pitch_vals:
        entry = {}
        for k, v in zip(pitch_keys, row):
            entry[k] = v
        pitch_entries.append(entry)

    print '\tpitchers'
    db.insertRowDict(pitch_entries, pitch_table, replace=True, insertMany=True, rid=0)
    db.conn.commit()

if __name__ == "__main__":
    process()


text:
package com.cms.cms;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.cms.cms.model.NodeRequests;
import com.cms.cms.model.User;
import com.cms.cms.model.callback.GetCallback;
import com.cms.cms.model.callback.GetUserCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CMSRegister extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    EditText etName, etAge, etEmail, etPassword, etAddress, etSsn;
    Spinner etDept, etAcc;
    Button bRegister;

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

        etName = (EditText) findViewById(R.id.etName);
        etAge = (EditText) findViewById(R.id.etAge);
        etEmail = (EditText) findViewById(R.id.etEmail);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etAddress = (EditText) findViewById(R.id.etAddress);
        etDept = (Spinner) findViewById(R.id.etdpt);
        etAcc = (Spinner) findViewById(R.id.etAcc);
        etSsn = (EditText) findViewById(R.id.etSsn);
        bRegister = (Button) findViewById(R.id.bRegister);

        etDept.setOnItemSelectedListener(this);
        etAcc.setOnItemSelectedListener(this);
        bRegister.setOnClickListener(this);

        getDepartments();
        getAccounts();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bRegister:
                String name = etName.getText().toString();
                String email = etEmail.getText().toString();
                String password = etPassword.getText().toString();
                String address = etAddress.getText().toString();
                String dept = etDept.getSelectedItem().toString();
                String acc = etAcc.getSelectedItem().toString();
                String ssn = etSsn.getText().toString();
                int age = Integer.parseInt(etAge.getText().toString());

                User user = new User(name, age, email, password, address, dept, ssn, acc);
                registerUser(user);
                break;
        }
    }

    private void getDepartments() {
        NodeRequests serverRequest = new NodeRequests(this, "departments");
        serverRequest.fetchCollectionAsyncTask(new GetCallback() {
            @Override
            public void done(HashMap<String, ArrayList> items) {
                populateDepartments(items.get("departments"));
            }
        });
    }

    private void populateDepartments(List departments) {
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, departments);
        etDept.setAdapter(spinnerAdapter);
    }

    private void getAccounts() {
        NodeRequests serverRequest = new NodeRequests(this, "accounts");
        serverRequest.fetchCollectionAsyncTask(new GetCallback() {
            public ArrayList AccList;

            @Override
            public void done(HashMap<String, ArrayList> accounts) {
                AccList = accounts.get("accounts");
                AccList.remove("Admin");
                populateAccounts(AccList);
            }
        });
    }

    private void populateAccounts(List accounts) {
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, accounts);
        etAcc.setAdapter(spinnerAdapter);
    }

    private void registerUser(User user) {
        NodeRequests serverRequest = new NodeRequests(this);
        serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
            @Override
            public void done(User returnedUser) {
                Intent loginIntent = new Intent(CMSRegister.this, CMSLogin.class);
                startActivity(loginIntent);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(
                getApplicationContext(),
                parent.getItemAtPosition(position).toString() + " Selected",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}


text:
package tparse

import (
	"bytes"
	"fmt"
	"math"
	"strconv"
	"strings"
	"time"
	"unicode"
)

// Parse will return the time value corresponding to the specified layout and value.  It also parses
// floating point and integer epoch values.
func Parse(layout, value string) (time.Time, error) {
	return ParseWithMap(layout, value, make(map[string]time.Time))
}

// ParseNow will return the time value corresponding to the specified layout and value.  It also
// parses floating point and integer epoch values.  It recognizes the special string `now` and
// replaces that with the time ParseNow is called.  This allows a suffix adding or subtracting
// various values from the base time.  For instance, ParseNow(time.ANSIC, "now+1d") will return a
// time corresponding to 24 hours from the moment the function is invoked.
//
// In addition to the duration abbreviations recognized by time.ParseDuration, it recognizes various
// tokens for days, weeks, months, and years.
//
//	package main
//
//	import (
//		"fmt"
//		"os"
//		"time"
//
//		"github.com/karrick/tparse"
//	)
//
//	func main() {
//		actual, err := tparse.ParseNow(time.RFC3339, "now+1d3w4mo7y6h4m")
//		if err != nil {
//			fmt.Fprintf(os.Stderr, "error: %s\n", err)
//			os.Exit(1)
//		}
//
//		fmt.Printf("time is: %s\n", actual)
//	}
func ParseNow(layout, value string) (time.Time, error) {
	m := map[string]time.Time{"now": time.Now()}
	return ParseWithMap(layout, value, m)
}

// ParseWithMap will return the time value corresponding to the specified layout and value.  It also
// parses floating point and integer epoch values.  It accepts a map of strings to time.Time values,
// and if the value string starts with one of the keys in the map, it replaces the string with the
// corresponding time.Time value.
//
//	package main
//
//	import (
//		"fmt"
//		"os"
//		"time"
//
//		"github.com/karrick/tparse"
//	)
//
//	func main() {
//		m := make(map[string]time.Time)
//		m["start"] = start
//
//		end, err := tparse.ParseWithMap(time.RFC3339, "start+8h", m)
//		if err != nil {
//			fmt.Fprintf(os.Stderr, "error: %s\n", err)
//			os.Exit(1)
//		}
//
//		fmt.Printf("start: %s; end: %s\n", start, end)
//	}
func ParseWithMap(layout, value string, dict map[string]time.Time) (time.Time, error) {
	if epoch, err := strconv.ParseFloat(value, 64); err == nil && epoch >= 0 {
		trunc := math.Trunc(epoch)
		nanos := fractionToNanos(epoch - trunc)
		return time.Unix(int64(trunc), int64(nanos)), nil
	}
	var base time.Time
	var y, m, d int
	var duration time.Duration
	var direction = 1
	var err error

	for k, v := range dict {
		if strings.HasPrefix(value, k) {
			base = v
			if len(value) > len(k) {
				// maybe has +, -
				switch dir := value[len(k)]; dir {
				case '+':
					// no-op
				case '-':
					direction = -1
				default:
					return base, fmt.Errorf("expected '+' or '-': %q", dir)
				}
				var nv string
				y, m, d, nv = ymd(value[len(k)+1:])
				if len(nv) > 0 {
					duration, err = time.ParseDuration(nv)
					if err != nil {
						return base, err
					}
				}
			}
			if direction < 0 {
				y = -y
				m = -m
				d = -d
			}
			return base.Add(time.Duration(int(duration)*direction)).AddDate(y, m, d), nil
		}
	}
	return time.Parse(layout, value)
}

func fractionToNanos(fraction float64) int64 {
	return int64(fraction * float64(time.Second/time.Nanosecond))
}

func ymd(value string) (int, int, int, string) {
	// alternating numbers and strings
	var y, m, d int
	var accum int     // accumulates digits
	var unit []byte   // accumulates units
	var unproc []byte // accumulate unprocessed durations to return

	unitComplete := func() {
		// NOTE: compare byte slices because some units, i.e. ms, are multi-rune
		if bytes.Equal(unit, []byte{'d'}) || bytes.Equal(unit, []byte{'d', 'a', 'y'}) || bytes.Equal(unit, []byte{'d', 'a', 'y', 's'}) {
			d += accum
		} else if bytes.Equal(unit, []byte{'w'}) || bytes.Equal(unit, []byte{'w', 'e', 'e', 'k'}) || bytes.Equal(unit, []byte{'w', 'e', 'e', 'k', 's'}) {
			d += 7 * accum
		} else if bytes.Equal(unit, []byte{'m', 'o'}) || bytes.Equal(unit, []byte{'m', 'o', 'n'}) || bytes.Equal(unit, []byte{'m', 'o', 'n', 't', 'h'}) || bytes.Equal(unit, []byte{'m', 'o', 'n', 't', 'h', 's'}) || bytes.Equal(unit, []byte{'m', 't', 'h'}) || bytes.Equal(unit, []byte{'m', 'n'}) {
			m += accum
		} else if bytes.Equal(unit, []byte{'y'}) || bytes.Equal(unit, []byte{'y', 'e', 'a', 'r'}) || bytes.Equal(unit, []byte{'y', 'e', 'a', 'r', 's'}) {
			y += accum
		} else {
			unproc = append(append(unproc, strconv.Itoa(accum)...), unit...)
		}
	}

	expectDigit := true
	for _, rune := range value {
		if unicode.IsDigit(rune) {
			if expectDigit {
				accum = accum*10 + int(rune-'0')
			} else {
				unitComplete()
				unit = unit[:0]
				accum = int(rune - '0')
			}
			continue
		}
		unit = append(unit, string(rune)...)
		expectDigit = false
	}
	if len(unit) > 0 {
		unitComplete()
		accum = 0
		unit = unit[:0]
	}
	// log.Printf("y: %d; m: %d; d: %d; nv: %q", y, m, d, unproc)
	return y, m, d, string(unproc)
}


text:
from CatalogSurfaceItem import *
WSTTextureName = 0
WSTColor = 1
WSTBasePrice = 2
WainscotingTypes = {1000: ('phase_3.5/maps/wall_paper_b3.jpg', CTFlatColorDark, 200),
 1010: ('phase_5.5/maps/wall_paper_b4_greyscale.jpg', CTBasicWoodColorOnWhite, 200),
 1020: ('phase_5.5/maps/wainscotings_neutral.jpg', CTBasicWoodColorOnWhite, 200),
 1030: ('phase_3.5/maps/wall_paper_b3.jpg', CTValentinesColors, 200),
 1040: ('phase_3.5/maps/wall_paper_b3.jpg', CTUnderwaterColors, 200)}

class CatalogWainscotingItem(CatalogSurfaceItem):

    def makeNewItem(self, patternIndex, colorIndex):
        self.patternIndex = patternIndex
        self.colorIndex = colorIndex
        CatalogSurfaceItem.makeNewItem(self)

    def getTypeName(self):
        return TTLocalizer.SurfaceNames[STWainscoting]

    def getName(self):
        name = TTLocalizer.WainscotingNames.get(self.patternIndex)
        if name:
            return name
        return self.getTypeName()

    def getSurfaceType(self):
        return STWainscoting

    def getPicture(self, avatar):
        frame = self.makeFrame()
        sample = loader.loadModel('phase_5.5/models/estate/wallpaper_sample')
        a = sample.find('**/a')
        b = sample.find('**/b')
        c = sample.find('**/c')
        a.hide()
        b.hide()
        c.setTexture(self.loadTexture(), 1)
        c.setColorScale(*self.getColor())
        sample.reparentTo(frame)
        self.hasPicture = True
        return (frame, None)

    def output(self, store = -1):
        return 'CatalogWainscotingItem(%s, %s%s)' % (self.patternIndex, self.colorIndex, self.formatOptionalData(store))

    def getFilename(self):
        return WainscotingTypes[self.patternIndex][WSTTextureName]

    def compareTo(self, other):
        if self.patternIndex != other.patternIndex:
            return self.patternIndex - other.patternIndex
        return self.colorIndex - other.colorIndex

    def getHashContents(self):
        return (self.patternIndex, self.colorIndex)

    def getBasePrice(self):
        return WainscotingTypes[self.patternIndex][WSTBasePrice]

    def loadTexture(self):
        from pandac.PandaModules import Texture
        filename = WainscotingTypes[self.patternIndex][WSTTextureName]
        texture = loader.loadTexture(filename)
        texture.setMinfilter(Texture.FTLinearMipmapLinear)
        texture.setMagfilter(Texture.FTLinear)
        return texture

    def getColor(self):
        if self.colorIndex == None:
            colorIndex = 0
        else:
            colorIndex = self.colorIndex
        colors = WainscotingTypes[self.patternIndex][WSTColor]
        if colors:
            if colorIndex < len(colors):
                return colors[colorIndex]
            else:
                print 'Warning: colorIndex not in colors. Returning white.'
                return CT_WHITE
        else:
            return CT_WHITE
        return

    def decodeDatagram(self, di, versionNumber, store):
        CatalogAtticItem.CatalogAtticItem.decodeDatagram(self, di, versionNumber, store)
        if versionNumber < 3:
            self.patternIndex = di.getUint8()
        else:
            self.patternIndex = di.getUint16()
        self.colorIndex = di.getUint8()
        wtype = WainscotingTypes[self.patternIndex]

    def encodeDatagram(self, dg, store):
        CatalogAtticItem.CatalogAtticItem.encodeDatagram(self, dg, store)
        dg.addUint16(self.patternIndex)
        dg.addUint8(self.colorIndex)

def getWainscotings(*indexList):
    list = []
    for index in indexList:
        list.append(CatalogWainscotingItem(index))

    return list

def getAllWainscotings(*indexList):
    list = []
    for index in indexList:
        colors = WainscotingTypes[index][WSTColor]
        if colors:
            for n in xrange(len(colors)):
                list.append(CatalogWainscotingItem(index, n))

        else:
            list.append(CatalogWainscotingItem(index, 0))

    return list

def getWainscotingRange(fromIndex, toIndex, *otherRanges):
    list = []
    froms = [fromIndex]
    tos = [toIndex]
    i = 0
    while i < len(otherRanges):
        froms.append(otherRanges[i])
        tos.append(otherRanges[i + 1])
        i += 2

    for patternIndex in WainscotingTypes.keys():
        for fromIndex, toIndex in zip(froms, tos):
            if patternIndex >= fromIndex and patternIndex <= toIndex:
                colors = WainscotingTypes[patternIndex][WSTColor]
                if colors:
                    for n in xrange(len(colors)):
                        list.append(CatalogWainscotingItem(patternIndex, n))

                else:
                    list.append(CatalogWainscotingItem(patternIndex, 0))

    return list


text:
declare module 'enzyme' {
  declare type PredicateFunction<T: Wrapper<*>> = (
    wrapper: T,
    index: number
  ) => boolean
  declare type UntypedSelector =
    | string
    | { [key: string]: number | string | boolean }
  declare type EnzymeSelector = UntypedSelector | React$ElementType

  // CheerioWrapper is a type alias for an actual cheerio instance
  // TODO: Reference correct type from cheerio's type declarations
  declare type CheerioWrapper = any

  declare class Wrapper<RootComponent> {
    equals(node: React$Element<any>): boolean;
    find(selector: UntypedSelector): this;
    find<T: React$ElementType>(selector: T): ReactWrapper<T>;
    findWhere(predicate: PredicateFunction<this>): this;
    filter(selector: UntypedSelector): this;
    filter<T: React$ElementType>(selector: T): ReactWrapper<T>;
    filterWhere(predicate: PredicateFunction<this>): this;
    hostNodes(): this;
    contains(nodes: React$Node): boolean;
    containsMatchingElement(node: React$Node): boolean;
    containsAllMatchingElements(nodes: React$Node): boolean;
    containsAnyMatchingElements(nodes: React$Node): boolean;
    dive(option?: { context?: Object }): this;
    exists(selector?: EnzymeSelector): boolean;
    isEmptyRender(): boolean;
    matchesElement(node: React$Node): boolean;
    hasClass(className: string): boolean;
    is(selector: EnzymeSelector): boolean;
    isEmpty(): boolean;
    not(selector: EnzymeSelector): this;
    children(selector?: UntypedSelector): this;
    children<T: React$ElementType>(selector: T): ReactWrapper<T>;
    childAt(index: number): this;
    parents(selector?: UntypedSelector): this;
    parents<T: React$ElementType>(selector: T): ReactWrapper<T>;
    parent(): this;
    closest(selector: UntypedSelector): this;
    closest<T: React$ElementType>(selector: T): ReactWrapper<T>;
    render(): CheerioWrapper;
    renderProp(propName: string): (...args: Array<any>) => this;
    unmount(): this;
    text(): string;
    html(): string;
    get(index: number): React$Node;
    getDOMNode(): HTMLElement | HTMLInputElement;
    at(index: number): this;
    first(): this;
    last(): this;
    state(key?: string): any;
    context(key?: string): any;
    props(): Object;
    prop(key: string): any;
    key(): string;
    simulate(event: string, ...args: Array<any>): this;
    simulateError(error: Error): this;
    slice(begin?: number, end?: number): this;
    setState(state: {}, callback?: () => void): this;
    setProps(props: {}, callback?: () => void): this;
    setContext(context: Object): this;
    instance(): React$ElementRef<RootComponent>;
    update(): this;
    debug(options?: Object): string;
    type(): string | Function | null;
    name(): string;
    forEach(fn: (node: this, index: number) => mixed): this;
    map<T>(fn: (node: this, index: number) => T): Array<T>;
    reduce<T>(
      fn: (value: T, node: this, index: number) => T,
      initialValue?: T
    ): Array<T>;
    reduceRight<T>(
      fn: (value: T, node: this, index: number) => T,
      initialValue?: T
    ): Array<T>;
    some(selector: EnzymeSelector): boolean;
    someWhere(predicate: PredicateFunction<this>): boolean;
    every(selector: EnzymeSelector): boolean;
    everyWhere(predicate: PredicateFunction<this>): boolean;
    length: number;
  }

  declare class ReactWrapper<T> extends Wrapper<T> {
    constructor(
      nodes: React$Element<T>,
      root: any,
      options?: ?Object
    ): ReactWrapper<T>;
    mount(): this;
    ref(refName: string): this;
    detach(): void;
  }

  declare class ShallowWrapper<T> extends Wrapper<T> {
    constructor(
      nodes: React$Element<T>,
      root: any,
      options?: ?Object
    ): ShallowWrapper<T>;
    equals(node: React$Node): boolean;
    shallow(options?: { context?: Object }): ShallowWrapper<T>;
    getElement(): React$Node;
    getElements(): Array<React$Node>;
  }

  declare function shallow<T>(
    node: React$Element<T>,
    options?: { context?: Object, disableLifecycleMethods?: boolean }
  ): ShallowWrapper<T>
  declare function mount<T>(
    node: React$Element<T>,
    options?: {
      context?: Object,
      attachTo?: HTMLElement,
      childContextTypes?: Object,
    }
  ): ReactWrapper<T>
  declare function render<T>(
    node: React$Element<T>,
    options?: { context?: Object }
  ): CheerioWrapper

  declare module.exports: {
    configure(options: {
      Adapter?: any,
      disableLifecycleMethods?: boolean,
    }): void,
    render: typeof render,
    mount: typeof mount,
    shallow: typeof shallow,
    ShallowWrapper: typeof ShallowWrapper,
    ReactWrapper: typeof ReactWrapper,
  }
}


text:
<?php

namespace SergeiK\WebStudioBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Portfolio
 *
 * @ORM\Table()
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Portfolio
{
    const SERVER_PATH_TO_IMAGE_FOLDER = 'uploads/images/';

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="link", type="string", length=255)
     */
    private $link;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255, nullable=true)
     */
    private $image;

    /**
     * @var string
     *
     * @ORM\Column(name="image_href", type="string", length=255, nullable=true)
     */
    private $image_href;

    private $file;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Portfolio
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set link
     *
     * @param string $link
     * @return Portfolio
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Portfolio
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Portfolio
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    public function upload(){
        if(null === $this->getFile()){
            return;
        }

        $filename = sha1(
            uniqid(
                mt_rand(),
                true
            )
        );

        if($this->getImageHref()){
            if(file_exists(Portfolio::SERVER_PATH_TO_IMAGE_FOLDER . $this->getImageHref())){
                unlink(Portfolio::SERVER_PATH_TO_IMAGE_FOLDER . $this->getImageHref());
            }
        }

        $this->setImageHref(
            $filename.'.'.$this->getFile()->guessClientExtension()
        );
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function postPersist(){

        if(null === $this->getFile()){
            return;
        }

        $this->getFile()->move(
            Portfolio::SERVER_PATH_TO_IMAGE_FOLDER,
            $this->getImageHref()
        );

        $this->setFile(null);
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function lifecycleFileUpload() {
        $this->upload();
    }

    /**
     * @ORM\PreRemove()
     */
    public function lifecycleFileDelete(){
        if($this->getImageHref()){
            if(file_exists(Portfolio::SERVER_PATH_TO_IMAGE_FOLDER . $this->getImageHref())){
                unlink(Portfolio::SERVER_PATH_TO_IMAGE_FOLDER . $this->getImageHref());
            }
        }
    }

    /**
     * Set image_href
     *
     * @param string $imageHref
     * @return Portfolio
     */
    public function setImageHref($imageHref)
    {
        $this->image_href = $imageHref;

        return $this;
    }

    /**
     * Get image_href
     *
     * @return string
     */
    public function getImageHref()
    {
        return $this->image_href;
    }
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Project.branch'
        db.add_column(u'orm_project', 'branch',
                      self.gf('django.db.models.fields.CharField')(default='master', max_length=50),
                      keep_default=False)

        # Adding field 'Project.short_description'
        db.add_column(u'orm_project', 'short_description',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=50, blank=True),
                      keep_default=False)

        # Adding field 'Project.user_id'
        db.add_column(u'orm_project', 'user_id',
                      self.gf('django.db.models.fields.IntegerField')(null=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Project.branch'
        db.delete_column(u'orm_project', 'branch')

        # Deleting field 'Project.short_description'
        db.delete_column(u'orm_project', 'short_description')

        # Deleting field 'Project.user_id'
        db.delete_column(u'orm_project', 'user_id')

    models = {
        u'orm.build': {
            'Meta': {'object_name': 'Build'},
            'bitbake_version': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'build_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'completed_on': ('django.db.models.fields.DateTimeField', [], {}),
            'cooker_log_path': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
            'distro': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'distro_version': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'errors_no': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'machine': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'outcome': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
            'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Project']", 'null': 'True'}),
            'started_on': ('django.db.models.fields.DateTimeField', [], {}),
            'timespent': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'warnings_no': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        u'orm.helptext': {
            'Meta': {'object_name': 'HelpText'},
            'area': ('django.db.models.fields.IntegerField', [], {}),
            'build': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'helptext_build'", 'to': u"orm['orm.Build']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'key': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'text': ('django.db.models.fields.TextField', [], {})
        },
        u'orm.layer': {
            'Meta': {'object_name': 'Layer'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'layer_index_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
            'local_path': ('django.db.models.fields.FilePathField', [], {'max_length': '255'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'orm.layer_version': {
            'Meta': {'object_name': 'Layer_Version'},
            'branch': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'build': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'layer_version_build'", 'to': u"orm['orm.Build']"}),
            'commit': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'layer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'layer_version_layer'", 'to': u"orm['orm.Layer']"}),
            'priority': ('django.db.models.fields.IntegerField', [], {})
        },
        u'orm.logmessage': {
            'Meta': {'object_name': 'LogMessage'},
            'build': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Build']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'lineno': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'message': ('django.db.models.fields.CharField', [], {'max_length': '240'}),
            'pathname': ('django.db.models.fields.FilePathField', [], {'max_length': '255', 'blank': 'True'}),
            'task': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Task']", 'null': 'True', 'blank': 'True'})
        },
        u'orm.package': {
            'Meta': {'object_name': 'Package'},
            'build': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Build']"}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'installed_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}),
            'installed_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'license': ('django.db.models.fields.CharField', [], {'max_length': '80', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'recipe': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Recipe']", 'null': 'True'}),
            'revision': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
            'section': ('django.db.models.fields.CharField', [], {'max_length': '80', 'blank': 'True'}),
            'size': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'summary': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'version': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
        },
        u'orm.package_dependency': {
            'Meta': {'object_name': 'Package_Dependency'},
            'dep_type': ('django.db.models.fields.IntegerField', [], {}),
            'depends_on': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'package_dependencies_target'", 'to': u"orm['orm.Package']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'package': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'package_dependencies_source'", 'to': u"orm['orm.Package']"}),
            'target': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Target']", 'null': 'True'})
        },
        u'orm.package_file': {
            'Meta': {'object_name': 'Package_File'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'package': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'buildfilelist_package'", 'to': u"orm['orm.Package']"}),
            'path': ('django.db.models.fields.FilePathField', [], {'max_length': '255', 'blank': 'True'}),
            'size': ('django.db.models.fields.IntegerField', [], {})
        },
        u'orm.project': {
            'Meta': {'object_name': 'Project'},
            'branch': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'short_description': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'user_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'})
        },
        u'orm.projectlayer': {
            'Meta': {'object_name': 'ProjectLayer'},
            'commit': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
            'giturl': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Project']"})
        },
        u'orm.projecttarget': {
            'Meta': {'object_name': 'ProjectTarget'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Project']"}),
            'target': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'orm.projectvariable': {
            'Meta': {'object_name': 'ProjectVariable'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Project']"}),
            'value': ('django.db.models.fields.TextField', [], {'blank': 'True'})
        },
        u'orm.recipe': {
            'Meta': {'object_name': 'Recipe'},
            'bugtracker': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'file_path': ('django.db.models.fields.FilePathField', [], {'max_length': '255'}),
            'homepage': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'layer_version': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'recipe_layer_version'", 'to': u"orm['orm.Layer_Version']"}),
            'license': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'section': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'summary': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'version': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
        },
        u'orm.recipe_dependency': {
            'Meta': {'object_name': 'Recipe_Dependency'},
            'dep_type': ('django.db.models.fields.IntegerField', [], {}),
            'depends_on': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'r_dependencies_depends'", 'to': u"orm['orm.Recipe']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'recipe': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'r_dependencies_recipe'", 'to': u"orm['orm.Recipe']"})
        },
        u'orm.target': {
            'Meta': {'object_name': 'Target'},
            'build': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Build']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'image_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'is_image': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'license_manifest_path': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True'}),
            'target': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'orm.target_file': {
            'Meta': {'object_name': 'Target_File'},
            'directory': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'directory_set'", 'null': 'True', 'to': u"orm['orm.Target_File']"}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'inodetype': ('django.db.models.fields.IntegerField', [], {}),
            'owner': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'path': ('django.db.models.fields.FilePathField', [], {'max_length': '100'}),
            'permission': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
            'size': ('django.db.models.fields.IntegerField', [], {}),
            'sym_target': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'symlink_set'", 'null': 'True', 'to': u"orm['orm.Target_File']"}),
            'target': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Target']"})
        },
        u'orm.target_image_file': {
            'Meta': {'object_name': 'Target_Image_File'},
            'file_name': ('django.db.models.fields.FilePathField', [], {'max_length': '254'}),
            'file_size': ('django.db.models.fields.IntegerField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'target': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Target']"})
        },
        u'orm.target_installed_package': {
            'Meta': {'object_name': 'Target_Installed_Package'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'package': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'buildtargetlist_package'", 'to': u"orm['orm.Package']"}),
            'target': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orm.Target']"})
        },
        u'orm.task': {
            'Meta': {'ordering': "('order', 'recipe')", 'unique_together': "(('build', 'recipe', 'task_name'),)", 'object_name': 'Task'},
            'build': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'task_build'", 'to': u"orm['orm.Build']"}),
            'cpu_usage': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '2'}),
            'disk_io': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'elapsed_time': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '2'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'line_number': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'logfile': ('django.db.models.fields.FilePathField', [], {'max_length': '255', 'blank': 'True'}),
            'message': ('django.db.models.fields.CharField', [], {'max_length': '240'}),
            'order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'outcome': ('django.db.models.fields.IntegerField', [], {'default': '-1'}),
            'path_to_sstate_obj': ('django.db.models.fields.FilePathField', [], {'max_length': '500', 'blank': 'True'}),
            'recipe': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'build_recipe'", 'to': u"orm['orm.Recipe']"}),
            'script_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'source_url': ('django.db.models.fields.FilePathField', [], {'max_length': '255', 'blank': 'True'}),
            'sstate_checksum': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'sstate_result': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'task_executed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'task_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'work_directory': ('django.db.models.fields.FilePathField', [], {'max_length': '255', 'blank': 'True'})
        },
        u'orm.task_dependency': {
            'Meta': {'object_name': 'Task_Dependency'},
            'depends_on': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'task_dependencies_depends'", 'to': u"orm['orm.Task']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'task_dependencies_task'", 'to': u"orm['orm.Task']"})
        },
        u'orm.variable': {
            'Meta': {'object_name': 'Variable'},
            'build': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'variable_build'", 'to': u"orm['orm.Build']"}),
            'changed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'human_readable_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'variable_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'variable_value': ('django.db.models.fields.TextField', [], {'blank': 'True'})
        },
        u'orm.variablehistory': {
            'Meta': {'object_name': 'VariableHistory'},
            'file_name': ('django.db.models.fields.FilePathField', [], {'max_length': '255'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'line_number': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'operation': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
            'value': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'variable': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'vhistory'", 'to': u"orm['orm.Variable']"})
        }
    }

    complete_apps = ['orm']


text:
"""
Collection of different neural network architectures together with
architecture-specific helper functions.
"""

from collections import Counter

from torch import nn
import torch
import numpy as np

import hannds_data as hd

class Network88(nn.Module):
    def __init__(self, hidden_size, n_layers, bidirectional, n_features, n_categories, rnn_type):
        super(Network88, self).__init__()
        self.rnn = _rnn_with_type(rnn_type, n_features, hidden_size, n_layers, bidirectional)

        self.n_directions = 2 if bidirectional else 1
        self.out_linear = nn.Linear(hidden_size * self.n_directions, n_features * n_categories)
        self.n_layers = n_layers
        self.n_features = n_features
        self.n_categories = n_categories
        self.criterion = nn.CrossEntropyLoss()

    def forward(self, input, hidden_in):
        rnn_output, hidden_out = self.rnn.forward(input, hidden_in)
        output = self.out_linear(rnn_output)
        output = output.view(-1, output.shape[1], self.n_features, self.n_categories)
        # Residual connection
        # output[:, :, :, 0] += 1.0 - input
        # output[:, :, :, 1] += input
        # output[:, :, :, 2] += input
        return output, hidden_out

    def compute_loss(self, output, labels):
        return self.criterion(output.view((-1, self.n_categories)), labels.view(-1))

    def compute_accuracy(self, X_batch, Y_batch, prediction):
        predicted_classes = torch.argmax(prediction, dim=3)
        filter_func = causal_filter
        X_numpy = X_batch.squeeze().cpu().numpy()
        Y_numpy = Y_batch.squeeze().cpu().numpy()
        classes_numpy = predicted_classes.squeeze().cpu().numpy()
        return compute_accuracy88(X_numpy, Y_numpy, classes_numpy, filter_func)
        # va1 = valid_accuracy_plain[0] + compute_accuracy88(X_numpy, Y_numpy, classes_numpy)
        # va2 = valid_accuracy_plain[1] + 1
        # valid_accuracy_plain = (va1, va2)

class Network88Tanh(nn.Module):
    def __init__(self, hidden_size, n_layers, bidirectional, n_features, rnn_type):
        super(Network88Tanh, self).__init__()
        self.rnn = _rnn_with_type(rnn_type, n_features, hidden_size, n_layers, bidirectional)
        self.n_directions = 2 if bidirectional else 1
        self.out_linear = nn.Linear(hidden_size * self.n_directions, n_features)
        self.n_layers = n_layers
        self.criterion = nn.MSELoss()

    def forward(self, input, hidden_in):
        rnn_output, hidden_out = self.rnn.forward(input, hidden_in)
        output = self.out_linear(rnn_output)
        output = torch.tanh(output)
        output = output * input
        return output, hidden_out

    def compute_loss(self, output, labels):
        return self.criterion(output, labels)

    def compute_accuracy(self, X_batch, Y_batch, prediction):
        num_notes = torch.sum(X_batch)
        left_hand = (prediction < 0.0).float()
        right_hand = (prediction > 0.0).float()
        prediction = left_hand * -1.0 + right_hand * 1.0
        prediction = causal_filter(prediction)
        diff = (prediction != Y_batch).float()
        errors_percent = torch.sum(diff) / num_notes * 100.0
        return 100.0 - errors_percent

class NetworkMidi(nn.Module):
    def __init__(self, hidden_size, n_layers, rnn_type, bidirectional):
        super(NetworkMidi, self).__init__()
        n_features = 4
        self.rnn = _rnn_with_type(rnn_type, n_features, hidden_size, n_layers, bidirectional=bidirectional)
        self.n_directions = 2 if bidirectional else 1
        self.linear = nn.Linear(hidden_size * self.n_directions, out_features=1)
        self.criterion = nn.BCEWithLogitsLoss()

    def forward(self, input, hidden_in):
        out, hidden_out = self.rnn(input, hidden_in)
        out = self.linear(out)
        return out, hidden_out

    def compute_loss(self, output, labels):
        return self.criterion(output.view(-1), labels.view(-1))

    def compute_accuracy(self, X_batch, Y_batch, prediction):
        labels_flat = Y_batch.view(-1)
        prediction_flat = (torch.sigmoid(prediction.view(-1)) >= 0.5).float()
        num_events = float(labels_flat.shape[0])
        num_correct = float(torch.sum(labels_flat == prediction_flat))
        return num_correct / num_events * 100.0

class NetworkMagenta(nn.Module):
    def __init__(self, hidden_size, n_layers, rnn_type, bidirectional):
        super(NetworkMagenta, self).__init__()
        input_size = 388
        self.rnn = _rnn_with_type(rnn_type, input_size, hidden_size, n_layers, bidirectional=bidirectional)
        self.linear = nn.Linear(hidden_size, out_features=1)
        self.n_directions = 2 if bidirectional else 1
        self.linear = nn.Linear(hidden_size * self.n_directions, out_features=1)
        self.criterion = nn.BCEWithLogitsLoss()

    def forward(self, input, hidden_in):
        out, hidden_out = self.rnn(input, hidden_in)
        out = self.linear(out)
        return out, hidden_out

    def compute_loss(self, output, labels):
        return self.criterion(output.view(-1), labels.view(-1))

    def compute_accuracy(self, X_batch, Y_batch, prediction):
        labels_flat = Y_batch.view(-1)
        prediction_flat = (torch.sigmoid(prediction.view(-1)) >= 0.5).float()
        num_events = float(labels_flat.shape[0])
        num_correct = float(torch.sum(labels_flat == prediction_flat))
        return num_correct / num_events * 100.0

def causal_filter(predicted_classes, label_not_played=0):
    """
    Filters the predicted classes: the assignment is decided at the
    note-on event. Changes the content of predicted_classes.
    """
    for row in range(1, predicted_classes.shape[0]):
        last_line = predicted_classes[row - 1]
        current_line = predicted_classes[row]
        both_note_on = np.logical_and(current_line != label_not_played, last_line != label_not_played)
        predicted_classes[row, both_note_on] = last_line[both_note_on]

    return predicted_classes

def majority_filter(predicted_classes):  # Needs to be profiled
    """
    Filters the predicted classes: the assignment is decided at the
    note-off event. Changes the content of predicted_classes.
    """
    for column in range(predicted_classes.shape[1]):
        row = 0
        while row < predicted_classes.shape[0]:
            last_note = predicted_classes[row - 1, column] if row > 0 else 0
            current_note = predicted_classes[row, column]
            start = row
            if last_note == hd.WINDOWED_NOT_PLAYED and current_note != hd.WINDOWED_NOT_PLAYED:
                row += 1
                while row < predicted_classes.shape[0]:
                    current_note = predicted_classes[row, column]
                    if current_note == hd.WINDOWED_NOT_PLAYED or row == predicted_classes.shape[0] - 1:
                        end = row
                        c = Counter(predicted_classes[start: end, column])
                        majority_value, _ = c.most_common()[0]
                        predicted_classes[start: end, column] = majority_value
                        row += 1
                        break
                    else:
                        row += 1
            else:
                row += 1

    return predicted_classes

def compute_accuracy88(X, Y, predicted_classes, filter_func=lambda x: x):
    assert len(X.shape) == len(Y.shape) == len(predicted_classes.shape) == 2
    n_notes = X.sum()
    predicted_classes = filter_func(predicted_classes)
    pred_lh = predicted_classes == hd.WINDOWED_LEFT_HAND
    pred_rh = predicted_classes == hd.WINDOWED_RIGHT_HAND
    label_lh = Y == hd.WINDOWED_LEFT_HAND
    label_rh = Y == hd.WINDOWED_RIGHT_HAND
    n_lh_correct = (pred_lh * label_lh).sum()
    n_rh_correct = (pred_rh * label_rh).sum()
    assert n_lh_correct <= n_notes
    assert n_rh_correct <= n_notes
    n_correct = n_lh_correct + n_rh_correct
    assert n_correct <= n_notes
    return n_correct / n_notes * 100.0

def _rnn_with_type(rnn_type, n_features, hidden_size, n_layers, bidirectional):
    if rnn_type.upper() == 'LSTM':
        return nn.LSTM(input_size=n_features, hidden_size=hidden_size, num_layers=n_layers, batch_first=True,
                       dropout=0.5, bidirectional=bidirectional)
    elif rnn_type.upper() == 'GRU':
        return nn.GRU(input_size=n_features, hidden_size=hidden_size, num_layers=n_layers, batch_first=True,
                      dropout=0.5, bidirectional=bidirectional)
    else:
        raise ValueError('Unknown RNN type: ' + rnn_type)