text:
#include "cenTimer.h"

#include "../../common/commons.h"
#include "../../common/error/error.h"

float timeDiviserToFrequencyInHertz(float timeDiviser) {
    return TIME_DIVIDER_1_HERTZ / timeDiviser;
}

unsigned long getTime(Timer* timer) {
    return timer->time;
}

void setTime(Timer* timer, unsigned long value) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return;
    }
    timer->time = value;
}

// STARTS / STOP

void startTimer(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return;
    }
    timer->enabled = true;
}

void stopTimer(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return;
    }
    timer->enabled = false;
}

// MARK

unsigned long markTimer(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return 0L;
    }
    if (!timer->enabled) {
        writeError(TIMER_MARK_WHEREAS_DISABLED);
        return 0L;
    }
    timer->markTime = timer->time;
    return timer->markTime;
}

unsigned long getTimeSinceLastMark(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return 0L;
    }
    return (timer->time - timer->markTime);
}

bool timeout(Timer* timer, unsigned long timeToCheck) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return false;
    }
    unsigned long timeSinceLastMarkValue = getTimeSinceLastMark(timer);
    return timeSinceLastMarkValue > timeToCheck;
}

// LOCK / UNLOCK

void lockAndWaitForTimer(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return;
    }
    // we lock the timer to be sure that he will not be fired
    timer->lock = true;

    // we wait after the end of the timer callback
    // do be sure that variables are ok
    while (timer->working) {
        // do nothing
    }
}

void lockTimer(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return;
    }
    timer->lock = true;
}

void unlockTimer(Timer* timer) {
    if (timer == NULL) {
        writeError(TIMER_NULL);
        return;
    }
    timer->lock = false;
}


text:
"use strict";
module.exports = function(Promise) {
    Promise.prototype.call = function Promise$call(propertyName) {
        var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}

        return this._then(function(obj) {
                return obj[propertyName].apply(obj, args);
            },
            void 0,
            void 0,
            void 0,
            void 0,
            this.call
       );
    };

    function Promise$getter(obj) {
        var prop = typeof this === "string"
            ? this
            : ("" + this);
        return obj[prop];
    }
    Promise.prototype.get = function Promise$get(propertyName) {
        return this._then(
            Promise$getter,
            void 0,
            void 0,
            propertyName,
            void 0,
            this.get
       );
    };
};

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Curvy Neighbor Bangs Black Stranger
titleinfo: pornvd
desc: Watch Curvy Neighbor Bangs Black Stranger. Pornhub is the ultimate xxx porn and sex site.
---

Curvy Neighbor Bangs Black Stranger

Watch Curvy Neighbor Bangs Black Stranger. Pornhub is the ultimate xxx porn and sex site.


text:
package cz.ivoa.vocloud.uwsparser;

import cz.ivoa.vocloud.uwsparser.model.UWSJob;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author voadmin
 */
public class UWSParser {

    private static final Logger logger = Logger.getLogger(UWSParser.class.getName());

    public UWSJob parseJob(String xml) {
        if (xml == null) {
            logger.log(Level.SEVERE, "No XML to parse");
            return null;
        }
        try {
            return parseJobUsingJAXB(xml);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "cant parse uwsJob", e);
            return null;
        }
    }

    UWSJob parseJobUsingJAXB(String xml) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(UWSJob.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        UWSJob uwsJob = (UWSJob) unmarshaller.unmarshal(new ByteArrayInputStream(xml.getBytes()));

//        //debugging reasons only
//        Marshaller marshaller = jc.createMarshaller();
//        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//        marshaller.marshal(uwsJob, System.out);
        return uwsJob;
    }

    @Deprecated
    UWSJob parseJobUsingSax(String xml) {
        UWSJobXmlHandler handler = new UWSJobXmlHandler();
        try {
            XMLReader saxParser = XMLReaderFactory.createXMLReader();
            saxParser.setContentHandler(handler);
            saxParser.setErrorHandler(handler);
            saxParser.parse(xml);
        } catch (IOException | SAXException ex) {
            logger.log(Level.WARNING, "error when parsing \n" + xml);
            logger.log(Level.WARNING, null, ex);
        }

        return handler.getJob();
    }
}


text:
<?php $this->load->view('globales/terminos-y-condiciones'); ?>
<?php $this->load->view('globales/politicas-de-privacidad'); ?>
<?php //if($this->permissions->get('hide_footer')) echo 'style="height:118px;"' ?>

Mensajes de Voz S.A.S - www.mensajesdevoz.co - Bogotá, Colombia

   <?php //if(!$this->permissions->get('hide_footer')): ?>

    <?php //endif; ?>

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">


text:
package it.redhat.handlers;

import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.Container;

/**
 * Created by samuele on 9/5/14.
 */
public class GetMemberByIdHandler extends ResultsHandler implements Handler<HttpServerRequest> {

    public GetMemberByIdHandler(Vertx vertx, Container container) {
       super(vertx, container);
    }

    @Override
    public void handle(HttpServerRequest httpServerRequest) {
        String id = httpServerRequest.params().get("id");

        if(id != null) {
            JsonObject select = new JsonObject()
                    .putString("action","prepared")
                    .putString("statement","SELECT * FROM Member WHERE id = ?")
                    .putArray("values" , new JsonArray().add(Integer.parseInt(id)));

            executeQuerySendResponse(select,httpServerRequest);
        }

    }
}


text: A raytracer in Rust


text:
{-# LANGUAGE Arrows
        , TypeOperators
        , RecordWildCards
        , OverloadedStrings
        #-}
module Document.Phase.Structures where

    --
    -- Modules
    --
import Document.Pipeline
import Document.Phase as P
import Document.Phase.Parameters
import Document.Phase.Types
import Document.Scope

import Logic.Expr

import UnitB.Syntax as AST

import Logic.Theories

    --
    -- Libraries
    --
import Control.Arrow hiding (left,app) -- (Arrow,arr,(>>>))
import Control.Lens as L hiding ((|>),(<.>),(<|),indices,Context)

import           Control.Monad
import           Control.Monad.Except
import           Control.Monad.Reader.Class

import qualified Data.Graph.Bipartite as G
import           Data.List as L hiding ( union, insert, inits )
import           Data.Map   as M hiding ( map, (\\) )
import qualified Data.Map   as M

import Text.Printf.TH

import Utilities.Syntactic

run_phase0_blocks :: Pipeline MM () (MMap MachineP0)
run_phase0_blocks = withInput $ proc doc -> do
                let mch = M.map (const ()) $ getMachineInput doc
                    _ctx = M.map (const ()) $ getContextInput doc
                    m0 = M.mapWithKey (const . MachineP0 mch) mch
                    _c0 = M.map (const $ TheoryP0 ()) _ctx
                returnA -< m0

run_phase1_types :: Pipeline MM (MMap MachineP0) SystemP1
run_phase1_types = proc p0 -> do
    ts <- set_decl      -< p0
    e <- arr (fmap $ unionsWith (++)) <<< run_phase
        [ event_splitting
        , event_decl
        , event_merging  ] -< p0
    r  <- refines_mch   -< p0
    verifSet <- verif_setting_mch   -< p0
    it <- import_theory -< p0
    refs <- triggerP <<< liftP' (make_all_tables refClash) -< r
    verifSet' <- triggerP <<< liftP' (make_all_tables verifClash) -< verifSet
    let _ = refs :: MMap (Map () (MachineId,LineInfo))
    r_ord <- topological_order -< mapMaybe (M.lookup ()) refs
    let t = M.map fst <$> ts
        s = M.map snd <$> ts
        -- f = _ :: Int
    evts' <- liftP' $ make_all_tables evtClash  -< inheritEvents r_ord <$> e
    types <- liftP' $ make_all_tables setClash  -< inherit r_ord  <$> t
    imp_th <- liftP' $ make_all_tables thyClash -< inherit r_ord  <$> it
    let f m = G.fromList
                (leftVerts m) (rightVerts m)
                (edges m)
        leftVerts m = concatMap (L.map (,()).snd) m
        rightVerts m = L.map ((,()).fst) m
        edges m = concatMap (\(x,xs) -> L.map (,x) xs) m
        makeGraphs = traverse f
    evts'   <- triggerP -< evts'
    let evts'' :: MMap [(SkipOrEvent, [SkipOrEvent])]
        evts'' = addSkip evts'
        addSkip = M.map (((Left SkipEvent,[Left SkipEvent]):).M.elems.M.map ((Right *** ifEmpty).fst))
        ifEmpty [] = [Left SkipEvent]
        ifEmpty xs = L.map Right xs
    evts'   <- triggerP -< makeGraphs evts''
    -- let _ = _
    types   <- triggerP -< types
    imp_th' <- triggerP -< imp_th
    s       <- triggerP -< s
    --     -- BIG FLAG
    --     -- the creation of p1 won't detect clashes between type names, it will merely overshadow
    --     -- some types with (hopefully) the most local types
    --     -- BIG FLAG
    let _ = evts' :: MMap (G.BiGraph SkipOrEvent () ())
        f th = M.unions $ map (view AST.types) $ M.elems th
        basic = preludeTheories
        imp_th = M.map (union basic . M.map fst) imp_th'
        all_types = M.intersectionWith (\ts th -> M.map fst ts `union` f th) types imp_th
        p1 = make_phase1 <$> p0 <.> imp_th
                         <.> (M.map (M.map fst) types)
                         <.> all_types
                         <.> (verifSet' & traverse.traverse %~ fst)
                         <.> s <.> evts'
    returnA -< SystemP r_ord p1
  where
    evtClash = [s|Multiple events with the name %s|] . pretty
    setClash = [s|Multiple sets with the name %s|] . render
    thyClash _   = "Theory imported multiple times"
    refClash _   = "Multiple refinement clauses"
    verifClash _ = "Multiple verification timeouts"

make_phase1 :: MachineP0
            -> Map Name Theory
            -> Map Name Sort
            -> Map Name Sort
            -> Map () Float
            -> [(Name, PostponedDef)]
            -> G.BiGraph SkipOrEvent () () -- Map Label (EventId, [EventId])
            -> MachineP1
make_phase1 _p0 _pImports _pTypes _pAllTypes
        timeout _pSetDecl evts = MachineP1 { .. }
    where
        _pEventRef = G.mapBothWithKey (const.EventP1) (const.EventP1) evts
        _pContext    = TheoryP1 { .. }
        _t0          = TheoryP0 ()
        _pVerTimeOut = M.findWithDefault 1 () timeout

set_decl :: MPipeline MachineP0
            ( [(Name,Sort,LineInfo)]
            , [(Name,PostponedDef)] )
set_decl = machineCmd "\\newset" $ \(Identity (SetName tag)) _m _ -> do
            let name     = tag
                new_sort = Sort tag (asInternal name) 0
                new_type = Gen new_sort []
                new_def = makeDef [] name [] (set_type new_type)
                                    $ zlift (set_type new_type) ztrue
            li <- ask
            return ([(tag,new_sort,li)],[(tag,(new_def,Local,li))])

event_splitting :: MPipeline MachineP0 [(Label, (EventId,[EventId]), LineInfo)]
event_splitting = machineCmd "\\splitevent" $ \(Abs aevt, cevts) _m _p0 -> do
    let _ = aevt  :: EventId
        _ = cevts :: [Conc EventId]
    li <- ask
    when (any (Conc "skip" ==) cevts) $ do
        throwError [Error "invalid event name: 'skip' is a reserved name" li]
    return [(as_label c,(c,[aevt]),li) | Conc c <- cevts]

event_merging :: MPipeline MachineP0 [(Label, (EventId,[EventId]), LineInfo)]
event_merging = machineCmd "\\mergeevents" $ \(aevts, Conc cevt) _m _p0 -> do
    let _ = aevts :: [Abs EventId]
        _ = cevt  :: EventId
    li <- ask
    when (cevt == "skip") $ do
        throwError [Error "invalid event name: 'skip' is a reserved name" li]
    return [(as_label cevt,(cevt,map getAbstract aevts),li)]

event_decl :: MPipeline MachineP0 [(Label, (EventId,[EventId]), LineInfo)]
event_decl = machineCmd "\\newevent" $ \(Identity (Conc evt)) _m _ -> do
            li <- ask
            when (evt == "skip") $ do
                throwError [Error "invalid event name: 'skip' is a reserved name" li]
            return [(as_label evt,(evt,[]),li)]

verif_setting_mch :: MPipeline MachineP0 [((), Float, LineInfo)]
verif_setting_mch = machineCmd "\\setTimeout" $ \(Identity (Factor to)) _cmch (MachineP0 _ms _) -> do
            li <- ask
            return [((),to,li)]

refines_mch :: MPipeline MachineP0 [((), MachineId, LineInfo)]
refines_mch = machineCmd "\\refines" $ \(Identity amch) cmch (MachineP0 ms _) -> do
            li <- ask
            unless (amch `M.member` ms)
                $ throwError [Error ([s|Machine %s refines a non-existant machine: %s|] (pretty cmch) (pretty amch)) li]
                -- check that mch is a machine
            return [((),amch,li)]

import_theory :: MPipeline MachineP0 [(Name, Theory, LineInfo)]
import_theory = machineCmd "\\with" $ \(Identity (TheoryName th_name)) _m _ -> do
        let th = supportedTheories
            msg = [s|Undefined theory: %s |]
                -- add suggestions
        li <- ask
        case th_name `M.lookup` th of
            Nothing -> throwError [Error (msg $ render th_name) li]
            Just th -> return [(th_name,th,li)]


text:
# -*- coding: utf-8 -*-
"""

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
 This script initializes the plugin, making it known to QGIS.
"""

def name():
    return "MinMaxRaster"

def description():
    return "Finds Highest and/or lowest point within a vector polygon on a Digital Elevation Model"

def version():
    return "Version 1.0"

def icon():
    return "icon.png"

def qgisMinimumVersion():
    return "2.0"

def author():
    return "Jakob Hvitnov"

def email():
    return "n/a"

def classFactory(iface):
    # load MinMaxRaster class from file MinMaxRaster
    from MinMaxRaster import MinMaxRaster
    return MinMaxRaster(iface)


text:
package com.sequenceiq.cloudbreak.reactor.handler.consumption;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.common.event.Selectable;
import com.sequenceiq.cloudbreak.eventbus.Event;
import com.sequenceiq.cloudbreak.reactor.api.event.stack.consumption.AttachedVolumeConsumptionCollectionUnschedulingFailed;
import com.sequenceiq.cloudbreak.reactor.api.event.stack.consumption.AttachedVolumeConsumptionCollectionUnschedulingRequest;
import com.sequenceiq.cloudbreak.reactor.api.event.stack.consumption.AttachedVolumeConsumptionCollectionUnschedulingSuccess;
import com.sequenceiq.cloudbreak.service.consumption.ConsumptionService;
import com.sequenceiq.cloudbreak.service.stack.StackDtoService;
import com.sequenceiq.flow.event.EventSelectorUtil;
import com.sequenceiq.flow.reactor.api.handler.ExceptionCatcherEventHandler;
import com.sequenceiq.flow.reactor.api.handler.HandlerEvent;

@Component
public class AttachedVolumeConsumptionCollectionUnschedulingHandler extends
        ExceptionCatcherEventHandler<AttachedVolumeConsumptionCollectionUnschedulingRequest> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AttachedVolumeConsumptionCollectionUnschedulingHandler.class);

    @Inject
    private StackDtoService stackDtoService;

    @Inject
    private ConsumptionService consumptionService;

    @Override
    public String selector() {
        return EventSelectorUtil.selector(AttachedVolumeConsumptionCollectionUnschedulingRequest.class);
    }

    @Override
    protected Selectable defaultFailureEvent(Long resourceId, Exception e, Event<AttachedVolumeConsumptionCollectionUnschedulingRequest> event) {
        return new AttachedVolumeConsumptionCollectionUnschedulingFailed(resourceId, e);
    }

    @Override
    protected Selectable doAccept(HandlerEvent<AttachedVolumeConsumptionCollectionUnschedulingRequest> event) {
        LOGGER.debug("Attached volume consumption collection unscheduling flow step started.");
        AttachedVolumeConsumptionCollectionUnschedulingRequest request = event.getData();

        Long resourceId = request.getResourceId();
        consumptionService.unscheduleAttachedVolumeConsumptionCollectionForStackIfNeeded(stackDtoService.getById(resourceId));

        LOGGER.debug("Attached volume consumption collection unscheduling flow step finished.");
        return new AttachedVolumeConsumptionCollectionUnschedulingSuccess(resourceId);
    }

}


text:
module.exports = {
  // Use newer version of jsdom
  testEnvironment: 'jest-environment-jsdom-sixteen',

  setupFiles: [
    // It contains some polyfills such as the isomorphic fetch
    'react-app-polyfill/jsdom',
    'jest-config-accurapp/setup',
  ],

  transform: {
    // Wrapper around babel-jest
    '\\.(js|jsx|ts|tsx)$': 'jest-config-accurapp/babelTransform',

    // Transform simple css files in an empty object
    // https://jestjs.io/docs/en/webpack.html
    '\\.css$': 'jest-config-accurapp/cssTransform',

    // Transform all other files into just the filename string
    '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': 'jest-config-accurapp/fileTransform',
  },

  // Don't transform css modules into an empty object
  transformIgnorePatterns: ['\\.module\\.(css)$'],

  // Instead use identity-obj-proxy which outputs the classnames
  moduleNameMapper: {
    '\\.module\\.(css)$': 'identity-obj-proxy',
  },

  watchPlugins: [
    // Filter your tests by file name or test name
    'jest-watch-typeahead/filename',
    'jest-watch-typeahead/testname',
  ],
}


text:
import Decimal from 'decimal.js'
import isEmpty from 'lodash/isEmpty'

import { AMaaSModel } from '../../core'

/**
 * Class representing a TransactionPNL
 * @memberof module:transactions
 * @extends module:core.AMaaSModel
 */
class TransactionPNL extends AMaaSModel {
  /**
   * Construct a new TransactionPNL object
   * @param {object} params - TransactionPNL creation options
   * @param {number} params.assetManagerId - ID of the TransactionPNL's Asset Manager
   * @param {string} params.bookId - ID of TransactionPNL's book
   * @param {string} params.assetId - ID of the TransactionPNL's Asset
   * @param {string} params.businessDate - Date of TransactionPNL
   * @param {string} params.pnlTimeStamp - Proft & Loss Timestamp
   * @param {number} params.clientId - Id of TransactionPNL's client
   * @param {string} params.currency - Currency of TransactionPNL
   * @param {Decimal} params.quantity - Quantity of TransactionPNL
   * @param {string} params.transactionId - ID of the TransactionPNL's Transaction
   * @param {Object} params.YTD - YTD PnL
   * @param {Object} params.MTD - MTD PnL
   * @param {Object} params.DTD - DTD PnL
   * @param {string} params.createdBy - Creator of TransactionPNL
   * @param {string} params.updatedBy - Latest user who updated the TransactionPNL
   * @param {string} params.createdTime - Created Time of the TransactionPNL
   * @param {string} params.updatedTime - Updated Time of the TransactionPNL
   * @param {number} params.version - Version of the TransactionPNL
   */
  constructor({
    assetManagerId,
    bookId,
    assetId,
    businessDate,
    pnlTimestamp,
    clientId,
    currency,
    quantity,
    transactionId,
    YTD,
    MTD,
    DTD,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version
  }) {
    super({
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
    function castPNL(pnl) {
      if (isEmpty(pnl)) return {}
      return {
        ...pnl,
        unrealisedPnl: new Decimal(pnl.unrealisedPnl || 0),
        fxPnl: new Decimal(pnl.fxPnl || 0),
        totalPnl: new Decimal(pnl.totalPnl || 0),
        assetPnl: new Decimal(pnl.assetPnl || 0),
        realisedPnl: new Decimal(pnl.realisedPnl || 0)
      }
    }
    Object.defineProperties(this, {
      _YTD: { writable: true, enumerable: false },
      YTD: {
        get: () => this._YTD,
        set: (newYTD = {}) => {
          this._YTD = castPNL(newYTD)
        },
        enumerable: true
      },
      _MTD: { writable: true, enumerable: false },
      MTD: {
        get: () => this._MTD,
        set: (newMTD = {}) => {
          this._MTD = castPNL(newMTD)
        },
        enumerable: true
      },
      _DTD: { writable: true, enumerable: false },
      DTD: {
        get: () => this._DTD,
        set: (newDTD = {}) => {
          this._DTD = castPNL(newDTD)
        },
        enumerable: true
      },
      _quantity: { writable: true, enumerable: false },
      quantity: {
        get: () => this._quantity,
        set: (newQuantity = 0) => {
          this._quantity = new Decimal(newQuantity || 0)
        },
        enumerable: true
      }
    })
    this.assetManagerId = assetManagerId
    this.bookId = bookId
    this.assetId = assetId
    this.businessDate = businessDate
    this.pnlTimestamp = pnlTimestamp
    this.clientId = clientId
    this.currency = currency
    this.quantity = quantity
    this.transactionId = transactionId
    this.YTD = YTD
    this.MTD = MTD
    this.DTD = DTD
  }
}

export default TransactionPNL


text:
#ifndef CAFFE2_OPERATORS_FUSED_ROWWISE_8BIT_CONVERSION_OPS_H_
#define CAFFE2_OPERATORS_FUSED_ROWWISE_8BIT_CONVERSION_OPS_H_

#include "caffe2/core/context.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/operators/reducer_functors.h"
#include "caffe2/utils/math.h"

namespace caffe2 {

#define IS_LITTLE_ENDIAN                                      \
  [] {                                                        \
    const int32_t kValue = 1;                                 \
    return reinterpret_cast<const uint8_t*>(&kValue)[0] == 1; \
  }()

template <class Context>
class FloatToFused8BitRowwiseQuantizedOp : public Operator<Context> {
 public:
  static constexpr float kEqualityThreshold = 1e-7f;
  static constexpr float kEpsilon = 1e-8f;

  USE_OPERATOR_CONTEXT_FUNCTIONS;
  USE_SIMPLE_CTOR_DTOR(FloatToFused8BitRowwiseQuantizedOp)

  bool RunOnDevice() override {
    CAFFE_ENFORCE(IS_LITTLE_ENDIAN, "Unsupported endianness");

    const auto& input = Input(DATA_FLOAT);
    auto* output = Output(DATA_FUSED_SCALE_BIAS_INT8);

    const auto input_rows = input.dim(0);
    const auto input_columns = input.dim(1);
    CAFFE_ENFORCE_EQ(input.ndim(), 2, "Expect input to be a matrix");

    // The "fused" representation stores the scale and bias with the row-wise
    // quantized data in one tensor. Since we quantize with 8 bits (1 byte) and
    // represent the scale and bias with 32-bit floats, we'll use the last 8
    // bytes of each row for scale (4 bytes) and bias (4 bytes).
    // | ... int8 data ... | scale | bias |
    // | number_of_columns |  4B   |  4B  |
    const std::vector<TIndex> output_dimensions = {input_rows,
                                                   input_columns + 8};
    output->Resize(output_dimensions);

    const auto* input_data = input.template data<float>();
    auto* output_data = output->template mutable_data<uint8_t>();
    const auto output_columns = output->dim(1);

    for (size_t row = 0; row < input_rows; ++row) {
      ConstEigenVectorArrayMap<float> input_row(
          input_data + row * input_columns, input_columns);

      uint8_t* output_row = output_data + row * output_columns;
      EigenVectorArrayMap<uint8_t> output_row_values(output_row, input_columns);
      EigenVectorArrayMap<float> output_row_scale_bias(
          reinterpret_cast<float*>(output_row + input_columns), 2);

      const float minimum_element = input_row.minCoeff();
      const float maximum_element = input_row.maxCoeff();
      const float range = maximum_element - minimum_element;

      output_row_scale_bias(0) = range / 255.0f;
      output_row_scale_bias(1) = minimum_element;
      const auto inverse_scale = 255.0f / (range + kEpsilon);
      output_row_values = ((input_row - minimum_element) * inverse_scale)
                              .round()
                              .cast<uint8_t>();
    }

    return true;
  }

 private:
  INPUT_TAGS(DATA_FLOAT);
  OUTPUT_TAGS(DATA_FUSED_SCALE_BIAS_INT8);
};

template <class Context>
class Fused8BitRowwiseQuantizedToFloatOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  USE_SIMPLE_CTOR_DTOR(Fused8BitRowwiseQuantizedToFloatOp)

  bool RunOnDevice() override {
    CAFFE_ENFORCE(IS_LITTLE_ENDIAN, "Unsupported endianness");

    const auto& input = Input(DATA_FUSED_SCALE_BIAS_INT8);
    auto* output = Output(DATA_FLOAT);

    const auto input_rows = input.dim(0);
    const auto input_columns = input.dim(1);
    CAFFE_ENFORCE_EQ(input.ndim(), 2, "Expect input to be a matrix");

    // The last 8 bytes per row are the scale and the bias. The rest of
    // input_columns is the number of values in the original row.
    const std::vector<TIndex> output_dimensions = {input_rows,
                                                   input_columns - 8};
    output->Resize(output_dimensions);
    const auto output_columns = output->dim(1);

    const auto* input_data = input.template data<uint8_t>();
    auto* output_data = output->template mutable_data<float>();

    for (size_t row = 0; row < input_rows; ++row) {
      const uint8_t* input_row = input_data + row * input_columns;
      ConstEigenVectorArrayMap<uint8_t> input_row_values(
          input_row, output_columns);
      ConstEigenVectorArrayMap<float> input_row_scale_bias(
          reinterpret_cast<const float*>(input_row + output_columns), 2);

      EigenVectorArrayMap<float> output_row(
          output_data + row * output_columns, output_columns);

      output_row = input_row_values.cast<float>() * input_row_scale_bias(0) +
          input_row_scale_bias(1);
    }
    return true;
  }

 private:
  INPUT_TAGS(DATA_FUSED_SCALE_BIAS_INT8);
  OUTPUT_TAGS(DATA_FLOAT);
};

#undef IS_LITTLE_ENDIAN

} // namespace caffe2

#endif // CAFFE2_OPERATORS_FUSED_ROWWISE_8BIT_CONVERSION_OPS_H_


text:
"""
@author: Gaetan Hadjeres
"""

import click

from DatasetManager.chorale_dataset import ChoraleDataset
from DatasetManager.dataset_manager import DatasetManager
from DatasetManager.metadata import FermataMetadata, TickMetadata, KeyMetadata

from DeepBach.model_manager import DeepBach

@click.command()
@click.option('--note_embedding_dim', default=20,
              help='size of the note embeddings')
@click.option('--meta_embedding_dim', default=20,
              help='size of the metadata embeddings')
@click.option('--num_layers', default=2,
              help='number of layers of the LSTMs')
@click.option('--lstm_hidden_size', default=256,
              help='hidden size of the LSTMs')
@click.option('--dropout_lstm', default=0.5,
              help='amount of dropout between LSTM layers')
@click.option('--linear_hidden_size', default=256,
              help='hidden size of the Linear layers')
@click.option('--batch_size', default=256,
              help='training batch size')
@click.option('--num_epochs', default=5,
              help='number of training epochs')
@click.option('--train', is_flag=True,
              help='train the specified model for num_epochs')
@click.option('--num_iterations', default=500,
              help='number of parallel pseudo-Gibbs sampling iterations')
@click.option('--sequence_length_ticks', default=64,
              help='length of the generated chorale (in ticks)')
def main(note_embedding_dim,
         meta_embedding_dim,
         num_layers,
         lstm_hidden_size,
         dropout_lstm,
         linear_hidden_size,
         batch_size,
         num_epochs,
         train,
         num_iterations,
         sequence_length_ticks,
         ):
    dataset_manager = DatasetManager()

    metadatas = [
       FermataMetadata(),
       TickMetadata(subdivision=4),
       KeyMetadata()
    ]
    chorale_dataset_kwargs = {
        'voice_ids':      [0, 1, 2, 3],
        'metadatas':      metadatas,
        'sequences_size': 8,
        'subdivision':    4
    }
    bach_chorales_dataset: ChoraleDataset = dataset_manager.get_dataset(
        name='bach_chorales',
        **chorale_dataset_kwargs
        )
    dataset = bach_chorales_dataset

    deepbach = DeepBach(
        dataset=dataset,
        note_embedding_dim=note_embedding_dim,
        meta_embedding_dim=meta_embedding_dim,
        num_layers=num_layers,
        lstm_hidden_size=lstm_hidden_size,
        dropout_lstm=dropout_lstm,
        linear_hidden_size=linear_hidden_size
    )

    if train:
        deepbach.train(batch_size=batch_size,
                       num_epochs=num_epochs)
    else:
        deepbach.load()
        deepbach.cuda()

    print('Generation')
    score, tensor_chorale, tensor_metadata = deepbach.generation(
        num_iterations=num_iterations,
        sequence_length_ticks=sequence_length_ticks,
    )
    score.show('txt')
    score.show()

if __name__ == '__main__':
    main()


text:
package wisekb.shared.util.cli;

import org.apache.commons.exec.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;

public class CommandUtils {

    /**
     * SLF4J Logging
     */
    private static Logger logger = LoggerFactory.getLogger(CommandUtils.class);

    public static int execute(String[] cmds, String working, Map envs) throws IOException {
        CommandLine command = new CommandLine(cmds[0]);
        for (int i = 1; i < cmds.length; i++) {
            command.addArgument(cmds[i]);
        }
        CommandOutput adapter = executeCommand(command, working, envs, new CommandOutput(logger));
        return adapter.getExitCode();
    }

    public static CommandOutput execute(String[] cmds, String working, Map envs, CommandOutput adapter) throws IOException {
        CommandLine command = new CommandLine(cmds[0]);
        for (int i = 1; i < cmds.length; i++) {
            command.addArgument(cmds[i]);
        }
        return executeCommand(command, working, envs, adapter);
    }

    public static CommandOutput execute(String command, String working, Map envs, CommandOutput adapter) throws IOException {
        logger.info("Executing >> Command = {} / Working = {}", command, working);
        String[] cmds = org.apache.commons.lang.StringUtils.splitPreserveAllTokens(command, " ");
        return execute(cmds, working, envs, adapter);
    }

    public static int execute(String command, String working, Map envs) throws IOException {
        logger.info("Executing >> Command = {} / Working = {}", command, working);
        String[] cmds = org.apache.commons.lang.StringUtils.splitPreserveAllTokens(command, " ");
        return execute(cmds, working, envs);
    }

    public static int executeCommand(CommandLine command, String working, Map envs, Logger logger) throws IOException {
        logger.info("Executing >> Command = {} / Working = {}", command.toString(), working);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(new File(working));
        try {
            executor.setExitValue(0);
            CommandOutput adapter = new CommandOutput(logger);
            PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(adapter), new ExecLogHandler(adapter));
            executor.setStreamHandler(psh);
            return executor.execute(command, envs);
        } catch (ExecuteException ex) {
            // SystemAlert.get().send("COMMON", "COMMAND", "EXECUTE", "FAILED", "커맨드 라인 '" + command.toString() + "'을 실행할 수 없습니다. 종료코드는 " + ex.getExitValue() + " 입니다.", ex);
            return ex.getExitValue();
        }
    }

    public static CommandOutput executeCommand(CommandLine command, String working, Map envs, CommandOutput adapter) throws IOException {
        logger.info("Executing >> Command = {} / Working = {}", command.toString(), working);
        PumpStreamHandler psh = null;
        DefaultExecutor executor = new DefaultExecutor();
        try {
            executor.setWorkingDirectory(new File(working));
            executor.setExitValue(0);
            psh = new PumpStreamHandler(new ExecLogHandler(adapter), new ExecLogHandler(adapter));
            executor.setStreamHandler(psh);
            adapter.setExitCode(executor.execute(command, envs));
        } catch (ExecuteException ex) {
            // SystemAlert.get().send("COMMON", "COMMAND", "EXECUTE", "FAILED", "커맨드 라인 '" + command.toString() + "'을 실행할 수 없습니다. 종료코드는 " + ex.getExitValue() + " 입니다.", ex);
            adapter.setExitCode(ex.getExitValue());
        }
        return adapter;
    }

    static class ExecLogHandler extends LogOutputStream {

        private CommandOutput adapter;

        public ExecLogHandler(CommandOutput adapter) {
            this.adapter = adapter;
        }

        @Override
        protected void processLine(String line, int level) {
            if (adapter != null) {
                adapter.getBuilder().append(line);
            }
            if (adapter.getLogger() != null) {
                adapter.getLogger().info("LOG >> {}", line);
            }
        }
    }
}


text:
package com.facebook.buck.features.rust;

import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.description.attr.ImplicitDepsInferringDescription;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.FlavorDomain;
import com.facebook.buck.core.model.Flavored;
import com.facebook.buck.core.model.InternalFlavor;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleCreationContextWithTargetGraph;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.DescriptionWithTargetGraph;
import com.facebook.buck.core.rules.common.BuildableSupport;
import com.facebook.buck.core.rules.tool.BinaryWrapperRule;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.core.util.immutables.RuleArg;
import com.facebook.buck.cxx.CxxDeps;
import com.facebook.buck.downwardapi.config.DownwardApiConfig;
import com.facebook.buck.features.rust.RustBinaryDescription.Type;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.util.types.Pair;
import com.facebook.buck.versions.VersionRoot;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import java.util.Map.Entry;
import java.util.Optional;

public class RustTestDescription
    implements DescriptionWithTargetGraph<RustTestDescriptionArg>,
        ImplicitDepsInferringDescription<RustTestDescription.AbstractRustTestDescriptionArg>,
        Flavored,
        VersionRoot<RustTestDescriptionArg> {

  private final ToolchainProvider toolchainProvider;
  private final RustBuckConfig rustBuckConfig;
  private final DownwardApiConfig downwardApiConfig;

  public RustTestDescription(
      ToolchainProvider toolchainProvider,
      RustBuckConfig rustBuckConfig,
      DownwardApiConfig downwardApiConfig) {
    this.toolchainProvider = toolchainProvider;
    this.rustBuckConfig = rustBuckConfig;
    this.downwardApiConfig = downwardApiConfig;
  }

  @Override
  public Class<RustTestDescriptionArg> getConstructorArgType() {
    return RustTestDescriptionArg.class;
  }

  @Override
  public BuildRule createBuildRule(
      BuildRuleCreationContextWithTargetGraph context,
      BuildTarget buildTarget,
      BuildRuleParams params,
      RustTestDescriptionArg args) {
    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
    BuildTarget exeTarget = buildTarget.withAppendedFlavors(InternalFlavor.of("unittest"));
    CxxDeps allDeps =
        CxxDeps.builder()
            .addDeps(args.getDeps())
            .addDeps(args.getNamedDeps().values())
            .addPlatformDeps(args.getPlatformDeps())
            .build();

    RustBinaryDescription.Type type =
        RustBinaryDescription.BINARY_TYPE
            .getFlavorAndValue(buildTarget)
            .map(Entry::getValue)
            .orElse(Type.STATIC);

    ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
    RustPlatform rustPlatform =
        RustCompileUtils.getRustPlatform(
                getRustToolchain(buildTarget.getTargetConfiguration()), buildTarget, args)
            .resolve(context.getActionGraphBuilder(), buildTarget.getTargetConfiguration());

    ImmutableList.Builder<StringArg> testFlags = new ImmutableList.Builder<>();
    testFlags.addAll(rustPlatform.getRustTestFlags());
    if (args.isFramework()) {
      testFlags.add(StringArg.of("--test"));
    }

    Pair<ImmutableList<Arg>, ImmutableSortedMap<String, Arg>> flagsAndEnv =
        RustCompileUtils.getRustcFlagsAndEnv(
            context, buildTarget, rustPlatform, testFlags.build(), args);

    ImmutableList<Arg> linkerFlags =
        RustCompileUtils.getLinkerFlags(context, buildTarget, rustPlatform, args);

    BinaryWrapperRule testExeBuild =
        (BinaryWrapperRule)
            graphBuilder.computeIfAbsent(
                exeTarget,
                target ->
                    RustCompileUtils.createBinaryBuildRule(
                        target,
                        projectFilesystem,
                        params,
                        graphBuilder,
                        rustBuckConfig,
                        downwardApiConfig,
                        rustPlatform,
                        args.getCrate(),
                        args.getEdition(),
                        flagsAndEnv.getSecond(), // rustc environment
                        flagsAndEnv.getFirst(), // rustc flags
                        linkerFlags,
                        RustCompileUtils.getLinkStyle(
                            buildTarget, args.getLinkStyle(), rustPlatform),
                        args.isRpath(),
                        args.getSrcs(),
                        args.getMappedSrcs(),
                        args.getCrateRoot(),
                        ImmutableSet.of("lib.rs", "main.rs"),
                        type.getCrateType(),
                        allDeps.get(graphBuilder, rustPlatform.getCxxPlatform()),
                        args.getNamedDeps()));

    Tool testExe = testExeBuild.getExecutableCommand(OutputLabel.defaultLabel());

    BuildRuleParams testParams =
        params.copyAppendingExtraDeps(BuildableSupport.getDepsCollection(testExe, graphBuilder));

    return new RustTest(
        buildTarget,
        projectFilesystem,
        testParams,
        flagsAndEnv.getSecond(), // environment
        testExeBuild,
        args.getLabels(),
        args.getContacts(),
        downwardApiConfig.isEnabledForTests());
  }

  @Override
  public void findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellNameResolver cellRoots,
      AbstractRustTestDescriptionArg constructorArg,
      ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
      ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
    targetGraphOnlyDepsBuilder.addAll(
        RustCompileUtils.getPlatformParseTimeDeps(
            getRustToolchain(buildTarget.getTargetConfiguration()), buildTarget, constructorArg));
  }

  @Override
  public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains(
      TargetConfiguration toolchainTargetConfiguration) {
    return Optional.of(
        ImmutableSet.of(
            getRustToolchain(toolchainTargetConfiguration).getRustPlatforms(),
            RustBinaryDescription.BINARY_TYPE));
  }

  private RustToolchain getRustToolchain(TargetConfiguration toolchainTargetConfiguration) {
    return toolchainProvider.getByName(
        RustToolchain.DEFAULT_NAME, toolchainTargetConfiguration, RustToolchain.class);
  }

  @RuleArg
  interface AbstractRustTestDescriptionArg extends RustLinkableArgs {}
}


text:
var Books = require('../app/models/book');
var User = require('../app/models/user');
var Item = require('../app/models/item');
var Order = require('../app/models/order');
var mongoose = require('mongoose');

module.exports = function (app, passport) {

    //remove from cart
    //route to order page
    app.get('/destroy/:id', isLoggedIn, function (req, res) {

        Item.remove({buyer_id: req.user.id},{book_id: req.params.id} ).exec();
        res.redirect('/store');
    });

    //route to order page
    app.get('/order/:id', isLoggedIn, function (req, res) {

        Order.find({"_id": req.params.id}, function (err, order) {
            if (err) {
            };
            res.render('order.ejs', {
                user: req.user,
                order: order[0]
            });
        });
    });

    // check out
    app.post('/done', isLoggedIn, function (req, res) {

        //try to add to item database

        User.findById(req.user, function (err, shopper) {

            //get new order
            var order = new Order();
            order.transactionDate = new Date();
            order.shopper_id = req.user.id;
            order.shopper_fn = req.param('firstName');
            order.shopper_ln = req.param('lastName');
            order.shopper_add = req.param('address');
            order.shopper_phone = req.param('phone');
            order.shopper_email = req.param('email');
            order.shopper_CC_Number = req.param('CCNo');
            order.shopper_CC_Exp_Month = req.param('CCExpiresMonth');
            order.shopper_CC_Exp_Year = req.param('CCExpiresYear');
            order.items.push(req.param('items'));
            order.save();

            // get total
            Item.aggregate([
                { $group: {
                    _id: '$buyer_id',
                    total: { $sum: '$price'}
                }}
            ], function (err, result) {
                    if (err) {
                        //console.error(err);
                    } else {

                        order.total = result[0]['total'];
                        order.save();
                    }
                }
            );

            //decrease book quantity
            Item.find({buyer_id: req.user.id}, function (err, items) {
                items.forEach((function(item) {
                    Books.update({_id: item.book_id},{$inc: {stock: -1}}).exec();
                }));

            });

            //remove checked out book from database item
            Item.remove({buyer_id: req.user.id}).exec();

        });

        res.redirect('/store');

    });

    app.get('/checkout', isLoggedIn, function (req, res) {

        Item.find({"buyer_id": req.user.id}, function (err, item) {
            res.render('checkout.ejs', {
                item: item,
                user: req.user
            });
        });

    });

    //delete an item from cart

    // add item to chart
    app.post('/cart', isLoggedIn, function (req, res) {

        //try to add to item database
        Books.findById(req.param('addBookID'), function (err, current_book) {

            var item          = new Item();
            item.price        = current_book.proice;
            item.quantity     = "1";
            item.price        = current_book.price;
            item.modifiedDate = new Date(),
            item.buyer_id     = req.user.id,
            item.book_id      = req.param('addBookID');
            item.book_author  = current_book.author;
            item.book_title   = current_book.title;

            // save the user
            item.save();

        });

        res.redirect('/store');

    });

    app.get('/viewcart', isLoggedIn, function (req, res) {

        //res.render('cart.ejs', {
        //    user : req.user // get the user out of session and pass to template
        //});
        ////try to sum the total price

        Item.aggregate([
            { $group: {
                _id: '$buyer_id',
                total: { $sum: '$price'}
            }}
        ], function (err, result) {
                if (err) {
                    //console.error(err);
                } else {

                    //console.log(result[0]['total']);
                }
            }
        );

        Item.find({"buyer_id": req.user.id}, function (err, item, total) {
            res.render('cart.ejs', {
                item: item,
                user: req.user
            });
        });

    });

    //routes product page
    app.get('/product/:id', isLoggedIn, function (req, res) {

        Books.find({"_id": req.params.id}, function (err, store_book) {
            if (err) {
            }
            ;
            res.render('product.ejs', {
                user: req.user,
                books: store_book[0]
            });
        });
    });

    // =====================================
    // Book Store SECTION =========================
    // =====================================
    // we will want this protected so you have to be logged in to visit
    // we will use route middleware to verify this (the isLoggedIn function)
    app.get('/store', isLoggedIn, function (req, res) {
        Books.find({language: 'English'}, function (err, store_books) {
            if (err) {
            }
            ;
            res.render('store.ejs', {
                user: req.user,
                books: store_books
            });
        });
    });

    // =====================================
    // HOME PAGE (with login links) ========
    // =====================================
    app.get('/', function (req, res) {
        res.render('index.ejs'); // load the index.ejs file
    });

    // =====================================
    // LOGIN ===============================
    // =====================================
    // show the login form
    app.get('/login', function (req, res) {

        // render the page and pass in any flash data if it exists
        res.render('login.ejs', { message: req.flash('loginMessage') });
    });

    // process the login form
    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/store', // redirect to the secure profile section
        failureRedirect: '/login', // redirect back to the signup page if there is an error
        failureFlash: true // allow flash messages
    }));

    // =====================================
    // SIGNUP ==============================
    // =====================================
    // show the signup form
    app.get('/signup', function (req, res) {

        // render the page and pass in any flash data if it exists
        res.render('signup.ejs', { message: req.flash('signupMessage') });
    });

    // process the signup form
    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/store', // redirect to the secure profile section
        failureRedirect: '/signup', // redirect back to the signup page if there is an error
        failureFlash: true // allow flash messages
    }));

    // =====================================
    // PROFILE SECTION =========================
    // =====================================
    // we will want this protected so you have to be logged in to visit
    // we will use route middleware to verify this (the isLoggedIn function)
    app.get('/profile', isLoggedIn, function (req, res) {

        Order.find({"shopper_id": req.user.id}, function (err, order) {
            res.render('profile.ejs', {
                order: order,
                user: req.user
            });
        });

//        res.render('profile.ejs', {
//            user: req.user // get the user out of session and pass to template
//        });
    });

    // =====================================
    // LOGOUT ==============================
    // =====================================
    app.get('/logout', function (req, res) {
        req.logout();
        res.redirect('/');
        mongoose.connection.close();
    });
};

// route middleware to make sure
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}


text:
package org.pentaho.di.repository.kdr.delegates;

import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleAuthException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.IUser;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.RepositoryElementInterface;
import org.pentaho.di.repository.UserInfo;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;

public class KettleDatabaseRepositoryUserDelegate extends KettleDatabaseRepositoryBaseDelegate {

	private static Class<?> PKG = UserInfo.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$

	public KettleDatabaseRepositoryUserDelegate(KettleDatabaseRepository repository) {
		super(repository);
	}

	public RowMetaAndData getUser(ObjectId id_user) throws KettleException
	{
		return repository.connectionDelegate.getOneRow(quoteTable(KettleDatabaseRepository.TABLE_R_USER), quote(KettleDatabaseRepository.FIELD_USER_ID_USER), id_user);
	}

	public synchronized ObjectId getUserID(String login) throws KettleException
	{
		return repository.connectionDelegate.getIDWithValue(quoteTable(KettleDatabaseRepository.TABLE_R_USER), quote(KettleDatabaseRepository.FIELD_USER_ID_USER), quote(KettleDatabaseRepository.FIELD_USER_LOGIN), login);
	}

	// Load user with login from repository, don't verify password...
	public IUser loadUserInfo(IUser userInfo, String login) throws KettleException
	{
		try
		{
			userInfo.setObjectId( getUserID(login) );
			if (userInfo.getObjectId()!=null)
			{
				RowMetaAndData r = getUser(userInfo.getObjectId());
				if (r!=null)
				{
					userInfo.setLogin( r.getString("LOGIN", null) );
					userInfo.setPassword( Encr.decryptPassword( r.getString("PASSWORD", null) ) );
					userInfo.setUsername( r.getString("NAME", null) );
					userInfo.setDescription( r.getString("DESCRIPTION", null) );
					userInfo.setEnabled( r.getBoolean("ENABLED", false) );
					return userInfo;
				}
				else
				{
					throw new KettleDatabaseException(BaseMessages.getString(PKG, "UserInfo.Error.UserNotFound", login));
				}
			}
            else
            {
                throw new KettleDatabaseException(BaseMessages.getString(PKG, "UserInfo.Error.UserNotFound", login));
            }
		}
		catch(KettleDatabaseException dbe)
		{
			throw new KettleException(BaseMessages.getString(PKG, "UserInfo.Error.UserNotLoaded", login, ""), dbe);
		}
	}

	/** Load user with login from repository and verify the password...
	 *
	 * @param rep
	 * @param login
	 * @param passwd
	 * @throws KettleException
	 */
	public IUser loadUserInfo(IUser userInfo, String login, String passwd) throws KettleException
	{
	  if(userInfo == null || login == null || login.length() <= 0) {
      throw new KettleDatabaseException(BaseMessages.getString(PKG, "UserInfo.Error.IncorrectPasswortLogin"));
	  }

	  try {
		loadUserInfo(userInfo, login);
	  }
	  catch (KettleException ke) {
	     throw new KettleAuthException(BaseMessages.getString(PKG, "UserInfo.Error.IncorrectPasswortLogin"));
	  }
		// Verify the password:
		// decrypt password if needed and compare with the one
		String userPass=Encr.decryptPasswordOptionallyEncrypted(passwd);

		if ( userInfo.getObjectId()==null || !userInfo.getPassword().equals(userPass))
		{
            throw new KettleAuthException(BaseMessages.getString(PKG, "UserInfo.Error.IncorrectPasswortLogin"));
		}
		return userInfo;
	}

	public void saveUserInfo(IUser userInfo) throws KettleException
	{
		try
		{
			// Do we have a user id already?
			if (userInfo.getObjectId()==null)
			{
				userInfo.setObjectId(getUserID(userInfo.getLogin())); // Get userid in the repository
			}

			if (userInfo.getObjectId()==null)
			{
				// This means the login doesn't exist in the database
				// and we have no id, so we don't know the old one...
				// Just grab the next user ID and do an insert:
				userInfo.setObjectId(repository.connectionDelegate.getNextUserID());
				repository.connectionDelegate.insertTableRow("R_USER", fillTableRow(userInfo));
			}
			else
			{
				repository.connectionDelegate.updateTableRow("R_USER", "ID_USER", fillTableRow(userInfo));
			}

			// Put a commit behind it!
			repository.commit();
		}
		catch(KettleDatabaseException dbe)
		{
			throw new KettleException(BaseMessages.getString(PKG, "UserInfo.Error.SavingUser", userInfo.getLogin()), dbe);
		}

	}

	public RowMetaAndData fillTableRow(IUser userInfo)
	{
        RowMetaAndData r = new RowMetaAndData();
		r.addValue( new ValueMeta("ID_USER", ValueMetaInterface.TYPE_INTEGER), userInfo.getObjectId() );
		r.addValue( new ValueMeta("LOGIN", ValueMetaInterface.TYPE_STRING), userInfo.getLogin() );
		r.addValue( new ValueMeta("PASSWORD", ValueMetaInterface.TYPE_STRING), Encr.encryptPassword(userInfo.getPassword()) );
		r.addValue( new ValueMeta("NAME", ValueMetaInterface.TYPE_STRING), userInfo.getUsername() );
		r.addValue( new ValueMeta("DESCRIPTION", ValueMetaInterface.TYPE_STRING), userInfo.getDescription() );
		r.addValue( new ValueMeta("ENABLED", ValueMetaInterface.TYPE_BOOLEAN), Boolean.valueOf(userInfo.isEnabled()) );
		return r;
	}

	public synchronized int getNrUsers() throws KettleException
	{
		int retval = 0;

		String sql = "SELECT COUNT(*) FROM "+quoteTable(KettleDatabaseRepository.TABLE_R_USER);
		RowMetaAndData r = repository.connectionDelegate.getOneRow(sql);
		if (r != null)
		{
			retval = (int) r.getInteger(0, 0L);
		}

		return retval;
	}

	public boolean existsUserInfo(RepositoryElementInterface user) throws KettleException {
		return (user.getObjectId()!=null || getUserID(user.getName())!=null);
	}

	public synchronized void renameUser(ObjectId id_user, String newname) throws KettleException
	{
		String sql = "UPDATE "+quoteTable(KettleDatabaseRepository.TABLE_R_USER)+" SET "+quote(KettleDatabaseRepository.FIELD_USER_NAME)+" = ? WHERE "+quote(KettleDatabaseRepository.FIELD_USER_ID_USER)+" = ?";

		RowMetaAndData table = new RowMetaAndData();
		table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_USER_NAME, ValueMetaInterface.TYPE_STRING), newname);
		table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_USER_ID_USER, ValueMetaInterface.TYPE_INTEGER), id_user);

		repository.connectionDelegate.getDatabase().execStatement(sql, table.getRowMeta(), table.getData());
	}
}


text:
package com.sleepcamel.bsoneer.processor.codeprovider;

import javax.lang.model.type.TypeMirror;

import com.sleepcamel.bsoneer.processor.domain.Property;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.CodeBlock.Builder;

abstract public class SingleStatementDecodeCodeProvider implements DecodeCodeProvider {

	public boolean applies(Property property) {
		return applies(property.getResolvedType());
	}

	@Override
	public CodeBlock getDecodeCode(Property property, DecodeCodeProviders decodeProviders) {
		Builder builder = CodeBlock.builder();
		TypeMirror tm = property.getResolvedType();

		String accessName = property.getSetterCall();
		accessName += property.hasSetter() ? "(" : " = ";
		builder.add("instance." + accessName);
		putDecodeCode(builder, tm, decodeProviders, null, true);
		if ( property.hasSetter() ){
			builder.add(")");
		}
		builder.add(";\n");
		return builder.build();
	}

	@Override
	public int variablesUsed() {
		return 1;
	}

	@Override
	public boolean hasToInstantiate() {
		return false;
	}
}


text:
#include "Bounded_queue.h"
#include <iostream>

using namespace std;

/**
 * test_enqueue2
 *
 * This tests the behavior of enqueuing onto a queue that has no size
 */

int main()
{
  Bounded_queue bq1{0};
  try {
    bq1.enqueue(1);
  } catch (Error& error) {
    cout << error.what() << endl;
  }
}


text:
package com.ashman.fivehundredpx;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.ashman.fivehundredpx.net.json.replies.Photo;
import com.ashman.fivehundredpx.util.Util;

import java.io.File;

public class GalleryListAdapter extends ArrayAdapter<GalleryRow> {
    private BaseFragmentActivity activity;
    private GalleryData galleryData;
    private String packageName;

    public GalleryListAdapter(BaseFragmentActivity activity,
                              int resourceId, GalleryData galleryData) {
        super(activity, resourceId, galleryData.getGalleryRows());
        this.activity = activity;
        this.galleryData = galleryData;
        packageName = FiveHundredApplication.get().getPackageName();
    }

    private void populateImageField(Photo photo, Bitmap cachedBitmap,
                                    ImageView imageView, ProgressBar progressBar) {
        if(photo == null)
            cachedBitmap = BitmapFactory.decodeResource(
                    activity.getResources(), R.drawable.no_more);
        imageView.setTag(photo);
        if(cachedBitmap == null) {
            // Don't have bitmap cached yet/anymore
            // show the progress bar and start downloading
            imageView.setVisibility(View.INVISIBLE);
            progressBar.setVisibility(View.VISIBLE);
            downloadBitmap(photo, imageView, progressBar);
        } else {
            setImageBitmap(photo, cachedBitmap, imageView, progressBar);
        }
    }

    @SuppressLint("NewApi")
    private void setImageBitmap(final Photo photo, final Bitmap bitmap,
                                final ImageView imageView, ProgressBar progressBar) {
        progressBar.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);

        if(photo != null && photo.isNsfw()) {
            imageView.setImageResource(R.drawable.nsfw);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    photo.setNsfw(false);
                    imageView.setImageBitmap(bitmap);
                    setImageClickable(photo, imageView, bitmap);
                }
            });
        } else {
            imageView.setImageBitmap(bitmap);
            if(photo != null)
                setImageClickable(photo, imageView, bitmap);
        }

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(
                    R.layout.gallery_listitem, null, false);
            //Set layout params so that initial list items are not squished.
            //Returned images are square, so it's easy to set the required height
            int height = parent.getWidth() / 3;
            ListView.LayoutParams params = new ListView.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, height);
            convertView.setLayoutParams(params);
            holder = new ViewHolder();
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        GalleryRow rowData = getItem(position);

        //Cached Bitmaps
        Bitmap cachedBitmap1 = galleryData.getCached(rowData.getImageUrl1());
        Bitmap cachedBitmap2 = galleryData.getCached(rowData.getImageUrl2());
        Bitmap cachedBitmap3 = galleryData.getCached(rowData.getImageUrl3());

        //Image Views
        holder.image1 = (ImageView) convertView.findViewById(R.id.gallery_listitem_image1);
        holder.image2 = (ImageView) convertView.findViewById(R.id.gallery_listitem_image2);
        holder.image3 = (ImageView) convertView.findViewById(R.id.gallery_listitem_image3);

        //And Finally Progress Bars
        holder.progressBar1 = (ProgressBar) convertView.findViewById(
                R.id.gallery_listitem_progressbar1);
        holder.progressBar2 = (ProgressBar) convertView.findViewById(
                R.id.gallery_listitem_progressbar2);
        holder.progressBar3 = (ProgressBar) convertView.findViewById(
                R.id.gallery_listitem_progressbar3);

        //Populate all 3 image fields
        populateImageField(rowData.getPhoto1(), cachedBitmap1, holder.image1, holder.progressBar1);
        populateImageField(rowData.getPhoto2(), cachedBitmap2, holder.image2, holder.progressBar2);
        populateImageField(rowData.getPhoto3(), cachedBitmap3, holder.image3, holder.progressBar3);

        return convertView;
    }

    private void downloadBitmap(final Photo photo, final ImageView imageView,
                                final ProgressBar progressBar) {
        int sizeToUse = FiveHundredApplication.get().getDefaultPhotoSize().getSize();
        galleryData.download(photo.getUrl(sizeToUse),
                new GalleryData.BitmapLoadedListener() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, String url) {
                if(photo.equals(imageView.getTag()))
                    setImageBitmap(photo, bitmap, imageView, progressBar);
            }
        });
    }

    public void setImageClickable(final Photo photo, final ImageView imageView,
                                  final Bitmap bitmap) {
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                File imageFile = Util.saveBitmapToLocalFile(
                            getContext().getFilesDir().getAbsolutePath(),
                            "temp", bitmap);
                int[] screenLocation = new int[2];
                view.getLocationOnScreen(screenLocation);

                final Intent subActivity = new Intent(getContext(),
                        PictureViewActivity.class);
                int orientation = getContext().getResources().getConfiguration().orientation;
                subActivity.
                        putExtra(packageName + ".orientation", orientation).
                        putExtra(packageName + ".bitmapFilename", imageFile.getName()).
                        putExtra(packageName + ".bitmapConfig", bitmap.getConfig().name()).
                        putExtra(packageName + ".left", screenLocation[0]).
                        putExtra(packageName + ".top", screenLocation[1]).
                        putExtra(packageName + ".width", view.getWidth()).
                        putExtra(packageName + ".height", view.getHeight()).
                        putExtra(packageName + ".bitmapHeight", bitmap.getHeight()).
                        putExtra(packageName + ".bitmapWidth", bitmap.getWidth()).
                        putExtra(packageName + ".photoData", photo);
                getContext().startActivity(subActivity);
                activity.overridePendingTransition(0, 0);
            }
        });
    }

    private static class ViewHolder {
        ProgressBar progressBar1;
        ProgressBar progressBar2;
        ProgressBar progressBar3;
        ImageView image1;
        ImageView image2;
        ImageView image3;
    }
}