text:
import _ from "lodash/fp"
import chai from "chai"
import chaiAsPromised from "chai-as-promised"
import { aspects, aspect, aspectSync } from "../src"
import Promise from "bluebird"

chai.use(chaiAsPromised)
chai.expect()
const expect = chai.expect

describe("Aspect Functions", () => {
  // Example Aspect composition
  let Command = _.flow(
    aspects.status(),
    aspects.concurrency(),
    aspects.logs(),
    aspects.errors()
  )

  it("should combine aspect states", async () => {
    let f = Command(() => 6)
    expect(f.state.status).to.equal(null)
    expect(f.state.processing).to.be.false
    expect(f.state.failed).to.be.false
    expect(f.state.succeeded).to.be.false
    expect(f.state.logs).to.deep.equal([])
    expect(f.state.errors).to.deep.equal([])
  })
  it("should support .after calls (`logs` aspect)", async () => {
    let f = Command(() => 6)
    await f()
    expect(f.state.logs).to.deep.equal([6])
    await f()
    expect(f.state.logs).to.deep.equal([6, 6])
  })
  it("should support .onError and before (`concurrency`, `errors`, and `status` aspects)", async () => {
    let g = Command(() => {
      throw Error(5)
    })
    expect(g.state.processing).to.be.false
    await g()
    expect(g.state.errors[0].message).to.equal("5")
    expect(g.state.processing).to.be.false
    // Should be blocked as a concurrent run since it's still processing
    g.state.processing = true
    await g()
    expect(g.state.errors[1].message).to.equal("Concurrent Runs Not Allowed")
  })
  it("should support throwing in onError", async () => {
    // Use the single error object to avoid 'Unhandled promise rejection' in
    // some browsers.
    let theException = new Error("hi from aspect")
    let ThrowHi = aspect({
      onError() {
        throw theException
      },
    })
    let throwsHi = ThrowHi(() => {
      throw Error("Not hi")
    })

    expect(throwsHi()).to.be.rejectedWith(theException)
  })
  it("should support single error", async () => {
    let throwsHi = aspects.error()(() => {
      throw Error("Hi")
    })
    await throwsHi()
    expect(throwsHi.state.error.message).to.equal("Hi")
  })
  it("should support status and clearing status", async () => {
    // Increase the timeout/delay to hundreds ms to make testing IE9/10/11 more
    // stable & avoid exception:
    // AssertionError: expected null to equal 'processing'
    let clearingStatus = aspects.command(undefined, 250)
    let f = clearingStatus(async () => Promise.delay(200))
    let result = f()
    await Promise.delay(100)
    expect(f.state.status).to.equal("processing")
    expect(f.state.processing).to.be.true
    await result
    expect(f.state.status).to.equal("succeeded")
    expect(f.state.succeeded).to.be.true
    await Promise.delay(300)
    expect(f.state.status).to.equal(null)
    let g = clearingStatus(async () => {
      throw Error("error")
    })
    await g()
    expect(g.state.status).to.equal("failed")
    expect(g.state.failed).to.be.true
    await Promise.delay(15)
    expect(f.state.status).to.equal(null)
  })
    // Try to handle the case for mobile safari browers with error:
    // Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()"
    // is called; if returning a Promise, ensure it resolves.
    .timeout(10000)
  it("should support synchronous aspects", () => {
    let x = 1
    let y = 0
    let firstIncrementX = aspectSync({
      before() {
        x++
      },
    })
    let f = firstIncrementX(() => {
      y = x
    })
    f()
    expect(y).to.equal(2)
  })
  it("should mark deprecated methods on state", () => {
    let fn = aspects.deprecate("test", "1.2.3", "something else")(() => {})

    expect(fn.state.isDeprecated).to.be.true
  })
})


text:
package com.amazonaws.services.cloudtrail.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListImportFailuresRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ID of the import.
     *

     */
    private String importId;
    /**
     *

     * The maximum number of failures to display on a single page.
     *

     */
    private Integer maxResults;
    /**
     *

     * A token you can use to get the next page of import failures.
     *

     */
    private String nextToken;

    /**
     *

     * The ID of the import.
     *

     *
     * @param importId
     *        The ID of the import.
     */

    public void setImportId(String importId) {
        this.importId = importId;
    }

    /**
     *

     * The ID of the import.
     *

     *
     * @return The ID of the import.
     */

    public String getImportId() {
        return this.importId;
    }

    /**
     *

     * The ID of the import.
     *

     *
     * @param importId
     *        The ID of the import.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListImportFailuresRequest withImportId(String importId) {
        setImportId(importId);
        return this;
    }

    /**
     *

     * The maximum number of failures to display on a single page.
     *

     *
     * @param maxResults
     *        The maximum number of failures to display on a single page.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of failures to display on a single page.
     *

     *
     * @return The maximum number of failures to display on a single page.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of failures to display on a single page.
     *

     *
     * @param maxResults
     *        The maximum number of failures to display on a single page.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListImportFailuresRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * A token you can use to get the next page of import failures.
     *

     *
     * @param nextToken
     *        A token you can use to get the next page of import failures.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * A token you can use to get the next page of import failures.
     *

     *
     * @return A token you can use to get the next page of import failures.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * A token you can use to get the next page of import failures.
     *

     *
     * @param nextToken
     *        A token you can use to get the next page of import failures.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListImportFailuresRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getImportId() != null)
            sb.append("ImportId: ").append(getImportId()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListImportFailuresRequest == false)
            return false;
        ListImportFailuresRequest other = (ListImportFailuresRequest) obj;
        if (other.getImportId() == null ^ this.getImportId() == null)
            return false;
        if (other.getImportId() != null && other.getImportId().equals(this.getImportId()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getImportId() == null) ? 0 : getImportId().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListImportFailuresRequest clone() {
        return (ListImportFailuresRequest) super.clone();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package provider_test

import (
	"os"
	"testing"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"

	"github.com/stretchr/testify/assert"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)

func TestInstanceCredentialsProvider(t *testing.T) {
	//testcase 1
	//return nil, nil
	p := provider.NewInstanceCredentialsProvider()
	c, err := p.Resolve()
	assert.Nil(t, c)
	assert.Nil(t, err)

	//testcase 2
	//return nil, errors.New("Environmental variable 'ALIBABA_CLOUD_ECS_METADATA' are empty")
	os.Setenv(provider.ENVEcsMetadata, "")
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.EqualError(t, err, "Environmental variable 'ALIBABA_CLOUD_ECS_METADATA' are empty")

	//testcase 3
	//return nil, err
	os.Setenv(provider.ENVEcsMetadata, "test")
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.NotNil(t, err)

	//testcase 4
	//return nil, fmt.Errorf("The role was not found in the instance")
	tmp := provider.HookGet
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 404, []byte(""), nil
		}
	}
	defer func() {
		provider.HookGet = tmp
	}()
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.EqualError(t, err, "The role was not found in the instance")

	//testcase 5
	//return nil, fmt.Errorf("Received %d when getting security credentials for %s", status, roleName)
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 400, []byte(""), nil
		}
	}
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.EqualError(t, err, "Received 400 when getting security credentials for test")

	//testcase 6
	//json unmarshal error
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 200, []byte(`{
				AccessKSTS.*******
			  }`), nil
		}
	}
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.NotNil(t, err)

	//testcase 7, AccessKeyId does not receive
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 200, []byte(`{
				"AccessKeySecret" : "*******",
				"Expiration" : "2019-01-28T15:15:56Z",
				"SecurityToken" : "SecurityToken",
				"LastUpdated" : "2019-01-28T09:15:55Z",
				"Code" : "Success"
			  }`), nil
		}
	}
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.EqualError(t, err, "AccessKeyId not in map")

	//testcase 8,AccessKeySecret does not receive
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 200, []byte(`{
				"AccessKeyId" : "STS.*******",
				"Expiration" : "2019-01-28T15:15:56Z",
				"SecurityToken" : "SecurityToken",
				"LastUpdated" : "2019-01-28T09:15:55Z",
				"Code" : "Success"
			  }`), nil
		}
	}
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.EqualError(t, err, "AccessKeySecret not in map")

	//testcase 9, SecurityToken does not receive
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 200, []byte(`{
				"AccessKeyId" : "STS.*******",
				"AccessKeySecret" : "*******",
				"Expiration" : "2019-01-28T15:15:56Z",
				"LastUpdated" : "2019-01-28T09:15:55Z",
				"Code" : "Success"
			  }`), nil
		}
	}
	c, err = p.Resolve()
	assert.Nil(t, c)
	assert.EqualError(t, err, "SecurityToken not in map")

	//testcase, normal receive
	provider.HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
		return func(string) (int, []byte, error) {
			return 200, []byte(`{
				"AccessKeyId" : "STS.*******",
				"AccessKeySecret" : "*******",
				"Expiration" : "2019-01-28T15:15:56Z",
				"SecurityToken" : "SecurityToken",
				"LastUpdated" : "2019-01-28T09:15:55Z",
				"Code" : "Success"
			  }`), nil
		}
	}
	c, err = p.Resolve()
	assert.Nil(t, err)
	assert.Equal(t, credentials.NewStsTokenCredential("STS.*******", "*******", "SecurityToken"), c)

}


text:
ZVEMDH4 ;DJB,VEDD**Help Text - Field Global Location [08/01/94]
 ;;12;VPE;;COPYRIGHT David Bolduc @1993
 ;
VEDD2 ;;;
 ;;; E N T E R                            R  E  S  U  L  T
 ;;; ---------    ----------------------------------------------------------------
 ;;;
 ;;;    ^         Quit back to Main Menu.
 ;;;
 ;;;    ^^        Exit VEDD completely.
 ;;;
 ;;; <SPACE>      Quit back to Main Menu
 ;;;
 ;;; <ESC>H       Help text for scrolling.
 ;;;
 ;;;    I         Allows you to select a field and display its data dictionary.
 ;;;
 ;;;   'n'        Entering a field's Reference number from the REF column, is a
 ;;;              shortcut method for displaying a field's data dictionary.
 ;;;
 ;;;  <TAB>       As noted above, you enter the REF number to select a field.
 ;;;              You may also select a field by positioning the highlight
 ;;;              located on the extreme left hand side of the screen, and then
 ;;;              hitting <TAB>.
 ;;;
 ;;;    D         Data display. In addition to the data dictionary, you may
 ;;;              look at the actual data in the file. After selecting a REF
 ;;;              number or range of numbers, you select the type of display
 ;;;              you want. You have the following choices:
 ;;;                         E  = External values
 ;;;                         I  = Internal values
 ;;;                         EN = External values, null fields ignored
 ;;;                         IN = Internal values, null fields ignored
 ;;;              You will then be asked which entry you want to see. If any
 ;;;              of the fields you requested are multiples, you will also be
 ;;;              asked which multiple entry you want to see.  After viewing
 ;;;              the data, you are returned to the Global Location screen.
 ;;;
 ;;;    F         Find a field. You will be prompted for a field name. Enter a
 ;;;              name or part of a name. VEDD will locate the field and position
 ;;;              it at the top of the display. If no field is found the screen
 ;;;              will be blank because you are at the end of the file. Use the
 ;;;              Up-Arrow key to scroll up and again display fields.
 ;;;***


text:
#include <algorithm>
#include <fcntl.h>
#include <unistd.h>

#include "RFProtocolLivolo.h"
#include "RFProtocolX10.h"
#include "RFProtocolRST.h"
#include "RFProtocolRaex.h"
#include "RFProtocolOregon.h"
#include "RFProtocolOregonV3.h"
#include "RFProtocolNooLite.h"
#include "RFProtocolRubitek.h"
#include "RFProtocolMotionSensor.h"
#include "RFProtocolHS24Bit.h"
#include "RFProtocolVhome.h"
#include "RFProtocolEV1527.h"

#include "../libutils/DebugPrintf.h"
#include "../libutils/Exception.h"
#include "../libutils/logging.h"

using std::string;

CRFParser::CRFParser()
{
    m_InputTime = 0;
}

CRFParser::~CRFParser()
{
}

void CRFParser::AddProtocol(string protocol)
{
    if (protocol == "X10")
        AddProtocol(new CRFProtocolX10());
    else if (protocol == "RST")
        AddProtocol(new CRFProtocolRST());
    else if (protocol == "Raex")
        AddProtocol(new CRFProtocolRaex());
    else if (protocol == "Livolo")
        AddProtocol(new CRFProtocolLivolo());
    else if (protocol == "Oregon") {
        AddProtocol(new CRFProtocolOregon());
        AddProtocol(new CRFProtocolOregonV3());
    } else if (protocol == "nooLite")
        AddProtocol(new CRFProtocolNooLite());
    else if (protocol == "Rubitek")
        AddProtocol(new CRFProtocolRubitek());
    else if (protocol == "MotionSensor")
        AddProtocol(new CRFProtocolMotionSensor());
    else if (protocol == "VHome")
        AddProtocol(new CRFProtocolVhome());
    else if (protocol == "EV1527")
        AddProtocol(new CRFProtocolEV1527());
    else if (protocol == "All") {
        AddProtocol(new CRFProtocolNooLite());
        AddProtocol(new CRFProtocolX10());
        AddProtocol(new CRFProtocolRST());
        AddProtocol(new CRFProtocolRaex());
        AddProtocol(new CRFProtocolLivolo());
        AddProtocol(new CRFProtocolOregon());
        AddProtocol(new CRFProtocolOregonV3());
        AddProtocol(new CRFProtocolRubitek());
        AddProtocol(new CRFProtocolHS24Bit());
        //AddProtocol(new CRFProtocolVhome());
        AddProtocol(new CRFProtocolEV1527());
        //AddProtocol(new CRFProtocolMotionSensor());
    } else
        throw CHaException(CHaException::ErrBadParam, "AddProtocol - no such protocol: " + protocol);
}

void CRFParser::AddProtocol(CRFProtocol *p)
{
    m_Protocols.push_back(std::unique_ptr<CRFProtocol>(p));
    m_ProtocolsBegins.push_back(0);
}

void CRFParser::ClearRetainedInputData() {
    m_ProtocolsBegins.assign(m_ProtocolsBegins.size(), 0);
    m_InputData.clear();
    m_InputTime = 0;
    m_ParsedResults.clear();
    for (auto &protocol : m_Protocols) {
        protocol->ClearRetainedInputData();
    }
}

string CRFParser::Parse(base_type *data, size_t len)
{
    DPRINTF_DECLARE(dprintf, false);
    dprintf("$P Parse begin (len = %)\n", len);
    AddInputData(data, len);
    TryToParseExistingData();
    dprintf("$P Extracting parsed\n");
    auto ret = ExtractParsed();

    ClearRetainedInputData();

    dprintf("$P Extracted %\n", ret);
    if (ret.size() != 0) {
        std::string top = ret.front();
        dprintf("$P Just before return\n");
        return top;
    }
    return "";
}

void CRFParser::TryToParseExistingData() {
    DPRINTF_DECLARE(dprintf, false);

    if (m_InputData.size() < MIN_PACKET_LEN)
        return;

    bool lastWasPulse = CRFProtocol::isPulse(m_InputData.back());
    m_InputData.push_back((lastWasPulse ? 0 : PULSE_BIT) | PULSE_MASK);
    m_InputData.push_back((!lastWasPulse ? 0 : PULSE_BIT) | PULSE_MASK);

    bool beginWasShifted = false;

    for (int i = 0; i < (int)m_Protocols.size(); i++) {
        auto &protocol = m_Protocols[i];
        int &protocolBegin = m_ProtocolsBegins[i];

        int packetLen = m_InputData.size() - protocolBegin;

        if (packetLen < MIN_PACKET_LEN) {
            continue;
        }

        std::string parsed;

        try {
            parsed = protocol->Parse(
                    m_InputData.begin() + protocolBegin,
                    m_InputData.end(), m_InputTime);
        }
        catch (std::exception e) {
            LOG(CRIT) << "Error in parser. Protocol: " << protocol->getName()
                    << " message: " << e.what();
            continue;
        }
        catch (...) {
            LOG(CRIT) << "Error in parser. Protocol: " << protocol->getName();
            continue;
        }

        dprintf("$P Parsed = \'%\'\n", parsed);

        if (!parsed.empty()) {
            m_ParsedResults.push_back(parsed);
            protocolBegin = m_InputData.size();
        }
    }

    m_InputData.pop_back();
    m_InputData.pop_back();

    if (beginWasShifted) {
        int newBegin = *std::min_element(m_ProtocolsBegins.begin(), m_ProtocolsBegins.end());
        std::for_each(m_ProtocolsBegins.begin(), m_ProtocolsBegins.end(),
                [newBegin](int &beg) { beg -= newBegin; });
        m_InputData.erase(m_InputData.begin(), m_InputData.begin() + newBegin);
    }
}

// add some data to parse
void CRFParser::AddInputData(base_type signal)
{
    DPRINTF_DECLARE(dprintf, false);
    m_InputData.push_back(signal);
    m_InputTime += CRFProtocol::getLengh(signal);

    //dprintf("$P Start\n");

    bool beginWasShifted = false;

    for (int i = 0; i < (int)m_Protocols.size(); i++) {
        auto &protocol = m_Protocols[i];
        int &protocolBegin = m_ProtocolsBegins[i];

        int packetLen = m_InputData.size() - protocolBegin;
        //dprintf("$P protocol=%, sig=%, good=%\n", protocol->getName(), CRFProtocol::SignedRepresentation(signal), (protocol->IsGoodSignal(signal) ? "YES" : "NO"));
        if (!protocol->IsGoodSignal(signal)) {

            beginWasShifted = true;
            if (packetLen < MIN_PACKET_LEN) {
                protocolBegin = m_InputData.size();
                continue;
            }

            dprintf("$P Add input data, try decode packet (protocol = %, len = %)\n",
                    protocol->getName(), packetLen);

            std::string parsed = protocol->Parse(m_InputData.begin() + protocolBegin,
                                            m_InputData.end(), m_InputTime);
            dprintf("$P Parsed = \'%\'\n", parsed);

            if (!parsed.empty()) {
                m_ParsedResults.push_back(parsed);
            }

            protocolBegin = m_InputData.size();
        }
        else {
            if (packetLen > MAX_PACKET_LEN) {
                protocolBegin = m_InputData.size();
                beginWasShifted = true;
            }
        }
    }

    if (beginWasShifted) {
        int newBegin = *std::min_element(m_ProtocolsBegins.begin(), m_ProtocolsBegins.end());
        std::for_each(m_ProtocolsBegins.begin(), m_ProtocolsBegins.end(),
                [newBegin](int &beg) { beg -= newBegin; });
        m_InputData.erase(m_InputData.begin(), m_InputData.begin() + newBegin);
    }

    //dprintf("$P Finished\n");

}

// add some data to parse
void CRFParser::AddInputData(base_type *data, size_t len)
{
    for (base_type *i = data; i != data + len; i++)
        AddInputData(*i);
}
// get all results parsed from all data given by AddInputData
std::vector<string> CRFParser::ExtractParsed()
{
    std::vector<string> parsed;
    std::swap(parsed, m_ParsedResults);
    return parsed;
}

string CRFParser::GenerateFileName(string prefix, std::string savePath) {

#ifndef WIN32
    static int internalNumber = 0;
    time_t Time = time(NULL);
    char DateStr[100], FileName[1024];
    strftime(DateStr, sizeof(DateStr), "%d%m-%H%M%S", localtime(&Time));
    snprintf(FileName, sizeof(FileName),  "%s/%s-%s-%03d.rcf", savePath.c_str(),
             prefix.c_str(), DateStr, (++internalNumber) % 1000);
    return FileName;
#endif
}

void CRFParser::SaveFile(base_type *data, size_t size, const char *prefix, std::string savePath)
{
#ifndef WIN32
    if (savePath.length()) {
        std::string FileName = GenerateFileName(prefix, savePath);
        LOG(INFO) << "Write to file " << FileName << " " << size << " signals";
        int of = open(FileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IRGRP);

        if (of == -1) {
            LOG(INFO) << "error opening " << FileName;
            return;
        };

        int ret = write(of, data, sizeof(data[0]) * size);

        close(of);

        if (ret == -1) {
            throw CHaException(CHaException::ErrSystemAPIError, "Can't save file");
        }

    }
#endif
}


text:
package it.uniroma2.sag.kelp.kernel.tree;

import it.uniroma2.sag.kelp.data.representation.structure.similarity.StructureElementSimilarityI;
import it.uniroma2.sag.kelp.data.representation.tree.TreeRepresentation;
import it.uniroma2.sag.kelp.data.representation.tree.node.TreeNode;
import it.uniroma2.sag.kelp.data.representation.tree.node.TreeNodePairs;
import it.uniroma2.sag.kelp.kernel.DirectKernel;
//import it.uniroma2.sag.kelp.kernel.tree.deltamatrix.DeltaMatrix;
//import it.uniroma2.sag.kelp.kernel.tree.deltamatrix.StaticDeltaMatrix;
import it.uniroma2.sag.kelp.kernel.tree.deltamatrix.DeltaMatrix;
import it.uniroma2.sag.kelp.kernel.tree.deltamatrix.StaticDeltaMatrix;

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

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Partial Tree Kernel implementation.
 *
 * A Partial Tree Kernel is a convolution kernel. The kernel function is defined
 * as: </br>
 *
 * \(K(T_1,T_2) = \sum_{n_1 \in N_{T_1}} \sum_{n_2 \in N_{T_2}}
 * \Delta(n_1,n_2)\)
 *
 * </br> where \(\Delta(n_1,n_2)=\sum^{|F|}_i=1 I_i(n_1) I_i(n_2)\), that is the
 * number of common fragments rooted at the n1 and n2. It can be computed as:
 * </br> - if the involved node are leaves then
 * \(\Delta_{\sigma}(n_1,n_2)=\mu\lambda\sigma(n_1,n_2)\) </br> - else \( *
 * \Delta_{\sigma}(n_1,n_2)= \displaystyle \mu \sigma(n_1,n_2)\times \Big
 * (\lambda^2 + \hspace{-2em}
 * \sum_{\vec{I}_1,\vec{I}_2,l(\vec{I}_1)=l(\vec{I}_2)}
 * \lambda^{d(\vec{I}_1)+d(\vec{I}_2)} \prod_{j=1}^{l(\vec{I}_1)}
 * \Delta_{\sigma}(c_{n_1}({\vec{I}_{1j}}),c_{n_2}({\vec{I}_{2j})})\Big) \)
 *
 * </br> where:
 *
 * </br> - \(\sigma(n_1, n_2)\) is any similarity function between nodes \(n_1\)
 * and \(n_2\), e.g., between their lexical labels;
 *
 * </br> - \(\vec I_1\) and \(\vec I_2\) denote two sequences of indexes, i.e.,
 * \(\vec I = (i_1, i_{2},..,l(I))\), with \(1 \leq i_1 < i_2 < ..< i_{l(I)} \);
 *
 *
 * </br> - \({d(\vec{I}_1)} = \vec{I}_{1l(\vec{I}_1)} - \vec{I}_{11}+1$ and
 * $d(\vec{I}_2)= \vec{I}_{2l(\vec{I}_2)} -\vec{I}_{21}+1$;
 *
 * </br> - \(c_{n_{1}}(h)\) is the \(h^{th}\) child of the node \(n_{1}\); </br>
 * - \(\lambda, \mu \in [0,1]\) are decay factors to penalize the contribution
 * of large sized fragments.
 *
 *
 * </br></br> For more details </br> [Croce et al(2011)] Croce D., Moschitti A.,
 * Basili R. (2011) Structured lexical similarity via convolution kernels on
 * dependency trees. In: Proceedings of EMNLP, Edinburgh, Scotland, UK.
 *
 * @author Danilo Croce, Giuseppe Castellucci
 */
@JsonTypeName("sptk")
public class SmoothedPartialTreeKernel extends DirectKernel<TreeRepresentation> {
	/**
	 * Vertical Decay Factor
	 */
	private float mu = 0.4f;
	/**
	 * Horizontal Decay factor
	 */
	private float lambda = 0.4f;

	/**
	 * Horizontal Decay factor, pow 2
	 */
	@JsonIgnore
	private float lambda2;

	/**
	 * Multiplicative factor to scale up/down the leaves contribution
	 */
	private float terminalFactor = 1;

	/**
	 * All similarity score below this threshold are ignored
	 */
	private float similarityThreshold = 0.01f;

	/**
	 * The similarity function between tree nodes
	 */
	private StructureElementSimilarityI nodeSimilarity;

	/**
	 * The delta matrix, used to cache the delta functions applied to subtrees
	 */
	private DeltaMatrix deltaMatrix = StaticDeltaMatrix.getInstance();

	private int recursion_id = 0;

	private static final int NO_RESPONSE = -1;

	private static final int MAX_RECURSION = 40;
	private static final int MAX_CHILDREN = 5;

	private static final int MAX_NUMBER_OF_CHILDREN_PT = 100;

	private final float[][][] DPS_buffer = new float[MAX_RECURSION][MAX_NUMBER_OF_CHILDREN_PT][MAX_NUMBER_OF_CHILDREN_PT];
	private final float[][][] DP_buffer = new float[MAX_RECURSION][MAX_NUMBER_OF_CHILDREN_PT][MAX_NUMBER_OF_CHILDREN_PT];
	private final float[][] kernel_mat_buffer = new float[MAX_RECURSION][MAX_NUMBER_OF_CHILDREN_PT
			* MAX_NUMBER_OF_CHILDREN_PT];

	public SmoothedPartialTreeKernel() {

	}

	/**
	 * @param LAMBDA
	 *            Horizontal Decay factor
	 * @param MU
	 *            Vertical Decay Factor
	 * @param terminalFactor
	 *            Multiplicative factor to scale up/down the leaves contribution
	 * @param similarityThreshold
	 *            All similarity score below this threshold are ignored
	 * @param nodeSimilarityI
	 *            The similarity function between tree nodes
	 * @param representationIdentifier
	 *            the representation on which operate
	 */
	public SmoothedPartialTreeKernel(float LAMBDA, float MU,
			float terminalFactor, float similarityThreshold,
			StructureElementSimilarityI nodeSimilarity,
			String representationIdentifier) {
		super(representationIdentifier);
		this.lambda = LAMBDA;
		this.lambda2 = LAMBDA * LAMBDA;
		this.mu = MU;
		this.terminalFactor = terminalFactor;
		this.similarityThreshold = similarityThreshold;
		this.nodeSimilarity = nodeSimilarity;
	}

	/**
	 * Determine the subtrees (from the two trees) whose root have a similarity
	 * score above a given threshold
	 *
	 * @param a
	 *            First Tree
	 * @param b
	 *            Second Tree
	 *
	 * @return The node pairs having the similarity score above @param
	 *         similarityThreshold
	 */
	private ArrayList<TreeNodePairs> determineSubList(TreeRepresentation a,
			TreeRepresentation b) {
		ArrayList<TreeNodePairs> intersect = new ArrayList<TreeNodePairs>();
		int i = 0, j = 0;
		int n_a, n_b;
		List<TreeNode> list_a, list_b;

		list_a = a.getOrderedNodeSetByLabel();
		list_b = b.getOrderedNodeSetByLabel();
		n_a = list_a.size();
		n_b = list_b.size();

		float sim;
		for (i = 0; i < n_a; i++) {
			for (j = 0; j < n_b; j++) {
				sim = nodeSimilarity.sim(list_a.get(i).getContent(), list_b
						.get(j).getContent());

				if (sim >= similarityThreshold) {
					intersect.add(new TreeNodePairs(list_a.get(i), list_b
							.get(j)));
					deltaMatrix.add(list_a.get(i).getId(), list_b.get(j)
							.getId(), NO_RESPONSE);
				} else {
					deltaMatrix.add(list_a.get(i).getId(), list_b.get(j)
							.getId(), 0);
				}
			}
		}
		return intersect;
	}

	/**
	 * Evaluate the Smoothed Partial Tree Kernel
	 *
	 * @param a
	 *            First tree
	 * @param b
	 *            Second Tree
	 * @return Kernel value
	 */
	private float evaluateKernelNotNormalize(TreeRepresentation repA,
			TreeRepresentation repB) {

		// Initialize the delta function cache
		deltaMatrix.clear();

		ArrayList<TreeNodePairs> pairs = determineSubList(repA, repB);

		float sum = 0;

		for (int i = 0; i < pairs.size(); i++) {
			sum += sptkDeltaFunction(pairs.get(i).getNx(), pairs.get(i).getNz());
		}

		return sum;
	}

	@JsonIgnore
	public DeltaMatrix getDeltaMatrix() {
		return deltaMatrix;
	}

	/**
	 * Get the Vertical Decay factor
	 *
	 * @return Vertical Decay factor
	 */
	public float getLambda() {
		return lambda;
	}

	/**
	 * Get the Horizontal Decay factor
	 *
	 * @return Horizontal Decay factor
	 */
	public float getMu() {
		return mu;
	}

	/**
	 * @return The similarity function between tree nodes
	 */
	public StructureElementSimilarityI getNodeSimilarity() {
		return nodeSimilarity;
	}

	/**
	 * @return The similarity threshold. All similarity score below this
	 *         threshold are ignored
	 */
	public float getSimilarityThreshold() {
		return similarityThreshold;
	}

	/**
	 * @return Multiplicative factor to scale up/down the leaves contribution
	 */
	public float getTerminalFactor() {
		return terminalFactor;
	}

	@Override
	public float kernelComputation(TreeRepresentation repA,
			TreeRepresentation repB) {
		return (float) evaluateKernelNotNormalize(repA, repB);
	}

	@JsonIgnore
	public void setDeltaMatrix(DeltaMatrix deltaMatrix) {
		this.deltaMatrix = deltaMatrix;
	}

	/**
	 * @param lambda
	 *            Horizontal Decay factor
	 */
	public void setLambda(float lambda) {
		this.lambda = lambda;
		this.lambda2 = this.lambda * this.lambda;
	}

	/**
	 * @param mu
	 *            Vertical Decay Factor
	 */
	public void setMu(float mu) {
		this.mu = mu;
	}

	/**
	 * @param nodeSimilarity
	 *            The similarity function between structure elements contained in tree nodes
	 */
	public void setNodeSimilarity(StructureElementSimilarityI nodeSimilarity) {
		this.nodeSimilarity = nodeSimilarity;
	}

	/**
	 * @param similarityThreshold
	 *            All similarity score below this threshold are ignored
	 */
	public void setSimilarityThreshold(float similarityThreshold) {
		this.similarityThreshold = similarityThreshold;
	}

	/**
	 * @param terminalFactor
	 *            Multiplicative factor to scale up/down the leaves contribution
	 */
	public void setTerminalFactor(float terminalFactor) {
		this.terminalFactor = terminalFactor;
	}

	/**
	 * The Smoothed String Kernel formulation, that recursively estimates the
	 * partial overal between children sequences.
	 *
	 * @param Sx
	 *            childer of the first subtree
	 * @param Sz
	 *            childer of the second subtree
	 *
	 * @return string kernel score
	 */
	private float smoothedStringKernelDeltaFunction(ArrayList<TreeNode> Sx,
			ArrayList<TreeNode> Sz) {

		int n = Sx.size();
		int m = Sz.size();

		float[][] DPS = DPS_buffer[recursion_id];
		float[][] DP = DP_buffer[recursion_id];
		float[] kernel_mat = kernel_mat_buffer[recursion_id];
		recursion_id++;

		int i, j, l, p;
		float K;

		p = n;
		if (m < n)
			p = m;

		if (p > MAX_CHILDREN)
			p = MAX_CHILDREN;

		float temp;
		kernel_mat[0] = 0;
		for (i = 1; i <= n; i++) {
			for (j = 1; j <= m; j++) {
				temp = sptkDeltaFunction(Sx.get(i - 1), Sz.get(j - 1));
				// temp = Delta_PT(*(Sx + i - 1), *(Sz + j - 1)) * node_sim(*Sx,
				// *Sz);
				if (temp != NO_RESPONSE) {
					DPS[i][j] = temp;
					kernel_mat[0] += DPS[i][j];
				} else
					DPS[i][j] = 0;
			}
		}
		for (l = 1; l < p; l++) {
			kernel_mat[l] = 0;
			for (j = 0; j <= m; j++)
				DP[l - 1][j] = 0.0f;
			for (i = 0; i <= n; i++)
				DP[i][l - 1] = 0.0f;
			for (i = l; i <= n; i++)
				for (j = l; j <= m; j++) {
					DP[i][j] = DPS[i][j] + lambda * DP[i - 1][j] + lambda
							* DP[i][j - 1] - lambda2 * DP[i - 1][j - 1];

					temp = sptkDeltaFunction(Sx.get(i - 1), Sz.get(j - 1));
					// temp = Delta_PT(*(Sx + i - 1), *(Sz + j - 1)) *
					// node_sim(*Sx, *Sz);
					if (temp != NO_RESPONSE) {
						DPS[i][j] = temp * DP[i - 1][j - 1];
						kernel_mat[l] += DPS[i][j];
					} // else DPS[i][j] = 0;
				}
		}
		// K=kernel_mat[p-1];
		K = 0;
		for (l = 0; l < p; l++) {
			K += kernel_mat[l];
			// printf("String kernel of legnth %d: %1.7f \n\n",l+1,kernel_mat[l]);
		}
		recursion_id--;
		return K;
	}

	/**
	 * Smoothed Partial Tree Kernel Delta Function
	 *
	 * @param Nx
	 *            root of the first tree
	 * @param Nz
	 *            root of the second tree
	 * @return
	 */
	private float sptkDeltaFunction(TreeNode Nx, TreeNode Nz) {
		if (deltaMatrix.get(Nx.getId(), Nz.getId()) != NO_RESPONSE) {
			return deltaMatrix.get(Nx.getId(), Nz.getId()); // already there
		}
		float sum = 0;
		float sim = this.nodeSimilarity.sim(Nx.getContent(), Nz.getContent());

		if (sim < similarityThreshold) {
			deltaMatrix.add(Nx.getId(), Nz.getId(), 0);
			return 0;
		} else {
			if (Nx.getNoOfChildren() == 0 || Nz.getNoOfChildren() == 0) {
				float val = mu * lambda2 * terminalFactor * sim;
				deltaMatrix.add(Nx.getId(), Nz.getId(), val);
				return val;
			} else {
				sum = sim
						* mu
						* (lambda2 + smoothedStringKernelDeltaFunction(
								Nx.getChildren(), Nz.getChildren()));
				deltaMatrix.add(Nx.getId(), Nz.getId(), sum);
				return sum;
			}
		}
	}
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root'),
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();


text:
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Export('ForInSeriesBuilder')

//@Require('Class')
//@Require('ForInSeries')
//@Require('IterableFlowBuilder')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var Class                   = bugpack.require('Class');
    var ForInSeries             = bugpack.require('ForInSeries');
    var IterableFlowBuilder     = bugpack.require('IterableFlowBuilder');

    //-------------------------------------------------------------------------------
    // Declare Class
    //-------------------------------------------------------------------------------

    /**
     * @class
     * @extends {IterableFlowBuilder}
     */
    var ForInSeriesBuilder = Class.extend(IterableFlowBuilder, {

        _name: "ForInSeriesBuilder",

        //-------------------------------------------------------------------------------
        // Flow Methods
        //-------------------------------------------------------------------------------

        /**
         * @protected
         * @return {Flow}
         */
        doFactoryFlow: function() {
            return new ForInSeries(this.getData(), this.getIteratorMethod());
        }
    });

    //-------------------------------------------------------------------------------
    // Export
    //-------------------------------------------------------------------------------

    bugpack.export('ForInSeriesBuilder', ForInSeriesBuilder);
});


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/power_save_blocker_impl.h"

#include <X11/Xlib.h>
#include <stdint.h>
#include <X11/extensions/dpms.h>
#include <X11/extensions/scrnsaver.h>
// Xlib #defines Status, but we can't have that for some of our headers.
#ifdef Status
#undef Status
#endif

#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/nix/xdg_util.h"
#include "base/synchronization/lock.h"
#include "content/public/browser/browser_thread.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "ui/gfx/x/x11_types.h"

namespace {

enum DBusAPI {
  NO_API,           // Disable. No supported API available.
  GNOME_API,        // Use the GNOME API. (Supports more features.)
  FREEDESKTOP_API,  // Use the FreeDesktop API, for KDE4, KDE5, and XFCE.
};

// Inhibit flags defined in the org.gnome.SessionManager interface.
// Can be OR'd together and passed as argument to the Inhibit() method
// to specify which power management features we want to suspend.
enum GnomeAPIInhibitFlags {
  INHIBIT_LOGOUT            = 1,
  INHIBIT_SWITCH_USER       = 2,
  INHIBIT_SUSPEND_SESSION   = 4,
  INHIBIT_MARK_SESSION_IDLE = 8
};

const char kGnomeAPIServiceName[] = "org.gnome.SessionManager";
const char kGnomeAPIInterfaceName[] = "org.gnome.SessionManager";
const char kGnomeAPIObjectPath[] = "/org/gnome/SessionManager";

const char kFreeDesktopAPIPowerServiceName[] =
    "org.freedesktop.PowerManagement";
const char kFreeDesktopAPIPowerInterfaceName[] =
    "org.freedesktop.PowerManagement.Inhibit";
const char kFreeDesktopAPIPowerObjectPath[] =
    "/org/freedesktop/PowerManagement/Inhibit";

const char kFreeDesktopAPIScreenServiceName[] = "org.freedesktop.ScreenSaver";
const char kFreeDesktopAPIScreenInterfaceName[] = "org.freedesktop.ScreenSaver";
const char kFreeDesktopAPIScreenObjectPath[] = "/org/freedesktop/ScreenSaver";

}  // namespace

namespace content {

class PowerSaveBlockerImpl::Delegate
    : public base::RefCountedThreadSafe<PowerSaveBlockerImpl::Delegate> {
 public:
  // Picks an appropriate D-Bus API to use based on the desktop environment.
  Delegate(PowerSaveBlockerType type,
           const std::string& description,
           bool freedesktop_only);

  // Post a task to initialize the delegate on the UI thread, which will itself
  // then post a task to apply the power save block on the FILE thread.
  void Init();

  // Post a task to remove the power save block on the FILE thread, unless it
  // hasn't yet been applied, in which case we just prevent it from applying.
  void CleanUp();

 private:
  friend class base::RefCountedThreadSafe<Delegate>;
  ~Delegate() {}

  // Selects an appropriate D-Bus API to use for this object. Must be called on
  // the UI thread. Checks enqueue_apply_ once an API has been selected, and
  // enqueues a call back to ApplyBlock() if it is true. See the comments for
  // enqueue_apply_ below.
  void InitOnUIThread();

  // Returns true if ApplyBlock() / RemoveBlock() should be called.
  bool ShouldBlock() const;

  // Apply or remove the power save block, respectively. These methods should be
  // called once each, on the same thread, per instance. They block waiting for
  // the action to complete (with a timeout); the thread must thus allow I/O.
  void ApplyBlock();
  void RemoveBlock();

  // Asynchronous callback functions for ApplyBlock and RemoveBlock.
  // Functions do not receive ownership of |response|.
  void ApplyBlockFinished(dbus::Response* response);
  void RemoveBlockFinished(dbus::Response* response);

  // Wrapper for XScreenSaverSuspend. Checks whether the X11 Screen Saver
  // Extension is available first. If it isn't, this is a no-op.
  // Must be called on the UI thread.
  static void XSSSuspendSet(bool suspend);

  // If DPMS (the power saving system in X11) is not enabled, then we don't want
  // to try to disable power saving, since on some desktop environments that may
  // enable DPMS with very poor default settings (e.g. turning off the display
  // after only 1 second). Must be called on the UI thread.
  static bool DPMSEnabled();

  // If no other method is available (i.e. not running under a Desktop
  // Environment) check whether the X11 Screen Saver Extension can be used
  // to disable the screen saver. Must be called on the UI thread.
  static bool XSSAvailable();

  // Returns an appropriate D-Bus API to use based on the desktop environment.
  // Must be called on the UI thread, as it may call DPMSEnabled() above.
  static DBusAPI SelectAPI();

  const PowerSaveBlockerType type_;
  const std::string description_;
  const bool freedesktop_only_;

  // Initially, we post a message to the UI thread to select an API. When it
  // finishes, it will post a message to the FILE thread to perform the actual
  // application of the block, unless enqueue_apply_ is false. We set it to
  // false when we post that message, or when RemoveBlock() is called before
  // ApplyBlock() has run. Both api_ and enqueue_apply_ are guarded by lock_.
  DBusAPI api_;
  bool enqueue_apply_;
  base::Lock lock_;

  // Indicates that a D-Bus power save blocking request is in flight.
  bool block_inflight_;
  // Used to detect erronous redundant calls to RemoveBlock().
  bool unblock_inflight_;
  // Indicates that RemoveBlock() is called before ApplyBlock() has finished.
  // If it's true, then the RemoveBlock() call will be processed immediately
  // after ApplyBlock() has finished.
  bool enqueue_unblock_;

  scoped_refptr<dbus::Bus> bus_;

  // The cookie that identifies our inhibit request,
  // or 0 if there is no active inhibit request.
  uint32_t inhibit_cookie_;

  DISALLOW_COPY_AND_ASSIGN(Delegate);
};

PowerSaveBlockerImpl::Delegate::Delegate(PowerSaveBlockerType type,
                                         const std::string& description,
                                         bool freedesktop_only)
    : type_(type),
      description_(description),
      freedesktop_only_(freedesktop_only),
      api_(NO_API),
      enqueue_apply_(false),
      inhibit_cookie_(0) {
  // We're on the client's thread here, so we don't allocate the dbus::Bus
  // object yet. We'll do it later in ApplyBlock(), on the FILE thread.
}

void PowerSaveBlockerImpl::Delegate::Init() {
  base::AutoLock lock(lock_);
  DCHECK(!enqueue_apply_);
  enqueue_apply_ = true;
  block_inflight_ = false;
  unblock_inflight_ = false;
  enqueue_unblock_ = false;
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                          base::Bind(&Delegate::InitOnUIThread, this));
}

void PowerSaveBlockerImpl::Delegate::CleanUp() {
  base::AutoLock lock(lock_);
  if (enqueue_apply_) {
    // If a call to ApplyBlock() has not yet been enqueued because we are still
    // initializing on the UI thread, then just cancel it. We don't need to
    // remove the block because we haven't even applied it yet.
    enqueue_apply_ = false;
  } else {
    if (ShouldBlock()) {
      BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                              base::Bind(&Delegate::RemoveBlock, this));
    }

    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                            base::Bind(&Delegate::XSSSuspendSet, false));
  }
}

void PowerSaveBlockerImpl::Delegate::InitOnUIThread() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  base::AutoLock lock(lock_);
  api_ = SelectAPI();

  if (enqueue_apply_) {
    if (ShouldBlock()) {
      // The thread we use here becomes the origin and D-Bus thread for the
      // D-Bus library, so we need to use the same thread above for
      // RemoveBlock(). It must be a thread that allows I/O operations, so we
      // use the FILE thread.
      BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                              base::Bind(&Delegate::ApplyBlock, this));
    }
    XSSSuspendSet(true);
  }
  enqueue_apply_ = false;
}

bool PowerSaveBlockerImpl::Delegate::ShouldBlock() const {
  return freedesktop_only_ ? api_ == FREEDESKTOP_API : api_ != NO_API;
}

void PowerSaveBlockerImpl::Delegate::ApplyBlock() {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);
  DCHECK(!bus_);  // ApplyBlock() should only be called once.
  DCHECK(!block_inflight_);

  dbus::Bus::Options options;
  options.bus_type = dbus::Bus::SESSION;
  options.connection_type = dbus::Bus::PRIVATE;
  bus_ = new dbus::Bus(options);

  scoped_refptr<dbus::ObjectProxy> object_proxy;
  scoped_ptr<dbus::MethodCall> method_call;
  scoped_ptr<dbus::MessageWriter> message_writer;

  switch (api_) {
    case NO_API:
      NOTREACHED();  // We should never call this method with this value.
      return;
    case GNOME_API:
      object_proxy = bus_->GetObjectProxy(
          kGnomeAPIServiceName,
          dbus::ObjectPath(kGnomeAPIObjectPath));
      method_call.reset(
          new dbus::MethodCall(kGnomeAPIInterfaceName, "Inhibit"));
      message_writer.reset(new dbus::MessageWriter(method_call.get()));
      // The arguments of the method are:
      //     app_id:        The application identifier
      //     toplevel_xid:  The toplevel X window identifier
      //     reason:        The reason for the inhibit
      //     flags:         Flags that spefify what should be inhibited
      message_writer->AppendString(
          base::CommandLine::ForCurrentProcess()->GetProgram().value());
      message_writer->AppendUint32(0);  // should be toplevel_xid
      message_writer->AppendString(description_);
      {
        uint32_t flags = 0;
        switch (type_) {
          case kPowerSaveBlockPreventDisplaySleep:
            flags |= INHIBIT_MARK_SESSION_IDLE;
            flags |= INHIBIT_SUSPEND_SESSION;
            break;
          case kPowerSaveBlockPreventAppSuspension:
            flags |= INHIBIT_SUSPEND_SESSION;
            break;
        }
        message_writer->AppendUint32(flags);
      }
      break;
    case FREEDESKTOP_API:
      switch (type_) {
        case kPowerSaveBlockPreventDisplaySleep:
          object_proxy = bus_->GetObjectProxy(
              kFreeDesktopAPIScreenServiceName,
              dbus::ObjectPath(kFreeDesktopAPIScreenObjectPath));
          method_call.reset(new dbus::MethodCall(
              kFreeDesktopAPIScreenInterfaceName, "Inhibit"));
          break;
        case kPowerSaveBlockPreventAppSuspension:
          object_proxy = bus_->GetObjectProxy(
              kFreeDesktopAPIPowerServiceName,
              dbus::ObjectPath(kFreeDesktopAPIPowerObjectPath));
          method_call.reset(new dbus::MethodCall(
              kFreeDesktopAPIPowerInterfaceName, "Inhibit"));
          break;
      }
      message_writer.reset(new dbus::MessageWriter(method_call.get()));
      // The arguments of the method are:
      //     app_id:        The application identifier
      //     reason:        The reason for the inhibit
      message_writer->AppendString(
          base::CommandLine::ForCurrentProcess()->GetProgram().value());
      message_writer->AppendString(description_);
      break;
  }

  block_inflight_ = true;
  object_proxy->CallMethod(
      method_call.get(), dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&PowerSaveBlockerImpl::Delegate::ApplyBlockFinished, this));
}

void PowerSaveBlockerImpl::Delegate::ApplyBlockFinished(
    dbus::Response* response) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);
  DCHECK(bus_);
  DCHECK(block_inflight_);
  block_inflight_ = false;

  if (response) {
    // The method returns an inhibit_cookie, used to uniquely identify
    // this request. It should be used as an argument to Uninhibit()
    // in order to remove the request.
    dbus::MessageReader message_reader(response);
    if (!message_reader.PopUint32(&inhibit_cookie_))
      LOG(ERROR) << "Invalid Inhibit() response: " << response->ToString();
  } else {
    LOG(ERROR) << "No response to Inhibit() request!";
  }

  if (enqueue_unblock_) {
    enqueue_unblock_ = false;
    // RemoveBlock() was called while the Inhibit operation was in flight,
    // so go ahead and remove the block now.
    BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                            base::Bind(&Delegate::RemoveBlock, this));
  }
}

void PowerSaveBlockerImpl::Delegate::RemoveBlock() {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);
  DCHECK(bus_);  // RemoveBlock() should only be called once.
  DCHECK(!unblock_inflight_);

  if (block_inflight_) {
    DCHECK(!enqueue_unblock_);
    // Can't call RemoveBlock until ApplyBlock's async operation has
    // finished. Enqueue it for execution once ApplyBlock is done.
    enqueue_unblock_ = true;
    return;
  }

  scoped_refptr<dbus::ObjectProxy> object_proxy;
  scoped_ptr<dbus::MethodCall> method_call;

  switch (api_) {
    case NO_API:
      NOTREACHED();  // We should never call this method with this value.
      return;
    case GNOME_API:
      object_proxy = bus_->GetObjectProxy(
          kGnomeAPIServiceName,
          dbus::ObjectPath(kGnomeAPIObjectPath));
      method_call.reset(
          new dbus::MethodCall(kGnomeAPIInterfaceName, "Uninhibit"));
      break;
    case FREEDESKTOP_API:
      switch (type_) {
        case kPowerSaveBlockPreventDisplaySleep:
          object_proxy = bus_->GetObjectProxy(
              kFreeDesktopAPIScreenServiceName,
              dbus::ObjectPath(kFreeDesktopAPIScreenObjectPath));
          method_call.reset(new dbus::MethodCall(
              kFreeDesktopAPIScreenInterfaceName, "UnInhibit"));
          break;
        case kPowerSaveBlockPreventAppSuspension:
          object_proxy = bus_->GetObjectProxy(
              kFreeDesktopAPIPowerServiceName,
              dbus::ObjectPath(kFreeDesktopAPIPowerObjectPath));
          method_call.reset(new dbus::MethodCall(
              kFreeDesktopAPIPowerInterfaceName, "UnInhibit"));
          break;
      }
      break;
  }

  dbus::MessageWriter message_writer(method_call.get());
  message_writer.AppendUint32(inhibit_cookie_);
  unblock_inflight_ = true;
  object_proxy->CallMethod(
      method_call.get(), dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&PowerSaveBlockerImpl::Delegate::RemoveBlockFinished, this));
}

void PowerSaveBlockerImpl::Delegate::RemoveBlockFinished(
    dbus::Response* response) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);
  DCHECK(bus_);
  unblock_inflight_ = false;

  if (!response)
    LOG(ERROR) << "No response to Uninhibit() request!";
  // We don't care about checking the result. We assume it works; we can't
  // really do anything about it anyway if it fails.
  inhibit_cookie_ = 0;

  bus_->ShutdownAndBlock();
  bus_ = nullptr;
}

// static
void PowerSaveBlockerImpl::Delegate::XSSSuspendSet(bool suspend) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!XSSAvailable())
    return;

  XDisplay* display = gfx::GetXDisplay();
  XScreenSaverSuspend(display, suspend);
}

// static
bool PowerSaveBlockerImpl::Delegate::DPMSEnabled() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  XDisplay* display = gfx::GetXDisplay();
  BOOL enabled = false;
  int dummy;
  if (DPMSQueryExtension(display, &dummy, &dummy) && DPMSCapable(display)) {
    CARD16 state;
    DPMSInfo(display, &state, &enabled);
  }
  return enabled;
}

// static
bool PowerSaveBlockerImpl::Delegate::XSSAvailable() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  XDisplay* display = gfx::GetXDisplay();
  int dummy;
  int major;
  int minor;

  if (!XScreenSaverQueryExtension(display, &dummy, &dummy))
    return false;

  if (!XScreenSaverQueryVersion(display, &major, &minor))
    return false;

  return major > 1 || (major == 1 && minor >= 1);
}

// static
DBusAPI PowerSaveBlockerImpl::Delegate::SelectAPI() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  scoped_ptr<base::Environment> env(base::Environment::Create());
  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_GNOME:
    case base::nix::DESKTOP_ENVIRONMENT_UNITY:
      if (DPMSEnabled())
        return GNOME_API;
      break;
    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
    case base::nix::DESKTOP_ENVIRONMENT_KDE5:
      if (DPMSEnabled())
        return FREEDESKTOP_API;
      break;
    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      // Not supported.
      break;
  }
  return NO_API;
}

PowerSaveBlockerImpl::PowerSaveBlockerImpl(PowerSaveBlockerType type,
                                           Reason reason,
                                           const std::string& description)
    : delegate_(new Delegate(type, description, false /* freedesktop_only */)) {
  delegate_->Init();

  if (type == kPowerSaveBlockPreventDisplaySleep) {
    freedesktop_suspend_delegate_ =
        new Delegate(kPowerSaveBlockPreventAppSuspension, description,
                     true /* freedesktop_only */);
    freedesktop_suspend_delegate_->Init();
  }
}

PowerSaveBlockerImpl::~PowerSaveBlockerImpl() {
  delegate_->CleanUp();
  if (freedesktop_suspend_delegate_)
    freedesktop_suspend_delegate_->CleanUp();
}

}  // namespace content


text:
import time

from cavstudio_db.models import SearchSet, Snapshot
from cavstudio_db.serializers import SearchSetSerializer, SnapshotSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.shortcuts import get_object_or_404

@api_view()
def get_all_snapshots_for_project_including_snapshot(request):
    snapshot_id = request.query_params['snapshotId']
    snapshot = get_object_or_404(Snapshot, id=snapshot_id)

    projectId = snapshot.data['projectId']
    snapshots = Snapshot.objects.raw('''
        SELECT cavstudio_db_snapshot.*
        FROM cavstudio_db_snapshot,
             json_each(cavstudio_db_snapshot.data, "$.projectId") AS project_id
        WHERE project_id.value=%s
    ''', [projectId])

    snapshots = sorted(snapshots, key=lambda s: s.data.get('date'), reverse=True)

    snapshots_json = SnapshotSerializer(snapshots, many=True).data
    return Response({'results': snapshots_json})

@api_view()
def get_user_projects_summary(request):
    snapshots = list(Snapshot.objects.all())

    # filter out the featured concepts
    snapshots = [s for s in snapshots if not s.data.get('featured')]

    snapshots.sort(key=lambda s: s.data['date'], reverse=True)

    project_ids = set(s.data['projectId'] for s in snapshots)
    projects_json = []

    for project_id in project_ids:
        # latestSnapshot = snapshots.filter(s => s.projectId === projectId)[0]
        latest_snapshot = next(s for s in snapshots if s.data['projectId'] == project_id)

        if latest_snapshot.data.get('deleted'):
            continue

        try:
            images = latest_snapshot.data['positiveSet']['images'] or []
        except KeyError:
            images = []

        top_images = sorted(images, key=lambda i: i['weight'], reverse=True)[:3]

        projects_json.append({
            'id': project_id,
            'latestSnapshot': {
                'id': latest_snapshot.id,
                'date': latest_snapshot.data['date'],
                'name': latest_snapshot.data['name'],
                'creatorName': latest_snapshot.data['creatorName'],
                'publishInfo': latest_snapshot.data['publishInfo'],
                'topImages': top_images,
            }
        })

    return Response({'results': projects_json})

@api_view()
def get_snapshot(request):
    snapshot_id = request.data['snapshotId']

    snapshot = get_object_or_404(Snapshot, id=snapshot_id)

    snapshot_json = SnapshotSerializer(snapshot).data

    return Response({'result': snapshot_json})

@api_view(['POST'])
def set_snapshot(request):
    snapshot_id = request.data['snapshotId']
    snapshot = request.data['snapshot']

    Snapshot.objects.update_or_create(id=snapshot_id, defaults={'data': snapshot})

    return Response()

@api_view(['POST'])
def delete_snapshot(request):
    snapshot_id = request.data['snapshotId']

    snapshot = get_object_or_404(Snapshot, id=snapshot_id)

    snapshot.data['deleted'] = True
    snapshot.data['deletedDate'] = time.time()

    snapshot.save()

    return Response()

@api_view()
def get_search_sets(request):
    search_sets = [s for s in SearchSet.objects.all() if not s.data.get('deleted')]

    search_sets_json = SearchSetSerializer(search_sets, many=True).data

    return Response({'results': search_sets_json})

@api_view()
def get_search_set(request):
    search_set_id = request.query_params['searchSetId']

    search_set = get_object_or_404(SearchSet, id=search_set_id)

    search_set_json = SearchSetSerializer(search_set).data

    return Response({'result': search_set_json})

@api_view(['POST'])
def set_search_set(request):
    search_set_id = request.data['searchSetId']
    search_set_data = request.data['searchSet']

    SearchSet.objects.update_or_create(id=search_set_id, defaults={'data': search_set_data})

    return Response()

@api_view(['POST'])
def delete_search_set(request):
    search_set_id = request.data['searchSetId']

    search_set = get_object_or_404(SearchSet, id=search_set_id)

    search_set.data['deleted'] = True
    search_set.data['deletedDate'] = time.time()

    search_set.save()

    return Response()

@api_view(['POST'])
def copy_snapshot_to_new_project(request):
    src_snapshot_id = request.data['srcSnapshotId']
    dst_snapshot_id = request.data['dstSnapshotId']
    dst_project_id = request.data['dstProjectId']
    dst_name = request.data['dstName']

    snapshot = get_object_or_404(Snapshot, id=src_snapshot_id)

    # changing the id makes this ORM object reference a new row in the
    # database
    snapshot.id = dst_snapshot_id
    snapshot.data['snapshotId'] = dst_snapshot_id
    snapshot.data['projectId'] = dst_project_id
    snapshot.data['name'] = dst_name

    snapshot.save()

    return Response()


text:
import Widget from 'static/js/widget.js';
import table from 'widget/module/table/table.js';
import dateControl from 'widget/classComponent/datecontrol/datecontrol.js';
import cityselect from 'widget/component/cityselect/cityselect.js';
import dialog from 'widget/classComponent/dialog/dialog.js';
import editor from 'widget/component/editor/editor.js';

var style = __inline('./form.inline.less');
var tpl = __inline('./form.tmpl');

require.loadCss({
    name: 'usersys-widget-form-style',
    content: style
});

var form = Widget.extend({

    init : function (data = {}) {

        this.localData = {};
    	let res  = this.processData(data);
        this.eles = this.display(res, tpl, 'native');
        this.render();
        this.bind();
    },
    processData :function (data = {}){
    	this.data = data;
        return this.data;
    },
    render :function(){

        if($('.city-select').length !== 0){
            new Vue({
                el: $('.city-select', this._containerDom_).get(0)
            });
        }
        if($('.date-control').length !== 0){

            new Vue({
                el: $('.date-control', this._containerDom_).get(0)
            });
        }
        if($('.text-edit').length !== 0) {
            new Vue({
                el: $('.text-edit', this._containerDom_).get(0)
            });
        }

        if($('.time').length !== 0){
            var container = $(this);
        }

        if(this.data.tabs.length !== 0){
            var navType = this.data.type;
            var arr = $('.nav-tabs > li').toArray();
            arr.forEach(function(li){
                if($(li).attr('data-key') === navType ){
                     $(li).addClass('active');
                 }else{
                    $(li).hasClass('active') && $(c).removeClass('active');
                 }
            });
        }
    },
    bind : function(){

        var me = this;

        $('.dep .choose-button').click(function(){
            var setting = {
                type : 'dep',
                close : false ,
                css :[  {width : 600}, {height : 349} ],
                title : '选择部门',
                buttons : [
                    {'name' : '选择' , 'activeClass' : 'btn-primary' },
                    {'name' : '取消' , 'activeClass' : 'btn-default' },
                ],
                onConfirm: () => {

                    let list = window.deparTreeInstance.getCheckedNodes(true);
                    let keys = [];
                    let values = [];
                    list.forEach((item) => {
                        if (!item.isParent) {
                            keys.push(item.id);
                            values.push(item.name);
                        }
                    });

                    let inputEle = $(this).prev();
                    inputEle.val(values.join(','));
                    inputEle.attr('data-values', values.join(','));
                }
            }
            dialog.show(setting);
        });

        $('.panel-body').on('click', '[data-role=submit]', function () {
            var inputCollections = $('.panel-body').find('[data-key]');
            var data = {};
            for (var i = 0, len = inputCollections.length; i < len; i++) {
                var ele = $(inputCollections[i]);
                var key = ele.attr('data-key');
                var val = ele.attr('data-values') || ele.val();
                if (key) {
                    data[key] = val;
                }
            }
            if($('.city-select').length !== 0){
                console.log(cityselect.options.data());
            }

            //console.log(data);
            var url = me.data.url ;
            //data = $.extend({param: data},{url : url});
           // me.updateTable(data);
        });

        $('.panel-body').on('click', '[data-role=clearInput]', function () {
            var inputCollections = $('.panel-body').find('[data-key]');
            for (var i = 0, len = inputCollections.length; i < len; i++) {
                var ele = $(inputCollections[i]);
                var key = ele.val('');
            }
        });
    },
    updateTable : function(data){
        listener.trigger('page', 'tableUpdate', data);
    }
})

export default form;


text:
"""
Use this module to get and run all tk tests.

Tkinter tests should live in a package inside the directory where this file
lives, like test_tkinter.
Extensions also should live in packages following the same rule as above.
"""

import os
import sys
import unittest
import importlib
import test.test_support

this_dir_path = os.path.abspath(os.path.dirname(__file__))

def is_package(path):
    for name in os.listdir(path):
        if name in ('__init__.py', '__init__.pyc', '__init.pyo'):
            return True
    return False

def get_tests_modules(basepath=this_dir_path, gui=True, packages=None):
    """This will import and yield modules whose names start with test_
    and are inside packages found in the path starting at basepath.

    If packages is specified it should contain package names that want
    their tests collected.
    """
    py_ext = '.py'

    for dirpath, dirnames, filenames in os.walk(basepath):
        for dirname in list(dirnames):
            if dirname[0] == '.':
                dirnames.remove(dirname)

        if is_package(dirpath) and filenames:
            pkg_name = dirpath[len(basepath) + len(os.sep):].replace('/', '.')
            if packages and pkg_name not in packages:
                continue

            filenames = filter(
                    lambda x: x.startswith('test_') and x.endswith(py_ext),
                    filenames)

            for name in filenames:
                try:
                    yield importlib.import_module(
                            ".%s" % name[:-len(py_ext)], pkg_name)
                except test.test_support.ResourceDenied:
                    if gui:
                        raise

def get_tests(text=True, gui=True, packages=None):
    """Yield all the tests in the modules found by get_tests_modules.

    If nogui is True, only tests that do not require a GUI will be
    returned."""
    attrs = []
    if text:
        attrs.append('tests_nogui')
    if gui:
        attrs.append('tests_gui')
    for module in get_tests_modules(gui=gui, packages=packages):
        for attr in attrs:
            for test in getattr(module, attr, ()):
                yield test

if __name__ == "__main__":
    test.test_support.run_unittest(*get_tests())


text:
/*******************************************************************************
 * \file barometer_sim.hpp
 *
 * \author MAV'RIC Team
 * \author Julien Lecoeur
 *
 * \brief Simulation for barometers
 *
 ******************************************************************************/

#ifndef BAROMETER_SIM_HPP_
#define BAROMETER_SIM_HPP_

#include "drivers/barometer.hpp"
#include "simulation/dynamic_model.hpp"

/**
 * \brief   Simulation for barometers
 */
class Barometer_sim: public Barometer
{
public:
    /**
     * \brief   Constructor
     *
     * \param   dynamic_model   Reference to dynamic model
     */
    Barometer_sim(Dynamic_model& dynamic_model);

    /**
     * \brief   Initialise the sensor
     *
     * \return  Success
     */
    bool init(void);

    /**
     * \brief   Main update function
     * \detail  Reads new values from sensor
     *
     * \return  Success
     */
    bool update(void);

    /**
    * \brief   Get the last update time in microseconds
    *
    * \return   Value
    */
    uint64_t last_update_us(void) const;

    /**
     * \brief   Return the pressure (in Pa)
     *
     * \return  Value
     */
    float pressure(void)  const;

    /**
     * \brief   Get the altitude in meters above sea level
     *
     * \detail  Global frame: (>0 means upward)
     *
     * \return  Value
     */
    float altitude_gf(void) const;

    /**
     * \brief   Get the altitude in meters above sea level (not filtered)
     *
     * \detail  Global frame: (>0 means upward)
     *
     * \return  Value
     */
    float altitude_gf_raw(void) const;

    /**
     * \brief   Get the vertical speed in meters/second
     *
     * \detail  NED frame: (>0 means downward)
     *
     * \return  Value
     */
    float vertical_speed_lf(void) const;

    /**
     * \brief   Get the vertical speed in meters/second (not filtered)
     *
     * \detail  NED frame: (>0 means downward)
     *
     * \return  Value
     */
    float vertical_speed_lf_raw(void) const;

    /**
     * \brief   Get sensor temperature
     *
     * \return  Value
     */
    float temperature(void) const;

private:
    Dynamic_model&  dynamic_model_; ///< Reference to dynamic model

    uint64_t last_update_us_;   ///< Last update time
    float pressure_;            ///< Measured pressure
    float temperature_;         ///< Measured temperature
    float altitude_gf_;         ///< Measured altitude (global frame)
    float altitude_filtered;    ///< Measured altitude without bias removal
    float speed_lf_;            ///< Vario altitude speed (ned frame)
};

#endif /* BAROMETER_SIM_HPP_ */


text:
using System.Web.Mvc;

namespace SitemapifySample.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}


text:
[![Build Status](https://travis-ci.org/jkr2255/prop_logic.svg?branch=master)](https://travis-ci.org/jkr2255/prop_logic)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/jkr2255/prop_logic/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/jkr2255/prop_logic/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/jkr2255/prop_logic/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/jkr2255/prop_logic/?branch=master)
[![Gem Version](https://badge.fury.io/rb/prop_logic.svg)](https://badge.fury.io/rb/prop_logic)

PropLogic implements propositional logic in Ruby, usable like normal variables.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'prop_logic'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install prop_logic

### Requirements
Using with CRuby, Version >= 2.0.0 is required. Doesn't work stably on 1.9.x due to unreliable behaviors on weak reference.

In JRuby and Rubinus it should work.

## Usage
### Overview
First, variables can be declared using `PropLogic.new_variable`. Next, it can be calculated using normal Ruby operators
such as `&`, `|`, `~`, and some methods. Finally, you can test satisfiability of these expressions.

```ruby
# declartion
a = PropLogic.new_variable 'a'
b = PropLogic.new_variable 'b'
c = PropLogic.new_variable 'c'

# calculation
expr1 = (a & b) | c
expr2 = ~(a.then(b))
expr3 = expr1 | expr2

# conversion
nnf = expr3.to_nnf
cnf = expr3.to_cnf
sat = expr3.sat?

# comparement
diff = (~a | ~b).equiv?(~(a & b)) # true

# assignment
(a & b).assign_true(a).assign_false(b).reduce # PropLogic::False
```

### Using normal Hash for caching
By default, `prop_logic` uses weak reference for caching terms, allowing garbage collection.

If this is inappropriate (overhead or unstability), use `require 'prop_logic/hash_cache'` to use `Hash` for caching.

## Restriction
SAT solver bundled with this gem is brute-force solver (intended only for testing), so it is inappropriate to use for
real-scale problems.

In CRuby and Rubinius, bindings to MiniSat ([jkr2255/prop_logic-minisat](https://github.com/jkr2255/prop_logic-minisat)) is available.
It is a plugin for this gem, so no code (except require and Gemfile) needs to be changed to use `prop_logic-minisat`.

In JRuby binding to Sat4j ([jkr2255/prop_logic-sat4j](https://github.com/jkr2255/prop_logic-sat4j)) is available.

## References
`PropLogic::Term` is immutable, meaning that all calculations return new Terms.
### `PropLogic::Term` instance methods
#### `#and(*others)`, `#&(*others)`
calculate `self & others[0] & others[1] & ...`.
#### `#or(*others)`, `#|(*others)`
calculate `self | others[0] | others[1] & ...`.

#### Warning for reducing with `&` / `|`
Because of immutability and internal system of and/or terms, `many_terms.reduce(&:and)` is exteremely slow.
Use `PropLogic.all_and`/`PropLogic.all_or` or `one_term.and(*others)` to avoid this pitfall.

#### `#not()`,`#~()`, `#-@()`
calculate `Not(self)`. `#!` is not present because it confuses Ruby behavior. (if present, `!term` is always *truthy*)

#### `#then(other), #>>(other)`
caslculate `If self then other`.

#### NNF
NNF doesn't contain following terms:
- If-then
- Negation of And/Or
- Double negation

`#nnf?` checks if the term is NNF, and `#to_nnf` returns term converted to NNF.

#### Reduction
Term is regarded as reduced if:
0. it is NNF
0. it contains no constants (`PropLogic::True`/`PropLogic::False`)
0. it contains no ambivalent terms
0. it contains no duplicated terms

`#reduced?` checks if the term is reduced, and `#reduce` returns reduced term.

#### Reduction
CNF is one of these:
1. Variable and its negation
2. Logical sum of multiple 1
3. Logical product of multiple (1 or 2)

`#cnf?` checks if the term is CNF, and `#to_cnf` returns terms converted to CNF (may use extra variables).

#### SAT judgement
`#sat?` returns:
- boolean `false` if unsatisfiable
- `nil` if satisfiability is undetermined
- One term satisfying original term if satisfiable

`#unsat?` returns `true` if unsatisfiable, `false` otherwise.

#### SAT enumrator
`#each_sat` is an enumerator for all satifiabilities. Returns `Enumerator` if calling without block.

### `PropLogic` module methods
#### `PropLogic.new_variable(name = nil)`
declare new variable with name `name`. if `name` is not supplied, unique name is set.

Notice that even if the same `name` as before specified, it returns *different* variable.

#### `PropLogic.all_and(*terms)`/`PropLogic.all_or(*terms)`
calculate all and/or of `terms`. Use this when and/or calculation for many variables.

#### `PropLogic.sat_solver`/ PropLogic.sat_solver=`
set/get SAT solver object. It shoud have `#call(term)` method and return value is described in `Term#sat?`.

#### `PropLogic.incremental_solver`/ PropLogic.incremental_solver=`
set/get incremental SAT solver object. It shoud be class with `#add` and `#sat?` methods.
(see `DefaultIncrementalSolver` for its interface)

### Information
`PropLogic::Term` has some subclasses, but these classes are subject to change.
Using subclasses of `PropLogic::Term` directly is not recommended.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/prop_logic/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## ToDo

- Introduce special blocks to build terms inside


text:
exports.Resource = require("./Resource.js");
exports.Push = require("./Push.js");
exports.Analytics = require("./Analytics.js");


text:
/*
 * Truncate a string (first argument) if it is longer than the given maximum string length (second argument).
 * Return the truncated string with a ... ending.
 * Note that inserting the three dots to the end will add to the string length.
 * However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.
 */

function truncateString(str, num) {
  if(str.length > num && num > 3)
    return str.substring(0, num - 3) + "...";
  if(str.length > num && num <= 3)
    return str.substring(0, num) + "...";
  // Clear out that junk in your trunk
  return str;
}

//test method
truncateString("A-tisket a-tasket A green and yellow basket", 11);


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

<title>Uses of Class com.example.baard.Habits.HabitStatistics.HabitCompletionVsTimeData</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.example.baard.Habits.HabitStatistics.HabitCompletionVsTimeData

Packages that use HabitStatistics.HabitCompletionVsTimeData

Package
Description

com.example.baard.Habits

Uses of HabitStatistics.HabitCompletionVsTimeData in com.example.baard.Habits

Methods in com.example.baard.Habits that return types with arguments of type HabitStatistics.HabitCompletionVsTimeData

Modifier and Type
Method and Description

java.util.ArrayList<HabitStatistics.HabitCompletionVsTimeData>
HabitStatistics.getHabitCompletionVsTimeData(Habit habit,
                            java.util.Date startDate,
                            java.util.Date endDate)

Calculate the habit completion over time based on the start and end dates, events and frequency

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
tinyMCE.addI18n('no.locomedia_dlg',{
  dialog_title: 'Sett inn media',
  upload: 'Last opp media',
  loading: 'Laster inn...',
  uploading: 'Laster opp...',
  destroying: 'Sletter...',
  confirm: 'Er du sikker?',
  no_items: 'Ingen media foreløpig.'
});


text:
id: a202eed8fc186c8434cb6d61
title: Reverse a String
isRequired: true
challengeType: 5
videoUrl: ''
localeTitle: Reverter uma string
---

## Description

 Inverta a string fornecida. Você pode precisar transformar a string em uma matriz antes de poder revertê-la. Seu resultado deve ser uma string. Lembre-se de usar Read-Search-Ask se você ficar preso. Escreva seu próprio código.

## Instructions

## Tests

```yml
tests:
  - text: <code>reverseString("hello")</code> deve retornar uma string.
    testString: 'assert(typeof reverseString("hello") === "string", "<code>reverseString("hello")</code> should return a string.");'
  - text: <code>reverseString("hello")</code> deve se tornar <code>"olleh"</code> .
    testString: 'assert(reverseString("hello") === "olleh", "<code>reverseString("hello")</code> should become <code>"olleh"</code>.");'
  - text: <code>reverseString("Howdy")</code> deve se tornar <code>"ydwoH"</code> .
    testString: 'assert(reverseString("Howdy") === "ydwoH", "<code>reverseString("Howdy")</code> should become <code>"ydwoH"</code>.");'
  - text: <code>reverseString("Greetings from Earth")</code> deve retornar <code>"htraE morf sgniteerG"</code> .
    testString: 'assert(reverseString("Greetings from Earth") === "htraE morf sgniteerG", "<code>reverseString("Greetings from Earth")</code> should return <code>"htraE morf sgniteerG"</code>.");'

```

## Challenge Seed

```js
function reverseString(str) {
  return str;
}

reverseString("hello");

```

## Solution

```js
function reverseString(str) {
  return str.split('').reverse().join('');
}

reverseString("hello");
```