text:
require "socket"
begin
  require "mongo"
rescue LoadError
  raise LoadError, 'Gem mongo is required for logging to MongoDB. Please add the gem "mongo" v2.0 or greater to your Gemfile.'
end

module SemanticLogger
  module Appender
    # The Mongo Appender for the SemanticLogger
    #
    # Mongo Document Schema:
    #    _id:         ObjectId("4d9cbcbf7abb3abdaf9679cd"),
    #    time:        ISODate("2011-04-06T19:19:27.006Z"),
    #    host:        'Name of the host on which this log entry originated',
    #    application  'Name of application or service logging the data - clarity_base, nginx, tomcat',
    #    pid:         process id
    #    thread:      "name or id of thread",
    #    name:        "com.clarity.MyClass",
    #    level:       'trace|debug|info|warn|error|fatal'
    #    level_index: 0|1|2|3|4|5
    #    message:     "Message supplied to the logging call",
    #    duration:    'human readable duration',
    #    duration_ms: ms,
    #    tags:        ["id1", "id2"]
    #    exception: {
    #      name:        'MyException',
    #      message:     'Invalid value',
    #      stack_trace: []
    #    }
    #    # When a backtrace is captured
    #    file_name:   'my_class.rb'
    #    line_number: 42
    #
    # Example:
    #   require 'semantic_logger'
    #
    #   client   = Mongo::MongoClient.new
    #   database = client['test']
    #
    #   appender = SemanticLogger::Appender::MongoDB.new(
    #     db:              database,
    #     collection_size: 1024**3 # 1.gigabyte
    #   )
    #   SemanticLogger.add_appender(appender: appender)
    #
    #   logger = SemanticLogger['Example']
    #
    #   # Log some messages
    #   logger.info 'This message is written to mongo as a document'
    class MongoDB < SemanticLogger::Subscriber
      attr_reader :client, :collection

      # Create a MongoDB Appender instance
      #
      # Parameters:
      #   uri: [String]
      #     Mongo connection string.
      #     Example:
      #       mongodb://127.0.0.1:27017/test
      #
      #   collection_name: [String]
      #     Name of the collection to store log data in
      #     Default: semantic_logger
      #
      #   write_concern: [Integer]
      #     Write concern to use
      #     see: http://docs.mongodb.org/manual/reference/write-concern/
      #     Default: 0
      #
      #   collection_size: [Integer]
      #     The size of the MongoDB capped collection to create in bytes
      #     Default: 1 GB
      #     Examples:
      #       Prod: 25GB (.5GB per day across 4 servers over 10 days)
      #       Dev: .5GB
      #       Test: File
      #       Release: 4GB
      #
      #   collection_max: [Integer]
      #     Maximum number of log entries that the capped collection will hold.
      #     Default: no max limit
      #
      #   level: [:trace | :debug | :info | :warn | :error | :fatal]
      #     Override the log level for this appender.
      #     Default: SemanticLogger.default_level
      #
      #   formatter: [Object|Proc|Symbol]
      #     An instance of a class that implements #call, or a Proc to be used to format
      #     the output from this appender
      #     Default: Use the built-in formatter (See: #call)
      #
      #   filter: [Regexp|Proc]
      #     RegExp: Only include log messages where the class name matches the supplied.
      #     regular expression. All other messages will be ignored.
      #     Proc: Only include log messages where the supplied Proc returns true
      #           The Proc must return true or false.
      #
      #   host: [String]
      #     Name of this host to appear in log messages.
      #     Default: SemanticLogger.host
      #
      #   application: [String]
      #     Name of this application to appear in log messages.
      #     Default: SemanticLogger.application
      def initialize(uri:,
                     collection_name: "semantic_logger",
                     write_concern: 0,
                     collection_size: 1024**3,
                     collection_max: nil,
                     **args,
                     &block)

        @client          = Mongo::Client.new(uri, logger: logger)
        @collection_name = collection_name
        @options         = {
          capped: true,
          size:   collection_size,
          write:  {w: write_concern}
        }
        @options[:max] = collection_max if collection_max

        reopen

        # Create the collection and necessary indexes
        create_indexes

        super(**args, &block)
      end

      # After forking an active process call #reopen to re-open
      # open the handles to resources
      def reopen
        @collection = client[@collection_name, @options]
      end

      # Create the required capped collection.
      #
      # Features of capped collection:
      # * No indexes by default (not even on _id)
      # * Documents cannot be deleted,
      # * Document updates cannot make them any larger
      # * Documents are always stored in insertion order
      #   * A find will always return the documents in their insertion order
      #
      # Creates an index based on tags to support faster searches.
      def create_indexes
        # Create Capped collection
        begin
          @collection.create
        rescue Mongo::Error::OperationFailure
          nil
        end

        @collection.indexes.create_one(tags: 1)
      end

      # Purge all data from the capped collection by dropping the collection
      # and recreating it.
      # Also useful when the size of the capped collection needs to be changed
      def purge_all
        collection.drop
        reopen
        create_indexes
      end

      # Log the message to MongoDB
      def log(log)
        # Insert log entry into Mongo
        collection.insert_one(formatter.call(log, self))
        true
      end

      private

      def default_formatter
        SemanticLogger::Formatters::Raw.new
      end
    end
  end
end


text:
@implementation SFGenreIntegrationTests {
	id artworkFactoryMock;
	id testPlayer;
	id nativeMediaFactoryMock;
	id nameGenreMapperMock;
}

- (void)setUp {
	artworkFactoryMock = [OCMockObject niceMockForClass:[ArtworkFactory class]];
	testPlayer = [[SFTestMediaPlayer alloc] init];
	nativeMediaFactoryMock = [OCMockObject niceMockForClass:[SFNativeMediaFactory class]];
	[[[nativeMediaFactoryMock stub] andCall:@selector(newAlbumWithName:) onObject:self] newAlbumWithName:[OCMArg any]];
	nameGenreMapperMock = [OCMockObject mockForClass:[NameGenreMapper class]];
}

- (void)tearDown {
}

- (SFAlbum *)newAlbumWithName:(NSString *)name {
	return [[SFAlbum alloc] initWithName:name player:testPlayer artworkFactory:artworkFactoryMock];
}

- (SFTrack *)trackWithId:(NSUInteger)trackId artist:(NSString *)artist albumArtist:(NSString *)albumArtist album:(NSString *)album compilation:(BOOL)compilation disc:(NSUInteger)disc trackNumber:(NSNumber *)trackNumber {
	return [SFTrackTestHelper trackWithId:trackId genre:@"NotUsed" artist:artist albumArtist:albumArtist album:album compilation:compilation disc:disc trackNumber:trackNumber artworkFactory:artworkFactoryMock nameGenreMapper:nameGenreMapperMock player:testPlayer];
}

- (void)testTracksSortedEqually {
	GenreDefinition *gdef = [[GenreDefinition alloc] initWithName:@"SomeName" origin:CGPointMake(0,0) color:[UIColor whiteColor] subgenres:@[]];
	SFGenre *genre1 = [[SFGenre alloc] initWithGenreDefinition:gdef player:testPlayer];

	[self addTestTracks:genre1];
	NSArray *tracksBeforePush = [genre1 tracks];
	[self pushDownTracks:genre1];
	NSArray *tracksAfterPush = [genre1 tracks];

	for(NSUInteger i = 0; i != [tracksBeforePush count]; ++i) {
		STAssertEquals(i + 1, [[[tracksBeforePush objectAtIndex:i] mediaItemId] unsignedIntegerValue], @"Unexpected track order: %@", tracksBeforePush);
	}

	STAssertEqualObjects(tracksBeforePush, tracksAfterPush, @"Should be same order of tracks");
}

- (void)addTestTracks:(SFGenre *)genre {
	[genre addTrack:[self trackWithId:5 artist:@"Ignore2" albumArtist:@"Foo" album:@"a1" compilation:YES disc:1 trackNumber:@1]];
	[genre addTrack:[self trackWithId:6 artist:@"Ignore5" albumArtist:@"Bar" album:@"A1" compilation:YES disc:1 trackNumber:@2]];
	[genre addTrack:[self trackWithId:7 artist:@"Ignore8" albumArtist:@"Foo" album:@"A2" compilation:NO disc:1 trackNumber:@1]];
	[genre addTrack:[self trackWithId:8 artist:@"Ignore6" albumArtist:@"foo" album:@"a2" compilation:NO disc:1 trackNumber:@2]];
	[genre addTrack:[self trackWithId:3 artist:@"Ignore1" albumArtist:@"artist" album:@"A1" compilation:NO disc:2 trackNumber:@1]];
	[genre addTrack:[self trackWithId:2 artist:@"Ignore3" albumArtist:@"artist" album:@"a1" compilation:NO disc:1 trackNumber:@2]];
	[genre addTrack:[self trackWithId:4 artist:@"Ignore0" albumArtist:@"ArtIst2" album:@"A0" compilation:NO disc:2 trackNumber:@1]];
	[genre addTrack:[self trackWithId:1 artist:@"Ignore1" albumArtist:@"ARTIST" album:@"A1" compilation:NO disc:1 trackNumber:@1]];
}

- (void)pushDownTracks:(SFGenre *)genre {
	id mockGenre = [OCMockObject partialMockForObject:genre];
	[[[mockGenre stub] andDo:[SynchronousChildrenAddingHelper synchronousChildrenAddingBlock]] addChildrenInMainThread:[OCMArg any]];

	[genre pushTracksIntoArtistChildren];
	[genre releaseLocalTracks];
	for(SFArtist *artist in [genre children]) {
		id mockArtist = [OCMockObject partialMockForObject:artist];
		[[[mockArtist stub] andDo:[SynchronousChildrenAddingHelper synchronousChildrenAddingBlock]] addChildrenInMainThread:[OCMArg any]];

		NSAssert([artist isKindOfClass:[SFArtist class]], @"Genre has non-artist child");
		[artist pushTracksIntoAlbumChildrenWithFactory:nativeMediaFactoryMock];
		[artist releaseLocalTracks];
	}
}

@end

redpajama_set_name: RedPajamaGithub


text:
#region License

#endregion

using System.Abstract;

namespace Contoso.Abstract
{
    /// <summary>
    /// An application service bus message handler interface
    /// </summary>
    /// <typeparam name="TMessage">The type of the message.</typeparam>
    /// <seealso cref="System.Abstract.IServiceMessageHandler{TMessage}" />
    public interface IAppServiceMessageHandler<TMessage> : IServiceMessageHandler<TMessage>
        where TMessage : class { }
}


text:
<?php

require_once(dirname(__FILE__) . '/new_db.inc');

function sum_list_step($context, $rows, $string) {
	if (empty($context))
	{
		$context = array('total' => 0, 'values' => array());
	}
	$context['total'] += intval($string);
	$context['values'][] = $context['total'];
	return $context;
}

function sum_list_finalize($context) {
	return implode(',', $context['values']);
}

echo "Creating Table\n";
var_dump($db->exec('CREATE TABLE test (a INTEGER, b INTEGER)'));

echo "INSERT into table\n";
var_dump($db->exec("INSERT INTO test (a, b) VALUES (1, -1)"));
var_dump($db->exec("INSERT INTO test (a, b) VALUES (2, -2)"));
var_dump($db->exec("INSERT INTO test (a, b) VALUES (3, -3)"));
var_dump($db->exec("INSERT INTO test (a, b) VALUES (4, -4)"));
var_dump($db->exec("INSERT INTO test (a, b) VALUES (4, -4)"));

$db->createAggregate('S', 'sum_list_step', 'sum_list_finalize', 1);

print_r($db->querySingle("SELECT S(a), S(b) FROM test", true));

echo "Closing database\n";
var_dump($db->close());
echo "Done\n";
?>


text:
package com.github.solairerove.web.rest;

import com.github.solairerove.Woodstock24App;

import com.github.solairerove.domain.Chapter;
import com.github.solairerove.repository.ChapterRepository;
import com.github.solairerove.service.ChapterService;
import com.github.solairerove.service.dto.ChapterDTO;
import com.github.solairerove.service.mapper.ChapterMapper;
import com.github.solairerove.web.rest.errors.ExceptionTranslator;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Test class for the ChapterResource REST controller.
 *
 * @see ChapterResource
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Woodstock24App.class)
public class ChapterResourceIntTest {

    private static final String DEFAULT_TITLE = "AAAAAAAAAA";
    private static final String UPDATED_TITLE = "BBBBBBBBBB";

    private static final String DEFAULT_CONTENT = "AAAAAAAAAA";
    private static final String UPDATED_CONTENT = "BBBBBBBBBB";

    @Autowired
    private ChapterRepository chapterRepository;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    private MockMvc restChapterMockMvc;

    private Chapter chapter;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        ChapterResource chapterResource = new ChapterResource(chapterService);
        this.restChapterMockMvc = MockMvcBuilders.standaloneSetup(chapterResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setControllerAdvice(exceptionTranslator)
            .setMessageConverters(jacksonMessageConverter).build();
    }

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static Chapter createEntity(EntityManager em) {
        Chapter chapter = new Chapter()
            .title(DEFAULT_TITLE)
            .content(DEFAULT_CONTENT);
        return chapter;
    }

    @Before
    public void initTest() {
        chapter = createEntity(em);
    }

    @Test
    @Transactional
    public void createChapter() throws Exception {
        int databaseSizeBeforeCreate = chapterRepository.findAll().size();

        // Create the Chapter
        ChapterDTO chapterDTO = chapterMapper.toDto(chapter);
        restChapterMockMvc.perform(post("/api/chapters")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(chapterDTO)))
            .andExpect(status().isCreated());

        // Validate the Chapter in the database
        List<Chapter> chapterList = chapterRepository.findAll();
        assertThat(chapterList).hasSize(databaseSizeBeforeCreate + 1);
        Chapter testChapter = chapterList.get(chapterList.size() - 1);
        assertThat(testChapter.getTitle()).isEqualTo(DEFAULT_TITLE);
        assertThat(testChapter.getContent()).isEqualTo(DEFAULT_CONTENT);
    }

    @Test
    @Transactional
    public void createChapterWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = chapterRepository.findAll().size();

        // Create the Chapter with an existing ID
        chapter.setId(1L);
        ChapterDTO chapterDTO = chapterMapper.toDto(chapter);

        // An entity with an existing ID cannot be created, so this API call must fail
        restChapterMockMvc.perform(post("/api/chapters")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(chapterDTO)))
            .andExpect(status().isBadRequest());

        // Validate the Alice in the database
        List<Chapter> chapterList = chapterRepository.findAll();
        assertThat(chapterList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    public void getAllChapters() throws Exception {
        // Initialize the database
        chapterRepository.saveAndFlush(chapter);

        // Get all the chapterList
        restChapterMockMvc.perform(get("/api/chapters?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(chapter.getId().intValue())))
            .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString())))
            .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString())));
    }

    @Test
    @Transactional
    public void getChapter() throws Exception {
        // Initialize the database
        chapterRepository.saveAndFlush(chapter);

        // Get the chapter
        restChapterMockMvc.perform(get("/api/chapters/{id}", chapter.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.id").value(chapter.getId().intValue()))
            .andExpect(jsonPath("$.title").value(DEFAULT_TITLE.toString()))
            .andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString()));
    }

    @Test
    @Transactional
    public void getNonExistingChapter() throws Exception {
        // Get the chapter
        restChapterMockMvc.perform(get("/api/chapters/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateChapter() throws Exception {
        // Initialize the database
        chapterRepository.saveAndFlush(chapter);
        int databaseSizeBeforeUpdate = chapterRepository.findAll().size();

        // Update the chapter
        Chapter updatedChapter = chapterRepository.findOne(chapter.getId());
        updatedChapter
            .title(UPDATED_TITLE)
            .content(UPDATED_CONTENT);
        ChapterDTO chapterDTO = chapterMapper.toDto(updatedChapter);

        restChapterMockMvc.perform(put("/api/chapters")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(chapterDTO)))
            .andExpect(status().isOk());

        // Validate the Chapter in the database
        List<Chapter> chapterList = chapterRepository.findAll();
        assertThat(chapterList).hasSize(databaseSizeBeforeUpdate);
        Chapter testChapter = chapterList.get(chapterList.size() - 1);
        assertThat(testChapter.getTitle()).isEqualTo(UPDATED_TITLE);
        assertThat(testChapter.getContent()).isEqualTo(UPDATED_CONTENT);
    }

    @Test
    @Transactional
    public void updateNonExistingChapter() throws Exception {
        int databaseSizeBeforeUpdate = chapterRepository.findAll().size();

        // Create the Chapter
        ChapterDTO chapterDTO = chapterMapper.toDto(chapter);

        // If the entity doesn't have an ID, it will be created instead of just being updated
        restChapterMockMvc.perform(put("/api/chapters")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(chapterDTO)))
            .andExpect(status().isCreated());

        // Validate the Chapter in the database
        List<Chapter> chapterList = chapterRepository.findAll();
        assertThat(chapterList).hasSize(databaseSizeBeforeUpdate + 1);
    }

    @Test
    @Transactional
    public void deleteChapter() throws Exception {
        // Initialize the database
        chapterRepository.saveAndFlush(chapter);
        int databaseSizeBeforeDelete = chapterRepository.findAll().size();

        // Get the chapter
        restChapterMockMvc.perform(delete("/api/chapters/{id}", chapter.getId())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        // Validate the database is empty
        List<Chapter> chapterList = chapterRepository.findAll();
        assertThat(chapterList).hasSize(databaseSizeBeforeDelete - 1);
    }

    @Test
    @Transactional
    public void equalsVerifier() throws Exception {
        TestUtil.equalsVerifier(Chapter.class);
        Chapter chapter1 = new Chapter();
        chapter1.setId(1L);
        Chapter chapter2 = new Chapter();
        chapter2.setId(chapter1.getId());
        assertThat(chapter1).isEqualTo(chapter2);
        chapter2.setId(2L);
        assertThat(chapter1).isNotEqualTo(chapter2);
        chapter1.setId(null);
        assertThat(chapter1).isNotEqualTo(chapter2);
    }

    @Test
    @Transactional
    public void dtoEqualsVerifier() throws Exception {
        TestUtil.equalsVerifier(ChapterDTO.class);
        ChapterDTO chapterDTO1 = new ChapterDTO();
        chapterDTO1.setId(1L);
        ChapterDTO chapterDTO2 = new ChapterDTO();
        assertThat(chapterDTO1).isNotEqualTo(chapterDTO2);
        chapterDTO2.setId(chapterDTO1.getId());
        assertThat(chapterDTO1).isEqualTo(chapterDTO2);
        chapterDTO2.setId(2L);
        assertThat(chapterDTO1).isNotEqualTo(chapterDTO2);
        chapterDTO1.setId(null);
        assertThat(chapterDTO1).isNotEqualTo(chapterDTO2);
    }

    @Test
    @Transactional
    public void testEntityFromId() {
        assertThat(chapterMapper.fromId(42L).getId()).isEqualTo(42);
        assertThat(chapterMapper.fromId(null)).isNull();
    }
}


text:
class Admin::RecordEditor < ApplicationController

  before_filter :login_required
  layout 'admin/application'

  def self.edits(active_record_symbol, icon = nil)
    @@record_symbol = active_record_symbol
    @@record_class_name = active_record_symbol.to_s.humanize
    if icon.nil?
      @@icon = @@record_symbol.to_s
    else
      @@icon = icon
    end

    class_eval <<END
    def toggle_attribute
      record = #{@@record_class_name}.find(params[:id])
      attribute = params[:attribute]
      record.toggle!(attribute)
      render(:partial => '/admin/attribute', :locals => {:record => record, :name => attribute})
    end
END
  end
end


text:
package uk.ac.ebi.phenotype.service.search;

import org.apache.solr.client.solrj.SolrClient;
import org.mousephenotype.cda.solr.SolrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * Support for solr search queries for core "mp"
 *
 */
@Service
public class SearchUrlServiceMp extends SearchUrlService {

    @Autowired
    @Qualifier("mpCore")
    private SolrClient solr;

    @Override
    public String qf() {
        return "mixSynQf";
    }

    @Override
    public String bq(String q) {
        if (q.equals("*:*") || q.equals("*")) {
            return "mp_term:\"male infertility\" ^100"
                    + " mp_term:\"female infertility\" ^100"
                    + " mp_term:infertility ^90";
        } else {
            return "mp_term:(" + q + ")^1000"
                    + " mp_term_synonym:(" + q + ")^500"
                    + " mp_definition:(" + q + ")^100";
        }
    }

    @Override
    public List<String> fieldList() {
        return Arrays.asList("mp_id", "mp_term", "mixSynQf", "mp_definition");
    }

    @Override
    public List<String> facetFields() {
        return Arrays.asList("top_level_mp_term_inclusive");
    }

    @Override
    public String facetSort() {
        return "index";
    }

    @Override
    public String facetMinCount() { return "0"; }

    @Override
    public List<String> gridHeaders() {
        return Arrays.asList("Phenotype", "Definition", "Ontology<br/>Tree");
    }

    @Override
    public String breadcrumb() {
        return "Phenotypes";
    }

    @Override
    public String sort() {
        return "mp_term asc";
    }

    @Override
    public String solrUrl() {
        return SolrUtils.getBaseURL(solr);
    }

}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package org.team3042.sweep;

import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.team3042.sweep.commands.CommandBase;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class SweeperBot extends IterativeRobot {

    //Command autonomousCommand;

    private String CALIBRATION_FILE_NAME = "CalibrationFile";
    private double CALIBRATION_MOTOR_SPEED = 0.25;
    private float CALIBRATION_LENGTH_IN_SECONDS = 2;
    private final int LOGGER_LEVEL = 1;

    public static Logger logger;
    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {
        //Creates logger
        SmartDashboard.putNumber("Logger level", LOGGER_LEVEL);
        logger = new Logger(true,true,LOGGER_LEVEL);
        logger.log("Robot init", 1);
        //Initialize the SmartDashboard
        SmartDashboard.putNumber("Calibration Length In Seconds", CALIBRATION_LENGTH_IN_SECONDS);
        SmartDashboard.putString("Calibration File Name", CALIBRATION_FILE_NAME);
        SmartDashboard.putNumber("Calibration Motor Speed", CALIBRATION_MOTOR_SPEED);
        SmartDashboard.putNumber("P value", .004);
        SmartDashboard.putNumber("Maintain distance", 1000);
        SmartDashboard.putNumber("Maintain speed", .3);

        // instantiate the command used for the autonomous period
        //autonomousCommand = new ExampleCommand();

        // Initialize all subsystems
        CommandBase.init();
    }

    public void autonomousInit() {
        // schedule the autonomous command (example)
        //autonomousCommand.start();
    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {
        Scheduler.getInstance().run();
    }

    public void teleopInit() {
	// This makes sure that the autonomous stops running when
        // teleop starts running. If you want the autonomous to
        // continue until interrupted by another command, remove
        // this line or comment it out.
        //autonomousCommand.cancel();
        Scheduler.getInstance().run();
    }

    /**
     * This function is called periodically during operator control
     */
    public void teleopPeriodic() {
        Scheduler.getInstance().run();
    }

    /**
     * This function is called periodically during test mode
     */
    public void testPeriodic() {
        LiveWindow.run();
    }

    public void disabledInit(){
        Scheduler.getInstance().removeAll();
    }

}


text:
using System;
using System.Numerics;

class P10_FactorialsUpTo100
{
    static void PrintArray(BigInteger[] array)
    {
        for (int i = 1; i <= array.GetUpperBound(0); i++)
        {
            Console.WriteLine("Factorial of {0} : {1}", i, array[i]);
        }
    }

    static void GetNextFactoriel(int index, BigInteger[] array)
    {
        array[index] = index * array[index - 1];
    }

    static void Main()
    {
        Console.Write("factorials up to ? : ");
        int range = int.Parse(Console.ReadLine());
        BigInteger[] factorialArray = new BigInteger[range + 1];
        factorialArray[0] = 0;
        factorialArray[1] = 1;

        for (int index = 2; index <= range; index++)
        {
            GetNextFactoriel(index, factorialArray);
        }

        PrintArray(factorialArray);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 16: 304 (1963)

#### Original name
Meliola angusta var. minor Hansf.

### Remarks
null


text:
#import "ABI9_0_0RCTAnimatedNode.h"

@interface ABI9_0_0RCTStyleAnimatedNode : ABI9_0_0RCTAnimatedNode

- (NSDictionary<NSString *, NSNumber *> *)updatedPropsDictionary;

@end


text:
using System;
using System.Collections;
using System.Collections.Generic;

public static class Program {
    public static void Method (string text) {
        Console.WriteLine("Method({0})", text);
    }

    public static void Method (MyType mt) {
        Console.WriteLine("Method({0})", mt);
    }

    public static void Main (string[] args) {
        Method("hello");

        Method(new MyType("world"));
    }
}

public class MyType {
    public readonly string Text;

    public MyType (string text) {
        Text = text;
    }

    public override string ToString () {
        return String.Format("MyType({0})", Text);
    }
}


text:
package uk.co.threeonefour.ifictionary.web.security.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.openid.OpenIDAuthenticationStatus;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import uk.co.threeonefour.ifictionary.web.security.service.SessionKeys;

public class OpenIDAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private String openIdRegistrationUrl;
    private NormalizedOpenIdAttributesBuilder normalizedOpenIdAttributesBuilder;

    public OpenIDAuthenticationFailureHandler(String openIdRegistrationUrl,
            NormalizedOpenIdAttributesBuilder normalizedOpenIdAttributesBuilder) {
        this.openIdRegistrationUrl = openIdRegistrationUrl;
        this.normalizedOpenIdAttributesBuilder = normalizedOpenIdAttributesBuilder;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        if (openIdAuthenticationSuccesfullButUserIsNotRegistered(exception)) {
            redirectToOpenIdRegistrationUrl(request, response, exception);
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }

    private void redirectToOpenIdRegistrationUrl(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        addOpenIdAttributesToSession(request, getOpenIdAuthenticationToken(exception));
        redirectStrategy.sendRedirect(request, response, openIdRegistrationUrl);
    }

    private void addOpenIdAttributesToSession(HttpServletRequest request,
            OpenIDAuthenticationToken openIdAuthenticationToken) throws ServletException {
        HttpSession session = request.getSession(false);
        sessionShouldBePresent(session);
        NormalizedOpenIdAttributes normalizedOpenIdAttributes = normalizedOpenIdAttributesBuilder
                .build(openIdAuthenticationToken);
        session.setAttribute(SessionKeys.openIdAttributes, normalizedOpenIdAttributes);
    }

    private void sessionShouldBePresent(HttpSession session) throws ServletException {
        if (session == null) {
            throw new ServletException("No session found");
        }
    }

    private boolean openIdAuthenticationSuccesfullButUserIsNotRegistered(AuthenticationException exception) {
        return exception instanceof UsernameNotFoundException
                && exception.getAuthentication() instanceof OpenIDAuthenticationToken
                && OpenIDAuthenticationStatus.SUCCESS.equals((getOpenIdAuthenticationToken(exception)).getStatus());
    }

    private OpenIDAuthenticationToken getOpenIdAuthenticationToken(AuthenticationException exception) {
        return ((OpenIDAuthenticationToken) exception.getAuthentication());
    }

}


text:
Team A1: Survey Gorilla Group Project
Jeff George, Arc Petretta, Jack Huang, Eunice Do

Description of your MVP:
A user (creator) will be able to log in and create a survey, with a title, and as many questions and answer choices as they want.
A user (taker) will be able to log in and take a survey.
At the end of the survey, a thank you page will be displayed.
A user (creator) will be able to see an analysis of their survey results.
Stretch: Any user can see the surveys they created, or the surveys they took.

A link to your team Trello board:
https://trello.com/b/wFpvK8H5/welcome-board

A link to your wireframes:
![Survey Gorilla Wireframe] (wireframe.jpg)

A brief description of your team dynamic and git workflow:
Pair programming in agile sprints on a new repo. One pair code reviews the other prior to merges.

## Survey Gorilla Schema
![Survey Schema] (survey_schema.png)

## Schema XML
```
<?xml version="1.0" encoding="utf-8" ?>
<!-- SQL XML created by WWW SQL Designer, http://code.google.com/p/wwwsqldesigner/ -->
<!-- Active URL: https://schemadesigner.devbootcamp.com/ -->
<sql>
<datatypes db="mysql">
  <group label="Numeric" color="rgb(238,238,170)">
    <type label="Integer" length="0" sql="INTEGER" re="INT" quote=""/>
    <type label="Decimal" length="1" sql="DECIMAL" re="DEC" quote=""/>
    <type label="Single precision" length="0" sql="FLOAT" quote=""/>
    <type label="Double precision" length="0" sql="DOUBLE" re="DOUBLE" quote=""/>
  </group>

  <group label="Character" color="rgb(255,200,200)">
    <type label="Char" length="1" sql="CHAR" quote="'"/>
    <type label="Varchar" length="1" sql="VARCHAR" quote="'"/>
    <type label="Text" length="0" sql="MEDIUMTEXT" re="TEXT" quote="'"/>
    <type label="Binary" length="1" sql="BINARY" quote="'"/>
    <type label="Varbinary" length="1" sql="VARBINARY" quote="'"/>
    <type label="BLOB" length="0" sql="BLOB" re="BLOB" quote="'"/>
  </group>

  <group label="Date & Time" color="rgb(200,255,200)">
    <type label="Date" length="0" sql="DATE" quote="'"/>
    <type label="Time" length="0" sql="TIME" quote="'"/>
    <type label="Datetime" length="0" sql="DATETIME" quote="'"/>
    <type label="Year" length="0" sql="YEAR" quote=""/>
    <type label="Timestamp" length="0" sql="TIMESTAMP" quote="'"/>
  </group>

  <group label="Miscellaneous" color="rgb(200,200,255)">
    <type label="ENUM" length="1" sql="ENUM" quote=""/>
    <type label="SET" length="1" sql="SET" quote=""/>
    <type label="Bit" length="0" sql="bit" quote=""/>
  </group>
</datatypes><table x="326" y="133" name="users">
<row name="id" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="username" null="1" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
<default>NULL</default></row>
<row name="password_hash" null="1" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
</table>
<table x="493" y="133" name="surveys">
<row name="id" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="title" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="description" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="user_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="users" row="id" />
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
</table>
<table x="652" y="134" name="questions">
<row name="id" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="text" null="1" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
<default>NULL</default></row>
<row name="survey_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="surveys" row="id" />
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
</table>
<table x="825" y="134" name="choices (options)">
<row name="id" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="text" null="1" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
<default>NULL</default></row>
<row name="question_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="questions" row="id" />
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
</table>
<table x="350" y="293" name="survey_users (responses)">
<row name="id" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="user_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="users" row="id" />
</row>
<row name="survey_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="surveys" row="id" />
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
</table>
<table x="664" y="331" name="choice_responses (selections)">
<row name="id" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="response_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="survey_users (responses)" row="id" />
</row>
<row name="choice_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="choices (options)" row="id" />
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
</table>
</sql>

```


text:
package org.ovirt.engine.core.searchbackend;

import java.util.Arrays;
import java.util.List;

import junit.framework.TestCase;

public class EnumValueAutoCompleterTest extends TestCase {

    public void testValues() {
        IAutoCompleter comp = new EnumValueAutoCompleter(Jedi.class);
        List<String> comps = Arrays.asList(comp.getCompletion("L"));
        System.out.println(comps);
        assertTrue("luke", comps.contains("luke"));
        assertTrue("leia", comps.contains("leia"));
    }

    public void testConvertFieldEnumValueToActualValue() {
        EnumValueAutoCompleter comp = new EnumValueAutoCompleter(Jedi.class);
        assertEquals("MACE", "4", comp.convertFieldEnumValueToActualValue("MACE"));
        assertEquals("mace", "4", comp.convertFieldEnumValueToActualValue("mace"));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bss.Optimization.Appetizers.Entities;

namespace Bss.Optimization.Appetizers.Glop
{
    public static class Extensions
    {
        public static int ToCents(this double price)
        {
            return Convert.ToInt32(Math.Round(price * 100));
        }

        public static double CalculateObjective(this OptimizationResults result, IEnumerable<MenuItem> items)
        {
            double objectiveValue = 0.0;
            foreach (var item in items)
                objectiveValue += item.Price * result.Items[item.Id];
            return objectiveValue;
        }

        public static int DistinctItemCount(this OptimizationResults result)
        {
            return result.Items.Count(i => i > 0);
        }

        public static int MaxSingleItemCount(this OptimizationResults result)
        {
            return result.Items.Max(i => i);
        }

        public static int PlateCount(this OptimizationResults result)
        {
            return result.Items.Sum(i => i);
        }
    }
}


text:
'use strict'
const cluster = require('cluster')

if(!cluster.isMaster) {
    module.exports = SuperClass
    return
}

class MasterServer extends SuperClass {
    startWorker() {
        const worker = super.startWorker()

        if(this.setupNetworkDiscovery())
            this.networkDiscovery.registerWorker(worker)

        return worker
    }

    getConfig(name, retry) {
        try {
            const Path = require('path')
            return require(Path.join(process.cwd(), 'config', 'servers.json'))
        } catch(e) {
            return {}
        }
    }

    setupNetworkDiscovery() {
        if(this.networkDiscovery)
            return true

        var discoveryIdentifier = process.options.discovery || process.env.discovery

        if(!discoveryIdentifier) {
            const config = this.getConfig('servers')
            discoveryIdentifier = config['network-discovery']
        }

        const NetworkDiscovery = plugins.require('network-tasks/NetworkDiscovery')
        this.networkDiscovery = NetworkDiscovery.Create(discoveryIdentifier)
        return true
    }
}

module.exports = MasterServer


text:
<?php

namespace Phlexible\Component\MediaTemplate\Model;

/**
 * Audio template.
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class AudioTemplate extends AbstractTemplate
{
    const TYPE_AUDIO = 'audio';

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->setType(self::TYPE_AUDIO);
    }

    /**
     * {@inheritdoc}
     */
    public function getManaged()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultParameters()
    {
        return array(
            'audio_bitrate' => '',
            'audio_samplerate' => '',
            'audio_samplebits' => '',
            'audio_channels' => '',
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getAllowedParameters()
    {
        return array(
            'audio_format',
            'audio_bitrate',
            'audio_samplerate',
            'audio_samplebits',
            'audio_channels',
        );
    }
}


text:
package com.graphhopper.jsprit.core.problem.misc;

import com.graphhopper.jsprit.core.problem.driver.Driver;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TourActivity;
import com.graphhopper.jsprit.core.problem.vehicle.Vehicle;

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

/**
 * Provides context information about a particular job insertion.
 */
public class JobInsertionContext {

    private VehicleRoute route;

    private Job job;

    private Vehicle newVehicle;

    private Driver newDriver;

    private double newDepTime;

    private List<TourActivity> associatedActivities = new ArrayList<TourActivity>();

    private ActivityContext activityContext;

    private ActivityContext relatedActivityContext;

    /**
     * Returns the existing route where the .getJob() needs to be inserted in.
     *
     * @return the route
     */
    public VehicleRoute getRoute() {
        return route;
    }

    /**
     * Returns the job that needs to be inserted.
     *
     * @return the job
     */
    public Job getJob() {
        return job;
    }

    /**
     * Returns the vehicle that should operate the new route, i.e. route this.getRoute() + new job this.getJob().
     *
     * @return the newVehicle
     */
    public Vehicle getNewVehicle() {
        return newVehicle;
    }

    /**
     * Returns the driver that should operate the new route, i.e. route this.getRoute() + new job this.getJob().
     *

     *
Currently the driver is just a mock, it has no functions

     *
     * @return the newDriver
     */
    public Driver getNewDriver() {
        return newDriver;
    }

    /**
     * Returns the new departure time at the new vehicle's start location.
     *
     * @return the newDepTime
     */
    public double getNewDepTime() {
        return newDepTime;
    }

    /**
     * Constructs the context.
     *
     * @param route      the existing route where the job needs to be inserted in
     * @param job        the job to be inserted
     * @param newVehicle the new vehicle that should operate the new route
     * @param newDriver  the new driver that should operate the new route
     * @param newDepTime the new departure time at the new vehicle's start location
     */
    public JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime) {
        super();
        this.route = route;
        this.job = job;
        this.newVehicle = newVehicle;
        this.newDriver = newDriver;
        this.newDepTime = newDepTime;
    }

    public List<TourActivity> getAssociatedActivities() {
        return associatedActivities;
    }

    /**
     * Sets pickup context.
     *
     * @param relatedActivityContext pickup context
     */
    public void setRelatedActivityContext(ActivityContext relatedActivityContext) {
        this.relatedActivityContext = relatedActivityContext;
    }

    /**
     * Returns pickup context. If no context available, returns null.
     *
     * @return pickup context
     */
    public ActivityContext getRelatedActivityContext() {
        return this.relatedActivityContext;
    }

    public void setActivityContext(ActivityContext activityContext){
        this.activityContext = activityContext;
    }

    public ActivityContext getActivityContext(){
        return this.activityContext;
    }
}


text:
//Copyright 2014 Esri

//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at

//       http://www.apache.org/licenses/LICENSE-2.0

//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Internal.Mapping;
using ArcGIS.Desktop.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProSDKSamples.Geocode
{
    /// <summary>
    /// Construct a URI for the ArcGIS Online geocode service
    /// </summary>
    public class GeocodeURI
    {
        //http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?text=380+New+York+Street%2C+Redlands%2C+CA+92373&outFields=match_addr,addr_type,region,postal,country&outSR=102100&maxLocations=5&f=pjson

        private static string _baseURL = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/";
        private static string _verb = "find";
        private static string _format = "pjson";//change to "pjson" to "pretty-print"
        private StringBuilder _url = new StringBuilder();

        /// <summary>
        /// Default constructor. Provide the search text for geocoding and a flag indicating whether or not
        /// to escape the search text. The default is True (i.e. escape the text)
        /// </summary>
        /// <param name="text">The text to search for</param>
        /// <param name="maxResults">The number of results to search for</param>
        /// <param name="escape">True to escape the text, False to include it un-escaped</param>
        public GeocodeURI(string text, int maxResults, bool escape = true)
        {
            //build the URL
            _url.Append(_baseURL);
            _url.Append(_verb);
            string queryStringFormat = "text={0}&outFields={1}&outSR={2}&maxLocations={3}&f={4}";

            MapViewInternal activeView = ProSDKSampleModule.ActiveMapViewInternal;

            int wkid = activeView.SpatialReference.WKID;
            wkid = 4326;
            //fill in the parameters
            string query = string.Format(queryStringFormat,
                                           escape ? System.Web.HttpUtility.UrlPathEncode(text) : text,
                                           CandidateAttributes.outFields,
                                           wkid,
                                           maxResults,
                                           _format);
            _url.Append("?");
            _url.Append(query);
        }
        /// <summary>
        /// The Uri containing all the relevant parameters and search text
        /// </summary>
        public Uri Uri
        {
            get
            {
                return new Uri(_url.ToString(), UriKind.Absolute);
            }
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;

namespace RaceTime.AssettoCorsa.WindowsService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.activiti.idm.engine.impl.persistence.entity;

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

import org.activiti.idm.api.Token;
import org.activiti.idm.api.TokenQuery;
import org.activiti.idm.engine.IdmEngineConfiguration;
import org.activiti.idm.engine.impl.Page;
import org.activiti.idm.engine.impl.TokenQueryImpl;
import org.activiti.idm.engine.impl.persistence.entity.data.DataManager;
import org.activiti.idm.engine.impl.persistence.entity.data.TokenDataManager;

/**
 * @author Tijs Rademakers
 */
public class TokenEntityManagerImpl extends AbstractEntityManager<TokenEntity> implements TokenEntityManager {

  protected TokenDataManager tokenDataManager;

  public TokenEntityManagerImpl(IdmEngineConfiguration idmEngineConfiguration, TokenDataManager tokenDataManager) {
    super(idmEngineConfiguration);
    this.tokenDataManager = tokenDataManager;
  }

  @Override
  protected DataManager<TokenEntity> getDataManager() {
    return tokenDataManager;
  }

  public Token createNewToken(String tokenId) {
    TokenEntity tokenEntity = create();
    tokenEntity.setId(tokenId);
    tokenEntity.setRevision(0); // needed as tokens can be transient
    return tokenEntity;
  }

  public void updateToken(Token updatedToken) {
    super.update((TokenEntity) updatedToken);
  }

  public boolean isNewToken(Token token) {
    return ((TokenEntity) token).getRevision() == 0;
  }

  public List<Token> findTokenByQueryCriteria(TokenQueryImpl query, Page page) {
    return tokenDataManager.findTokenByQueryCriteria(query, page);
  }

  public long findTokenCountByQueryCriteria(TokenQueryImpl query) {
    return tokenDataManager.findTokenCountByQueryCriteria(query);
  }

  public TokenQuery createNewTokenQuery() {
    return new TokenQueryImpl(getCommandExecutor());
  }

  public List<Token> findTokensByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
    return tokenDataManager.findTokensByNativeQuery(parameterMap, firstResult, maxResults);
  }

  public long findTokenCountByNativeQuery(Map<String, Object> parameterMap) {
    return tokenDataManager.findTokenCountByNativeQuery(parameterMap);
  }
}


text:
define([
	'jquery', 'backbone', 'numeral',
	'tmpl!view/bottombar-item',
	'app/func/modal/graph',
	'bootstrap'
], function($, Backbone, numeral, TmplBottomBar, ModalGraph) {

	var View = Backbone.View.extend({
		template: TmplBottomBar,

		loading: true,

		initialize: function(obj, App) {
			this.App = App;

			this.listenTo(this.model, 'change', this.update);

			this.$el.addClass('pointer').html(this.template(this.model.attributes));

			this.setupBar();
			this.setupModal();

			this.$el.click(function() {
				if(!this.loading) {
					this.modal.open();
				}
			}.bind(this));
		},

		setupBar: function() {
			this.divDetail = this.$('.detail');
			this.barProgressWait = $('
', {title: 'IO Wait', rel: 'tooltip', class: 'progress-bar progress-bar-warning'});
			this.barProgressSys = $('
', {title: 'System', rel: 'tooltip', class: 'progress-bar'});
			this.barProgressUser = $('
', {title: 'User', rel: 'tooltip', class: 'progress-bar progress-bar-info'});

			var div = $('
', {class: 'progress'}).append(this.barProgressWait).append(this.barProgressSys).append(this.barProgressUser);
			this.$('.progressDiv').append(div);

			this.$('[rel=tooltip]').tooltip();
		},

		setupModal: function() {
			this.modal = new ModalGraph($('#cpuModal'), ['IO Wait', 'System', 'User'], {
				colors: Config.Colors.CPU,
				initialize: function() {
					this.$('.progress-bar').tooltip();
				},
				yAxisFormatter: function(val, axis) {
					return val + '%';
				},
				update: function(model) {

					var cpuModel = model.get('cpu')
					  , loadAvgs = model.get('loadAvg')
					  , totalCPU = model.get('totalCPUs')
					  , cssNames = ['1min', '5min', '15min'];

					this.$('.cpuModel').html(cpuModel);

					for(var i = 0; i < cssNames.length; i++) {
						var load = Math.round(loadAvgs[i] * 100)
						  , percent = Math.round(loadAvgs[i] / totalCPU * 100);

						var percentColor = 'progress-bar-info';
						if(percent >= 75 && 90 > percent) {
							percentColor = 'progress-bar-warning';
						} else if(percent >= 90) {
							percentColor = 'progress-bar-danger';
						}

						var progressBar = this.$('dd.' + cssNames[i] + ' .progress-bar');
						progressBar.removeClass('progress-bar-info progress-bar-warning progress-bar-danger').addClass(percentColor);
						progressBar.css({width: percent + '%'});
						progressBar.attr('data-original-title', 'Load: ' + load + '%');
						this.$('dt.' + cssNames[i] + ' span').html(load + '%');
					}
				},
				tooltipLabel: function(data) {
					return data.data + '%
at %time%';
				}
			});
		},

		update: function(model) {
			if(this.loading) {
				this.$('.itemTooltip').attr('title', 'Click for more information').tooltip();
				this.loading = false;
			}

			var total = this.model.get('totalCPUs')
			  , sys = this.model.get('sys')
			  , user = this.model.get('user')
			  , wait = this.model.get('nice');

			var totalPercent = Math.ceil((user + sys + wait));
			this.barProgressUser.css({width: Math.floor(user / total) + '%'}).attr('data-original-title', 'User: ' + user + '%');
			this.barProgressSys.css({width: Math.round(sys / total) + '%'}).attr('data-original-title', 'System: ' + sys + '%');
			this.barProgressWait.css({width: Math.floor(wait / total) + '%'}).attr('data-original-title', 'IO Wait: ' + wait + '%');
			this.divDetail.html(Math.round(totalPercent) + '%');

			this.modal.update(model);
			this.modal.updateHistory(wait, sys, user);
		},

		render: function() {
			return this.$el;
		}
	});

	return View;
});


text:
/*!
 * \file
 * \brief Cross-thread function call dispatcher.
 *//*--------------------------------------------------------------------*/

#include "xeCallQueue.hpp"
#include "deInt32.h"
#include "deMemory.h"

using std::vector;

static inline int getNextQueueSize (int curSize, int minNewSize)
{
	return de::max(curSize*2, 1<<deLog2Ceil32(minNewSize));
}

namespace xe
{

// CallQueue

CallQueue::CallQueue (void)
	: m_canceled	(false)
	, m_callSem		(0)
	, m_callQueue	(64)
{
}

CallQueue::~CallQueue (void)
{
	// Destroy all calls.
	for (vector<Call*>::iterator i = m_calls.begin(); i != m_calls.end(); i++)
		delete *i;
}

void CallQueue::cancel (void)
{
	m_canceled = true;
	m_callSem.increment();
}

void CallQueue::callNext (void)
{
	Call* call = DE_NULL;

	// Wait for a call.
	m_callSem.decrement();

	if (m_canceled)
		return;

	// Acquire call from buffer.
	{
		de::ScopedLock lock(m_lock);
		call = m_callQueue.popBack();
	}

	try
	{
		// \note Enqueue lock is not held during call so it is possible to enqueue more work from dispatched call.
		CallReader reader(call);

		call->getFunction()(reader);

		// check callee consumed all
		DE_ASSERT(reader.isDataConsumed());
		call->clear();
	}
	catch (const std::exception&)
	{
		try
		{
			// Try to push call into free calls list.
			de::ScopedLock lock(m_lock);
			m_freeCalls.push_back(call);
		}
		catch (const std::exception&)
		{
			// We can't do anything but ignore this.
		}

		throw;
	}

	// Push back to free calls list.
	{
		de::ScopedLock lock(m_lock);
		m_freeCalls.push_back(call);
	}
}

Call* CallQueue::getEmptyCall (void)
{
	de::ScopedLock	lock	(m_lock);
	Call*			call	= DE_NULL;

	// Try to get from free calls list.
	if (!m_freeCalls.empty())
	{
		call = m_freeCalls.back();
		m_freeCalls.pop_back();
	}

	// If no free calls were available, create a new.
	if (!call)
	{
		m_calls.reserve(m_calls.size()+1);
		call = new Call();
		m_calls.push_back(call);
	}

	return call;
}

void CallQueue::enqueue (Call* call)
{
	de::ScopedLock lock(m_lock);

	if (m_callQueue.getNumFree() == 0)
	{
		// Call queue must be grown.
		m_callQueue.resize(getNextQueueSize(m_callQueue.getSize(), m_callQueue.getSize()+1));
	}

	m_callQueue.pushFront(call);
	m_callSem.increment();
}

void CallQueue::freeCall (Call* call)
{
	de::ScopedLock lock(m_lock);
	m_freeCalls.push_back(call);
}

// Call

Call::Call (void)
	: m_func(DE_NULL)
{
}

Call::~Call (void)
{
}

void Call::clear (void)
{
	m_func = DE_NULL;
	m_data.clear();
}

// CallReader

CallReader::CallReader (Call* call)
	: m_call	(call)
	, m_curPos	(0)
{
}

void CallReader::read (deUint8* bytes, size_t numBytes)
{
	DE_ASSERT(m_curPos + numBytes <= m_call->getDataSize());
	deMemcpy(bytes, m_call->getData()+m_curPos, numBytes);
	m_curPos += numBytes;
}

const deUint8* CallReader::getDataBlock (size_t numBytes)
{
	DE_ASSERT(m_curPos + numBytes <= m_call->getDataSize());

	const deUint8* ptr = m_call->getData()+m_curPos;
	m_curPos += numBytes;

	return ptr;
}

bool CallReader::isDataConsumed (void) const
{
	return m_curPos == m_call->getDataSize();
}

CallReader& operator>> (CallReader& reader, std::string& value)
{
	value.clear();
	for (;;)
	{
		char c;
		reader.read((deUint8*)&c, sizeof(char));
		if (c != 0)
			value.push_back(c);
		else
			break;
	}

	return reader;
}

// CallWriter

CallWriter::CallWriter (CallQueue* queue, Call::Function function)
	: m_queue		(queue)
	, m_call		(queue->getEmptyCall())
	, m_enqueued	(false)
{
	m_call->setFunction(function);
}

CallWriter::~CallWriter (void)
{
	if (!m_enqueued)
		m_queue->freeCall(m_call);
}

void CallWriter::write (const deUint8* bytes, size_t numBytes)
{
	DE_ASSERT(!m_enqueued);
	size_t curPos = m_call->getDataSize();
	m_call->setDataSize(curPos+numBytes);
	deMemcpy(m_call->getData()+curPos, bytes, numBytes);
}

void CallWriter::enqueue (void)
{
	DE_ASSERT(!m_enqueued);
	m_queue->enqueue(m_call);
	m_enqueued = true;
}

CallWriter& operator<< (CallWriter& writer, const char* str)
{
	int pos = 0;
	for (;;)
	{
		writer.write((const deUint8*)str + pos, sizeof(char));
		if (str[pos] == 0)
			break;
		pos += 1;
	}

	return writer;
}

} // xe


text:
Modifying a widget usually requires direct access to the object. However, assigning all mutable widgets to variables can quickly clutter your UI code. For this reason, the Tabris.js API offers methods to find widgets by certain attributes, and even to manipulate multiple widgets at once. Widgets can be selected by their *type*, their *ID*, or their *class* attributes, using a format established by CSS.

## Selecting widgets by type

The simplest method to select widgets is to refer to their type. For example, the following statement would uncheck all checkboxes on a page:

```js
page.find('CheckBox').set('selection', false);
```

## Selecting widgets by ID

The `id` of a widget is a property like any other. It is initially undefined, so you have to assign an ID yourself to refer to the widget. Usually you would do this when you create the widget:

```js
new tabris.Button({id: 'submit'});
```

To select a widget by its ID, you can use the selector expression `'#id'` where `id` is the ID of the widget:

```js
page.find('#submit').set('enabled', false);
```

IDs should be unique. Although this is not enforced by the framework, it's a good practice not to use the same ID twice within a component to avoid confusion.

## Selecting widgets by class attribute

The `class` property is a string containing a whitespace separated list of "classes". A class is an arbitrary name for a state or category the widget should be identifiable by. It may only contain alphanumeric characters, `'_'` and `'-'`.

```js
new tabris.TextView({class: 'label important'});
```

Classes may be mixed, re-used and changed on any widget at any time. Using the `classList` property is a handy way to do so:

```js
textView.classList.push('important');
```

To select a widget by a class attribute, use the selector expression `'.class'` where `class` is the class name:

```js
page.find('.important').set('textColor', 'red');
```

## Selector Expressions

The following types of selector expressions are supported:

- `'*'` matches all widgets.
- `'Type'` matches all widgets of the given type, e.g. `'Button'` matches all Button widgets.
- `'.class'` matches all widgets that have the given class in their class list, e.g. `'.foo'` matches a widget with `class` set to `'foo'`, but also `'foo bar`'.
- `'#id'` matches all widgets with the given ID, e.g. `'#foo'` matches all widgets with the ID `'foo'`.

## Selector Functions

All methods that accept a selector expression can also be called with a predicate function to test each widget of a collection. This function will be called for each widget and returns `true` to include the widget, and `false` to skip it. For example, the following snippet would select all visible widgets on a page:

```js
var visibleChildren = page.children(widget => widget.visible);
```

## Working with Selectors

The following methods on Widget accept a selector expression:

- `widget.find(selector)` will select all descendants that match the selector.
- `widget.children(selector)` will select all direct children that match the selector, but not their children.
- `widget.siblings(selector)` will select all siblings of the widget that match the selector.

These methods return a [WidgetCollection](api/WidgetCollection.md). You can extract widgets from the collection using the methods `first()` and `last()` or using array index notation:

```js
var submitButton = page.find('#submit').first(); // or
var submitButton = page.find('#submit')[0];
```

You can also set properties on the included widgets without extracting them:

```js
page.find('.input').set('enabled', false);
```

## The apply method

An efficient way to configure multiple widgets in a component is using the `apply()` method on the parent.

### How it works

- `apply({<selector: properties>*})`

The apply method uses selectors to apply different sets of properties to different widgets in one call. For example, to apply a background color to all widgets within a page you could call:

```js
page.apply({'*': {background: 'green'}});
```

You can also set different properties on different widgets:

```js
page.apply({
  '#okbutton': {text: 'OK!', background: 'yellow'},
  '#cancelbutton': {text: 'Cancel!', textColor: 'red'}
});
```

The order in which these properties are applied depends on the type of selectors being used. The order is:

- `'*'` > `'Type'` > `'.class'` > `'#id'`

For example, the following call would make all widgets within the page blue, except for the buttons, which would be green, except for `'#mybutton'`, which would be red:

```js
page.apply({
  '#mybutton': {background: 'red'},
  'Button': {background: 'green'},
  '*': {background: 'blue'}
});
```

>  The on-screen order of the properties in the object literal is meaningless. According to the EcmaScript standard the members of a JavaScript object do not have a defined order.

### How to use it

While we used object literals in the examples above, the apply method can be very effectively used with [modules](module), allowing most or all property values (except IDs) to be extracted from your code.

Imagine, for example, that you want to apply different texts to your widgets depending on your locale. You could do it like this:

```js
var lang = tabris.device.get('language');
try {
  page.apply(module.require('./texts-' + lang));
} catch() {
  // fallback if the desired language file does not exist:
  page.apply(module.require('./texts-en'));
}
```

Since JSON files can be used as modules, your language file (e.g. `texts-en.json`) could simply look like this:

```json
{
  '#okbutton': {'text': 'OK'},
  '#cancelbutton': {'text': 'Cancel'}
}
```

An alternative pattern would be to always use the same module...

```js
  page.apply(module.require('./texts'));
}
```

But use scripting within the module to calculate the actual values:

```js
var texts = {
  en: {
    '#okbutton': {text: 'OK!'}
    '#cancelbutton': {text: 'Cancel!'}
  },
  //...
};
module.exports = texts[tabris.device.get('language')] || texts.en;
```

The same pattern can be applied for platform-specific colors, font-sizes based on screen width, or layout data depending on device orientation:

```js
page.on('resize', function() {
  var bounds = page.get('bounds');
  page.apply(require('./layout-' + (bounds.width > bounds.height) ? 'landscape' : 'portrait'));
});
```

>  It is better to use the aspect ratio of the page as a basis for selecting a layout than the device orientation. This is because when the device is re-oriented, the page is first re-sized, and then rotated in an animation. Also, in future Tabris.js versions a page may not always have the same aspect ratio as the screen.


text:
The tools,scripts, and information in this section help reverse engineer
and analyze Android-related binaries.

## jni_translate
Android apps can include compiled native code (usually written in C/C++) within a native library. This code uses the Java Native Interface to interact with the Java (or Kotlin) code within the Android app. Learn more at https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html). Each JNI function within the Android native lib will take the JNIEnv pointer as its first argument. The JNIEnv struct is a table of function pointers that provide useful Java functions to the native code.

The *jni_translate.py* IDA Python script will comment within the IDA disassembly what function from the JNIEnv struct is being called to help ease analysis. This is necessary because most calls to functions within the JNIEnv are called as indirect offset accesses to JNIEnv*.

For example, the following disassembly is a call to GetStaticMethodId which is at offset 0x1C4 in the JNIEnv struct.
```
LDR R1, [R0]		#R0 is JNIEnv*
MOVS R0, #0x1C4
LDR R4, [R0, R1]	# R4 = [JNIEnv + 0x1C4] = Ptr to GetStaticMethodId()
BLX R4				# Call GetStaticMethodId
```

This script will add the function name as a comment in the IDA Disassembly.

## WeddingCake
The WeddingCake anti-analysis library is an Android native code wrapper
that includes many techniques to frustrate analysis. More information
about this packer and how to run the tools included here is available
from Maddie Stone's BlackHat USA 2018 talk, "Unpacking the Packed Unpacker".

*WeddingCake_decrypt.py*: This IDAPython script will run on ARM32 ELFs
that have been packed with the WeddingCake Android anti-analysis library.
The script will decrypt all of the encrypted strings in the IDA database
and overwrite the database with the decrypted contents. To run the script,
you must ensure that the JNI_OnLoad function is defined and exported in
the IDA database.

*WeddingCake_sysprops.txt*: All of the system properties that WeddingCake
checks for and the values that will cause the application to exit.

Copyright 2018 Google LLC.
Author: maddiestone@google.com (Maddie Stone)


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>TripleO: Using the fake_pxe driver with Ironic · Leif Madsen</title>

  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole-overrides.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-overrides.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-x.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/highlight/monokai.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://blog.leifmadsen.com/touch-icon-144-precomposed.png">
  <link href="http://blog.leifmadsen.com/favicon.png" rel="icon">

  <meta name="description" content="Leif Madsen's Blog">
  <meta name="keywords" content="blog,leif,madsen,canada,containers,asterisk,development,devops,infrastructure,implementation engineer">

Leif Madsen

I’m not clever enough for a tagline.

Blog

Posts

Copyright © 2016 License

       Powered by Hugo and Hyde-X

TripleO: Using the fake_pxe driver with Ironic

    Nov 11, 2016 · 7 minute read · Comments

    TripleOnfvpe

I’ve been working on testing things with TripleO and normally I use TripleO
Quickstart to spin things up
in a virtual environment.

Often when doing NFV work though, you need things that can’t be used in a
virtual environment (such as DPDK, SR-IOV, etc) so you need some baremetal
nodes.

In my home lab environment though, I don’t have the luxury of IPMI, so I need
to make use of the fake_pxe driver in Ironic, which allows for standard PXE
control, but requires you to deal with powering on and off the machines
manually. Let me show you how I make use of that.

tl;dr

power off machines

start introspection

power up machines

wait for openstack baremetal node list to show available

power off machines

start openstack overcloud deploy [...]

watch output of openstack baremetal node list

when you see wait for call-back then power on the machines

machines will boot via PXE, pull image from undercloud, write to disk

machine will power down automatically via Linux shutdown

watch openstack baremetal node list for active

power machines on

machine will report back to undercloud, and Puppet will execute to configure
system

Why use the fake_pxe driver?

The fake_pxe driver “provides stubs instead of real power and management
operations”1
so that you can utilize hardware that supports PXE, but doesn’t provide the
necessary functionality to control power management functionality remotely.

This allows you to use some standard commodity hardware that doesn’t have the
advanced power management systems of more expensive hardware.

Enabling the driver in Ironic

By default the fake_pxe driver isn’t enabled on the undercloud. You can
enable it in the /etc/ironic/ironic.conf by modifying the following line:

enabled_drivers = pxe_ipmitool,pxe_ssh,pxe_drac,pxe_ilo,fake_pxe

Add fake_pxe to the end of the enabled_drivers configuration option. Then
we’ll need to restart the Ironic services.

$ sudo systemctl list-unit-files | grep ironic
openstack-ironic-api.service                  enabled
openstack-ironic-conductor.service            enabled
openstack-ironic-inspector-dnsmasq.service    enabled
openstack-ironic-inspector.service            enabled

I believe the only service you need to restart to make the driver active is
openstack-ironic-conductor.service but you can easily restart all the
services with the following commands:

ironic_services=$(sudo systemctl list-unit-files | grep ironic | awk '/enabled/ {print $1}')
sudo systemctl restart $ironic_services

Validate driver is active

Now that we’ve modified the ironic.conf file and restarted the Ironic
services, let’s double check the driver is active:

$ openstack baremetal driver list
Jun 2017. Please use osc_lib.utils
+---------------------+-----------------------+
| Supported driver(s) | Active host(s)        |
+---------------------+-----------------------+
| fake_pxe            | localhost.localdomain |
| pxe_drac            | localhost.localdomain |
| pxe_ilo             | localhost.localdomain |
| pxe_ipmitool        | localhost.localdomain |
| pxe_ssh             | localhost.localdomain |
+---------------------+-----------------------+

Workflow for TripleO deploy

Awesome, our driver is enabled. Now we can make use of it for our nodes. Using
the driver and understanding when to turn machines on and off wasn’t super
obvious, so lets review the workflow.

Import nodes for introspection

First, we need to make sure our baremetal nodes are configured on the
undercloud to make use of the fake_pxe driver. In our instackenv.json we
can set that up:

{
    "nodes": [
        {
            "pm_type":"fake_pxe",
            "mac":[
                "aa:bb:cc:dd:ee:ff"
            ],
            "cpu":"2",
            "memory":"4096",
            "disk":"40",
            "arch":"x86_64",
            "pm_user":"admin",
            "pm_password":"password",
            "pm_addr":"10.0.0.8",
            "capabilities": "profile:control,boot_option:local"
        }
    ]
}

We’ve configured the pm_type to be fake_pxe, filled in our MAC address, and
setup some initial data about the node. I generally enable the
inspection_extras = true option in the undercloud.conf file so that the
hardware is evaluated during introspection and the database setup
appropriately. You can modify these values to match the hardware if you don’t
want to execute that step (or it isn’t detecting the hardware accurately).

The other pm_??? values are just dummy data, and don’t need to be populated
with anything meaningful (since we don’t have any IPMI interface to connect to,
they are unnecessary). In previous versions of TripleO importing the nodes
would fail without the pm_??? values which is why they are there at all.

Perform introspection

With our nodes imported, can start the introspection process. Remember that we
want to start with the nodes turned off. Of course make sure you have the BIOS
setup to allow booting from PXE as the first boot device.

Start the introspection process:

$ openstack baremetal import --initial-state=enroll instackenv.json

$ openstack baremetal introspection bulk start

You can monitor status of the machines using watch:

$ watch -n30 "openstack baremetal node list"

When the introspection process starts, you’ll see the Power State switch to
power on and the Provisioning State field work its way through the
introspection process.

At this point, power on the machines.

+--------------------------------------+------+---------------+-------------+--------------------+-------------+
| UUID                                 | Name | Instance UUID | Power State | Provisioning State | Maintenance |
+--------------------------------------+------+---------------+-------------+--------------------+-------------+
| 25167102-fc8d-4907-b16c-dbdb09ea9d10 | None | None          | power on    | manageable         | False       |
| 97c229c3-07bc-4f5e-a451-6ae3341f1f5a | None | None          | power on    | manageable         | False       |
| a5d8a413-4458-480f-8a94-5f22902cea6c | None | None          | power on    | manageable         | False       |
+--------------------------------------+------+---------------+-------------+--------------------+-------------+

When introspection completes, you’ll see the Provisioning State switch to
available and the Power State should show power off. You’ll need to
manually power down the machines at this point.

+--------------------------------------+------+---------------+-------------+--------------------+-------------+
| UUID                                 | Name | Instance UUID | Power State | Provisioning State | Maintenance |
+--------------------------------------+------+---------------+-------------+--------------------+-------------+
| 25167102-fc8d-4907-b16c-dbdb09ea9d10 | None | None          | power off   | available          | False       |
| 97c229c3-07bc-4f5e-a451-6ae3341f1f5a | None | None          | power off   | available          | False       |
| a5d8a413-4458-480f-8a94-5f22902cea6c | None | None          | power off   | available          | False       |
+--------------------------------------+------+---------------+-------------+--------------------+-------------+

Start overcloud deployment

With introspection completed and our machines powered off, we can start the
overcloud deployment. I won’t get into how to deploy your cloud here (you might
want to refresh your memory with TripleO: Consuming Composable
Roles) but here is the general process:

power off machines

start openstack overcloud deploy [...]

watch output of openstack baremetal node list

when you see wait for call-back then power on the machines

machines will boot via PXE, pull image from undercloud, write to disk

machine will power down automatically via Linux shutdown

watch openstack baremetal node list for active

power machines on

machine will report back to undercloud, and Puppet will execute to configure
system

Once you run the openstack overcloud deploy [...] command, you’ll watch the
output of your openstack overcloud baremetal list command, waiting for Power
State to switch to power on. At this point you’ll power up the nodes.

Here is what we’ll see while the overcloud starts to get provisioned:

+--------------------------------------+------+---------------+-------------+--------------------+-------------+
| UUID                                 | Name | Instance UUID | Power State | Provisioning State | Maintenance |
+--------------------------------------+------+---------------+-------------+--------------------+-------------+
| 25167102-fc8d-4907-b16c-dbdb09ea9d10 | None | None          | power off   | available          | False       |
| 97c229c3-07bc-4f5e-a451-6ae3341f1f5a | None | None          | power off   | available          | False       |
| a5d8a413-4458-480f-8a94-5f22902cea6c | None | None          | power off   | available          | False       |
+--------------------------------------+------+---------------+-------------+--------------------+-------------+

Once you see the Provisioning State switch to wait call-back then you can
power the nodes back up so they can pull the disk image from the undercloud and
write it to the local disk drive.

+--------------------------------------+------+--------------------------------------+-------------+--------------------+-------------+
| UUID                                 | Name | Instance UUID                        | Power State | Provisioning State | Maintenance |
+--------------------------------------+------+--------------------------------------+-------------+--------------------+-------------+
| 25167102-fc8d-4907-b16c-dbdb09ea9d10 | None | c57f80dc-2e27-465a-b4ba-3e811313627b | power on    | wait call-back     | False       |
| 97c229c3-07bc-4f5e-a451-6ae3341f1f5a | None | ef1d5f8e-79fd-423c-bdd2-39b850dadac8 | power on    | wait call-back     | False       |
| a5d8a413-4458-480f-8a94-5f22902cea6c | None | 784f79b0-37de-461a-957a-8cac55fea72c | power on    | wait call-back     | False       |
+--------------------------------------+------+--------------------------------------+-------------+--------------------+-------------+

The machines will then call back to the undercloud and you should see the
Provisioning State change to deploying.

After about 5-10 minutes (depending on image size, network speed, disk speed,
etc) your machines should power themselves off. The Power State value won’t
change to power off though so you’ll need to physically look at the machines
to validate the nodes have powered off.

We need to continue monitoring the nodes for the Provisioning State to switch
to active, meaning the undercloud is ready for you to power the machines back
up. After the state changes to active power the machines back on manually.

At this point, you’re done playing power jockey, and can simply sit back and
watch your overcloud COMPLETE or FAIL.

Conclusion

The fake_pxe driver is useful when you need to utilize commodity hardware
that doesn’t have remote power management, when you’re using hardware that
doesn’t have a driver available for power management, or when your IPMI network
isn’t available to the undercloud directly. Knowing when to power the nodes up
and down is really the only key to being successful with hardware that doesn’t
have remote power management.

Please enable JavaScript to view the comments powered by Disqus.