text:
//!
//! @file   ModelUtilities.cpp
//! @brief Contains model specific helpfunctions for CLI
//!

#include <iostream>
#include <fstream>
#include <algorithm>

#include "ModelUtilities.h"
#include "version_cli.h"
#include "CliUtilities.h"

#include "HopsanEssentials.h"
#include "HopsanTypes.h"

#ifdef USEHDF5
#include "hopsanhdf5exporter.h"
#endif

using namespace std;
using namespace hopsan;

void generateFullSubSystemHierarchyName(const ComponentSystem *pSys, HString &rFullSysName, const HString& separator)
{
    if (pSys->getSystemParent())
    {
        generateFullSubSystemHierarchyName(pSys->getSystemParent(), rFullSysName, separator);
        rFullSysName.append(pSys->getName()).append(separator);
    }
    else
    {
        // Do not include top-level name in sub-system hierarchy
        rFullSysName.clear();
    }
}

HString generateFullSubSystemHierarchyName(const Component *pComponent, const HString &separator, bool includeLastSeparator)
{
    const ComponentSystem* pSystem = pComponent->isComponentSystem() ? dynamic_cast<const ComponentSystem*>(pComponent) : pComponent->getSystemParent();

    HString fullSysName;
    generateFullSubSystemHierarchyName(pSystem, fullSysName, separator);
    if (!includeLastSeparator && !fullSysName.empty()) {
        fullSysName.erase(fullSysName.size()-separator.size(),separator.size());
    }
    return fullSysName;
}

HString generateFullPortVariableName(const Port *pPort, const size_t dataId)
{
   HString fullName;
   const NodeDataDescription *pND = pPort->getNodeDataDescription(dataId);
   if (pND)
   {
       Component *pComp = pPort->getComponent();
       ComponentSystem *pSys = pComp->getSystemParent();
       if (pSys)
       {
           generateFullSubSystemHierarchyName(pSys, fullName);
       }

       fullName.append(pComp->getName()).append("#").append(pPort->getName()).append("#").append(pND->name);
   }
   return fullName;
}

//! @brief Helpfunction to print timestep info for a system
//! @param[in] pSystem The system to print info for
void printTsInfo(const ComponentSystem* pSystem)
{
    cout << "Ts: " << pSystem->getDesiredTimeStep() << " InheritTs: " << pSystem->doesInheritTimestep();
}

//! @brief Print system parameters in a system
//! @param[in] pSystem The system to print info for
void printSystemParams(ComponentSystem* pSystem)
{
    const vector<ParameterEvaluator*> *pParams = pSystem->getParametersVectorPtr();
    for (size_t i=0; i<pParams->size(); ++i)
    {
        cout << " SysParam: " << pParams->at(i)->getName().c_str() << "=" << pParams->at(i)->getValue().c_str();
    }
}

//! @brief Print component hierarcy in a system
//! @param[in] pSystem The system to print info for
//! @param[in] prefix Text to add before printout
//! @param[in] doPrintTsInfo Should timestep info be included
//! @param[in] doPrintSystemParams Should system parameters be printed
void printComponentHierarchy(ComponentSystem *pSystem, std::string prefix,
                             const bool doPrintTsInfo,
                             const bool doPrintSystemParams)
{
    if (pSystem)
    {
        cout << prefix << pSystem->getName().c_str() << ", ";
        if (doPrintTsInfo)
        {
            printTsInfo(pSystem);
        }

        if (doPrintSystemParams)
        {
            cout << " ";
            printSystemParams(pSystem);
        }

        cout << endl;

        prefix.append("  ");
        vector<HString> names = pSystem->getSubComponentNames();
        for (size_t i=0; i<names.size(); ++i)
        {
            if ( pSystem->getSubComponent(names[i])->isComponentSystem() )
            {
                printComponentHierarchy(pSystem->getSubComponentSystem(names[i]), prefix, doPrintTsInfo, doPrintSystemParams);
            }
            else
            {
                cout << prefix << names[i].c_str() << endl;
            }
        }
    }
}

void transposeCSVresults(const std::string &rFileName)
{
    ifstream infile(rFileName.c_str());
    if ( infile.good() )
    {
        vector< vector<string> > linesVec;
        vector<string> lineVec;
        // Read all lines into string vectors
        while(!infile.eof())
        {
            string line;
            getline(infile, line);

            // Split on delimiter
            splitStringOnDelimiter(line, ',', lineVec);

            // Store line vector
            if (lineVec.size() > 0)
            {
                linesVec.push_back(lineVec);
                lineVec.clear();

                // Clear data but reserve memory for next run
                size_t n = lineVec.size();
                lineVec.clear();
                lineVec.reserve(n);
            }
        }
        infile.close();

        // Write back transposed
        ofstream ofile(rFileName.c_str());
        if ( ofile.good() )
        {
            size_t rows = linesVec.size();
            if (rows > 0)
            {
                // Assumes same nr cols on each row
                size_t cols = linesVec[0].size();
                for (size_t c=0; c<cols; ++c)
                {
                    ofile << linesVec[0][c];
                    //cout << linesVec[0][c];
                    for (size_t r=1; r<rows; ++r)
                    {
                        ofile << "," <<  linesVec[r][c];
                        //cout << ", " <<  linesVec[r][c];
                    }
                    ofile << endl;
                    //cout << endl;
                }
            }
        }
        ofile.close();
    }
}

void exportParameterValuesToCSV(const std::string &rFileName, hopsan::ComponentSystem* pSystem, string prefix, ofstream *pFile)
{
    bool doCloseFile=false;
    if (!pFile)
    {
        pFile = new ofstream;
        pFile->open(rFileName.c_str());
        if (!pFile->good())
        {
            printErrorMessage("Could not open: " + rFileName + " for writing!");
            return;
            delete pFile;
        }
        doCloseFile = true;
    }

    if (pSystem)
    {
        // Handle own system parameters
        const std::vector<ParameterEvaluator*> *pSysParameters =  pSystem->getParametersVectorPtr();
        for (size_t p=0; p<pSysParameters->size(); ++p)
        {
            //! @todo what about alias name
            HString fullSelfName = prefix.empty() ? "self" : prefix.c_str();
            HString fullname = fullSelfName + "#" + pSysParameters->at(p)->getName();
            *pFile << fullname.c_str() << "," << pSysParameters->at(p)->getValue().c_str() << endl;
        }

        // Now handle subcomponent parameters
        vector<HString> names = pSystem->getSubComponentNames();
        for (size_t c=0; c<names.size(); ++c)
        {
            Component *pComp = pSystem->getSubComponent(names[c]);
            if (pComp)
            {
                if (pComp->isComponentSystem())
                {
                    exportParameterValuesToCSV(rFileName, static_cast<ComponentSystem*>(pComp), prefix+pComp->getName().c_str()+"$", pFile);
                }
                else
                {
                    const std::vector<ParameterEvaluator*> *pParameters =  pComp->getParametersVectorPtr();
                    for (size_t p=0; p<pParameters->size(); ++p)
                    {
                        //! @todo what about alias name
                        HString parname = pParameters->at(p)->getName();
                        HString fullname = prefix.c_str() + pComp->getName() + "#" + parname;
                        *pFile << fullname.c_str() << "," << pParameters->at(p)->getValue().c_str() << endl;
                    }
                }
            }
        }
    }

    if (doCloseFile)
    {
        pFile->close();
        delete pFile;
    }

}

//! @todo should we use CSV parser instead?
void importParameterValuesFromCSV(const std::string filePath, hopsan::ComponentSystem* pSystem)
{
    if (pSystem)
    {
        std::ifstream file;
        file.open(filePath.c_str());
        if ( file.is_open() )
        {
            std::vector<std::string> lineVec;
            std::string line;
            while ( file.good() )
            {
                getline(file, line);
                if (*line.begin() != '#')
                {
                    // Split on delimiter
                    splitStringOnDelimiter(line, ',', lineVec);

                    // Parse line vector
                    if (lineVec.size() == 2)
                    {
                        std::vector<std::string> nameParts;
                        string fullComponentName, parameterName;
                        splitStringOnDelimiter(lineVec[0], '#', nameParts);

                        // Split last name part into fullcomponent and parameter#value name
                        if (nameParts.size() == 2 || nameParts.size() == 3 ) {
                            if (nameParts.size() == 2) {
                                fullComponentName = nameParts[0];
                                parameterName = nameParts[1];
                            }
                            if (nameParts.size() == 3) {
                                // Set component name and reset the parameter (startvalue) name
                                fullComponentName = nameParts[0];
                                parameterName = nameParts[1]+"#"+nameParts[2];
                            }

                            hopsan::Component* pComponent;
                            if (fullComponentName == "self") {
                                pComponent = pSystem;
                            }
                            else {
                                pComponent = getComponentWithFullName(pSystem, fullComponentName);
                            }
                            if (pComponent) {
                                // lineVec[1] should be the parameter value
                                //! @todo what about parameter alias
                                bool ok = pComponent->setParameterValue(parameterName.c_str(), lineVec[1].c_str());
                                if (!ok) {
                                    printErrorMessage("Setting parameter: " + parameterName + " in component: " + fullComponentName);
                                }
                            }
                        }
                        else {
                            printErrorMessage(lineVec[0] + " should be FullComponentName#ParameterName on line: " + line);
                        }
                    }
                    else
                    {
                        // Print error for non-empty lines
                        if (lineVec.size() > 0)
                        {
                            printWarningMessage(string("Wrong line format: ") + line);
                        }
                    }
                }
            }
            file.close();
        }
        else
        {
            printErrorMessage(string("Could not open file: ")+filePath);
        }
    }
}

//! @brief Read data on which nodes to save after simualtion from text file
//! @param[in] filePath The file to read from
//! @param[out] rComps The component names
//! @param[out] rPorts The port names
void readNodesToSaveFromTxtFile(const std::string filePath, std::vector<std::string> &rComps, std::vector<std::string> &rPorts)
{
    rComps.clear();
    rPorts.clear();
    std::string line;
    std::ifstream file;
    file.open(filePath.c_str());
    if ( file.is_open() )
    {
        while ( file.good() )
        {
            getline(file, line);
            cout << "line: " << line << endl;
            if (*line.begin() != '#')
            {
                std::string comp, port;
                size_t sep;

                sep = line.find(';');
                comp = line.substr(0, sep);
                port = line.substr(sep+1);

                rComps.push_back(comp);
                rPorts.push_back(port);
            }
        }
        file.close();
    }
    else
    {
        printErrorMessage("Could not open file: " + filePath);
    }
}

Component *getComponentWithFullName(ComponentSystem *pRootSystem, const string &fullComponentName)
{
    std::vector<std::string> nameParts;
    splitStringOnDelimiter(fullComponentName, '$', nameParts);

    // Search into subsystems
    hopsan::ComponentSystem* pCurrentSystem = pRootSystem;
    for (size_t i=0; i<nameParts.size()-1; ++i) {
        // First check if the component is a sub system, in which case the loop continues to the next part
        auto pSystemComponent = pCurrentSystem->getSubComponentSystem(nameParts[i].c_str());
        if (pSystemComponent) {
            pCurrentSystem = pSystemComponent;
        }
        else {
            printErrorMessage("Subsystem: "+nameParts[i]+" could not be found in parent system: "+pCurrentSystem->getName().c_str());
            return nullptr;
        }
    }

    // Now lookup the component
    hopsan::Component* pComponent = pCurrentSystem->getSubComponent(nameParts.back().c_str());
    if (pComponent) {
        return pComponent;
    }
    else {
        printErrorMessage("No component: " + nameParts.back() + " in system: " + pCurrentSystem->getName().c_str() );
        return nullptr;
    }
}

hopsan::Port* getPortWithFullName(hopsan::ComponentSystem *pRootSystem, const std::string &fullPortName)
{
    std::vector<std::string> nameParts;
    splitStringOnDelimiter(fullPortName, '#', nameParts);

    hopsan::Component* pComponent = getComponentWithFullName(pRootSystem, nameParts.front());
    if (pComponent) {
        std::string portName;
        if (nameParts.size() == 2 || nameParts.size() == 3 ) {
            portName = nameParts[1];
            // Ignore ValuePart numParts[2] if it is pressent
        }
        else {
            printErrorMessage("A portname on the format ComponentName#PortName could not be found: " + fullPortName);
        }

        return pComponent->getPort(portName.c_str());
    }
    return nullptr;
}

//! @brief Save results to HDF5 format
//! @param [in] pRootSystem Pointer to component system
//! @param [in] rFileName File name for output file
//! @param [in] includeFilter list of full port names or variables names to include (excluding all others)
//! @param [in] howMany Specifies if all results or only final values should be saved
void saveResultsToHDF5(ComponentSystem *pRootSystem, const string &rFileName, const std::vector<string>& includeFilter, const SaveResults howMany)
{
#ifdef USEHDF5
    if(!pRootSystem) {
        return;
    }
    HopsanHDF5Exporter exporter(rFileName.c_str(), pRootSystem->getName().c_str(), std::string("HopsanCLI "+std::string(HOPSANCLIVERSION)).c_str());

    auto addTimeVariable = [&exporter, howMany](ComponentSystem* pSystem) {
        vector<double> *pLogTimeVector = pSystem->getLogTimeVector();
        const size_t numLoggedSamples = pSystem->getNumActuallyLoggedSamples();
        if (numLoggedSamples > 0) {
            HVector<double> timeVector;
            if(howMany == Full) {
                timeVector.assign_from(pLogTimeVector->data(), numLoggedSamples);
            }
            else {
                timeVector.append((*pLogTimeVector)[numLoggedSamples-1]);
            }
            HString parentSystemNames = generateFullSubSystemHierarchyName(pSystem,".", false);
            exporter.addVariable(parentSystemNames, "", "","Time","","s","Time",timeVector);
        }
    };

    auto addVariable = [&exporter, howMany](const ComponentSystem* pSystem, const Component* pComponent, const Port* pPort, size_t variableIndex) {
        const vector< vector<double> > *pLogData = pPort->getLogDataVectorPtr();
        const size_t numLoggedSamples = pSystem->getNumActuallyLoggedSamples();
        if( (pLogData != nullptr) && !pLogData->empty() && (numLoggedSamples > 0)) {
            HVector<double> dataVector;
            if(howMany == Full) {
                dataVector.reserve(numLoggedSamples);
                for (size_t t=0; t < numLoggedSamples; ++t) {
                    dataVector.append((*pLogData)[t][variableIndex]);
                }
            }
            else {
                dataVector.append((*pLogData)[numLoggedSamples-1][variableIndex]);
            }

            HString parentSystemNames = generateFullSubSystemHierarchyName(pSystem,".", false);
            const NodeDataDescription& variable = *pPort->getNodeDataDescription(variableIndex);

            exporter.addVariable(parentSystemNames, pComponent->getName(), pPort->getName(), variable.name, pPort->getVariableAlias(variableIndex).c_str(),
                                 variable.unit, variable.quantity, dataVector);
        }
    };

    saveResultsTo(pRootSystem, includeFilter, addTimeVariable, addVariable);

    bool writeOK = exporter.writeToFile();
    if (!writeOK) {
        printErrorMessage(("Failure when writing HDF5 file: "+exporter.getLastError()).c_str());
    }
#else
    printErrorMessage("HopsanCLI was built without HDF5 support");
#endif
}

//! @brief Save results to HDF5 format
//! @param [in] pRootSystem Pointer to component system
//! @param [in] rFileName File name for output file
//! @param [in] howMany Specifies if all results or only final values should be saved
//! @param [in] includeFilter list of full port names or variables names to include (excluding all others)
void saveResultsToCSV(ComponentSystem *pRootSystem, const string &rFileName, const SaveResults howMany, const std::vector<string>& includeFilter)
{
    if (pRootSystem)
    {
        ofstream outfile;
        outfile.open(rFileName.c_str());
        if (outfile.good()) {

            auto addTimeVariable = [&outfile, howMany](ComponentSystem* pSystem) {
                //! @todo alias a for time ? is that even posible
                HString parentSystemNames = generateFullSubSystemHierarchyName(pSystem,"$");
                if (howMany == Final) {
                    outfile << parentSystemNames.c_str() << "Time,,s," << std::scientific << pSystem->getTime() << endl;
                }
                else if (howMany == Full) {
                    vector<double> *pLogTimeVector = pSystem->getLogTimeVector();
                    if (pLogTimeVector->size() > 0) {
                        outfile << parentSystemNames.c_str() << "Time,,s";
                        for (size_t t=0; t<pSystem->getNumActuallyLoggedSamples(); ++t) {
                            outfile << "," << std::scientific << (*pLogTimeVector)[t];
                        }
                        outfile << endl;
                    }
                }
            };

            auto addVariable = [&outfile, howMany](const ComponentSystem* pSystem, const Component* pComponent, const Port* pPort, size_t variableIndex) {
                const NodeDataDescription& variable = *pPort->getNodeDataDescription(variableIndex);
                const vector< vector<double> > *pLogData = pPort->getLogDataVectorPtr();
                if( (pLogData != nullptr) && !pLogData->empty()) {
                    const HString fullVarName = generateFullSubSystemHierarchyName(pSystem,"$") + pComponent->getName() + "#" + pPort->getName() + "#" + variable.name;
                    if (howMany == Final) {
                        outfile << fullVarName.c_str() << "," << pPort->getVariableAlias(variableIndex).c_str() << "," << variable.unit.c_str();
                        outfile << "," << std::scientific << pPort->readNode(variableIndex) << endl;
                    }
                    else if (howMany == Full)
                    {
                        // Only write something if data has been logged (skip ports that are not logged)
                        // We assume that the data vector has been cleared
                        if (pPort->getLogDataVectorPtr()->size() > 0) {
                            outfile << fullVarName.c_str() << "," << pPort->getVariableAlias(variableIndex).c_str() << "," << variable.unit.c_str();
                            for (size_t t=0; t<pSystem->getNumActuallyLoggedSamples(); ++t) {
                                outfile << "," << std::scientific << (*pLogData)[t][variableIndex];
                            }
                            outfile << endl;
                        }
                    }
                }
            };

            saveResultsTo(pRootSystem, includeFilter, addTimeVariable, addVariable);

        }
        else {
            printErrorMessage("Could not open: " + rFileName + " for writing!");
        }

        outfile.close();
    }
}


text:
require 'spec_helper'

describe 'buttons' do
  Given(:main_form) { start_app }

  context 'pressing' do
    When { main_form.data_entry_form }
    Then { expect(on(DataEntryForm)).to be_present }
  end

  context '#value' do
    Then { main_form.data_entry_form_value == 'Data Entry Form' }
  end
end

redpajama_set_name: RedPajamaGithub


text:
class CategoriesController < ApplicationController
  before_action :set_category, only: [:show, :edit, :update, :destroy]

  # GET /categories
  # GET /categories.json
  def index
    # To support search (e.g. in select2 auto complete)
    params[:q] ? @categories = Category.where("name ilike ?", "#{params[:q]}%").limit(20) : @categories = Category.all

    respond_to do |format|
      format.html { }
      format.json {
        if params[:q]
          render :json => @categories.collect {|p| { id: p.name, text: p.name }}
        else
          render json: CategoryDatatable.new(view_context)
        end
      }
    end
  end

  # GET /categories/1
  # GET /categories/1.json
  def show
  end

  # GET /categories/new
  def new
    @category = Category.new
  end

  # GET /categories/1/edit
  def edit
  end

  # POST /categories
  # POST /categories.json
  def create
    @category = Category.new(category_params)

    respond_to do |format|
      if @category.save
        format.html { redirect_to categories_path, notice: 'Category was successfully created.' }
        format.json { render :show, status: :created, location: @category }
      else
        format.html { render :new }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /categories/1
  # PATCH/PUT /categories/1.json
  def update
    respond_to do |format|
      if @category.update(category_params)
        format.html { redirect_to categories_path, notice: 'Category was successfully updated.' }
        format.json { render :show, status: :ok, location: @category }
      else
        format.html { render :edit }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /categories/1
  # DELETE /categories/1.json
  def destroy
    @category.destroy
    respond_to do |format|
      format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_category
      @category = Category.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def category_params
      params.require(:category).permit(:name)
    end
end


text: <title>documentStrictDocType-fail</title>


text:
"""
********************************************************************************
* Name: permissions.py
* Author: nswain
* Created On: May 09, 2016
* Copyright:
* License: BSD 2-Clause
********************************************************************************
"""
# flake8: noqa
# DO NOT ERASE
from tethys_apps.base import Permission, PermissionGroup, has_permission
from tethys_apps.decorators import permission_required, login_required


text:
module.exports = {
  Model: require('./inline_image.js'),
  View: require('../annotation/annotation_view.js')
};


text:
<?php

class Mage_Adminhtml_Model_System_Config_Source_Web_Protocol
{

    public function toOptionArray()
    {
        return array(
            array('value'=>'', 'label'=>''),
            array('value'=>'http', 'label'=>Mage::helper('adminhtml')->__('HTTP (unsecure)')),
            array('value'=>'https', 'label'=>Mage::helper('adminhtml')->__('HTTPS (SSL)')),
        );
    }

}


text:
namespace Sleemon.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data.Linq.Mapping;

    public partial class KnowledgeBase
        : Entity
    {
        public KnowledgeBase()
        {
        }

        [Column(Name = "Id", DbType = "Int32", IsPrimaryKey = true, CanBeNull = false, IsDbGenerated = true)]
        public int Id { get; set; }
        [Column(Name = "Title", DbType = "String", CanBeNull = false)]
        public string Title { get; set; }
        [Column(Name = "Detail", DbType = "String", CanBeNull = false)]
        public string Detail { get; set; }
        [Column(Name = "KnowledgeCategory", DbType = "Int32", CanBeNull = false)]
        public int KnowledgeCategory { get; set; }
        [Column(Name = "LastUpdateUser", DbType = "String", CanBeNull = false)]
        public string LastUpdateUser { get; set; }
        [Column(Name = "LastUpdateTime", DbType = "DateTime", CanBeNull = false)]
    	private System.DateTime _lastUpdateTime;
    	public virtual System.DateTime LastUpdateTime
    	{
    		get { return _lastUpdateTime; }
    		set
    		{
    			if (value.Kind == DateTimeKind.Unspecified) {
    				_lastUpdateTime = DateTime.SpecifyKind(value, DateTimeKind.Utc);
    			} else {
    				_lastUpdateTime = value;
    			}
    		}
    	}
        [Column(Name = "IsActive", DbType = "Boolean", CanBeNull = false)]
        public bool IsActive { get; set; }

        private ICollection<KnowledgeBaseKeyword> _KnowledgeBaseKeyword;
        public virtual ICollection<KnowledgeBaseKeyword> KnowledgeBaseKeyword
        {
            get { return this._KnowledgeBaseKeyword ?? (this._KnowledgeBaseKeyword = new HashSet<KnowledgeBaseKeyword>()); }
            set { this._KnowledgeBaseKeyword = value; }
        }
    }
}


text:
require 'test_helper'
require 'vindicia-api'

class VindiciaTest < Test::Unit::TestCase
  def setup
    unless Vindicia.config.is_configured?
      schema = File.read(File.dirname(__FILE__) + '/../../schema/vindicia/Vindicia.xsd')
      response = Net::HTTPResponse.new('1.1', '200', 'OK')
      response.expects(:body).once.returns(schema)
      Vindicia.expects(:get_vindicia_file).once.returns(response)
    end

    @gateway = VindiciaGateway.new(
                 :login => 'login',
                 :password => 'password',
                 :account_id => 1
               )

    @credit_card = credit_card
    @amount = 100

    @options = {
      :order_id => '1',
      :billing_address => address,
      :line_items => {
        :name => 'Test Product',
        :sku => 'TEST_PRODUCT',
        :price => 5,
        :quantity => 1
      }
    }
  end

  def test_successful_purchase
    @gateway.expects(:ssl_post).twice.returns(successful_authorize_response, successful_capture_response)

    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_instance_of Response, response
    assert_success response

    assert response.authorization.include?(@options[:order_id])
    assert response.test?
  end

  def test_unsuccessful_authorize_status
    @gateway.expects(:ssl_post).once.returns(unsuccessful_authorize_response(:status => "Cancelled"))

    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert response.test?
  end

  def test_unsuccessful_authorize_avs
    @gateway.expects(:ssl_post).twice.returns(unsuccessful_authorize_response(:avs => "T"), successful_void_response)

    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert response.test?
  end

  def test_unsuccessful_authorize_cvn
    @gateway.expects(:ssl_post).twice.returns(unsuccessful_authorize_response(:cvn => "N"), successful_void_response)

    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert response.test?
  end

  def test_unsuccessful_capture
    @gateway.expects(:ssl_post).twice.returns(successful_authorize_response, unsuccessful_capture_response)

    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert response.test?
  end

  def test_unsuccessful_request
    @gateway.expects(:ssl_post).returns(failed_purchase_response)

    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert response.test?
  end

  def test_successful_recurring_setup
    @gateway.expects(:ssl_post).times(3).returns(successful_authorize_response,
                                                 successful_capture_response,
                                                 successful_update_response)

    response = assert_deprecation_warning(Gateway::RECURRING_DEPRECATION_MESSAGE) do
      @gateway.recurring(@amount, @credit_card, @options.merge(:product_sku => "TEST_SKU"))
    end
    assert_instance_of Response, response
    assert_success response

    assert response.authorization.include?(@options[:order_id])
    assert response.test?
  end

  def test_unsuccessful_recurring_setup
    @gateway.expects(:ssl_post).times(4).returns(successful_authorize_response,
                                                 successful_capture_response,
                                                 unsuccessful_update_response,
                                                 successful_void_response)

    response = assert_deprecation_warning(Gateway::RECURRING_DEPRECATION_MESSAGE) do
      @gateway.recurring(@amount, @credit_card, @options.merge(:product_sku => "TEST_SKU"))
    end
    assert_failure response
    assert response.test?
  end

  private

  def successful_authorize_response
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <authResponse xmlns="http://soap.vindicia.com/v3_6/Transaction">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">200</returnCode>
              <soapId xsi:type="xsd:string">0f3f650ca1882fc5f15d83c8dd3f69838662491d</soapId>
              <returnString xsi:type="xsd:string">OK</returnString>
            </return>

            <transaction xmlns="" xsi:type="vin:Transaction">
              <merchantTransactionId xmlns="" xsi:type="xsd:string">#{@options[:order_id]}</merchantTransactionId>

              <statusLog xmlns="" xsi:type="vin:TransactionStatus">
                <status xmlns="" xsi:type="vin:TransactionStatusType">Authorized</status>
                <creditCardStatus xmlns="" xsi:type="vin:TransactionStatusCreditCard">
                  <authCode xmlns="" xsi:type="xsd:string">100</authCode>
                  <avsCode xmlns="" xsi:type="xsd:string">X</avsCode>
                  <cvnCode xmlns="" xsi:type="xsd:string">M</cvnCode>
                </creditCardStatus>
              </statusLog>

              <statusLog xmlns="" xsi:type="vin:TransactionStatus">
                <status xmlns="" xsi:type="vin:TransactionStatusType">New</status>
              </statusLog>
            </transaction>
          </authResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end

  def unsuccessful_authorize_response(options = {})
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <authResponse xmlns="http://soap.vindicia.com/v3_6/Transaction">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">200</returnCode>
              <soapId xsi:type="xsd:string">0f3f650ca1882fc5f15d83c8dd3f69838662491d</soapId>
              <returnString xsi:type="xsd:string">OK</returnString>
            </return>

            <transaction xmlns="" xsi:type="vin:Transaction">
              <merchantTransactionId xmlns="" xsi:type="xsd:string">#{@options[:order_id]}</merchantTransactionId>

              <statusLog xmlns="" xsi:type="vin:TransactionStatus">
                <status xmlns="" xsi:type="vin:TransactionStatusType">#{options[:status] || "Authorized"}</status>
                <creditCardStatus xmlns="" xsi:type="vin:TransactionStatusCreditCard">
                  <authCode xmlns="" xsi:type="xsd:string">100</authCode>
                  <avsCode xmlns="" xsi:type="xsd:string">#{options[:avs] || "X"}</avsCode>
                  <cvnCode xmlns="" xsi:type="xsd:string">#{options[:cvn] || "M"}</cvnCode>
                </creditCardStatus>
              </statusLog>

              <statusLog xmlns="" xsi:type="vin:TransactionStatus">
                <status xmlns="" xsi:type="vin:TransactionStatusType">New</status>
              </statusLog>
            </transaction>
          </authResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end

  def unsuccessful_capture_response
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <captureResponse xmlns="http://soap.vindicia.com/v3_6/Transaction">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">200</returnCode>

              <soapId xsi:type="xsd:string">f500e87cc8941c90310f31ef1de9684a3171fed6</soapId>

              <returnString xsi:type="xsd:string">Ok</returnString>
            </return>

            <qtySuccess xmlns="" xsi:type="xsd:int">0</qtySuccess>

            <qtyFail xmlns="" xsi:type="xsd:int">1</qtyFail>

            <results xmlns="" xsi:type="vin:CaptureResult">
              <returnCode xmlns="" xsi:type="xsd:int">400</returnCode>
              <merchantTransactionId xmlns="" xsi:type="xsd:string">#{@options[:order_id]}</merchantTransactionId>
            </results>
          </captureResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end

  def successful_capture_response
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <captureResponse xmlns="http://soap.vindicia.com/v3_6/Transaction">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">200</returnCode>

              <soapId xsi:type="xsd:string">f500e87cc8941c90310f31ef1de9684a3171fed6</soapId>

              <returnString xsi:type="xsd:string">Ok</returnString>
            </return>

            <qtySuccess xmlns="" xsi:type="xsd:int">1</qtySuccess>

            <qtyFail xmlns="" xsi:type="xsd:int">0</qtyFail>

            <results xmlns="" xsi:type="vin:CaptureResult">
              <returnCode xmlns="" xsi:type="xsd:int">200</returnCode>
              <merchantTransactionId xmlns="" xsi:type="xsd:string">#{@options[:order_id]}</merchantTransactionId>
            </results>
          </captureResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end
  # Not exactly the same, but very similar
  alias :successful_void_response :successful_capture_response

  def failed_purchase_response
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <authResponse xmlns="http://soap.vindicia.com/v3_6/Transaction">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">400</returnCode>
              <soapId xsi:type="xsd:string">e91e2caacf88e5c912eae8dbf354db8af053d20e</soapId>
              <returnString xsi:type="xsd:string">OK</returnString>
            </return>

            <transaction xmlns="" xsi:type="vin:Transaction">
              <merchantTransactionId xmlns="" xsi:type="xsd:string">R557887665</merchantTransactionId>
            </transaction>
          </authResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end

  # AutoBill responses
  def successful_update_response
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <updateResponse xmlns="http://soap.vindicia.com/v3_6/AutoBill">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">200</returnCode>
              <soapId xsi:type="xsd:string">398ee6483a4b27dda94064cd67cf27464f6394eb</soapId>
              <returnString xsi:type="xsd:string">OK</returnString>
            </return>

            <autobill xmlns="" xsi:type="vin:AutoBill">
              <VID xmlns="" xsi:type="xsd:string">5857cab01a01a05939d1db9a8c63e3119254b405</VID>
              <merchantAutoBillId xmlns="" xsi:type="xsd:string">A#{@options[:order_id]}</merchantAutoBillId>
              <status xmlns="" xsi:type="vin:AutoBillStatus">Active</status>
              <startTimestamp xmlns="" xsi:type="xsd:dateTime">2011-05-13T10:32:23-07:00</startTimestamp>
              <endTimestamp xmlns="" xsi:type="xsd:dateTime">2011-05-15T10:32:23-07:00</endTimestamp>
            </autobill>

            <created xmlns="" xsi:type="xsd:boolean">1</created>
          </updateResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end

  def unsuccessful_update_response
    <<-END
      <?xml version="1.0" encoding="UTF-8"?>
      <soap:Envelope
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:vin="http://soap.vindicia.com/v3_6/Vindicia"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
          xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <updateResponse xmlns="http://soap.vindicia.com/v3_6/AutoBill">
            <return xmlns="" xsi:type="vin:Return">
              <returnCode xsi:type="vin:ReturnCode">200</returnCode>
              <soapId xsi:type="xsd:string">398ee6483a4b27dda94064cd67cf27464f6394eb</soapId>
              <returnString xsi:type="xsd:string">OK</returnString>
            </return>

            <autobill xmlns="" xsi:type="vin:AutoBill">
              <VID xmlns="" xsi:type="xsd:string">5857cab01a01a05939d1db9a8c63e3119254b405</VID>
              <merchantAutoBillId xmlns="" xsi:type="xsd:string">A#{@options[:order_id]}</merchantAutoBillId>
              <status xmlns="" xsi:type="vin:AutoBillStatus">Cancelled</status>
              <startTimestamp xmlns="" xsi:type="xsd:dateTime">2011-05-13T10:32:23-07:00</startTimestamp>
              <endTimestamp xmlns="" xsi:type="xsd:dateTime">2011-05-15T10:32:23-07:00</endTimestamp>
            </autobill>

            <created xmlns="" xsi:type="xsd:boolean">0</created>
          </updateResponse>
        </soap:Body>
      </soap:Envelope>
    END
  end
end


text:
package org.conqat.engine.html_presentation.javascript;

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

import org.conqat.lib.commons.collections.CollectionUtils;
import org.conqat.lib.commons.collections.UnmodifiableList;

/**
 * Represents a single JavaScript file. This class is immutable.
 *
 * @author $Author: deissenb $
 * @version $Rev: 38039 $
 * @ConQAT.Rating GREEN Hash: 4408897DFBE8B1A68718A45EAF2CFB8F
 */
public class JavaScriptFile implements Comparable<JavaScriptFile> {

	/** The type of JavaScript contained. */
	public static enum EType {

		/**
		 * A file that contains JavaScript code that is required and thus
		 * included in the compiled JavaScript in any case. This is typically
		 * used for all non-third-party code.
		 */
		CODE_REQUIRED,

		/**
		 * A file that contains code that is from a library and might be
		 * referenced from other files. This is only included if an actual
		 * reference is found. Furthermore, compiler warnings are not reported
		 * for these files.
		 */
		CODE_LIBRARY,

		/**
		 * A file containing a closure template (a.k.a. Soy). Technically, this
		 * is no JavaScript, but it is converted to JavaScript during
		 * compilation. Template files are always required, as there are no
		 * third-party templates.
		 */
		CLOSURE_TEMPLATE,

		/**
		 * A file containing extern descriptions for Google's closure compiler.
		 * This is always included as externs description to the compiler.
		 */
		CLOSURE_EXTERN
	}

	/** The type of this file. */
	private final EType type;

	/** A unique name used to identify this file. */
	private final String name;

	/** The content of this file. */
	private final String content;

	/**
	 * The list of namespaces provided by this file. The namespaces are
	 * basically just a list of arbitrary strings and are not related to
	 * {@link #name}. The provided namespaces are inspected to determine if an
	 * optional code file should be included during compilation.
	 */
	private final List<String> providedNamespaces = new ArrayList<String>();

	/**
	 * The list of namespaces required by this file. The namespaces are
	 * basically just a list of arbitrary strings and are not related to
	 * {@link #name}. The required namespaces are inspected to resolve
	 * additional code files required for building the script.
	 */
	private final List<String> requiredNamespaces = new ArrayList<String>();

	/** Constructor. */
	/* package */JavaScriptFile(EType type, String name, String content,
			List<String> providedNamespaces, List<String> requiredNamespaces) {
		this.type = type;
		this.name = name;
		this.content = content;
		this.providedNamespaces.addAll(providedNamespaces);
		this.requiredNamespaces.addAll(requiredNamespaces);
	}

	/** Returns the type. */
	public EType getType() {
		return type;
	}

	/** Returns the name. */
	public String getName() {
		return name;
	}

	/** Returns the content. */
	public String getContent() {
		return content;
	}

	/** Returns the provided namespaces. */
	public UnmodifiableList<String> getProvidedNamespaces() {
		return CollectionUtils.asUnmodifiable(providedNamespaces);
	}

	/** Returns the required namespaces. */
	public UnmodifiableList<String> getRequiredNamespaces() {
		return CollectionUtils.asUnmodifiable(requiredNamespaces);
	}

	/**
	 * {@inheritDoc}
	 * <p>
	 * Compares by name.
	 */
	@Override
	public int compareTo(JavaScriptFile other) {
		return name.compareTo(other.name);
	}
}


text:
<?php
while(true) {
  // Your worker role code goes in here.
  //
  // Note that whenever the control loop ends or breaks,
  // the worker role instance will automatically restart.
}


text:
/*
 * yeelink_rsp.h
 *
 *  Created on: Apr 30, 2015
 *      Author: jk
 */

#ifndef SRC_YEELINK_RSP_H_
#define SRC_YEELINK_RSP_H_

#include <stdio.h>

size_t yeelink_onCreateDevice(void *contents, size_t size, size_t nmemb, void *userp);
size_t yeelink_onCreateSensor(void *contents, size_t size, size_t nmemb, void *userp);
size_t yeelink_onsaveGPS(void *contents, size_t size, size_t nmemb, void *userp);

#endif /* SRC_YEELINK_RSP_H_ */


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<context:component-scan base-package="arron.developer.controller" />
	<context:component-scan base-package="models" />
	<context:component-scan base-package="services" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/views/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

	<mvc:resources mapping="/resources/**" location="/resources/" />

	<mvc:annotation-driven />

</beans>


text:
/**
 * @brief Driver for Nordic Semiconductor nRF5X UART
 */

#include <uart.h>
#include <hal/nrf_uart.h>
#include <hal/nrf_gpio.h>

static NRF_UART_Type *const uart0_addr = (NRF_UART_Type *)CONFIG_UART_0_BASE;

#ifdef CONFIG_UART_0_INTERRUPT_DRIVEN

static uart_irq_callback_user_data_t irq_callback; /**< Callback function pointer */
static void *irq_cb_data; /**< Callback function arg */

/* Variable used to override the state of the TXDRDY event in the initial state
 * of the driver. This event is not set by the hardware until a first byte is
 * sent, and we want to use it as an indication if the transmitter is ready
 * to accept a new byte.
 */
static volatile u8_t uart_sw_event_txdrdy;

#endif /* CONFIG_UART_0_INTERRUPT_DRIVEN */

static bool event_txdrdy_check(void)
{
	return (nrf_uart_event_check(uart0_addr, NRF_UART_EVENT_TXDRDY)
#ifdef CONFIG_UART_0_INTERRUPT_DRIVEN
		|| uart_sw_event_txdrdy
#endif
	       );
}

static void event_txdrdy_clear(void)
{
	nrf_uart_event_clear(uart0_addr, NRF_UART_EVENT_TXDRDY);
#ifdef CONFIG_UART_0_INTERRUPT_DRIVEN
	uart_sw_event_txdrdy = 0;
#endif
}

/**
 * @brief Set the baud rate
 *
 * This routine set the given baud rate for the UART.
 *
 * @param dev UART device struct
 * @param baudrate Baud rate
 *
 * @return N/A
 */

static int baudrate_set(struct device *dev, u32_t baudrate)
{
	nrf_uart_baudrate_t nrf_baudrate; /* calculated baudrate divisor */

	switch (baudrate) {
	case 300:
		/* value not supported by Nordic HAL */
		nrf_baudrate = 0x00014000;
		break;
	case 600:
		/* value not supported by Nordic HAL */
		nrf_baudrate = 0x00027000;
		break;
	case 1200:
		nrf_baudrate = NRF_UART_BAUDRATE_1200;
		break;
	case 2400:
		nrf_baudrate = NRF_UART_BAUDRATE_2400;
		break;
	case 4800:
		nrf_baudrate = NRF_UART_BAUDRATE_4800;
		break;
	case 9600:
		nrf_baudrate = NRF_UART_BAUDRATE_9600;
		break;
	case 14400:
		nrf_baudrate = NRF_UART_BAUDRATE_14400;
		break;
	case 19200:
		nrf_baudrate = NRF_UART_BAUDRATE_19200;
		break;
	case 28800:
		nrf_baudrate = NRF_UART_BAUDRATE_28800;
		break;
	case 31250:
		nrf_baudrate = NRF_UART_BAUDRATE_31250;
		break;
	case 38400:
		nrf_baudrate = NRF_UART_BAUDRATE_38400;
		break;
	case 56000:
		nrf_baudrate = NRF_UART_BAUDRATE_56000;
		break;
	case 57600:
		nrf_baudrate = NRF_UART_BAUDRATE_57600;
		break;
	case 76800:
		nrf_baudrate = NRF_UART_BAUDRATE_76800;
		break;
	case 115200:
		nrf_baudrate = NRF_UART_BAUDRATE_115200;
		break;
	case 230400:
		nrf_baudrate = NRF_UART_BAUDRATE_230400;
		break;
	case 250000:
		nrf_baudrate = NRF_UART_BAUDRATE_250000;
		break;
	case 460800:
		nrf_baudrate = NRF_UART_BAUDRATE_460800;
		break;
	case 921600:
		nrf_baudrate = NRF_UART_BAUDRATE_921600;
		break;
	case 1000000:
		nrf_baudrate = NRF_UART_BAUDRATE_1000000;
		break;
	default:
		return -EINVAL;
	}

	nrf_uart_baudrate_set(uart0_addr, nrf_baudrate);

	return 0;
}

/**
 * @brief Poll the device for input.
 *
 * @param dev UART device struct
 * @param c Pointer to character
 *
 * @return 0 if a character arrived, -1 if the input buffer if empty.
 */

static int uart_nrfx_poll_in(struct device *dev, unsigned char *c)
{
	if (!nrf_uart_event_check(uart0_addr, NRF_UART_EVENT_RXDRDY)) {
		return -1;
	}

	/* Clear the interrupt */
	nrf_uart_event_clear(uart0_addr, NRF_UART_EVENT_RXDRDY);

	/* got a character */
	*c = nrf_uart_rxd_get(uart0_addr);

	return 0;
}

/**
 * @brief Output a character in polled mode.
 *
 * @param dev UART device struct
 * @param c Character to send
 *
 * @return Sent character
 */
static unsigned char uart_nrfx_poll_out(struct device *dev,
					unsigned char c)
{
	/* The UART API dictates that poll_out should wait for the transmitter
	 * to be empty before sending a character. However, without locking,
	 * this introduces a rare yet possible race condition if the thread is
	 * preempted between sending the byte and checking for completion.

	 * Because of this race condition, the while loop has to be placed
	 * after the write to TXD, and we can't wait for an empty transmitter
	 * before writing. This is a trade-off between losing a byte once in a
	 * blue moon against hanging up the whole thread permanently
	 */

	/* Reset the transmitter ready state. */
	event_txdrdy_clear();

	/* Activate the transmitter. */
	nrf_uart_task_trigger(uart0_addr, NRF_UART_TASK_STARTTX);

	/* Send the provided character. */
	nrf_uart_txd_set(uart0_addr, (u8_t)c);

	/* Wait until the transmitter is ready, i.e. the character is sent. */
	while (!event_txdrdy_check()) {
	}

	/* Deactivate the transmitter so that it does not needlessly consume
	 * power.
	 */
	nrf_uart_task_trigger(uart0_addr, NRF_UART_TASK_STOPTX);

	return c;
}

/** Console I/O function */
static int uart_nrfx_err_check(struct device *dev)
{
	u32_t error = 0;

	if (nrf_uart_event_check(uart0_addr, NRF_UART_EVENT_ERROR)) {
		/* register bitfields maps to the defines in uart.h */
		error = nrf_uart_errorsrc_get_and_clear(uart0_addr);
	}

	return error;
}

#ifdef CONFIG_UART_0_INTERRUPT_DRIVEN

/** Interrupt driven FIFO fill function */
static int uart_nrfx_fifo_fill(struct device *dev,
			       const u8_t *tx_data,
			       int len)
{
	u8_t num_tx = 0;

	while ((len - num_tx > 0) &&
	       event_txdrdy_check()) {

		/* Clear the interrupt */
		event_txdrdy_clear();

		/* Send a character */
		nrf_uart_txd_set(uart0_addr, (u8_t)tx_data[num_tx++]);
	}

	return (int)num_tx;
}

/** Interrupt driven FIFO read function */
static int uart_nrfx_fifo_read(struct device *dev,
			       u8_t *rx_data,
			       const int size)
{
	u8_t num_rx = 0;

	while ((size - num_rx > 0) &&
	       nrf_uart_event_check(uart0_addr, NRF_UART_EVENT_RXDRDY)) {
		/* Clear the interrupt */
		nrf_uart_event_clear(uart0_addr, NRF_UART_EVENT_RXDRDY);

		/* Receive a character */
		rx_data[num_rx++] = (u8_t)nrf_uart_rxd_get(uart0_addr);
	}

	return num_rx;
}

/** Interrupt driven transfer enabling function */
static void uart_nrfx_irq_tx_enable(struct device *dev)
{
	u32_t key;

	/* Indicate that this device started a transaction that should not be
	 * interrupted by putting the SoC into the deep sleep mode.
	 */
	device_busy_set(dev);

	/* Activate the transmitter. */
	nrf_uart_task_trigger(uart0_addr, NRF_UART_TASK_STARTTX);

	nrf_uart_int_enable(uart0_addr, NRF_UART_INT_MASK_TXDRDY);

	/* Critical section is used to avoid any UART related interrupt which
	 * can occur after the if statement and before call of the function
	 * forcing an interrupt.
	 */
	key = irq_lock();
	if (uart_sw_event_txdrdy) {
		/* Due to HW limitation first TXDRDY interrupt shall be
		 * triggered by the software.
		 */
		NVIC_SetPendingIRQ(CONFIG_UART_0_IRQ_NUM);
	}
	irq_unlock(key);
}

/** Interrupt driven transfer disabling function */
static void uart_nrfx_irq_tx_disable(struct device *dev)
{
	nrf_uart_int_disable(uart0_addr, NRF_UART_INT_MASK_TXDRDY);

	/* Deactivate the transmitter so that it does not needlessly consume
	 * power.
	 */
	nrf_uart_task_trigger(uart0_addr, NRF_UART_TASK_STOPTX);

	/* The transaction is over. It is okay to enter the deep sleep mode
	 * if needed.
	 */
	device_busy_clear(dev);
}

/** Interrupt driven receiver enabling function */
static void uart_nrfx_irq_rx_enable(struct device *dev)
{
	nrf_uart_int_enable(uart0_addr, NRF_UART_INT_MASK_RXDRDY);
}

/** Interrupt driven receiver disabling function */
static void uart_nrfx_irq_rx_disable(struct device *dev)
{
	nrf_uart_int_disable(uart0_addr, NRF_UART_INT_MASK_RXDRDY);
}

/** Interrupt driven transfer empty function */
static int uart_nrfx_irq_tx_ready_complete(struct device *dev)
{
	return event_txdrdy_check();
}

/** Interrupt driven receiver ready function */
static int uart_nrfx_irq_rx_ready(struct device *dev)
{
	return nrf_uart_event_check(uart0_addr, NRF_UART_EVENT_RXDRDY);
}

/** Interrupt driven error enabling function */
static void uart_nrfx_irq_err_enable(struct device *dev)
{
	nrf_uart_int_enable(uart0_addr, NRF_UART_INT_MASK_ERROR);
}

/** Interrupt driven error disabling function */
static void uart_nrfx_irq_err_disable(struct device *dev)
{
	nrf_uart_int_disable(uart0_addr, NRF_UART_INT_MASK_ERROR);
}

/** Interrupt driven pending status function */
static int uart_nrfx_irq_is_pending(struct device *dev)
{
	return ((nrf_uart_int_enable_check(uart0_addr,
					   NRF_UART_INT_MASK_TXDRDY) &&
		 event_txdrdy_check())
		||
		(nrf_uart_int_enable_check(uart0_addr,
					   NRF_UART_INT_MASK_RXDRDY) &&
		 uart_nrfx_irq_rx_ready(dev)));
}

/** Interrupt driven interrupt update function */
static int uart_nrfx_irq_update(struct device *dev)
{
	return 1;
}

/** Set the callback function */
static void uart_nrfx_irq_callback_set(struct device *dev,
				       uart_irq_callback_user_data_t cb,
				       void *cb_data)
{
	(void)dev;
	irq_callback = cb;
	irq_cb_data = cb_data;
}

/**
 * @brief Interrupt service routine.
 *
 * This simply calls the callback function, if one exists.
 *
 * @param arg Argument to ISR.
 *
 * @return N/A
 */
static void uart_nrfx_isr(void *arg)
{
	ARG_UNUSED(arg);

	if (irq_callback) {
		irq_callback(irq_cb_data);
	}
}
#endif /* CONFIG_UART_0_INTERRUPT_DRIVEN */

DEVICE_DECLARE(uart_nrfx_uart0);

/**
 * @brief Initialize UART channel
 *
 * This routine is called to reset the chip in a quiescent state.
 * It is assumed that this function is called only once per UART.
 *
 * @param dev UART device struct
 *
 * @return 0 on success
 */
static int uart_nrfx_init(struct device *dev)
{
	int err;

	/* Setting default height state of the TX PIN to avoid glitches
	 * on the line during peripheral activation/deactivation.
	 */
	nrf_gpio_pin_write(CONFIG_UART_0_TX_PIN, 1);
	nrf_gpio_cfg_output(CONFIG_UART_0_TX_PIN);

	nrf_gpio_cfg_input(CONFIG_UART_0_RX_PIN, NRF_GPIO_PIN_NOPULL);

	nrf_uart_txrx_pins_set(uart0_addr,
			       CONFIG_UART_0_TX_PIN,
			       CONFIG_UART_0_RX_PIN);

#ifdef CONFIG_UART_0_NRF_FLOW_CONTROL
#ifndef CONFIG_UART_0_RTS_PIN
#error Flow control for UART0 is enabled, but RTS pin is not defined.
#endif
#ifndef CONFIG_UART_0_CTS_PIN
#error Flow control for UART0 is enabled, but CTS pin is not defined.
#endif
	/* Setting default height state of the RTS PIN to avoid glitches
	 * on the line during peripheral activation/deactivation.
	 */
	nrf_gpio_pin_write(CONFIG_UART_0_RTS_PIN, 1);
	nrf_gpio_cfg_output(CONFIG_UART_0_RTS_PIN);

	nrf_gpio_cfg_input(CONFIG_UART_0_CTS_PIN, NRF_GPIO_PIN_NOPULL);

	nrf_uart_hwfc_pins_set(uart0_addr,
			       CONFIG_UART_0_RTS_PIN,
			       CONFIG_UART_0_CTS_PIN);
#endif /* CONFIG_UART_0_NRF_FLOW_CONTROL */

	nrf_uart_configure(uart0_addr,
#ifdef CONFIG_UART_0_NRF_PARITY_BIT
			   NRF_UART_PARITY_INCLUDED,
#else
			   NRF_UART_PARITY_EXCLUDED,
#endif /* CONFIG_UART_0_NRF_PARITY_BIT */
#ifdef CONFIG_UART_0_NRF_FLOW_CONTROL
			   NRF_UART_HWFC_ENABLED);
#else
			   NRF_UART_HWFC_DISABLED);
#endif /* CONFIG_UART_0_NRF_PARITY_BIT */

	/* Set baud rate */
	err = baudrate_set(dev, CONFIG_UART_0_BAUD_RATE);
	if (err) {
		return err;
	}

	/* Enable the UART and activate its receiver. With the current API
	 * the receiver needs to be active all the time. The transmitter
	 * will be activated when there is something to send.
	 */
	nrf_uart_enable(uart0_addr);

	nrf_uart_event_clear(uart0_addr, NRF_UART_EVENT_RXDRDY);

	nrf_uart_task_trigger(uart0_addr, NRF_UART_TASK_STARTRX);

#ifdef CONFIG_UART_0_INTERRUPT_DRIVEN
	/* Simulate that the TXDRDY event is set, so that the transmitter status
	 * is indicated correctly.
	 */
	uart_sw_event_txdrdy = 1;

	IRQ_CONNECT(CONFIG_UART_0_IRQ_NUM,
		    CONFIG_UART_0_IRQ_PRI,
		    uart_nrfx_isr,
		    DEVICE_GET(uart_nrfx_uart0),
		    0);
	irq_enable(CONFIG_UART_0_IRQ_NUM);
#endif

	return 0;
}

/* Common function: uart_nrfx_irq_tx_ready_complete is used for two API entries
 * because Nordic hardware does not distinguish between them.
 */
static const struct uart_driver_api uart_nrfx_uart_driver_api = {
	.poll_in          = uart_nrfx_poll_in,
	.poll_out         = uart_nrfx_poll_out,
	.err_check        = uart_nrfx_err_check,
#ifdef CONFIG_UART_0_INTERRUPT_DRIVEN
	.fifo_fill        = uart_nrfx_fifo_fill,
	.fifo_read        = uart_nrfx_fifo_read,
	.irq_tx_enable    = uart_nrfx_irq_tx_enable,
	.irq_tx_disable   = uart_nrfx_irq_tx_disable,
	.irq_tx_ready     = uart_nrfx_irq_tx_ready_complete,
	.irq_rx_enable    = uart_nrfx_irq_rx_enable,
	.irq_rx_disable   = uart_nrfx_irq_rx_disable,
	.irq_tx_complete  = uart_nrfx_irq_tx_ready_complete,
	.irq_rx_ready     = uart_nrfx_irq_rx_ready,
	.irq_err_enable   = uart_nrfx_irq_err_enable,
	.irq_err_disable  = uart_nrfx_irq_err_disable,
	.irq_is_pending   = uart_nrfx_irq_is_pending,
	.irq_update       = uart_nrfx_irq_update,
	.irq_callback_set = uart_nrfx_irq_callback_set,
#endif /* CONFIG_UART_0_INTERRUPT_DRIVEN */
};

#ifdef CONFIG_DEVICE_POWER_MANAGEMENT
static void uart_nrfx_set_power_state(u32_t new_state)
{
	if (new_state == DEVICE_PM_ACTIVE_STATE) {
		nrf_uart_enable(uart0_addr);
		nrf_uart_task_trigger(uart0_addr, NRF_UART_TASK_STARTRX);
	} else {
		assert(new_state == DEVICE_PM_LOW_POWER_STATE ||
		       new_state == DEVICE_PM_SUSPEND_STATE ||
		       new_state == DEVICE_PM_OFF_STATE);
		nrf_uart_disable(uart0_addr);
	}
}

static int uart_nrfx_pm_control(struct device *dev,
				u32_t ctrl_command,
				void *context)
{
	static u32_t current_state = DEVICE_PM_ACTIVE_STATE;

	if (ctrl_command == DEVICE_PM_SET_POWER_STATE) {
		u32_t new_state = *((const u32_t *)context);

		if (new_state != current_state) {
			uart_nrfx_set_power_state(new_state);
			current_state = new_state;
		}
	} else {
		assert(ctrl_command == DEVICE_PM_GET_POWER_STATE);
		*((u32_t *)context) = current_state;
	}

	return 0;
}
#endif /* CONFIG_DEVICE_POWER_MANAGEMENT */

DEVICE_DEFINE(uart_nrfx_uart0,
	      CONFIG_UART_0_NAME,
	      uart_nrfx_init,
	      uart_nrfx_pm_control,
	      NULL,
	      NULL,
	      /* Initialize UART device before UART console. */
	      PRE_KERNEL_1,
	      CONFIG_KERNEL_INIT_PRIORITY_DEVICE,
	      &uart_nrfx_uart_driver_api);


text:
package org.robolectric.shadows.support.v4;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.widget.LinearLayout;
import org.robolectric.Robolectric;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.android.controller.ComponentController;

/**
 * Version of FragmentController that can be used for android.support.v4.Fragment. Only
 * necessary if more complex lifecycle management is needed, otherwise SupportFragmentTestUtil
 * should be sufficient.
 */
public class SupportFragmentController<F extends Fragment> extends ComponentController<SupportFragmentController<F>, F> {
  private final F fragment;
  private final ActivityController<? extends FragmentActivity> activityController;

  protected SupportFragmentController(F fragment, Class<? extends FragmentActivity> activityClass) {
    this(fragment, activityClass, null);
  }

  protected SupportFragmentController(F fragment, Class<? extends FragmentActivity> activityClass, Intent intent) {
    super(Robolectric.getShadowsAdapter(), fragment, intent);
    this.fragment = fragment;
    this.activityController = Robolectric.buildActivity(activityClass, intent);
  }

  public static <F extends Fragment> SupportFragmentController<F> of(F fragment) {
    return new SupportFragmentController<>(fragment, FragmentControllerActivity.class);
  }

  public static <F extends Fragment> SupportFragmentController<F> of(F fragment, Class<? extends FragmentActivity> activityClass) {
    return new SupportFragmentController<>(fragment, activityClass);
  }

  public static <F extends Fragment> SupportFragmentController<F> of(F fragment, Class<? extends FragmentActivity> activityClass, Intent intent) {
    return new SupportFragmentController<>(fragment, activityClass, intent);
  }

  /**
   * Creates the activity with {@link Bundle} and adds the fragment to the view with ID {@code contentViewId}.
   */
  public SupportFragmentController<F> create(final int contentViewId, final Bundle bundle) {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.create(bundle).get().getSupportFragmentManager().beginTransaction().add(contentViewId, fragment).commit();
      }
    });
    return this;
  }

  /**
   * Creates the activity with {@link Bundle} and adds the fragment to it. Note that the fragment will be added to the view with ID 1.
   */
  public SupportFragmentController<F> create(final Bundle bundle) {
    return create(1, bundle);
  }

  @Override
  public SupportFragmentController<F> create() {
    return create(null);
  }

  @Override
  public SupportFragmentController<F> destroy() {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.destroy();
      }
    });
    return this;
  }

  public SupportFragmentController<F> start() {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.start();
      }
    });
    return this;
  }

  public SupportFragmentController<F> resume() {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.resume();
      }
    });
    return this;
  }

  public SupportFragmentController<F> pause() {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.pause();
      }
    });
    return this;
  }

  public SupportFragmentController<F> stop() {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.stop();
      }
    });
    return this;
  }

  public SupportFragmentController<F> visible() {
    shadowMainLooper.runPaused(new Runnable() {
      @Override
      public void run() {
        activityController.visible();
      }
    });
    return this;
  }

  private static class FragmentControllerActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      LinearLayout view = new LinearLayout(this);
      view.setId(1);

      setContentView(view);
    }
  }
}


text:
<!doctype html>

  <meta charset="utf-8">

  <title>The Mansion</title>
  <meta name="description" content="A quick EndDash example.">
  <meta name="author" content="Amicus">


text:
package com.amazonaws.services.kinesisfirehose.model.transform;

import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * BufferingHintsMarshaller
 */
public class BufferingHintsJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(BufferingHints bufferingHints,
            StructuredJsonGenerator jsonGenerator) {

        if (bufferingHints == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (bufferingHints.getSizeInMBs() != null) {
                jsonGenerator.writeFieldName("SizeInMBs").writeValue(
                        bufferingHints.getSizeInMBs());
            }
            if (bufferingHints.getIntervalInSeconds() != null) {
                jsonGenerator.writeFieldName("IntervalInSeconds").writeValue(
                        bufferingHints.getIntervalInSeconds());
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static BufferingHintsJsonMarshaller instance;

    public static BufferingHintsJsonMarshaller getInstance() {
        if (instance == null)
            instance = new BufferingHintsJsonMarshaller();
        return instance;
    }

}


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

<TITLE>
Uses of Class org.apache.poi.poifs.crypt.dsig.SignatureConfig (POI API Documentation)
</TITLE>

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.poi.poifs.crypt.dsig.SignatureConfig

Packages that use SignatureConfig

org.apache.poi.poifs.crypt.dsig

org.apache.poi.poifs.crypt.dsig.facets

org.apache.poi.poifs.crypt.dsig.services

Uses of SignatureConfig in org.apache.poi.poifs.crypt.dsig

Methods in org.apache.poi.poifs.crypt.dsig that return SignatureConfig

 SignatureConfig
SignatureInfo.getSignatureConfig()

Methods in org.apache.poi.poifs.crypt.dsig with parameters of type SignatureConfig

 void
SignatureMarshalListener.setSignatureConfig(SignatureConfig signatureConfig)

 void
SignatureInfo.setSignatureConfig(SignatureConfig signatureConfig)

 void
SignatureConfig.SignatureConfigurable.setSignatureConfig(SignatureConfig signatureConfig)

 void
OOXMLURIDereferencer.setSignatureConfig(SignatureConfig signatureConfig)

Uses of SignatureConfig in org.apache.poi.poifs.crypt.dsig.facets

Fields in org.apache.poi.poifs.crypt.dsig.facets declared as SignatureConfig

protected  SignatureConfig
SignatureFacet.signatureConfig

Methods in org.apache.poi.poifs.crypt.dsig.facets with parameters of type SignatureConfig

static javax.xml.crypto.dsig.Reference
SignatureFacet.newReference(java.lang.String uri,
             java.util.List<javax.xml.crypto.dsig.Transform> transforms,
             java.lang.String type,
             java.lang.String id,
             byte[] digestValue,
             SignatureConfig signatureConfig)

protected static void
XAdESSignatureFacet.setCertID(org.etsi.uri.x01903.v13.CertIDType certId,
          SignatureConfig signatureConfig,
          boolean issuerNameNoReverseOrder,
          java.security.cert.X509Certificate certificate)

          Gives back the JAXB CertID data structure.

 void
SignatureFacet.setSignatureConfig(SignatureConfig signatureConfig)

Uses of SignatureConfig in org.apache.poi.poifs.crypt.dsig.services

Methods in org.apache.poi.poifs.crypt.dsig.services with parameters of type SignatureConfig

 void
TSPTimeStampService.setSignatureConfig(SignatureConfig signatureConfig)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text: a play around with multi port tcp


text:
package com.linkedin.norbert
package network
package netty

import java.net.InetSocketAddress

import com.linkedin.norbert.cluster.{InvalidNodeException, Node}
import org.jboss.netty.bootstrap.ServerBootstrap
import org.jboss.netty.channel.group.{ChannelGroup, ChannelGroupFuture}
import org.jboss.netty.channel.{Channel, ChannelFuture}
import org.specs2.mock.Mockito
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

class NettyClusterIoServerComponentSpec extends SpecificationWithJUnit with Mockito {

  trait NettyClusterIoServerSetup extends Scope with NettyClusterIoServerComponent {
    val bootstrap = mock[ServerBootstrap]
    val channelGroup = mock[ChannelGroup]
    val clusterIoServer = new NettyClusterIoServer(bootstrap, channelGroup)
  }

  "NettyClusterIoServer" should {
    "bind should fail if the node's url is in the incorrect format" in new NettyClusterIoServerSetup {
      clusterIoServer.bind(Node(1, "", false), true) must throwA[InvalidNodeException]
      clusterIoServer.bind(Node(1, "localhost", false), true) must throwA[InvalidNodeException]
      clusterIoServer.bind(Node(1, "localhost:foo", false), true) must throwA[InvalidNodeException]
    }

    "binds to the specified port" in new NettyClusterIoServerSetup {
      val address = new InetSocketAddress(31313)
      val channel = mock[Channel]
      bootstrap.bind(address) returns channel

      clusterIoServer.bind(Node(1, "localhost:31313", false), true)

      there was one(bootstrap).bind(address)
    }

    "shutdown should shutdown opened sockets" in new NettyClusterIoServerSetup {
      val channel = mock[Channel]
      val socketFuture = mock[ChannelFuture]
      val groupFuture = mock[ChannelGroupFuture]
      channel.close returns socketFuture
      channelGroup.close returns groupFuture
      socketFuture.awaitUninterruptibly returns socketFuture
      groupFuture.awaitUninterruptibly returns groupFuture
      bootstrap.bind(any[InetSocketAddress]) returns channel

      clusterIoServer.bind(Node(1, "localhost:31313", false), true)
      clusterIoServer.shutdown

      got {
        one(channel).close
        one(socketFuture).awaitUninterruptibly

        one(channelGroup).close
        one(groupFuture).awaitUninterruptibly
      }
    }
  }
}


text:
import datetime
import functools
import operator

from django.contrib import messages
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Q
from django.views.generic.base import ContextMixin

VALID_STRING_LOOKUPS = (
    "iexact",
    "contains",
    "icontains",
    "startswith",
    "istartswith",
    "endswith",
    "iendswith",
    "search",
    "regex",
    "iregex",
)

class SearchableListMixin(object):
    """
    Filter queryset like a django admin search_fields does, but with little
     more intelligence:
    if self.search_split is set to True (by default) it will split query
     to words (by whitespace)
    Also tries to convert each word to date with self.search_date_formats and
     then search each word in separate field
    e.g. with query 'foo bar' you can find object with
     obj.field1__icontains='foo' and obj.field2__icontains=='bar'

    To provide custom lookup just set one of the search_fields to tuple,
    e.g. search_fields = [('field1', 'iexact'), 'field2', ('field3', 'startswith')]

    This class is designed to be used with django.generic.ListView

    You could specify query by overriding get_search_query method
    by default this method will try to get 'q' key from request.GET
    (this can be disabled with search_use_q=False)
    """

    search_fields = ["id"]
    search_date_fields = None
    search_date_formats = ["%d.%m.%y", "%d.%m.%Y"]
    search_split = True
    search_use_q = True
    check_lookups = True

    def get_words(self, query):
        if self.search_split:
            return query.split()
        return [query]

    def get_search_fields_with_filters(self):
        fields = []
        for sf in self.search_fields:
            if isinstance(sf, str):
                fields.append((sf, "icontains"))
            else:
                if self.check_lookups and sf[1] not in VALID_STRING_LOOKUPS:
                    raise ValueError("Invalid string lookup - %s" % sf[1])
                fields.append(sf)
        return fields

    def try_convert_to_date(self, word):
        """
        Tries to convert word to date(datetime) using search_date_formats
        Return None if word fits no one format
        """
        for frm in self.search_date_formats:
            try:
                return datetime.datetime.strptime(word, frm).date()
            except ValueError:
                pass
        return None

    def get_search_query(self):
        """
        Get query from request.GET 'q' parameter when search_use_q is set to True
        Override this method to provide your own query to search
        """
        return self.search_use_q and self.request.GET.get("q", "").strip()

    def get_queryset(self):
        qs = super(SearchableListMixin, self).get_queryset()
        query = self.get_search_query()
        if query:
            w_qs = []
            search_pairs = self.get_search_fields_with_filters()
            for word in self.get_words(query):
                filters = [
                    Q(**{"%s__%s" % (pair[0], pair[1]): word}) for pair in search_pairs
                ]
                if self.search_date_fields:
                    dt = self.try_convert_to_date(word)
                    if dt:
                        filters.extend(
                            [
                                Q(**{field_name: dt})
                                for field_name in self.search_date_fields
                            ]
                        )
                w_qs.append(functools.reduce(operator.or_, filters))
            qs = qs.filter(functools.reduce(operator.and_, w_qs))
            qs = qs.distinct()
        return qs

class SortHelper(object):
    def __init__(
        self, request, sort_fields_aliases, sort_param_name, sort_type_param_name
    ):
        # Create a list from sort_fields_aliases, in case it is a generator,
        # since we want to iterate through it multiple times.
        sort_fields_aliases = list(sort_fields_aliases)

        self.initial_params = request.GET.copy()
        self.sort_fields = dict(sort_fields_aliases)
        self.inv_sort_fields = dict((v, k) for k, v in sort_fields_aliases)
        self.initial_sort = self.inv_sort_fields.get(
            self.initial_params.get(sort_param_name), None
        )
        self.initial_sort_type = self.initial_params.get(sort_type_param_name, "asc")
        self.sort_param_name = sort_param_name
        self.sort_type_param_name = sort_type_param_name

        for field, alias in self.sort_fields.items():
            setattr(
                self,
                "get_sort_query_by_%s" % alias,
                functools.partial(self.get_params_for_field, field),
            )
            setattr(
                self,
                "get_sort_query_by_%s_asc" % alias,
                functools.partial(self.get_params_for_field, field, "asc"),
            )
            setattr(
                self,
                "get_sort_query_by_%s_desc" % alias,
                functools.partial(self.get_params_for_field, field, "desc"),
            )
            setattr(
                self,
                "is_sorted_by_%s" % alias,
                functools.partial(self.is_sorted_by, field),
            )

    def is_sorted_by(self, field_name):
        return field_name == self.initial_sort and self.initial_sort_type or False

    def get_params_for_field(self, field_name, sort_type=None):
        """
        If sort_type is None - inverse current sort for field, if no sorted - use asc
        """
        if not sort_type:
            if self.initial_sort == field_name:
                sort_type = "desc" if self.initial_sort_type == "asc" else "asc"
            else:
                sort_type = "asc"
        self.initial_params[self.sort_param_name] = self.sort_fields[field_name]
        self.initial_params[self.sort_type_param_name] = sort_type
        return "?%s" % self.initial_params.urlencode()

    def get_sort(self):
        if not self.initial_sort:
            return None
        sort = "%s" % self.initial_sort
        if self.initial_sort_type == "desc":
            sort = "-%s" % sort
        return sort

class SortableListMixin(ContextMixin):
    """
    You can provide either sort_fields as a plain list like
     ['id', 'some', 'foo__bar', ...]
    or, if you want to hide original field names you can provide list of tuples with
    alias that will be used:
    [('id', 'by_id'), ('some', 'show_this'), ('foo__bar', 'bar')]

    If sort_param_name exists in query but sort_type_param_name is omitted queryset
     will be sorted as 'asc'
    """

    sort_fields = []
    sort_fields_aliases = []
    sort_param_name = "o"
    sort_type_param_name = "ot"

    def get_sort_fields(self):
        if self.sort_fields:
            return zip(self.sort_fields, self.sort_fields)
        return self.sort_fields_aliases

    def get_sort_helper(self):
        return SortHelper(
            self.request,
            self.get_sort_fields(),
            self.sort_param_name,
            self.sort_type_param_name,
        )

    def _sort_queryset(self, queryset):
        self.sort_helper = self.get_sort_helper()
        sort = self.sort_helper.get_sort()
        if sort:
            queryset = queryset.order_by(sort)
        return queryset

    def get_queryset(self):
        qs = super(SortableListMixin, self).get_queryset()
        if self.sort_fields and self.sort_fields_aliases:
            raise ImproperlyConfigured(
                "You should provide sort_fields or sort_fields_aliaces but not both"
            )
        return self._sort_queryset(qs)

    def get_context_data(self, **kwargs):
        context = {}
        if hasattr(self, "sort_helper"):
            context["sort_helper"] = self.sort_helper
        context.update(kwargs)
        return super(SortableListMixin, self).get_context_data(**context)

class SuccessMessageWithInlinesMixin(object):
    """
    Adds a success message on successful form submission.
    """

    success_message = ""

    def forms_valid(self, form, inlines):
        response = super(SuccessMessageWithInlinesMixin, self).forms_valid(
            form, inlines
        )
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data


text:
Invoking Pants Build
====================

This page discusses some advanced features of invoking the Pants build
tool on the command line. We assume you already know the
[[basic command-line structure|pants('src/docs:first_tutorial')]],
something like:

    :::bash
    $ ./pants test.junit --fail-fast bundle path/to/target path/to/another/target

For a full description of specifying target addresses, see
[[Target Addresses|pants('src/docs:target_addresses')]].
For a list of Pants' goals and their options, see the
Options Reference.

Order of Arguments
------------------

A simple Pants command line looks like <tt>./pants <var>goal</var> <var>target</var></tt>.
A less-simple Pants command looks like:

    :::bash
    ./pants <global options> <goal1> <options for goal1> <goal2> <options for goal2> \
            <target1> <target2> [-- pass-through options for last goal]

You can specify one or more goals. You can specify options for any goal right after that goal's
name:

    :::bash
    $ ./pants list --sep='|' examples/src/python/example:
    examples/src/python/example:readme|examples/src/python/example:pex_design|examples/sr...

Some goals are made up of tasks; to specify an option for that task, use the dotted
_goal.task_ notation:

    :::bash
    # compile src, keeping Java compile's "scratch files"
    ./pants compile.java --no-delete-scratch src::

You can specify one or more targets to operate upon. Target specifications come after goals
and goal options on the command line.

Global options are the options that `./pants -h` lists, options that affect the whole
Pants run, e.g., `-ldebug`. Specify global options after "goal".

When setting a value for an option, beware spaces. For example, `-l debug` and `--level debug`
don't do what you want. If you're tempted to put a space between an option and its value, use an
equals sign instead: `--level=debug`, `-ldebug`, and even `-l=debug` all work.

Some goals and tasks take "passthrough" args. That is, you can specify command-line args that are
passed through to some tool that Pants invoke in turn. These are specified last on the command
line after a double-hyphen like `-- foo bar` and are passed to the last goal specified. E.g., to
pass `-k list` to `pytest` (to say "only run tests whose names contain `list`") you could invoke:

    ./pants test.pytest tests/python/pants_test/tasks -- -k list

You could use `test` instead of `test.pytest` above; Pants then applies the
passthrough args to tools called by all of `test`, not just `test.pytest`.
This gets tricky. We happen to know we can pass `-k list` here, that `pytest` accepts passthrough
args, and that this `test` invocation upon `tests/python/...` won't invoke any other tools
(assuming nobody hid a `junit` test in the `python` directory).

Setting Options Other Ways
--------------------------

Instead of passing an option on the command line, you can set an environment variable or change
an option in an `.ini` file. Pants "looks" for an option value on the command line, environment
variable, and `.ini` file; it uses the first it finds.
For a complete, precedence-ordered list of places Pants looks for option values, see the
`Options` docstring in [src/python/pants/option/options.py]
(https://github.com/pantsbuild/pants/blob/master/src/python/pants/option/options.py).

### `PANTS_...` Environment Variables

Each goal option also has a corresponding environment variable. For example, either of these
commands opens a coverage report in your browser:

    :::bash
    $ ./pants test.junit --coverage-html-open examples/tests/java/org/pantsbuild/example::

    $ PANTS_TEST_JUNIT_COVERAGE_HTML_OPEN=1 ./pants test examples/tests/java/org/pantsbuild/example::

Pants checks for an environment variable whose name is `PANTS` + the goal name (or goal+task name)
+ the option name; all of these in all-caps, joined by underscores (instead of dots or hyphens).

### `pants.ini` Settings File

Pants can also read command-line options (and other options) from an `.ini` file. For example, if
your `pants.ini` file contains

    [test.junit]
    coverage_html_open: True

...then whenever Pants carries out the `test.junit` task, it will behave as if you passed
`test.junit --coverage-html-open`. If an environment variable and an `.ini` configuration both
specify a value for some option, the environment variable "wins".

### Overlay `.ini` Files with `--config-overrides`

Sometimes it's convenient to keep `.ini` settings in more than one file. Perhaps you usually
operate Pants in one "mode", but occasionally need to use a tweaked set of settings.

Use the `--config-overrides` command-line option to specify a second `.ini` file. Each of
this `.ini` file's values override the corresponding value in `pants.ini`, if any.
For example, if your `pants.ini` contains the section

    [test.junit]
    coverage_html_open: True
    debug: False

...and you invoke `--config-overrides=quick.ini` and your `quick.ini` says

    [test.junit]
    coverage_html_open: False
    skip: True

...then Pants will act as if you specified

    [test.junit]
    coverage_html_open: False
    skip: True
    debug: False


text:
var mongoose = require('mongoose');

var tabActiveSchema = new mongoose.Schema({
    orderNo: {type: Number},
    location: {type: String},
    tabId: {type: mongoose.Schema.Types.ObjectId, ref: 'tabs'},
    courseId: {type: mongoose.Schema.Types.ObjectId, ref: 'courses'},

    isActive: {type: Boolean, required: true, default: false},

    dateAdded: {type: Date},
    dateUpdated: {type: Date}
}, {
    usePushEach: true
});

tabActiveSchema.pre('save', function (next) {
    var now = new Date();
    this.dateUpdated = now;
    if (!this.dateAdded) {
        this.dateAdded = now;
    }
    next();
});

tabActiveSchema.pre('update', function (next) {
    this.dateUpdated = new Date();
    next();
});

var tab = mongoose.model('tabsActive', tabActiveSchema);

module.exports = tab;


text:
package com.twosigma.beakerx.chart.treemap;

public enum Mode {
  SQUARIFY("squarify"),//rectangular subdivision; squareness controlled via the target ratio.
  SLICE("slice"),// horizontal subdivision.
  DICE("dice"),// vertical subdivision.
  SLICE_DIC("slice-dic");// alternating between horizontal and vertical subdivision.

  private String jsName;

  Mode() {
  }

  Mode(String jsName) {
    this.jsName = jsName;
  }

  public String getJsName() {
    return jsName;
  }
}


text:
package org.jbb.lib.commons;

import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.resourceloading.PlatformResourceBundleLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
@ComponentScan
public class CommonsConfig {

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        PlatformResourceBundleLocator rbLocator =
                new PlatformResourceBundleLocator(ResourceBundleMessageInterpolator.USER_VALIDATION_MESSAGES, null, true);
        LocalValidatorFactoryBean validFactory = new LocalValidatorFactoryBean();
        validFactory.setMessageInterpolator(new ResourceBundleMessageInterpolator(rbLocator));
        return validFactory;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ua.pp.myprojects.zsudriver">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/MyTheme">
        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity android:name=".activities.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activities.AddJournalItemActivity" />
        <activity
            android:name=".activities.JournalActivity"
            android:label="@string/title_activity_journal"
            android:parentActivityName=".activities.MainActivity"
            android:theme="@style/MyTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ua.pp.myprojects.zsudriver.activities.MainActivity" />
        </activity>
        <activity android:name=".activities.MilUnitCarsActivity" />
        <activity android:name=".activities.NewUserActivity" />
        <activity android:name=".activities.EditJournalItemActivity"></activity>
    </application>

</manifest>


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="True" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="robots" content="index, follow" />

  <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro|Source+Sans+Pro:300,400,400i,700" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="http://flex.alxd.me/blog/theme/stylesheet/style.min.css">

  <link rel="stylesheet" type="text/css" href="http://flex.alxd.me/blog/theme/pygments/monokai.min.css">
  <link rel="stylesheet" type="text/css" href="http://flex.alxd.me/blog/theme/font-awesome/css/font-awesome.min.css">

    <link href="http://flex.alxd.me/blog/static/custom.css" rel="stylesheet">

    <link href="http://flex.alxd.me/blog/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Flex Atom">

    <meta name="theme-color" content="#333333">

    <meta name="msapplication-navbutton-color" content="#333333">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <meta name="msapplication-TileColor" content="#333333">

<meta name="author" content="Alexandre Vicenzi" />
<meta name="description" content="Flex theme 2.1.0 comes with features that I was delaying for so long. Flex 2.1.0 adds support for Google AdSense. If you choose wisely, ads are a way to win some money, but if not, you may loose your users due to excessive use of ads …" />
<meta name="keywords" content="pelican, python, theme">

<meta property="og:site_name" content="Flex"/>
<meta property="og:title" content="Flex 2.1.0"/>
<meta property="og:description" content="Flex theme 2.1.0 comes with features that I was delaying for so long. Flex 2.1.0 adds support for Google AdSense. If you choose wisely, ads are a way to win some money, but if not, you may loose your users due to excessive use of ads …"/>
<meta property="og:locale" content="en_US"/>
<meta property="og:url" content="http://flex.alxd.me/blog/flex-pelican-theme-update-2-1.html"/>
<meta property="og:type" content="article"/>
<meta property="article:published_time" content="2016-11-16 08:00:00-05:00"/>
<meta property="article:modified_time" content="2016-11-16 08:00:00-05:00"/>
<meta property="article:author" content="http://flex.alxd.me/blog/author/alexandre-vicenzi.html">
<meta property="article:section" content="News"/>
<meta property="article:tag" content="pelican"/>
<meta property="article:tag" content="python"/>
<meta property="article:tag" content="theme"/>
<meta property="og:image" content="http://flex.alxd.me/blog/images/flex-screenshot.png">

  <title>Flex – Flex 2.1.0</title>

Flex

The minimalist Pelican theme

About

Contact

          Home

      Archives
      Categories
      Tags

          Atom

Flex 2.1.0

          Posted on November 16, 2016 in News

Flex theme 2.1.0 comes with features that I was delaying for so long.

Flex 2.1.0 adds support for Google AdSense.

If you choose wisely, ads are a way to win some money, but if not, you may loose your users due to excessive use of ads.

Flex has six places for ads. Google recommends up to 3 ads per page. There is ads page only, and banner that appears on all pages.
Below you can see how to enable ads in your pelican configuration file.

GOOGLE_ADSENSE = {
    'ca_id': 'ca-pub-1234567890',    # Your AdSense ID
    'page_level_ads': True,          # Allow Page Level Ads (mobile)
    'ads': {
        'aside': '1234561',          # Side bar banner (all pages)
        'main_menu': '1234562',      # Banner before main menu (all pages)
        'index_top': '1234563',      # Banner after main menu (index only)
        'index_bottom': '1234564',   # Banner before footer (index only)
        'article_top': '1234565',    # Banner after article title (article only)
        'article_bottom': '1234566', # Banner after article content (article only)
    }
}

Version 2.1.0 also comes with new translations. You can see available translations here.

Hope you enjoy this version.

      pelican
      python
      theme

    Like this article? Share it with your friends!

        Please enable JavaScript to view comments.

  ©  2018 - This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License

    Powered by Pelican - Flex theme by Alexandre Vicenzi


text:
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
"""
from __future__ import division

class Solution(object):

    def isEven(self, number):
        return number % 2 == 0

    def findMedian(self, nums):
        length = len(nums)
        if self.isEven(length):
            return (nums[length // 2] + nums[length // 2 + 1]) / 2
        else:
            return nums[length // 2]

    # we have to keep the number of list to always be even or odd
    def cutHalf(self, nums, is_up):
        middle_index = len(nums) // 2
        if isEven(len(nums)):
            if is_up:
                return nums[middle_index:]
            else:
                return nums[0:middle_index]
        else:
            if is_up:
                return nums[middle_index:]
            else:
                return nums[0:middle_index + 1]

    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        median1 = self.findMedian(nums1)
        median2 = self.findMedian(nums2)
        if median1 == median2:
            return median1
        elif median1 > median2:
            return self.findMedianSortedArrays(nums1[len(nums1) // 2:], nums2[0:len(nums2) // 2+1])
        else:
            return self.findMedianSortedArrays(nums1[len(nums1) // 2:], nums2[len(nums2) // 2])


text: create index cix_headingved_key on headingved using btree (key);


text:
package org.zouzias.swaggerjaxrswink.model;

import com.wordnik.swagger.annotations.*;

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

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "Pet")
public class Pet {
  private long id;
  private Category category;
  private String name;
  private List<String> photoUrls = new ArrayList<String>();
  private List<Tag> tags = new ArrayList<Tag>();
  private String status;

  @XmlElement(name = "id")
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  @XmlElement(name = "category")
  public Category getCategory() {
    return category;
  }

  public void setCategory(Category category) {
    this.category = category;
  }

  @XmlElement(name = "name")
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @XmlElementWrapper(name = "photoUrls")
  @XmlElement(name = "photoUrl")
  public List<String> getPhotoUrls() {
    return photoUrls;
  }

  public void setPhotoUrls(List<String> photoUrls) {
    this.photoUrls = photoUrls;
  }

  @XmlElementWrapper(name = "tags")
  @XmlElement(name = "tag")
  public List<Tag> getTags() {
    return tags;
  }

  public void setTags(List<Tag> tags) {
    this.tags = tags;
  }

  @XmlElement(name = "status")
  @ApiModelProperty(value = "pet status in the store", allowableValues = "available,pending,sold")
  public String getStatus() {
    return status;
  }

  public void setStatus(String status) {
    this.status = status;
  }
}


text:
module Net
  class HTTP
    # Posts HTML form data to the URL, but allow for SSL.
    #
    # The existing 1.8.x implementaiton via post_form does not allow for SSL connections
    #
    # @param [URI] url
    # @param [Hash] POST data
    def HTTP.post_form_with_ssl(url, params)
      req = Post.new(url.path)
      req.form_data = params
      req.basic_auth url.user, url.password if url.user
      http = new(url.host, url.port)
      http.use_ssl = (url.scheme == 'https')
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
      http.ca_file = File.expand_path('../../../../vendor/curl-cacert.pem', __FILE__)
      http.start {|http|
        http.request(req)
      }
    end
  end
end