text:
require_dependency "inform/application_controller"
require 'date'
module Inform
  class ArticlesController < ApplicationController
    before_action :set_article, only: [:show, :edit, :update, :destroy]

    # GET /articles
    def index
      @articles = Article.all
    end

    # GET /articles/1
    def show
    end

    # GET /articles/new
    def new
      @article = Article.new
    end

    # GET /articles/1/edit
    def edit
    end

    # POST /articles
    def create
      @article = Article.new(article_params)
      if @article.save
        redirect_to @article, notice: '公告已被成功创建.'
      else
        render :new
      end
    end

    # PATCH/PUT /articles/1
    def update
      if @article.update(article_params)
        redirect_to @article, notice: '公告已被成功更新.'
      else
        render :edit
      end
    end

    # DELETE /articles/1
    def destroy
      @article.destroy
      redirect_to articles_url, notice: '公告已被成功删除.'
    end

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

      # Only allow a trusted parameter "white list" through.
      def article_params
        params.require(:article).permit(:title, :text)
      end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import $ from 'jquery';
import { Link } from 'react-router-dom';

const initialState = {
  name_2_11_c:'', date_2_11_c:'', lot_2_11_c:'', signature_2_11_c:'', dose_2_11_c:''
};

class VaccinationCalendar extends React.Component {

  constructor (props) {
    super(props);

    this.state = initialState;
    this.sendForm = this.sendForm.bind(this);
    this.setName211c = this.setName211c.bind(this);
    this.setDate211c = this.setDate211c.bind(this);
    this.setLot211c = this.setLot211c.bind(this);
    this.setSignature211c = this.setSignature211c.bind(this);
    this.setDose211c = this.setDose211c.bind(this);
  }

  componentWillMount() {
    $.ajax({
      url: "/api/v1/vaccinationcalendar",
      dataType: "json",
      method: "GET",
      success:function(response){
        console.log(response);
      }.bind(this)
    });
  }

  reset() {
    this.setState(initialState);
  }

  sendForm(evt) {
    let that = this;
    $.ajax({
      url: "/api/v1/vaccinationcalendar",
      contentType: 'application/json',
      dataType: 'json',
      method: "POST",
      data: JSON.stringify({ test: this.state }),
      success: function(response){
        console.log(response);
        that.reset();
        alert("Cadastrado com sucesso!");
      },
      error: function(response){
        console.log("erro");
        console.log(response);
      }.bind(this)
    });
  }

 render () {
  return (

            <form id="vaccinationcalendar" method="post">

                  <fieldset>

 2.11c CALENDÁRIO DE VACINAÇÃO

                  Nome

                  <input type="text"  value={this.state.name_2_11_c} onChange={this.setName211c} className="answers-134" id="2.11c-name" name="answers[2.11c[name]]"  />

                  Data

                  <input type="date" value={this.state.date_2_11_c} onChange={this.setDate211c} className="answers-135" id="2.11c-date" name="answers[2.11c[date]]"  />

                  Lote

                  <input type="text"  value={this.state.lot_2_11_c} onChange={this.setLot211c} className="answers-136" id="2.11c-lot" name="answers[2.11c[lot]]"  />

                  Assinado/Responsável

                  <input type="text"  value={this.state.signature_2_11_c} onChange={this.setSignature211c} className="answers-137" id="2.11c-signature" name="answers[2.11c[signature]]"  />

                  Dose

                  <input type="text"  value={this.state.dose_2_11_c} onChange={this.setDose211c} className="answers-138" id="2.11c-dose" name="answers[2.11c[dose]]"  />

                  </fieldset>

            </form>

                  <Link className="page-link" to="/glucosecontrol" tabIndex="-1"></Link>

                  <Link className="page-link" to="/oralhealthassessment"></Link>

    )
  }

  setName211c(evt) {
    this.setState({name_2_11_c: evt.target.value});
  }

  setFasting211b(evt) {
    this.setState({name_2_11_c: evt.target.value});
  }

  setDate211c(evt) {
    this.setState({date_2_11_c: evt.target.value});
  }

  setLot211c(evt) {
    this.setState({lot_2_11_c: evt.target.value});
  }

   setSignature211c(evt) {
    this.setState({signature_2_11_c: evt.target.value});
  }

   setDose211c(evt) {
    this.setState({dose_2_11_c: evt.target.value});
  }
}

export default VaccinationCalendar


text:
using System;

namespace DesignPatterns.Facade
{
    internal class Fulfilment
    {
        public Guid Id { get; } = Guid.NewGuid();
        public Order Order { get; }

        public Fulfilment(Order order)
        {
            if (order == null) throw new ArgumentNullException(nameof(order));
            Order = order;
        }

        public bool Success => true;
    }
}


text:
describe('Collection', function () {
  'use strict';

  var common = require('../common')
    , assume = require('assume')
    , Collection = common.Collection
    , File = common.File
    , collection;

  function noop () {};

  beforeEach(function () {
    collection = new Collection;
  });

  afterEach(function () {
    collection = null;
  });

  it('exposes the Collection constructor', function () {
    assume(Collection).to.be.a('function');
    assume(collection).to.be.instanceof(Collection);
    assume(collection.constructor).to.equal(Collection);
  });

  it('has empty readable stack', function () {
    assume(collection.stack).to.be.an('array');
    assume(collection.stack).to.have.length(0);
  });

  it('can be provided with options', function (done) {
    collection = new Collection({ files: new File, toString: function (file) {
      assume(file).to.be.instanceof(File);
      done();
    }});

    assume(collection._toString).is.a('function');
    assume(collection.stack).to.have.length(1);
    collection.toString();
  });

  describe('#toString', function () {
    it('is a getter', function () {
      var props = Object.getOwnPropertyDescriptor(Collection.prototype, 'toString');

      assume(Collection.prototype).to.have.property('toString');
      assume(props).to.have.property('get');
      assume(props.get).to.be.a('function');

      assume(props).to.have.property('enumerable', false);
      assume(props).to.have.property('configurable', false);
    });

    it('is a setter', function () {
      var props = Object.getOwnPropertyDescriptor(Collection.prototype, 'toString');

      assume(Collection.prototype).to.have.property('toString');
      assume(props).to.have.property('set');
      assume(props.get).to.be.a('function');

      assume(props).to.have.property('enumerable', false);
      assume(props).to.have.property('configurable', false);
    });

    it('sets the provided method on _toString', function () {
      collection = new Collection;
      assume(collection._toString).to.not.be.a('function');

      collection.toString = 'not a function';
      assume(collection._toString).to.not.be.a('function');

      collection.toString = noop;
      assume(collection._toString).to.be.a('function');
      assume(collection._toString).to.equal(noop);
    });

    it('returns default function that wraps the provided toString', function () {
      collection = new Collection({toString: function (v) {
        return '
'+ v +'
';
      }});

      collection.stack.push(1, 2, 3, false, 'some test string');

      assume(collection.toString).is.a('function');
      assume(collection.toString).to.have.length(0);
      assume(collection.toString()).to.equal('
1

2

3

false

some test string
');
    });
  });

  describe('#isFile', function () {
    it('is a function', function () {
      assume(collection.isFile).to.be.a('function');
      assume(collection.isFile).to.have.length(1);
    });

    it('checks if the object resembles a File', function () {
      assume(collection.isFile()).to.equal(false);
      assume(collection.isFile({})).to.equal(false);
      assume(collection.isFile(new File)).to.equal(true);
    });
  });

  describe('#push', function () {
    it('is a function', function () {
      assume(collection.isFile).to.be.a('function');
      assume(collection.isFile).to.have.length(1);
    });

    it('adds files to the stack', function () {
      var file = new File;
      file.hash = '1234567890abcdef';

      collection.push(false);
      assume(collection.stack).to.have.length(0);

      collection.push(file);
      assume(collection.stack).to.have.length(1);
      assume(collection.stack[0].length).to.equal(file.length);
      assume(collection.stack[0].hash).to.equal(file.hash);

      collection.push(new File);
      assume(collection.stack).to.have.length(2);
    });

    it('ignores non-unique files', function () {
      var file = new File;

      collection.push(file);
      assume(collection.stack).to.have.length(1);

      collection.push(file);
      assume(collection.stack).to.have.length(1);
    });
  });

  describe('#toJSON', function () {
    it('is a function', function () {
      assume(collection.toJSON).to.be.a('function');
      assume(collection.toJSON).to.have.length(0);
    });

    it('returns array of location of files in the collection', function () {
      collection.push(new File('empty1', { extname: '.css' }));
      collection.push(new File('empty2', { extname:'.js' }));

      var json = JSON.stringify(collection);
      assume(json).to.be.a('string');
      assume(json).to.equal(
        '["/da39a3ee5e6b4b0d3255bfef95601890afd80709.css","/da39a3ee5e6b4b0d3255bfef95601890afd80709.js"]'
      );

      assume(JSON.parse(json)).to.be.an('array');
      assume(JSON.parse(json)).to.include('/da39a3ee5e6b4b0d3255bfef95601890afd80709.css');
    });
  });

  describe('#concat', function () {
    it('is a function', function () {
      assume(collection.isFile).to.be.a('function');
      assume(collection.isFile).to.have.length(1);
    });

    it('concats files to the stack', function () {
      var file = new File;

      collection.concat(false);
      assume(collection.stack).to.have.length(0);

      collection.concat(new File);
      assume(collection.stack).to.have.length(1);
      assume(collection.stack[0].length).to.equal(file.length);
      assume(collection.stack[0].hash).to.equal(file.hash);
    });

    it('concats two seperate collections', function () {
      var local = new Collection({ files: new File('test1') });

      collection = new Collection({ files: new File('test2') });
      local.concat(collection);

      assume(local.stack).to.have.length(2);
      assume(local.stack[0]).to.have.property('aliases');
      assume(local.stack[0].aliases).to.include('test1');
      assume(local.stack[1].aliases).to.include('test2');
    });
  });
});


text:
#ifndef VC_AVX_CONST_H_
#define VC_AVX_CONST_H_

#include <cstddef>
#include "types.h"
#include "const_data.h"
#include "macros.h"

namespace Vc_VERSIONED_NAMESPACE
{
namespace AVX
{
    template<typename T> struct IndexesFromZeroData;
    template<> struct IndexesFromZeroData<int> {
        static Vc_ALWAYS_INLINE Vc_CONST const int *address() { return reinterpret_cast<const int *>(&_IndexesFromZero32[0]); }
    };
    template<> struct IndexesFromZeroData<unsigned int> {
        static Vc_ALWAYS_INLINE Vc_CONST const unsigned int *address() { return &_IndexesFromZero32[0]; }
    };
    template<> struct IndexesFromZeroData<short> {
        static Vc_ALWAYS_INLINE Vc_CONST const short *address() { return reinterpret_cast<const short *>(&_IndexesFromZero16[0]); }
    };
    template<> struct IndexesFromZeroData<unsigned short> {
        static Vc_ALWAYS_INLINE Vc_CONST const unsigned short *address() { return &_IndexesFromZero16[0]; }
    };
    template<> struct IndexesFromZeroData<signed char> {
        static Vc_ALWAYS_INLINE Vc_CONST const signed char *address() { return reinterpret_cast<const signed char *>(&_IndexesFromZero8[0]); }
    };
    template<> struct IndexesFromZeroData<char> {
        static Vc_ALWAYS_INLINE Vc_CONST const char *address() { return reinterpret_cast<const char *>(&_IndexesFromZero8[0]); }
    };
    template<> struct IndexesFromZeroData<unsigned char> {
        static Vc_ALWAYS_INLINE Vc_CONST const unsigned char *address() { return &_IndexesFromZero8[0]; }
    };

    template<typename _T> struct Const
    {
        typedef Vector<_T> V;
        typedef typename V::EntryType T;
        typedef typename V::Mask M;

        static Vc_ALWAYS_INLINE Vc_CONST V _pi_4()        { return V(c_trig<T>::data[0]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _pi_4_hi()     { return V(c_trig<T>::data[1]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _pi_4_rem1()   { return V(c_trig<T>::data[2]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _pi_4_rem2()   { return V(c_trig<T>::data[3]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _1_16()        { return V(c_trig<T>::data[4]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _16()          { return V(c_trig<T>::data[5]); }

        static Vc_ALWAYS_INLINE Vc_CONST V atanP(int i)      { return V(c_trig<T>::data[(12 + i)]); }
        static Vc_ALWAYS_INLINE Vc_CONST V atanQ(int i)      { return V(c_trig<T>::data[(17 + i)]); }
        static Vc_ALWAYS_INLINE Vc_CONST V atanThrsHi()      { return V(c_trig<T>::data[22]); }
        static Vc_ALWAYS_INLINE Vc_CONST V atanThrsLo()      { return V(c_trig<T>::data[23]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _pi_2_rem()       { return V(c_trig<T>::data[24]); }
        static Vc_ALWAYS_INLINE Vc_CONST V lossThreshold()   { return V(c_trig<T>::data[8]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _4_pi()           { return V(c_trig<T>::data[9]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _pi_2()           { return V(c_trig<T>::data[10]); }
        static Vc_ALWAYS_INLINE Vc_CONST V _pi()             { return V(c_trig<T>::data[11]); }
        static Vc_ALWAYS_INLINE Vc_CONST V asinCoeff0(int i) { return V(c_trig<T>::data[(28 + i)]); }
        static Vc_ALWAYS_INLINE Vc_CONST V asinCoeff1(int i) { return V(c_trig<T>::data[(33 + i)]); }
        static Vc_ALWAYS_INLINE Vc_CONST V asinCoeff2(int i) { return V(c_trig<T>::data[(37 + i)]); }
        static Vc_ALWAYS_INLINE Vc_CONST V asinCoeff3(int i) { return V(c_trig<T>::data[(43 + i)]); }
        static Vc_ALWAYS_INLINE Vc_CONST V smallAsinInput()  { return V(c_trig<T>::data[25]); }
        static Vc_ALWAYS_INLINE Vc_CONST V largeAsinInput()  { return V(c_trig<T>::data[26]); }

        static Vc_ALWAYS_INLINE Vc_CONST M exponentMask() { return M(V(c_log<T>::d(1)).data()); }
        static Vc_ALWAYS_INLINE Vc_CONST V _1_2()         { return V(c_log<T>::d(18)); }
        static Vc_ALWAYS_INLINE Vc_CONST V _1_sqrt2()     { return V(c_log<T>::d(15)); }
        static Vc_ALWAYS_INLINE Vc_CONST V P(int i)       { return V(c_log<T>::d(2 + i)); }
        static Vc_ALWAYS_INLINE Vc_CONST V Q(int i)       { return V(c_log<T>::d(8 + i)); }
        static Vc_ALWAYS_INLINE Vc_CONST V min()          { return V(c_log<T>::d(14)); }
        static Vc_ALWAYS_INLINE Vc_CONST V ln2_small()    { return V(c_log<T>::d(17)); }
        static Vc_ALWAYS_INLINE Vc_CONST V ln2_large()    { return V(c_log<T>::d(16)); }
        static Vc_ALWAYS_INLINE Vc_CONST V neginf()       { return V(c_log<T>::d(13)); }
        static Vc_ALWAYS_INLINE Vc_CONST V log10_e()      { return V(c_log<T>::d(19)); }
        static Vc_ALWAYS_INLINE Vc_CONST V log2_e()       { return V(c_log<T>::d(20)); }

        static Vc_ALWAYS_INLINE_L Vc_CONST_L V highMask() Vc_ALWAYS_INLINE_R Vc_CONST_R;
        static Vc_ALWAYS_INLINE_L Vc_CONST_L V highMask(int bits) Vc_ALWAYS_INLINE_R Vc_CONST_R;
    };

    template <> Vc_ALWAYS_INLINE Vc_CONST Vector<float> Const<float>::highMask()
    {
        return _mm256_broadcast_ss(
            reinterpret_cast<const float *>(&c_general::highMaskFloat));
    }
    template <> Vc_ALWAYS_INLINE Vc_CONST Vector<double> Const<double>::highMask()
    {
        return _mm256_broadcast_sd(
            reinterpret_cast<const double *>(&c_general::highMaskDouble));
    }
    template <> Vc_ALWAYS_INLINE Vc_CONST Vector<float> Const<float>::highMask(int bits)
    {
#ifdef Vc_IMPL_AVX2
#if defined Vc_ICC || defined Vc_MSVC
        __m256i allone = _mm256_set1_epi64x(~0);
#else
        auto allone = ~__m256i();
#endif
        return _mm256_castsi256_ps(_mm256_slli_epi32(allone, bits));
#else
        __m128 tmp = _mm_castsi128_ps(_mm_slli_epi32(_mm_setallone_si128(), bits));
        return concat(tmp, tmp);
#endif
    }
    template <> Vc_ALWAYS_INLINE Vc_CONST Vector<double> Const<double>::highMask(int bits)
    {
#ifdef Vc_IMPL_AVX2
#if defined Vc_ICC || defined Vc_MSVC
        __m256i allone = _mm256_set1_epi64x(~0);
#else
        auto allone = ~__m256i();
#endif
        return _mm256_castsi256_pd(_mm256_slli_epi64(allone, bits));
#else
        __m128d tmp = _mm_castsi128_pd(_mm_slli_epi64(_mm_setallone_si128(), bits));
        return concat(tmp, tmp);
#endif
    }
}  // namespace AVX

namespace AVX2
{
using AVX::IndexesFromZeroData;
using AVX::Const;
}  // namespace AVX2
}  // namespace Vc

#endif // VC_AVX_CONST_H_


text:
require 'minitest/autorun'
require 'nasa_earth'

class NasaEarthTest < Minitest::Test
  def setup
    api_key_file = File.join(File.dirname(__FILE__), 'api_key.txt')

    unless File.exists? api_key_file
      raise "Please put your API key inside a file named #{api_key_file}"
    end

     File.open(api_key_file) do |file|
       @api_key = file.read
     end
     @client = NasaEarth.new api_key: @api_key
  end

  def test_api_key_setup
    assert_equal @api_key, @client.api_key
  end

  def test_imagery_endpoint
    response = @client.imagery lat: 10.0, lon: 10.0
    assert_equal '200', response['code']
    assert_equal 'OK', response['message']
    assert_includes response['content'], 'url'
  end

  def test_imagery_endpoint_missing_parameters
    assert_raises(ArgumentError) do
      @client.imagery dim: 10.0
    end
  end

  def test_imagery_endpoint_invalid_parameters
    assert_raises(ArgumentError) do
      @client.imagery lat: 'invalid', lon: 10.0
    end
  end

  def test_assets_endpoint
    response = @client.assets lat: 10.0, lon: 10.0
    assert_equal '200', response['code']
    assert_equal 'OK', response['message']
  end

  def test_assets_endpoint_missing_parameters
    assert_raises(ArgumentError) do
      @client.assets dim: 10.0
    end
  end

  def test_imagery_endpoint_invalid_parameters
    assert_raises(ArgumentError) do
      @client.assets lat: 'invalid', lon: 10.0
    end
  end
end


text:
const gulp = require('gulp');
const conventionalChangelog = require('gulp-conventional-changelog');
const conventionalGithubReleaser = require('conventional-github-releaser');
const bump = require('gulp-bump');
const gutil = require('gulp-util');
const git = require('gulp-git');
const fs = require('fs');

gulp.task('changelog', () => {
  return gulp.src('CHANGELOG.md', {
    buffer: true
  })
  .pipe(conventionalChangelog({
    preset: 'angular' // Or to any other commit message convention you use.
  }))
  .pipe(gulp.dest('./'));
});

gulp.task('github-release', done => {
  const token = JSON.parse(fs.readFileSync('./gulp/.githubreleaser.json', 'utf8')).token;
  conventionalGithubReleaser({
    type: 'oauth',
    token: token
  }, {
    preset: 'angular' // Or to any other commit message convention you use.
  }, done);
});

gulp.task('bump-version', () => {
  // We hardcode the version change type to 'patch' but it may be a good idea to
  // use minimist (https://www.npmjs.com/package/minimist) to determine with a
  // command argument whether you are doing a 'major', 'minor' or a 'patch' change.
  return gulp.src(['./bower.json', './package.json'])
    .pipe(bump({type: 'patch'}).on('error', gutil.log))
    .pipe(gulp.dest('./'));
});

gulp.task('commit-changes', () => {
  return gulp.src('.')
    .pipe(git.add())
    .pipe(git.commit('[Prerelease] Bumped version number'));
});

gulp.task('push-changes', (cb) => {
  git.push('origin', 'master', cb);
});

gulp.task('create-new-tag', (cb) => {
  const getPackageJsonVersion = () => {
    // We parse the json file instead of using require because require caches
    // multiple calls so the version number won't be updated
    return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
  };
  const version = getPackageJsonVersion();

  git.tag(version, 'Created Tag for version: ' + version, error => {
    if (error) {
      return cb(error);
    }
    git.push('origin', 'master', {args: '--tags'}, cb);
  });
});

gulp.task('release', gulp.series(
  'bump-version',
  'changelog',
  'commit-changes',
  'push-changes',
  'create-new-tag',
  'github-release'
));


text:
static const NSString *VIMMetadataTaskName = @"METADATA";

@interface VIMAddMetadataTask ()

@property (nonatomic, strong) NSString *videoURI;
@property (nonatomic, strong) VIMVideoMetadata *videoMetadata;

@property (nonatomic, assign) BOOL success;

@end

@implementation VIMAddMetadataTask

- (instancetype)initWithVideoURI:(NSString *)videoURI metadata:(VIMVideoMetadata *)videoMetadata
{
    NSAssert(videoURI != nil, @"videoURI must not be nil");
    self = [super init];
    if (self)
    {
        self.name = (NSString *)VIMMetadataTaskName;

        _videoURI = videoURI;
        _videoMetadata = videoMetadata;
    }

    return self;
}

#pragma mark - Public API

- (void)resume
{
    NSAssert(self.state != TaskStateFinished, @"Cannot start a finished task");

    if ((self.state == TaskStateExecuting || self.state == TaskStateSuspended) && [self.sessionManager taskExistsForIdentifier:self.backgroundTaskIdentifier])
    {
        [VIMTaskQueueDebugger postLocalNotificationWithContext:self.sessionManager.session.configuration.identifier message:[NSString stringWithFormat:@"%@ restarted", self.name]];

        self.state = TaskStateExecuting;

        self.sessionManager.delegate = self;
        [self.sessionManager setupBlocks];

        return;
    }

    [VIMTaskQueueDebugger postLocalNotificationWithContext:self.sessionManager.session.configuration.identifier message:[NSString stringWithFormat:@"%@ started", self.name]];

    self.state = TaskStateExecuting;

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];

    if ([self.videoMetadata.videoTitle length] > 0)
    {
        parameters[@"name"] = self.videoMetadata.videoTitle;
    }

    if ([self.videoMetadata.videoDescription length] > 0)
    {
        parameters[@"description"] = self.videoMetadata.videoDescription;
    }

    if ([self.videoMetadata.videoPrivacy length] > 0)
    {
        parameters[@"privacy"] = @{@"view" : self.videoMetadata.videoPrivacy};
    }

    if ([[parameters allKeys] count] == 0) // There isn't any metadata to set...
    {
        self.success = YES;

        [self taskDidComplete];

        return;
    }

    if ([self.videoURI length] == 0)
    {
        self.error = [NSError errorWithDomain:VIMMetadataTaskErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Unable to add metadata to videoAsset, videoURI is nil."}];

        [self taskDidComplete];

        return;
    }

    NSURL *fullURL = [NSURL URLWithString:self.videoURI relativeToURL:self.sessionManager.baseURL];

    NSError *error = nil;
    NSMutableURLRequest *request = [self.sessionManager.requestSerializer requestWithMethod:@"PATCH" URLString:[fullURL absoluteString] parameters:parameters error:&error];
    if (error)
    {
        self.error = [NSError errorWithDomain:VIMMetadataTaskErrorDomain code:error.code userInfo:error.userInfo];

        [self taskDidComplete];

        return;
    }

    NSURLSessionDownloadTask *task = [self.sessionManager downloadTaskWithRequest:request progress:NULL destination:nil completionHandler:nil];
    self.backgroundTaskIdentifier = task.taskIdentifier;

    self.sessionManager.delegate = self;
    [self.sessionManager setupBlocks];

    if (self.delegate && [self.delegate respondsToSelector:@selector(taskDidStart:)])
    {
        [self.delegate taskDidStart:self];
    }

    [task resume];
}

- (BOOL)didSucceed
{
    return self.success;
}

#pragma mark - VIMNetworkTaskSessionManager Delegate

- (void)sessionManager:(VIMNetworkTaskSessionManager *)sessionManager taskDidComplete:(NSURLSessionTask *)task
{
    if (task.taskIdentifier != self.backgroundTaskIdentifier)
    {
        return;
    }

    self.backgroundTaskIdentifier = NSNotFound;
    sessionManager.delegate = nil;

    if (self.state == TaskStateCancelled || self.state == TaskStateSuspended)
    {
        return;
    }

    if (task.error)
    {
        self.error = [NSError errorWithDomain:VIMMetadataTaskErrorDomain code:task.error.code userInfo:task.error.userInfo];

        [self taskDidComplete];

        return;
    }

    // Why would an invalid status code not be flagged with an NSError and caught in the above conditional? [AH] 9/14/2015

    NSHTTPURLResponse *HTTPResponse = ((NSHTTPURLResponse *)task.response);
    if (HTTPResponse && (HTTPResponse.statusCode < 200 || HTTPResponse.statusCode > 299))
    {
        NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Invalid status code.",
                                   AFNetworkingOperationFailingURLResponseErrorKey: HTTPResponse};

        self.error = [NSError errorWithDomain:VIMMetadataTaskErrorDomain code:0 userInfo:userInfo];

        [self taskDidComplete];

        return;
    }

    self.success = YES;

    [self taskDidComplete];
}

#pragma mark - NSCoding

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self)
    {
        self.videoMetadata = [coder decodeObjectForKey:NSStringFromSelector(@selector(videoMetadata))];
        self.success = [coder decodeBoolForKey:NSStringFromSelector(@selector(success))];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
    [super encodeWithCoder:coder];

    [coder encodeObject:self.videoMetadata forKey:NSStringFromSelector(@selector(videoMetadata))];
    [coder encodeBool:self.success forKey:NSStringFromSelector(@selector(success))];
}

@end


text:
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.

namespace Lunet.Bundles;

public static class BundleObjectProperties
{
    public const string Name = "name";

    public const string Links = "links";

    public const string JsType = "js";

    public const string CssType = "css";

    public const string ContentType = "content";

    public const string UrlDestination = "url_dest";

    public const string Concat = "concat";

    public const string Minify = "minify";

    public const string MinifyExtension = "minify_ext";

    public const string Minifier = "minifier";
}


text:
$(document).ready(function(){
    $('#myCarousel').hammer().on('swipeleft',function(){
        $('#myCarousel').carousel('next');
    })
    $('#myCarousel').hammer().on('swiperight',function(){
        $('#myCarousel').carousel('prev');
    })
});


text:
package controllers

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	secretsstorev1 "sigs.k8s.io/secrets-store-csi-driver/apis/v1"
	"sigs.k8s.io/secrets-store-csi-driver/pkg/client/clientset/versioned/scheme"
	"sigs.k8s.io/secrets-store-csi-driver/pkg/util/fileutil"
	"sigs.k8s.io/secrets-store-csi-driver/pkg/util/k8sutil"
	"sigs.k8s.io/secrets-store-csi-driver/pkg/util/secretutil"

	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	apiruntime "k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/kubernetes"
	clientcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
	"k8s.io/client-go/tools/record"
	"k8s.io/klog/v2"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/predicate"
)

const (
	SecretManagedLabel         = "secrets-store.csi.k8s.io/managed"
	SecretUsedLabel            = "secrets-store.csi.k8s.io/used"
	secretCreationFailedReason = "FailedToCreateSecret"

	SyncSecretForbiddenWarning = "The secret operation failed with forbidden error. If you installed the CSI driver using helm, ensure syncSecret.enabled=true is set."
)

// SecretProviderClassPodStatusReconciler reconciles a SecretProviderClassPodStatus object
type SecretProviderClassPodStatusReconciler struct {
	client.Client
	mutex         *sync.Mutex
	scheme        *apiruntime.Scheme
	nodeID        string
	reader        client.Reader
	writer        client.Writer
	eventRecorder record.EventRecorder
}

// New creates a new SecretProviderClassPodStatusReconciler
func New(mgr manager.Manager, nodeID string) (*SecretProviderClassPodStatusReconciler, error) {
	eventBroadcaster := record.NewBroadcaster()
	kubeClient := kubernetes.NewForConfigOrDie(mgr.GetConfig())
	eventBroadcaster.StartRecordingToSink(&clientcorev1.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")})
	recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: "csi-secrets-store-controller"})

	return &SecretProviderClassPodStatusReconciler{
		Client:        mgr.GetClient(),
		mutex:         &sync.Mutex{},
		scheme:        mgr.GetScheme(),
		nodeID:        nodeID,
		reader:        mgr.GetCache(),
		writer:        mgr.GetClient(),
		eventRecorder: recorder,
	}, nil
}

func (r *SecretProviderClassPodStatusReconciler) RunPatcher(ctx context.Context) {
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			if err := r.Patcher(ctx); err != nil {
				klog.ErrorS(err, "failed to patch secret owner ref")
			}
		}
	}
}

func (r *SecretProviderClassPodStatusReconciler) Patcher(ctx context.Context) error {
	klog.V(10).Info("patcher started")
	r.mutex.Lock()
	defer r.mutex.Unlock()

	spcPodStatusList := &secretsstorev1.SecretProviderClassPodStatusList{}
	spcMap := make(map[string]secretsstorev1.SecretProviderClass)
	secretOwnerMap := make(map[types.NamespacedName][]metav1.OwnerReference)
	// get a list of all spc pod status that belong to the node
	err := r.reader.List(ctx, spcPodStatusList, r.ListOptionsLabelSelector())
	if err != nil {
		return fmt.Errorf("failed to list secret provider class pod status, err: %w", err)
	}

	spcPodStatuses := spcPodStatusList.Items
	for i := range spcPodStatuses {
		spcName := spcPodStatuses[i].Status.SecretProviderClassName
		spc := &secretsstorev1.SecretProviderClass{}
		namespace := spcPodStatuses[i].Namespace

		if val, exists := spcMap[namespace+"/"+spcName]; exists {
			spc = &val
		} else {
			if err := r.reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: spcName}, spc); err != nil {
				return fmt.Errorf("failed to get spc %s, err: %w", spcName, err)
			}
			spcMap[namespace+"/"+spcName] = *spc
		}
		// get the pod and check if the pod has a owner reference
		pod := &corev1.Pod{}
		err = r.reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: spcPodStatuses[i].Status.PodName}, pod)
		if err != nil {
			return fmt.Errorf("failed to fetch pod during patching, err: %w", err)
		}
		var ownerRefs []metav1.OwnerReference
		for _, ownerRef := range pod.GetOwnerReferences() {
			ownerRefs = append(ownerRefs, metav1.OwnerReference{
				APIVersion: ownerRef.APIVersion,
				Kind:       ownerRef.Kind,
				UID:        ownerRef.UID,
				Name:       ownerRef.Name,
			})
		}
		// If a pod has no owner references, then it's a static pod and
		// doesn't belong to a replicaset. In this case, use the spcps as
		// owner reference just like we do it today
		if len(ownerRefs) == 0 {
			// Create a new owner ref.
			gvk, err := apiutil.GVKForObject(&spcPodStatuses[i], r.scheme)
			if err != nil {
				return err
			}
			ref := metav1.OwnerReference{
				APIVersion: gvk.GroupVersion().String(),
				Kind:       gvk.Kind,
				UID:        spcPodStatuses[i].GetUID(),
				Name:       spcPodStatuses[i].GetName(),
			}
			ownerRefs = append(ownerRefs, ref)
		}

		for _, secret := range spc.Spec.SecretObjects {
			key := types.NamespacedName{Name: secret.SecretName, Namespace: namespace}
			val, exists := secretOwnerMap[key]
			if exists {
				secretOwnerMap[key] = append(val, ownerRefs...)
			} else {
				secretOwnerMap[key] = ownerRefs
			}
		}
	}

	for secret, owners := range secretOwnerMap {
		patchFn := func() (bool, error) {
			if err := r.patchSecretWithOwnerRef(ctx, secret.Name, secret.Namespace, owners...); err != nil {
				if !apierrors.IsConflict(err) || !apierrors.IsTimeout(err) {
					klog.ErrorS(err, "failed to set owner ref for secret", "secret", klog.ObjectRef{Namespace: secret.Namespace, Name: secret.Name})
				}
				// syncSecret.enabled is set to false by default in the helm chart for installing the driver in v0.0.23+
				// that would result in a forbidden error, so generate a warning that can be helpful for debugging
				if apierrors.IsForbidden(err) {
					klog.Warning(SyncSecretForbiddenWarning)
				}
				return false, nil
			}
			return true, nil
		}
		if err := wait.ExponentialBackoff(wait.Backoff{
			Steps:    5,
			Duration: 1 * time.Millisecond,
			Factor:   1.0,
			Jitter:   0.1,
		}, patchFn); err != nil {
			return err
		}
	}

	klog.V(10).Info("patcher completed")
	return nil
}

// ListOptionsLabelSelector returns a ListOptions with a label selector for node name.
func (r *SecretProviderClassPodStatusReconciler) ListOptionsLabelSelector() client.ListOption {
	return client.MatchingLabels(map[string]string{
		secretsstorev1.InternalNodeLabel: r.nodeID,
	})
}

// +kubebuilder:rbac:groups=secrets-store.csi.x-k8s.io,resources=secretproviderclasspodstatuses,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=secrets-store.csi.x-k8s.io,resources=secretproviderclasspodstatuses/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=secrets-store.csi.x-k8s.io,resources=secretproviderclasses,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// +kubebuilder:rbac:groups="storage.k8s.io",resources=csidrivers,verbs=get;list;watch,resourceNames=secrets-store.csi.k8s.io

func (r *SecretProviderClassPodStatusReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	klog.InfoS("reconcile started", "spcps", req.NamespacedName.String())

	spcPodStatus := &secretsstorev1.SecretProviderClassPodStatus{}
	if err := r.reader.Get(ctx, req.NamespacedName, spcPodStatus); err != nil {
		if apierrors.IsNotFound(err) {
			klog.InfoS("reconcile complete", "spcps", req.NamespacedName.String())
			return ctrl.Result{}, nil
		}
		klog.ErrorS(err, "failed to get spc pod status", "spcps", req.NamespacedName.String())
		return ctrl.Result{}, err
	}

	// Obtain the full pod metadata. An object reference is needed for sending
	// events and the UID is helpful for validating the SPCPS TargetPath.
	pod := &corev1.Pod{}
	if err := r.reader.Get(ctx, client.ObjectKey{Namespace: req.Namespace, Name: spcPodStatus.Status.PodName}, pod); err != nil {
		klog.ErrorS(err, "failed to get pod", "pod", klog.ObjectRef{Namespace: req.Namespace, Name: spcPodStatus.Status.PodName})
		if apierrors.IsNotFound(err) {
			return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
		}
		return ctrl.Result{}, err
	}
	// skip reconcile if the pod is being terminated
	// or the pod is in succeeded state (for jobs that complete aren't gc yet)
	// or the pod is in a failed state (all containers get terminated)
	if !pod.GetDeletionTimestamp().IsZero() || pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
		klog.V(5).InfoS("pod is being terminated, skipping reconcile", "pod", klog.KObj(pod))
		return ctrl.Result{}, nil
	}

	spcName := spcPodStatus.Status.SecretProviderClassName
	spc := &secretsstorev1.SecretProviderClass{}
	if err := r.reader.Get(ctx, client.ObjectKey{Namespace: req.Namespace, Name: spcName}, spc); err != nil {
		klog.ErrorS(err, "failed to get spc", "spc", spcName)
		if apierrors.IsNotFound(err) {
			return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
		}
		return ctrl.Result{}, err
	}

	if len(spc.Spec.SecretObjects) == 0 {
		klog.InfoS("no secret objects defined for spc, nothing to reconcile", "spc", klog.KObj(spc), "spcps", klog.KObj(spcPodStatus))
		return ctrl.Result{}, nil
	}

	// determine which pod volume this is associated with
	podVol := k8sutil.SPCVolume(pod, spc.Name)
	if podVol == nil {
		return ctrl.Result{}, fmt.Errorf("failed to find secret provider class pod status volume for pod %s/%s", req.Namespace, spcPodStatus.Status.PodName)
	}

	// validate TargetPath
	if fileutil.GetPodUIDFromTargetPath(spcPodStatus.Status.TargetPath) != string(pod.UID) {
		return ctrl.Result{}, fmt.Errorf("secret provider class pod status targetPath did not match pod UID for pod %s/%s", req.Namespace, spcPodStatus.Status.PodName)
	}
	if fileutil.GetVolumeNameFromTargetPath(spcPodStatus.Status.TargetPath) != podVol.Name {
		return ctrl.Result{}, fmt.Errorf("secret provider class pod status volume name did not match pod Volume for pod %s/%s", req.Namespace, spcPodStatus.Status.PodName)
	}

	files, err := fileutil.GetMountedFiles(spcPodStatus.Status.TargetPath)
	if err != nil {
		r.generateEvent(pod, corev1.EventTypeWarning, secretCreationFailedReason, fmt.Sprintf("failed to get mounted files, err: %+v", err))
		klog.ErrorS(err, "failed to get mounted files", "spc", klog.KObj(spc), "pod", klog.KObj(pod), "spcps", klog.KObj(spcPodStatus))
		return ctrl.Result{RequeueAfter: 10 * time.Second}, err
	}
	errs := make([]error, 0)
	for _, secretObj := range spc.Spec.SecretObjects {
		secretName := strings.TrimSpace(secretObj.SecretName)

		if err = secretutil.ValidateSecretObject(*secretObj); err != nil {
			klog.ErrorS(err, "failed to validate secret object in spc", "spc", klog.KObj(spc), "pod", klog.KObj(pod), "spcps", klog.KObj(spcPodStatus))
			errs = append(errs, fmt.Errorf("failed to validate secret object in spc %s/%s, err: %w", spc.Namespace, spc.Name, err))
			continue
		}
		exists, err := r.secretExists(ctx, secretName, req.Namespace)
		if err != nil {
			klog.ErrorS(err, "failed to check if secret exists", "secret", klog.ObjectRef{Namespace: req.Namespace, Name: secretName}, "spc", klog.KObj(spc), "pod", klog.KObj(pod), "spcps", klog.KObj(spcPodStatus))
			// syncSecret.enabled is set to false by default in the helm chart for installing the driver in v0.0.23+
			// that would result in a forbidden error, so generate a warning that can be helpful for debugging
			if apierrors.IsForbidden(err) {
				klog.Warning(SyncSecretForbiddenWarning)
			}
			errs = append(errs, fmt.Errorf("failed to check if secret %s exists, err: %w", secretName, err))
			continue
		}

		var funcs []func() (bool, error)

		if !exists {
			secretType := secretutil.GetSecretType(strings.TrimSpace(secretObj.Type))

			var datamap map[string][]byte
			if datamap, err = secretutil.GetSecretData(secretObj.Data, secretType, files); err != nil {
				r.generateEvent(pod, corev1.EventTypeWarning, secretCreationFailedReason, fmt.Sprintf("failed to get data in spc %s/%s for secret %s, err: %+v", req.Namespace, spcName, secretName, err))
				klog.ErrorS(err, "failed to get data in spc for secret", "spc", klog.KObj(spc), "pod", klog.KObj(pod), "secret", klog.ObjectRef{Namespace: req.Namespace, Name: secretName}, "spcps", klog.KObj(spcPodStatus))
				errs = append(errs, fmt.Errorf("failed to get data in spc %s/%s for secret %s, err: %w", req.Namespace, spcName, secretName, err))
				continue
			}

			labelsMap := make(map[string]string)
			if secretObj.Labels != nil {
				labelsMap = secretObj.Labels
			}
			annotationsMap := make(map[string]string)
			if secretObj.Annotations != nil {
				annotationsMap = secretObj.Annotations
			}
			// Set secrets-store.csi.k8s.io/managed=true label on the secret that's created and managed
			// by the secrets-store-csi-driver. This label will be used to perform a filtered list watch
			// only on secrets created and managed by the driver
			labelsMap[SecretManagedLabel] = "true"

			createFn := func() (bool, error) {
				if err := r.createK8sSecret(ctx, secretName, req.Namespace, datamap, labelsMap, annotationsMap, secretType); err != nil {
					klog.ErrorS(err, "failed to create Kubernetes secret", "spc", klog.KObj(spc), "pod", klog.KObj(pod), "secret", klog.ObjectRef{Namespace: req.Namespace, Name: secretName}, "spcps", klog.KObj(spcPodStatus))
					// syncSecret.enabled is set to false by default in the helm chart for installing the driver in v0.0.23+
					// that would result in a forbidden error, so generate a warning that can be helpful for debugging
					if apierrors.IsForbidden(err) {
						klog.Warning(SyncSecretForbiddenWarning)
					}
					return false, nil
				}
				return true, nil
			}
			funcs = append(funcs, createFn)
		}

		for _, f := range funcs {
			if err := wait.ExponentialBackoff(wait.Backoff{
				Steps:    5,
				Duration: 1 * time.Millisecond,
				Factor:   1.0,
				Jitter:   0.1,
			}, f); err != nil {
				r.generateEvent(pod, corev1.EventTypeWarning, secretCreationFailedReason, err.Error())
				return ctrl.Result{RequeueAfter: 5 * time.Second}, err
			}
		}
	}

	if len(errs) > 0 {
		return ctrl.Result{Requeue: true}, nil
	}

	klog.InfoS("reconcile complete", "spc", klog.KObj(spc), "pod", klog.KObj(pod), "spcps", klog.KObj(spcPodStatus))
	// requeue the spc pod status again after 5mins to check if secret and ownerRef exists
	// and haven't been modified. If secret doesn't exist, then this requeue will ensure it's
	// created in the next reconcile and the owner ref patched again
	return ctrl.Result{RequeueAfter: 5 * time.Minute}, nil
}

func (r *SecretProviderClassPodStatusReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&secretsstorev1.SecretProviderClassPodStatus{}).
		WithEventFilter(r.belongsToNodePredicate()).
		Complete(r)
}

// belongsToNodePredicate defines predicates for handlers
func (r *SecretProviderClassPodStatusReconciler) belongsToNodePredicate() predicate.Funcs {
	return predicate.Funcs{
		UpdateFunc: func(e event.UpdateEvent) bool {
			return r.processIfBelongsToNode(e.ObjectNew)
		},
		CreateFunc: func(e event.CreateEvent) bool {
			return r.processIfBelongsToNode(e.Object)
		},
		DeleteFunc: func(e event.DeleteEvent) bool {
			return false
		},
		GenericFunc: func(e event.GenericEvent) bool {
			return r.processIfBelongsToNode(e.Object)
		},
	}
}

// processIfBelongsToNode determines if the secretproviderclasspodstatus belongs to the node based on the
// internal.secrets-store.csi.k8s.io/node-name: <node name> label. If belongs to node, then the spcps is processed.
func (r *SecretProviderClassPodStatusReconciler) processIfBelongsToNode(objMeta metav1.Object) bool {
	node, ok := objMeta.GetLabels()[secretsstorev1.InternalNodeLabel]
	if !ok {
		return false
	}
	if !strings.EqualFold(node, r.nodeID) {
		return false
	}
	return true
}

// createK8sSecret creates K8s secret with data from mounted files
// If a secret with the same name already exists in the namespace of the pod, the error is nil.
func (r *SecretProviderClassPodStatusReconciler) createK8sSecret(ctx context.Context, name, namespace string, datamap map[string][]byte, labelsmap map[string]string, annotationsmap map[string]string, secretType corev1.SecretType) error {
	secret := &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Namespace:   namespace,
			Name:        name,
			Labels:      labelsmap,
			Annotations: annotationsmap,
		},
		Type: secretType,
		Data: datamap,
	}

	err := r.writer.Create(ctx, secret)
	if err == nil {
		klog.InfoS("successfully created Kubernetes secret", "secret", klog.ObjectRef{Namespace: namespace, Name: name})
		return nil
	}
	if apierrors.IsAlreadyExists(err) {
		return nil
	}
	return err
}

// patchSecretWithOwnerRef patches the secret owner reference with the spc pod status
func (r *SecretProviderClassPodStatusReconciler) patchSecretWithOwnerRef(ctx context.Context, name, namespace string, ownerRefs ...metav1.OwnerReference) error {
	secret := &corev1.Secret{}
	secretKey := types.NamespacedName{
		Namespace: namespace,
		Name:      name,
	}
	if err := r.Client.Get(ctx, secretKey, secret); err != nil {
		if apierrors.IsNotFound(err) {
			klog.V(5).InfoS("secret not found for patching", "secret", klog.ObjectRef{Namespace: namespace, Name: name})
			return nil
		}
		return err
	}

	patch := client.MergeFromWithOptions(secret.DeepCopy(), client.MergeFromWithOptimisticLock{})
	needsPatch := false

	secretOwnerRefs := secret.GetOwnerReferences()
	secretOwnerMap := make(map[string]types.UID)
	for _, or := range secretOwnerRefs {
		secretOwnerMap[or.Name] = or.UID
	}

	for i := range ownerRefs {
		if _, exists := secretOwnerMap[ownerRefs[i].Name]; exists {
			continue
		}
		// add to map for tracking
		secretOwnerMap[ownerRefs[i].Name] = ownerRefs[i].UID
		needsPatch = true
		klog.V(5).InfoS("Adding owner ref for secret", "ownerRefAPIVersion", ownerRefs[i].APIVersion, "ownerRefName", ownerRefs[i].Name, "secret", klog.ObjectRef{Namespace: namespace, Name: name})
		secretOwnerRefs = append(secretOwnerRefs, ownerRefs[i])
	}

	if needsPatch {
		secret.SetOwnerReferences(secretOwnerRefs)
		return r.writer.Patch(ctx, secret, patch)
	}
	return nil
}

// secretExists checks if the secret with name and namespace already exists
func (r *SecretProviderClassPodStatusReconciler) secretExists(ctx context.Context, name, namespace string) (bool, error) {
	o := &corev1.Secret{}
	secretKey := types.NamespacedName{
		Namespace: namespace,
		Name:      name,
	}
	err := r.Client.Get(ctx, secretKey, o)
	if err == nil {
		return true, nil
	}
	if apierrors.IsNotFound(err) {
		return false, nil
	}
	return false, err
}

// generateEvent generates an event
func (r *SecretProviderClassPodStatusReconciler) generateEvent(obj apiruntime.Object, eventType, reason, message string) {
	if obj != nil {
		r.eventRecorder.Eventf(obj, eventType, reason, message)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using Csla;
using Csla.Data;
using Invoices.DataAccess;

namespace Invoices.DataAccess.SQLite
{
    /// <summary>
    /// DAL SQL Server implementation of <see cref="IInvoiceViewDal"/>
    /// </summary>
    public partial class InvoiceViewDal : IInvoiceViewDal
    {

        #region DAL methods

        private List<InvoiceLineInfoDto> _invoiceLineList = new List<InvoiceLineInfoDto>();

        /// <summary>
        /// Gets the Invoice Lines.
        /// </summary>
        /// <value>A list of <see cref="InvoiceLineInfoDto"/>.</value>
        public List<InvoiceLineInfoDto> InvoiceLineList
        {
            get { return _invoiceLineList; }
        }

        /// <summary>
        /// Loads a InvoiceView object from the database.
        /// </summary>
        /// <param name="invoiceId">The fetch criteria.</param>
        /// <returns>A InvoiceViewDto object.</returns>
        public InvoiceViewDto Fetch(Guid invoiceId)
        {
            using (var ctx = ConnectionManager<SQLiteConnection>.GetManager("Invoices"))
            {
                using (var cmd = new SQLiteCommand("dbo.GetInvoiceView", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@InvoiceId", invoiceId).DbType = DbType.Guid;
                    var dr = cmd.ExecuteReader();
                    return Fetch(dr);
                }
            }
        }

        private InvoiceViewDto Fetch(IDataReader data)
        {
            var invoiceView = new InvoiceViewDto();
            using (var dr = new SafeDataReader(data))
            {
                if (dr.Read())
                {
                    invoiceView.InvoiceId = dr.GetGuid("InvoiceId");
                    invoiceView.InvoiceNumber = dr.GetString("InvoiceNumber");
                    invoiceView.CustomerId = dr.GetString("CustomerId");
                    invoiceView.InvoiceDate = dr.GetSmartDate("InvoiceDate", true);
                    invoiceView.IsActive = dr.GetBoolean("IsActive");
                    invoiceView.CreateDate = dr.GetSmartDate("CreateDate", true);
                    invoiceView.CreateUser = dr.GetInt32("CreateUser");
                    invoiceView.ChangeDate = dr.GetSmartDate("ChangeDate", true);
                    invoiceView.ChangeUser = dr.GetInt32("ChangeUser");
                    invoiceView.RowVersion = dr.GetValue("RowVersion") as byte[];
                }
                FetchChildren(dr);
            }
            return invoiceView;
        }

        private void FetchChildren(SafeDataReader dr)
        {
            dr.NextResult();
            while (dr.Read())
            {
                _invoiceLineList.Add(FetchInvoiceLineInfo(dr));
            }
        }

        private InvoiceLineInfoDto FetchInvoiceLineInfo(SafeDataReader dr)
        {
            var invoiceLineInfo = new InvoiceLineInfoDto();
            // Value properties
            invoiceLineInfo.InvoiceLineId = dr.GetGuid("InvoiceLineId");
            invoiceLineInfo.ProductId = dr.GetGuid("ProductId");
            invoiceLineInfo.Quantity = dr.GetInt32("Quantity");
            invoiceLineInfo.UnitCost = dr.GetDecimal("UnitCost");
            invoiceLineInfo.Cost = dr.GetDecimal("Cost");
            invoiceLineInfo.PercentDiscount = dr.GetByte("PercentDiscount");

            return invoiceLineInfo;
        }

        #endregion

    }
}


text:
namespace Microsoft.Azure.CognitiveServices.Personalizer.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// An action with it's associated features used for ranking.
    /// </summary>
    public partial class RankableAction
    {
        /// <summary>
        /// Initializes a new instance of the RankableAction class.
        /// </summary>
        public RankableAction()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the RankableAction class.
        /// </summary>
        /// <param name="id">Id of the action.</param>
        /// <param name="features">List of dictionaries containing
        /// features.</param>
        public RankableAction(string id, IList<object> features)
        {
            Id = id;
            Features = features;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets id of the action.
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets list of dictionaries containing features.
        /// </summary>
        [JsonProperty(PropertyName = "features")]
        public IList<object> Features { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Id == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Id");
            }
            if (Features == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Features");
            }
            if (Id != null)
            {
                if (Id.Length > 256)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "Id", 256);
                }
            }
        }
    }
}


text:
package org.elasticsearch.client.ml.job.config;

import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

public class JobUpdateTests extends AbstractXContentTestCase<JobUpdate> {

    @Override
    protected JobUpdate createTestInstance() {
        return createRandom(randomAlphaOfLength(4));
    }

    /**
     * Creates a completely random update when the job is null
     * or a random update that is is valid for the given job
     */
    public static JobUpdate createRandom(String jobId) {
        JobUpdate.Builder update = new JobUpdate.Builder(jobId);
        if (randomBoolean()) {
            int groupsNum = randomIntBetween(0, 10);
            List<String> groups = new ArrayList<>(groupsNum);
            for (int i = 0; i < groupsNum; i++) {
                groups.add(JobTests.randomValidJobId());
            }
            update.setGroups(groups);
        }
        if (randomBoolean()) {
            update.setDescription(randomAlphaOfLength(20));
        }
        if (randomBoolean()) {
            update.setDetectorUpdates(createRandomDetectorUpdates());
        }
        if (randomBoolean()) {
            update.setModelPlotConfig(ModelPlotConfigTests.createRandomized());
        }
        if (randomBoolean()) {
            update.setAnalysisLimits(AnalysisLimitsTests.createRandomized());
        }
        if (randomBoolean()) {
            update.setRenormalizationWindowDays(randomNonNegativeLong());
        }
        if (randomBoolean()) {
            update.setBackgroundPersistInterval(TimeValue.timeValueHours(randomIntBetween(1, 24)));
        }
        if (randomBoolean()) {
            update.setModelSnapshotRetentionDays(randomNonNegativeLong());
        }
        if (randomBoolean()) {
            update.setDailyModelSnapshotRetentionAfterDays(randomNonNegativeLong());
        }
        if (randomBoolean()) {
            update.setResultsRetentionDays(randomNonNegativeLong());
        }
        if (randomBoolean()) {
            update.setCategorizationFilters(Arrays.asList(generateRandomStringArray(10, 10, false)));
        }
        if (randomBoolean()) {
            update.setCustomSettings(Collections.singletonMap(randomAlphaOfLength(10), randomAlphaOfLength(10)));
        }
        if (randomBoolean()) {
            update.setAllowLazyOpen(randomBoolean());
        }

        return update.build();
    }

    private static List<JobUpdate.DetectorUpdate> createRandomDetectorUpdates() {
        int size = randomInt(10);
        List<JobUpdate.DetectorUpdate> detectorUpdates = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            String detectorDescription = null;
            if (randomBoolean()) {
                detectorDescription = randomAlphaOfLength(12);
            }
            List<DetectionRule> detectionRules = null;
            if (randomBoolean()) {
                detectionRules = new ArrayList<>();
                detectionRules.add(new DetectionRule.Builder(
                        Collections.singletonList(new RuleCondition(RuleCondition.AppliesTo.ACTUAL, Operator.GT, 5))).build());
            }
            detectorUpdates.add(new JobUpdate.DetectorUpdate(i, detectorDescription, detectionRules));
        }
        return detectorUpdates;
    }

    @Override
    protected JobUpdate doParseInstance(XContentParser parser) {
        return JobUpdate.PARSER.apply(parser, null).build();
    }

    @Override
    protected boolean supportsUnknownFields() {
        return true;
    }

    @Override
    protected Predicate<String> getRandomFieldsExcludeFilter() {
        return field -> !field.isEmpty();
    }
}


text:
class Role < ActiveRecord::Base
	has_and_belongs_to_many :users
	has_and_belongs_to_many :rights, :order => 'name ASC'

  validates_presence_of :name

  # Sets rights by list of id's passed in
	def right_ids=(id_list)
		self.rights.clear
		for id in id_list
			next if id.empty?
			right = Right.find(id)
			self.rights << right if right
		end
	end
end


text:
Plugin.define "DMXReady-Members-Area-Manager" do
author "Brendan Coles <bcoles@gmail.com>" # 2010-07-25
version "0.1"
description "DMXReady Members Area Manager allows you to quickly create a whole area of your website that is 'members only' so you can control who sees your content."
website "http://www.dmxready.com/?product=members-area-manager"

# Google results as at 2010-07-25 #
# 29 for inurl:inc_membersareamanager.asp

# Dorks #
dorks [
'inurl:inc_membersareamanager.asp'
]

# Matches #
matches [

# Forgot password link
{ :regexp=>/
Forget Password\?<\/a>/ },

# Form HTML
{ :regexp=>/<form ACTION="[^"]*\/applications\/MembersAreaManager\/inc_membersareamanager\.asp" method="POST" name="login" onSubmit="YY_checkform\('login','entity_username','#q','0','Please provide username','entity_password','#q','0','Please provide password'\);return document.MM_returnValue" >/ },

]

end


text:
'''
Algorithms to compute statistics on :abbr:`fMRI (functional MRI)`

    Change directory to provide relative paths for doctests
    >>> import os
    >>> filepath = os.path.dirname(os.path.realpath(__file__))
    >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data'))
    >>> os.chdir(datadir)

'''
from __future__ import (print_function, division, unicode_literals,
                        absolute_import)
import os

import numpy as np
import nibabel as nb

from .. import logging
from ..interfaces.base import (traits, TraitedSpec, BaseInterface,
                               BaseInterfaceInputSpec, File, InputMultiPath)
IFLOG = logging.getLogger('interface')

class SignalExtractionInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc='4-D fMRI nii file')
    label_files = InputMultiPath(File(exists=True), mandatory=True,
                                 desc='a 3-D label image, with 0 denoting '
                                 'background, or a list of 3-D probability '
                                 'maps (one per label) or the equivalent 4D '
                                 'file.')
    class_labels = traits.List(mandatory=True,
                               desc='Human-readable labels for each segment '
                               'in the label file, in order. The length of '
                               'class_labels must be equal to the number of '
                               'segments (background excluded). This list '
                               'corresponds to the class labels in label_file '
                               'in ascending order')
    out_file = File('signals.tsv', usedefault=True, exists=False,
                    desc='The name of the file to output to. '
                    'signals.tsv by default')
    incl_shared_variance = traits.Bool(True, usedefault=True, desc='By default '
                                       '(True), returns simple time series calculated from each '
                                       'region independently (e.g., for noise regression). If '
                                       'False, returns unique signals for each region, discarding '
                                       'shared variance (e.g., for connectivity. Only has effect '
                                       'with 4D probability maps.')
    include_global = traits.Bool(False, usedefault=True,
                                 desc='If True, include an extra column '
                                 'labeled "GlobalSignal", with values calculated from the entire brain '
                                 '(instead of just regions).')
    detrend = traits.Bool(False, usedefault=True, desc='If True, perform detrending using nilearn.')

class SignalExtractionOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc='tsv file containing the computed '
                    'signals, with as many columns as there are labels and as '
                    'many rows as there are timepoints in in_file, plus a '
                    'header row with values from class_labels')

class SignalExtraction(BaseInterface):
    '''
    Extracts signals over tissue classes or brain regions

    >>> seinterface = SignalExtraction()
    >>> seinterface.inputs.in_file = 'functional.nii'
    >>> seinterface.inputs.label_files = 'segmentation0.nii.gz'
    >>> seinterface.inputs.out_file = 'means.tsv'
    >>> segments = ['CSF', 'GrayMatter', 'WhiteMatter']
    >>> seinterface.inputs.class_labels = segments
    >>> seinterface.inputs.detrend = True
    >>> seinterface.inputs.include_global = True
    '''
    input_spec = SignalExtractionInputSpec
    output_spec = SignalExtractionOutputSpec
    _results = {}

    def _run_interface(self, runtime):
        maskers = self._process_inputs()

        signals = []
        for masker in maskers:
            signals.append(masker.fit_transform(self.inputs.in_file))
        region_signals = np.hstack(signals)

        output = np.vstack((self.inputs.class_labels, region_signals.astype(str)))

        # save output
        self._results['out_file'] = os.path.abspath(self.inputs.out_file)
        np.savetxt(self._results['out_file'], output, fmt=b'%s', delimiter='\t')
        return runtime

    def _process_inputs(self):
        ''' validate and  process inputs into useful form.
        Returns a list of nilearn maskers and the list of corresponding label names.'''
        import nilearn.input_data as nl
        import nilearn.image as nli

        label_data = nli.concat_imgs(self.inputs.label_files)
        maskers = []

        # determine form of label files, choose appropriate nilearn masker
        if np.amax(label_data.get_data()) > 1: # 3d label file
            n_labels = np.amax(label_data.get_data())
            maskers.append(nl.NiftiLabelsMasker(label_data))
        else: # 4d labels
            n_labels = label_data.get_data().shape[3]
            if self.inputs.incl_shared_variance: # 4d labels, independent computation
                for img in nli.iter_img(label_data):
                    maskers.append(nl.NiftiMapsMasker(self._4d(img.get_data(), img.affine)))
            else: # 4d labels, one computation fitting all
                maskers.append(nl.NiftiMapsMasker(label_data))

        # check label list size
        if not np.isclose(int(n_labels), n_labels):
            raise ValueError('The label files {} contain invalid value {}. Check input.'
                             .format(self.inputs.label_files, n_labels))

        if len(self.inputs.class_labels) != n_labels:
            raise ValueError('The length of class_labels {} does not '
                             'match the number of regions {} found in '
                             'label_files {}'.format(self.inputs.class_labels,
                                                     n_labels,
                                                     self.inputs.label_files))

        if self.inputs.include_global:
            global_label_data = label_data.get_data().sum(axis=3) # sum across all regions
            global_label_data = np.rint(global_label_data).astype(int).clip(0, 1) # binarize
            global_label_data = self._4d(global_label_data, label_data.affine)
            global_masker = nl.NiftiLabelsMasker(global_label_data, detrend=self.inputs.detrend)
            maskers.insert(0, global_masker)
            self.inputs.class_labels.insert(0, 'GlobalSignal')

        for masker in maskers:
            masker.set_params(detrend=self.inputs.detrend)

        return maskers

    def _4d(self, array, affine):
        ''' takes a 3-dimensional numpy array and an affine,
        returns the equivalent 4th dimensional nifti file '''
        return nb.Nifti1Image(array[:, :, :, np.newaxis], affine)

    def _list_outputs(self):
        return self._results


text:
import modConfig from './config.js';
import modController from './controller.js';
import modService from './service.js';

let mod = angular.module('Teknoputra.Ionic.search', []);

mod.config(modConfig);
mod.controller('WPHCSearchController', modController);
mod.service('$WPHCSearch', modService);

export default mod = mod.name;


text:
<?php
	// Surftown Website Parked Page
	// Replace this file with your own index file
	$ch	= curl_init();
	$timeout = 10;
	$url	= $_SERVER['SERVER_NAME'];

	curl_setopt($ch, CURLOPT_URL, 'http://go.surftown.com/parked/');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, array(domain => $url));

	$data = curl_exec($ch);
	echo($data);
	curl_close($ch);
?>


text:
@interface MRExpandModalViewController ()

@property (nonatomic, assign) UIInterfaceOrientationMask supportedOrientationMask;

@end

@implementation MRExpandModalViewController

- (instancetype)initWithOrientationMask:(UIInterfaceOrientationMask)orientationMask
{
    if (self = [super init]) {
        _supportedOrientationMask = orientationMask;
        self.modalPresentationStyle = UIModalPresentationFullScreen;
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)setSupportedOrientationMask:(UIInterfaceOrientationMask)supportedOrientationMask
{
    _supportedOrientationMask = supportedOrientationMask;

    [UIViewController attemptRotationToDeviceOrientation];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return ([[UIApplication sharedApplication] mp_supportsOrientationMask:self.supportedOrientationMask]) ? self.supportedOrientationMask : UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

#pragma mark - <MPClosableViewDelegate>

// We transfer closable view delegation to the expand view controller in the event MRController is deallocated and the expand modal is presented.
- (void)closeButtonPressed:(MPClosableView *)closableView
{
    // All we need to do is dismiss ourself.
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
package net.sourceforge.vietocr;

import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.imageio.metadata.*;
import com.sun.media.imageio.plugins.tiff.*;
import java.awt.Toolkit;
import java.awt.image.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.w3c.dom.NodeList;

public class ImageIOHelper {

    final static String OUTPUT_FILE_NAME = "Tesstmp";
    final static String TIFF_EXT = ".tif";
    final static String TIFF_FORMAT = "tiff";
    final static String JAI_IMAGE_WRITER_MESSAGE = "Need to install JAI Image I/O package.\nhttps://java.net/projects/jai-imageio/";
    final static String JAI_IMAGE_READER_MESSAGE = "Unsupported image format. May need to install JAI Image I/O package.\nhttps://java.net/projects/jai-imageio/";

    /**
     * Creates a list of TIFF image files from an image file. It basically
     * converts images of other formats to TIFF format, or a multi-page TIFF
     * image to multiple TIFF image files.
     *
     * @param imageFile input image file
     * @param index an index of the page; -1 means all pages, as in a multi-page
     * TIFF image
     * @return a list of TIFF image files
     * @throws Exception
     */
    public static List<File> createTiffFiles(File imageFile, int index) throws IOException {
        List<File> tiffFiles = new ArrayList<File>();

        String imageFileName = imageFile.getName();
        String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);

        if (!readers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
        }

        ImageReader reader = readers.next();

        ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
        reader.setInput(iis);
        //Read the stream metadata
//        IIOMetadata streamMetadata = reader.getStreamMetadata();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

        //Get tif writer and set output to file
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);

        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }

        ImageWriter writer = writers.next();

        //Read the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        int imageTotal = reader.getNumImages(true);

        for (int i = 0; i < imageTotal; i++) {
            // all if index == -1; otherwise, only index-th
            if (index == -1 || i == index) {
//                BufferedImage bi = reader.read(i);
//                IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i));
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
                ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
                writer.setOutput(ios);
                writer.write(streamMetadata, oimage, tiffWriteParam);
                ios.close();
                tiffFiles.add(tiffFile);
            }
        }
        writer.dispose();
        reader.dispose();

        return tiffFiles;
    }

    /**
     * Creates a list of TIFF image files from a list of
     * IIOImage objects.
     *
     * @param imageList a list of IIOImage objects
     * @param index an index of the page; -1 means all pages
     * @return a list of TIFF image files
     * @throws Exception
     */
    public static List<File> createTiffFiles(List<IIOImage> imageList, int index) throws IOException {
        return createTiffFiles(imageList, index, 0, 0);
    }

    public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY) throws IOException {
        List<File> tiffFiles = new ArrayList<File>();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

        //Get tif writer and set output to file
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);

        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }

        ImageWriter writer = writers.next();

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        // all if index == -1; otherwise, only index-th
        for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
            if (dpiX != 0 && dpiY != 0) {
                // Get the default image metadata.
                ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
                IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
                imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
                oimage.setMetadata(imageMetadata);
            }

            File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
            ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
            writer.setOutput(ios);
            writer.write(streamMetadata, oimage, tiffWriteParam);
            ios.close();
            tiffFiles.add(tiffFile);
        }
        writer.dispose();

        return tiffFiles;
    }

    /**
     * Set DPI using API.
     */
    private static IIOMetadata setDPIViaAPI(IIOMetadata imageMetadata, int dpiX, int dpiY)
            throws IIOInvalidTreeException {
        // Derive the TIFFDirectory from the metadata.
        TIFFDirectory dir = TIFFDirectory.createFromMetadata(imageMetadata);

        // Get {X,Y}Resolution tags.
        BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance();
        TIFFTag tagXRes = base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION);
        TIFFTag tagYRes = base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION);

        // Create {X,Y}Resolution fields.
        TIFFField fieldXRes = new TIFFField(tagXRes, TIFFTag.TIFF_RATIONAL,
                1, new long[][]{{dpiX, 1}});
        TIFFField fieldYRes = new TIFFField(tagYRes, TIFFTag.TIFF_RATIONAL,
                1, new long[][]{{dpiY, 1}});

        // Append {X,Y}Resolution fields to directory.
        dir.addTIFFField(fieldXRes);
        dir.addTIFFField(fieldYRes);

        // Convert to metadata object and return.
        return dir.getAsMetadata();
    }

    /**
     * Gets pixel data of an IIOImage object.
     *
     * @param image an IIOImage object
     * @return a byte buffer of pixel data
     * @throws IOException
     */
    public static ByteBuffer getImageByteBuffer(IIOImage image) throws IOException {
        return getImageByteBuffer(image.getRenderedImage());
    }

    /**
     * Gets pixel data of an RenderedImage object.
     * @param image an RenderedImage object
     * @return a byte buffer of pixel data
     * @throws IOException
     */
    public static ByteBuffer getImageByteBuffer(RenderedImage image) throws IOException {
        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

        //Get tif writer and set output to file
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);

        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }

        ImageWriter writer = writers.next();

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
        writer.setOutput(ios);
        writer.write(streamMetadata, new IIOImage(image, null, null), tiffWriteParam);
//        writer.write(image);
        writer.dispose();
//        ImageIO.write(image, "tiff", ios); // this can be used in lieu of writer
        ios.seek(0);
        BufferedImage bi = ImageIO.read(ios);
        return convertImageData(bi);
    }

    /**
     * Converts BufferedImage to ByteBuffer.
     *
     * @param bi Input image
     * @return pixel data
     */
    public static ByteBuffer convertImageData(BufferedImage bi) {
        DataBuffer buff = bi.getRaster().getDataBuffer();
        // ClassCastException thrown if buff not instanceof DataBufferByte because raster data is not necessarily bytes.
        // Convert the original buffered image to grayscale.
        if (!(buff instanceof DataBufferByte)) {
            bi = ImageHelper.convertImageToGrayscale(bi);
            buff = bi.getRaster().getDataBuffer();
        }
        byte[] pixelData = ((DataBufferByte) buff).getData();
        //        return ByteBuffer.wrap(pixelData);
        ByteBuffer buf = ByteBuffer.allocateDirect(pixelData.length);
        buf.order(ByteOrder.nativeOrder());
        buf.put(pixelData);
        buf.flip();
        return buf;
    }

    /**
     * Gets a list of IIOImage objects for an image file.
     *
     * @param imageFile input image file. It can be any of the supported
     * formats, including TIFF, JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL
     * Ghostscript is installed
     * @return a list of IIOImage objects
     * @throws Exception
     */
    public static List<IIOImage> getIIOImageList(File imageFile) throws IOException {
        File workingTiffFile = null;

        ImageReader reader = null;
        ImageInputStream iis = null;

        try {
            List<IIOImage> iioImageList = new ArrayList<IIOImage>();

            String imageFileName = imageFile.getName();
            String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
            if (imageFormat.matches("(pbm|pgm|ppm)")) {
                imageFormat = "pnm";
            } else if (imageFormat.equals("jp2")) {
                imageFormat = "jpeg2000";
            }
            Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);

            if (!readers.hasNext()) {
                throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
            }

            reader = readers.next();
            iis = ImageIO.createImageInputStream(imageFile);
            reader.setInput(iis);

            int imageTotal = reader.getNumImages(true);

            for (int i = 0; i < imageTotal; i++) {
//                IIOImage oimage = new IIOImage(reader.read(i), null, reader.getImageMetadata(i));
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                iioImageList.add(oimage);
            }

            return iioImageList;
        } finally {
            try {
                if (iis != null) {
                    iis.close();
                }
                if (reader != null) {
                    reader.dispose();
                }
            } catch (Exception e) {
                // ignore
            }
            if (workingTiffFile != null && workingTiffFile.exists()) {
                workingTiffFile.delete();
            }
        }
    }

    /**
     * Gets a list of IIOImage objects for a BufferedImage.
     * @param bi input image
     * @return a list of IIOImage objects
     * @throws IOException
     */
    public static List<IIOImage> getIIOImageList(BufferedImage bi) throws IOException {
        List<IIOImage> iioImageList = new ArrayList<IIOImage>();
        IIOImage oimage = new IIOImage(bi, null, null);
        iioImageList.add(oimage);
        return iioImageList;
    }

    /**
     * Merges multiple images into one TIFF image.
     *
     * @param inputImages an array of image files
     * @param outputTiff the output TIFF file
     * @throws Exception
     */
    public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException {
        List<IIOImage> imageList = new ArrayList<IIOImage>();

        for (int i = 0; i < inputImages.length; i++) {
            imageList.addAll(getIIOImageList(inputImages[i]));
        }

        if (imageList.isEmpty()) {
            // if no image
            return;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);

        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }

        ImageWriter writer = writers.next();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff);
        writer.setOutput(ios);

        IIOImage firstIioImage = imageList.remove(0);
        writer.write(streamMetadata, firstIioImage, tiffWriteParam);

        int i = 1;
        for (IIOImage iioImage : imageList) {
            writer.writeInsert(i++, iioImage, tiffWriteParam);
        }
        ios.close();

        writer.dispose();
    }

    /**
     * Reads image meta data.
     *
     * @param oimage
     * @return a map of meta data
     */
    public static Map<String, String> readImageData(IIOImage oimage) {
        Map<String, String> dict = new HashMap<String, String>();

        IIOMetadata imageMetadata = oimage.getMetadata();
        if (imageMetadata != null) {
            IIOMetadataNode dimNode = (IIOMetadataNode) imageMetadata.getAsTree("javax_imageio_1.0");
            NodeList nodes = dimNode.getElementsByTagName("HorizontalPixelSize");
            int dpiX;
            if (nodes.getLength() > 0) {
                float dpcWidth = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue());
                dpiX = (int) Math.round(25.4f / dpcWidth);
            } else {
                dpiX = Toolkit.getDefaultToolkit().getScreenResolution();
            }
            dict.put("dpiX", String.valueOf(dpiX));

            nodes = dimNode.getElementsByTagName("VerticalPixelSize");
            int dpiY;
            if (nodes.getLength() > 0) {
                float dpcHeight = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue());
                dpiY = (int) Math.round(25.4f / dpcHeight);
            } else {
                dpiY = Toolkit.getDefaultToolkit().getScreenResolution();
            }
            dict.put("dpiY", String.valueOf(dpiY));
        }

        return dict;
    }
}


text:
[![Build Status](https://secure.travis-ci.org/claudijd/bnat.png)](http://travis-ci.org/claudijd/bnat)
[![Dependency Status](https://gemnasium.com/claudijd/bnat.png)](https://gemnasium.com/claudijd/bnat)
[![Code Climate](https://codeclimate.com/github/claudijd/bnat.png)](https://codeclimate.com/github/claudijd/bnat)

BNAT (Broken NAT) is namely defined as IP communication that is being improperly nat'd to create an inoperable communication channel. A common example of BNAT is found in asymmetric routing where we (intentionally or unintentionally) create a logical layer 3 loop in a TCP/IP session between a client and a server. This is commonly found in complex routing scenarios or situations where mistakes are "corrected" to make something work without understanding or caring about the actual flow of traffic.

## Very Basic Example

```
.1 ----SYN-----> .2 (.1 is the client and starts a session w/ a syn to .2)
.1 <--SYN/ACK--- .3 (.3 responds to .1 with the syn/ack)
.1 ----RST-----> .3 (.1 responds to .3 with a rst)
```

## Why Does BNAT Matter?

BNAT effectively hides TCP ports from being identified by modern TCP clients and port scanning utilities like NMAP. With the right tools, you can identify ports that would otherwise be considered as closed/filtered which can be converted into legitimate open ports. This opens the door for traditional exploitation vectors in a service that was previously unreachable.

## BNAT Presentations

- [**BNAT Hijacking: Repairing Broken Communication Channels**](https://speakerdeck.com/claudijd/bnat-hijacking-repairing-broken-communication-channels)

## BNAT Videos

- [**BNAT-Scan compared to NMAP -sS Scan**](http://www.youtube.com/watch?v=8Um1cJswCeM)
- [**BNAT-Router handling BNAT'd SSH Session**](http://www.youtube.com/watch?v=C8zv10VHyUg)
- [**Using Metaploit's BNAT auxmod's to exploit Tomcat**](http://www.youtube.com/watch?v=FS_cg1PVhkI)

## Blog Posts

- [**Metasploit Blog - A Tale From Defcon and the Fun of BNAT**](https://community.rapid7.com/community/metasploit/blog/2011/08/26/a-tale-from-defcon-and-the-fun-of-bnat)
- [**Spiderlabs Blog - Advanced BNAT in the Wild**](http://blog.spiderlabs.com/2011/09/advanced-bnat-broken-network-address-translation-in-the-wild.html)

## Setup

TODO

## Rubies Supported

TODO

## Contributing

If you are interested in contributing to this project, please see [CONTRIBUTING.md](https://github.com/claudijd/bnat/blob/master/CONTRIBUTING.md)

## Credits

TODO


text:
/**
 * Created by USER: tarso.
 * On         DATE: 11/01/17.
 * By         NAME: app01.js.
 *
 * Source: https://github.com/datastax/nodejs-driver
 */

'use strict';

const assert = require('assert');

const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['172.17.0.4', '172.17.0.5'], keyspace: 'demo' });

const query = 'SELECT * FROM names';

client.execute(query, { prepare: true }, function (err, result) {
  if (err) {
    throw err;
  }

//  console.log(result.rows);
  console.log('Raw result... (typeof: %s)', typeof(result));
  console.log(result);
  console.log('  Host response: %s', result.info.queriedHost);

  console.log('Raw result.rows... (typeof: %s)', typeof(result.rows));
  console.log(result.rows);

  console.log('Pretty result.rows[n]... (typeof: %s)', typeof(result.rows[0]));
  console.log('   qty: %d', result.rows.length);
  for (var nSxi = 0, len = result.rows.length; nSxi < len; nSxi++) {
    console.log('{ "id": %d, "name": "%s" }', result.rows[nSxi].id, result.rows[nSxi].name);
  }

  process.exit();
});

/*
client.execute(query, [ ], function(err, result) {
  assert.ifError(err);
  console.log('Result: ', result);
  // client.exit(0);
});
*/


text:
package com.actian.services.dataflow.operators;

import static com.pervasive.datarush.types.TokenTypeConstant.STRING;

import java.util.Properties;

import com.pervasive.datarush.annotations.OperatorDescription;
import com.pervasive.datarush.annotations.PortDescription;
import com.pervasive.datarush.annotations.PropertyDescription;
import com.pervasive.datarush.graphs.DROperatorException;
import com.pervasive.datarush.operators.ExecutableOperator;
import com.pervasive.datarush.operators.ExecutionContext;
import com.pervasive.datarush.operators.RecordPipelineOperator;
import com.pervasive.datarush.operators.StreamingMetadataContext;
import com.pervasive.datarush.ports.physical.RecordInput;
import com.pervasive.datarush.ports.physical.RecordOutput;
import com.pervasive.datarush.ports.physical.StringOutputField;
import com.pervasive.datarush.ports.record.FullDataDistribution;
import com.pervasive.datarush.ports.record.RecordPort;
import com.pervasive.datarush.tokens.TokenUtils;
import com.pervasive.datarush.types.RecordTokenType;
import com.pervasive.datarush.types.RecordTokenTypeBuilder;
import java.io.FileInputStream;
import java.io.IOException;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.annotate.JsonProperty;

//@JsonTypeName("mockExternalRecordSource")
@JsonAutoDetect(JsonMethod.NONE)
@OperatorDescription("A source for external data.")
public class MockableExternalRecordSource extends ExecutableOperator implements RecordPipelineOperator {

	private final RecordPort input = newRecordInput("input", true);
	private final RecordPort output = newRecordOutput("output");
	private Properties properties = new Properties();
    private String parameterFile = "";

	@PortDescription("Mock input data")
	public RecordPort getInput() {
		return input;
	}

	@PortDescription("Output data")
	public RecordPort getOutput() {
		return output;
	}

	@JsonProperty
	@PropertyDescription("A collection of name/value out parameters")
	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

    @JsonProperty
    public String getParameterFile() {
        return parameterFile;
    }

    public void setParameterFile(String filename) {
        this.parameterFile = filename;
    }

	@Override
	protected void execute(ExecutionContext ctx) {
		// Pass through
		RecordInput inputRec = null;
		try {
			inputRec = (RecordInput) ctx.getInputPort(getInput());
		} catch (NullPointerException ex) {
			; // Get this exception if no input.
		}

        // Load properties from a file?
        if (parameterFile != null && !parameterFile.isEmpty()) {
            try {
                properties.loadFromXML(new FileInputStream(parameterFile));
            } catch (IOException ex) {
                throw new DROperatorException(ctx.getPath(), ex);
            }
        }

		RecordOutput outputRec = (RecordOutput) ctx.getOutputPort(getOutput());
		if (inputRec != null) {
			while (inputRec.stepNext()) {
                TokenUtils.transfer(inputRec.getFields(), outputRec.getFields());
				outputRec.push();
			}
		} else {
			for (Object key : properties.keySet()) {
				StringOutputField sof = (StringOutputField) outputRec.getField((String) key);
				if (sof != null) {
					sof.set(properties.getProperty((String) key));
				}
			}
			outputRec.push();
		}
		outputRec.pushEndOfData();
	}

	@Override
	protected void computeMetadata(StreamingMetadataContext ctx) {
		// Confirm that there is no redistribution
		// Check for input
		RecordTokenType schema;
		try {
			schema = input.getCombinedMetadata(ctx).getType();
		} catch (IllegalStateException ex) {
			RecordTokenTypeBuilder builder = new RecordTokenTypeBuilder();

			for (Object key : properties.keySet()) {
				builder.addField((String) key, STRING);
			}
			schema = builder.toType();
		}
		// Confirm schema is all string type
		output.setType(ctx, schema );
		getOutput().setOutputDataDistribution(ctx, FullDataDistribution.INSTANCE);
	}

}


text:
package fr.paris.lutece.portal.web.insert;

import org.apache.commons.lang3.StringUtils;
import org.springframework.mock.web.MockHttpServletRequest;

import fr.paris.lutece.test.LuteceTestCase;

/**
 * InsertServiceSelectorJspBean Test Class
 */
public class InsertServiceSelectorJspBeanTest extends LuteceTestCase
{
    /**
     * Test of getServicesListPage method, of class fr.paris.lutece.portal.web.insertservice.InsertServiceSelectorJspBean.
     */
    public void testGetServicesListPage( )
    {
        MockHttpServletRequest request = new MockHttpServletRequest( );
        request.addParameter( "input", "text" );
        request.addParameter( "selected_text", "selected_text" );

        InsertServiceSelectorJspBean instance = new InsertServiceSelectorJspBean( );

        assertTrue( StringUtils.isNotEmpty( instance.getServicesListPage( request ) ) );
    }

    /**
     * Test of displayService method, of class fr.paris.lutece.portal.web.insertservice.InsertServiceSelectorJspBean.
     */
    public void testDisplayService( )
    {
        MockHttpServletRequest request = new MockHttpServletRequest( );
        InsertServiceSelectorJspBean instance = new InsertServiceSelectorJspBean( );

        assertTrue( StringUtils.isNotEmpty( instance.displayService( request ) ) );
    }
}


text:
#include <aws/greengrass/model/UpdateThingRuntimeConfigurationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Greengrass::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateThingRuntimeConfigurationRequest::UpdateThingRuntimeConfigurationRequest() :
    m_telemetryConfigurationHasBeenSet(false),
    m_thingNameHasBeenSet(false)
{
}

Aws::String UpdateThingRuntimeConfigurationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_telemetryConfigurationHasBeenSet)
  {
   payload.WithObject("TelemetryConfiguration", m_telemetryConfiguration.Jsonize());

  }

  return payload.View().WriteReadable();
}


text:
'''
Created on Nov 6, 2013

@author: Stuart Jones [stu@kellyjones.org]
'''
from datetime import datetime
import glob

torqueFileSuffix = ".csv"
torqueFilePrefix = "trackLog-"

####################################################################
## function: getTorqueLogDatestamp(string)
## returns: Date
##
## Logs from Torque carry a filename with a specific
## naming convention. This function will read the name
## of a file and return a date (with time) value
## as parsed from the filename.
####################################################################
def getTorqueLogDatestamp(logFileName):
    myfilename = logFileName
    dateStringInFilename = myfilename.replace(torqueFilePrefix, "").replace(torqueFileSuffix, "")
    strippedString = dateStringInFilename.replace("_", " ").replace("-", " ")
    fileTimestamp = datetime.strptime(strippedString, "%Y %b %d %H %M %S")
    return fileTimestamp

####################################################################
## function: getTorqueLogFiles(string)
## returns: List
##
## Scans the given directory for all files that match the expected
## naming conventions; they will start with the prefix as indicated
## in the "torqueFilePrefix" variable, and end in the file extension
## as indicated in the "torqueFileSuffix" variable.
##
## This function uses Python glob() to return a list of all matching
## files
####################################################################
def getTorqueLogFiles(fromDirectory):
    return glob.glob1(fromDirectory, torqueFilePrefix+"*"+torqueFileSuffix)


text:
package cabf_br

import (
	"github.com/zmap/zcrypto/encoding/asn1"
	"github.com/zmap/zcrypto/x509"
	"github.com/zmap/zlint/v3/lint"
	"github.com/zmap/zlint/v3/util"
)

type subCertNotCA struct{}

func init() {
	lint.RegisterLint(&lint.Lint{
		Name:          "e_sub_cert_not_is_ca",
		Description:   "Subscriber Certificate: basicContrainsts cA field MUST NOT be true.",
		Citation:      "BRs: 7.1.2.3",
		Source:        lint.CABFBaselineRequirements,
		EffectiveDate: util.CABEffectiveDate,
		Lint:          NewSubCertNotCA,
	})
}

func NewSubCertNotCA() lint.LintInterface {
	return &subCertNotCA{}
}

func (l *subCertNotCA) CheckApplies(c *x509.Certificate) bool {
	return util.IsExtInCert(c, util.KeyUsageOID) && c.KeyUsage&x509.KeyUsageCertSign == 0 && util.IsExtInCert(c, util.BasicConstOID)
}

func (l *subCertNotCA) Execute(c *x509.Certificate) *lint.LintResult {
	e := util.GetExtFromCert(c, util.BasicConstOID)
	var constraints basicConstraints
	if _, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
		return &lint.LintResult{Status: lint.Fatal}
	}
	if constraints.IsCA {
		return &lint.LintResult{Status: lint.Error}
	} else {
		return &lint.LintResult{Status: lint.Pass}
	}
}


text:
import collections
import datetime

import pytz

from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render

from standup.status.models import Status, Team, StandupUser

def require_superuser(fun):
    def authorize_user(user):
        return user.is_active and user.is_superuser

    return user_passes_test(authorize_user)(fun)

@require_superuser
def errormenow_view(request):
    # This is an intentional error designed to kick up the error page because
    # otherwise it's difficult to test.
    1 / 0  # noqa

@require_superuser
def statistics_view(request):
    """Show health statistics for the system

    .. Note::

       This is an "admin" view, so it uses Django templates.

    """
    hours_24 = datetime.datetime.now(tz=pytz.UTC) - datetime.timedelta(hours=24)
    week = datetime.datetime.now(tz=pytz.UTC) - datetime.timedelta(days=7)

    groups = collections.OrderedDict()

    groups['Standup users'] = collections.OrderedDict([
        ('Team count', Team.objects.count()),
        ('User count', StandupUser.objects.count()),
        ('New users in last 24 hours', StandupUser.objects.filter(user__date_joined__gte=hours_24).count()),
        ('Active users (posted in last week)',
         StandupUser.objects.filter(id__in=Status.objects.filter(created__gte=week).values('user__id')).count()),
    ])

    groups['Standup status'] = collections.OrderedDict([
        ('Status count', Status.objects.count()),
        ('Status in last 24 hours', Status.objects.filter(created__gte=hours_24).count()),
        ('Status in last week', Status.objects.filter(created__gte=week).count()),
    ])

    context = {
        'title': 'Site statistics',
        'statsitems': groups
    }

    return render(request, 'admin/statistics.html', context)


text:
package org.gradle.api.internal.artifacts.ivyservice;

import org.gradle.api.artifacts.ResolveException;
import org.gradle.api.internal.artifacts.ArtifactDependencyResolver;
import org.gradle.api.internal.artifacts.GlobalDependencyResolutionRules;
import org.gradle.api.internal.artifacts.ResolverResults;
import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal;
import org.gradle.api.internal.artifacts.repositories.ResolutionAwareRepository;

import java.util.List;

public class CacheLockingArtifactDependencyResolver implements ArtifactDependencyResolver {
    private final CacheLockingManager lockingManager;
    private final ArtifactDependencyResolver resolver;

    public CacheLockingArtifactDependencyResolver(CacheLockingManager lockingManager, ArtifactDependencyResolver resolver) {
        this.lockingManager = lockingManager;
        this.resolver = resolver;
    }

    public void resolve(final ConfigurationInternal configuration,
                                   final List<? extends ResolutionAwareRepository> repositories,
                                   final GlobalDependencyResolutionRules metadataHandler,
                                   final ResolverResults results) throws ResolveException {
        lockingManager.useCache(String.format("resolve %s", configuration), new Runnable() {
            public void run() {
                resolver.resolve(configuration, repositories, metadataHandler, results);
            }
        });
    }
}