text:
/* CVS $Id: $ */
package de.unibonn.iai.eis.diachron.semantics;
import com.hp.hpl.jena.rdf.model.*;

/**
 * Vocabulary definitions from src/main/resources/vocabularies/dqm/dqm-prob.ttl
 * @author Auto-generated by schemagen on 17 May 2016 15:13
 */
public class DQMPROB {
    /**
The RDF model that holds the vocabulary terms
 */
    private static Model m_model = ModelFactory.createDefaultModel();

    /**
The namespace of the vocabulary as a string
 */
    public static final String NS = "http://www.diachron-fp7.eu/dqm-prob#";

    /**
The namespace of the vocabulary as a string

     *  @see #NS */
    public static String getURI() {return NS;}

    /**
The namespace of the vocabulary as a resource
 */
    public static final Resource NAMESPACE = m_model.createResource( NS );

    public static final Property actualContentType = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#actualContentType" );

    public static final Property expectedContentType = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#expectedContentType" );

    public static final Property forCodedProperty = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#forCodedProperty" );

    public static final Property hasMisplacedClass = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hasMisplacedClass" );

    public static final Property hasMisplacedProperty = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hasMisplacedProperty" );

    public static final Property hasMisusedDatatypeProperty = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hasMisusedDatatypeProperty" );

    public static final Property hasMisusedObjectProperty = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hasMisusedObjectProperty" );

    public static final Property hasNoBackLink = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hasNoBackLink" );

    public static final Property hasViolatingTriple = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hasViolatingTriple" );

    public static final Property hijackedTripleStatement = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#hijackedTripleStatement" );

    public static final Property missingPopulationCoverageList = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#missingPopulationCoverageList" );

    public static final Property problematicTriple = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#problematicTriple" );

    public static final Property violatedObject = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#violatedObject" );

    public static final Property violatedPredicate = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#violatedPredicate" );

    public static final Property violatingDisjoinedClass = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#violatingDisjoinedClass" );

    public static final Property violatingSubjects = m_model.createProperty( "http://www.diachron-fp7.eu/dqm-prob#violatingSubjects" );

    /**
The class used is deprecated in the respective schema
 */
    public static final Resource DeprecatedClass = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#DeprecatedClass" );

    /**
The property used is deprecated in its respective schema.
 */
    public static final Resource DeprecatedProperty = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#DeprecatedProperty" );

    /**
An Incorrect URI style used for dataset. For datasets with more than 500K
     *  triples Slash URIs are suggested, whilst for less than 500K triples Hash URIs
     *  should be used

     */
    public static final Resource IncorrectCoolURIUsage = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#IncorrectCoolURIUsage" );

    /**
The property should not be used within a resource of this type.
 */
    public static final Resource IncorrectDomain = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#IncorrectDomain" );

    /**
The defined format using the void:feature predicate is unknown. Check http://www.w3.org/ns/formats/.
 */
    public static final Resource IncorrectFormatDefined = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#IncorrectFormatDefined" );

    /**
The property's value has an incorrect data type
 */
    public static final Resource IncorrectRange = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#IncorrectRange" );

    /**
The described URI is not a valid RDF data dump
 */
    public static final Resource InvalidDataDumpURI = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#InvalidDataDumpURI" );

    /**
The described SPARQL endpoint is either invalid or not responding
 */
    public static final Resource InvalidSPARQLEndPoint = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#InvalidSPARQLEndPoint" );

    /**
The referred predicate and objects are used in multiple subject resources
     *  which violates the IFP metric.

     */
    public static final Resource InverseFunctionalPropertyViolation = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#InverseFunctionalPropertyViolation" );

    /**
According to W3C URI standards, a URI should not be longer than 80 characters
     *  including the schema. Long URIs are not recommended. Refer to CoolURIs (http://www.linkeddata.org/how-to-publish)

     */
    public static final Resource LongURI = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#LongURI" );

    /**
The External Link provide a low number of resources that provide RDF
 */
    public static final Resource LowPercentageOfValidPLDResources = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#LowPercentageOfValidPLDResources" );

    /**
The referred resource, used a defined class instead of a property, in the
     *  property's position.

     */
    public static final Resource MisplacedClass = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MisplacedClass" );

    /**
The referred resource, used a defined property instead of a class, in an rdf:type
     *  statement object's position.

     */
    public static final Resource MisplacedProperty = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MisplacedProperty" );

    /**
The described Resource has a misreported content type
 */
    public static final Resource MisreportedTypeException = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MisreportedTypeException" );

    /**
The referred dataset have missing metadata properties thus cannot calculate
     *  currency.

     */
    public static final Resource MissingMetadataForCurrency = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MissingMetadataForCurrency" );

    /**
The referred dataset have missing metadata properties thus cannot calculate
     *  data freshness.

     */
    public static final Resource MissingMetadataForFreshness = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MissingMetadataForFreshness" );

    /**
The referred dataset have missing metadata properties thus cannot calculate
     *  data timeliness.

     */
    public static final Resource MissingMetadataForTimelinessOfResource = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MissingMetadataForTimelinessOfResource" );

    /**
The referred list of objects are not covered in the dataset.
 */
    public static final Resource MissingPopulationCoverage = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MissingPopulationCoverage" );

    /**
The referred resource used a datatype property instead of an Object Property.
 */
    public static final Resource MisusedDatatypeProperty = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MisusedDatatypeProperty" );

    /**
The referred resource used an object property instead of a datatype property.
 */
    public static final Resource MisusedObjectProperty = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MisusedObjectProperty" );

    /**
The referred resource is multi-typed with disjoined classes.
 */
    public static final Resource MultiTypedResourceWithDisjointedClasses = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#MultiTypedResourceWithDisjointedClasses" );

    /**
The described resource does not provide a valid back link
 */
    public static final Resource NoBackLink = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoBackLink" );

    /**
The dataset has no valid SPARQL Endpoints defined with the void:sparqlEndpoint
     *  predicate

     */
    public static final Resource NoEndPointAccessibility = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoEndPointAccessibility" );

    /**
Entities in this list have no Human Readable Label.
 */
    public static final Resource NoHumanReadableLabel = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoHumanReadableLabel" );

    /**
The dataset must have more than one serialisation format defined using the
     *  void:feature predicate.

     */
    public static final Resource NoMultipleFormatDefined = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoMultipleFormatDefined" );

    /**
The dataset has no valid RDF Dump defined with the void:dataDump predicate
 */
    public static final Resource NoRDFAccessibility = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoRDFAccessibility" );

    /**
No regular expression in the voID description.
 */
    public static final Resource NoURIRegExPresence = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoURIRegExPresence" );

    /**
The described RDF Document/Dataset has no valid licence in the voID description
     *  or in its metadata

     */
    public static final Resource NoValidLicenceInDataset = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoValidLicenceInDataset" );

    /**
The described RDF Document/Dataset has no valid licence in the in its descriptive
     *  metadata

     */
    public static final Resource NoValidLicenceInDatasetForHumans = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoValidLicenceInDatasetForHumans" );

    /**
The External Link provided does not give valid RDF
 */
    public static final Resource NoValidRDFDataForExternalLink = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoValidRDFDataForExternalLink" );

    /**
Vocabularies in this list are not indicated by a respective voID description.
 */
    public static final Resource NoVocabularyIndication = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NoVocabularyIndication" );

    /**
The described resource has a dereferenceable code as recommended by the LOD
     *  Principles (i.e. 303 See Other or Hash URI), but no meaningful data

     */
    public static final Resource NotMeaningful = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NotMeaningful" );

    /**
The described RDF Document/Dataset has a valid licence that is not recommended
     *  according to the voID W3C Standards

     */
    public static final Resource NotRecommendedLicenceInDataset = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NotRecommendedLicenceInDataset" );

    /**
The described RDF Document/Dataset has a valid licence that is not recommended
     *  according to the voID W3C Standards

     */
    public static final Resource NotRecommendedLicenceInDatasetForHumans = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NotRecommendedLicenceInDatasetForHumans" );

    /**
The described resource do not resolve in a valid Dereferenced Link
 */
    public static final Resource NotValidDereferenceableBackLink = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NotValidDereferenceableBackLink" );

    /**
The described resource do not resolve in a valid Dereferenced Forward-Link
 */
    public static final Resource NotValidForwardLink = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#NotValidForwardLink" );

    /**
The referred resource hijacked an external authorative concept.
 */
    public static final Resource OntologyHijackingException = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#OntologyHijackingException" );

    /**
The resource URI includes a parameterised string.
 */
    public static final Resource ParametarisedURI = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#ParametarisedURI" );

    /**
The referred resource has a replica resource with a different id.
 */
    public static final Resource ResourceReplica = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#ResourceReplica" );

    /**
The described resource has a dereferenceability Status Code of 200 instead
     *  of the required Status Code 303

     */
    public static final Resource SC200OK = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC200OK" );

    /**
The described resource has a dereferenceability Status Code of 301 Moved Permanently
 */
    public static final Resource SC301MovedPermanently = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC301MovedPermanently" );

    /**
The described resource has a dereferenceability Status Code of 302 Found
 */
    public static final Resource SC302Found = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC302Found" );

    /**
The described resource has a dereferenceability Status Code of 303 but the
     *  content is not parsable due to incorrect content-type

     */
    public static final Resource SC303WithoutParsableContent = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC303WithoutParsableContent" );

    /**
The described resource has a dereferenceability Status Code of 307 Temporary
     *  Redirected

     */
    public static final Resource SC307TemporaryRedirectory = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC307TemporaryRedirectory" );

    /**
The described resource has a dereferenceability Status Code of a 3XX Redirection
     *  but not the recommended 303 See Other

     */
    public static final Resource SC3XXRedirection = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC3XXRedirection" );

    /**
The described resource has a dereferenceability Status Code of 4XX Client
     *  Error

     */
    public static final Resource SC4XXClientError = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC4XXClientError" );

    /**
The described resource has a dereferenceability Status Code of 5XX Server
     *  Error

     */
    public static final Resource SC5XXServerError = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#SC5XXServerError" );

    /**
The class used is undefined in the respective schema
 */
    public static final Resource UndefinedClass = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UndefinedClass" );

    /**
The property used is undefined in its respective schema.
 */
    public static final Resource UndefinedProperty = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UndefinedProperty" );

    /**
The resource type is unknown.
 */
    public static final Resource UnknownType = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UnknownType" );

    /**
The dataset did not use terms from the suggested vocabulary.
 */
    public static final Resource UnusedSuggestedVocabulary = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UnusedSuggestedVocabulary" );

    /**
The resource is using RDF collections feature. The use of rdf:Alt, rdf:Bag,
     *  rdf:List, or any other prolix feature is strongly discouraged.

     */
    public static final Resource UsageOfCollections = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UsageOfCollections" );

    /**
The resource is using RDF containers feature (type - rdf:Container). The use
     *  of rdf:Container or any other prolix feature is strongly discouraged.

     */
    public static final Resource UsageOfContainers = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UsageOfContainers" );

    /**
The resource is using RDF reification feature (type - rdf:Statement). The
     *  use of rdf:Statement or any other prolix feature is strongly discouraged.

     */
    public static final Resource UsageOfReification = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#UsageOfReification" );

    /**
The described resource has a violating forward link dereferencable triple
 */
    public static final Resource ViolatingTriple = m_model.createResource( "http://www.diachron-fp7.eu/dqm-prob#ViolatingTriple" );

}


text:
// +build linux

/*
 Package i2c provides low level control over the linux i2c bus.

 Before usage you should load the i2c-dev kernel module

       sudo modprobe i2c-dev

 Each i2c bus can address 127 independent i2c devices, and most
 linux systems contain several buses.

 Source: https://github.com/d2r2/go-i2c
 */
package adcpi

import (
	"fmt"
	"os"
	"syscall"
)

const (
	I2C_SLAVE = 0x0703
	/* Ugly hack so this compiles on windows. */
	SYS_IOCTL = 16
)

/*
 I2C represents a connection to an i2c device.
 */
type I2C struct {
	rc *os.File
}

/*
 New opens a connection to an i2c device.
 */
func NewI2C(addr uint8, bus int) (*I2C, error) {
	f, err := os.OpenFile(fmt.Sprintf("/dev/i2c-%d", bus), os.O_RDWR, 0600)
	if err != nil {
		return nil, err
	}
	if err := ioctl(f.Fd(), I2C_SLAVE, uintptr(addr)); err != nil {
		return nil, err
	}
	this := &I2C{rc: f}
	return this, nil
}

/*
 Write sends buf to the remote i2c device. The interpretation of
 the message is implementation dependant.
 */
func (this *I2C) Write(buf []byte) (int, error) {
	return this.rc.Write(buf)
}

func (this *I2C) WriteByte(b byte) (int, error) {
	var buf [1]byte
	buf[0] = b
	return this.rc.Write(buf[:])
}

func (this *I2C) Read(p []byte) (int, error) {
	return this.rc.Read(p)
}

func (this *I2C) Close() error {
	return this.rc.Close()
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Read byte from i2c device register specified in reg.
 */
func (this *I2C) ReadRegU8(reg byte) (byte, error) {
	_, err := this.Write([]byte{reg})
	if err != nil {
		return 0, err
	}
	buf := make([]byte, 1)
	_, err = this.Read(buf)
	if err != nil {
		return 0, err
	}
	return buf[0], nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Write byte to i2c device register specified in reg.
 */
func (this *I2C) WriteRegU8(reg byte, value byte) error {
	buf := []byte{reg, value}
	_, err := this.Write(buf)
	if err != nil {
		return err
	}
	return nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Read unsigned big endian word (16 bits) from i2c device
 starting from address specified in reg.
 */
func (this *I2C) ReadRegU16BE(reg byte) (uint16, error) {
	_, err := this.Write([]byte{reg})
	if err != nil {
		return 0, err
	}
	buf := make([]byte, 2)
	_, err = this.Read(buf)
	if err != nil {
		return 0, err
	}
	w := uint16(buf[0])<<8 + uint16(buf[1])
	return w, nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Read unsigned little endian word (16 bits) from i2c device
 starting from address specified in reg.
 */
func (this *I2C) ReadRegU16LE(reg byte) (uint16, error) {
	w, err := this.ReadRegU16BE(reg)
	if err != nil {
		return 0, err
	}
	// exchange bytes
	w = (w&0xFF)<<8 + w>>8
	return w, nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Read signed big endian word (16 bits) from i2c device
 starting from address specified in reg.
 */
func (this *I2C) ReadRegS16BE(reg byte) (int16, error) {
	_, err := this.Write([]byte{reg})
	if err != nil {
		return 0, err
	}
	buf := make([]byte, 2)
	_, err = this.Read(buf)
	if err != nil {
		return 0, err
	}
	w := int16(buf[0])<<8 + int16(buf[1])
	return w, nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Read unsigned little endian word (16 bits) from i2c device
 starting from address specified in reg.
 */
func (this *I2C) ReadRegS16LE(reg byte) (int16, error) {
	w, err := this.ReadRegS16BE(reg)
	if err != nil {
		return 0, err
	}
	// exchange bytes
	w = (w&0xFF)<<8 + w>>8
	return w, nil

}

/*
 SMBus (System Management Bus) protocol over I2C.
 Write unsigned big endian word (16 bits) value to i2c device
 starting from address specified in reg.
 */
func (this *I2C) WriteRegU16BE(reg byte, value uint16) error {
	buf := []byte{reg, byte((value & 0xFF00) >> 8), byte(value & 0xFF)}
	_, err := this.Write(buf)
	if err != nil {
		return err
	}
	return nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Write unsigned big endian word (16 bits) value to i2c device
 starting from address specified in reg.
 */
func (this *I2C) WriteRegU16LE(reg byte, value uint16) error {
	w := (value*0xFF00)>>8 + value<<8
	return this.WriteRegU16BE(reg, w)
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Write signed big endian word (16 bits) value to i2c device
 starting from address specified in reg.
 */
func (this *I2C) WriteRegS16BE(reg byte, value int16) error {
	buf := []byte{reg, byte((uint16(value) & 0xFF00) >> 8), byte(value & 0xFF)}
	_, err := this.Write(buf)
	if err != nil {
		return err
	}
	return nil
}

/*
 SMBus (System Management Bus) protocol over I2C.
 Write signed big endian word (16 bits) value to i2c device
 starting from address specified in reg.
 */
func (this *I2C) WriteRegS16LE(reg byte, value int16) error {
	w := int16((uint16(value)*0xFF00)>>8) + value<<8
	return this.WriteRegS16BE(reg, w)
}

func ioctl(fd, cmd, arg uintptr) error {
	_, _, err := syscall.Syscall6(uintptr(syscall.SYS_IOCTL), fd, cmd, arg, uintptr(0), uintptr(0), uintptr(0))
	if err != 0 {
		return err
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
import atexit
import logging

from managesf import model
from managesf.services import base
from managesf.services.nodepool.common import get_values, get_age
from managesf.services.nodepool.common import validate_input

logger = logging.getLogger(__name__)

crud = model.ImageUpdatesCRUD()

LIST_CMD = 'nodepool image-list | sed -e 1,3d -e "$ d"'
LIST_FIELDS = ['id', 'provider_name', 'image_name', 'hostname', 'version',
               'image_id', 'server_id', 'state', 'age']
UPDATE_CMD = ('nodepool image-update %(provider)s %(image)s')

UPDATES_CACHE = {}
REFRESH_LOCKED = False

def _refresh_cache():
    global REFRESH_LOCKED
    if REFRESH_LOCKED:
        logger.debug("image update cache is locked, refresh it later")
        return
    to_remove = []
    REFRESH_LOCKED = True
    logger.debug("locking image update cache for refresh")
    for u in UPDATES_CACHE:
        if UPDATES_CACHE[u]['stdout'].channel.exit_status_ready():
            stdout = UPDATES_CACHE[u]['stdout']
            stderr = UPDATES_CACHE[u]['stderr']
            client = UPDATES_CACHE[u]['client']
            exit_code = int(stdout.channel.recv_exit_status())
            if exit_code > 0:
                status = "FAILURE"
            else:
                status = "SUCCESS"
            crud.update(id=u, status=status, exit_code=str(exit_code),
                        output=stdout.read(), stderr=stderr.read())
            client.close()
            to_remove.append(u)
    for u in to_remove:
        del UPDATES_CACHE[u]
    REFRESH_LOCKED = False
    logger.debug("image update cache unlocked")

class SFNodepoolImageManager(base.ImageManager):
    """Image related operations from Nodepool's CLI, via SSH"""
    def __init__(self, plugin):
        super(SFNodepoolImageManager, self).__init__(plugin)

    def get(self, provider_name=None, image_name=None, **kwargs):
        """lists one or several images depending on filtering options"""
        images_info = []
        client = self.plugin.get_client()
        logger.debug("[%s] calling %s" % (self.plugin.service_name,
                                          LIST_CMD))
        stdin, stdout, stderr = client.exec_command(LIST_CMD)
        return_code = int(stdout.channel.recv_exit_status())
        client.close()
        if return_code > 0:
            e = stderr.read()
            m = "[%s] image get failed with exit code %i: %s"
            m = m % (self.plugin.service_name, return_code, e)
            logger.error(m)
            raise Exception(m)
        for line in stdout.readlines():
            values = get_values(line)
            image = dict(zip(LIST_FIELDS, values))
            image['age'] = get_age(image['age'])
            if provider_name and image_name:
                if (provider_name == image['provider_name'] and
                   image_name == image['image_name']):
                    images_info.append(image)
            elif provider_name:
                if provider_name == image['provider_name']:
                    images_info.append(image)
            elif image_name:
                if image_name == image['image_name']:
                    images_info.append(image)
            else:
                images_info.append(image)
        return images_info

    def start_update(self, provider_name, image_name):
        """updates (rebuild) the image image_name on provider provider_name"""
        _refresh_cache()
        if (not validate_input(provider_name) or
           not validate_input(image_name)):
            msg = "invalid provider %r and/or image %r" % (provider_name,
                                                           image_name)
            raise Exception(msg)
        client = self.plugin.get_client()
        args = {'provider': provider_name,
                'image': image_name}
        update_id = int(crud.create(**args))
        logger.debug("[%s] calling %s" % (self.plugin.service_name,
                                          UPDATE_CMD % args))
        cmd = UPDATE_CMD % args
        stdin, stdout, stderr = client.exec_command(cmd, get_pty=True)
        UPDATES_CACHE[update_id] = {'stdout': stdout,
                                    'stderr': stderr,
                                    'client': client}
        UPDATES_CACHE[update_id].update(args)
        return update_id

    def get_update_info(self, id):
        """fetches relevant info on an image update possibly still
        in progress"""
        _refresh_cache()
        x = crud.get(id)
        if x:
            return {'id': id,
                    'status': x['status'],
                    'provider': x['provider'],
                    'image': x['image'],
                    'exit_code': x['exit_code'],
                    'output': x['output'],
                    'error': x['stderr']}
        elif int(id) in UPDATES_CACHE:
            # TODO(mhu) Find a way to return the output in progress. Could we
            # copy the file-like stdout object?
            return {'id': id,
                    'status': 'IN_PROGRESS',
                    'provider': UPDATES_CACHE['provider'],
                    'image': UPDATES_CACHE['image'],
                    'exit_code': None,
                    'output': None,
                    'error': None}
        else:
            return {}

# For the DBZ fans
def final_flush():
    from sqlalchemy.exc import OperationalError
    try:
        _refresh_cache()
        for u in UPDATES_CACHE:
            stdout = UPDATES_CACHE[u]['stdout']
            stderr = UPDATES_CACHE[u]['stderr']
            client = UPDATES_CACHE[u]['client']
            status = "INTERRUPTED"
            crud.update(id=u, status=status, output=stdout.read(),
                        stderr=stderr.read())
            client.close()
    except OperationalError as e:
        msg = "[img-update] Error handling final cache flush on db: %s"
        logger.error(msg % e)
    except Exception as e:
        msg = "[img-update] Unknown error handling final cache flush: %s"
        logger.error(msg % e)

atexit.register(final_flush)


text:
class User < ActiveRecord::Base
  attr_accessible :email
  attr_accessible :name
  attr_accessible :first_name
  attr_accessible :last_name
end


text:
module Bitbot
  module Trader
    module Providers
      class MtGox
        # Parses raw open orders
        #
        class AccountInfoParser < Parser
          include Virtus.model

          attribute :Trade_Fee, Float
          attribute :Wallets, Hash

          # Makes raw account info hash into Account object
          #
          # @return [Account]
          #
          # @api private
          #
          def parse
            parsed = attributes

            Account.new(
              fee: parsed[:Trade_Fee],
              wallets: self.class.parse_wallets(parsed[:Wallets])
            )
          end

          # Parses raw wallets
          #
          # @param [Hash<String, Hash>] raw_wallets
          #
          # @return [Array<Hash>]
          #
          # @api private
          #
          def self.parse_wallets(raw_wallets)
            raw_wallets.map { |_key, raw_wallet|
              ValueWithCurrencyCoercer.call(raw_wallet["Balance"])
            }
          end
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

	<title>WOWSlider</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="description" content="WOWSlider" />

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

		1
		2
		3
		4

responsive slider by WOWSlider.com v8.5m

HTML code for the slider /Users/ansonmenzie/BootcampB33/Bootcamp_Repos/FinalProject/OriginalPranksters/public/wowsliderprank.html

		How to add this slider to HTML page

1 Upload these folders to your server

data1/

engine1/

Current location: /Users/ansonmenzie/BootcampB33/Bootcamp_Repos/FinalProject/OriginalPranksters/public.
These folders should be located in the same folder as your html page

2 Paste this code to your page between the tags <head></head>

	<textarea onclick="this.select()"><!-- Start WOWSlider.com HEAD section -->
<link rel="stylesheet" type="text/css" href="engine1/style.css" />
<script type="text/javascript" src="engine1/jquery.js"></script>
<!-- End WOWSlider.com HEAD section --></textarea>

3 Paste this code to your page between the tags <body></body> in the place that you want the slider to appear

	<textarea onclick="this.select()" rows="15"><!-- Start WOWSlider.com BODY section -->
<div id="wowslider-container1">
<div class="ws_images"><ul>
		<li><a href="food.html"><img src="data1/images/pizza_man_jpg..jpg" alt="Pizza Delivery Prank" title="Pizza Delivery Prank" id="wows1_0"/></a></li>
		<li><a href="amzn.html"><img src="data1/images/amazonbox.jpg" alt="Amazon Order Prank" title="Amazon Order Prank" id="wows1_1"/></a></li>
		<li><a href="fantasy.html"><img src="data1/images/fantasy_football_prank.jpg" alt="Fantasy Football Prank" title="Fantasy Football Prank" id="wows1_2"/></a></li>
		<li><a href="doctor.html"><img src="data1/images/dr._appointment_prank.jpg" alt="Dr. Appointment Prank" title="Dr. Appointment Prank" id="wows1_3"/></a></li>
	</ul></div>
	<div class="ws_bullets"><div>
		<a href="#" title="Pizza Delivery Prank"><span><img src="data1/tooltips/pizza_man_jpg..jpg" alt="Pizza Delivery Prank"/>1</span></a>
		<a href="#" title="Amazon Order Prank"><span><img src="data1/tooltips/amazonbox.jpg" alt="Amazon Order Prank"/>2</span></a>
		<a href="#" title="Fantasy Football Prank"><span><img src="data1/tooltips/fantasy_football_prank.jpg" alt="Fantasy Football Prank"/>3</span></a>
		<a href="#" title="Dr. Appointment Prank"><span><img src="data1/tooltips/dr._appointment_prank.jpg" alt="Dr. Appointment Prank"/>4</span></a>
	</div></div><div class="ws_script" style="position:absolute;left:-99%"><a href="http://wowslider.com">responsive slider</a> by WOWSlider.com v8.5m</div>
<div class="ws_shadow"></div>
</div>
<script type="text/javascript" src="engine1/wowslider.js"></script>
<script type="text/javascript" src="engine1/script.js"></script>
<!-- End WOWSlider.com BODY section --></textarea>

Also you can try the Insert-To-Page wizard, to add the slider visually, without touching the code!

	Click here for the detailed info.


text:
import os

from piptools.scripts.compile import cli

PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)

def main():
    cli([os.path.join(PROJECT_DIRECTORY, 'requirements.in')])

if __name__ == "__main__":
    main()


text:
Open Source Point of Sale is a web based point of sale system written in the PHP language. It uses MySQL as the data storage back-end and has a simple user interface.

How to Install
--------------
1. Create/locate a new mysql database to install open source point of sale into
2. Execute the file database/database.sql to create the tables needed
3. unzip and upload Open Source Point of Sale files to web server
4. Copy application/config/database.php.tmpl to application/config/database.php
5. Modify application/config/database.php to connect to your database
6. Modify application/config/config.php encryption key with your own
7. Go to your point of sale install via the browser
8. LOGIN using
username: admin
password:pointofsale
9. Enjoy

If you like the project, and you are making money out of it on a daily basis, then consider to buy me a coffee so I can keep adding features.


text:
@interface EditProfileViewController () <UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource> {
    NSArray *arrCountry;
    NSArray *arrDOB;
    NSArray *arrGender;
}

@end

@implementation EditProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *dictInfo = [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"];
    self.txtFullName.text = [dictInfo valueForKey:@"Display_Name"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
    NSDate *dob = [dateFormatter dateFromString:[dictInfo valueForKey:@"DOB"]];
    [dateFormatter setDateFormat:@"YYYY/MM/dd"];
    self.txtDOB.text = [dateFormatter stringFromDate:dob];

    self.txtEmail.text = [dictInfo valueForKey:@"User_Email"];
    self.txtGender.text = ([dictInfo valueForKey:@"Gender"]) ? [dictInfo valueForKey:@"Gender"] : @"Gender";
    self.txtPhone.text = [dictInfo valueForKey:@"Mobile_No"];
    self.txtPhone.text = [dictInfo valueForKey:@"Country_id"];
    arrCountry = [[NSArray alloc] initWithObjects:@"Country", @"Kingdom of Saudi Arabia ",nil];
    arrGender = [[NSArray alloc] initWithObjects:@"Gender", @"Male", @"Female", nil];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if(self.txtDOB == textField ) {
        //        [(CustomDatePicker *)textField showPicker];
        return NO;
    }
    if(self.txtGender == textField || self.txtCountry == textField ) {
        //        [(CustomDropDownTextField *)textField showPicker];
        return NO;
    }
    return YES;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (pickerView.tag) {
        case 1:
            return arrGender.count;
            break;
        case 2:
            return arrCountry.count;
            break;
        case 3:
            return arrCountry.count;
            break;
        default:
            break;
    }
    return arrCountry.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    switch (pickerView.tag) {
        case 1:
            return arrGender[row];
            break;
        case 2:
            return arrCountry[row];
            break;
        case 3:
            return arrCountry[row];
            break;
        default:
            break;
    }
    return nil;
}

- (IBAction)submitTapped:(id)sender {
    if([self validate]) {
        NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
        [dict setObject:self.txtFullName.text forKey:@"Display_Name"];
        [dict setObject:self.txtDOB.text forKey:@"Date"];
        [dict setObject:self.txtEmail.text forKey:@"User_Email"];
        [dict setObject:self.txtGender.text forKey:@"Gender"];
        [dict setObject:self.txtPhone.text forKey:@"Mobile_No"];
        [dict setObject:[@(self.txtCountry.tag) stringValue] forKey:@"Country_id"];
        [dict setObject:[NSString stringWithFormat:@"%d", self.btnSubscribeNewsletter.selected] forKey:@"Subscribe_NewsLetter"];
        [dict setObject:@"en" forKey:@"language"];

        [ApiManager postCall:@"user/PatientRegistertion" params:dict callBack:^(NSData* data) {
            NSError *parseError = nil;
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
            if(dictionary) {
                if ([[dictionary valueForKey:@"Status"] integerValue]) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [AppDelegate.this setRootView];
                    });

                } else {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [super showErrorPopup:@"Error" msg:@"Invalid email or password."];
                    });

                }
            }
        }];
    }
}

- (IBAction)termsAndConditions:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (IBAction)subscribeNewsletter:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (BOOL)validate {
    NSString *errmsg = [self checkValues];
    if(errmsg.length > 0) {
        [super showErrorPopup:@"Error" msg:errmsg];
        return NO;
    }
    return YES;
}

- (NSString *)checkValues {
    if([self.txtFullName.text isEqualToString:@""]) {
        return @"Please enater name.";
    } else if([self.txtGender.text isEqualToString:@"Gender"]){
        return @"Please select Gender.";
    } else if([self.txtDOB.text isEqualToString:@"DOB"]){
        return @"Please select DOB.";
    } else if([self.txtEmail.text isEqualToString:@""]){
        return @"Please enater email address.";
    } else if([self.txtPhone.text isEqualToString:@""]){
        return @"Please enater phone.";
    } else if([self.txtCountry.text isEqualToString:@"Country"]){
        return @"Please select select.";
    } else if(!self.btnTermsAndConditions.selected){
        return @"Please select terms and conditions.";
    }

    return @"";
}

- (void) openPicker:(UITapGestureRecognizer*) gesture {
    CustomDropDownTextField *tf = (CustomDropDownTextField*)gesture.view;
    [(CustomDropDownTextField *)tf showPicker];
}

- (void) openDatePicker:(UITapGestureRecognizer*) gesture {
    CustomDatePicker *tf = (CustomDatePicker*)gesture.view;
    [(CustomDatePicker *)tf showPicker];
}

@end


text:
from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals
)

import copy
import six

class PytingoData(object):
    """Settings flexible mapper"""

    __slots__ = [
        "_data_dict", "_meta_field", "_separator", "_wildcard", "_list_accessor", "_meta", "_processed_data_dict"
    ]

    def __init__(self, data_dict, process_meta=True, meta_field=".meta", separator=".", wildcard="*", list_accessor="$"):
        """
        Args:
            :param data_dict:
            :type data_dict:

            :param process_meta:
            :type process_meta:

            :param meta_field:
            :type meta_field:

            :param separator:
            :type separator:

            :param wildcard:
            :type wildcard:
        """
        if not isinstance(data_dict, dict):
            raise ValueError("data_dict must be of type dict.")
        if not isinstance(process_meta, bool):
            raise ValueError("process_meta must be of type bool.")

        if not isinstance(meta_field, six.string_types):
            raise ValueError("meta_field must be of type str.")
        if not isinstance(separator, six.string_types):
            raise ValueError("separator must be of type str.")
        if not isinstance(wildcard, six.string_types):
            raise ValueError("wildcard must be of type str.")
        if not isinstance(list_accessor, six.string_types):
            raise ValueError("list_accessor must be of type str.")

        # We make a deep copy to avoid side effects if data_dict changes.
        self._data_dict = copy.deepcopy(data_dict)

        self._meta_field = meta_field
        self._separator = separator
        self._wildcard = wildcard
        self._list_accessor = list_accessor

        if not process_meta or self._meta_field not in self._data_dict:
            self._meta = {}
            self._processed_data_dict = self._data_dict
        else:
            self._meta = self._data_dict.pop(self._meta_field)
            self._process_meta()

    def _process_meta(self):
        """
        """
        # We make a deep copy to modify self._processed_data_dict without any risks.
        self._processed_data_dict = copy.deepcopy(self._data_dict)

        if "inheritance" in self._meta:
            self._process_inheritance()

    def _process_inheritance(self):
        """
        """
        inheritance = self._meta["inheritance"]

        for inheritor_str_path in inheritance:
            inheritors = self._get_inheritors(
                inheritor_str_path.split(self._separator)
            )

            for inheritor in inheritors:
                if isinstance(inheritor, dict):
                    for inheritable_value_key in inheritance[inheritor_str_path]:
                        if inheritable_value_key in inheritor:
                            continue

                        try:
                            inheritor[inheritable_value_key] = self.get(inheritable_value_key)
                        except KeyError:
                            pass
                elif isinstance(inheritor, list):
                    pass
                else:
                    # TODO: Raise Custom Exception
                    raise ValueError(
                        "A field pointed by the path '" + inheritor_str_path +
                        "' is an atomic value and can't inherit anything."
                    )

    def _get_inheritors(self, path, tracepoint=None):
        if tracepoint is None:
            if path == []:
                raise RuntimeError("There is no point to make . inheriting from a subfield.")
            tracepoint = self._processed_data_dict

        key = path[0]

        if isinstance(tracepoint, dict):
            if key == self._wildcard:
                inheritors = []
                selected_items_type = None

                for tp_key in tracepoint:
                    item_type = type(tracepoint[tp_key])

                    if selected_items_type is None:
                        selected_items_type = item_type
                    elif selected_items_type != item_type:
                        raise ValueError(
                            "The items types must be uniform when the items are selected with a wildcard."
                        )

                    if len(path) == 1:
                        inheritors.append(tracepoint[tp_key])
                    else:
                        inheritors.extend(self._get_inheritors(
                            path[1:], tracepoint[tp_key]
                        ))

                return inheritors

            elif key in tracepoint:
                if len(path) == 1:
                    return [tracepoint[key]]

                return self._get_inheritors(path[1:], tracepoint[key])
            else:
                return []

        elif isinstance(tracepoint, list):
            inheritors = []
            selected_items_type = None

            for item in tracepoint:
                item_type = type(item)

                if selected_items_type is None:
                    selected_items_type = item_type
                elif selected_items_type != item_type:
                    raise ValueError(
                        "The items types must be uniform when the items are selected with a wildcard."
                    )

                inheritors.extend(self._get_inheritors(
                    (path if key != self._wildcard else path[1:]), item
                ))

            return inheritors

        else:
            return []

    def as_dict(self):
        # We make a copy to avoid trolling from outside the object.
        return copy.deepcopy(self._processed_data_dict)

    def __iter__(self):
        # That's useful to iterate over dict-like settings fields.
        return self._processed_data_dict.__iter__()

    def get(self, key):
        """
        This method gives us a value of our SettingsData object.
        If the given key refers to an intermediate subdictionary, then
        a new SettingsData object is returned.
        """

        value = self._processed_data_dict
        for _key in key.split(self._separator):
            if _key != '':
                if isinstance(value, dict):
                    value = value[_key]
                elif isinstance(value, list):
                    value = value[int(_key)]

        if isinstance(value, dict):
            return PytingoData(
                value, False, self._meta_field, self._separator, self._wildcard, self._list_accessor
            )
        else:
            return value

    def __getattr__(self, attr):
        """
        Convenient accessor.
        """
        return self.get(attr)

    def __getitem__(self, item):
        """
        Convenient accessor.
        """
        return self.get(item)

    def __eq__(self, b):
        for k in self._processed_data_dict:
            if self.get(k) != b.get(k):
                return False

        return True

    def __ne__(self, b):
        return not self.__eq__(b)

    def __contains__(self, item):
        try:
            self.get(item)

            return True
        except KeyError:
            return False


text:
Imports System.ComponentModel.DataAnnotations
Imports System.Web.DynamicData
Imports System.Web

Class Decimal_EditField
    Inherits FieldTemplateUserControl

        Public Overrides ReadOnly Property DataControl As Control
            Get
                Return TextBox1
            End Get
        End Property

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            TextBox1.ToolTip = Column.Description
            SetUpValidator(RequiredFieldValidator1)
            SetUpValidator(CompareValidator1)
            SetUpValidator(RegularExpressionValidator1)
            SetUpValidator(RangeValidator1)
            SetUpValidator(DynamicValidator1)
        End Sub

        Protected Overrides Sub ExtractValues(ByVal dictionary As IOrderedDictionary)
            dictionary(Column.Name) = ConvertEditedValue(TextBox1.Text)
        End Sub

End Class


text:
#include "layereditor.h"

#include <iostream>
#include <QPushButton>
#include <stdexcept>

#include "keyable.h"
#include "utils.h"

LayerEditor::LayerEditor(QWidget *parent, TimeContext* frameContext) : QWidget(parent), _frameContext(frameContext)
{
}

#include <iostream>

void LayerEditor::setLayer(QSharedPointer<Layer> layer)
{
    _layer = layer;

    updateAttributes();
}

void LayerEditor::updateAttributes()
{
    // put current layer values in inputs
    QMap<QString, QVariant> properties = _layer->properties();
    QMap<QString, QVariant>::iterator i;
    int row = 0;

    const int currentFrame = _frameContext->currentFrame();
    for (i = properties.begin(); i != properties.end(); ++i) {
        QString name = i.key();
        QVariant value = i.value();

        QPushButton* keyFrameButton = 0;
        if (_buttons.contains(name))
            keyFrameButton = _buttons[name];

        int type = value.userType();

        QWidget* input = _inputs[name];
        if (type == qMetaTypeId<KeyablePointF>()) {
            QLineEdit* textInput = qobject_cast<QLineEdit*>(input);
            KeyablePointF kp = value.value<KeyablePointF>();
            QPointF p = kp.eval(currentFrame);
            textInput->setText(QString("").sprintf("(%.2f,%.2f)", p.x(), p.y()));

            if (keyFrameButton)
                setButtonKeyFrame(keyFrameButton, !kp.hasKeyFrameAt(currentFrame));
        } else {
            throw std::runtime_error("setLayer: unsupported property type");
        }

        // update keyframe buttons

    }
    /*
    const QMetaObject *metaobject = layer->metaObject();
    QString className = metaobject->className();

    int propertyCount = metaobject->propertyCount();
    for (int i = 0; i < propertyCount; i++) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();
        if (strcmp(name, "objectName") == 0) // not a layer property
            continue;

        QVariant::Type type = metaproperty.type();
        QWidget* input = _inputs[QString(name)];
        if (type == QVariant::Color) {

        } else {
            QLineEdit* textInput = qobject_cast<QLineEdit*>(input);

            if (type == QVariant::Point) {
                QPoint p = layer->property(name).toPoint();
                textInput->setText(QString("").sprintf("(%i,%i)", p.x(), p.y()));
            }
            else if (type == QVariant::PointF) {
                QPointF p = layer->property(name).toPointF();
                textInput->setText(QString("").sprintf("(%.2f,%.2f)", p.x(), p.y()));
            }
            else if (type == QVariant::String) {
                QString s = layer->property(name).toString();
                textInput->setText(s);
            }
        }
    }
    */
}

void LayerEditor::registerInput(QString name, QWidget* widget)
{
    _inputs.insert(name, widget);
}

void LayerEditor::registerButton(QString name, QPushButton* button)
{
    _buttons.insert(name, button);
}

void LayerEditor::updateTextProperty(QLineEdit* lineInput)
{
    if (lineInput == 0) {
        lineInput = qobject_cast<QLineEdit*>(sender());
    }
    QString propertyName = lineInput->property("variable").toString();

    QVariant property = _layer->properties()[propertyName];
    int type = property.userType();

    const int currentFrame = _frameContext->currentFrame();

    if (type == qMetaTypeId<KeyablePoint>()) {

    } else if (type == qMetaTypeId<KeyablePointF>()) {
        QPointF newValue = stringToPointF(lineInput->text());
        KeyablePointF kp = property.value<KeyablePointF>();
        if (kp.hasKeyFrameAt(currentFrame)) {
            kp.setPointF(newValue, currentFrame);
        } else {
            kp.setPointF(newValue, currentFrame, false);
        }

        _layer->setProperty(propertyName, QVariant::fromValue(kp));
    }
}

void LayerEditor::updateFrame(int frame)
{
    updateAttributes();
}

void LayerEditor::setKeyFrame()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    QString propertyName = button->property("variable").toString();

    // if it has a keyframe remove it
    //button->setProperty()
    //button->icon().

    const int frame = _frameContext->currentFrame();
    if (button->property("add_keyframe").toBool()) {
        _layer->setKeyFrame(propertyName, frame);
        _frameContext->updateFrame(frame);
        setButtonKeyFrame(button, false);

    } else {
        _layer->removeKeyFrame(propertyName, frame);
        _frameContext->updateFrame(frame);
        setButtonKeyFrame(button, true);
    }
}


text:
import datetime
import math
import os
import platform
import time
from typing import List, Sequence, Optional, Any, Tuple, Dict

import xarray as xr

from cate.conf import conf
from cate.conf.defaults import GLOBAL_CONF_FILE
from cate.conf.userprefs import set_user_prefs, get_user_prefs
from cate.core.ds import DATA_STORE_POOL
from cate.core.ds import add_as_local
from cate.core.ds import get_data_descriptor
from cate.core.ds import get_data_store_notices
from cate.core.ds import get_metadata_from_descriptor
from cate.core.op import OP_REGISTRY
from cate.core.workspace import OpKwArgs, Workspace
from cate.core.wsmanag import WorkspaceManager
from cate.util.misc import cwd
from cate.util.monitor import Monitor
from cate.util.sround import sround_range

__author__ = "Norman Fomferra (Brockmann Consult GmbH), " \
             "Marco Zühlke (Brockmann Consult GmbH)"

# noinspection PyMethodMayBeStatic
class WebSocketService:
    """
    Object which implements Cate's server-side methods.

    All methods receive inputs deserialized from JSON-RPC requests and must
    return JSON-serializable outputs.

    If *auto_stop_info* given, it is expected to provide two attributes:

    * time_of_last_activity (float): time stamp in seconds of last activity.
    * auto_stop_after (float): time period of inactivity in seconds
      after auto-close occurs.

    :param: workspace_manager The current workspace manager.
    :param: auto_stop_info Optional object that provides current
        auto-stop information.
    """

    def __init__(self,
                 workspace_manager: WorkspaceManager,
                 auto_stop_info=None):
        self.workspace_manager = workspace_manager
        self.auto_stop_info = auto_stop_info

    def _resolve_path(self, path: str) -> str:
        """Resolve incoming path against workspace manager's root path."""
        return self.workspace_manager.resolve_path(path)

    def _resolve_workspace_dir(self, workspace_dir_or_name: str) -> str:
        """Resolve incoming workspace dir path or name against workspace manager's root path."""
        # TODO (forman): remove me! this method exists, because we have
        #  workspace_manager.resolve_workspace_dir(), and this only because new_workspace()
        #  and save_workspace_as() take names instead of paths.
        return self.workspace_manager.resolve_workspace_dir(workspace_dir_or_name)

    def _serialize_workspace(self, workspace: Workspace) -> dict:
        """Serialize outgoing workspace JSON to have base_dir
        relative to workspace manager's root path."""
        workspace_json = workspace.to_json_dict()
        if self.workspace_manager.root_path:
            workspace_json['base_dir'] = \
                os.path.sep + os.path.relpath(workspace_json['base_dir'],
                                              self.workspace_manager.root_path)
        return workspace_json

    def keep_alive(self):
        """This operation is used to keep the WebSocket connection alive."""
        if not self.auto_stop_info:
            return None
        # Send auto-stop info (issue #1026)
        time_of_last_activity = self.auto_stop_info.time_of_last_activity
        available_time = self.auto_stop_info.auto_stop_after
        inactivity_time = time.time() - time_of_last_activity
        remaining_time = max(available_time - inactivity_time, 0)
        return dict(
            available_time=available_time,
            inactivity_time=inactivity_time,
            remaining_time=remaining_time
        )

    def get_config(self) -> dict:
        return dict(data_stores_path=conf.get_data_stores_path(),
                    use_workspace_imagery_cache=conf.get_use_workspace_imagery_cache(),
                    default_res_pattern=conf.get_default_res_pattern(),
                    http_proxy=conf.get_http_proxy())

    def set_config(self, config: dict) -> None:

        # Read existing config file as text
        conf_text = ''
        # noinspection PyBroadException
        try:
            with open(GLOBAL_CONF_FILE, 'r') as fp:
                conf_text = fp.read()
        except Exception:
            # ok
            pass

        # Split into config file lines
        conf_lines = conf_text.split('\n')
        for key, value in config.items():
            if value:
                new_entry = '%s = %s' % (key, repr(value))
            else:
                new_entry = '# %s =' % key
            # Try replacing existing code lines starting with key
            # Replace in reverse line order, because config files are interpreted top-down
            indices = list(range(len(conf_lines)))
            indices.reverse()
            inserted = False
            for i in indices:
                conf_line = conf_lines[i]
                if conf_line.startswith('#'):
                    # If comment, remove leading whitespaces
                    conf_line = conf_line[1:].lstrip()
                # If it starts with key,
                # next character must be '='
                # and line must not end with line continuation character
                if conf_line.startswith(key) \
                        and conf_line[len(key):].lstrip().index('=') >= 0 \
                        and not conf_line.endswith('\\'):
                    conf_lines[i] = new_entry
                    inserted = True
                    break
            if not inserted:
                conf_lines.append(new_entry)

        # Now join lines back again and write modified config file
        conf_text = '\n'.join(conf_lines)
        with open(GLOBAL_CONF_FILE, 'w') as fp:
            fp.write(conf_text)

    def get_data_stores(self) -> List[Dict[str, Any]]:
        """
        Get registered data stores.

        :return: JSON-serializable list of data stores, sorted by name.
        """
        # TODO add sensible notices
        data_stores = []
        for instance_id in sorted(DATA_STORE_POOL.store_instance_ids):
            config = DATA_STORE_POOL.get_store_config(instance_id)
            data_stores.append(dict(id=instance_id,
                                    title=config.title,
                                    isLocal=config.store_id == 'file',
                                    description=config.description,
                                    notices=get_data_store_notices(instance_id)))
        return data_stores

    def get_data_sources(self, data_store_id: str, monitor: Monitor) -> List[Dict[str, Any]]:
        """
        Get data sources for a given data store.

        :param data_store_id: ID of the data store
        :param monitor: a progress monitor
        :return: JSON-serializable list of data sources, sorted by name.
        """
        data_store = DATA_STORE_POOL.get_store(data_store_id)
        if data_store is None:
            raise ValueError('Unknown data store: "%s"' % data_store_id)
        data_ids = list(data_store.get_data_ids(
            include_attrs=['title',
                           'verification_flags',
                           'data_type'])
        )
        data_sources = []
        with monitor.starting(f'Retrieving data sources for data store {data_store_id}',
                              total_work=len(data_ids)):
            for data_id, attrs in data_ids:
                data_sources.append(dict(
                    id=data_id,
                    title=attrs.get('title', data_id),
                    verification_flags=attrs.get('verification_flags'),
                    data_type=attrs.get('data_type'))
                )
                monitor.progress(1)
        return data_sources

    def get_data_source_meta_info(self,
                                  data_store_id: str,
                                  data_source_id: str,
                                  monitor: Monitor) -> Dict[str, Any]:
        """
        Get the meta data of the data source.

        :param data_store_id: ID of the data store
        :param data_source_id: ID of the data source
        :param monitor: a progress monitor
        :return: JSON-serializable list of data sources, sorted by name.
        """
        data_store = DATA_STORE_POOL.get_store(data_store_id)
        if data_store is None:
            raise ValueError('Unknown data store: "%s"' % data_store_id)
        with monitor.starting(f'Retrieving metadata for data source {data_source_id}'):
            data_source_descriptor = data_store.describe_data(data_source_id)
            return get_metadata_from_descriptor(data_source_descriptor)

    def add_local_data_source(self, data_source_id: str,
                              file_path_pattern: str,
                              monitor: Monitor):
        """
        Adds a local data source made up of the specified files.

        :param data_source_id: The identifier of the local data source.
        :param file_path_pattern: The files path containing wildcards.
        :param monitor: a progress monitor.
        :return: JSON-serializable list with the newly added local data source
        """
        resolved_pattern = self._resolve_path(file_path_pattern)
        data, data_id = add_as_local(data_source_id=data_source_id,
                                     paths=resolved_pattern)
        data_source = dict(id=data_id, title=data_id)
        descriptor = get_data_descriptor(data_id)
        if descriptor:
            data_source['data_type'] = descriptor.data_type
        return [data_source]

    def remove_local_data_source(self,
                                 data_source_id: str,
                                 remove_files: bool,
                                 monitor: Monitor) -> list:
        """
        Removes the datasource (and optionally the giles belonging  to it)
        from the local data store.

        :param data_source_id: The identifier of the local data source.
        :param remove_files: Wether to remove the files belonging to this data source.
        :param monitor: a progress monitor.
        :return: JSON-serializable list of 'local' data sources, sorted by name.
        """
        data_store = DATA_STORE_POOL.get_store('local')
        if data_store is None:
            raise ValueError('Unknown data store: "%s"' % 'local')
        # TODO use monitor, while removing files
        if remove_files:
            data_store.delete_data(data_source_id)
        else:
            data_store.deregister_data(data_source_id)
        return self.get_data_sources('local', monitor=monitor)

    def get_operations(self, registry=None) -> List[dict]:
        """
        Get registered operations.

        :return: JSON-serializable list of data sources, sorted by name.
        """
        registry = registry or OP_REGISTRY
        op_list = []
        for op_name, op_reg in registry.op_registrations.items():
            if op_reg.op_meta_info.header.get('deprecated') or op_name.startswith('_'):
                # do not list deprecated and private operations
                continue
            op_json_dict = op_reg.op_meta_info.to_json_dict()
            op_json_dict['name'] = op_name
            op_json_dict['inputs'] = [dict(name=name, **props)
                                      for name, props in op_json_dict['inputs'].items()
                                      if not (props.get('deprecated') or props.get('context'))]
            op_json_dict['outputs'] = [dict(name=name, **props)
                                       for name, props in op_json_dict['outputs'].items()
                                       if not props.get('deprecated')]
            op_list.append(op_json_dict)

        return sorted(op_list, key=lambda op: op['name'])

    def get_open_workspaces(self) -> Sequence[dict]:
        workspace_list = self.workspace_manager.get_open_workspaces()
        return [self._serialize_workspace(workspace) for workspace in workspace_list]

    def get_workspace(self, base_dir: str) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace = self.workspace_manager.get_workspace(base_dir)
        return self._serialize_workspace(workspace)

    def list_workspace_names(self) -> Sequence[str]:
        workspace_names = self.workspace_manager.list_workspace_names()
        return workspace_names

    # see cate-desktop: src/renderer.states.WorkspaceState
    def new_workspace(self, base_dir: Optional[str], description: str = None) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir) if base_dir else None
        workspace = self.workspace_manager.new_workspace(base_dir, description)
        return self._serialize_workspace(workspace)

    # see cate-desktop: src/renderer.states.WorkspaceState
    def open_workspace(self, base_dir: str, monitor: Monitor) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        with cwd(base_dir):
            workspace = self.workspace_manager.open_workspace(base_dir, monitor=monitor)
        return self._serialize_workspace(workspace)

    # see cate-desktop: src/renderer.states.WorkspaceState
    def close_workspace(self, base_dir: str) -> None:
        base_dir = self._resolve_workspace_dir(base_dir)
        self.workspace_manager.close_workspace(base_dir)

    def close_all_workspaces(self) -> None:
        self.workspace_manager.close_all_workspaces()

    def save_workspace(self, base_dir: str, monitor: Monitor) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace = self.workspace_manager.save_workspace(base_dir, monitor=monitor)
        return self._serialize_workspace(workspace)

    def save_workspace_as(self, base_dir: str, to_dir: str, monitor: Monitor) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace = self.workspace_manager.save_workspace_as(base_dir, to_dir, monitor=monitor)
        return self._serialize_workspace(workspace)

    def save_all_workspaces(self, monitor: Monitor = Monitor.NONE) -> None:
        self.workspace_manager.save_all_workspaces(monitor=monitor)

    def clean_workspace(self, base_dir: str) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace = self.workspace_manager.clean_workspace(base_dir)
        return self._serialize_workspace(workspace)

    def delete_workspace(self, base_dir: str, remove_completely: bool = False) -> None:
        base_dir = self._resolve_workspace_dir(base_dir)
        self.workspace_manager.delete_workspace(base_dir, remove_completely)

    def rename_workspace_resource(self, base_dir: str, res_name: str, new_res_name) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace = self.workspace_manager.rename_workspace_resource(base_dir,
                                                                     res_name,
                                                                     new_res_name)
        return self._serialize_workspace(workspace)

    def delete_workspace_resource(self, base_dir: str, res_name: str) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace = self.workspace_manager.delete_workspace_resource(base_dir, res_name)
        return self._serialize_workspace(workspace)

    def set_workspace_resource(self,
                               base_dir: str,
                               op_name: str,
                               op_args: OpKwArgs,
                               res_name: Optional[str],
                               overwrite: bool,
                               monitor: Monitor) -> list:
        base_dir = self._resolve_workspace_dir(base_dir)
        with cwd(base_dir):
            workspace, res_name = \
                self.workspace_manager.set_workspace_resource(base_dir,
                                                              op_name,
                                                              op_args,
                                                              res_name=res_name,
                                                              overwrite=overwrite,
                                                              monitor=monitor)
            return [self._serialize_workspace(workspace), res_name]

    def set_workspace_resource_persistence(self,
                                           base_dir: str,
                                           res_name: str,
                                           persistent: bool) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        with cwd(base_dir):
            workspace = self.workspace_manager.set_workspace_resource_persistence(base_dir,
                                                                                res_name,
                                                                                persistent)
            return self._serialize_workspace(workspace)

    def write_workspace_resource(self, base_dir: str, res_name: str,
                                 file_path: str, format_name: str = None,
                                 monitor: Monitor = Monitor.NONE) -> None:
        base_dir = self._resolve_workspace_dir(base_dir)
        with cwd(base_dir):
            self.workspace_manager.write_workspace_resource(base_dir,
                                                            res_name,
                                                            file_path,
                                                            format_name=format_name,
                                                            monitor=monitor)

    def run_op_in_workspace(self, base_dir: str, op_name: str, op_args: OpKwArgs,
                            monitor: Monitor = Monitor.NONE) -> Optional[Any]:
        with cwd(base_dir):
            return self.workspace_manager.run_op_in_workspace(base_dir,
                                                              op_name,
                                                              op_args,
                                                              monitor=monitor)

    def extract_pixel_values(self, base_dir: str, source: str,
                             point: Tuple[float, float], indexers: dict) -> dict:
        base_dir = self._resolve_workspace_dir(base_dir)
        with cwd(base_dir):
            from cate.ops.subset import extract_point
            ds = self.workspace_manager.get_workspace(base_dir).resource_cache.get(source)
            if ds is None:
                return {}
            return extract_point(ds, point, indexers)

    def print_workspace_resource(self, base_dir: str, res_name_or_expr: str = None,
                                 monitor: Monitor = Monitor.NONE) -> None:
        base_dir = self._resolve_workspace_dir(base_dir)
        with cwd(base_dir):
            self.workspace_manager.print_workspace_resource(base_dir,
                                                            res_name_or_expr=res_name_or_expr,
                                                            monitor=monitor)

    def get_color_maps(self):
        from cate.util.im.cmaps import get_cmaps
        return get_cmaps()

    # Note, we should turn this into an operation "actual_min_max(ds, var)"
    def get_workspace_variable_statistics(self,
                                          base_dir: str,
                                          res_name: str,
                                          var_name: str,
                                          var_index: Sequence[int],
                                          monitor=Monitor.NONE):
        base_dir = self._resolve_workspace_dir(base_dir)
        workspace_manager = self.workspace_manager
        workspace = workspace_manager.get_workspace(base_dir)
        if res_name not in workspace.resource_cache:
            raise ValueError('Unknown resource "%s"' % res_name)

        dataset = workspace.resource_cache[res_name]
        if not isinstance(dataset, xr.Dataset):
            raise ValueError('Resource "%s" must be a Dataset' % res_name)

        if var_name not in dataset:
            raise ValueError('Variable "%s" not found in "%s"' % (var_name, res_name))

        variable = dataset[var_name]
        if var_index:
            variable = variable[tuple(var_index)]

        with monitor.starting('Computing min/max', total_work=100.):
            with monitor.child(work=50.).observing('Computing min'):
                actual_min = float(variable.min(skipna=True))
            with monitor.child(work=50.).observing('Computing max'):
                actual_max = float(variable.max(skipna=True))

        actual_min, actual_max = sround_range((actual_min, actual_max), ndigits=2)
        return dict(min=actual_min, max=actual_max)

    def set_preferences(self, prefs: dict):
        set_user_prefs(prefs)

    def get_preferences(self) -> dict:
        return get_user_prefs()

    def update_file_node(self, path: str) -> dict:
        """
        Return updated file node at *path*.
        :param path: A normalized, absolute path that never has a trailing "/".
        :return: A JSON dictionary containing an updated file node at *path*.
        """
        if self.workspace_manager.root_path:
            path = self._resolve_path(path)

        if platform.system() == 'Windows':
            drive_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            if not path:
                child_nodes = []
                for letter in drive_letters:
                    drive_path = f'{letter}:/'
                    if os.path.exists(drive_path):
                        child_node = _new_file_node(f'{letter}:', is_dir=True)
                        try:
                            stat_result = os.stat(drive_path)
                            _update_file_node_stat_result(child_node, stat_result)
                        except OSError as error:
                            _update_file_node_error(child_node, error)
                        child_nodes.append(child_node)
                return _new_file_node('', is_dir=True, child_nodes=child_nodes, status="ready")
            if len(path) == 2 and path[0] in drive_letters and path[1] == ':':
                basename = path
                path = basename + '/'
            else:
                basename = os.path.basename(path)
        elif path == '':
            path = '/'
            basename = ''
        elif path == '/':
            basename = ''
        else:
            basename = os.path.basename(path)

        if path == self.workspace_manager.root_path or basename == '.':
            basename = ''

        if basename.startswith('.'):
            # Make it a little securer
            raise ValueError('cannot update hidden files')

        child_nodes = None
        is_dir = os.path.isdir(path)
        if is_dir:
            child_nodes = []
            dir_it = None
            try:
                dir_it = os.scandir(path)
                for dir_entry in dir_it:
                    name = str(dir_entry.name)
                    if name.startswith('.'):
                        continue
                    child_node = _new_file_node(name,
                                                is_dir=dir_entry.is_dir(),
                                                status=None)
                    try:
                        stat_result = dir_entry.stat()
                        _update_file_node_stat_result(child_node, stat_result=stat_result)
                    except OSError as error:
                        _update_file_node_error(child_node, error)
                    child_nodes.append(child_node)
            except OSError as error:
                file_node = _new_file_node(basename, is_dir=is_dir)
                return _update_file_node_error(file_node, error)
            finally:
                if dir_it is not None:
                    # noinspection PyUnresolvedReferences
                    dir_it.close()
        file_node = _new_file_node(basename,
                                   is_dir=is_dir,
                                   child_nodes=child_nodes,
                                   status='ready')
        try:
            stat_result = os.stat(path)
            return _update_file_node_stat_result(file_node, stat_result)
        except OSError as error:
            return _update_file_node_error(file_node, error)

def _new_file_node(name: str,
                   is_dir: bool = False,
                   child_nodes: List[Dict] = None,
                   status=None) -> Dict:
    file_node = {
        "name": name,
        "isDir": is_dir
    }
    if child_nodes is not None:
        file_node["childNodes"] = child_nodes
    if status is not None:
        file_node["status"] = status
    return file_node

def _update_file_node_stat_result(file_node: Dict, stat_result) -> Dict:
    file_node["lastModified"] = _format_time(stat_result.st_mtime)
    file_node["size"] = stat_result.st_size
    return file_node

def _update_file_node_error(file_node: Dict, error) -> Dict:
    file_node["status"] = "error"
    file_node["message"] = f'{error}'
    return file_node

def _format_time(seconds):
    text = datetime.datetime.fromtimestamp(seconds).isoformat()
    if '.' in text:
        text = text[0:text.rindex('.')]
    if 'T' in text:
        text = text.replace('T', ' ')
    return text


text:
#ifndef	_ASN_CODECS_H_
#define	_ASN_CODECS_H_

#ifdef __cplusplus
extern "C" {
#endif

struct asn_TYPE_descriptor_s;	/* Forward declaration */

/*
 * This structure defines a set of parameters that may be passed
 * to every ASN.1 encoder or decoder function.
 * WARNING: if max_stack_size member is set, and you are calling the
 *   function pointers of the asn_TYPE_descriptor_t directly,
 *   this structure must be ALLOCATED ON THE STACK!
 *   If you can't always satisfy this requirement, use ber_decode(),
 *   xer_decode() and uper_decode() functions instead.
 */
typedef struct asn_codec_ctx_s {
	/*
	 * Limit the decoder routines to use no (much) more stack than a given
	 * number of bytes. Most of decoders are stack-based, and this
	 * would protect against stack overflows if the number of nested
	 * encodings is high.
	 * The OCTET STRING, BIT STRING and ANY BER decoders are heap-based,
	 * and are safe from this kind of overflow.
	 * A value from getrlimit(RLIMIT_STACK) may be used to initialize
	 * this variable. Be careful in multithreaded environments, as the
	 * stack size is rather limited.
	 */
	size_t  max_stack_size; /* 0 disables stack bounds checking */
} asn_codec_ctx_t;

/*
 * Type of the return value of the encoding functions (der_encode, xer_encode).
 */
typedef struct asn_enc_rval_s {
	/*
	 * Number of bytes encoded.
	 * -1 indicates failure to encode the structure.
	 * In this case, the members below this one are meaningful.
	 */
	ssize_t encoded;

	/*
	 * Members meaningful when (encoded == -1), for post mortem analysis.
	 */

	/* Type which cannot be encoded */
	struct asn_TYPE_descriptor_s *failed_type;

	/* Pointer to the structure of that type */
	void *structure_ptr;
} asn_enc_rval_t;
#define	_ASN_ENCODE_FAILED do {					\
	asn_enc_rval_t tmp_error;				\
	tmp_error.encoded = -1;					\
	tmp_error.failed_type = td;				\
	tmp_error.structure_ptr = sptr;				\
	ASN_DEBUG("Failed to encode element %s", td ? td->name : "");	\
	return tmp_error;					\
} while(0)
#define	_ASN_ENCODED_OK(rval) do {				\
	rval.structure_ptr = 0;					\
	rval.failed_type = 0;					\
	return rval;						\
} while(0)

/*
 * Type of the return value of the decoding functions (ber_decode, xer_decode)
 *
 * Please note that the number of consumed bytes is ALWAYS meaningful,
 * even if code==RC_FAIL. This is to indicate the number of successfully
 * decoded bytes, hence providing a possibility to fail with more diagnostics
 * (i.e., print the offending remainder of the buffer).
 */
enum asn_dec_rval_code_e {
	RC_OK,		/* Decoded successfully */
	RC_WMORE,	/* More data expected, call again */
	RC_FAIL		/* Failure to decode data */
};
typedef struct asn_dec_rval_s {
	enum asn_dec_rval_code_e code;	/* Result code */
	size_t consumed;		/* Number of bytes consumed */
} asn_dec_rval_t;
#define	_ASN_DECODE_FAILED do {					\
	asn_dec_rval_t tmp_error;				\
	tmp_error.code = RC_FAIL;				\
	tmp_error.consumed = 0;					\
	ASN_DEBUG("Failed to decode element %s", td ? td->name : "");	\
	return tmp_error;					\
} while(0)
#define	_ASN_DECODE_STARVED do {				\
	asn_dec_rval_t tmp_error;				\
	tmp_error.code = RC_WMORE;				\
	tmp_error.consumed = 0;					\
	return tmp_error;					\
} while(0)

#ifdef __cplusplus
}
#endif

#endif	/* _ASN_CODECS_H_ */


text:
program test_dimred

  ! This program demonstrates how to:
  !
  ! 1. Simulate ground-based SWIR measurement (spectrum)
  ! 2. Retrieve ch4 profile from the measurement using
  !    dimension reduction approach and Levenberg-Marquardt
  !    optimization
  !
  ! Simo Tukiainen, 2015

  use global_variables
  use math, only : Bvgd, Levmar
  use forward_model, only : Init_fmodel, Simulate_meas
  use retrieval
  implicit none

  type(obs) :: data
  real(DP), dimension(:), allocatable :: air, dens, alt, wn, t, q, theta, prior, profile, r
  real(DP), dimension(:,:), allocatable :: cs, p, c1, c2, c, cerr
  character(len=*), parameter :: CSFILE = "abs_coef.dat"
  character(len=*), parameter :: ATMOSFILE = "atmos.dat"
  integer :: nalt, d, nobs
  real(DP) :: noise, rss

  ! read cross sections and true/prior profiles
  call Init_fmodel(dens, prior, air, alt, cs, wn, CSFILE, ATMOSFILE)

  nalt = size(alt) ! number of altitudes
  nobs = size(wn) ! number of wavelengths

  ! simulate measurement
  write(*,*)
  write(*,*) 'Give std of noise. Signal is between 0-1 and the noise is additive ~ N(0,std^2)'
  write(*,*) 'Common value is e.g. 0.001 but you can try different values..'
  read(*,*) noise
  t = Simulate_meas(cs, dens, noise)

  ! Experimental prior covariance with two exponential components
  C1 = Bvgd(alt, 25.0_DP, 25.0_DP, 5.0_DP, 5.0_DP, 0.5_DP) * 1e7
  C2 = Bvgd(alt, 5.0_DP, 5.0_DP, 15.0_DP, 15.0_DP, 0.8_DP) * 5e6
  C = C1 + C2

  ! Its reduction
  write(*,*) ' Give number of principal components (~2-5 is good)'
  do
     read(*,*) d
     if (d < 0) then
        write(*,*) ' It can''t be negative! Try again...'
     elseif (d > nalt) then
        write(*,*) ' Too many! Try again...'
     else
        exit
     end if
  end do
  allocate(p(nalt, d), q(nalt))
  call Reduce_dim(c, d, p, q)

  ! Initial values for parameters
  allocate(theta(d))
  theta = 0.0

  ! Save needed variables to the data-structure
  data%t = t
  data%p = p
  data%d = d
  data%noise = noise
  data%cs = cs
  data%prior = prior
  data%air = air
  data%nobs = size(t)
  data%nprior = size(prior)

  ! Retrieve parameters
  allocate(r(nobs+d))
  call Levmar(resfun, jacfun, theta, cerr, r, rss, data)

  ! Inverted profile
  profile = Redu2full(P, prior, air, theta)

  ! Save results
  call Write_data(P,       'output/P.dat')
  call Write_data(profile, 'output/profile.dat')
  call Write_data(t,       'output/t.dat')
  call Write_data(dens,    'output/dens.dat')
  call Write_data(prior,   'output/prior.dat')
  call Write_data(air,     'output/air.dat')
  call Write_data(alt,     'output/alt.dat')
  call Write_data(r,       'output/r.dat')
  call Write_data(wn,      'output/wn.dat')
  call Write_data(d,       'output/d.dat')
  call Write_data(C,       'output/C.dat')
  call Write_data(q,       'output/q.dat')

end program test_dimred


text:
namespace lua {

    //////////////////////////////////////////////////////////////////////////////////////////////
    namespace stack {

        //////////////////////////////////////////////////////////////////////////////////////////////
        /// Function get single value from lua stack
        template<typename T>
        inline T readValue(::lua_State* luaState,
                           detail::DeallocQueue* deallocQueue,
                           int stackTop)
        {
            static_assert(std::is_same<traits::RemoveCVR<T>, T>::value, "T must not be CV-qualified or a reference");
            return lua::Value(std::make_shared<detail::StackItem>(luaState, deallocQueue, stackTop - 1, 1, 0)).to<T>();
        }

        /// Function creates indexes for mutli values and get them from stack
        template<typename... Ts, std::size_t... Is>
        inline std::tuple<Ts...> unpackMultiValues(::lua_State* luaState,
                                                                      detail::DeallocQueue* deallocQueue,
                                                                      int stackTop,
                                                                      traits::Indices<Is...>)
        {
            return std::make_tuple(readValue<Ts>(luaState, deallocQueue, Is + stackTop)...);
        }

        /// Function expects that number of elements in tuple and number of pushed values in stack are same. Applications takes care of this requirement by popping overlapping values before calling this function
        template<typename... Ts>
        inline std::tuple<Ts...> get_and_pop(::lua_State* luaState,
                                                                detail::DeallocQueue* deallocQueue,
                                                                int stackTop)
        {
            return unpackMultiValues<Ts...>(luaState, deallocQueue, stackTop, typename traits::MakeIndices<sizeof...(Ts)>::Type());
        }

        template<>
        inline std::tuple<> get_and_pop<>(::lua_State*,
                                          detail::DeallocQueue*,
                                          int)
        {
            return {};
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    /// Class for automaticly cas lua::Function instance to multiple return values with lua::tie
    template <typename ... Ts>
    class Return final
    {
        /// Return values
        std::tuple<Ts&...> m_tiedValues;

    public:

        /// Constructs class with given arguments
        ///
        /// @param args    Return values
        explicit Return(Ts&... args)
            : m_tiedValues(args...)
        {
        }

        /// Operator sets values to std::tuple
        ///
        /// @param function     Function being called
        void operator=(const Value& value)
        {

            int requiredValues = std::min<int>(sizeof...(Ts), value.m_stack->pushed);

            // When there are more returned values than variables in tuple, we will clear values that are not needed
            if (requiredValues < value.m_stack->grouped + 1)
            {

                int currentStackTop = lua_gettop(value.m_stack->state);

                // We will check if we haven't pushed some other new lua::Value to stack
                if (value.m_stack->top + value.m_stack->pushed == currentStackTop)
                    lua_settop(value.m_stack->state, value.m_stack->top + requiredValues);
                else
                    value.m_stack->deallocQueue->push(detail::DeallocStackItem(value.m_stack->top, value.m_stack->pushed));
            }

            // We will take pushed values and distribute them to returned lua::Values
            value.m_stack->pushed = 0;

            m_tiedValues = stack::get_and_pop<traits::RemoveCVR<Ts>...>(value.m_stack->state, value.m_stack->deallocQueue, value.m_stack->top + 1);
        }

    };

    /// Use this function when you want to retrieve multiple return values from lua::Function
    template <typename ... Ts>
    Return<Ts&...> tie(Ts&... args)
    {
        return Return<Ts&...>(args...);
    }
}