text:
var should = require('./init.js');
var async = require('async');

var j = require('../'), db, User;
var ValidationError = j.ValidationError;

function getValidAttributes() {
  return {
    name: 'Anatoliy',
    email: 'email@example.com',
    state: '',
    age: 26,
    gender: 'male',
    createdByAdmin: false,
    createdByScript: true,
  };
}

describe('validations', function() {

  var User, Entry;

  before(function(done) {
    db = getSchema();
    User = db.define('User', {
      email: String,
      name: String,
      password: String,
      state: String,
      age: Number,
      gender: String,
      domain: String,
      pendingPeriod: Number,
      createdByAdmin: Boolean,
      createdByScript: Boolean,
      updatedAt: Date,
    });
    Entry = db.define('Entry', {
      id: { type: 'string', id: true, generated: false },
      name: { type: 'string' },
    });
    Entry.validatesUniquenessOf('id');
    db.automigrate(done);
  });

  beforeEach(function(done) {
    User.destroyAll(function() {
      delete User.validations;
      done();
    });
  });

  after(function() {
    // db.disconnect();
  });

  describe('commons', function() {

    describe('skipping', function() {

      it('should NOT skip when `if` is fulfilled', function() {
        User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
        var user = new User;
        user.createdByAdmin = true;
        user.isValid().should.be.false;
        user.errors.pendingPeriod.should.eql(['can\'t be blank']);
        user.pendingPeriod = 1;
        user.isValid().should.be.true;
      });

      it('should skip when `if` is NOT fulfilled', function() {
        User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
        var user = new User;
        user.createdByAdmin = false;
        user.isValid().should.be.true;
        user.errors.should.be.false;
        user.pendingPeriod = 1;
        user.isValid().should.be.true;
      });

      it('should NOT skip when `unless` is fulfilled', function() {
        User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
        var user = new User;
        user.createdByAdmin = false;
        user.isValid().should.be.false;
        user.errors.pendingPeriod.should.eql(['can\'t be blank']);
        user.pendingPeriod = 1;
        user.isValid().should.be.true;
      });

      it('should skip when `unless` is NOT fulfilled', function() {
        User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
        var user = new User;
        user.createdByAdmin = true;
        user.isValid().should.be.true;
        user.errors.should.be.false;
        user.pendingPeriod = 1;
        user.isValid().should.be.true;
      });

    });

    describe('skipping in async validation', function() {

      it('should skip when `if` is NOT fulfilled', function(done) {
        User.validateAsync('pendingPeriod', function(err, done) {
          if (!this.pendingPeriod) err();
          done();
        }, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
        var user = new User;
        user.createdByAdmin = false;
        user.isValid(function(valid) {
          valid.should.be.true;
          user.errors.should.be.false;
          done();
        });
      });

      it('should NOT skip when `if` is fulfilled', function(done) {
        User.validateAsync('pendingPeriod', function(err, done) {
          if (!this.pendingPeriod) err();
          done();
        }, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
        var user = new User;
        user.createdByAdmin = true;
        user.isValid(function(valid) {
          valid.should.be.false;
          user.errors.pendingPeriod.should.eql(['can\'t be blank']);
          done();
        });
      });

      it('should skip when `unless` is NOT fulfilled', function(done) {
        User.validateAsync('pendingPeriod', function(err, done) {
          if (!this.pendingPeriod) err();
          done();
        }, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
        var user = new User;
        user.createdByAdmin = true;
        user.isValid(function(valid) {
          valid.should.be.true;
          user.errors.should.be.false;
          done();
        });
      });

      it('should NOT skip when `unless` is fulfilled', function(done) {
        User.validateAsync('pendingPeriod', function(err, done) {
          if (!this.pendingPeriod) err();
          done();
        }, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
        var user = new User;
        user.createdByAdmin = false;
        user.isValid(function(valid) {
          valid.should.be.false;
          user.errors.pendingPeriod.should.eql(['can\'t be blank']);
          done();
        });
      });

    });

    describe('lifecycle', function() {

      it('should work on create', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.create(function(e, u) {
          should.exist(e);
          User.create({ name: 'Valid' }, function(e, d) {
            should.not.exist(e);
            done();
          });
        });
      });

      it('should work on update', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.create({ name: 'Valid' }, function(e, d) {
          d.updateAttribute('name', null, function(e) {
            should.exist(e);
            e.should.be.instanceOf(Error);
            e.should.be.instanceOf(ValidationError);
            d.updateAttribute('name', 'Vasiliy', function(e) {
              should.not.exist(e);
              done();
            });
          });
        });
      });

      it('should ignore errors on upsert by default', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        // It's important to pass an id value, otherwise DAO falls back
        // to regular create()
        User.updateOrCreate({ id: 999 }, done);
      });

      it('should be skipped by upsert when disabled via settings', function(done) {
        var Customer = User.extend('Customer');
        Customer.attachTo(db);
        db.autoupdate(function(err) {
          if (err) return done(err);
          Customer.prototype.isValid = function() {
            throw new Error('isValid() should not be called at all');
          };
          Customer.settings.validateUpsert = false;
          // It's important to pass an id value, otherwise DAO falls back
          // to regular create()
          Customer.updateOrCreate({ id: 999 }, done);
        });
      });

      it('should work on upsert when enabled via settings', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.settings.validateUpsert = true;
        // It's important to pass an id value, otherwise DAO falls back
        // to regular create()
        User.upsert({ id: 999 }, function(err, u) {
          if (!err) return done(new Error('Validation should have failed.'));
          err.should.be.instanceOf(ValidationError);
          done();
        });
      });

      it('should return error code', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.create(function(e, u) {
          should.exist(e);
          e.details.codes.name.should.eql(['presence']);
          done();
        });
      });

      it('should allow to modify error after validation', function(done) {
        User.afterValidate = function(next) {
          next();
        };
        done();
      });

      it('should include validation messages in err.message', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.create(function(e, u) {
          should.exist(e);
          e.message.should.match(/`name` can't be blank/);
          done();
        });
      });

      it('should include property value in err.message', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.create(function(e, u) {
          should.exist(e);
          e.message.should.match(/`name` can't be blank \(value: undefined\)/);
          done();
        });
      });

      it('should include model name in err.message', function(done) {
        delete User.validations;
        User.validatesPresenceOf('name');
        User.create(function(e, u) {
          should.exist(e);
          e.message.should.match(/`User` instance/i);
          done();
        });
      });

      it('should return validation metadata', function() {
        var expected = { name: [{ validation: 'presence', options: {}}] };
        delete User.validations;
        User.validatesPresenceOf('name');
        var validations = User.validations;
        validations.should.eql(expected);
      });
    });
  });

  describe('validation with or without options', function() {
    it('should work on update with options', function(done) {
      delete User.validations;
      User.validatesPresenceOf('name');
      User.create({ name: 'Valid' }, function(e, d) {
        d.updateAttribute('name', null, { options: 'options' }, function(e) {
          should.exist(e);
          e.should.be.instanceOf(Error);
          e.should.be.instanceOf(ValidationError);
          d.updateAttribute('name', 'Vasiliy', { options: 'options' }, function(e) {
            should.not.exist(e);
            done();
          });
        });
      });
    });

    it('should work on update without options', function(done) {
      delete User.validations;
      User.validatesPresenceOf('name');
      User.create({ name: 'Valid' }, function(e, d) {
        d.updateAttribute('name', null, function(e) {
          should.exist(e);
          e.should.be.instanceOf(Error);
          e.should.be.instanceOf(ValidationError);
          d.updateAttribute('name', 'Vasiliy', function(e) {
            should.not.exist(e);
            done();
          });
        });
      });
    });

    it('should work on create with options', function(done) {
      delete User.validations;
      User.validatesPresenceOf('name');
      User.create(function(e, u) {
        should.exist(e);
        User.create({ name: 'Valid' }, { options: 'options' }, function(e, d) {
          should.not.exist(e);
          done();
        });
      });
    });

    it('should work on create without options', function(done) {
      delete User.validations;
      User.validatesPresenceOf('name');
      User.create(function(e, u) {
        should.exist(e);
        User.create({ name: 'Valid' }, function(e, d) {
          should.not.exist(e);
          done();
        });
      });
    });
  });

  describe('presence', function() {

    it('should validate presence', function() {
      User.validatesPresenceOf('name', 'email');

      var validations = User.validations;
      validations.name.should.eql([{ validation: 'presence', options: {}}]);
      validations.email.should.eql([{ validation: 'presence', options: {}}]);

      var u = new User;
      u.isValid().should.not.be.true;
      u.name = 1;
      u.isValid().should.not.be.true;
      u.email = 2;
      u.isValid().should.be.true;
    });

    it('should reject NaN value as a number', function() {
      User.validatesPresenceOf('age');
      var u = new User();
      u.isValid().should.be.false;
      u.age = NaN;
      u.isValid().should.be.false;
      u.age = 1;
      u.isValid().should.be.true;
    });

    it('should allow "NaN" value as a string', function() {
      User.validatesPresenceOf('name');
      var u = new User();
      u.isValid().should.be.false;
      u.name = 'NaN';
      u.isValid().should.be.true;
    });

    it('should skip validation by property (if/unless)', function() {
      User.validatesPresenceOf('domain', { unless: 'createdByScript' });

      var user = new User(getValidAttributes());
      user.isValid().should.be.true;

      user.createdByScript = false;
      user.isValid().should.be.false;
      user.errors.domain.should.eql(['can\'t be blank']);

      user.domain = 'domain';
      user.isValid().should.be.true;
    });

  });

  describe('absence', function() {

    it('should validate absence', function() {
      User.validatesAbsenceOf('reserved', { if: 'locked' });
      var u = new User({ reserved: 'foo', locked: true });
      u.isValid().should.not.be.true;
      u.reserved = null;
      u.isValid().should.be.true;
      var u = new User({ reserved: 'foo', locked: false });
      u.isValid().should.be.true;
    });

  });

  describe('uniqueness', function() {
    it('should validate uniqueness', function(done) {
      User.validatesUniquenessOf('email');
      var u = new User({ email: 'hey' });
      Boolean(u.isValid(function(valid) {
        valid.should.be.true;
        u.save(function() {
          var u2 = new User({ email: 'hey' });
          u2.isValid(function(valid) {
            valid.should.be.false;
            done();
          });
        });
      })).should.be.false;
    });

    it('should handle same object modification', function(done) {
      User.validatesUniquenessOf('email');
      var u = new User({ email: 'hey' });
      Boolean(u.isValid(function(valid) {
        valid.should.be.true;
        u.save(function() {
          u.name = 'Goghi';
          u.isValid(function(valid) {
            valid.should.be.true;
            u.save(done);
          });
        });
        // async validations always falsy when called as sync
      })).should.not.be.ok;
    });

    it('should support multi-key constraint', function(done) {
      var EMAIL = 'user@xample.com';
      var SiteUser = db.define('SiteUser', {
        siteId: String,
        email: String,
      });
      SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] });
      async.waterfall([
        function automigrate(next) {
          db.automigrate(next);
        },
        function createSite1User(next) {
          SiteUser.create(
            { siteId: 1, email: EMAIL },
            next);
        },
        function createSite2User(user1, next) {
          SiteUser.create(
            { siteId: 2, email: EMAIL },
            next);
        },
        function validateDuplicateUser(user2, next) {
          var user3 = new SiteUser({ siteId: 1, email: EMAIL });
          user3.isValid(function(valid) {
            valid.should.be.false;
            next();
          });
        },
      ], function(err) {
        if (err && err.name == 'ValidationError') {
          console.error('ValidationError:', err.details.messages);
        }
        done(err);
      });
    });

    it('should skip blank values', function(done) {
      User.validatesUniquenessOf('email');
      var u = new User({ email: '  ' });
      Boolean(u.isValid(function(valid) {
        valid.should.be.true;
        u.save(function() {
          var u2 = new User({ email: null });
          u2.isValid(function(valid) {
            valid.should.be.true;
            done();
          });
        });
      })).should.be.false;
    });

    it('should work with if/unless', function(done) {
      User.validatesUniquenessOf('email', {
        if: function() { return true; },
        unless: function() { return false; },
      });
      var u = new User({ email: 'hello' });
      Boolean(u.isValid(function(valid) {
        valid.should.be.true;
        done();
      })).should.be.false;
    });

    it('should work with id property on create', function(done) {
      Entry.create({ id: 'entry' }, function(err, entry) {
        var e = new Entry({ id: 'entry' });
        Boolean(e.isValid(function(valid) {
          valid.should.be.false;
          done();
        })).should.be.false;
      });
    });

    it('should work with id property after create', function(done) {
      Entry.findById('entry', function(err, e) {
        Boolean(e.isValid(function(valid) {
          valid.should.be.true;
          done();
        })).should.be.false;
      });
    });
  });

  describe('format', function() {
    it('should validate format');
    it('should overwrite default blank message with custom format message');

    it('should skip missing values when allowing null', function() {
      User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
      var u = new User({});
      u.isValid().should.be.true;
    });

    it('should skip null values when allowing null', function() {
      User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
      var u = new User({ email: null });
      u.isValid().should.be.true;
    });

    it('should not skip missing values', function() {
      User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
      var u = new User({});
      u.isValid().should.be.false;
    });

    it('should not skip null values', function() {
      User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
      var u = new User({ email: null });
      u.isValid().should.be.false;
    });
  });

  describe('numericality', function() {
    it('should validate numericality');
  });

  describe('inclusion', function() {
    it('should validate inclusion');
  });

  describe('exclusion', function() {
    it('should validate exclusion');
  });

  describe('length', function() {
    it('should validate length');
  });

  describe('custom', function() {
    it('should validate using custom sync validation', function() {
      User.validate('email', function(err) {
        if (this.email === 'hello') err();
      }, { code: 'invalid-email' });
      var u = new User({ email: 'hello' });
      Boolean(u.isValid()).should.be.false;
      u.errors.codes.should.eql({ email: ['invalid-email'] });
    });

    it('should validate and return detailed error messages', function() {
      User.validate('global', function(err) {
        if (this.email === 'hello' || this.email === 'hey') {
          this.errors.add('email', 'Cannot be `' + this.email + '`', 'invalid-email');
          err(false); // false: prevent global error message
        }
      });
      var u = new User({ email: 'hello' });
      Boolean(u.isValid()).should.be.false;
      u.errors.should.eql({ email: ['Cannot be `hello`'] });
      u.errors.codes.should.eql({ email: ['invalid-email'] });
    });

    it('should validate using custom async validation', function(done) {
      User.validateAsync('email', function(err, next) {
        process.nextTick(next);
      }, {
        if: function() { return true; },
        unless: function() { return false; },
      });
      var u = new User({ email: 'hello' });
      Boolean(u.isValid(function(valid) {
        valid.should.be.true;
        done();
      })).should.be.false;
    });
  });

  describe('invalid value formatting', function() {
    var origMaxLen;
    beforeEach(function saveAndSetMaxLen() {
      origMaxLen = ValidationError.maxPropertyStringLength;
    });

    afterEach(function restoreMaxLen() {
      ValidationError.maxPropertyStringLength = origMaxLen;
    });

    it('should truncate long strings', function() {
      ValidationError.maxPropertyStringLength = 9;
      var err = givenValidationError('prop', '1234567890abc', 'is invalid');
      getErrorDetails(err)
        .should.equal('`prop` is invalid (value: "12...abc").');
    });

    it('should truncate long objects', function() {
      ValidationError.maxPropertyStringLength = 12;
      var err = givenValidationError('prop', { foo: 'bar' }, 'is invalid');
      getErrorDetails(err)
        .should.equal('`prop` is invalid (value: { foo:... }).');
    });

    it('should truncate long arrays', function() {
      ValidationError.maxPropertyStringLength = 12;
      var err = givenValidationError('prop', [{ a: 1, b: 2 }], 'is invalid');
      getErrorDetails(err)
        .should.equal('`prop` is invalid (value: [ { a...} ]).');
    });

    it('should print only top-level object properties', function() {
      var err = givenValidationError('prop', { a: { b: 'c' }}, 'is invalid');
      getErrorDetails(err)
        .should.equal('`prop` is invalid (value: { a: [Object] }).');
    });

    it('should print only top-level props of objects in array', function() {
      var err = givenValidationError('prop', [{ a: { b: 'c' }}], 'is invalid');
      getErrorDetails(err)
        .should.equal('`prop` is invalid (value: [ { a: [Object] } ]).');
    });

    it('should exclude colors from Model values', function() {
      var obj = new User();
      obj.email = 'test@example.com';
      var err = givenValidationError('user', obj, 'is invalid');
      getErrorDetails(err).should.equal(
        '`user` is invalid (value: { email: \'test@example.com\' }).');
    });

    function givenValidationError(propertyName, propertyValue, errorMessage) {
      var jsonVal = {};
      jsonVal[propertyName] = propertyValue;
      var errorVal = {};
      errorVal[propertyName] = [errorMessage];

      var obj = {
        errors: errorVal,
        toJSON: function() { return jsonVal; },
      };
      return new ValidationError(obj);
    }

    function getErrorDetails(err) {
      return err.message.replace(/^.*Details: /, '');
    }
  });
});


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "languages".
 *
 * @property integer $language_id
 * @property string $language_name
 *
 * @property ItemLanguage[] $itemLanguages
 * @property MenuLanguage[] $menuLanguages
 */
class Languages extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'languages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['language_name','language_code'], 'required'],
            [['language_name'], 'string', 'max' => 255],
            [['language_code'], 'string', 'max' => 2],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'language_id' => 'Language ID',
            'language_name' => 'Language Name',
            'language_code'=> 'Language Code'
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getItemLanguages()
    {
        return $this->hasMany(ItemLanguage::className(), ['language_id' => 'language_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenuLanguages()
    {
        return $this->hasMany(MenuLanguage::className(), ['language_id' => 'language_id']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
//  (C) Copyright Edward Diener 2015
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#if !defined(BOOST_VMD_IS_VMD_SEQ_HPP)
#define BOOST_VMD_IS_VMD_SEQ_HPP

#include <boost/vmd/detail/setup.hpp>

#if BOOST_PP_VARIADICS

#include <boost/preprocessor/control/iif.hpp>
#include <boost/vmd/identity.hpp>
#include <boost/vmd/is_empty.hpp>
#include <boost/vmd/is_seq.hpp>

/*

  The succeeding comments in this file are in doxygen format.

*/

/** \file
*/

/** \def BOOST_VMD_IS_VMD_SEQ(sequence)

    \brief Determines if a sequence is a VMD seq.

    The macro checks that the sequence is a VMD seq.
    A VMD seq, which may be a Boost PP seq or emptiness, is a superset of a Boost PP seq.
    It returns 1 if it is a VMD seq, else if returns 0.

    sequence = a possible Boost PP seq

    returns = 1 if it a VMD seq, else returns 0.

*/

#define BOOST_VMD_IS_VMD_SEQ(sequence) \
    BOOST_VMD_IDENTITY_RESULT \
        ( \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_IS_EMPTY(sequence), \
            BOOST_VMD_IDENTITY(1), \
            BOOST_VMD_IS_SEQ \
            ) \
        (sequence) \
        ) \
/**/

#endif /* BOOST_PP_VARIADICS */
#endif /* BOOST_VMD_IS_VMD_SEQ_HPP */


text:
@class ManualFillActionItem;
@class ManualFillAddressItem;

// Objects conforming to this protocol need to react when new data is available.
@protocol ManualFillAddressConsumer

// Tells the consumer to show the passed addreses.
- (void)presentAddresses:(NSArray<ManualFillAddressItem*>*)addresses;

// Asks the consumer to present the passed actions
- (void)presentActions:(NSArray<ManualFillActionItem*>*)actions;

@end

#endif  // IOS_CHROME_BROWSER_UI_AUTOFILL_MANUAL_FILL_ADDRESS_CONSUMER_H_


text:
from settings_handler import settings
from job import EXECUTION_TYPES as job_execution_types
from job import WEEKDAYS as job_weekdays
import recipes_handler
import jobs_handler
import os
import settings_handler
import jobs_executor
import util
import _Getch

def makeMenu(options, directInput=True):
    sortedKeys = sorted(options)
    for key in sortedKeys:
        print "%5s %s" % (key, options[key]["name"])

    if directInput:
        print "Selection: ",
        selection = _Getch.getch()
        print
    else:
        selection = raw_input("Selection (commit with Enter): ")
    while not selection in options:
        print "Invalid selection"
        if directInput:
            print "New selection: ",
            selection = _Getch.getch()
            print
        else:
            selection = raw_input("New Selection: ")

    if "arg" in options[selection]:
        options[selection]["function"](*options[selection]["arg"])
    else:
        options[selection]["function"]()

def mainMenu():
    clear()
    print "Welcome to the paperboy server"
    print "What would you like to do"

    makeMenu(mainOptions)

def jobsMenu():
    clear()
    print "Jobs Menu"
    makeMenu(jobsOptions)

def listJobs():
    clear()
    copyListJobOptions = listJobsOptions.copy()

    print "List jobs:"

    for (index, job) in enumerate(jobs, 1):
        copyListJobOptions[str(index)] = jobOption(job.recipeRef, index - 1)

    makeMenu(copyListJobOptions)

def jobProperties(job):
    clear()
    copyJobPropertiesOptions = jobPropertiesOptions.copy()

    index = jobs.index(job)

    copyJobPropertiesOptions["d"] = {"name": "delete job",
                                     "function": deleteJob,
                                     "arg": [job]}

    optionsList = []
    optionsList.append({"name": "execution type: %20s" % job.executionType,
                        "function": changeJobInterval,
                        "arg": [job]})
    optionsList.append({"name": "execution time: %20s"
                        % util.formatTime(job.executionTime),
                        "function": changeJobExecutionTime,
                        "arg": [job]})
    if not job.executionType == "daily":
        optionsList.append({"name": "execution day : %20s" % job.executionDay,
                            "function": changeJobExecutionDay,
                            "arg": [job]})

    # append the options to the menu
    for (x, option) in enumerate(optionsList, 1):
        copyJobPropertiesOptions[str(x)] = option

    print "Properties of \"%s\"" % job.recipeRef
    makeMenu(copyJobPropertiesOptions)

def changeJobInterval(job):
    intervalOptions = {}
    for (x, interval) in enumerate(job_execution_types, 1):
        intervalOptions[str(x)] = {"name": interval,
                                   "function": setJobInterval,
                                   "arg": [job,
                                           job.setExecutionType,
                                           interval]}
    intervalOptions["x"] = {"name": "exit menu",
                            "function": jobProperties,
                            "arg": [job]}

    makeMenu(intervalOptions)

def setJobInterval(job, function, interval):
    function(interval)
    jobs_handler.saveJobs(jobs)
    jobProperties(job)

def changeJobExecutionTime(job):
    new_time = None

    while not new_time:
        new_time_str = raw_input("New Execution Time: ")
        try:
            new_time = util.parseTime(new_time_str)
        except:
            new_time = None
            print "Invalid time formate please write HH:MM"

    job.setExecutionTime(new_time)
    jobs_handler.saveJobs(jobs)
    jobProperties(job)

def changeJobExecutionDay(job):
    if job.executionType == "weekly":
        dayOptions = {}
        for (x, day) in enumerate(job_weekdays, 1):
            dayOptions[str(x)] = {"name": day,
                                  "function": setJobExecutionDay,
                                  "arg": [job, job.setExecutionDay, day]}
        dayOptions["x"] = {"name": "exit menu",
                           "function": jobProperties,
                           "arg": [job]}
        makeMenu(dayOptions)
    else:
        new_day = None
        while not new_day:
            new_day_str = raw_input("New execution day (1 to 30): ")
            try:
                new_day = int(new_day_str)
                if new_day < 1 or new_day > 30:
                    new_day = None
                    print "Invalid day please enter a number between 1 and 30."
            except:
                new_day = None
                print "Invalid day please enter a number between 1 and 30."

        job.setExecutionDay(new_day)
        jobs_handler.saveJobs(jobs)
        jobProperties(job)

def setJobExecutionDay(job, function, day):
    function(day)
    jobs_handler.saveJobs(jobs)
    jobProperties(job)

def jobOption(name, index):
    return {"name": "%s" % (name),
            "function": jobProperties,
            "arg": [jobs[index]]}

def deleteJob(job):
    jobs_handler.deleteJob(job)
    loadJobs()
    listJobs()

def newJob(startIndex=0):
    clear()
    nextIndex = startIndex + 10
    previousIndex = startIndex - 10
    recipes = recipes_handler.loadBuiltinRecipes()
    copyJobOptions = newJobOptions.copy()
    print "New Job (found %d)" % len(recipes)

    if startIndex > 0:
        copyJobOptions["p"] = {"name": "previous 10 recipes",
                               "function": newJob,
                               "arg": [previousIndex]}
    if nextIndex < len(recipes):
        copyJobOptions["n"] = {"name": "next 10 recipes",
                               "function": newJob,
                               "arg": [nextIndex]}

    for (recipe, x) in zip(recipes[startIndex:nextIndex],
                           range(startIndex, nextIndex)):
        newJobOption(copyJobOptions, x, recipe)

    makeMenu(copyJobOptions, False)

def filterJobsTitle():
    newValue = raw_input("New Title Filter: ")
    recipes_handler.titleFilter = newValue
    newJob()

def filterJobsDescription():
    newValue = raw_input("New Description Filter: ")
    recipes_handler.descriptionFilter = newValue
    newJob()

def filterJobsLanguage():
    newValue = raw_input("New Language Filter: ")
    recipes_handler.languageFilter = newValue
    newJob()

def newJobOption(dict, x, recipe):
    dict[str(x + 1)] = {"name": "[%s]%s" % (recipe.language, recipe.title),
                        "function": createJob,
                        "arg": [recipe.title]}

def createJob(ref):
    newJob = jobs_handler.newJob(ref)
    loadJobs()
    jobProperties(jobs[newJob.id])

def exitToMainMenu():
    mainMenu()

def settingsMenu():
    clear()
    print "Settings:"
    copySettingsOptions = settingsOptions.copy()

    # colletct options
    optionsList = []
    optionsList.append(newOption("Builtin recipes folder",
                                 settings.calibreFolder,
                                 settings.setCalibreFolder))
    optionsList.append(newOption("Export format", settings.format,
                                 settings.setFormat))
    optionsList.append(newOption("Mail from", settings.mailFrom,
                                 settings.setMailFrom))
    optionsList.append(newOption("Mail To", settings.mailTo,
                                 settings.setMailTo))

    if settings.useSmtp():
        print "Using SMPT"
        copySettingsOptions["s"] = {"name": "Use sendmail",
                                    "function": sendmailSettings}
        optionsList.append(newOption("Smtp server",
                                     settings.smtpServer["address"],
                                     settings.setSmtpServerAdress))
        if "port" in settings.smtpServer:
            optionsList.append(newOption("Smtp port",
                                         settings.smtpServer["port"],
                                         settings.setSmtpServerPort))
        if "security" in settings.smtpServer:
            optionsList.append(newOption("Smtp security",
                                         settings.smtpServer["security"],
                                         settings.setSmtpServerSecurity))
        if "login" in settings.smtpServer:
            optionsList.append(newOption("Smtp login",
                                         settings.smtpServer["login"],
                                         settings.setSmtpLogin))
        if "password" in settings.smtpServer:
            encodedPw = "*" * len(settings.smtpServer["password"])
            optionsList.append(newOption("Smtp password",
                                         encodedPw,
                                         settings.setSmtpPassword))
    else:
        print "Using sendmail"
        copySettingsOptions["s"] = {"name": "Use smtp server",
                                    "function": createDefaultSmtpSettings}

    # append the options to the menu
    for (x, option) in enumerate(optionsList, 1):
        copySettingsOptions[str(x)] = option

    print
    print "Options:"
    makeMenu(copySettingsOptions)

def quit():
    clear()
    print "Goodbye"

def editSetting(name, function):
    newValue = raw_input("%s: " % name)
    function(newValue)
    settings_handler.saveSettings()
    settingsMenu()

def createDefaultSmtpSettings():
    settings.setSmtpServer("localhost", 587, "starttls")
    settings.setSmtpLogin("username")
    settings.setSmtpPassword("username")
    settings_handler.saveSettings()
    settingsMenu()

def sendmailSettings():
    settings.deleteSmtpSettings()
    settings_handler.saveSettings()
    settingsMenu()

def newOption(name, option, function):
    return {"name": "%22s: %30s" % (name, str(option)),
            "function": editSetting,
            "arg": [name, function]}

def clear():
    os.system('clear')
    return

def executeJobs():
    clear()
    jobs_executor.execJobs(jobs)
    makeMenu(executeJobsOptions)

def loadJobs():
    global jobs
    jobs = jobs_handler.loadJobs()

mainOptions = {"1": {"name": "jobs", "function": jobsMenu},
               "2": {"name": "paperboy settings", "function": settingsMenu},
               "3": {"name": "execute jobs", "function": executeJobs},
               "q": {"name": "quit", "function": quit}}
jobsOptions = {"1": {"name": "list jobs", "function": listJobs},
               "2": {"name": "new job", "function": newJob, "arg": [0]},
               "x": {"name": "exit menu", "function": exitToMainMenu}}

newJobOptions = {"t": {"name": "filter title", "function": filterJobsTitle},
                 # "d": {"name": "filter description",
                 #       "function": filterJobsDescription},
                 "l": {"name": "filter language",
                       "function": filterJobsLanguage},
                 "x": {"name": "exit menu", "function": jobsMenu}}

listJobsOptions = {"x": {"name": "exit menu", "function": jobsMenu}}

jobPropertiesOptions = {"x": {"name": "exit menu", "function": listJobs}}

executeJobsOptions = {"x": {"name": "goto main menu",
                            "function": exitToMainMenu}}
settingsOptions = {"x": {"name": "exit menu", "function": exitToMainMenu}}

jobs = []
loadJobs()
mainMenu()


text:
@implementation NSDictionary (IDPExtension)

- (NSObject *)objectAtPath:(NSString *)path
{
    if (!path || path.length <=0 ) {
        return nil;
    }
	NSDictionary *dictProgress=[[self copy] autorelease];
    NSArray *strings = [path componentsSeparatedByString:@"/"];
    NSString *lastkey=[strings lastObject];
    for (int i=0;i<[strings count]-1;i++){
        NSString *pth=[strings objectAtIndex:i];
        if ([pth length]>0){
            if ([dictProgress isKindOfClass:[NSDictionary class]]){
                dictProgress=[dictProgress objectForKey:pth];
            }
            else
            {
//                @throw [NSException exceptionWithName:NSInvalidArchiveOperationException
//                                               reason:@"NSDictionnary::Path incorrect"
//                                             userInfo:nil];
                return nil;
            }
        }
    }
    if (dictProgress && [dictProgress isKindOfClass:[NSDictionary class]]) {
        return [dictProgress objectForKey:lastkey];
    }else
    {
        return nil;
    }

}

- (NSObject *)objectAtPath:(NSString *)path otherwise:(NSObject *)other
{
	NSObject * obj = [self objectAtPath:path];
	return obj ? obj : other;
}

- (BOOL)boolAtPath:(NSString *)path
{
	return [self boolAtPath:path otherwise:NO];
}

- (BOOL)boolAtPath:(NSString *)path otherwise:(BOOL)other
{
	NSObject * obj = [self objectAtPath:path];
	if ( [obj isKindOfClass:[NSNull class]] )
	{
		return NO;
	}
	else if ( [obj isKindOfClass:[NSNumber class]] )
	{
		return [(NSNumber *)obj intValue] ? YES : NO;
	}
	else if ( [obj isKindOfClass:[NSString class]] )
	{
		if ( [(NSString *)obj hasPrefix:@"y"] ||
			[(NSString *)obj hasPrefix:@"Y"] ||
			[(NSString *)obj hasPrefix:@"T"] ||
			[(NSString *)obj hasPrefix:@"t"] ||
			[(NSString *)obj isEqualToString:@"1"] )
		{
			// YES/Yes/yes/TRUE/Ture/true/1
			return YES;
		}
		else
		{
			return NO;
		}
	}

	return other;
}

- (NSNumber *)numberAtPath:(NSString *)path
{
	NSObject * obj = [self objectAtPath:path];
	if ( [obj isKindOfClass:[NSNull class]] )
	{
		return nil;
	}
	else if ( [obj isKindOfClass:[NSNumber class]] )
	{
		return (NSNumber *)obj;
	}
	else if ( [obj isKindOfClass:[NSString class]] )
	{
		return [NSNumber numberWithDouble:[(NSString *)obj doubleValue]];
	}

	return nil;
}

- (NSNumber *)numberAtPath:(NSString *)path otherwise:(NSNumber *)other
{
	NSNumber * obj = [self numberAtPath:path];
	return obj ? obj : other;
}

- (NSString *)stringAtPath:(NSString *)path
{
	NSObject * obj = [self objectAtPath:path];
	if ( [obj isKindOfClass:[NSNull class]] )
	{
		return nil;
	}
	else if ( [obj isKindOfClass:[NSNumber class]] )
	{
        return [NSString stringWithFormat:@"%@",(NSNumber *)obj];
//		return [NSString stringWithFormat:@"%d", [(NSNumber *)obj intValue]];
	}
	else if ( [obj isKindOfClass:[NSString class]] )
	{
		return (NSString *)obj;
	}

	return nil;
}

- (NSString *)stringAtPath:(NSString *)path otherwise:(NSString *)other
{
	NSString * obj = [self stringAtPath:path];
	return obj ? obj : other;
}

- (NSArray *)arrayAtPath:(NSString *)path
{
	NSObject * obj = [self objectAtPath:path];
	return [obj isKindOfClass:[NSArray class]] ? (NSArray *)obj : nil;
}

- (NSArray *)arrayAtPath:(NSString *)path otherwise:(NSArray *)other
{
	NSArray * obj = [self arrayAtPath:path];
	return obj ? obj : other;
}

- (NSMutableArray *)mutableArrayAtPath:(NSString *)path
{
	NSObject * obj = [self objectAtPath:path];
	return [obj isKindOfClass:[NSMutableArray class]] ? (NSMutableArray *)obj : nil;
}

- (NSMutableArray *)mutableArrayAtPath:(NSString *)path otherwise:(NSMutableArray *)other
{
	NSMutableArray * obj = [self mutableArrayAtPath:path];
	return obj ? obj : other;
}

- (NSDictionary *)dictAtPath:(NSString *)path
{
	NSObject * obj = [self objectAtPath:path];
	return [obj isKindOfClass:[NSDictionary class]] ? (NSDictionary *)obj : nil;
}

- (NSDictionary *)dictAtPath:(NSString *)path otherwise:(NSDictionary *)other
{
	NSDictionary * obj = [self dictAtPath:path];
	return obj ? obj : other;
}

- (NSMutableDictionary *)mutableDictAtPath:(NSString *)path
{
	NSObject * obj = [self objectAtPath:path];
	return [obj isKindOfClass:[NSMutableDictionary class]] ? (NSMutableDictionary *)obj : nil;
}

- (NSMutableDictionary *)mutableDictAtPath:(NSString *)path otherwise:(NSMutableDictionary *)other
{
	NSMutableDictionary * obj = [self mutableDictAtPath:path];
	return obj ? obj : other;
}

-(NSData*)data
{
    NSData* data = [NSKeyedArchiver archivedDataWithRootObject:self];
    return data;
}

@end

#pragma mark -

@implementation NSMutableDictionary (IDPExtension)

- (void)setObjectNoRetain:(id)anObject forKey:(id<NSCopying>)aKey
{
    [self setObject:anObject forKey:aKey];
    [anObject release];
}
- (void)removeObjectForKeyNoRelease:(id)aKey
{
    id value =[self objectForKey:aKey];
    if (value) {
        [value retain];
    }
    [self removeObjectForKey:aKey];
}
- (void)removeAllObjectsNoRelease
{
    for(id value in self.allValues)
    {
        [value retain];
    }
    [self removeAllObjects];
}
@end


text:
package models;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import internal.APIClient;
import internal.APIResponseHandler;
import internal.Constants;
import internal.JSONProcessor;

/**
 * Created by zachv on 7/20/15.
 * Wecrowd Android
 */

public class Campaign {
    // Protected members
    final Integer campaignID;
    final String title;
    private final String endDate;
    private Bitmap imageBMP;
    Integer goal;

    // Unexposed members
    String imageURL;

    // Constructors
    private Campaign(Integer ID, String title) {
        this.campaignID = ID;
        this.title = title;

        this.endDate = readableDateString();
    }

    private Campaign(Integer ID, String title, Integer goal) {
        this(ID, title);
        this.goal = goal;
    }

    Campaign(Integer ID, String title, Integer goal, String imageURL) {
        this(ID, title, goal);
        this.imageURL = imageURL;
    }

    // Static methods
    public static void fetchAllCampaigns(final APIResponseHandler responseHandler) {
        APIClient.get(Constants.ENDPOINT_FEATURED_CAMPAIGNS, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray responseArray) {
                super.onSuccess(statusCode, headers, responseArray);
                final Campaign[] campaigns = new Campaign[responseArray.length()];

                for (int i = 0; i < responseArray.length(); ++i) {
                    JSONObject responseObject;
                    Campaign campaign;

                    responseObject = JSONProcessor.jsonObjectFromArray(responseArray, i);

                    campaign = campaignFromJSONObject(responseObject);
                    campaigns[i] = campaign;
                }

                responseHandler.onCompletion(campaigns, null);
            }

            @Override
            public void onFailure(int statusCode,
                                  Header[] headers,
                                  String responseString,
                                  Throwable throwable)
            {
                super.onFailure(statusCode, headers, responseString, throwable);

                responseHandler.onCompletion((Campaign[]) null, throwable);
            }
        });
    }

    static Campaign campaignFromJSONObject(JSONObject object) {
        String title, imageURL;
        Integer ID, goal;

        ID = JSONProcessor.integerFromJSON(object, Constants.CAMPAIGN_ID);
        title = JSONProcessor.stringFromJSON(object, Constants.CAMPAIGN_NAME);
        imageURL = JSONProcessor.stringFromJSON(object, Constants.CAMPAIGN_IMAGE_URL);
        goal = JSONProcessor.integerFromJSON(object, Constants.CAMPAIGN_GOAL);

        return new Campaign(ID, title, goal, imageURL);
    }

    // External methods
    public static void fetchImage(final Campaign campaign,
                                  final APIResponseHandler responseHandler)
    {
        if (campaign.imageBMP == null) {
            APIClient.getFromRaw(campaign.imageURL, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
                    campaign.imageBMP = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    if (responseHandler != null) {
                        responseHandler.onCompletion(campaign.imageBMP, null);
                    }
                }

                @Override
                public void onFailure(int statusCode,
                                      Header[] headers,
                                      byte[] bytes,
                                      Throwable throwable) {
                    if (responseHandler != null) {
                        responseHandler.onCompletion((Bitmap) null, throwable);
                    }
                }
            });
        } else {
            responseHandler.onCompletion(campaign.imageBMP, null);
        }
    }

    // Utilities
    private String readableDateString() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);

        return dateFormat.format(Calendar.getInstance().getTime());
    }

    // Accessors
    public Integer getCampaignID() { return campaignID; }
    public String getTitle() { return title; }
    public String getEndDate() { return endDate; }
    public Integer getGoal() { return goal; }
}


text:
package org.apache.openwhisk.core.database.test.behavior

import java.time.Instant

import org.apache.openwhisk.common.TransactionId
import org.apache.openwhisk.core.database.{
  DocumentConflictException,
  DocumentProvider,
  DocumentRevisionMismatchException,
  NoDocumentException
}
import org.apache.openwhisk.core.entity._

trait ArtifactStoreCRUDBehaviors extends ArtifactStoreBehaviorBase {

  behavior of s"${storeType}ArtifactStore put"

  it should "put document and get a revision 1" in {
    implicit val tid: TransactionId = transid()
    val doc = put(authStore, newAuth())
    doc.rev.empty shouldBe false
  }

  it should "put and update document" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)

    val auth2 =
      getWhiskAuth(doc)
        .copy(namespaces = Set(wskNS("foo1")))
        .revision[WhiskAuth](doc.rev)
    val doc2 = put(authStore, auth2)

    doc2.rev should not be doc.rev
    doc2.rev.empty shouldBe false
  }

  it should "put delete and then recreate document with same id with different rev" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)

    delete(authStore, doc) shouldBe true

    val auth2 = auth.copy(namespaces = Set(wskNS("foo1")))
    val doc2 = put(authStore, auth2)

    doc2.rev should not be doc.rev
    doc2.rev.empty shouldBe false
  }

  it should "throw DocumentConflictException when updated with old revision" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)

    val auth2 = getWhiskAuth(doc).copy(namespaces = Set(wskNS("foo1"))).revision[WhiskAuth](doc.rev)
    val doc2 = put(authStore, auth2)

    //Updated with _rev set to older one
    val auth3 = getWhiskAuth(doc2).copy(namespaces = Set(wskNS("foo2"))).revision[WhiskAuth](doc.rev)
    intercept[DocumentConflictException] {
      put(authStore, auth3)
    }
  }

  it should "throw DocumentConflictException if document with same id is inserted twice" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)

    intercept[DocumentConflictException] {
      put(authStore, auth)
    }
  }

  it should "work if same document was deleted earlier" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    //1. Create a document
    val doc = put(authStore, auth)

    //2. Now delete the document
    delete(authStore, doc) shouldBe true

    //3. Now recreate the same document.
    val doc2 = put(authStore, auth)

    //Recreating a deleted document should work
    doc2.rev.empty shouldBe false
  }

  behavior of s"${storeType}ArtifactStore delete"

  it should "deletes existing document" in {
    implicit val tid: TransactionId = transid()
    val doc = put(authStore, newAuth())
    delete(authStore, doc) shouldBe true
  }

  it should "throws IllegalArgumentException when deleting without revision" in {
    intercept[IllegalArgumentException] {
      implicit val tid: TransactionId = transid()
      delete(authStore, DocInfo("doc-with-empty-revision"))
    }
  }

  it should "throws NoDocumentException when document does not exist" in {
    intercept[NoDocumentException] {
      implicit val tid: TransactionId = transid()
      delete(authStore, DocInfo ! ("non-existing-doc", "42"))
    }
  }

  it should "throws DocumentConflictException when revision does not match" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)

    val auth2 = getWhiskAuth(doc).copy(namespaces = Set(wskNS("foo1"))).revision[WhiskAuth](doc.rev)
    val doc2 = put(authStore, auth2)

    intercept[DocumentConflictException] {
      delete(authStore, doc)
    }
  }

  behavior of s"${storeType}ArtifactStore get"

  it should "get existing entity matching id and rev" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)
    val authFromGet = getWhiskAuth(doc)
    authFromGet shouldBe auth
    authFromGet.docinfo.rev shouldBe doc.rev
  }

  it should "get existing entity matching id only" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)
    val authFromGet = getWhiskAuth(doc)
    authFromGet shouldBe auth
  }

  it should "get entity with timestamp" in {
    implicit val tid: TransactionId = transid()
    val activation = WhiskActivation(
      EntityPath("testnamespace"),
      EntityName("activation1"),
      Subject(),
      ActivationId.generate(),
      start = Instant.now.inMills,
      end = Instant.now.inMills)
    val activationDoc = put(activationStore, activation)
    val activationFromDb = activationStore.get[WhiskActivation](activationDoc).futureValue
    activationFromDb shouldBe activation
  }

  it should "throws DocumentRevisionMismatchException when document revision does not match" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    val doc = put(authStore, auth)

    val auth2 = getWhiskAuth(doc).copy(namespaces = Set(wskNS("foo1"))).revision[WhiskAuth](doc.rev)
    val doc2 = put(authStore, auth2)

    authStore.get[WhiskAuth](doc).failed.futureValue shouldBe a[DocumentRevisionMismatchException]

    val authFromGet = getWhiskAuth(doc2)
    authFromGet shouldBe auth2
  }

  it should "throws NoDocumentException when document does not exist" in {
    implicit val tid: TransactionId = transid()
    authStore.get[WhiskAuth](DocInfo("non-existing-doc")).failed.futureValue shouldBe a[NoDocumentException]
  }

  it should "not get a deleted document" in {
    implicit val tid: TransactionId = transid()
    val auth = newAuth()
    //1. Create a document
    val docInfo = put(authStore, auth)

    //2. Now delete the document
    delete(authStore, docInfo) shouldBe true

    //3. Now getting a deleted document should fail
    authStore.get[WhiskAuth](docInfo).failed.futureValue shouldBe a[NoDocumentException]

    //Check get by id flow also which return none for such "soft" deleted document
    authStore match {
      case provider: DocumentProvider =>
        provider.get(docInfo.id).futureValue shouldBe None
      case _ =>
    }
  }
}


text:
'use strict'

var chai = require('chai')
var dirtyChai = require('dirty-chai')
var expect = chai.expect
chai.use(dirtyChai)

let path = require('path')
var ActionheroPrototype = require(path.join(__dirname, '/../../actionhero.js'))
var actionhero = new ActionheroPrototype()
var api

describe('Action: Cache', () => {
  before((done) => {
    actionhero.start((error, a) => {
      expect(error).to.be.null()
      api = a
      done()
    })
  })

  after((done) => {
    actionhero.stop(() => {
      done()
    })
  })

  it('no params', (done) => {
    api.specHelper.runAction('cacheTest', {}, (response) => {
      expect(response.error).to.equal('Error: key is a required parameter for this action')
      done()
    })
  })

  it('just key', (done) => {
    api.specHelper.runAction('cacheTest', {key: 'test key'}, (response) => {
      expect(response.error).to.equal('Error: value is a required parameter for this action')
      done()
    })
  })

  it('just value', (done) => {
    api.specHelper.runAction('cacheTest', {value: 'abc123'}, (response) => {
      expect(response.error).to.equal('Error: key is a required parameter for this action')
      done()
    })
  })

  it('gibberish param', (done) => {
    api.specHelper.runAction('cacheTest', {thingy: 'abc123'}, (response) => {
      expect(response.error).to.equal('Error: key is a required parameter for this action')
      done()
    })
  })

  it('requires value to be longer than 2 letters', (done) => {
    api.specHelper.runAction('cacheTest', {key: 'abc123', value: 'v'}, (response) => {
      expect(response.error).to.equal('Error: `value` should be at least 3 letters long')
      done()
    })
  })

  it('correct params', (done) => {
    api.specHelper.runAction('cacheTest', {key: 'testKey', value: 'abc123'}, (response) => {
      expect(response.cacheTestResults.saveResp).to.equal(true)
      expect(response.cacheTestResults.loadResp.value).to.equal('abc123')
      expect(response.cacheTestResults.deleteResp).to.equal(true)
      done()
    })
  })
})


text:
class Background : public Entity {
public:
  Background(TextureHolder &textures);
  void setPosition(sf::Vector2f pos);

private:
  virtual void updateCurrent(sf::Time dt);
  virtual void drawCurrent(sf::RenderTarget &target,
                           sf::RenderStates states) const;

private:
  sf::Sprite mSprite;
  sf::Vector2f mPosition;
};

#endif // BACKGROUND_H


text:
<!DOCTYPE html>

    <title>Softuni Blog</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="styles/style.css" />

                Softuni Blog

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>

Welcome (user)

New Post

Logout

                            Something Happened !

                            Problems for exercises and homework for the "Software Technologies" course @ SoftUni.
							After following the steps for this exercise, you should have built the base for our blog.
							Note that this exercise uses bootstrap extensively, so every HTML code you write will be instantly stylized and will look good off the shelf. This is not the case when you write plain HTML without ready styles.
							However, pay attention to the <tags> that we are using. Almost all <tags> that we are going to write use a class="" attribute (that is <tag class="some class">). The class="" attribute points to the corresponding selector in the style.css file. This is exactly the same as when you are writing your own styles but in our case, they are provided by the open source framework called bootstrap.
							With this in mind, let's get to work.

                        Author

                                back &raquo

© 2017 - Software university foundation!


text:
/**
 * The goal of these tests is to verify the behavior of all blob commands given
 * the current state is notYetStarted.  The initial state.
 */
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"

#include <cstdint>
#include <string>
#include <vector>

#include <gtest/gtest.h>

namespace ipmi_flash
{
namespace
{

using ::testing::Return;
using ::testing::UnorderedElementsAreArray;

class FirmwareHandlerNotYetStartedTest : public IpmiOnlyFirmwareStaticTest
{};

/*
 * There are the following calls (parameters may vary):
 * Note: you cannot have a session yet, so only commands that don't take a
 * session parameter are valid. Once you open() from this state, we will vary
 * you transition out of this state (ensuring the above is true). Technically
 * the firmware handler receives the session number with open(), but the blob
 * manager is providing this normally.
 *
 * canHandleBlob
 * getBlobIds
 * deleteBlob
 * stat
 * open
 *
 * canHandleBlob is just a count check (or something similar) against what is
 * returned by getBlobIds.  It is tested in firmware_canhandle_unittest
 */

/*
 * deleteBlob()
 */
TEST_F(FirmwareHandlerNotYetStartedTest, DeleteBlobInStateReturnsFalse)
{
    auto blobs = handler->getBlobIds();
    for (const auto& b : blobs)
    {
        EXPECT_FALSE(handler->deleteBlob(b));
    }
}

/* canHandleBlob, getBlobIds */
TEST_F(FirmwareHandlerNotYetStartedTest, GetBlobListValidateListContents)
{
    /* By only checking that the hash and static blob ids are present to start
     * with, we're also verifying others aren't.
     */
    EXPECT_THAT(handler->getBlobIds(),
                UnorderedElementsAreArray(startingBlobs));

    /* Verify canHandleBlob is reading from the same list (basically) */
    for (const auto& blob : startingBlobs)
    {
        EXPECT_TRUE(handler->canHandleBlob(blob));
    }
}

/* stat(blob_id) */
TEST_F(FirmwareHandlerNotYetStartedTest, StatEachBlobIdVerifyResults)
{
    /* In this original state, calling stat() on the blob ids will return the
     * idle status
     */

    auto blobs = handler->getBlobIds();
    for (const auto& blob : blobs)
    {
        blobs::BlobMeta meta = {};
        EXPECT_TRUE(handler->stat(blob, &meta));
        EXPECT_EQ(expectedIdleMeta, meta);
    }
}

/* open(each blob id) (verifyblobid will no longer be available at this state.
 */
TEST_F(FirmwareHandlerNotYetStartedTest, OpenStaticImageFileVerifyStateChange)
{
    EXPECT_CALL(*imageMock2, open(staticLayoutBlobId, std::ios::out))
        .WillOnce(Return(true));
    EXPECT_CALL(*prepareMockPtr, trigger()).WillOnce(Return(true));

    EXPECT_TRUE(handler->open(session, flags, staticLayoutBlobId));

    expectedState(FirmwareBlobHandler::UpdateState::uploadInProgress);

    EXPECT_TRUE(handler->canHandleBlob(activeImageBlobId));
}

TEST_F(FirmwareHandlerNotYetStartedTest, OpenHashFileVerifyStateChange)
{
    EXPECT_CALL(*hashImageMock, open(hashBlobId, std::ios::out))
        .WillOnce(Return(true));
    /* Opening the hash blob id doesn't trigger a preparation, only a firmware
     * blob.
     */
    EXPECT_CALL(*prepareMockPtr, trigger()).Times(0);

    EXPECT_TRUE(handler->open(session, flags, hashBlobId));

    expectedState(FirmwareBlobHandler::UpdateState::uploadInProgress);

    EXPECT_TRUE(handler->canHandleBlob(activeHashBlobId));
}

/*
 * expire(session)
 */
TEST_F(FirmwareHandlerNotYetStartedTest, ExpireOnNotYetStartedAbortsProcess)
{
    ASSERT_TRUE(handler->expire(session));

    EXPECT_THAT(handler->getBlobIds(),
                UnorderedElementsAreArray(startingBlobs));

    expectedState(FirmwareBlobHandler::UpdateState::notYetStarted);
}

} // namespace
} // namespace ipmi_flash


text:
require 'finacle_api/common/serializable_object'
require 'finacle_api/bal_inq/response/bank_info'
require 'finacle_api/bal_inq/response/acct_type'

module FinacleApi
  module BalInq
    module ResponseEntity
      class AcctId < SerializableObject
        attr_accessor :acct_id, :acct_type, :acct_curr, :bank_info
        def initialize(options={})
          options ||= {}
          @acct_type = AcctType.new(options.delete(:acct_type))
          @bank_info = BankInfo.new(options.delete(:bank_info))
          options.each do |key, value|
            send(:"#{key}=", value) if respond_to?(:"#{key}=")
          end
        end
      end
    end
  end
end


text:
from .cfcoords import translate_coords
from .datamodels import CDS, ECMWF

__all__ = ["CDS", "ECMWF", "translate_coords"]


text:
'use strict';

var path   = require('path')
  , chai   = require('chai')
  , helper = require(path.join(__dirname, 'lib', 'agent_helper.js'))
  , facts  = require(path.join(__dirname, '..', 'lib', 'collector', 'facts.js'))
  , API    = require(path.join(__dirname, '..', 'api.js'))
  , Config = require(path.join(__dirname, '..', 'lib', 'config'))
  ;

var should = chai.should();

describe('high security mode', function () {

  describe('config to be sent during connect', function () {
    var agent
      , api
      ;

    beforeEach(function () {
      agent = helper.loadMockedAgent();
      api = new API(agent);
    });

    afterEach(function () {
      helper.unloadAgent(agent);
    });

    it('should contain high_security', function () {
      var factoids = facts(agent);
      factoids.high_security.should.not.equal(null);
    });
  });

  describe('conditional application of server side settings', function () {
    var config;

    describe('high_security === true', function () {
      beforeEach(function () {
        config = new Config({high_security: true});
      });

      it('should reject disabling ssl', function () {
        // enabled by defualt, but lets make sure.
        config.ssl = true;
        config.onConnect({high_security: true, ssl: false});
        config.ssl.should.equal(true);
      });

      it('should reject enabling capture_params', function () {
        // disabled by default, but lets make sure.
        config.capture_params = false;
        config.onConnect({high_security: true, capture_params: true});
        config.capture_params.should.equal(false);
      });

      it('should shut down the agent if high_security is false', function () {
        config.onConnect({high_security: false});
        config.agent_enabled.should.equal(false);
      });

      it('should shut down the agent if high_security is missing', function () {
        config.onConnect({});
        config.agent_enabled.should.equal(false);
      });
    });

    describe('high_security === false', function () {
      beforeEach(function () {
        config = new Config({high_security: false});
      });

      it('should accept disabling ssl', function () {
        // enabled by defualt, but lets make sure.
        config.ssl = true;
        config.onConnect({ssl: false});
        config.ssl.should.equal(false);
      });

      it('should accept enabling capture_params', function () {
        // disabled by default, but lets make sure.
        config.capture_params = false;
        config.onConnect({capture_params: true});
        config.capture_params.should.equal(true);
      });
    });
  });

  describe('coerces other settings', function () {
    describe('_applyHighSecurity during init', function () {
      var orig = Config.prototype._applyHighSecurity;
      var called;

      beforeEach(function () {
        called = false;
        Config.prototype._applyHighSecurity = function() {
          called = true;
        };
      });

      afterEach(function () {
        Config.prototype._applyHighSecurity = orig;
      });

      it('should call if high_security is on', function () {
        // jshint nonew:false
        new Config({high_security: true});
        // jshint nonew:true
        called.should.equal(true);
      });

      it('should not call if high_security is off', function () {
        // jshint nonew:false
        new Config({high_security: false});
        // jshint nonew:true
        called.should.equal(false);
      });
    });

    describe('high_security === true', function () {
      it('should detect that ssl is off', function (done) {
        var config = new Config({high_security: true});
        config.ssl = false;
        config.on('ssl', function(value) {
          value.should.equal(true);
          config.ssl.should.equal(true);
          done();
        });
        config._applyHighSecurity();
      });

      it('should detect that capture_params is on', function (done) {
        var config = new Config({'high_security': true});
        config.capture_params = true;
        config.on('capture_params', function(value) {
          value.should.equal(false);
          config.capture_params.should.equal(false);
          done();
        });
        config._applyHighSecurity();
      });

      it('should detect no problems', function () {
        var config = new Config({high_security: true});
        config.ssl = true;
        config.capture_params = false;
        config._applyHighSecurity();
        config.ssl.should.equal(true);
        config.capture_params.should.equal(false);
      });
    });
  });

  describe('affect custom params', function () {
    var agent
      , api
      ;

    beforeEach(function () {
      agent = helper.loadMockedAgent();
      api = new API(agent);
    });

    afterEach(function () {
      helper.unloadAgent(agent);
    });

    it('should disable addCustomParameter if high_security is on', function () {
      agent.config.high_security = true;
      var success = api.addCustomParameter('key', 'value');
      success.should.equal(false);
    });

    it('should not affect addCustomParameter if high_security is off', function () {
      agent.config.high_security = false;
      var success = api.addCustomParameter('key', 'value');
      should.not.exist(success);
    });
  });
});


text:
graph LR
ui[fa:fa-user User interface] --> backend(Backend)
backend[fa:fa-cogs Backend] --> rmq(fa:fa-bars Message broker)
backend --> DB(fa:fa-database Database)
rmq --> W1[fa:fa-cog Worker 1]
rmq --> W2[fa:fa-cog Worker 2]
rmq --> W3[fa:fa-cog Worker 3]

classDef blue fill:#155799,stroke: none,color: #fff;
classDef green fill:#159957,stroke: none,color: #fff;

class ui green
class backend blue
class rmq blue
class DB blue
class W1 green
class W2 green
class W3 green


text:
package org.apache.river.test.spec.activation.activatableinvocationhandler;

import java.util.logging.Level;
import net.jini.activation.ActivatableInvocationHandler;
import org.apache.river.qa.harness.TestException;
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.qa.harness.Test;
import net.jini.activation.arg.ActivationID;
import org.apache.river.test.spec.activation.util.FakeActivationID;
import org.apache.river.test.spec.activation.util.RMCProxy;

/**
 * <pre>
 * Purpose
 *   This test verifies the behavior of the
 *   ActivatableInvocationHandler.checkTrustEquivalence method
 *   during normal and exceptional calls.
 *
 * Test Cases
 *   This test contains one test case defined by the Actions section below.
 *
 * Infrastructure
 *   This test requires the following infrastructure:
 *     1) FakeActivationID
 *     2) RMCProxy
 *
 * Actions
 *   For each test case the test performs the following steps:
 *       1) construct a ActivatableInvocationHandler object
 *          passing FakeActivationID and RMCProxy as a
 *          parameters
 *       2) call the checkTrustEquivalence method passing
 *          the same constructed handler as a parameter;
 *          verify the return value is true
 *       3) construct some object;
 *          call the checkTrustEquivalence method passing
 *          constructed object as a parameter;
 *          verify the return value is false
 *       4) construct another ActivatableInvocationHandler object
 *          passing new FakeActivationID and RMCProxy as a
 *          parameters
 *       5) adjust FakeActivationID so that it's checkTrustEquivalence
 *          method should return false;
 *          call the checkTrustEquivalence method passing
 *          the second handler as a parameter;
 *          verify the return value is false
 *       6) adjust FakeActivationID so that it's checkTrustEquivalence
 *          method should return true;
 *          call the checkTrustEquivalence method passing
 *          the second handler as a parameter;
 *          verify the return value is true
 * </pre>
 */
public class CheckTrustEquivalence_Test extends QATestEnvironment implements Test {

    /**
     * This method performs all actions mentioned in class description.
     */
    public void run() throws Exception {
        FakeActivationID aid = new FakeActivationID(logger);
        RMCProxy fp = new RMCProxy(logger);
        ActivatableInvocationHandler handler = new
                ActivatableInvocationHandler(aid, fp);
        assertion(handler.checkTrustEquivalence(handler));
        Object o = new Object();
        assertion(!handler.checkTrustEquivalence(o));

        ActivationID aid2 = new FakeActivationID(logger);
        RMCProxy fp2 = new RMCProxy(logger);
        ActivatableInvocationHandler handler2 = new
                ActivatableInvocationHandler(aid, fp);
        aid.setTrustEquivalence(false);
        assertion(!handler.checkTrustEquivalence(handler2));
        aid.setTrustEquivalence(true);
        assertion(handler.checkTrustEquivalence(handler2));
    }
}


text:
package openapi

import (
	"fmt"
	"reflect"
	"sync"
	"time"

	"github.com/go-openapi/spec"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"
	"k8s.io/klog"
	"k8s.io/kube-openapi/pkg/handler"

	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
	informers "k8s.io/apiextensions-apiserver/pkg/client/informers/internalversion/apiextensions/internalversion"
	listers "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/internalversion"
)

// Controller watches CustomResourceDefinitions and publishes validation schema
type Controller struct {
	crdLister  listers.CustomResourceDefinitionLister
	crdsSynced cache.InformerSynced

	// To allow injection for testing.
	syncFn func(string) error

	queue workqueue.RateLimitingInterface

	staticSpec     *spec.Swagger
	openAPIService *handler.OpenAPIService

	// specs per version and per CRD name
	lock     sync.Mutex
	crdSpecs map[string]map[string]*spec.Swagger
}

// NewController creates a new Controller with input CustomResourceDefinition informer
func NewController(crdInformer informers.CustomResourceDefinitionInformer) *Controller {
	c := &Controller{
		crdLister:  crdInformer.Lister(),
		crdsSynced: crdInformer.Informer().HasSynced,
		queue:      workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "crd_openapi_controller"),
		crdSpecs:   map[string]map[string]*spec.Swagger{},
	}

	crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc:    c.addCustomResourceDefinition,
		UpdateFunc: c.updateCustomResourceDefinition,
		DeleteFunc: c.deleteCustomResourceDefinition,
	})

	c.syncFn = c.sync
	return c
}

// Run sets openAPIAggregationManager and starts workers
func (c *Controller) Run(staticSpec *spec.Swagger, openAPIService *handler.OpenAPIService, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()
	defer klog.Infof("Shutting down OpenAPI controller")

	klog.Infof("Starting OpenAPI controller")

	c.staticSpec = staticSpec
	c.openAPIService = openAPIService

	if !cache.WaitForCacheSync(stopCh, c.crdsSynced) {
		utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
		return
	}

	// create initial spec to avoid merging once per CRD on startup
	crds, err := c.crdLister.List(labels.Everything())
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("failed to initially list all CRDs: %v", err))
		return
	}
	for _, crd := range crds {
		if !apiextensions.IsCRDConditionTrue(crd, apiextensions.Established) {
			continue
		}
		newSpecs, changed, err := buildVersionSpecs(crd, nil)
		if err != nil {
			utilruntime.HandleError(fmt.Errorf("failed to build OpenAPI spec of CRD %s: %v", crd.Name, err))
		} else if !changed {
			continue
		}
		c.crdSpecs[crd.Name] = newSpecs
	}
	if err := c.updateSpecLocked(); err != nil {
		utilruntime.HandleError(fmt.Errorf("failed to initially create OpenAPI spec for CRDs: %v", err))
		return
	}

	// only start one worker thread since its a slow moving API
	go wait.Until(c.runWorker, time.Second, stopCh)

	<-stopCh
}

func (c *Controller) runWorker() {
	for c.processNextWorkItem() {
	}
}

func (c *Controller) processNextWorkItem() bool {
	key, quit := c.queue.Get()
	if quit {
		return false
	}
	defer c.queue.Done(key)

	// log slow aggregations
	start := time.Now()
	defer func() {
		elapsed := time.Since(start)
		if elapsed > time.Second {
			klog.Warningf("slow openapi aggregation of %q: %s", key.(string), elapsed)
		}
	}()

	err := c.syncFn(key.(string))
	if err == nil {
		c.queue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
	c.queue.AddRateLimited(key)
	return true
}

func (c *Controller) sync(name string) error {
	c.lock.Lock()
	defer c.lock.Unlock()

	crd, err := c.crdLister.Get(name)
	if err != nil && !errors.IsNotFound(err) {
		return err
	}

	// do we have to remove all specs of this CRD?
	if errors.IsNotFound(err) || !apiextensions.IsCRDConditionTrue(crd, apiextensions.Established) {
		if _, found := c.crdSpecs[name]; !found {
			return nil
		}
		delete(c.crdSpecs, name)
		return c.updateSpecLocked()
	}

	// compute CRD spec and see whether it changed
	oldSpecs := c.crdSpecs[crd.Name]
	newSpecs, changed, err := buildVersionSpecs(crd, oldSpecs)
	if err != nil {
		return err
	}
	if !changed {
		return nil
	}

	// update specs of this CRD
	c.crdSpecs[crd.Name] = newSpecs
	return c.updateSpecLocked()
}

func buildVersionSpecs(crd *apiextensions.CustomResourceDefinition, oldSpecs map[string]*spec.Swagger) (map[string]*spec.Swagger, bool, error) {
	newSpecs := map[string]*spec.Swagger{}
	anyChanged := false
	for _, v := range crd.Spec.Versions {
		if !v.Served {
			continue
		}
		spec, err := BuildSwagger(crd, v.Name)
		if err != nil {
			return nil, false, err
		}
		newSpecs[v.Name] = spec
		if oldSpecs[v.Name] == nil || !reflect.DeepEqual(oldSpecs[v.Name], spec) {
			anyChanged = true
		}
	}
	if !anyChanged && len(oldSpecs) == len(newSpecs) {
		return newSpecs, false, nil
	}

	return newSpecs, true, nil
}

// updateSpecLocked aggregates all OpenAPI specs and updates openAPIService.
// It is not thread-safe. The caller is responsible to hold proper lock (Controller.lock).
func (c *Controller) updateSpecLocked() error {
	crdSpecs := []*spec.Swagger{}
	for _, versionSpecs := range c.crdSpecs {
		for _, s := range versionSpecs {
			crdSpecs = append(crdSpecs, s)
		}
	}
	return c.openAPIService.UpdateSpec(mergeSpecs(c.staticSpec, crdSpecs...))
}

func (c *Controller) addCustomResourceDefinition(obj interface{}) {
	castObj := obj.(*apiextensions.CustomResourceDefinition)
	klog.V(4).Infof("Adding customresourcedefinition %s", castObj.Name)
	c.enqueue(castObj)
}

func (c *Controller) updateCustomResourceDefinition(oldObj, newObj interface{}) {
	castNewObj := newObj.(*apiextensions.CustomResourceDefinition)
	klog.V(4).Infof("Updating customresourcedefinition %s", castNewObj.Name)
	c.enqueue(castNewObj)
}

func (c *Controller) deleteCustomResourceDefinition(obj interface{}) {
	castObj, ok := obj.(*apiextensions.CustomResourceDefinition)
	if !ok {
		tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
		if !ok {
			klog.Errorf("Couldn't get object from tombstone %#v", obj)
			return
		}
		castObj, ok = tombstone.Obj.(*apiextensions.CustomResourceDefinition)
		if !ok {
			klog.Errorf("Tombstone contained object that is not expected %#v", obj)
			return
		}
	}
	klog.V(4).Infof("Deleting customresourcedefinition %q", castObj.Name)
	c.enqueue(castObj)
}

func (c *Controller) enqueue(obj *apiextensions.CustomResourceDefinition) {
	c.queue.Add(obj.Name)
}


text:
#ifndef QPID_BROKER_AMQP_FILTER_H
#define QPID_BROKER_AMQP_FILTER_H

#include "qpid/amqp/MapReader.h"
#include "qpid/amqp/Descriptor.h"
#include "qpid/types/Variant.h"
#include <map>
#include <vector>
#include <boost/shared_ptr.hpp>

struct pn_data_t;
namespace qpid {
namespace broker {
class Exchange;
class Queue;
struct QueueSettings;
namespace amqp {
class Outgoing;

class Filter : private qpid::amqp::MapReader
{
  public:
    Filter();
    void read(pn_data_t*);
    void write(pn_data_t*);
    std::string getBindingKey(boost::shared_ptr<Exchange> exchange) const;

    /**
     * Apply filters where source is a queue
     */
    void apply(boost::shared_ptr<Outgoing> queue);

    /**
     * Configure subscription queue for case where source is an exchange
     */
    void configure(QueueSettings&);
    /**
     * Bind subscription queue for case where source is an exchange
     */
    void bind(boost::shared_ptr<Exchange> exchange, boost::shared_ptr<Queue> queue);

    /**
     * Not really the ideal place for this, but the logic is already implemented here...
     */
    static void write(std::map<std::string, qpid::types::Variant> source, pn_data_t* target);
  private:
    struct FilterBase
    {
        bool described;
        bool requested;
        qpid::amqp::Descriptor descriptor;
        std::string key;
        FilterBase();
        virtual ~FilterBase();
        void write(pn_data_t*);
        virtual void writeValue(pn_data_t*) = 0;
        void setDescriptor(const qpid::amqp::Descriptor&);
    };
    struct StringFilter : FilterBase
    {
        std::string value;
        void writeValue(pn_data_t*);
    };
    struct MapFilter : FilterBase
    {
        typedef std::map<std::string, qpid::types::Variant> ValueType;
        ValueType value;
        void writeValue(pn_data_t*);
    };

    void onStringValue(const qpid::amqp::CharSequence& key, const qpid::amqp::CharSequence& value, const qpid::amqp::Descriptor* descriptor);
    void onNullValue(const qpid::amqp::CharSequence&, const qpid::amqp::Descriptor*);
    void onBooleanValue(const qpid::amqp::CharSequence&, bool, const qpid::amqp::Descriptor*);
    void onUByteValue(const qpid::amqp::CharSequence&, uint8_t, const qpid::amqp::Descriptor*);
    void onUShortValue(const qpid::amqp::CharSequence&, uint16_t, const qpid::amqp::Descriptor*);
    void onUIntValue(const qpid::amqp::CharSequence&, uint32_t, const qpid::amqp::Descriptor*);
    void onULongValue(const qpid::amqp::CharSequence&, uint64_t, const qpid::amqp::Descriptor*);
    void onByteValue(const qpid::amqp::CharSequence&, int8_t, const qpid::amqp::Descriptor*);
    void onShortValue(const qpid::amqp::CharSequence&, int16_t, const qpid::amqp::Descriptor*);
    void onIntValue(const qpid::amqp::CharSequence&, int32_t, const qpid::amqp::Descriptor*);
    void onLongValue(const qpid::amqp::CharSequence&, int64_t, const qpid::amqp::Descriptor*);
    void onFloatValue(const qpid::amqp::CharSequence&, float, const qpid::amqp::Descriptor*);
    void onDoubleValue(const qpid::amqp::CharSequence&, double, const qpid::amqp::Descriptor*);
    bool onStartListValue(const qpid::amqp::CharSequence& key, uint32_t count, const qpid::amqp::Descriptor* descriptor);
    bool onStartMapValue(const qpid::amqp::CharSequence& key, uint32_t count, const qpid::amqp::Descriptor* descriptor);
    void onEndMapValue(const qpid::amqp::CharSequence& key, uint32_t count, const qpid::amqp::Descriptor* descriptor);
    void setFilter(StringFilter&, const StringFilter&);
    bool hasSubjectFilter() const;
    std::string getSubjectFilter() const;
    bool hasSelectorFilter() const;
    std::string getSelectorFilter() const;
    bool setDefaultSubjectFilter(bool wildcards=false);
    bool setDefaultSubjectFilter(const qpid::amqp::Descriptor& descriptor, const std::string& value=std::string());
    bool adjustDirectFilter();
    void setDefaultHeadersFilter();
    void setDefaultXQueryFilter();

    StringFilter subjectFilter;
    StringFilter selectorFilter;
    StringFilter xqueryFilter;
    MapFilter headersFilter;
    std::vector<FilterBase*> active;
    bool inHeadersMap;
    bool nolocal;
};
}}} // namespace qpid::broker::amqp

#endif  /*!QPID_BROKER_AMQP_FILTER_H*/


text:
package transactional

import "github.com/go-git/go-git/v5/config"

// ConfigStorage implements the storer.ConfigStorage for the transactional package.
type ConfigStorage struct {
	config.ConfigStorer
	temporal config.ConfigStorer

	set bool
}

// NewConfigStorage returns a new ConfigStorer based on a base storer and a
// temporal storer.
func NewConfigStorage(s, temporal config.ConfigStorer) *ConfigStorage {
	return &ConfigStorage{ConfigStorer: s, temporal: temporal}
}

// SetConfig honors the storer.ConfigStorer interface.
func (c *ConfigStorage) SetConfig(cfg *config.Config) error {
	if err := c.temporal.SetConfig(cfg); err != nil {
		return err
	}

	c.set = true
	return nil
}

// Config honors the storer.ConfigStorer interface.
func (c *ConfigStorage) Config() (*config.Config, error) {
	if !c.set {
		return c.ConfigStorer.Config()
	}

	return c.temporal.Config()
}

// Commit it copies the config from the temporal storage into the base storage.
func (c *ConfigStorage) Commit() error {
	if !c.set {
		return nil
	}

	cfg, err := c.temporal.Config()
	if err != nil {
		return err
	}

	return c.ConfigStorer.SetConfig(cfg)
}


text:
"""
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in
range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches
required.

Example 1:
nums = [1, 3], n = 6
Return 1.

Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.

Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].

Example 3:
nums = [1, 2, 2], n = 5
Return 0.
"""
__author__ = 'Daniel'

class Solution(object):
    def minPatches(self, nums, n):
        """
        https://discuss.leetcode.com/topic/35494/solution-explanation

        Greedy
        Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index
        if cur_max < Ai:
          we have a void gap at [cur_max + 1, Ai]
          we need to patch a cur_max in the array to maximize the all-cover reach
        else:
          cur_max += Ai

        :type nums: List[int]
        :type n: int
        :rtype: int
        """
        cnt = 0
        cur_max = 0
        i = 0
        while cur_max < n:
            if i >= len(nums) or cur_max + 1 < nums[i]:
                cur_max += cur_max + 1
                cnt += 1
            else:
                cur_max += nums[i]
                i += 1

        return cnt

    def minPatches2(self, nums, n):
        """
        https://discuss.leetcode.com/topic/35494/solution-explanation

        Greedy
        Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index
        if cur_max < Ai:
          we have a void gap at [cur_max + 1, Ai]
          we need to patch a cur_max in the array to maximize the all-cover reach
        else:
          cur_max += Ai

        :type nums: List[int]
        :type n: int
        :rtype: int
        """
        nums = filter(lambda x: x <= n, nums)

        cnt = 0
        cur_max = 0
        for elt in nums:
            while cur_max + 1 < elt:
                cur_max += cur_max + 1
                cnt += 1

            cur_max += elt

        # after iterating all array element
        while cur_max < n:
            cur_max += cur_max + 1
            cnt += 1

        return cnt

if __name__ == "__main__":
    assert Solution().minPatches([1, 2, 2, 6, 34], 20) == 1


text:
import * as nls from 'vscode-nls';
import { CancellationToken, ConfigurationChangeEvent, Disposable, env, Event, EventEmitter, ThemeIcon, Timeline, TimelineChangeEvent, TimelineItem, TimelineOptions, TimelineProvider, Uri, workspace } from 'vscode';
import { Model } from './model';
import { Repository, Resource } from './repository';
import { debounce } from './decorators';
import { emojify, ensureEmojis } from './emoji';

const localize = nls.loadMessageBundle();

export class GitTimelineItem extends TimelineItem {
	static is(item: TimelineItem): item is GitTimelineItem {
		return item instanceof GitTimelineItem;
	}

	readonly ref: string;
	readonly previousRef: string;
	readonly message: string;

	constructor(
		ref: string,
		previousRef: string,
		message: string,
		timestamp: number,
		id: string,
		contextValue: string
	) {
		const index = message.indexOf('\n');
		const label = index !== -1 ? `${message.substring(0, index)} \u2026` : message;

		super(label, timestamp);

		this.ref = ref;
		this.previousRef = previousRef;
		this.message = message;
		this.id = id;
		this.contextValue = contextValue;
	}

	get shortRef() {
		return this.shortenRef(this.ref);
	}

	get shortPreviousRef() {
		return this.shortenRef(this.previousRef);
	}

	private shortenRef(ref: string): string {
		if (ref === '' || ref === '~' || ref === 'HEAD') {
			return ref;
		}
		return ref.endsWith('^') ? `${ref.substr(0, 8)}^` : ref.substr(0, 8);
	}
}

export class GitTimelineProvider implements TimelineProvider {
	private _onDidChange = new EventEmitter<TimelineChangeEvent | undefined>();
	get onDidChange(): Event<TimelineChangeEvent | undefined> {
		return this._onDidChange.event;
	}

	readonly id = 'git-history';
	readonly label = localize('git.timeline.source', 'Git History');

	private readonly disposable: Disposable;
	private providerDisposable: Disposable | undefined;

	private repo: Repository | undefined;
	private repoDisposable: Disposable | undefined;
	private repoStatusDate: Date | undefined;

	constructor(private readonly model: Model) {
		this.disposable = Disposable.from(
			model.onDidOpenRepository(this.onRepositoriesChanged, this),
			workspace.onDidChangeConfiguration(this.onConfigurationChanged, this)
		);

		if (model.repositories.length) {
			this.ensureProviderRegistration();
		}
	}

	dispose() {
		this.providerDisposable?.dispose();
		this.disposable.dispose();
	}

	async provideTimeline(uri: Uri, options: TimelineOptions, _token: CancellationToken): Promise<Timeline> {
		// console.log(`GitTimelineProvider.provideTimeline: uri=${uri} state=${this._model.state}`);

		const repo = this.model.getRepository(uri);
		if (!repo) {
			this.repoDisposable?.dispose();
			this.repoStatusDate = undefined;
			this.repo = undefined;

			return { items: [] };
		}

		if (this.repo?.root !== repo.root) {
			this.repoDisposable?.dispose();

			this.repo = repo;
			this.repoStatusDate = new Date();
			this.repoDisposable = Disposable.from(
				repo.onDidChangeRepository(uri => this.onRepositoryChanged(repo, uri)),
				repo.onDidRunGitStatus(() => this.onRepositoryStatusChanged(repo))
			);
		}

		const config = workspace.getConfiguration('git.timeline');

		// TODO@eamodio: Ensure that the uri is a file -- if not we could get the history of the repo?

		let limit: number | undefined;
		if (options.limit !== undefined && typeof options.limit !== 'number') {
			try {
				const result = await this.model.git.exec(repo.root, ['rev-list', '--count', `${options.limit.id}..`, '--', uri.fsPath]);
				if (!result.exitCode) {
					// Ask for 2 more (1 for the limit commit and 1 for the next commit) than so we can determine if there are more commits
					limit = Number(result.stdout) + 2;
				}
			}
			catch {
				limit = undefined;
			}
		} else {
			// If we are not getting everything, ask for 1 more than so we can determine if there are more commits
			limit = options.limit === undefined ? undefined : options.limit + 1;
		}

		await ensureEmojis();

		const commits = await repo.logFile(uri, {
			maxEntries: limit,
			hash: options.cursor,
			// sortByAuthorDate: true
		});

		const paging = commits.length ? {
			cursor: limit === undefined ? undefined : (commits.length >= limit ? commits[commits.length - 1]?.hash : undefined)
		} : undefined;

		// If we asked for an extra commit, strip it off
		if (limit !== undefined && commits.length >= limit) {
			commits.splice(commits.length - 1, 1);
		}

		const dateFormatter = new Intl.DateTimeFormat(env.language, { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' });

		const dateType = config.get<'committed' | 'authored'>('date');
		const showAuthor = config.get<boolean>('showAuthor');

		const items = commits.map<GitTimelineItem>((c, i) => {
			const date = dateType === 'authored' ? c.authorDate : c.commitDate;

			const message = emojify(c.message);

			const item = new GitTimelineItem(c.hash, commits[i + 1]?.hash ?? `${c.hash}^`, message, date?.getTime() ?? 0, c.hash, 'git:file:commit');
			item.iconPath = new (ThemeIcon as any)('git-commit');
			if (showAuthor) {
				item.description = c.authorName;
			}
			item.detail = `${c.authorName} (${c.authorEmail}) — ${c.hash.substr(0, 8)}\n${dateFormatter.format(date)}\n\n${message}`;
			item.command = {
				title: 'Open Comparison',
				command: 'git.timeline.openDiff',
				arguments: [item, uri, this.id]
			};

			return item;
		});

		if (options.cursor === undefined) {
			const you = localize('git.timeline.you', 'You');

			const index = repo.indexGroup.resourceStates.find(r => r.resourceUri.fsPath === uri.fsPath);
			if (index) {
				const date = this.repoStatusDate ?? new Date();

				const item = new GitTimelineItem('~', 'HEAD', localize('git.timeline.stagedChanges', 'Staged Changes'), date.getTime(), 'index', 'git:file:index');
				// TODO@eamodio: Replace with a better icon -- reflecting its status maybe?
				item.iconPath = new (ThemeIcon as any)('git-commit');
				item.description = '';
				item.detail = localize('git.timeline.detail', '{0}  — {1}\n{2}\n\n{3}', you, localize('git.index', 'Index'), dateFormatter.format(date), Resource.getStatusText(index.type));
				item.command = {
					title: 'Open Comparison',
					command: 'git.timeline.openDiff',
					arguments: [item, uri, this.id]
				};

				items.splice(0, 0, item);
			}

			const working = repo.workingTreeGroup.resourceStates.find(r => r.resourceUri.fsPath === uri.fsPath);
			if (working) {
				const date = new Date();

				const item = new GitTimelineItem('', index ? '~' : 'HEAD', localize('git.timeline.uncommitedChanges', 'Uncommitted Changes'), date.getTime(), 'working', 'git:file:working');
				// TODO@eamodio: Replace with a better icon -- reflecting its status maybe?
				item.iconPath = new (ThemeIcon as any)('git-commit');
				item.description = '';
				item.detail = localize('git.timeline.detail', '{0}  — {1}\n{2}\n\n{3}', you, localize('git.workingTree', 'Working Tree'), dateFormatter.format(date), Resource.getStatusText(working.type));
				item.command = {
					title: 'Open Comparison',
					command: 'git.timeline.openDiff',
					arguments: [item, uri, this.id]
				};

				items.splice(0, 0, item);
			}
		}

		return {
			items: items,
			paging: paging
		};
	}

	private ensureProviderRegistration() {
		if (this.providerDisposable === undefined) {
			this.providerDisposable = workspace.registerTimelineProvider(['file', 'git', 'vscode-remote', 'gitlens-git'], this);
		}
	}

	private onConfigurationChanged(e: ConfigurationChangeEvent) {
		if (e.affectsConfiguration('git.timeline.date') || e.affectsConfiguration('git.timeline.showAuthor')) {
			this.fireChanged();
		}
	}

	private onRepositoriesChanged(_repo: Repository) {
		// console.log(`GitTimelineProvider.onRepositoriesChanged`);

		this.ensureProviderRegistration();

		// TODO@eamodio: Being naive for now and just always refreshing each time there is a new repository
		this.fireChanged();
	}

	private onRepositoryChanged(_repo: Repository, _uri: Uri) {
		// console.log(`GitTimelineProvider.onRepositoryChanged: uri=${uri.toString(true)}`);

		this.fireChanged();
	}

	private onRepositoryStatusChanged(_repo: Repository) {
		// console.log(`GitTimelineProvider.onRepositoryStatusChanged`);

		// This is less than ideal, but for now just save the last time a status was run and use that as the timestamp for staged items
		this.repoStatusDate = new Date();

		this.fireChanged();
	}

	@debounce(500)
	private fireChanged() {
		this._onDidChange.fire(undefined);
	}
}


text:
package org.slc.sli.sif.zone;

import openadk.library.ADKException;
import openadk.library.ADKFlags;
import openadk.library.Zone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Configuration for zone publishers
 */
public class PublishZoneConfigurator implements ZoneConfigurator {

    private static final Logger LOG = LoggerFactory.getLogger(PublishZoneConfigurator.class);

    @Override
    public void configure(Zone[] allZones) {
        for (Zone zone : allZones) {
            try {
                // Connect to this zone
                LOG.info("- Connecting to zone \"" + zone.getZoneId() + "\" at " + zone.getZoneUrl());

                zone.connect(ADKFlags.PROV_REGISTER | ADKFlags.PROV_PROVIDE);
            } catch (ADKException ex) {
                LOG.error("  " + ex.getMessage(), ex);
            }
        }

    }

}


text:
FactoryGirl.define do
	factory :feedback do
		comment 'Lorem Ipsum'
		association :performance_review
		association :question
		rating '3'
	end
end


text:
:orphan:

Welcome to The Atmark
=====================

.. == description ==
.. _description:
.. include:: ../README.rst
    :end-before: .. _description:

.. == badges ==
.. _badges:
.. include:: ../README.rst
    :start-after: .. _badges:
    :end-before: .. _documentation:

User's Guide
------------

This part of the documentation will show you how to get started in using The Atmark.

.. toctree::
   :maxdepth: 2

   installation
   quickstart

API Reference
-------------

If you are looking for information on a specific function, class or
method, this part of the documentation is for you.

.. toctree::
   :maxdepth: 2

   api

.. == bugtracker ==
.. _bugtracker:
.. include:: ../README.rst
    :start-after: .. _bugtracker:
    :end-before: .. _contributing:

.. == contributing ==
.. _contributing:
.. include:: ../README.rst
    :start-after: .. _contributing:
    :end-before: .. _contributors:

.. == contributors ==
.. _contributors:
.. include:: ../README.rst
    :start-after: .. _contributors:
    :end-before: .. _license:

.. == links ==
.. _links:
.. include:: ../README.rst
    :start-after: .. _links:


text:
require 'rails_helper'

RSpec.describe "Admin::Petitions", type: :request do

end


text:
package org.beryx.viewreka.fxui.chart.xy;

import java.util.Collection;
import java.util.Map;

import javafx.scene.chart.XYChart.Data;

/**
 * The chart data handled by a {@link XYChartController}
 * @param <X> the type of the X axis
 * @param <Y> the type of the Y axis
 */
public class XYChartData<X,Y> {
	private final String title;
	/** indexed by seriesName */
	private final Map<String, Collection<Data<X, Y>>> dataMap;

	/**
	 * @param title the chart title
	 * @param dataMap the map of series data indexed by series names
	 */
	public XYChartData(String title, Map<String, Collection<Data<X, Y>>> dataMap) {
		this.title = title;
		this.dataMap = dataMap;
	}

	/**
	 * @return the chart title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * Retrieves the map of series data
	 * @return a map of series data indexed by series names
	 */
	public Map<String, Collection<Data<X, Y>>> getDataMap() {
		return dataMap;
	}

	@Override
	public String toString() {
		return title + ": " + dataMap;
	}
}