text
stringlengths
10
2.61M
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "centos/7" (0..2).each do |i| pri = (i == 0) config.vm.define "minio-#{i}", primary: pri do |minio| minio.vm.hostname = "minio-#{i}" minio.vm.network "private_network", ip: "192.168.50.#{100 + i}", virtualbox__intnet: true minio.vm.network "forwarded_port", guest: 9000, host: 9000 + i, host_ip: "127.0.0.1" end end config.vm.provision "shell", inline: <<-SHELL if [ ! -f /usr/local/bin/minio ]; then curl https://dl.minio.io/server/minio/release/linux-amd64/minio -o /usr/local/bin/minio chmod +x /usr/local/bin/minio fi if [ ! -f /usr/local/bin/mc ]; then curl https://dl.minio.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc chmod +x /usr/local/bin/mc fi if [ ! -d /var/lib/minio ]; then mkdir -p /var/lib/minio chown -R vagrant:vagrant /var/lib/minio fi SHELL end # ===== REQUIREMENTS ===== # min: 2 disks/node # ======================== # export MINIO_ACCESS_KEY=admin # export MINIO_SECRET_KEY=Teko@123? # minio server /var/lib/minio # minio server http://192.168.50.10{0...2}/var/lib/minio/disk{1...4}
fastlane_version '2.105.2' # before_all do # ensure_git_branch # ensure_git_status_clean # git_pull # end # platform :ios do # # iOS Lanes # desc 'Fetch certificates and provisioning profiles' # lane :certificates do # match(app_identifier: 'com.rn.mobile', type: 'development', readonly: true) # end # desc 'generate iOS appiconset from master image' # lane :icon do # appicon( # appicon_devices: [:iphone, :ios_marketing], # appicon_path: "ios/rn/Images.xcassets" # ) # end # end platform :android do desc 'generate Android launch icon from master image' lane :icon do android_appicon( appicon_image_file: 'fastlane/metadata/app_icon_android.png', appicon_icon_types: [:launcher], appicon_path: 'android/app/src/main/res/mipmap' ) android_appicon( appicon_image_file: 'fastlane/metadata/app_icon_android.png', appicon_icon_types: [:notification], appicon_path: 'android/app/src/main/res/mipmap', appicon_filename: 'ic_notification' ) end lane :build_and_release_to_play_store do |options| # Bundle the app gradle( task: 'bundle', build_type: 'Release', project_dir: "android/" ) # Upload to Play Store's Internal Testing upload_to_play_store( package_name: 'com.rn', track: "internal", json_key: "./android/app/google-private-key.json", aab: "./android/app/build/outputs/bundle/release/app.aab" ) end end
# Die Class 1: Numeric # I worked on this challenge by myself # I spent 3 hours on this challenge. # 0. Pseudocode # Input: an integer - number of sides of a die # Output: an integer - result of rolling the [input-number]-sided die # Steps: # - create instance variable for # of sides # - generate a random integer between 1 and [number-of-sides] # - raise an error if sides argument is less than 1 # 1. Initial Solution class Die def initialize(sides) # code goes here @sides = sides unless sides > 1 raise ArgumentError.new("Choose an integer larger than 1") end end def sides @sides end def roll # code goes here prng = Random.new prng.rand(1..@sides) end end # 3. Refactored Solution class Die def initialize(sides) @sides = sides unless sides > 1 raise ArgumentError.new('Choose an integer larger than 1') end end def sides @sides end def roll prng = Random.new prng.rand(1..@sides) end end # 4. Reflection =begin - What is an ArgumentError and why would you use one? An ArgumentError is raised when a method is passed an argument that it doesn't understand. For example, if a method expects 1 argument and it is passed 2 arguments, an ArgumentError should be raised. You used ArgumentErrors when you are defining a method within a class that you've created and you want that method to return an error message when it receives the wrong number or types of arguments. - What new Ruby methods did you implement? What challenges and successes did you have in implementing them? I implemented the rand(max) method for the first time. It turned out to be a pretty simple and easy-to-implement way of generating a random integer within a range. - What is a Ruby class? A Ruby class is an object. - Why would you use a Ruby class? Ruby classes are useful when you want to create instance variables or when you want to create group behaviors that allow you to create objects that behave in a certain way. - What is the difference between a local variable and an instane variable? The difference is scope. A local variable's scope is limited to the method in which it is defined. You can't call a local variable outside of its method. Instance variables are limited in scope to class. Any method within a class can access that class's instance variables. - Where can an instance variable be used? An instance variable can be used in any method within its class. =end
class AddTagRefToContacts < ActiveRecord::Migration def change add_reference :contacts, :tag, index: true add_foreign_key :contacts, :tags end end
require 'test_helper' class Piece3sControllerTest < ActionController::TestCase setup do @piece3 = piece3s(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:piece3s) end test "should get new" do get :new assert_response :success end test "should create piece3" do assert_difference('Piece3.count') do post :create, piece3: { name: @piece3.name, user_id: @piece3.user_id } end assert_redirected_to piece3_path(assigns(:piece3)) end test "should show piece3" do get :show, id: @piece3 assert_response :success end test "should get edit" do get :edit, id: @piece3 assert_response :success end test "should update piece3" do patch :update, id: @piece3, piece3: { name: @piece3.name, user_id: @piece3.user_id } assert_redirected_to piece3_path(assigns(:piece3)) end test "should destroy piece3" do assert_difference('Piece3.count', -1) do delete :destroy, id: @piece3 end assert_redirected_to piece3s_path end end
# frozen_string_literal: true module FindIt # Logic shared across the indexing code module Data def online_resource?(record) format_field = record['008']&.value format_field && (format_field[23] == 'o') end end end
module SimonSays <<<<<<< HEAD def echo(word) @word = word return "#{@word}" end def shout(word) @word = word.upcase return "#{@word}" end def repeat(word, times=2) @word = "#{word}" @final_word = @word for i in 1...times @final_word = @final_word + " " + "#{word}" end return @final_word end def start_of_word(word, end_pnt) @word = word return @word[0...end_pnt] end def first_word(word) @word = word.scan(/\w+/) return @word[0] end end ======= def echo(st) st end def shout(st) st.upcase end def first_word(st) st.split.first end def start_of_word(st,i) st[0...i] end def repeat(st, t=2) return "Go Away!" if t==0 ([st]*t).join(' ') end end >>>>>>> 529b28228eac9e841374d40584eb6341ab03b2dd
module Reservations module Representers class Data attr_reader :user, :reservation def initialize reservation, user @reservation = reservation @user = user end def call { type: 'reservation', id: reservation.id, attributes: {}, relationships: { user: Users::Representers::Relationship.new( user ).call, movie: Movies::Representers::Relationship.new( reservation.movie ).call, screening: Screenings::Representers::Relationship.new( reservation.screening ).call, cinema: ::Cinemas::Representers::Relationship.new( cinema: reservation.cinema ).call, seats: Seats::Representers::MultipleRelationships.new( reservation.seats ).call } } end end end end
class User attr_reader :icon attr_accessor :wins, :losses @@counter = 0 def initialize @icon = "X" if @@counter == 0 @icon = "O" if @@counter > 0 @wins = 0 @losses = 0 @@counter += 1 end def selection i = 0 while i < 1 p "#{self} make a selection..." temp = gets.chomp.upcase if temp.length != 2 p "Error, input must be 2 characters..." elsif (["A","B","C"].include? (temp[0])) == false p "Error, please select either row a, b, or c..." elsif (["1","2","3"].include? (temp[1])) == false p "Error, please select a column as 1, 2, or 3..." else p "input successful..." return temp end end end end class Game < User attr_accessor :player_1, :player_2, :board def initialize() @player_1 = User.new @player_2 = User.new @board = { "row A": ["-","-","-"], "row B": ["-","-","-"], "row C": ["-","-","-"] } end def draw_board @board.each do |key, value| p value end end def reset @player_1.wins = 0 @player_2.wins = 0 @board = { "row A": ["-","-","-"], "row B": ["-","-","-"], "row C": ["-","-","-"] } play_round end def stalemate_check isTrue = 0 @board.each do |k,v| if v.all? {|item| item == "X" || item == "O"} isTrue += 1 end end return true if isTrue == 3 end def player_1_selection i = 0 while i < 1 temp = @player_1.selection if @board[:"row #{temp[0]}"][(temp[1].to_i) - 1] != '-' p "Please select empty space..." else break end end @board[:"row #{temp[0]}"][(temp[1].to_i) - 1] = @player_1.icon end def player_2_selection i = 0 while i < 1 temp = @player_2.selection if @board[:"row #{temp[0]}"][(temp[1].to_i) - 1] != '-' p "Please select empty space..." else break end end @board[:"row #{temp[0]}"][(temp[1].to_i) - 1] = @player_2.icon end def check_win @board.each do |key,value| #checks horizontal wins if value.all? {|item| item == "X" && item != "-"} p "There's a winner!" p "#{key} across and the Player X" @player_1.wins += 1 @player_2.losses += 1 return elsif value.all? {|item| item == "O" && item != "-"} p "There's a winner!" p "#{key} across and the Player O" @player_2.wins += 1 @player_1.losses += 1 return end end i = 0 #checks vertical wins while i < 3 if @board[:"row A"][i] == "-" i += 1 next end if @board[:"row A"][i] == @board[:"row B"][i] && @board[:"row A"][i] == @board[:"row C"][i] p "We have a vertical winner...player #{@board[:"row A"][i]}!" if @board[:"row A"][i] == "X" @player_1.wins += 1 @player_2.losses += 1 else @player_2.wins += 1 @player_1.losses += 1 end return else i += 1 end end if @board[:"row B"][1] != "-" #checks diagonal wins if @board[:"row A"][0] == @board[:"row B"][1] && @board[:"row C"][2] == @board[:"row B"][1] p "We have a diagonal winner...player #{@board[:"row B"][1]}!" if @board[:"row B"][1] == "X" @player_1.wins += 1 @player_2.losses += 1 else @player_2.wins += 1 @player_1.losses += 1 end return elsif @board[:"row A"][2] == @board[:"row B"][1] && @board[:"row C"][0] == @board[:"row B"][1] p "We have a diagonal winner...player #{@board[:"row B"][1]}!" return end end p "There's no winner yet, keep playing..." end def play_round draw_board i = 0 while i < 25 player_1_selection draw_board check_win if @player_1.wins == 1 p "player 1 wins! Play again..." reset elsif @player_2.wins == 1 p "Player 2 wins! Play again..." reset elsif stalemate_check == true p "stalemate, play again..." reset end player_2_selection draw_board check_win if @player_1.wins == 1 p "player 1 wins! Play again..." reset elsif @player_2.wins == 1 p "Player 2 wins! Play again..." reset elsif stalemate_check == true p "stalemate, play again..." reset end end end end #class Game end game_1 = Game.new game_1.play_round
class Post < ActiveRecord::Base belongs_to :charity belongs_to :user validates :title, presence: true, length: { minimum: 3 } validates :summary, length: { maximum: 160 } validates :post_content, presence: true end
module Vanity class NoConfigurationError < StandardError end class NoVanityRoutesTableError < StandardError end end
module Arcane module Generators class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates')) def copy_application_refinery template 'application_refinery.rb', 'app/refineries/application_refinery.rb' end end end end
require 'rails_helper' require_relative '../../app/services/duel_service' require_relative '../../app/models/fighter' RSpec.describe DuelService do let(:fighter1) { Fighter.new(name: 'Rambo', health: 80, attack: 30) } let(:fighter2) { Fighter.new(name: 'Terminator', health: 100, attack: 10) } let(:equipment1) { Equipment.new(name: 'shield', force: 0, protection: 10) } let(:equipment2) { Equipment.new(name: 'knife', force: 5, protection: 0) } let(:equipment3) { Equipment.new(name: 'iron fist', force: 5, protection: 0) } let(:duel_service) { DuelService.new(fighter1, fighter2, [equipment1, equipment2, equipment3]) } describe '#execute' do it 'returns duel with a winner and logs' do duel = duel_service.execute expect(duel.fighter1).to eql(fighter1) expect(duel.fighter2).to eql(fighter2) expect(duel.winner).to eql(fighter1) logs = [ '=============================================================', "#{fighter1.name} with health: 80, attack: 30", '==============================VS=============================', "#{fighter2.name} with health: 100, attack: 10", '=============================================================', 'Equipments: shield, knife, iron fist', '=============================================================', 'Rambo(80) attacks Terminator(70)', 'Terminator(70) attacks Rambo(70)', 'Rambo(70) attacks Terminator(40)', 'Terminator(40) attacks Rambo(60)', 'Rambo(60) attacks Terminator(10)', 'Terminator(10) attacks Rambo(50)', 'Rambo(50) attacks Terminator(0)' ] expect(duel.logs).to eql(logs) end end end
require 'rspec' require 'rr' RSpec.configure do |config| config.mock_with :rr end require "./lib/conferences.rb" require "./lib/session.rb" require "./lib/video.rb" require "fixtures" DataMapper.setup(:default,"in_memory://localhost") DataMapper.finalize describe "Accessing session content: " do include Fixtures before do @sessions = sessions @videos = videos @sessions[0].videos << @videos[0] @sessions[1].videos << @videos[1] @sessions[2].videos << @videos[2] @videos[0].session = @sessions[0] @videos[1].session = @sessions[1] @videos[2].session = @sessions[2] end describe "when viewing the three sections of the VLC, depending on access:" do it "lists all public videos, irrespective of access level" do command = ListVideos.new :public, {} mock(command).all_videos(:public) {[@sessions.first]} results = command.populate results[:sessions].length.should == 1 results[:sessions].first.id.should == 1 end it "adds a newsletter notice if a visitor requests subscriber videos" do command = ListVideos.new :subscriber, {} mock(command).all_videos(:subscriber) {@sessions[0..1]} results = command.populate results[:sessions].length.should == 2 results[:notice].should == :subscriber end it "just lists subscriber videos when requested by a subscriber" do command = ListVideos.new :subscriber, {"SUBSCRIBER"=>"YES"} mock(command).all_videos(:subscriber) {@sessions[0..1]} results = command.populate results[:sessions].length.should == 2 results[:notice].should be nil end it "just lists subscriber videos when requested by a member" do command = ListVideos.new :subscriber, {"MEMBERID"=>"DC"} mock(command).all_videos(:subscriber) {@sessions[0..1]} results = command.populate results[:sessions].length.should == 2 results[:notice].should be nil end it "adds a sign-up notice if a subscriber requests member videos" do command = ListVideos.new :member, {} mock(command).all_videos(:member) {@sessions[0..2]} results = command.populate results[:sessions].length.should == 3 results[:notice].should be :member end it "just lists member videos when requested by a member" do command = ListVideos.new :member, {"MEMBERID"=>"DC"} mock(command).all_videos(:member) {@sessions[0..2]} results = command.populate results[:sessions].length.should == 3 results[:notice].should be nil end end describe "when viewing session details," do it "allows access to public videos if not logged in" do mock(Session).first(:id=>"1") {@sessions[0]} command = ShowSession.new "1", {} results = command.populate results[:session].id.should == 1 results[:player].should == :video_flv results[:notice].should be nil end it "does not allow access to subscriber videos if not logged in" do mock(Session).first(:id=>"2") {@sessions[1]} command = ShowSession.new "2", {} results = command.populate results[:session].id.should be 2 results[:player].should be nil results[:notice].should == :subscriber end it "shows subscriber videos if logged in as subscriber" do mock(Session).first(:id=>"2") {@sessions[1]} command = ShowSession.new "2", {"SUBSCRIBER"=>"YES"} results = command.populate results[:session].id.should == 2 results[:player].should == :video_bit results[:notice].should be nil end it "shows subscriber videos if logged in as member" do mock(Session).first(:id=>"2") {@sessions[1]} command = ShowSession.new "2", {"MEMBERID"=>"DC"} results = command.populate results[:session].id.should == 2 results[:player].should == :video_bit results[:notice].should be nil end it "does not allow access to member videos if logged in as subscriber" do mock(Session).first(:id=>"3") {@sessions[2]} command = ShowSession.new "3", {"SUBSCRIBER"=>"YES"} results = command.populate results[:session].id.should be 3 results[:player].should be nil results[:notice].should == :member end it "shows subscriber videos if logged in as member" do mock(Session).first(:id=>"3") {@sessions[2]} command = ShowSession.new "3", {"MEMBERID"=>"DC"} results = command.populate results[:session].id.should == 3 results[:player].should == :video_bit results[:notice].should be nil end end describe "when viewing session details with video embedded," do it "uses the appropriate player when playing older videos" do mock(Session).first(:id=>"1") {@sessions[0]} command = ShowSession.new "1", {"MEMBERID"=>"DC"} results = command.populate results[:session].id.should be 1 results[:player].should == :video_flv results[:video].media.should == "http://cdn/File.flv" end it "uses the appropriate player when playing newer videos" do mock(Session).first(:id=>"2") {@sessions[1]} command = ShowSession.new "2", {"MEMBERID"=>"DC"} results = command.populate results[:session].id.should be 2 results[:player].should == :video_bit results[:video].media.should == "2f3429fcdc073" end end end
require 'vanagon/project' require 'vanagon/driver' require 'vanagon/errors' require 'fakefs/spec_helpers' describe 'Vanagon::Project' do let(:component) { double(Vanagon::Component) } let(:configdir) { '/a/b/c' } let(:platform) do OpenStruct.new(:settings => {}) end let(:upstream_platform) do OpenStruct.new(:settings => {}) end let(:project_block) { "project 'test-fixture' do |proj| proj.component 'some-component' end" } let(:upstream_project_block) { "project 'upstream-test' do |proj| proj.setting(:test, 'upstream-test') end" } let(:inheriting_project_block) { "project 'inheritance-test' do |proj| proj.inherit_settings 'upstream-test', 'git://some.url', 'master' end" } let(:inheriting_project_block_with_settings) { "project 'inheritance-test' do |proj| proj.setting(:merged, 'yup') proj.inherit_settings 'upstream-test', 'git://some.url', 'master' end" } let(:preset_inheriting_project_block) { "project 'inheritance-test' do |proj| proj.setting(:test, 'inheritance-test') proj.inherit_settings 'upstream-test', 'git://some.url', 'master' end" } let(:postset_inheriting_project_block) { "project 'inheritance-test' do |proj| proj.inherit_settings 'upstream-test', 'git://some.url', 'master' proj.setting(:test, 'inheritance-test') end" } let (:dummy_platform_settings) { plat = Vanagon::Platform::DSL.new('debian-6-i386') plat.instance_eval("platform 'debian-6-i386' do |plat| plat.servicetype 'sysv' plat.servicedir '/etc/init.d' plat.defaultdir '/etc/default' settings[:platform_test] = 'debian' end") plat._platform } describe '#vendor=' do dummy_platform = Vanagon::Platform.new('el-7-x86_64') good_vendor = 'Puppet Inc. <release@puppet.com>' bad_vendor = 'Puppet Inc.' it 'fails if vendor field does not include email address' do project = Vanagon::Project.new('vendor-test', dummy_platform) expect { project.vendor = bad_vendor }.to raise_error(Vanagon::Error, /Project vendor field must include email address/) end it 'sets project vendor to the supplied value' do project = Vanagon::Project.new('vendor-test', dummy_platform) project.vendor = good_vendor expect(project.vendor).to eq(good_vendor) end end describe '#vendor_name_only' do it 'returns just the name of the vendor' do project = Vanagon::Project.new('vendor-test', Vanagon::Platform.new('el-7-x86_64')) project.vendor = 'Puppet Inc. <release@puppet.com>' expect(project.vendor_name_only).to eq('Puppet Inc.') end end describe '#vendor_email_only' do it 'returns just the email address of the vendor' do project = Vanagon::Project.new('vendor-test', Vanagon::Platform.new('el-7-x86_64')) project.vendor = 'Puppet Inc. <release@puppet.com>' expect(project.vendor_email_only).to eq('release@puppet.com') end end describe '#get_root_directories' do before do allow_any_instance_of(Vanagon::Project::DSL).to receive(:puts) allow(Vanagon::Driver).to receive(:configdir).and_return(configdir) allow(Vanagon::Component).to receive(:load_component).with('some-component', any_args).and_return(component) end let(:test_sets) do [ { :directories => ["/opt/puppetlabs/bin", "/etc/puppetlabs", "/var/log/puppetlabs", "/etc/puppetlabs/puppet", "/opt/puppetlabs"], :results => ["/opt/puppetlabs", "/etc/puppetlabs", "/var/log/puppetlabs"], }, { :directories => ["/opt/puppetlabs/bin", "/etc/puppetlabs", "/var/log/puppetlabs", "/etc/puppetlabs/puppet", "/opt/puppetlabs/lib"], :results => ["/opt/puppetlabs/bin", "/etc/puppetlabs", "/var/log/puppetlabs", "/opt/puppetlabs/lib"], }, ] end it 'returns only the highest level directories' do test_sets.each do |set| expect(component).to receive(:directories).and_return([]) proj = Vanagon::Project::DSL.new('test-fixture', configdir, platform, []) proj.instance_eval(project_block) set[:directories].each {|dir| proj.directory dir } expect(proj._project.get_root_directories.sort).to eq(set[:results].sort) end end end describe "#load_upstream_settings" do before(:each) do # stub out all of the git methods so we don't actually clone allow(Vanagon::Component::Source::Git).to receive(:valid_remote?).with(URI.parse('git://some.url')).and_return(true) git_source = Vanagon::Component::Source::Git.new('git://some.url', workdir: Dir.getwd) allow(Vanagon::Component::Source::Git).to receive(:new).and_return(git_source) expect(git_source).to receive(:fetch).and_return(true) # stubs for the upstream project upstream_proj = Vanagon::Project::DSL.new('upstream-test', configdir, upstream_platform, []) upstream_proj.instance_eval(upstream_project_block) expect(Vanagon::Project).to receive(:load_project).and_return(upstream_proj._project) expect(Vanagon::Platform).to receive(:load_platform).and_return(upstream_platform) class Vanagon class Project BUILD_TIME = '2017-07-10T13:34:25-07:00' VANAGON_VERSION = '0.0.0-rspec' end end end it 'loads upstream settings' do inheriting_proj = Vanagon::Project::DSL.new('inheritance-test', configdir, platform, []) inheriting_proj.instance_eval(inheriting_project_block) expect(inheriting_proj._project.settings[:test]).to eq('upstream-test') end it 'overrides duplicate settings from before the load' do inheriting_proj = Vanagon::Project::DSL.new('inheritance-test', configdir, platform, []) inheriting_proj.instance_eval(preset_inheriting_project_block) expect(inheriting_proj._project.settings[:test]).to eq('upstream-test') end it 'lets you override settings after the load' do inheriting_proj = Vanagon::Project::DSL.new('inheritance-test', configdir, platform, []) inheriting_proj.instance_eval(postset_inheriting_project_block) expect(inheriting_proj._project.settings[:test]).to eq('inheritance-test') end it 'merges settings' do inheriting_proj = Vanagon::Project::DSL.new('inheritance-test', configdir, platform, []) inheriting_proj.instance_eval(inheriting_project_block_with_settings) expect(inheriting_proj._project.settings[:test]).to eq('upstream-test') expect(inheriting_proj._project.settings[:merged]).to eq('yup') end end describe 'platform settings' do before do allow(Vanagon::Component) .to receive(:load_component) .with('some-component', any_args) .and_return(component) end it 'loads settings set in platforms' do settings_proj = Vanagon::Project::DSL.new( 'settings-test', configdir, dummy_platform_settings, [] ) settings_proj.instance_eval(project_block) expect(settings_proj._project.settings[:platform_test]).to eq('debian') end end describe "#load_yaml_settings" do subject(:project) do project = Vanagon::Project.new('yaml-inheritance-test', Vanagon::Platform.new('aix-7.2-ppc')) project.settings = { merged: 'nope', original: 'original' } project end let(:yaml_filename) { 'settings.yaml' } let(:sha1_filename) { "#{yaml_filename}.sha1" } let(:yaml_path) { "/path/to/#{yaml_filename}" } let(:sha1_path) { "/path/to/#{sha1_filename}" } let(:yaml_content) { { other: 'other', merged: 'yup' }.to_yaml } let(:local_yaml_uri) { "file://#{yaml_path}" } let(:http_yaml_uri) { "http:/#{yaml_path}" } before(:each) do allow(Dir).to receive(:mktmpdir) { |&block| block.yield '' } end it "fails for a local source if the settings file doesn't exist" do expect { project.load_yaml_settings(local_yaml_uri) }.to raise_error(Vanagon::Error) end it "fails if given a git source" do expect { project.load_yaml_settings('git://some/repo.uri') }.to raise_error(Vanagon::Error) end it "fails when given an unknown source" do expect { project.load_yaml_settings("fake://source.uri") }.to raise_error(Vanagon::Error) end it "fails if downloading over HTTP without a valid sha1sum URI" do allow(Vanagon::Component::Source::Http) .to receive(:valid_url?) .with(http_yaml_uri) .and_return(true) http_source = instance_double(Vanagon::Component::Source::Http) allow(Vanagon::Component::Source).to receive(:source).and_return(http_source) allow(http_source).to receive(:verify).and_return(true) expect { project.load_yaml_settings(http_yaml_uri) }.to raise_error(Vanagon::Error) end context "given a valid source" do before(:each) do local_source = instance_double(Vanagon::Component::Source::Local) allow(local_source).to receive(:fetch) allow(local_source).to receive(:verify).and_return(true) allow(local_source).to receive(:file).and_return(yaml_path) allow(Vanagon::Component::Source).to receive(:determine_source_type).and_return(:local) allow(Vanagon::Component::Source).to receive(:source).and_return(local_source) allow(File).to receive(:read).with(yaml_path).and_return(yaml_content) expect { project.load_yaml_settings(local_yaml_uri) }.not_to raise_exception end it "overwrites the current project's settings when they conflict" do expect(project.settings[:merged]).to eq('yup') end it "adopts new settings found in the other project" do expect(project.settings[:other]).to eq('other') end it "keeps its own settings when there are no conflicts" do expect(project.settings[:original]).to eq('original') end end end describe "#filter_component" do # All of the following tests should be run with one project level # component that isn't included in the build_deps of another component before(:each) do @proj = Vanagon::Project.new('test-fixture-with-comps', platform) @not_included_comp = Vanagon::Component.new('test-fixture-not-included', {}, {}) @proj.components << @not_included_comp end it "returns nil when given a component that doesn't exist" do expect(@proj.filter_component("fake")).to eq([]) end it "returns only the component with no build deps" do comp = Vanagon::Component.new('test-fixture1', {}, {}) @proj.components << comp expect(@proj.filter_component(comp.name)).to eq([comp]) end it "returns component and one build dep" do comp1 = Vanagon::Component.new('test-fixture1', {}, {}) comp2 = Vanagon::Component.new('test-fixture2', {}, {}) comp1.build_requires << comp2.name @proj.components << comp1 @proj.components << comp2 expect(@proj.filter_component(comp1.name)).to eq([comp1, comp2]) end it "returns only the component with build deps that are not components of the @project" do comp = Vanagon::Component.new('test-fixture1', {}, {}) comp.build_requires << "fake-name" @proj.components << comp expect(@proj.filter_component(comp.name)).to eq([comp]) end it "returns the component and build deps with both @project components and external build deps" do comp1 = Vanagon::Component.new('test-fixture1', {}, {}) comp2 = Vanagon::Component.new('test-fixture2', {}, {}) comp1.build_requires << comp2.name comp1.build_requires << "fake-name" @proj.components << comp1 @proj.components << comp2 expect(@proj.filter_component(comp1.name)).to eq([comp1, comp2]) end it "returns the component and multiple build deps" do comp1 = Vanagon::Component.new('test-fixture1', {}, {}) comp2 = Vanagon::Component.new('test-fixture2', {}, {}) comp3 = Vanagon::Component.new('test-fixture3', {}, {}) comp1.build_requires << comp2.name comp1.build_requires << comp3.name @proj.components << comp1 @proj.components << comp2 @proj.components << comp3 expect(@proj.filter_component(comp1.name)).to eq([comp1, comp2, comp3]) end it "returns the component and multiple build deps with external build deps" do comp1 = Vanagon::Component.new('test-fixture1', {}, {}) comp2 = Vanagon::Component.new('test-fixture2', {}, {}) comp3 = Vanagon::Component.new('test-fixture3', {}, {}) comp1.build_requires << comp2.name comp1.build_requires << comp3.name comp1.build_requires << "another-fake-name" @proj.components << comp1 @proj.components << comp2 @proj.components << comp3 expect(@proj.filter_component(comp1.name)).to eq([comp1, comp2, comp3]) end end describe '#get_preinstall_actions' do it "Collects the preinstall actions for the specified package state" do proj = Vanagon::Project.new('action-test', platform) proj.get_preinstall_actions('upgrade') proj.get_preinstall_actions('install') expect(proj.get_preinstall_actions('install')).to be_instance_of(String) end end describe '#get_trigger_scripts' do it "Collects the install triggers for the project for the specified packing state" do proj = Vanagon::Project.new('action-test', platform) expect(proj.get_trigger_scripts('install')).to eq({}) expect(proj.get_trigger_scripts('upgrade')).to be_instance_of(Hash) end it 'fails with empty install trigger action' do proj = Vanagon::Project.new('action-test', platform) expect { proj.get_trigger_scripts([]) }.to raise_error(Vanagon::Error) end it 'fails with incorrect install trigger action' do proj = Vanagon::Project.new('action-test', platform) expect { proj.get_trigger_scripts('foo') }.to raise_error(Vanagon::Error) end end describe '#get_interest_triggers' do it "Collects the interest triggers for the project for the specified packaging state" do proj = Vanagon::Project.new('action-test', platform) expect(proj.get_interest_triggers('install')).to eq([]) expect(proj.get_interest_triggers('upgrade')).to be_instance_of(Array) end it 'fails with empty interest trigger action' do proj = Vanagon::Project.new('action-test', platform) expect { proj.get_interest_triggers([]) }.to raise_error(Vanagon::Error) end it 'fails with incorrect interest trigger action' do proj = Vanagon::Project.new('action-test', platform) expect { proj.get_interest_triggers('foo') }.to raise_error(Vanagon::Error) end end describe '#get_activate_triggers' do it "Collects the activate triggers for the project for the specified packaging state" do proj = Vanagon::Project.new('action-test', platform) expect(proj.get_activate_triggers()).to be_instance_of(Array) expect(proj.get_activate_triggers()).to be_instance_of(Array) end end describe '#generate_dependencies_info' do before(:each) do @proj = Vanagon::Project.new('test-project', platform) end it "returns a hash of components and their versions" do comp1 = Vanagon::Component.new('test-component1', {}, {}) comp1.version = '1.0.0' comp2 = Vanagon::Component.new('test-component2', {}, {}) comp2.version = '2.0.0' comp2.options[:ref] = '123abcd' comp3 = Vanagon::Component.new('test-component3', {}, {}) @proj.components << comp1 @proj.components << comp2 @proj.components << comp3 expect(@proj.generate_dependencies_info()).to eq({ 'test-component1' => { 'version' => '1.0.0' }, 'test-component2' => { 'version' => '2.0.0', 'ref' => '123abcd' }, 'test-component3' => {}, }) end end describe '#build_manifest_json' do before(:each) do class Vanagon class Project BUILD_TIME = '2017-07-10T13:34:25-07:00' VANAGON_VERSION = '0.0.0-rspec' end end @proj = Vanagon::Project.new('test-project', platform) end it 'should generate a hash with the expected build metadata' do comp1 = Vanagon::Component.new('test-component1', {}, {}) comp1.version = '1.0.0' @proj.components << comp1 @proj.version = '123abcde' expect(@proj.build_manifest_json()).to eq({ 'packaging_type' => { 'vanagon' => '0.0.0-rspec' }, 'version' => '123abcde', 'components' => { 'test-component1' => { 'version' => '1.0.0' } }, 'build_time' => '2017-07-10T13:34:25-07:00', }) end it 'should call pretty-print when we want pretty json' do comp1 = Vanagon::Component.new('test-component1', {}, {}) comp1.version = '1.0.0' @proj.components << comp1 @proj.version = '123abcde' expect(JSON).to receive(:pretty_generate) @proj.build_manifest_json(true) end end describe '#save_manifest_json' do include FakeFS::SpecHelpers let(:platform_name) { 'el-7-x86_64' } let(:platform) { Vanagon::Platform.new(platform_name) } before(:each) do class Vanagon class Project BUILD_TIME = '2018-07-10T13:34:25-07:00' VANAGON_VERSION = '0.0.0-rspec' end end @proj = Vanagon::Project.new('test-project', platform) end it 'should generate a file with the expected build metadata' do correct_sample_metadata = { 'packaging_type' => { 'vanagon' => '0.0.0-rspec' }, 'version' => '123abcde', 'components' => { 'test-component-10' => { 'version' => '1.2.3' } }, 'build_time' => '2018-07-10T13:34:25-07:00', } bad_sample_metadata = { 'BAD KEY' => 'BAD VALUE' } comp1 = Vanagon::Component.new('test-component-10', {}, {}) comp1.version = '1.2.3' @proj.components << comp1 @proj.version = '123abcde' FakeFS do @proj.save_manifest_json(platform) old_style_metadata = JSON.parse(File.read('ext/build_metadata.json')) expect(old_style_metadata).to eq(correct_sample_metadata) metadata_with_project_and_platform = JSON.parse( File.read("ext/build_metadata.test-project.#{platform_name}.json")) expect(metadata_with_project_and_platform).to eq(correct_sample_metadata) expect(metadata_with_project_and_platform).not_to eq(bad_sample_metadata) end end end describe '#publish_yaml_settings' do let(:platform_name) { 'aix-7.2-ppc' } let(:platform) { Vanagon::Platform.new(platform_name) } subject(:project) do project = Vanagon::Project.new('test-project', platform) project.settings = { key: 'value' } project.version = 'version' project.yaml_settings = true project end let(:yaml_output_path) { File.expand_path("test-project-version.#{platform_name}.settings.yaml", "output") } let(:sha1_output_path) { File.expand_path("test-project-version.#{platform_name}.settings.yaml.sha1", "output") } let(:yaml_file) { double('yaml_file') } let(:sha1_file) { double('sha1_file') } let(:sha1_content) { 'abcdef' } let(:sha1_object) { instance_double(Digest::SHA1, hexdigest: sha1_content) } it 'writes project settings as yaml and a sha1sum for the settings to the output directory' do expect(File).to receive(:open).with(yaml_output_path, "w").and_yield(yaml_file) expect(Digest::SHA1).to receive(:file).with(yaml_output_path).and_return(sha1_object) expect(File).to receive(:open).with(sha1_output_path, "w").and_yield(sha1_file) expect(yaml_file).to receive(:write).with({key: 'value'}.to_yaml) expect(sha1_file).to receive(:puts).with(sha1_content) expect { project.publish_yaml_settings(platform) }.not_to raise_error end it 'does not write yaml settings or a sha1sum unless told to' do project.yaml_settings = false expect(File).not_to receive(:open) expect { project.publish_yaml_settings(platform) }.not_to raise_error end it "fails if the output directory doesn't exist" do allow_any_instance_of(File).to receive(:open).with(yaml_output_path).and_raise(Errno::ENOENT) allow_any_instance_of(File).to receive(:open).with(sha1_output_path).and_raise(Errno::ENOENT) expect { project.publish_yaml_settings(platform) }.to raise_error(Errno::ENOENT) end it "fails unless the project has a version" do project.version = nil expect { project.publish_yaml_settings(platform) }.to raise_error(Vanagon::Error) end end describe '#generate_package' do it "builds packages by default" do platform = Vanagon::Platform::DSL.new('el-7-x86_64') platform.instance_eval("platform 'el-7-x86_6' do |plat| end") proj = Vanagon::Project::DSL.new('test-fixture', configdir, platform._platform, []) expect(platform._platform).to receive(:generate_package) { ["# making a package"] } expect(proj._project.generate_package).to eq(["# making a package"]) end it "builds packages and archives if configured for both" do platform = Vanagon::Platform::DSL.new('el-7-x86_64') platform.instance_eval("platform 'el-7-x86_6' do |plat| end") proj = Vanagon::Project::DSL.new('test-fixture', configdir, platform._platform, []) proj.generate_archives(true) expect(platform._platform).to receive(:generate_package) { ["# making a package"] } expect(platform._platform).to receive(:generate_compiled_archive) { ["# making an archive"] } expect(proj._project.generate_package).to eq(["# making a package", "# making an archive"]) end it "can build only archives" do platform = Vanagon::Platform::DSL.new('el-7-x86_64') platform.instance_eval("platform 'el-7-x86_6' do |plat| end") proj = Vanagon::Project::DSL.new('test-fixture', configdir, platform._platform, []) proj.generate_archives(true) proj.generate_packages(false) expect(platform._platform).to receive(:generate_compiled_archive) { ["# making an archive"] } expect(proj._project.generate_package).to eq(["# making an archive"]) end it "builds nothing if that's what you really want" do platform = Vanagon::Platform::DSL.new('el-7-x86_64') platform.instance_eval("platform 'el-7-x86_6' do |plat| end") proj = Vanagon::Project::DSL.new('test-fixture', configdir, platform._platform, []) proj.generate_packages(false) expect(proj._project.generate_package).to eq([]) end end describe '#get_rpm_ghost_files' do it 'returns an empty array when there are no ghost files' do proj = Vanagon::Project.new('test-ghost', platform) expect(proj.get_rpm_ghost_files).to eq([]) end it 'returns ghost files when some are set' do proj = Vanagon::Project.new('test-ghosts', platform) comp = Vanagon::Component.new('ghosts', {}, {}) comp.add_rpm_ghost_file('ghost') proj.components << comp expect(proj.get_rpm_ghost_files).to eq(['ghost']) end end end
class Item < ApplicationRecord has_many :item_tags, dependent: :destroy has_many :tags, through: :item_tags belongs_to :user belongs_to :category has_many :comments, dependent: :destroy has_many :pictures, dependent: :destroy has_many :likes, dependent: :destroy validates_associated :pictures accepts_nested_attributes_for :pictures, allow_destroy: true extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :postage belongs_to_active_hash :prefecture belongs_to_active_hash :delivery_date with_options presence: true do validates :pictures, length: { maximum: 10, message: 'は10枚以内で入力してください' }, on: :create validates :name, length: { maximum: 40 } validates :explanation, length: { maximum: 1000 } validates :category_id validates :condition, exclusion: { in: %w(---), message: 'を入力してください' } validates :price, numericality: { only_integer: true, greater_than_or_equal_to: 300, less_than_or_equal_to: 9999999 } validates :user_id validates :postage_id, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 2 } validates :prefecture_id, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 47 } validates :delivery_date_id, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 2 } end enum condition:{ unused: 1, nearly_unused: 2, not_injured: 3, bit_injured: 4, injured: 5, bad: 6 } after_create do item = Item.find_by(id: self.id) tags = self.explanation.scan(/[##](?<!##)[\w\p{Han}0-9ぁ-ヶヲ-゚ー]+/).map(&:strip) tags.uniq.map do |t| tag = Tag.find_or_create_by(name: t.delete('##')) item.tags << tag end end before_update do item = Item.find_by(id: self.id) ids = item.tags.ids tags = self.explanation.scan(/[##](?<!##)[\w\p{Han}0-9ぁ-ヶヲ-゚ー]+/).map(&:strip) tags.uniq.map do |t| tag = Tag.find_or_create_by(name: t.delete('##')) if (isExist = item.tags.where(name: tag.name)) != [] ids.delete(isExist[0].id) else item.tags << tag end end ids.each do |id| item.tags.delete(id) end end def self.search(keyword) return Item.all unless keyword Item.where(['name LIKE ? OR explanation LIKE ?', "%#{keyword}%", "%#{keyword}%"]) end end
class WindowsController < ApplicationController def index @windows = Window.all end def show @window = Window.find(params[:id]) end end
class Vote < ApplicationRecord belongs_to :user belongs_to :restaurant validates_uniqueness_of :restaurant_id, scope: :user_id end
module Resourced class Object include Base include Doze::Router include Typisch::Typed def initialize(uri, application_context) @uri = uri @application_context = application_context end def serialization_data; self; end def serialization_type; self.class.type; end route("/property/{property}", :name => 'property_by_name') do |router, uri, params| router.property_resource(params[:property], uri) end def property_resource(name, uri=expand_route_template('property_by_name', :property => name)) type = property_type(name) or return case type when Typisch::Type::Sequence options = self.class.property_resource_options[name.to_sym] || {} Sequence.new(uri, send(name), type, @application_context, options) else SerializedWithType.new(uri, send(name), type, @application_context) end end def property_type(name) # avoids doing a to_sym on possibly-arbitrary-user-input string type.property_names_to_types.each {|n,type| return type if n.to_s == name.to_s} end def self.register_type(registry, derived_from=nil, &block) super(registry, derived_from, &block) end def self.property_resource_options @property_resource_options ||= {} end end end
class Users::RegistrationsController < Devise::RegistrationsController protected def update_resource(resource, params) resource.update_without_current_password(params) end def after_update_path_for(resource) user_url(id: current_user.id) end end
require 'rails_helper' RSpec.describe Api::V1::InvoiceItems::InvoicesController, type: :controller do fixtures :items, :invoice_items, :invoices describe "#index" do it "serves all an invoice_items' invoices' json" do get :index, format: :json, invoice_item_id: invoice_items(:invoice_item_2).id expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) # first_invoice = body.first expect(body["customer_id"]).to eq invoices(:invoice_1).customer_id expect(body["merchant_id"]).to eq invoices(:invoice_1).merchant_id expect(body["status"]).to eq invoices(:invoice_1).status expect(body["created_at"]).to eq "2012-03-25T09:54:09.000Z" expect(body["updated_at"]).to eq "2012-03-25T09:54:09.000Z" end end end
class Change1VoltclMpoints < ActiveRecord::Migration[5.0] def change remove_column :mpoints, :voltcl, :integer, null: false, default: 10 add_column :mpoints, :voltcl, :float, null: false, default: 10 end end
class StageDecorator < Draper::Decorator delegate_all # decorates_association :scores def ridden_on h.l model.ridden_on, :format => :short end def distance h.number_with_precision model.distance.to_s + " km" end end
class Api::V1::ContactsController < Api::V1::BaseController before_action :find_contact, only: [:show, :update, :destroy] before_action :check_emails, only: [:create, :update] resource_description do short 'Contacts information resources' formats ['json'] end api :GET, '/v1/contacts.json?access_token=TOKEN', 'Returns the information about all contacts of user' error code: 401, desc: 'Unauthorized' example "contacts: [{'id':8,'name':'testing'}, {'id':9,'name':'something'}]" def index render json: { contacts: ActiveModel::Serializer::CollectionSerializer.new(current_resource_owner.contacts.order(name: :asc), each_serializer: ContactSerializer) } end api :GET, '/v1/contacts/:id.json?access_token=TOKEN', 'Returns the information about speсific contact of user' error code: 401, desc: 'Unauthorized' example "error: 'Contact does not exist'" example "contact: {'id':8,'name':'testing','phone':'55-55-55','address':'','company':'','birthday':''}" def show render json: { contact: ContactSerializer::FullData.new(@contact) } end api :POST, '/v1/contacts.json', 'Creates contact' param :access_token, String, desc: 'Token info', required: true param :contact, Hash, required: true do param :name, String, desc: 'Name', required: true param :email, String, desc: 'Email', required: true param :phone, String, desc: 'Phone', required: true param :address, String, desc: 'Address', required: true param :company, String, desc: 'Company', required: true param :birthday, String, desc: 'Birthday', required: true end meta contact: { name: 'sample', email: 'sample@gmail.com', phone: '', address: '', company: '', birthday: '' } error code: 401, desc: 'Unauthorized' example "error: 'You have another contact with such email'" example "error: 'Incorrect contact data'" example "contacts: [{'id':8,'name':'testing'}, {'id':9,'name':'something'}]" def create contact = Contact.new(contacts_params.merge(user: current_resource_owner)) if contact.save render json: { contacts: ActiveModel::Serializer::CollectionSerializer.new(current_resource_owner.contacts.order(name: :asc), each_serializer: ContactSerializer) } else render json: { error: 'Incorrect contact data' }, status: 400 end end api :PATCH, '/v1/contacts/:id.json', 'Updates contact' param :access_token, String, desc: 'Token info', required: true param :contact, Hash, required: true do param :name, String, desc: 'Name', required: true param :email, String, desc: 'Email', required: true param :phone, String, desc: 'Phone', required: true param :address, String, desc: 'Address', required: true param :company, String, desc: 'Company', required: true param :birthday, String, desc: 'Birthday', required: true end meta contact: { name: 'sample', email: 'sample@gmail.com', phone: '', address: '', company: '', birthday: '' } error code: 401, desc: 'Unauthorized' example "error: 'You have another contact with such email'" example "error: 'Incorrect contact data'" example "contacts: [{'id':8,'name':'testing'}, {'id':9,'name':'something'}]" def update if @contact.update(contacts_params) render json: { contacts: ActiveModel::Serializer::CollectionSerializer.new(current_resource_owner.contacts.order(name: :asc), each_serializer: ContactSerializer) } else render json: { error: 'Incorrect contact data' }, status: 400 end end api :DELETE, '/v1/contacts/:id.json?access_token=TOKEN', 'Destroy contact' error code: 401, desc: 'Unauthorized' example "error: 'Contact does not exist'" example "contact: {'id':8,'name':'testing','phone':'55-55-55','address':'','company':'','birthday':''}" def destroy @contact.destroy render json: { contacts: ActiveModel::Serializer::CollectionSerializer.new(current_resource_owner.contacts.order(name: :asc), each_serializer: ContactSerializer) } end private def find_contact @contact = current_resource_owner.contacts.find_by(id: params[:id]) render json: { error: 'Contact does not exist' }, status: 400 unless @contact end def check_emails unless current_resource_owner.check_contact_email(@contact.nil? ? nil : @contact.id, contacts_params[:email]) render json: { error: 'You have another contact with such email' }, status: 400 end end def contacts_params params.require(:contact).permit(:name, :email, :phone, :address, :company, :birthday) end end
class Task < ActiveRecord::Base validates_presence_of :name default_scope :conditions => {:done => false} def updated updated_at > 5.minutes.ago end end
class Guests::OmniauthCallbacksController < Devise::OmniauthCallbacksController def self.callback_for(provider) class_eval %Q{ def #{provider} @guest = Guest.fetch_or_store_oauth(request.env["omniauth.auth"], current_guest) if @guest.persisted? sign_in_and_redirect @guest, :event => :authentication set_flash_message(:notice, :success, :kind => "#{provider}".capitalize) else session["devise.#{provider}_data"] = request.env["omniauth.auth"] redirect_to new_guest_registration_url flash[:alert] = "Authentication from #{provider} failed. You can create an account with us." end end } end [:google_oauth2, :facebook].each do |provider| callback_for provider end end
gem 'minitest', '~> 4.3.2' gem 'minitest-reporters' require 'minitest/reporters' gem 'ansi' require 'ansi/code' module JEMC; class Reporter include Minitest::Reporter attr_accessor :color, :columns, :max_tests def initialize(options = {}) # @detailed_skip = options.fetch(:detailed_skip, true) # @slow_count = options.fetch(:slow_count, 0) # @slow_suite_count = options.fetch(:slow_suite_count, 0) # @fast_fail = options.fetch(:fast_fail, false) # @test_times = [] # @suite_times = [] @color = options.fetch(:color) do output.tty? && ( ENV["TERM"] =~ /^screen|color/ || ENV["EMACS"] == "t" ) end @columns = ENV['COLUMNS'] || `tput cols`.to_i || 80 end def before_suites(suites, type) puts self.max_tests = suites.map{|x| x.test_methods.size}.max for suite in suites do class << suite attr_accessor :reporter attr_accessor :tests end suite.reporter = self suite.tests = Hash.new suite.tests[:pass] = [] suite.tests[:fail] = [] suite.tests[:error] = [] suite.tests[:skip] = [] def suite.suffix dig = reporter.max_tests.to_s.size groups = [:pass, :fail, :error] colors = [:green,:red,:magenta] (' ' + groups .map { |x| self.tests[x].size } .map { |x,e| (x > 0) ? ("%0#{dig}d" % x) : dig.times.map{' '}.join } .each_with_index .map { |x,i| reporter.send(colors[i], x) } .join('/')) end def suite.suffix_size ANSI::Code.uncolor(self.suffix).size end end end def before_suite(suite) return if suite.test_methods.size <= 0 length = @columns-suite.test_methods.size-suite.suffix_size print str_fit(suite.name, length-1)+' ' end def after_suite(suite) return if suite.test_methods.size <= 0 puts suite.suffix suite.tests[:skip].each { |x| skipped_show(*x) } suite.tests[:fail].each { |x| failure_show(*x) } suite.tests[:error].each { |x| error_show(*x) } end def after_suites(suites, type) puts puts '%d tests, %d assertions, %d failures, %d errors, %d skips' % [runner.test_count, runner.assertion_count, \ runner.failures, runner.errors, runner.skips] end def pass(suite, test, test_runner) print green('.') suite.tests[:pass] << [test, test_runner.exception] end def skip(suite, test, test_runner) print blue('s') suite.tests[:skip] << [test, test_runner.exception] end def failure(suite, test, test_runner) print red('F') suite.tests[:fail] << [test, test_runner.exception] end def error(suite, test, test_runner) print magenta('E') suite.tests[:error] << [test, test_runner.exception] end def skipped_show(test, exc) pre = black('>')+blue('>')+bold(blue('s'))+' ' pre_size = ANSI::Code.uncolor(pre).size puts pre+blue(str_fit(test, @columns-pre_size)) end def failure_show(test, exc) pre = black('>')+red('>')+bold(red('F'))+' ' pre_size = ANSI::Code.uncolor(pre).size puts pre+red(str_fit(test, @columns-pre_size)) exc.backtrace.unshift runner.location(exc)+":in `'" puts backtrace(exc) puts yellow("#{exc.class}: #{exc.message}") puts end def error_show(test, exc) pre = black('>')+magenta('>')+bold(magenta('E'))+' ' pre_size = ANSI::Code.uncolor(pre).size puts pre+magenta(str_fit(test, @columns-pre_size)) puts backtrace(exc) puts yellow("#{exc.class}: #{exc.message}") puts end def backtrace(exception) index = exception.backtrace \ .find_index{|x| x=~/\/minitest\/(?=[^\/]*$).*['`]run['`]$/} index ||= -1 exception.backtrace.map do |line| m = line.match /(.*)(?<=\/)([^\:\/]*):(\d+)(?=:in):in ['`](.*)['`]/ m ||= line.match /()([^\:\/]*):(\d+)(?=:in):in ['`](.*)['`]/ str_fit(m[1], columns/3, :keep=>:tail, :align=>:right) \ + white(str_fit(m[2], columns/3-m[3].size-1, :keep=>:head))+':'+white(m[3]) \ + bold(cyan(str_fit(' '+m[4], (columns-2*(columns/3)), \ :keep=>:head, :align=>:right))) end[0...index].reverse end # [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white] for color in ANSI::Code.colors+[:bold] eval <<-CODE def #{color}(string) @color ? ANSI::Code.#{color}(string) : string end CODE end # Pad or truncate a string intelligently def str_fit(str, length, keep: :both, align: :left, pad:' ', mid:'...') str = str.to_s raise ArgumentError, "Keyword argument :keep must be :head, :tail, or :both."\ unless [:head, :tail, :both].include? keep raise ArgumentError, "Keyword argument :align must be :left, :right, or :center."\ unless [:left, :right, :center].include? align length = [0,length].max diff = length - str.size # Return padded string if length is the same or to be increased if diff>=0 padstr = diff.times.map{pad}.join[0..diff] case align when :left return str + padstr when :right return padstr + str when :center return padstr[0...(padstr.size/2)] + str + padstr[0...(padstr.size-(padstr.size/2))] end end # Return truncated midstring if length is the same or smaller than mid's size return mid[0...length] if length<=mid.size boundary_re = /((?<=[a-zA-Z])(?![a-zA-Z]))|((?<![a-zA-Z])(?=[a-zA-Z]))/ indices = str.to_enum(:scan, boundary_re).map{$`.size}-[0,str.size] # p indices # Collect pairs of indices closest to desired diff nearest = [[str.size,0,str.size]] for x in indices x = 0 if keep==:tail for y in indices y = str.size if keep==:head if (y>x) candidate = [(y-x+diff-mid.size).abs,(y-x+diff-mid.size),x,y] if nearest[0][0]> candidate[0] nearest = [candidate] elsif nearest[0][0]==candidate[0] nearest << candidate end end end end nearest.uniq! # Choose the most appropriate pair of indices from nearest case keep when :both nearest.sort!{|a,b| (str.size-(a[2]+a[3])).abs <=> (str.size-(b[2]+b[3])).abs} when :tail nearest.reverse! end nearest = nearest.first if nearest[0]!=0 case keep when :both nearest[2]+=(nearest[1]/2) nearest[3]-=(nearest[1]-(nearest[1]/2)) when :head nearest[2]+=nearest[1] when :tail nearest[3]-=nearest[1] end if nearest[2]<0 nearest[2]+=(0-nearest[2]) nearest[3]+=(0-nearest[2]) elsif nearest[3]>str.size nearest[3]+=(str.size-nearest[2]) nearest[3]+=(str.size-nearest[2]) end nearest[1]=(y-x+diff-mid.size) nearest[0]=nearest[1].abs end return str[0...nearest[2]]+mid+str[nearest[3]..str.size] end end end Minitest::Reporters.use! JEMC::Reporter.new
class AddModerationToSearch < ActiveRecord::Migration def change add_column :searches, :moderator_id, :integer add_column :searches, :moderation_status, :integer, default: 1 add_column :searches, :moderation_message, :text add_column :searches, :moderation_email, :boolean, default: :false end end
module System::PlayerActions def self.run entity = World.player Input.action = :wait if entity.creature.dead == true return unless Input.action return unless World.turn == :player case Input.action when :go_west then move entity, -1, 0 when :go_east then move entity, +1, 0 when :go_north then move entity, 0, -1 when :go_south then move entity, 0, +1 when :go_north_west then move entity, -1, -1 when :go_north_east then move entity, +1, -1 when :go_south_west then move entity, -1, +1 when :go_south_east then move entity, +1, +1 when :examine then examine entity when :fire then fire entity when :fire! then mouse_fire entity when :wait then wait when :cancel then cancel entity end end internal def self.move entity, dx, dy case entity.player.mode when :normal move_entity entity, dx, dy when :fire, :examine move_cursor entity, dx, dy end end internal def self.move_entity entity, dx, dy moved = System::Movement.move entity, dx, dy end_turn 1 if moved end internal def self.move_cursor entity, dx, dy entity.player.cursor.x += dx unless entity.player.cursor.x + dx < Camera.position.x or entity.player.cursor.x + dx > Camera.position.x + Display.width - 1 entity.player.cursor.y += dy unless entity.player.cursor.y + dy < Camera.position.y or entity.player.cursor.y + dy > Camera.position.y + Display.height - 1 end internal def self.examine entity case entity.player.mode when :normal set_cursor_mode entity, :examine when :examine entity.player.mode = :normal end end internal def self.fire entity case entity.player.mode when :normal set_cursor_mode entity, :fire when :fire shoot entity entity.player.mode = :normal end end internal def self.set_cursor_mode entity, mode entity.player.cursor.x = entity.position.x entity.player.cursor.y = entity.position.y entity.player.mode = mode end internal def self.mouse_fire entity if entity.player.mode == :normal entity.player.cursor.x = Input.cursor.x entity.player.cursor.y = Input.cursor.y shoot entity end end internal def self.shoot entity return if entity.player.cursor.x == entity.position.x and entity.player.cursor.y == entity.position.y Log.add "You shoot with your gun," System::Combat.shoot_at entity, entity.player.cursor end_turn 1 end internal def self.cancel entity entity.player.mode = :normal if entity.player.mode == :fire or entity.player.mode == :examine end internal def self.wait end_turn 1 end internal def self.end_turn input_delay World.turn = :npc Input.disable_for input_delay Camera.set_dirty end end
# == Schema Information # # Table name: responses # # id :integer not null, primary key # user_id :integer not null # answer_choice_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Response < ApplicationRecord # validates_uniqueness_of :user_id, :answer_choice_id # validate :cannot_answer_twice, :cannot_answer_own_question # def sibling_responses belongs_to :respondent, primary_key: :id, foreign_key: :user_id, class_name: :User belongs_to :answer_choice, primary_key: :id, foreign_key: :answer_choice_id, class_name: :AnswerChoice has_one :question, through: :answer_choice, source: :question has_one :author, through: :question, source: :author def sibling_responses question.responses.where.not(id: @id) end def respondent_already_answered? !sibling_responses.where(user_id: @user_id).nil? end def cannot_answer_twice if respondent_already_answered? errors[:respondent] << 'cannot answer twice' end end def cannot_answer_own_question if answer_choice.question.poll.author.id == @user_id errors[:respondent] << 'cannot be the author' end end end
class AddIndexToTeamsTeamName < ActiveRecord::Migration def change add_index :teams, :team_name, unique: true #Should consider how to enforce case insensitivity at the db level. end end
class UsersController < ApiController # Don't do any of this if when a user is registering before_action :require_login, except: [:create, :test] # Tests connection between backend and UI def test render json: { message: 'Hello World' } end # Create user with data from the registration form def create user = User.create!(user_params) render json: { token: user.auth_token } end # Fetch user def profile user = User.find_by_auth_token!(request.headers[:token]) render json: user.profile_info end private def user_params # Specify that only a user object will be accepted with these keys params.require(:user).permit(:username, :email, :password, :first_name, :last_name) end end
require 'time' require 'json' require 'openssl' require 'aws-sdk-ssm' require 'aws-sdk-sts' require 'uri' require 'net/http' module Api class BadRequest < StandardError; end class NotFound < StandardError; end class Forbidden < StandardError; end class << self def sts @sts ||= Aws::STS::Client.new end def ssm @ssm ||= Aws::SSM::Client.new end def region @region ||= ssm.config.region end def client_role_arn @client_role_arn ||= ENV.fetch('S3COLLECT_CLIENT_ROLE_ARN') end def files_bucket @files_bucket ||= ENV.fetch('S3COLLECT_FILES_BUCKET') end def psk_secret @psk_secret ||= ENV.fetch('S3COLLECT_PSK_SECRET') end def slack_webhook_url @slack_webhook_url ||= URI.parse(ENV.fetch('S3COLLECT_SLACK_WEBHOOK_URL')) end def psks @psks ||= {} end def get_psk(name) return psks[name] if psks[name] psks[name] ||= ssm.get_parameter(name: psk_secret, with_decryption: true).parameter.value.each_line.find { |_| _.start_with?("#{name}:") }&.split(?:,2)&.last&.unpack1('m*') end Token = Struct.new(:version, :key, :signature, :expiry, :campaign) do def complete? version && key && signature && campaign && expiry end def signature_payload "#{expiry}:#{campaign}" end end def verify_token(token_str) return nil unless token_str token = Token.new(*token_str.split(?:,5)) return nil unless token.complete? psk = get_psk(token.key) return nil unless psk return nil if Time.now > Time.at(token.expiry.to_i) expected_signature = OpenSSL::HMAC.hexdigest("sha384", psk, token.signature_payload) return nil unless secure_compare(expected_signature, token.signature) return token end ContinuationHandler = Struct.new(:version, :signature, :expiry, :session_prefix) do def complete? version && signature && expiry && session_prefix end def signature_payload "#{expiry}:#{session_prefix}" end end def verify_continuation_handler(key, handler_str) return nil unless handler_str handler = ContinuationHandler.new(*handler_str.split(?:,4)) return nil unless handler.complete? psk = get_psk(key) return nil unless psk return nil if Time.now > Time.at(handler.expiry.to_i) expected_signature = OpenSSL::HMAC.hexdigest("sha384", psk, handler.signature_payload) return nil unless secure_compare(expected_signature, handler.signature) return handler end def create_continuation_handler(key, prefix, expires_in: 3600) psk = get_psk(key) handler = ContinuationHandler.new('1', nil, (Time.now + expires_in).to_i.to_s, prefix) signature = OpenSSL::HMAC.hexdigest('sha384', psk, handler.signature_payload) "#{handler.version}:#{signature}:#{handler.expiry}:#{handler.session_prefix}" end def handler(event:, context:) p id: context.aws_request_id, event: event, context: context resp = case event.fetch('routeKey') when 'POST /sessions' return post_sessions(event, context) when 'POST /complete' return post_complete(event, context) else raise NotFound, "404: #{event.fetch('routeKey')}" end p(id: context.aws_request_id, response: {status: response['statusCode'], body: (400..499).cover?(response['statusCode']) ? response['body'] : nil}) rescue BadRequest => e $stderr.puts e.full_message return {'isBase64Encoded' => false, 'statusCode' => 400, 'headers' => {'Content-Type': 'application/json'}, 'body' => {message: e.message}.to_json} rescue NotFound => e $stderr.puts e.full_message return {'isBase64Encoded' => false, 'statusCode' => 404, 'headers' => {'Content-Type': 'application/json'}, 'body' => {message: e.message}.to_json} rescue Forbidden => e $stderr.puts e.full_message return {'isBase64Encoded' => false, 'statusCode' => 403, 'headers' => {'Content-Type': 'application/json'}, 'body' => {message: e.message}.to_json} end def post_sessions(event, context) body = JSON.parse(event.fetch('body') || '') name = body&.dig('name') or raise BadRequest, "name is missing" raise BadRequest, "name has an invalid format" unless name.match?(/\A[a-zA-Z0-9._\-]{1,20}\z/) token = verify_token(body&.fetch('token')) or raise Forbidden, "token is invalid; likely mistyped or expired" time = Time.at(event.fetch('requestContext').fetch('timeEpoch')/1000).utc.iso8601.gsub(':','').gsub('-','') session_prefix = case when body['continuation_handler'] (verify_continuation_handler(token.key, body['continuation_handler']) or raise BadRequest, "invalid continuation_handler") .session_prefix else "#{time}--#{context.aws_request_id}" end prefix = "#{token.campaign}/#{name}/#{session_prefix}/" role_session = sts.assume_role( duration_seconds: 3600, role_arn: client_role_arn, role_session_name: "#{name.gsub(/[_ ]/,'-')}@#{context.aws_request_id}", policy: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: %w( s3:PutObject ), Resource: "arn:aws:s3:::#{files_bucket}/#{prefix}*", Condition: { StringEqualsIfExists: { "s3:x-amz-storage-class" => "STANDARD", }, Null: { "s3:x-amz-server-side-encryption" => true, "s3:x-amz-server-side-encryption-aws-kms-key-id" => true, "s3:x-amz-website-redirect-location" => true, # These cannot be applied unless a bucket has ObjectLockConfiguration, but to ensure safety "s3:object-lock-legal-hold" => true, "s3:object-lock-retain-until-date" => true, "s3:object-lock-remaining-retention-days" => true, # ACLs cannot be applied unless s3:PutObjectAcl }, }, }, { Effect: 'Allow', Action: %w( s3:AbortMultipartUpload ), Resource: "arn:aws:s3:::#{files_bucket}/#{prefix}*", }, ], }.to_json, ) { 'statusCode' => 200, 'isBase64Encoded' => false, 'headers' => {'Content-Type' => 'application/json'}, 'body' => { region: region, bucket: files_bucket, prefix: prefix, use_accelerated_endpoint: true, refresh_after: 3500, continuation_handler: create_continuation_handler(token.key, session_prefix), credentials: { access_key_id: role_session.credentials.access_key_id, secret_access_key: role_session.credentials.secret_access_key, session_token: role_session.credentials.session_token, }, }.to_json, } rescue JSON::ParserError raise BadRequest, "Payload has an invalid JSON" end def post_complete(event, context) body = JSON.parse(event.fetch('body') || '') name = body&.dig('name') or raise BadRequest, "name is missing" raise BadRequest, "name has an invalid format" unless name.match?(/\A[a-zA-Z0-9._\-]{1,20}\z/) token = verify_token(body&.fetch('token')) or raise Forbidden, "token is invalid; likely mistyped or expired" session_prefix = (verify_continuation_handler(token.key, body['continuation_handler']) or raise BadRequest, "invalid continuation_handler") .session_prefix prefix = "#{token.campaign}/#{name}/#{session_prefix}/" s3_console_url = "https://s3.console.aws.amazon.com/s3/buckets/#{URI.encode_www_form_component(files_bucket)}/#{prefix}" Net::HTTP.post_form( slack_webhook_url, payload: {text: ":mailbox: #{name} uploaded files to #{token.campaign} (<#{s3_console_url}|S3 console>)"}.to_json, ) { 'statusCode' => 200, 'isBase64Encoded' => false, 'headers' => {'Content-Type' => 'application/json'}, 'body' => { ok: true, }.to_json, } rescue JSON::ParserError raise BadRequest, "Payload has an invalid JSON" end ## # https://github.com/rack/rack/blob/master/lib/rack/utils.rb # https://github.com/rack/rack/blob/master/MIT-LICENSE def secure_compare(a, b) return false unless a.bytesize == b.bytesize l = a.unpack("C*") r, i = 0, -1 b.each_byte { |v| r |= v ^ l[i += 1] } r == 0 end end end def handler(event:, context:) Api.handler(event: event, context: context) end
class AddGenreToSongs < ActiveRecord::Migration[5.2] change_column :songs, :genre_id, :integer end
class CharacterImage < ActiveRecord::Base belongs_to :character # paperclip options has_attached_file :photo, :styles => { :small => "190x190#", :tiny => "50x50#", :large => "320x240>" }, :default_url => "/images/missing.jpg" validates_attachment_presence :photo validates_attachment_size :photo, :less_than => 5.megabytes end
class User < ApplicationRecord has_secure_token :api_token has_secure_password end
module AdminPage module ProtocolDrugs class Edit < ApplicationPage NAME = {id: "medication_name"}.freeze MEDICATION_DOSAGE = {id: "medication_dosage"}.freeze RX_NORM_CODE = {id: "medication_rxnorm_code"}.freeze UPDATE_MEDICATION_BUTTON = {css: "input.btn-primary"}.freeze MEDICATION_LIST_NAME_HEADING = {css: "h1"}.freeze def edit_medication_info(dosage, code) present?(MEDICATION_LIST_NAME_HEADING) type(MEDICATION_DOSAGE, dosage) type(RX_NORM_CODE, code) click(UPDATE_MEDICATION_BUTTON) # assertion page.has_content?("Medication was successfully updated") end end end end
# require_relative 'customer_repository' # require_relative 'invoice_repository' # require_relative 'invoiceitem_repository' # require_relative 'item_repository' # require_relative 'merchant_repository' # require_relative 'transaction_repository' class SalesEngine attr_reader :merchant_repository, :invoice_repository, :item_repository, :invoice_item_repository, :customer_repository, :transaction_repository, :filepath def initialize(filepath=nil) @filepath = filepath @merchant_file = 'test/fixtures/merchants_fixtures.csv' @invoice_file = 'test/fixtures/invoices_fixtures.csv' @item_file = 'test/fixtures/items_fixtures.csv' @item_invoice_file = 'test/fixtures/invoice_items_fixtures.csv' @customer_file = 'test/fixtures/customers_fixtures.csv' @transaction_file = 'test/fixtures/transactions_fixtures.csv' end def startup @merchant_repository = MerchantRepository.new(@merchant_file, self) @invoice_repository = InvoiceRepository.new(@invoice_file, self) @item_repository = ItemRepository.new(@item_file, self) @invoice_item_repository = InvoiceItemRepository.new(@item_invoice_file, self) @customer_repository = CustomerRepository.new(@customer_file, self) @transaction_repository = TransactionRepository.new(@transaction_file, self) end def find_invoices_by_customer_id(id) item_repository.find_all_by_id(id) end def find_transactions_by_invoice_id(id) transaction_repository.find_all_by_invoice_id(id) end def find_invoice_items_by_invoice_id invoice_item_repository.find_all_by_invoice_id(id) end def find_items_by(id)     sales_engine.find_items_by_merchant_id(id)   end def find_invoices_by(id)     sales_engine.find_invoices_by_merchant_id(id)   end def find_items_by_invoice_id(id) items = invoice_item_repository.find_all_by_invoice_id(id) items.map { |e| item_repository.find_by_id(e.item_id)} item_repository.find_by_id(invoice_item.item_id) end def find_by_customer_id(id) customer_repository.find_by_id(id) end def find_by_merchant_id(id) merchant_repository.find_by_id(id) end def find_invoice(id) invoice_repository.find_by_id(id) end def find_invoice_items_by_item_id(id)     invoice_item_repository.find_by_id(id)   end def find_merchant_by_merchant_id(id)     merchant_repository.find_by_id(id)   end # sales_engine = SalesEngine.new(nil) # sales_engine.startup end
class PatientSummary < ActiveRecord::Base self.primary_key = :id belongs_to :patient, foreign_key: :id belongs_to :next_appointment, class_name: "Appointment", foreign_key: :next_appointment_id scope :overdue, -> { joins(:next_appointment).merge(Appointment.overdue) } scope :all_overdue, -> { joins(:next_appointment).merge(Appointment.all_overdue) } scope :passed_unvisited, -> { joins(:next_appointment).merge(Appointment.passed_unvisited) } scope :last_year_unvisited, -> { joins(:next_appointment).merge(Appointment.last_year_unvisited) } belongs_to :latest_bp_passport, class_name: "PatientBusinessIdentifier", foreign_key: :latest_bp_passport_id has_many :current_prescription_drugs, -> { where(is_deleted: false).order(created_at: :desc) }, class_name: "PrescriptionDrug", foreign_key: :patient_id def latest_blood_pressure_to_s [latest_blood_pressure_systolic, latest_blood_pressure_diastolic].join("/") end def readonly? true end end
class UserExamAnswerFacade attr_reader :params, :session def initialize(params, session) @params = params @params[:answer] ||= {} @session = session @question = Question.find session[:current_question_id] end def rate! case @question.form when 'single' single_answer when 'multiple' multiple_answer when 'open' open_answer # else # fail ArgumentError, 'invalid question type' end end private def single_answer id = params[:answer][:id] u = UserAnswer.create(user_exam_id: session[:user_exam_id], answer_id: id, question_id: @question.id) session[:result] += @question.value if u.correct end def multiple_answer ids = params[:answer].fetch(:id) { [nil] } correct, wrong = 0, 0 ids.each do |i| u = UserAnswer.create(user_exam_id: session[:user_exam_id], answer_id: i, question_id: @question.id) next if i.to_i.zero? u.correct ? correct += 1 : wrong += 1 end diff = correct > wrong ? correct - wrong : 0 session[:result] += (diff.to_f) * @question.value / @question.correct_answers.size end def open_answer text = params[:answer].fetch(:text) { ' ' } u = UserAnswer.create(user_exam_id: session[:user_exam_id], text: text, question_id: @question.id) session[:result] += @question.value if u.correct end end
require 'spec_helper' describe MovieLibrary do it_behaves_like "a collection" before(:each) do MovieLibrary.class_variable_set(:@@main_instance, nil) MovieLibrary.create_main_instance end let(:library) {MovieLibrary.new} let(:valid_movie) {Movie.new("Blade Runner", "Do androids dream of electric sheep", "1982", "Sci Fi") } let(:movie_two) {Movie.new("Dirty Harry", "Do you feel lucky", "1971", "Thriller") } describe "create_main_instance" do it "should set the main instance" do MovieLibrary.main_instance.size.should == 0 MovieLibrary.main_instance << valid_movie MovieLibrary.main_instance.size.should == 1 end it "should allow main_instance to be shared between movie library instances" do user1 = Customer.new("test","pass") user2 = Customer.new("test2","pass") user1.main_library.should == MovieLibrary.main_instance user2.main_library.should == MovieLibrary.main_instance end end describe "add movie" do it "should allow you to add a movie to the library" do library.size.should == 0 library << valid_movie library.size.should == 1 end end describe "remove movie" do it "should allow you to remove a movie from the library" do library.size.should == 0 library << valid_movie library.size.should == 1 library.delete(valid_movie) library.size.should == 0 end end describe "find" do it "should return a movie if it is found in the customer queue" do library.size.should == 0 library << valid_movie library.find(valid_movie.title).should == valid_movie end end end
module Configer class Value def get_name; @name; end def get_docu; @docu; end def has_valid_type? return @type && @type.respond_to?(:to_config_s) && @type.respond_to?(:from_config_s) end def get_value; return @value; end def set_value(val) if @type && !val.is_a?(@type) && !@type.include?(Configer::DummyType) raise "invalid value #{val}(#{val.class}) for type #{@type}" end return @value=val end def from_config_s(value) if has_valid_type?() && value.is_a?(String) return @value=@type.from_config_s(value) end return @value=value end def to_config_s if has_valid_type? && (@value.is_a?(@type) || @type.include?(Configer::DummyType)) return @type.to_config_s(@value) end return @value end def to_json_hash h=Hash.new h["##{@name}_desc"]=@docu if @docu h[@name]=to_config_s return h end def initialize(params) @name,@type,@default,@value,@docu=nil,nil,nil,nil,nil params.each_pair do |key,value| case key when :name @name=value when :type @type=value when :default @default=value set_value(value) when :docu @docu=value else raise "unknown parameter Value#{key}" end end end end end
require 'stax/aws/ecr' module Stax class Docker < Base no_commands do ## default to ECR registry for this account def docker_registry @_docker_registry ||= "#{aws_account_id}.dkr.ecr.#{aws_region}.amazonaws.com" end ## name the docker repo after the git repo def docker_repository @_docker_repository ||= File.basename(Git.toplevel) end ## full image name for docker push def docker_image @_docker_image ||= "#{docker_registry}/#{docker_repository}" end ## build a docker image locally def docker_build debug("Docker build #{docker_image}") system "docker build -t #{docker_image} #{Git.toplevel}" end ## push docker image from local def docker_push debug("Docker push #{docker_image}") system "docker push #{docker_image}" end end desc 'registry', 'show registry name' def registry puts docker_registry end desc 'repository', 'show repository name' def repository puts docker_repository end desc 'image', 'show image name' def image puts docker_image end ## override this method with the desired builder desc 'build', 'build docker image' def build docker_build end desc 'login', 'login to registry' def login Aws::Ecr.auth.each do |auth| debug("Login to ECR registry #{auth.proxy_endpoint}") user, pass = Base64.decode64(auth.authorization_token).split(':') system "docker login -u #{user} -p #{pass} #{auth.proxy_endpoint}" end end desc 'push', 'push docker image to registry' def push docker_push end desc 'exists', 'check if docker image exists in ECR' def exists puts Aws::Ecr.exists?(docker_repository, Git.sha) end desc 'poll', 'poll ECR until docker image exists' def poll debug("Waiting for image in ECR #{docker_repository}:#{Git.sha}") sleep 10 until Aws::Ecr.exists?(docker_repository, Git.sha) end end end
class Profile < ActiveRecord::Base belongs_to :user validates :first_name, presence: true, if: 'last_name.nil?' validates :last_name, presence: true, if: 'first_name.nil?' validate :gender_valid validate :sue_valid def gender_valid if gender != 'male' && gender != 'female' errors.add(:gender, 'invalid gender') end end def sue_valid if first_name == 'Sue' && gender == 'male' errors.add(:gender, 'invalid gender') end end def self.get_all_profiles(min, max) Profile.where(:birth_year => min..max).order(birth_year: :asc) end end
require 'test/unit' require 'open-uri' require_relative 'web_page' require_relative 'interaction' # tests the understanding of a web page class TestWebPage < Test::Unit::TestCase def test_case_url_equal assert(DEFAULT_WEB_PAGE == DEFAULT_WEB_PAGE) assert_equal(false, DEFAULT_WEB_PAGE == WebPage.new('http://bbc.co.uk')) assert_raise(RuntimeError) { WebPage.new('bbc.co.uk') } end def test_case_retrieve_facebook_interactions if internet_connection? DEFAULT_WEB_PAGE.retrieve_facebook_interactions() assert(is_number?(DEFAULT_WEB_PAGE.facebook_shares())) end end private def internet_connection? begin true if open("http://www.google.com/") rescue false end end def is_number?(other) true if Float(other) rescue false end DEFAULT_PAGE_VIEW = Interaction.new(1,Interaction::PAGE_VIEW) DEFAULT_URL = 'http://metro.co.uk/2013/04/30/revealed-the-gadget-that-tells-your-facebook-friends-how-drunk-you-are-3708597/' DEFAULT_WEB_PAGE = WebPage.new(DEFAULT_URL) end
class SubmittalSerializer < ActiveModel::Serializer attributes :id, :plan_id, :data, :is_accepted, :created_at has_one :user has_one :plan has_many :attachments end
class Status < ActiveRecord::Base attr_accessible :description, :priority, :title has_many :servers validates :title, presence: true validates :description, presence: true validates :priority, presence: true end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "puppetlabs/ubuntu-14.04-64-puppet" config.vm.network :private_network, ip: "192.168.33.33" config.vm.network :forwarded_port, host: 3306, guest: 3306 config.vm.hostname = "mysql.box" config.vm.provision :puppet do |puppet| puppet.manifests_path = 'puppet/manifests' puppet.module_path = 'puppet/modules' puppet.manifest_file = 'init.pp' # puppet.options = "--verbose --debug" end end
namespace :rbenv do desc "Setup the rbenv-vars for application" task :setup do content ="RAILS_ENV=production\n" rbenv_vars_file = "#{shared_path}/.rbenv-vars" run_locally do secret_key = capture "rails secret" content << "SECRET_KEY_BASE=#{secret_key}\n" end on roles(:app) do if test "[[ ! -f #{rbenv_vars_file} ]]" upload!(StringIO.new(content), rbenv_vars_file) end end end end
module Opity module Version MAJOR = 0 MINOR = 1 TINY = 0 TAG = 'beta0' LIST = [MAJOR, MINOR, TINY, TAG] STRING = LIST.compact.join(".") end end
Pod::Spec.new do |s| s.name = 'ErxesSDK' s.version = '0.5.0' s.summary = 'A short description of erxes-ios-sdk.' s.swift_version = '5.0' s.description = 'erxes for IOS SDK, for integrating erxes into your iOS application https://erxes.io/' s.homepage = 'https://github.com/erxes/erxes-ios-sdk' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'erxes' => 'info@erxes.io' } s.source = { :git => 'https://github.com/erxes/erxes-ios-sdk.git', :tag => s.version.to_s } s.ios.deployment_target = '9.0' s.source_files = 'ErxesSDK/Classes/**/*' s.resource_bundles = { 'ErxesSDK' => ['ErxesSDK/Assets/**/*.{jpg,storyboard,png,ttf,gif,strings,lproj}'] } s.pod_target_xcconfig = {'DEFINES_MODULE' => 'YES','SWIFT_VERSION' => '5.0'} s.frameworks = 'Photos' s.dependency 'Apollo', '~> 0.15.0' s.dependency 'Apollo/WebSocket' s.dependency 'Apollo/SQLite' s.dependency 'Fusuma', '~> 1.3.0' s.dependency 'Alamofire', '~> 4.8.0' s.dependency 'SDWebImage', '~> 5.1.0' s.dependency 'SnapKit', '~> 4.2.0' s.dependency 'ErxesFont','~> 1.0.1' end
class ManageIQ::Providers::Amazon::NetworkManager::NetworkRouter < ::NetworkRouter def self.display_name(number = 1) n_('Network Router (Amazon)', 'Network Routers (Amazon)', number) end end
require_relative 'acceptance_helper' feature 'Change email', %q{ In order to use real email As a new user I want to be able to change temporary email } do given(:user) { create(:user) } scenario 'User setting new email' do sign_in(user) visit set_email_user_path(user) fill_in 'user[email]', :with => 'new_custom_made_email@test.com' click_on 'Update' expect(page).to have_text "Hello, new_custom_made_email@test.com" end end
class PrintSpeed < ApplicationRecord has_many :items validates :configuration, presence: true end
require "application_system_test_case" class MydbsTest < ApplicationSystemTestCase setup do @mydb = mydbs(:one) end test "visiting the index" do visit mydbs_url assert_selector "h1", text: "Mydbs" end test "creating a Mydb" do visit mydbs_url click_on "New Mydb" fill_in "Email", with: @mydb.email fill_in "Image", with: @mydb.image fill_in "Title", with: @mydb.title fill_in "Vid Link", with: @mydb.vid_link click_on "Create Mydb" assert_text "Mydb was successfully created" click_on "Back" end test "updating a Mydb" do visit mydbs_url click_on "Edit", match: :first fill_in "Email", with: @mydb.email fill_in "Image", with: @mydb.image fill_in "Title", with: @mydb.title fill_in "Vid Link", with: @mydb.vid_link click_on "Update Mydb" assert_text "Mydb was successfully updated" click_on "Back" end test "destroying a Mydb" do visit mydbs_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Mydb was successfully destroyed" end end
class DocumentationsController < ApplicationController before_action :set_documentation, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! skip_before_filter :verify_authenticity_token # GET /documentations # GET /documentations.json def index @documentations = Documentation.all end # GET /documentations/new def new Documentation.reload @documentations = Documentation.all render :index end # GET /documentations/1/edit def edit end # PATCH/PUT /documentations/1 # PATCH/PUT /documentations/1.json def update respond_to do |format| if @documentation.update(documentation_params) format.html { redirect_to @documentation, notice: 'Documentation was successfully updated.' } format.json { render :show, status: :ok, location: @documentation } else format.html { render :edit } format.json { render json: @documentation.errors, status: :unprocessable_entity } end end end def show set_documentation render file: @documentation.page('index.html'), layout: false end def page set_documentation render file: @documentation.page("#{params[:page]}.#{params[:format]}"), layout: false end private # Use callbacks to share common setup or constraints between actions. # @return [Documentation] def set_documentation @documentation = Documentation.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def documentation_params params[:documentation] end end
class JobSerializer include JSONAPI::Serializer attributes :company, :position, :application_link, :status, :created_at, :updated_at attribute :steps do |object| object.steps.each do |step| end end end
require_relative 'board' class Debugger attr_reader :board def initialize(board) @board = board end def inspect(pos, selection_mode, current_player) puts "\n\n\n\n DEBUGGER:" space = board[pos] puts "Class: #{space.class}" puts "Color: #{space.color}" puts "Selection mode: #{selection_mode}" puts "Current Player: #{current_player.color}" puts "Current player in check? #{board.in_check?(current_player.color)}" puts "Temporary moves: #{space.temporary_moves}" puts "Valid moves: #{space.valid_moves}" end end class OffBoardError < StandardError end
class CreateCategoriesTable < ActiveRecord::Migration def change create_table :categories do |t| t.string :name t.timestamps end end end
class DuplicateHotelRecord < ActiveRecord::Base validates :cleartrip_hotel_id, uniqueness: { scope: :yatra_hotel_id } belongs_to :cleartrip_hotel, foreign_key: 'cleartrip_hotel_id', class_name: 'Hotel' belongs_to :yatra_hotel, foreign_key: 'yatra_hotel_id', class_name: 'Hotel' def self.create_records(hotel_id, city_id, similar_hotels_ids=[]) duplicate_records = [] similar_hotels_ids.each do |duplicate_hotel_id| duplicate_records << new(cleartrip_hotel_id: hotel_id, yatra_hotel_id: duplicate_hotel_id, city_id: city_id) end import duplicate_records end end
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :relationships, foreign_key: :following_id has_many :followings, through: :relationships, source: :follower has_many :reverse_of_relationships, class_name: "Relationship", foreign_key: :follower_id has_many :followers, through: :reverse_of_relationships, source: :following has_many :comments has_many :likes, dependent: :destroy has_many :recipes, dependent: :destroy def already_liked?(recipe) self.likes.exists?(recipe_id: recipe.id) end def is_followed_by?(user) reverse_of_relationships.find_by(following_id: user.id).present? end has_many :recipes, dependent: :destroy attachment :profile_image validates :username, presence: true end
ActiveAdmin.register Country do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :name, :language # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if params[:action] == 'create' && current_user.admin? # permitted # end index do column :name column :language actions end config.filters = false end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Xapit::FacetOption do it "should combine previous identifiers with current one on to_param" do option = Xapit::FacetOption.new(nil, nil, nil) option.existing_facet_identifiers = ["abc", "123"] stub(option).identifier { "foo" } option.to_param.should == "abc-123-foo" end it "should remove current identifier from previous identifiers if it exists" do Xapit.setup(:breadcrumb_facets => false) option = Xapit::FacetOption.new(nil, nil, nil) option.existing_facet_identifiers = ["abc", "123", "foo"] stub(option).identifier { "foo" } option.to_param.should == "abc-123" end it "should support breadcrumb style facets" do Xapit.setup(:breadcrumb_facets => true) option = Xapit::FacetOption.new(nil, nil, nil) option.existing_facet_identifiers = ["abc", "123", "foo"] stub(option).identifier { "123" } option.to_param.should == "abc-123" end describe "with database" do before(:each) do XapitMember.xapit do |index| index.facet :age, "Person Age" index.facet :category end end it "should have identifier hashing name and value" do option = Xapit::FacetOption.new("XapitMember", "age", "17") option.identifier.should == "0c93ee1" end it "should find facet option from database given id" do doc = Xapian::Document.new doc.data = "XapitMember|||age|||17" doc.add_term("QXapit::FacetOption-abc123") Xapit::Config.writable_database.add_document(doc) option = Xapit::FacetOption.find("abc123") option.name.should == "17" option.facet.name.should == "Person Age" end it "should save facet to database" do Xapit::Config.writable_database # make sure there's a database setup in case we try to read from it option = Xapit::FacetOption.new(nil, nil, nil) option.facet = XapitMember.xapit_facet_blueprint("age") option.name = "23" option.save Xapit::FacetOption.find(option.identifier).should_not be_nil end it "should not save facet if it already exists" do doc = Xapian::Document.new doc.data = "XapitMember|||age|||17" doc.add_term("QXapit::FacetOption-abc123") Xapit::Config.writable_database.add_document(doc) stub(Xapit::Config.writable_database).add_document { raise "should not add doc" } option = Xapit::FacetOption.new(XapitMember, nil, nil) stub(option).identifier { "abc123" } option.save end it "should find facet option which doesn't have a value" do doc = Xapian::Document.new doc.data = "XapitMember|||age|||" doc.add_term("QXapit::FacetOption-abc123") Xapit::Config.writable_database.add_document(doc) option = Xapit::FacetOption.find("abc123") option.name.should == "" option.facet.name.should == "Person Age" end end end
class Task attr_accessor :name, :parent def initialize(name) @name = name @parent = nil end def get_time_required 0.0 end def total_number_basic_tasks 1 end end class CompositeTask < Task def initialize(name) super(name) @sub_tasks = [] end def add_sub_task(task) @sub_tasks << task task.parent = self end def remove_sub_task(task) @sub_tasks.delete(task) task.parent = nil end def total_number_basic_tasks total = 0 @sub_tasks.each {|task| total += task.total_number_basic_tasks} total end # def <<(task) # @sub_tasks << task # end # # def [](index) # @sub_tasks[index] # end # # def remove_sub_task(task) # @sub_tasks.delete(task) # end # # def []=(index, new_value) # @sub_tasks[index] = new_value # end def get_time_required time=0.0 @sub_tasks.each {|task| time += task.get_time_required} time end end #Composite task class MakeBatterTask < CompositeTask def initialize super('Make batter') add_sub_task( AddDryIngredientsTask.new ) add_sub_task( AddLiquidsTask.new ) add_sub_task( MixTask.new ) end end #Leaf task class AddDryIngredientsTask < Task def initialize super('Add dry ingredients') end def get_time_required 1.0 # 1 minute to add flour and sugar end end #Leaf task class MixTask < Task def initialize super('Mix that batter up!') end def get_time_required 3.0 # Mix for 3 minutes end end
class Api::V4::FacilityMedicalOfficersController < APIController def sync_to_user medical_officers = current_facility_group.facilities .eager_load(teleconsultation_medical_officers: :phone_number_authentications) .map { |facility| facility_medical_officers(facility) } render json: to_response(medical_officers) end private def facility_medical_officers(facility) {id: facility.id, facility_id: facility.id, medical_officers: transform_medical_officers(facility.teleconsultation_medical_officers), created_at: Time.current, updated_at: Time.current, deleted_at: nil} end def transform_medical_officers(medical_officers) medical_officers.map do |medical_officer| Api::V4::TeleconsultationMedicalOfficerTransformer.to_response(medical_officer) end end def to_response(payload) {facility_medical_officers: payload} end end
RSpec.feature 'Users can signup to site', type: :feature do scenario 'Can visit Signup Page' do visit('/') click_on('Signup') expect(page).to have_content('Please Signup') end scenario 'User can signup' do visit('/') click_on('Signup') fill_in('user[username]', with: 'user1') fill_in('user[email]', with: 'test@test.com') fill_in('user[password]', with: 'password') page.select('Kashyyyk', from: 'user[planet]') click_on('Join the Rebel Alliance') expect(page).to have_content('Congratulations user1, You Have Signed Up to wookiebook!') expect(page).to have_content('Planet: Kashyyyk') expect(page).to have_content('user1') end scenario 'User cannot sign up with email which is already taken' do User.create!(email: 'test@test.com', password: 'password').save visit('/') click_on('Signup') fill_in('user[username]', with: 'user1') fill_in('user[email]', with: 'test@test.com') fill_in('user[password]', with: 'password') page.select('Kashyyyk', from: 'user[planet]') click_on('Join the Rebel Alliance') expect(page).to have_content('Email already taken, please choose another') end scenario 'User cannot sign up with invalid email' do visit('/') click_on('Signup') fill_in('user[username]', with: 'user1') fill_in('user[email]', with: 'test@testcom') fill_in('user[password]', with: 'password') page.select('Kashyyyk', from: 'user[planet]') click_on('Join the Rebel Alliance') expect(page).to have_content('Email format invalid, please enter valid email') end scenario 'User cannot sign up password less than 6 charaters' do visit('/') click_on('Signup') fill_in('user[username]', with: 'user1') fill_in('user[email]', with: 'test@test.com') fill_in('user[password]', with: 'passw') page.select('Kashyyyk', from: 'user[planet]') click_on('Join the Rebel Alliance') expect(page).to have_content('The password must have at least 6 characters') end scenario 'User cannot sign up password more than 10 charaters' do visit('/') click_on('Signup') fill_in('user[username]', with: 'user1') fill_in('user[email]', with: 'test@test.com') fill_in('user[password]', with: 'password10c') page.select('Kashyyyk', from: 'user[planet]') click_on('Join the Rebel Alliance') expect(page).to have_content('The password must have no more than 10 characters') end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'lita/github_pr_list/version' Gem::Specification.new do |spec| spec.name = "lita-github_pr_list" spec.version = Lita::GithubPrList::VERSION spec.authors = ["Michael van den Beuken", "Ruben Estevez", "Jordan Babe", "Mathieu Gilbert", "Ryan Jones", "Darko Dosenovic", "Jonathan Weyermann", "Adam Melnyk"] spec.email = ["michael.beuken@gmail.com", "ruben.a.estevez@gmail.com", "jorbabe@gmail.com", "mathieu.gilbert@ama.ab.ca", "ryan.michael.jones@gmail.com", "darko.dosenovic@ama.ab.ca", "jonathan.weyermann@ama.ab.ca", "adam.melnyk@ama.ab.ca"] spec.summary = %q{List open pull requests for an organization.} spec.description = %q{List open pull requests for an organization.} spec.homepage = "https://github.com/amaabca/lita-github_pr_list" spec.license = "MIT" spec.metadata = { "lita_plugin_type" => "handler" } spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency "lita" spec.add_runtime_dependency "octokit", "~> 3.0" spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "pry" spec.add_development_dependency "rspec" spec.add_development_dependency "rspec-instafail" spec.add_development_dependency "simplecov" end
module BECoding::Direction::Lookup DIRECTIONS = { E: BECoding::Direction::East, W: BECoding::Direction::West, N: BECoding::Direction::North, S: BECoding::Direction::South } def self.init_by_uppercase(uppercase) raise NoDirectionFoundError.new, "No direction found by uppercase: #{uppercase}" unless DIRECTIONS.has_key? uppercase.to_sym DIRECTIONS[uppercase.to_sym].new end class NoDirectionFoundError < StandardError ; end end
module ApiHelpers require "fakeredis" def sign_in(user, password=nil, extra_params={}) password ||= 'secret123' params = { email: user.email, password: password }.merge(extra_params) post "/api/v1/users/sign_in", params.to_json, json_headers expect(response).to have_http_status 201 sign_in_info = JSON.parse(response.body) sign_in_info['user'] end def sign_out(user, email, auth_token) params = { } headers = add_authentication_to_headers(json_headers, email, auth_token) delete "/api/v1/users/sign_out", params.to_json, headers expect(response).to have_http_status 204 end def json_headers { 'Content-Type' => 'application/json', 'Accept' => 'application/json', } end def add_authentication_to_headers(headers, email, auth_token) headers['X-API-EMAIL'] = email headers['X-API-TOKEN'] = auth_token headers end def create_user(options={}) user = FactoryGirl.create :user, options expect(user.id).to be_present user.confirm user end def normal_user_sign_in_path "/auth/users/sign_in" # http://stackoverflow.com/questions/23140117/allow-a-user-to-add-new-users-in-devise-and-remain-logged-in-as-themselves # "/users/sign_in" end end
class BaseApiController < ApplicationController skip_before_filter :verify_authenticity_token, :only => [:show, :update, :destroy, :create, :authenticate] include ExceptionHandler before_action :authorize_request, :base_url attr_reader :current_user private def json_response(object, status = :ok) render json: object, status: status end # Check for valid request token and return user def authorize_request @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user] @exp = (AuthorizeApiRequest.new(request.headers).call)[:exp] end def base_url $base_url = "http://#{request.host}:#{request.port}" end end
module Stylin module NavigationHelper def styleguide_navigation content_for :styleguide_navigation do if APP_CONFIG[:section_groupings] custom_section_navigation else generic_section_navigation end end end def generic_section_navigation elements = [] Styleguide.new.section_names.each do |section_name| elements << section_link(section_name) end content_tag(:ul, elements.join("\n").html_safe) end def custom_section_navigation elements = [] APP_CONFIG[:section_groupings].each do |section, description| sections = Styleguide.new.find(section_group: section) section_links = sections.map do |section| section_link(section.section) end elements << content_tag(:li) do "#{section} #{description}".html_safe + content_tag(:ul, section_links.join("\n").html_safe) end end content_tag(:ul, elements.join("\n").html_safe) end private def section_link(section_name) content_tag(:li, link_to(section_name, styleguide_path(Styleguide.sluggify(section_name)) ) ) end end end
# frozen_string_literal: true class Event < ApplicationRecord has_many :tickets, dependent: :destroy validates :name, :event_date, presence: true end
# クラスの継承 # 親クラス class User def initialize(name) @name = name end def sayHi puts "hello, my name is #{@name}" end end # 継承クラス class SuperUser < User def shout puts "HELLO!! from #{@name}!" # 親クラスのインスタンス変数が使える end end tom = User.new("Tom") bob = SuperUser.new("Bob") tom.sayHi() bob.sayHi() bob.shout()
module HarvestWorld module Web def app @app ||= ($harvest_app ||= Harvest::App.new) end def run_app require 'harvest/http/server' $server = Harvest::HTTP::Server::HarvestHTTPServer.new( harvest_app: app, port: 3000, cache_path: File.expand_path(PROJECT_DIR + "/tmp/cache/3000") ) $server.start end # Not sure why we can't use @app here any more - this should # only ever be called after run_app def reset_app app.reset end private def new_client require 'harvest/clients/harvest_web_client' Harvest::Clients::HarvestWebClient.new("http://localhost:3000/").tap do |client| client.start end end end end
require 'io/console' class Board INITIAL_MARKER = ' ' BOARD_BUFFER = 10 WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + # rows [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + # columns [[3, 5, 7], [1, 5, 9]] # diagonals attr_accessor :spaces def initialize reset end def reset @spaces = ['_'] + [INITIAL_MARKER] * 9 end # rubocop: disable Metrics/AbcSize, Metrics/MethodLength def draw(buffer = BOARD_BUFFER) buffer = ' ' * buffer puts "" puts "#{'Main'.center(17)}#{buffer}#{'Key'.center(17)}" puts "" puts " | | #{buffer} | | " puts " #{self[1]} | #{self[2]} | #{self[3]} #{buffer}" \ " 1 | 2 | 3 " puts " | | #{buffer} | | " puts "-----+-----+-----#{buffer}-----+-----+-----" puts " | | #{buffer} | | " puts " #{self[4]} | #{self[5]} | #{self[6]} #{buffer}" \ " 4 | 5 | 6 " puts " | | #{buffer} | | " puts "-----+-----+-----#{buffer}-----+-----+-----" puts " | | #{buffer} | | " puts " #{self[7]} | #{self[8]} | #{self[9]} #{buffer}" \ " 7 | 8 | 9 " puts " | | #{buffer} | | " end # rubocop: enable Metrics/AbcSize, Metrics/MethodLength def [](index) spaces[index] end def []=(space_number, marker) spaces[space_number] = marker end def empty_spaces empty_spaces_arr = [] spaces.each_with_index do |space, idx| empty_spaces_arr << idx.to_s if space == INITIAL_MARKER end empty_spaces_arr end def joinor(array, delimiter = ', ', ending = 'or') if array.size == 1 array[0] elsif array.size == 2 "#{array[0]} #{ending} #{array[1]}" elsif array.size > 2 "#{array[0..-2].join(delimiter)}#{delimiter[0]} #{ending} #{array[-1]}" end end def space_marked?(space) space != INITIAL_MARKER end def full? empty_spaces.empty? end end class Player attr_accessor :score attr_reader :marker, :name def mark_board(board, space) board[space] = marker end def win?(board) Board::WINNING_LINES.each do |line| if values_per_line(board, marker, line) == 3 return true end end false end def values_per_line(board, marker, line) board.spaces.values_at(*line).count(marker) end end class Human < Player def initialize set_name set_marker @score = 0 end def set_name n = nil loop do puts "What is your name?" n = gets.chomp break if n =~ /\w/ && n !~ /\s/ puts "Invalid name. Please enter only alphanumeric " \ "characters and no whitespace." end @name = n end def set_marker choice = nil loop do puts "Choose a marker: 'X' or 'O'." choice = gets.chomp.upcase break if ['X', 'O'].include?(choice) puts "Invalid choice." end @marker = choice end def moves(board) choice = nil loop do puts "Choose a space: #{board.joinor(board.empty_spaces)}." choice = gets.chomp break if board.empty_spaces.include?(choice) puts "Invalid choice. Please enter an available space." end mark_board(board, choice.to_i) end end class Computer < Player attr_reader :opponent_marker def initialize(opponent_marker) @name = ['R2D2', 'C3PO', 'Wallie', 'Eva', 'Johnny 5'].sample @marker, @opponent_marker = opponent_marker == 'X' ? ['O', 'X'] : ['X', 'O'] @score = 0 end # rubocop: disable Metrics/MethodLength def moves(board) choice = if winning_move?(board) winning_move?(board) elsif block_player?(board) block_player?(board) elsif board[5] == Board::INITIAL_MARKER 5 else board.empty_spaces.sample end mark_board(board, choice.to_i) end # rubocop: enable Metrics/MethodLength def winning_move?(board) Board::WINNING_LINES.each do |line| if values_per_line(board, marker, line) == 2 && values_per_line(board, Board::INITIAL_MARKER, line) == 1 line.each do |pos| return pos if board[pos] == Board::INITIAL_MARKER end end end false end def block_player?(board) Board::WINNING_LINES.each do |line| if values_per_line(board, opponent_marker, line) == 2 && values_per_line(board, Board::INITIAL_MARKER, line) == 1 line.each do |pos| return pos if board[pos] == Board::INITIAL_MARKER end end end false end end class TTTGame SCORE_TO_WIN = 5 GO_FIRST = 'choose' # can also set this to 'human' or 'computer' attr_accessor :current_player, :first_move attr_reader :board, :human, :computer def initialize @board = Board.new @current_player = GO_FIRST @winner = nil @first_move = nil end def clear system('clear') end def continue_game puts "(Press any button to continue)" STDIN.getch print " \r" end def display_beginning_sequence clear puts "Welcome to Tic Tac Toe!" configure_settings puts "#{current_player.name} will go first." puts "First to win #{SCORE_TO_WIN} games will be the grand winner!" continue_game clear end def configure_settings @human = Human.new @computer = Computer.new(human.marker) if current_player == 'choose' choice = who_goes_first? self.current_player = choice == '1' ? human : computer else self.current_player = GO_FIRST == 'human' ? human : computer end self.first_move = current_player end def who_goes_first? puts "Who will go first, #{human.name} or #{computer.name}?" loop do puts "Enter '1' for #{human.name}, '2' for #{computer.name}." choice = gets.chomp return choice if ['1', '2'].include?(choice) puts "Invalid entry." end end def clear_and_display_layout clear display_header board.draw end def display_layout display_header board.draw end def display_header puts "The score is #{human.name}: #{human.score}, " \ "#{computer.name}: #{computer.score}" puts "#{human.name} is a #{human.marker}. " \ "#{computer.name} is a #{computer.marker}." end def alternate_player self.current_player = current_player == human ? computer : human end def display_result # current_player.score += 1 if current_player.win?(board) clear_and_display_layout if current_player.win?(board) # board.someone_win? puts "#{current_player.name} is the winner!" current_player.score += 1 else puts "It's a tie!" end end def grand_winner? human.score == SCORE_TO_WIN || computer.score == SCORE_TO_WIN end def play_again? answer = nil loop do puts "Would you like to play again? (y/n)" answer = gets.chomp.downcase break if %w(y n).include?(answer) puts "Sorry, must be a y or n" end reset(full_reset: true) if answer == 'y' answer == 'y' end def reset(full_reset = false) board.reset self.current_player = first_move if full_reset score_reset display_play_again_message else continue_game clear end end def score_reset human.score = 0 computer.score = 0 end def display_play_again_message clear puts "Let's play again!" puts "" end def display_goodbye_message puts "Thanks for playing Tic Tac Toe! Goodbye!" end # rubocop: disable Metrics/MethodLength, Metrics/AbcSize def play display_beginning_sequence loop do loop do display_layout loop do current_player.moves(board) break if current_player.win?(board) || board.full? alternate_player clear_and_display_layout end display_result break if grand_winner? reset end puts "#{current_player.name} is the Grand Winner!!" break unless play_again? end display_goodbye_message end end # rubocop: enable Metrics/MethodLength, Metrics/AbcSize game = TTTGame.new game.play
# == Schema Information # # Table name: posts # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # title :string(255) # content :text # writer_id :integer # published :boolean default(FALSE) # require 'spec_helper' describe Post do describe "> Post모델 객체의 생성" do it "> 유효한 데이터로 생성한 Post 객체는 유효하다." do expect(create(:post)).to be_valid end end describe "> 유효성 검증" do it "> Title이 없으면 유효하지 않다." do expect(build(:post)).to validate_presence_of :title end it "> Content가 없으면 유효하지 않다." do expect(build(:post)).to validate_presence_of :content end it "> Post 생성시 hit는 0이다." end describe "> 관계선언 검증" do it "> 4개의 Comment를 가지고 있다." end end
# frozen_string_literal: true # https://adventofcode.com/2019/day/14 require 'pry' require './boilerplate' ORE = 'ORE' Ingredient = Struct.new(:amount, :chemical) do def to_s; "Ingredient<#{amount} #{chemical}>"; end end class Reaction < Boilerstate attr :source, :inputs, :output def parse(line) @source = line @inputs, @output = line.split('=>').map(&:strip) @inputs = @inputs.split(',').map(&:strip) @inputs = @inputs.map do |i| amount, chemical = i.split(' ').map(&:strip) Ingredient.new(amount.to_i, chemical) end amount, chemical = @output.split(' ') @output = Ingredient.new(amount.to_i, chemical) end def to_s; "Reaction<#{@source}>"; end end class Solver < Boilerstate attr_accessor :reactions def parse(lines) @reactions = lines.map do |l| reaction = Reaction.new(l) [reaction.output.chemical, reaction] end.to_h end def ore_required_for(amount, chemical, inventory = {}) reaction = @reactions[chemical] # use as much as we can from the existing inventory, either use part of # it or all of it if !inventory[chemical].nil? if amount > inventory[chemical] amount -= inventory[chemical] inventory[chemical] = 0 else inventory[chemical] -= amount return {amount: 0, extra: 0} end end # figure out how many times we need to run this reaction in order to get the # desired amount times = (amount / reaction.output.amount.to_f).ceil chem_produced = (reaction.output.amount * times) # logic for ore, in which we have unlimited amount and is our return # condition, only used when the only input for a reaction is ore if reaction.inputs.length == 1 && reaction.inputs[0].chemical == ORE ore_needed = (reaction.inputs[0].amount * times) return {amount: ore_needed, extra: (chem_produced - amount)} else ore_needed = 0 reaction.inputs.each do |input| required = ore_required_for(input.amount * times, input.chemical, inventory) ore_needed += required[:amount] if required[:extra] > 0 inventory[input.chemical] ||= 0 inventory[input.chemical] += required[:extra] end end {amount: ore_needed, extra: (chem_produced - amount)} end end def fuel_for_ore(ore_amount) ore_for_one_fuel = ore_required_for(1, 'FUEL')[:amount] current_guess = ore_amount / ore_for_one_fuel current_ore = ore_required_for(current_guess, 'FUEL')[:amount] while (current_ore != ore_amount) previous_guess = current_guess current_guess = (current_guess * (((ore_amount - current_ore) / ore_amount.to_f) + 1.0)).round current_ore = ore_required_for(current_guess, 'FUEL')[:amount] # if the guess didn't change we're on the boundary if previous_guess == current_guess if current_ore > ore_amount return current_guess - 1 elsif ore_required_for(current_guess + 1, 'FUEL')[:amount] > ore_amount return current_guess else return current_guess + 1 end end end current_guess end end EXAMPLE_ONE = ['10 ORE => 10 A', '1 ORE => 1 B', '1 ORE => 2 FOO', '7 A, 1 B => 1 C', '7 A, 1 C => 1 D', '7 A, 1 D => 1 E', '7 A, 1 E => 1 FUEL'] EXAMPLE_TWO = ['9 ORE => 2 A', '8 ORE => 3 B', '7 ORE => 5 C', '3 A, 4 B => 1 AB', '5 B, 7 C => 1 BC', '4 C, 1 A => 1 CA', '2 AB, 3 BC, 4 CA => 1 FUEL'] EXAMPLE_THREE = [ '157 ORE => 5 NZVS', '165 ORE => 6 DCFZ', '44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL', '12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ', '179 ORE => 7 PSHF', '177 ORE => 5 HKGWZ', '7 DCFZ, 7 PSHF => 2 XJWVT', '165 ORE => 2 GPVTF', '3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT' ] EXAMPLE_FOUR = [ '2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG', '17 NVRVD, 3 JNWZP => 8 VPVL', '53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL', '22 VJHF, 37 MNCFX => 5 FWMGM', '139 ORE => 4 NVRVD', '144 ORE => 7 JNWZP', '5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC', '5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV', '145 ORE => 6 MNCFX', '1 NVRVD => 8 CXFTF', '1 VJHF, 6 MNCFX => 4 RFSQX', '176 ORE => 6 VJHF', ] part 1 do reaction = Reaction.new('7 A, 1 D => 1 E') assert_call_on(reaction, [Ingredient.new(7, 'A'), Ingredient.new(1, 'D')], :inputs) assert_call_on(reaction, Ingredient.new(1, 'E'), :output) solver = Solver.new(EXAMPLE_ONE) assert_call_on(solver, {amount: 10, extra: 0}, :ore_required_for, 10, 'A') assert_call_on(solver, {amount: 10, extra: 5}, :ore_required_for, 5, 'A') assert_call_on(solver, {amount: 10, extra: 9}, :ore_required_for, 1, 'A') assert_call_on(solver, {amount: 1, extra: 0}, :ore_required_for, 1, 'B') assert_call_on(solver, {amount: 1, extra: 1}, :ore_required_for, 1, 'FOO') assert_call_on(solver, {amount: 1, extra: 0}, :ore_required_for, 2, 'FOO') assert_call_on(solver, {amount: 2, extra: 1}, :ore_required_for, 3, 'FOO') assert_call_on(solver, {amount: 0, extra: 0}, :ore_required_for, 1, 'E', {'E' => 1}) assert_call_on(solver, {amount: 11, extra: 0}, :ore_required_for, 2, 'C', {'C' => 1}) assert_call_on(solver, {amount: 10, extra: 5}, :ore_required_for, 15, 'A', {'A' => 10}) assert_call_on(solver, {amount: 31, extra: 0}, :ore_required_for, 1, 'FUEL') assert_call_on(solver, {amount: 62, extra: 0}, :ore_required_for, 2, 'FUEL') solver = Solver.new(EXAMPLE_TWO) assert_call_on(solver, {amount: 165, extra: 0}, :ore_required_for, 1, 'FUEL') solver = Solver.new(EXAMPLE_THREE) assert_call_on(solver, {amount: 13312, extra: 0}, :ore_required_for, 1, 'FUEL') solver = Solver.new(EXAMPLE_FOUR) assert_call_on(solver, {amount: 180697, extra: 0}, :ore_required_for, 1, 'FUEL') assert_call_on(Solver.new(input), {amount: 1065255, extra: 0}, :ore_required_for, 1, 'FUEL') end part 2 do assert_call_on(Solver.new(EXAMPLE_THREE), 82892753, :fuel_for_ore, 1000000000000) assert_call_on(Solver.new(EXAMPLE_FOUR), 5586022, :fuel_for_ore, 1000000000000) assert_call_on(Solver.new(input), 1766154, :fuel_for_ore, 1000000000000) # !1766155 end
class BootstrapThumbnailResourceRenderer < ResourceRenderer::ResourceRenderer::Base def render(&block) helper.content_tag(:div, { :'data-target' => '#modal-gallery', :'data-toggle' => 'modal-gallery'}) do block.call(self) end end def thumbnail(attribute_name, options = {}, &block) options.reverse_merge!(as: :thumbnail, image_tag_options: { class: 'thumbnail img-responsive' }) helper.content_tag(:div, class: 'col-xs-12 col-sm-6 col-md-4 col-lg-2') do display(attribute_name, options, &block) end end end
# # Author:: Jamie Winsor (<jamie@vialstudios.com>) # Copyright:: 2011, En Masse Entertainment, Inc # License:: Apache License, Version 2.0 # # 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. # RSpec::Matchers.define :have_video_codec do |v_codec| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.video_codec(given) == v_codec.to_s end failure_message_for_should do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected codec #{v_codec}, but got #{analyser.video_codec(given)}" end failure_message_for_should_not do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected codec to not be #{v_codec}, but got #{analyser.video_codec(given)}" end end RSpec::Matchers.define :have_resolution do |resolution| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.resolution(given) == resolution.to_s end end RSpec::Matchers.define :have_frame_rate do |frame_rate| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.frame_rate(given) == frame_rate end failure_message_for_should do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected frame_rate #{frame_rate}, but got #{analyser.frame_rate(given)}" end failure_message_for_should_not do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected frame_rate to not be #{frame_rate}, but got #{analyser.frame_rate(given)}" end end RSpec::Matchers.define :have_bitrate do |bitrate| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.bitrate(given) == bitrate end failure_message_for_should do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected bitrate #{bitrate}, but got #{analyser.bitrate(given)}" end failure_message_for_should_not do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected bitrate to not be #{bitrate}, but got #{analyser.bitrate(given)}" end end RSpec::Matchers.define :have_audio_bitrate do |bitrate| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.audio_bitrate(given) == bitrate end failure_message_for_should do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected audio bitrate #{bitrate}, but got #{analyser.audio_bitrate(given)}" end failure_message_for_should_not do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected audio bitrate to not be #{bitrate}, but got #{analyser.audio_bitrate(given)}" end end RSpec::Matchers.define :have_audio_codec do |audio_codec| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.audio_codec(given) == audio_codec end failure_message_for_should do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected audio_codec #{audio_codec}, but got #{analyser.audio_codec(given)}" end failure_message_for_should_not do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new "Expected audio_codec to not be #{audio_codec}, but got #{analyser.audio_codec(given)}" end end RSpec::Matchers.define :have_audio_channels do |audio_channels| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.audio_channels(given) == audio_channels end end RSpec::Matchers.define :have_audio_sample_rate do |audio_sample_rate| match do |given| analyser = EnMasse::Dragonfly::FFMPEG::Analyser.new analyser.audio_sample_rate(given) == audio_sample_rate end end RSpec::Matchers.define :have_file_extension do |file_extension| match do |given| File.extname(given.path) == file_extension end end
module CassandraObject class RailsInitializer def self.configure! self.new.configure! end def configure! return if cassandra_configs.nil? CassandraObject::Base.config = cassandra_configs[Rails.env || 'development'] end def cassandra_configs @config ||= YAML.load_file(Rails.root.join('config', 'cassandra.yml')) end end end
class Character < ActiveRecord::Base attr_accessible :current_morph, :current_room, :dc_name, :name belongs_to :account belongs_to :current_room, :class_name => "Room" belongs_to :current_morph, :class_name => "Morph" has_many :morphs, :dependent => :destroy has_many :messages has_many :rooms validates :name, :presence => true, :length => { :in => 3..40 } validates :name, :uniqueness => true scope :in_game, joins(:account).where(:accounts => { :in_game => true }) scope :in_room, lambda {|room| in_game.where(:current_room_id => room.id)} def self.named name where(:dc_name => name.downcase).first end def name= n write_attribute :name, n write_attribute :dc_name, n.downcase end def follow exit MessageContent.system_pose self, exit.exit_message update_attribute :current_room, exit.destination MessageContent.system_pose self, exit.enter_message end end
module Sitemod class ModDataManager @@instance = nil attr_reader :mod_directories attr_reader :sitemod_path def reload_mod_directories! if File.directory?(@sitemod_path) @mod_directories = Dir.glob(@sitemod_path + "/**/*/").map do |dir| trim_base(dir) end end end def mods_in_directory(site) path = @sitemod_path + '/' + site mod_files = { "js" => Dir[path + '/*.js'] + Dir[path + '/*.coffee'], "css" => Dir[path + '/*.css'] + Dir[path + '/*.scss'] } mod_files.keys.each do |mod_type| mod_files[mod_type].map! do |file| trim_base(file) end end mod_files end def self.instance @@instance = self.new unless @@instance @@instance end private def initialize @sitemod_path = File.expand_path('~') + '/.sitemod' @mod_directories = [] end def trim_base(str) str.sub(/^#{Regexp.escape(sitemod_path)}\/?/, '').sub(/\/$/, '') end end end
require 'test_helper' class ProductJpsControllerTest < ActionController::TestCase setup do @product_jp = product_jps(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:product_jps) end test "should get new" do get :new assert_response :success end test "should create product_jp" do assert_difference('ProductJp.count') do post :create, product_jp: { long_desc: @product_jp.long_desc, name: @product_jp.name, product_id: @product_jp.product_id, short_desc: @product_jp.short_desc } end assert_redirected_to product_jp_path(assigns(:product_jp)) end test "should show product_jp" do get :show, id: @product_jp assert_response :success end test "should get edit" do get :edit, id: @product_jp assert_response :success end test "should update product_jp" do put :update, id: @product_jp, product_jp: { long_desc: @product_jp.long_desc, name: @product_jp.name, product_id: @product_jp.product_id, short_desc: @product_jp.short_desc } assert_redirected_to product_jp_path(assigns(:product_jp)) end test "should destroy product_jp" do assert_difference('ProductJp.count', -1) do delete :destroy, id: @product_jp end assert_redirected_to product_jps_path end end
RSpec::Matchers.define :be_access do match do |data| @matcher = ::Matchers::BeAccess.new(self, data) @matcher.result end failure_message { |*| @matcher.failure_message } failure_message_when_negated { |*| @matcher.failure_message_when_negated } end RSpec::Matchers.define :be_permissions do match do |data| @matcher = ::Matchers::BeAccess.new(self, data) @matcher.result end failure_message { |*| @matcher.failure_message } failure_message_when_negated { |*| @matcher.failure_message_when_negated } end module Matchers class BeAccess < Struct.new(:rspec, :data) MSGS = { positive: "Expected exactly the following permissions to exist, but they do not:\n\n%s\n\n%s", negative: "Expected exactly the following permissions to not exist, but they do:\n\n%s", data: "User id=%d login=%s, repo id=%d slug=%s, permissions: %s" } def result match errors.empty? end def failure_message MSGS[:positive] % [formatted_data, formatted_errors] end def failure_message_when_negated MSGS[:negative] % [formatted_data] end private def match user_permissions.each do |(user, repo, perms)| expect { rspec.expect(user).to rspec.have_permissions(repo, perms) } end expect { rspec.expect(rspec).to_not rspec.have_permissions_other_than(all_permissions) } end PERMISSIONS = { admin: false, push: false, pull: true } def user_permissions data.inject([]) do |result, (user, repos, *perms)| Array(repos).inject(result) do |result, repo| result << [user, repo, normalize_perms(user, repo, perms)] end end end def all_permissions data.inject([]) do |result, (user, repos, *perms)| Array(repos).inject(result) do |result, repo| result << { user_id: user.id, repository_id: repo.id }.merge(normalize_perms(user, repo, perms)) end end end def normalize_perms(user, repo, perms) perms = expand_permissions(perms) { user_id: user.id, repository_id: repo.id }.merge(perms) end def expand_permissions(perms) perms << :push if perms.include?(:admin) perms.inject(PERMISSIONS.dup) do |perms, key| perms.merge(key => true) end end def expect yield rescue RSpec::Expectations::ExpectationNotMetError => e errors << e.message end def errors @errors ||= [] end def formatted_data data.map do |(user, repos, *perms)| perms = expand_permissions(perms) Array(repos).map do |repo| MSGS[:data] % [user.id, user.login, repo.id, repo.slug, perms.inspect] end end.flatten.join("\n") end def formatted_errors errors.join("\n\n") end end end
class ChangeDurationFormatToCourses < ActiveRecord::Migration[6.0] def change remove_column :courses, :duration, :string add_column :courses, :duration, :integer end end
class PostsController < ApplicationController def index; end def new @post = Post.new @post.languages.build if @post.languages.empty? end def create @post = Post.new(post_params) #byebug @post.languages.build if @post.languages.empty? if @post.save flash[:success] = true redirect_to action: 'new' else render 'new' end end private def post_params params.require(:post).permit(:title, languages_attributes: [:language]) end end
FactoryBot.define do factory :product do name { FFaker::AnimalUS.common_name } category { build(:category) } price { "9.99" } end end
require 'net/http' require 'rexml/document' class Teiden @@APIDomain = "mukku.org" @@APIPath = "/v2.00/TGL/" def initialize(timeGroup, minutesToHalt = 5, minutesToWake = 5) @timeGroup = timeGroup[0..0] @subGroup = timeGroup[1..1] @secToHalt = minutesToHalt * 60 @secToWake = minutesToWake * 60 end def fetch begin xml = Net::HTTP.get(@@APIDomain, @@APIPath) return xml rescue p $! return nil end end def exec xml = self.fetch return if xml.nil? doc = createAndCheck(xml) return if doc.nil? entry = REXML::XPath.first(doc, "//Result/TimeGroup/Group[self::node()='#{@timeGroup}']/../SubGroup[self::node()='#{@subGroup}']/../") unless entry.nil? then cutOffCount = REXML::XPath.first(doc, "//Count/text()").to_s.to_i timeStart = REXML::XPath.first(doc, "//Start/text()").to_s.to_i timeEnd = REXML::XPath.first(doc, "//End/text()").to_s.to_i if cutOffCount == 0 then puts "power cutoff is NOT scheduled."; return end if timeEnd < Time.new.to_i then return end if timeStart < Time.new.to_i + @secToHalt then `logger "Power cutoff is scheduled #{Time.at timeStart} to #{Time.at timeEnd}. Going to halt now!!!"` `echo #{timeEnd + @secToWake} > /sys/class/rtc/rtc0/wakealarm` `shutdown -h now` end end end def createAndCheck(xml) success = false begin doc = REXML::Document.new(xml) unless doc.nil? then doc.elements.each("//TeidenAPI/ResultInfo/Status"){|e| success = true if e.text == "OK" } end rescue end if success then doc else nil end end end # 以下を適宜書き換える teiden = Teiden.new("1E") teiden.exec()
module StoreEngine module TestHelpers def validate_not_found(path, method = "get") lambda { page.driver.send(method, path) }.should raise_error(ActionController::RoutingError) end end end
require "rails_helper" describe ApplicationController, type: :controller do before do setup_application_instance # For authentication a JWT will be included in the Authorization header using the Bearer scheme, # it is signed using the shared secret for the tool and will include the stored consumer key in the # kid field of the token's header object. @token = JWT.encode( { exp: 24.hours.from_now.to_i }, @application_instance.lti_secret, "HS256", { typ: "JWT", alg: "HS256", kid: @application_instance.lti_key }, ) end controller do include CanvasImsccSupport def create render json: { message: "all is well" } end end it "Returns unauthorized if no token is found" do post :create, params: {}, format: :json expect(response).to have_http_status(:unauthorized) end it "Returns unauthorized if the header isn't properly formed" do request.headers["Authorization"] = @token post :create, params: {}, format: :json expect(response).to have_http_status(:unauthorized) json = JSON.parse(response.body) expect(json["message"]).to eq("Unauthorized: Invalid token: Invalid authorization header.") end it "Returns unauthorized if the kid header value has a bad ltt key" do bad_token = JWT.encode( { exp: 24.hours.from_now.to_i }, @application_instance.lti_secret, "HS256", { typ: "JWT", alg: "HS256", kid: "anybadltikey" }, ) request.headers["Authorization"] = bad_token post :create, params: {}, format: :json expect(response).to have_http_status(:unauthorized) json = JSON.parse(response.body) expect(json["message"]).to eq("Unauthorized: Invalid token: Invalid authorization header.") end it "Returns unauthorized if the token has the wrong signature" do bad_token = JWT.encode( { exp: 24.hours.from_now.to_i }, "arandomsecretvalue", "HS256", { typ: "JWT", alg: "HS256", kid: @application_instance.lti_key }, ) request.headers["Authorization"] = "Bearer #{bad_token}" post :create, params: {}, format: :json expect(response).to have_http_status(:unauthorized) json = JSON.parse(response.body) expect(json["message"]).to eq("Unauthorized: Invalid token: Signature verification failed") end it "Returns true if the token is valid" do request.headers["Authorization"] = "Bearer #{@token}" post :create, params: {}, format: :json expect(response).to have_http_status(:success) json = JSON.parse(response.body) expect(json["message"]).to eq("all is well") end it "sets @application_instance" do request.headers["Authorization"] = "Bearer #{@token}" post :create, params: {}, format: :json expect(assigns(:application_instance)).to eq(@application_instance) end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable belongs_to :student #, dependent: :destroy has_many :answers #, dependent: :destroy has_many :comments #, dependent: :destroy mount_uploader :avatar, AvatarUploader def is_admin? return true if self.role == "admin" end def is_student? return true if self.role == "student" end def active_for_authentication? super and self.is_active? end def inactive_message "You are not allowed to log in." end end
# Author:: Derek Wang (mailto:derek.yuanzhi.wang@gmail.com) # Copyright:: # License:: # Description:: # Usage:: class TsServiceDemandBreakdownUsagePattern < ActiveRecord::Base belongs_to :user belongs_to :service_demand_breakdown # validation rules validates :user_id, :presence => true validates_associated :user validates :year, :numericality => {:only_integer => true, :message => "Invalid data format, please use a valid interger!"} validates :month, :numericality => {:only_integer => true, :message => "Invalid data format, please use a valid interger!"} validates :date, :numericality => {:only_integer => true, :message => "Invalid data format, please use a valid interger!"} validates :quantity, :numericality => {:message => "Invalid data format, please use a valid number!"} validates_associated :service_demand_breakdown attr_accessible :year,:month,:date,:quantity,:service_demand_breakdown_id,:current_time # Some helper methods def service_demand_breakdown_identity service_demand_breakdown.nil? ? "" : ServiceDemandBreakdown.column_names.include?('name') ? service_demand_breakdown.name : service_demand_breakdown.id end # Initialise default value for a new instance of a model after_initialize :set_defaults private def set_defaults if new_record? self.year ||= 0 self.month ||= 0 self.date ||= 0 self.quantity ||= 0.0 self.current_time ||= DateTime.now end end end
class Comment < ApplicationRecord validates :content, presence: true belongs_to :post belongs_to :pet has_many :likes, as: :likeable has_many :likers, through: :likes, source: :pet end
class Zombie < ApplicationRecord scope :in_name_order, -> { order(:name) } end
require 'json' require 'base64' require 'rbnacl/libsodium' require 'jwt' NONCE_KEY = 'nonce' TOKEN_KEY = 'encrypted_token' JWT_DATA = 'data' # Service object to retrieve Canvas token from bearer tokens. class DecryptPayload def initialize(bearer_token) @payload = bearer_token @secret_key = Base64.urlsafe_decode64 ENV['SECRET_KEY'] @hmac_secret = Base64.urlsafe_decode64 ENV['HMAC_SECRET'] end def call payload = JWT.decode @payload, @hmac_secret, true, algorithm: 'HS256' payload = JSON.parse payload.first[JWT_DATA] secret_box = RbNaCl::SecretBox.new(@secret_key) nonce = Base64.urlsafe_decode64 payload[NONCE_KEY] token = Base64.urlsafe_decode64 payload[TOKEN_KEY] secret_box.decrypt(nonce, token) rescue => e return({ code: 401, error: e.to_s }) end end
module Api module V1 class UsersController < ApplicationController before_action :authenticate!, if: :valid_actions? include ActionController::HttpAuthentication::Token::ControllerMethods def login user = User.find_by_email(params[:email]) if user.present? render json: {access_token: user.token, email: user.email} else render json: {error: "No user is registered with email #{params[:email]}"} end end def signup data = required_params user = User.new(data) result = user.save if result render json: {email: user.email, access_token: user.token} else render json: {error: user.errors } end end def logout user = User.find_by_email(user.email) user.reset_token user.save end def cart byebug cart = current_user.cart render json: {cart: cart.cart_items} end private def valid_actions? params["action"] == "cart" end def authenticate! authenticate_or_request_with_http_token do |token, _options| User.find_by(token: token) end end def current_user @current_user ||= authenticate! end def required_params params.permit(:email,:password) end end end end
# encoding: utf-8 require "uuidtools" class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(params[:user]) unless verify_recaptcha(:model => @user) redirect_to signup_url, :alert => "驗証碼輸入錯誤" return end @user.status = User::STATUS_PENDING_APPROVAL @user.activation_hash = UUIDTools::UUID.random_create.to_s @user.provider = User::PROVIDER_IDENTITY if @user.save NotifierMailer.welcome_email(@user).deliver redirect_to root_url, :notice => "註冊成功! 請檢查你的電郵啟動帳戶." else render "new" end end # GET /users/activate/:id/:hash def activate @user = User.find(params[:id]) if @user.status == User::STATUS_PENDING_APPROVAL && @user.activation_hash == params[:hash] @user.status = User::STATUS_ACTIVE @user.activation_hash = nil @user.save redirect_to root_url, :notice => "您的帳號已啟動!" else redirect_to root_url, :notice => "啟動碼錯誤, 請重試." end end # GET /users/edit def edit if session[:user_id] @user ||= User.find(session[:user_id]) else redirect_to root_url end end # POST /users/update def update @user ||= User.find(session[:user_id]) if session[:user_id] if @user.update_attributes(params[:user]) redirect_to root_url, :notice => "User Profile Updated Successfully." else render users_edit_path end end # POST /users/reset def password_reset @user = User.find(:first, :conditions => ["lower(email) = ?", params["email"].downcase]) @password = random_password(8) @user.update_attribute(:password, @password) NotifierMailer.reset_email(@user, @password).deliver redirect_to login_path, :notice => "密碼重設成功, 請檢查電郵." end # GET /fb_channel.html def channel # Reference: https://developers.facebook.com/docs/reference/javascript/ # 1 Year cache_expire = 60*60*24*365; response.headers['Pragma'] = 'public' response.headers['Cache-Control'] = "max-age=#{cache_expire}" response.headers['Expires'] = (DateTime.now + cache_expire.seconds).strftime('%a, %d %b %Y %H:%M:%S GMT') # don't use any layout. just return the plain 1 line in the response render layout: false end def random_password(len) chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a newpass = "" 1.upto(len) { |i| newpass << chars[rand(chars.size-1)] } return newpass end end
#正規表現 構文 module Pattern def bracket(outer_precedence) if precedence < outer_precedence '(' + to_s + ')' else to_s end end def inspect "/#{self}/" end # => インターフェイスの改善 def matches?(string) to_nfa_design.accepts?(string) end end class Empty include Pattern def to_s '' end def precedence 3 end end class Literal < Struct.new(:character) include Pattern def to_s character end def precedence 3 end end class Concatenate < Struct.new(:first, :second) include Pattern def to_s [first, second].map { |pattern| pattern.bracket(precedence) }.join end def precedence 1 end end class Choose < Struct.new(:first, :second) include Pattern def to_s [first, second].map { |pattern| pattern.bracket(precedence) }.join('|') end def precedence 0 end end class Repeat < Struct.new(:pattern) include Pattern def to_s pattern.bracket(precedence) + '*' end def precedence 2 end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) #Destruction User.destroy_all Provider.destroy_all #Healthpost admin user User.create(email: 'admin@healthpost.com', password: 'password', admin: true) #Providers memorial_hermann = Provider.create(name: 'Memorial Hermann') memorial_hermann.users.create(email: 'healthpost_admin@memorialhermann.com', password: 'password', provider_admin: true) memorial_hermann.users.create(email: 'healthpost_user@memorialhermann.com', password: 'password') hca_gulf_coast = Provider.create(name: 'HCA Gulf Coast') hca_gulf_coast.users.create(email: 'healthpost_admin@hcagulfcoast.com', password: 'password', provider_admin: true) hca_gulf_coast.users.create(email: 'healthpost_user@hcagulfcoast.com', password: 'password') methodist = Provider.create(name: 'Methodist') methodist.users.create(email: 'healthpost_admin@methodist.com', password: 'password', provider_admin: true) methodist.users.create(email: 'healthpost_user@methodist.com', password: 'password')
# Encoding: UTF-8 # Ruby Hack Night Asteroids by David Andrews and Jason Schweier, 2016 require "player" WIDTH = 800 unless defined? WIDTH HEIGHT = 600 unless defined? HEIGHT RSpec.describe Player do describe "#invulnerable?" do context "when new" do let!(:subject) { described_class.new(double("dt")) } it { is_expected.to be_invulnerable } context "with 500ms of invulnerability" do before do described_class.class_variable_set(:@@invulnerable_time, 500) end it "is invulnerable before 500ms" do advance_time(499) expect(subject).to be_invulnerable end it "is vulnerable on or after 500ms" do advance_time(500) expect(subject).not_to be_invulnerable end end end end end def advance_time(ms) time = Gosu.milliseconds allow(Gosu).to receive(:milliseconds) { time + ms } end