text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe Admin::ReportTypesController, type: :controller do before do @admin = FactoryGirl.create(:admin) @report_type = FactoryGirl.create(:report_type) end describe "GET #index" do it "returns a success response" do sign_in @admin get :index expect(response).to be_success end end describe "GET #show" do it "returns a success response" do sign_in @admin get :show, params: { id: @report_type.id } expect(response).to be_success end end describe "GET #new" do it "returns a success response" do sign_in @admin get :new, params: {} expect(response).to be_success end end describe "GET #edit" do it "returns a success response" do sign_in @admin get :edit, params: {id: @report_type.id} expect(response).to be_success end end describe "POST #create" do it "creates a new ReportType" do report_type_params = FactoryGirl.attributes_for(:report_type) sign_in @admin expect { post :create, params: {report_type: report_type_params} }.to change(ReportType, :count).by(1) end end describe "PATCH #update" do it "updates the requested report_type" do report_type_params = FactoryGirl.attributes_for(:report_type, name: "New Report Type") sign_in @admin patch :update, params: {id: @report_type.id, report_type: report_type_params} expect(@report_type.reload.name).to eq "New Report Type" end end describe "DELETE #destroy" do it "destroys the requested report_type" do sign_in @admin expect { delete :destroy, params: {id: @report_type.id} }.to change(ReportType, :count).by(-1) end end end
def my_select(collection) # if array is length > 0 ## This block should not run!" # iterate through each item # is it nil? # checking for truthiness #return original array i = 0 newArray = [] while i < collection.length varName = yield(collection[i]) if varName == TRUE newArray << collection[i] end i += 1 end newArray end
require 'rails_helper' RSpec.describe "author show page", type: :feature do before(:each) do @author_1 = Author.create!(name: "Author 1") @author_2 = Author.create!(name: "Author 2") @author_3 = Author.create!(name: "Author 3") @book_1 = @author_1.books.create!(title: "Book 1", publication_year: 1999, pages: 100, cover_image: "book1.png") @book_2 = @author_1.books.create!(title: "Book 2", publication_year: 2000, pages: 105, cover_image: "book2.png") @book_3 = Book.create!(title: "Book 3", publication_year: 2001, pages: 110, cover_image: "book3.png", authors:[@author_1, @author_2]) @book_4 = @author_3.books.create!(title: "Book 4", publication_year: 2002, pages: 120, cover_image: "book4.png") @book_5 = @author_2.books.create!(title: "Book 5", publication_year: 2003, pages: 125, cover_image: "book5.png") @user_1 = User.create!(username: "User 1") @user_2 = User.create!(username: "User 2") @user_3 = User.create!(username: "User 3") @review_1 = @user_1.reviews.create!(title: "Review Book 1.1", rating: 1, text: "Worst", book: @book_1) @review_2 = @user_2.reviews.create!(title: "Review Book 1.2", rating: 4, text: "Best", book: @book_1) @review_3 = @user_3.reviews.create!(title: "Review Book 2", rating: 5, text: "Best", book: @book_2) end it 'displays all books by that author with title, pages, publication year, cover image, and co-authors' do visit author_path(@author_1) expect(current_path).to eq(author_path(@author_1)) expect(page).to have_content(@author_1.name) expect(page).to_not have_content(@book_4.title) within "#book-#{@book_1.id}" do expect(page).to have_content(@book_1.title) expect(page).to have_content(@book_1.pages) expect(page).to have_content(@book_1.publication_year) expect(page).to have_css("img[src='#{@book_1.cover_image}']") expect(page).to_not have_content(@author_2.name) expect(page).to_not have_content(@author_3.name) end within "#book-#{@book_2.id}" do expect(page).to have_content(@book_2.title) expect(page).to have_content(@book_2.pages) expect(page).to have_content(@book_2.publication_year) expect(page).to have_css("img[src='#{@book_2.cover_image}']") expect(page).to_not have_content(@author_2.name) expect(page).to_not have_content(@author_3.name) end within "#book-#{@book_3.id}" do expect(page).to have_content(@book_3.title) expect(page).to have_content(@book_3.pages) expect(page).to have_content(@book_3.publication_year) expect(page).to have_css("img[src='#{@book_3.cover_image}']") expect(page).to have_content(@author_2.name) expect(page).to_not have_content(@author_3.name) expect(page).to_not have_content(@author_3.name) end end it "displays each book's highest rated review with title, rating, and username" do visit author_path(@author_1) expect(current_path).to eq(author_path(@author_1)) within "#book-#{@book_1.id}" do expect(page).to have_content(@book_1.title) expect(page).to have_content(@review_2.title) expect(page).to have_content(@review_2.rating) expect(page).to have_content(@review_2.user.username) expect(page).to_not have_content(@review_1.title) expect(page).to_not have_content(@review_3.title) end within "#book-#{@book_2.id}" do expect(page).to have_content(@book_2.title) expect(page).to have_content(@review_3.title) expect(page).to have_content(@review_3.rating) expect(page).to have_content(@review_3.user.username) expect(page).to_not have_content(@review_1.title) expect(page).to_not have_content(@review_2.title) end end it "displays the user names(s) as a link, which takes the visitor to that user's show page" do visit author_path(@author_1) within "#top-rated-review-#{@book_1.id}" do click_link @user_2.username expect(current_path).to eq(user_path(@user_2)) end visit author_path(@author_1) within "#top-rated-review-#{@book_2.id}" do click_link @user_3.username expect(current_path).to eq(user_path(@user_3)) end end it "visits author page and deletes a single author and returns user to book index page" do visit author_path(@author_1) expect(page).to have_content(@author_1.name) expect(page).to have_content(@book_1.title) expect(page).to have_content(@book_2.title) expect(page).to have_content(@book_3.title) expect(page).to have_content(@author_2.name) click_on "Delete this Author" expect(current_path).to eq(books_path) expect(page).to_not have_content(@book_1.title) expect(page).to_not have_content(@book_2.title) expect(page).to_not have_content(@book_3.title) expect(page).to_not have_content(@author_1.name) expect(page).to have_content(@author_2.name) end end
require "minitest_helper" describe LevelEditor::ImageInterroger do describe "6x3 image with 1 horizontal bar" do # 012345 # 0 xxxoxx x white # 1 ooo-xx o black # 2 xxxxxo - red before do @image_interroger = LevelEditor::ImageInterroger.new("images/test_case1.bmp") end it "must have an Magick::Image instance attribute" do @image_interroger.original_image.class.must_equal Magick::Image end it "can retrieve is width" do @image_interroger.width.must_equal(6) end it "can retrieve his heigth" do @image_interroger.height.must_equal(3) end it "convert the original image into an array of pixels" do @image_interroger.pixels.must_be_instance_of(Array) @image_interroger.pixels.size.must_equal(18) end it "can convert 2d coordinate into 1d to access in an 1D array" do @image_interroger.convert_2D_to_1D(0,0).must_equal(0) @image_interroger.convert_2D_to_1D(1,0).must_equal(1) @image_interroger.convert_2D_to_1D(5,0).must_equal(5) @image_interroger.convert_2D_to_1D(1,1).must_equal(7) @image_interroger.convert_2D_to_1D(5,2).must_equal(17) end it "can access to a pixel" do @image_interroger.get(0,0).must_be_instance_of(Magick::Pixel) end it "can access to a pixel color" do @image_interroger.get_color(0,0).must_equal("white") @image_interroger.get_color(3,0).must_equal("black") @image_interroger.get_color(3,1).must_equal("red") end it "can know if the next pixel on the right is identical" do @image_interroger.pixel_identical?(:right,0,0).must_equal(true) @image_interroger.pixel_identical?(:right,2,0).must_equal(false) @image_interroger.pixel_identical?(:right,5,0).must_equal(false) @image_interroger.pixel_identical?(:right,3,1).must_equal(false) @image_interroger.pixel_identical?(:right,3,0).must_equal(false) @image_interroger.pixel_identical?(:right,4,2).must_equal(false) @image_interroger.pixel_identical?(:right,5,2).must_equal(false) end it "can know if the next pixel on the left is identical" do @image_interroger.pixel_identical?(:left,0,0).must_equal(false) @image_interroger.pixel_identical?(:left,1,0).must_equal(true) @image_interroger.pixel_identical?(:left,5,2).must_equal(false) @image_interroger.pixel_identical?(:left,4,2).must_equal(true) @image_interroger.pixel_identical?(:left,4,1).must_equal(false) @image_interroger.pixel_identical?(:left,2,1).must_equal(true) @image_interroger.pixel_identical?(:left,1,1).must_equal(true) @image_interroger.pixel_identical?(:left,3,1).must_equal(false) end it "can know if the next pixel on the top is identical" do @image_interroger.pixel_identical?(:top,0,0).must_equal(false) @image_interroger.pixel_identical?(:top,3,0).must_equal(false) @image_interroger.pixel_identical?(:top,0,1).must_equal(false) @image_interroger.pixel_identical?(:top,4,2).must_equal(true) @image_interroger.pixel_identical?(:top,5,1).must_equal(true) @image_interroger.pixel_identical?(:top,5,2).must_equal(false) @image_interroger.pixel_identical?(:top,3,1).must_equal(false) end it "can know if the next pixel on the right is identical" do @image_interroger.pixel_identical?(:bottom,0,0).must_equal(false) @image_interroger.pixel_identical?(:bottom,0,1).must_equal(false) @image_interroger.pixel_identical?(:bottom,3,1).must_equal(false) @image_interroger.pixel_identical?(:bottom,5,1).must_equal(false) @image_interroger.pixel_identical?(:bottom,5,2).must_equal(false) @image_interroger.pixel_identical?(:bottom,5,0).must_equal(true) end it "can retrieve all pixels of the same line on the right" do @image_interroger.find_consecutive_pixels(:right,2,2,[]).must_equal([[2,2],[3,2],[4,2]]) @image_interroger.find_consecutive_pixels(:right,3,1,[]).must_equal([[3,1]]) @image_interroger.find_consecutive_pixels(:right,5,0,[]).must_equal([[5,0]]) @image_interroger.find_consecutive_pixels(:right,1,0,[]).must_equal([[1,0],[2,0]]) end it "can retrieve all pixels of the same line on the left" do @image_interroger.find_consecutive_pixels(:left,0,0,[]).must_equal([[0,0]]) @image_interroger.find_consecutive_pixels(:left,3,1,[]).must_equal([[3,1]]) @image_interroger.find_consecutive_pixels(:left,4,1,[]).must_equal([[4,1]]) @image_interroger.find_consecutive_pixels(:left,5,1,[]).must_equal([[5,1],[4,1]]) @image_interroger.find_consecutive_pixels(:left,4,2,[]).must_equal([[4,2],[3,2],[2,2],[1,2],[0,2]]) @image_interroger.find_consecutive_pixels(:left,2,1,[]).must_equal([[2,1],[1,1],[0,1]]) end it "can detect all the pixels of an horizontal line" do @image_interroger.find_all_pixels_on_axis(:horizontal,0,0).must_equal([[0,0],[1,0],[2,0]]) @image_interroger.find_all_pixels_on_axis(:horizontal,2,0).must_equal([[0,0],[1,0],[2,0]]) @image_interroger.find_all_pixels_on_axis(:horizontal,1,0).must_equal([[0,0],[1,0],[2,0]]) @image_interroger.find_all_pixels_on_axis(:horizontal,2,2).must_equal([[0,2],[1,2],[2,2],[3,2],[4,2]]) @image_interroger.find_all_pixels_on_axis(:horizontal,3,1).must_equal([[3,1]]) @image_interroger.find_all_pixels_on_axis(:horizontal,4,0).must_equal([[4,0],[5,0]]) end end describe "simple test case with 6x3 images with only vertical bars" do # 012345 # 0 oxoxxx x white # 1 oxo-xo o black # 2 xxoxxo - red before do @image_interroger = LevelEditor::ImageInterroger.new("images/test_case_2.bmp") end it "can retrieve all pixels of the same line in the top direction" do @image_interroger.find_consecutive_pixels(:top,0,0,[]).must_equal([[0,0]]) @image_interroger.find_consecutive_pixels(:top,0,1,[]).must_equal([[0,1],[0,0]]) @image_interroger.find_consecutive_pixels(:top,2,2,[]).must_equal([[2,2],[2,1],[2,0]]) end it "can retrieve all pixels of the same line in the bottom direction" do @image_interroger.find_consecutive_pixels(:bottom,0,0,[]).must_equal([[0,0],[0,1]]) @image_interroger.find_consecutive_pixels(:bottom,0,1,[]).must_equal([[0,1]]) @image_interroger.find_consecutive_pixels(:bottom,2,0,[]).must_equal([[2,0],[2,1],[2,2]]) @image_interroger.find_consecutive_pixels(:bottom,2,2,[]).must_equal([[2,2]]) end it "can detect all the pixels of a line" do first_black_line = [[0,0],[0,1]] second_black_line = [[2,0],[2,1],[2,2]] third_black_line = [[5,1],[5,2]] @image_interroger.find_all_pixels_on_axis(:vertical,0,0).must_equal(first_black_line) @image_interroger.find_all_pixels_on_axis(:vertical,0,1).must_equal(first_black_line) @image_interroger.find_all_pixels_on_axis(:vertical,2,1).must_equal(second_black_line) @image_interroger.find_all_pixels_on_axis(:vertical,2,0).must_equal(second_black_line) @image_interroger.find_all_pixels_on_axis(:vertical,2,2).must_equal(second_black_line) @image_interroger.find_all_pixels_on_axis(:vertical,5,1).must_equal(third_black_line) end end end
json.array!(@channel.articles.order(pubdate: :desc)) do |article| json.set! :site, article.channel.site json.set! :channel, article.channel json.extract! article, :id, :channel_id, :title, :link, :pubdate, :guid, :description, :content end
# encoding: utf-8 control "V-52187" do title "The DBMS must notify appropriate individuals when accounts are created." desc "Once an attacker establishes initial access to a system, they often attempt to create a persistent method of re-establishing access. One way to accomplish this is for the attacker to simply create a new account. Notification of account creation is one method and best practice for mitigating this risk. A comprehensive account management process will ensure an audit trail which documents the creation of application user accounts and notifies administrators and/or application owners exist. Such a process greatly reduces the risk that accounts will be surreptitiously created and provides logging that can be used for forensic purposes. Note that user authentication and account management must be done via an enterprise-wide mechanism whenever possible. Examples of enterprise-level authentication/access mechanisms include, but are not limited to, Active Directory and LDAP. This requirement applies to cases where accounts are directly managed by Oracle. Notwithstanding how accounts are normally managed, the DBMS must support the requirement to notify appropriate individuals upon account creation within Oracle. Indeed, in a configuration where accounts are managed externally, the creation of an account within Oracle may indicate hostile activity.false" impact 0.5 tag "check": "Check DBMS settings to determine whether it will notify appropriate individuals when accounts are created. If the DBMS does not notify appropriate individuals when accounts are created, this is a finding." tag "fix": "Working with the DBA and site management, determine the appropriate individuals (by job role) to be notified. If Oracle Audit Vault is available, configure it to notify the appropriate individuals when accounts are created. If Oracle Audit Vault is not available, configure the Oracle DBMS's auditing feature to record account-creation activity. Create and deploy a mechanism, such as a frequently-run job, to monitor the audit table or file for these records and notify the appropriate individuals." # Write Check Logic Here end
require 'rails_helper' RSpec.describe Message, type: :model do it "test creation" do @user = create(:user) @message = build(:message) expect(@message).to be_valid end it "test owner" do @user = create(:user) @message = build(:message, user_id: nil) expect(@message).to_not be_valid end it "test user id" do @user = create(:user, username: "elmismopo") @message = build(:message, user_id: @user.id + 1) expect(@message).to_not be_valid end end
module EmbeddableContent class TreeBasedNodeProcessor < EmbeddableContent::RecordNodeProcessor EMBBEDER_TAG_TREE_ID_ATTRIBUTE = 'data-tree-ref-id'.freeze private def node_should_be_replaced? super && tag_references_current_tree? end def tag_references_current_tree? embedded_tag_tree_id == tree_embedder_tag_id end def embedded_tag_tree_id node[EMBBEDER_TAG_TREE_ID_ATTRIBUTE] end def tree_embedder_tag_id tree_node&.embedder_tag_id end end end
class Letter #Letter objects that contain their own NAME, and a list of POSSIBLE interpretations #It is assumed that by the rules of the cryptogram that they cannot end up being themself attr_accessor :name, :possibles def initialize(itself="r") #Sets the possible list, and the self.name #lowercase letters are the unchanged letters, upcase is solved letters if itself == "'" || itself == '-' @name = itself @possibles = Set[itself] @possibles.freeze else @name = itself.downcase @possibles = Set.new @possibles = %w[ E T A O I N S H R D L C U M W F G Y P B V K J X Q Z ] @possibles.delete(itself.upcase) end end def singular? @possibles.length == 1 end end
require 'spec_helper' require 'facter/util/public_ipaddress' describe Facter::Util::PublicIpaddress do let (:openuri) do OpenURI end describe Facter::Util::PublicIpaddress.cache do it 'should return cache file path' do Facter::Util::PublicIpaddress.cache.should == '/var/tmp/public_ip.fact.cache' end end describe Facter::Util::PublicIpaddress.can_connect?('http://invalid.domain.tld') do it 'should return false if request times out' do Timeout.expects(:timeout).raises(Timeout::Error) Facter::Util::PublicIpaddress.can_connect?('http://invalid.domain.tld').should == false end it 'should return true if connect succeeds' do tmpfile = Tempfile.new('connect') tmpfile.write('abc') tmpfile.rewind openuri.stubs(:open_uri).returns(tmpfile) Facter::Util::PublicIpaddress.can_connect?('http://invalid.domain.tld').should == true end end describe Facter::Util::PublicIpaddress.get_ip('http://invalid.domain.tld') do it 'should return nil if connection fails' do Facter::Util::PublicIpaddress.expects(:can_connect?).returns(false) Facter::Util::PublicIpaddress.get_ip('http://invalid.domain.tld').should be_nil end it 'should return nil if the backend returns a wrong value' do tmpfile = Tempfile.new('get_ip_wrong') tmpfile.write('abc') tmpfile.rewind openuri.stubs(:open_uri).returns(tmpfile) Facter::Util::PublicIpaddress.expects(:update_cache).never Facter::Util::PublicIpaddress.get_ip('http://invalid.domain.tld').should be_nil end it 'should return value and cache it' do tmpfile = Tempfile.new('get_ip_right') tmpfile.write('5.4.3.2') tmpfile.rewind openuri.stubs(:open_uri).returns(tmpfile) Facter::Util::PublicIpaddress.expects(:update_cache).with('5.4.3.2').once Facter::Util::PublicIpaddress.get_ip('http://invalid.domain.tld').should == '5.4.3.2' end end describe Facter::Util::PublicIpaddress.update_cache('1.2.3.4') do it 'should write value to file' do File.expects(:open).with('/var/tmp/public_ip.fact.cache', 'w') #File.any_instance.expects(:write).with('1.2.3.4') # why not? Facter::Util::PublicIpaddress.update_cache('1.2.3.4') end end describe Facter::Util::PublicIpaddress.get_cache do it 'should return nil if file does not exist' do File.expects(:exists?).returns(false) Facter::Util::PublicIpaddress.get_cache.should == nil end it 'should return file content if it exists' do File.expects(:exists?).returns(true) File.expects(:read).with('/var/tmp/public_ip.fact.cache').returns('5.4.3.2') Facter::Util::PublicIpaddress.get_cache.should == '5.4.3.2' end end end
require 'spec_helper' describe Analyst::Entities::MethodCall do describe "#constants" do let(:code) { "Universe.spawn(Star, into: Galaxy.named('Milky Way'))" } let(:method_call) { Analyst.for_source(code).method_calls.first } it "lists constant targets and arguments" do found = method_call.constants.map(&:name) expect(found).to match_array %w[Universe Star Galaxy] end end describe "#arguments" do it "lists arguments" do code = "fn(:one, 'two', three)" args = Analyst.for_source(code).method_calls.first.arguments expect(args[0].value).to be :one expect(args[1].value).to eq 'two' expect(args[2].class).to eq Analyst::Entities::MethodCall expect(args[2].name).to eq 'three' end end end
require 'rails_helper' RSpec.describe SocialMediaBlitzing, type: :model do describe 'when mobilization is saved' do before :each do @social_media_blitzing = SocialMediaBlitzing.new end it 'should not take string in numeric field' do @social_media_blitzing.number_of_posts = 'string' @social_media_blitzing.number_of_people_posting = 'string' @social_media_blitzing.valid? expect(@social_media_blitzing.errors[:number_of_posts]).to include('is not a number') expect(@social_media_blitzing.errors[:number_of_people_posting]).to include('is not a number') end it 'should not take negative numbers in numeric field' do @social_media_blitzing.number_of_posts = -1 @social_media_blitzing.number_of_people_posting = -2 @social_media_blitzing.valid? expect(@social_media_blitzing.errors[:number_of_posts]).to include('must be greater than 0') expect(@social_media_blitzing.errors[:number_of_people_posting]).to include('must be greater than 0') end it 'should not take float numbers in numeric fields' do @social_media_blitzing.number_of_posts = 0.5 @social_media_blitzing.number_of_people_posting = 0.7 @social_media_blitzing.valid? expect(@social_media_blitzing.errors[:number_of_posts]).to include('must be a number') expect(@social_media_blitzing.errors[:number_of_people_posting]).to include('must be a number') end it 'should not take field greater than 1 billion' do @social_media_blitzing.number_of_posts = 1000000000+1 @social_media_blitzing.number_of_people_posting = 1000000000+1 @social_media_blitzing.valid? expect(@social_media_blitzing.errors[:number_of_posts]).to include('is too big') expect(@social_media_blitzing.errors[:number_of_people_posting]).to include('is too big') end it 'should have user and chapter' do @social_media_blitzing.valid? expect(@social_media_blitzing.errors[:user]).to include('can\'t be blank') expect(@social_media_blitzing.errors[:chapter]).to include('can\'t be blank') end it 'should not take values with length greater than permitted' do @social_media_blitzing.identifier = generate_random_string(51) @social_media_blitzing.valid? expect(@social_media_blitzing.errors[:identifier]).to include('Identifier is too long (maximum is 50 characters)') end end end def generate_random_string(size=1) characters = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten (0...size).map { characters[rand(characters.size)] }.join end
class HenryV < ShakesChar def initialize @name = "Henry V, King of England, Lord of Ireland" @play = "The Life of King Henry the V, and my role is based off the actual English King Henry V" @gender = "male" @age = 29 end def quote super + "Once more unto the breach, dear friends, once more; Or close the wall up with our English dead. In peace there's nothing so becomes a man As modest stillness and humility: But when the blast of war blows in our ears, Then imitate the action of the tiger; Stiffen the sinews, summon up the blood, Disguise fair nature with hard-favour'd rage; Then lend the eye a terrible aspect; Let pry through the portage of the head Like the brass cannon; let the brow o'erwhelm it As fearfully as doth a galled rock O'erhang and jutty his confounded base, Swill'd with the wild and wasteful ocean." end end
# -*- encoding : utf-8 -*- module Nyaa class Downloader attr_accessor :target, :destination, :retries attr_accessor :response, :filename def initialize(url, path, retries = 3) self.target = url self.destination = Nyaa::Utils.safe_path(path) self.retries = retries self.response = request self.filename = name_from_disposition @fail = nil end def save unless @fail path = self.destination + '/' + filename; File.open("#{self.destination}/#{filename}", 'w') do |f| f.write(self.response.read) end return path; end return nil; end def failed? @fail end private def request begin response = open(self.target) rescue StandardError => e if retries > 0 retries -= 1 sleep = 1 retry end @fail = true end @fail = false response end # Filename from Content Disposition Header Field # http://www.ietf.org/rfc/rfc2183.txt def name_from_disposition disp = self.response.meta['content-disposition'] disp_filename = disp.split(/;\s+/).select { |v| v =~ /filename\s*=/ }[0] re = /([""'])(?:(?=(\\?))\2.)*?\1/ if re.match(disp_filename) filename = re.match(disp_filename).to_s.gsub(/\A['"]+|['"]+\Z/, "") else nil end end end end
class Fixnum define_method(:prime_numbers) do number_range = (2..self) prime_array = [] number_range.each() do |number| prime_array.push(number) end prime = 2 until prime == self prime_array.delete_if{|number| number%prime==0 && number!= prime} prime += 1 end prime_array end end
require 'spec_helper_acceptance' describe 'removing yarn' do describe 'running puppet code' do pp = <<-EOS class { 'nodejs': repo_url_suffix => '6.x', } if $::osfamily == 'Debian' and $::operatingsystemrelease == '7.3' { class { 'yarn': manage_repo => false, install_method => 'npm', require => Class['nodejs'], package_ensure => 'absent', } } elsif $::osfamily == 'Debian' and $::operatingsystemrelease == '7.8' { class { 'yarn': manage_repo => false, install_method => 'source', require => Package['nodejs'], package_ensure => 'absent', } } else { class { 'yarn': package_ensure => 'absent', } if $::osfamily == 'RedHat' and $::operatingsystemrelease =~ /^5\.(\d+)/ { class { 'epel': } Class['epel'] -> Class['nodejs'] -> Class['yarn'] } } EOS let(:manifest) { pp } it 'should work with no errors' do apply_manifest(manifest, :catch_failures => true) end it 'should be idempotent' do apply_manifest(manifest, :catch_changes => true) end describe command('yarn -h') do its(:exit_status) { should eq 127 } end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Room do describe "(instance methods)" do before(:each) do @room = Factory(:room) end it "should return a permalink when converted to a param" do @room.to_param.should == @room.permalink end end describe "should be valid" do it "with valid attributes" do Factory.build(:room).should be_valid end end describe "should be invalid" do it "without permalink" do Factory.build(:room, :without => :permalink).should_not be_valid end it "with blank permalink" do Factory.build(:room, :permalink => '').should_not be_valid end it "if there is a room with the same permalink" do @room = Factory(:room) Factory.build(:room, :permalink => @room.permalink).should_not be_valid end end end
#!/usr/bin/env ruby # frozen_string_literal: true # # Copyright (C) 2016 Scarlett Clark <sgclark@kde.org> # Copyright (C) 2015-2016 Harald Sitter <sitter@kde.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) version 3, or any # later version accepted by the membership of KDE e.V. (or its # successor approved by the membership of KDE e.V.), which shall # act as a proxy defined in Section 6 of version 3 of the license. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>. require 'erb' require 'yaml' class Recipe class App def initialize(name) @name = name @distro_deps = '' @kf5_deps = '' end end attr_accessor :name attr_accessor :proper_name attr_accessor :dependencies attr_accessor :cmake attr_accessor :wayland attr_accessor :boost attr_accessor :version attr_accessor :summary attr_accessor :description attr_accessor :frameworks attr_accessor :external attr_accessor :apps def render ERB.new(File.read('Recipe.erb')).result(binding) end appimage = Recipe.new appimage.name = "artikulate" appimage.proper_name = appimage.name.capitalize appimage.version = '16.04.1' #Needed to add ability to pull in external builds that are simply to old #in Centos. appimage.external = 'libarchive,https://github.com/libarchive/libarchive,true,""' appimage.cmake = true appimage.wayland = false appimage.boost = false #Run gatherdeps local to get dep lists. TO_DO: run on jenkins. appimage.dependencies = 'bzip2-devel liblzma-devel xz-devel media-player-info.noarch libfam-devel python33 sqlite' appimage.frameworks = 'attica extra-cmake-modules karchive kcoreaddons kauth kcodecs kconfig kdoctools kguiaddons ki18n kwidgetsaddons kconfigwidgets kwindowsystem kcrash kcompletion kitemviews kiconthemes kdbusaddons kservice kjobwidgets solid sonnet ktextwidgets kglobalaccel kxmlgui kbookmarks kio knewstuff' appimage.apps = [Recipe::App.new("#{appimage.name}")] File.write('Recipe', appimage.render) end
class TelefonesController < ApplicationController before_action :set_telefone, only: [:show, :edit, :update, :destroy] # GET /telefones # GET /telefones.json def index @telefones = Telefone.all listarContatos end # GET /telefones/1 # GET /telefones/1.json def show listarContatos end # GET /telefones/new def new @telefone = Telefone.new listarContatos end # GET /telefones/1/edit def edit listarContatos end # POST /telefones # POST /telefones.json def create @telefone = Telefone.new(telefone_params) respond_to do |format| if @telefone.save format.html { redirect_to @telefone, notice: 'Telefone was successfully created.' } format.json { render :show, status: :created, location: @telefone } else format.html { render :new } format.json { render json: @telefone.errors, status: :unprocessable_entity } end end end # PATCH/PUT /telefones/1 # PATCH/PUT /telefones/1.json def update respond_to do |format| if @telefone.update(telefone_params) format.html { redirect_to @telefone, notice: 'Telefone was successfully updated.' } format.json { render :show, status: :ok, location: @telefone } else format.html { render :edit } format.json { render json: @telefone.errors, status: :unprocessable_entity } end end end # DELETE /telefones/1 # DELETE /telefones/1.json def destroy @telefone.destroy respond_to do |format| format.html { redirect_to telefones_url, notice: 'Telefone was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_telefone @telefone = Telefone.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def telefone_params params.require(:telefone).permit(:numero, :contato_id) end end def listarContatos @listarContatos = Contato.all end
require 'rails_helper' RSpec.describe Place, :type => :model do describe "validations" do it "validates presence of name" do place = FactoryGirl.build(:place, name: nil) expect(place.valid?).to be false expect(place.errors[:name].present?).to be true end it "validates uniqueness of name" do place1 = FactoryGirl.create(:place, name: "here") place2 = FactoryGirl.build(:place, name: "here") expect(place2.valid?).to be false expect(place2.errors[:name].present?).to be true end end end
require 'spec_helper' describe User do it "can't login with new user" do User.login('newuser', 'fakepassword').should == -1 end it "can't create user with no name" do User.add('', 'fakepassword').should == -3 end it "can't create user with too long name" do User.add('long'*100, 'fakepassword').should == -3 end it "can't create user with too long password" do User.add('fakename', 'fakepassword'*50).should == -4 end it "can add a new user" do User.add('usersuccess','pass').should == 1 end it "can login an existing user" do User.add('hey','pass') User.login('hey','pass').should == 2 end it "can't login with wrong password" do User.add('lol','passwrong') User.login('lol','pass').should == -1 end it "can't add existing user" do User.add('usersuccess1','pass') User.add('usersuccess1','pass').should == -2 end it "should increment logins" do User.add('usersuccess3','pass') User.login('usersuccess3','pass') User.login('usersuccess3','pass') User.login('usersuccess3','pass') User.login('usersuccess3','pass').should == 5 end it "can't create user w/ too long name and password" do User.add('fakename'*50, 'fakepassword'*50).should_not == 1 end end
class HttpUrlValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return true if value.blank? url = Addressable::URI.parse value scheme = url.scheme rescue nil probable_mistake = url.host.exclude?('.') rescue true if %w[http https].exclude?(scheme) || probable_mistake record.errors.add(attribute, 'is not a valid http(s) url') end end end
class CreateAuctionData < ActiveRecord::Migration def change create_table :auction_data do |t| #edited due to bug in rails 4.2.0 t.integer :auc, limit: 8 t.integer :item_id, limit: 8 t.string :owner t.string :ownerRealm t.integer :bid, limit: 8 t.integer :buyout, limit: 8 t.integer :quantity t.string :timeLeft t.integer :rand, limit: 8 t.integer :seed, limit: 8 t.integer :context, limit: 8 t.timestamps null: false end end end
require_relative 'prices' require "pry" class Pizza include Prices def initialize(size, type, crust) @size = size @type = type @crust = crust end def full_order { size: @size, type: @type, crust: @crust } end def calculate_price total_price = 0.0 pizza_prices.each do |trait, prices| prices.each do |choice, price| if full_order[trait].to_sym == choice total_price += price end end end total_price end end
require 'securerandom' class Thing attr_reader :id, :name, :created_at def initialize(id: SecureRandom.uuid, name:, created_at: nil) @id = id @name = name @created_at = created_at end end
require 'rails_helper' describe Repo do it 'exists' do attrs = { name: 'Test Repo', html_url: 'https://www.github.com/users/tylorschafer' } repo = Repo.new(attrs) expect(repo).to be_a Repo expect(repo.name).to eq(attrs[:name]) expect(repo.html_url).to eq(attrs[:html_url]) end end
# frozen_string_literal: true require 'brcobranca/calculo' require 'brcobranca/limpeza' require 'brcobranca/formatacao' require 'brcobranca/formatacao_string' require 'brcobranca/calculo_data' require 'brcobranca/currency' require 'brcobranca/validations' require 'brcobranca/util/date' require 'fast_blank' module Brcobranca # Exception lançada quando algum tipo de boleto soicitado ainda não tiver sido implementado. class NaoImplementado < RuntimeError end class ValorInvalido < StandardError end # Exception lançada quando os dados informados para o boleto estão inválidos. # # Você pode usar assim na sua aplicação: # rescue Brcobranca::BoletoInvalido => invalido # puts invalido.errors class BoletoInvalido < StandardError # Atribui o objeto boleto e pega seus erros de validação def initialize(boleto) errors = boleto.errors.full_messages.join(', ') super(errors) end end # Exception lançada quando os dados informados para o arquivo remessa estão inválidos. # # Você pode usar assim na sua aplicação: # rescue Brcobranca::RemessaInvalida => invalido # puts invalido.errors class RemessaInvalida < StandardError # Atribui o objeto boleto e pega seus erros de validação def initialize(remessa) errors = remessa.errors.full_messages.join(', ') super(errors) end end # Configurações do Brcobranca. # # Para mudar as configurações padrão, você pode fazer assim: # config/environments/test.rb: # # Brcobranca.setup do |config| # config.formato = :gif # end # # Ou colocar em um arquivo na pasta initializer do rails. class Configuration # Gerador de arquivo de boleto. # @return [Symbol] # @param [Symbol] (Padrão: :rghost) attr_accessor :gerador # Formato do arquivo de boleto a ser gerado. # @return [Symbol] # @param [Symbol] (Padrão: :pdf) # @see http://wiki.github.com/shairontoledo/rghost/supported-devices-drivers-and-formats Veja mais formatos na documentação do rghost. attr_accessor :formato # Resolução em pixels do arquivo gerado. # @return [Integer] # @param [Integer] (Padrão: 150) attr_accessor :resolucao # Ajusta o encoding do texto do boleto enviado para o GhostScript # O valor 'ascii-8bit' evita problemas com acentos e cedilha # @return [String] # @param [String] (Padrão: nil) attr_accessor :external_encoding # Atribui valores padrões de configuração def initialize self.gerador = :rghost self.formato = :pdf self.resolucao = 150 self.external_encoding = 'ascii-8bit' end end # Atribui os valores customizados para as configurações. def self.configuration @configuration ||= Configuration.new end # Bloco para realizar configurações customizadas. def self.setup yield(configuration) end # Módulo para classes de boletos module Boleto autoload :Base, 'brcobranca/boleto/base' autoload :BancoNordeste, 'brcobranca/boleto/banco_nordeste' autoload :BancoBrasil, 'brcobranca/boleto/banco_brasil' autoload :BancoBrasilia, 'brcobranca/boleto/banco_brasilia' autoload :Itau, 'brcobranca/boleto/itau' autoload :Hsbc, 'brcobranca/boleto/hsbc' autoload :Bradesco, 'brcobranca/boleto/bradesco' autoload :Caixa, 'brcobranca/boleto/caixa' autoload :Sicoob, 'brcobranca/boleto/sicoob' autoload :Sicredi, 'brcobranca/boleto/sicredi' autoload :Unicred, 'brcobranca/boleto/unicred' autoload :Santander, 'brcobranca/boleto/santander' autoload :Banestes, 'brcobranca/boleto/banestes' autoload :Banrisul, 'brcobranca/boleto/banrisul' autoload :Credisis, 'brcobranca/boleto/credisis' autoload :Safra, 'brcobranca/boleto/safra' autoload :Citibank, 'brcobranca/boleto/citibank' autoload :Ailos, 'brcobranca/boleto/ailos' # Módulos para classes de template module Template autoload :Base, 'brcobranca/boleto/template/base' autoload :Rghost, 'brcobranca/boleto/template/rghost' autoload :Rghost2, 'brcobranca/boleto/template/rghost2' autoload :RghostCarne, 'brcobranca/boleto/template/rghost_carne' autoload :RghostBolepix, 'brcobranca/boleto/template/rghost_bolepix' end end # Módulos para classes de retorno bancário module Retorno autoload :Base, 'brcobranca/retorno/base' autoload :RetornoCbr643, 'brcobranca/retorno/retorno_cbr643' autoload :RetornoCnab240, 'brcobranca/retorno/retorno_cnab240' autoload :RetornoCnab400, 'brcobranca/retorno/retorno_cnab400' # DEPRECATED module Cnab400 autoload :Base, 'brcobranca/retorno/cnab400/base' autoload :Bradesco, 'brcobranca/retorno/cnab400/bradesco' autoload :Banrisul, 'brcobranca/retorno/cnab400/banrisul' autoload :Itau, 'brcobranca/retorno/cnab400/itau' autoload :BancoNordeste, 'brcobranca/retorno/cnab400/banco_nordeste' autoload :BancoBrasilia, 'brcobranca/retorno/cnab400/banco_brasilia' autoload :Unicred, 'brcobranca/retorno/cnab400/unicred' autoload :Credisis, 'brcobranca/retorno/cnab400/credisis' autoload :Santander, 'brcobranca/retorno/cnab400/santander' autoload :BancoBrasil, 'brcobranca/retorno/cnab400/banco_brasil' end module Cnab240 autoload :Base, 'brcobranca/retorno/cnab240/base' autoload :Santander, 'brcobranca/retorno/cnab240/santander' autoload :Sicredi, 'brcobranca/retorno/cnab240/sicredi' autoload :Sicoob, 'brcobranca/retorno/cnab240/sicoob' autoload :Caixa, 'brcobranca/retorno/cnab240/caixa' autoload :Ailos, 'brcobranca/retorno/cnab240/ailos' end end # Módulos para as classes que geram os arquivos remessa module Remessa autoload :Base, 'brcobranca/remessa/base' autoload :Pagamento, 'brcobranca/remessa/pagamento' module Cnab400 autoload :Base, 'brcobranca/remessa/cnab400/base' autoload :BancoBrasil, 'brcobranca/remessa/cnab400/banco_brasil' autoload :Banrisul, 'brcobranca/remessa/cnab400/banrisul' autoload :Bradesco, 'brcobranca/remessa/cnab400/bradesco' autoload :Itau, 'brcobranca/remessa/cnab400/itau' autoload :Citibank, 'brcobranca/remessa/cnab400/citibank' autoload :Santander, 'brcobranca/remessa/cnab400/santander' autoload :Sicoob, 'brcobranca/remessa/cnab400/sicoob' autoload :BancoNordeste, 'brcobranca/remessa/cnab400/banco_nordeste' autoload :BancoBrasilia, 'brcobranca/remessa/cnab400/banco_brasilia' autoload :Unicred, 'brcobranca/remessa/cnab400/unicred' autoload :Credisis, 'brcobranca/remessa/cnab400/credisis' end module Cnab240 autoload :Base, 'brcobranca/remessa/cnab240/base' autoload :BaseCorrespondente, 'brcobranca/remessa/cnab240/base_correspondente' autoload :Caixa, 'brcobranca/remessa/cnab240/caixa' autoload :BancoBrasil, 'brcobranca/remessa/cnab240/banco_brasil' autoload :Sicoob, 'brcobranca/remessa/cnab240/sicoob' autoload :SicoobBancoBrasil, 'brcobranca/remessa/cnab240/sicoob_banco_brasil' autoload :Sicredi, 'brcobranca/remessa/cnab240/sicredi' autoload :Unicred, 'brcobranca/remessa/cnab240/unicred' autoload :Ailos, 'brcobranca/remessa/cnab240/ailos' end end # Módulos para classes de utilidades module Util autoload :Empresa, 'brcobranca/util/empresa' autoload :Errors, 'brcobranca/util/errors' end end
class HomeController < ApplicationController def index @initiatives = Initiative.latest(3) end end
module Sears class Address < Sears::Base attr_accessor :type, :line_1, :line_2, :city, :state, :zip_code, :segment_code, :country_code, :preferred def self.from_multi_lookup_response_string(string) raise InvalidResponseFormat unless string.size == 121 return self.new( :type => string[0, 1].strip, :line_1 => string[1, 40].strip, :line_2 => string[41, 40].strip, :city => string[81, 25].strip, :state => string[106, 2].strip, :zip_code => string[108, 6].strip, :segment_code => string[114, 4].strip, :country_code => string[118, 3].strip ) end def self.from_single_lookup_response_string(string) raise InvalidResponseFormat unless string.size == 122 return self.new( :type => string[0, 1].strip, :preferred => string[1, 1].strip, :line_1 => string[2, 40].strip, :line_2 => string[42, 40].strip, :city => string[82, 25].strip, :state => string[107, 2].strip, :zip_code => string[109, 6].strip, :segment_code => string[115, 4].strip, :country_code => string[119, 3].strip ) end [:type, :line_1, :line_2, :city, :state, :country_code].each do |attribute| define_method "#{attribute}=" do |object| return if object.blank? instance_variable_set("@#{attribute}".to_sym, object) end end def home? type == 'H' end def zip_code=(object) return if object.blank? raise InvalidAttributeValue.new(:zip_code, 'numbers only', object) unless object =~ /\d{1,6}/ @zip_code = object end def segment_code=(object) return if object.blank? raise InvalidAttributeValue.new(:segment_code, 'numbers only', object) unless object =~ /\d{1,4}/ @segment_code = object end def preferred=(object) return if object.blank? raise InvalidAttributeValue.new(:preferred, YN, object) unless YN.include? object @preferred = object end def preferred? preferred == 'Y' end end end
class UpdateHistoryCheckInOutViewsToVersion6 < ActiveRecord::Migration def change update_view :history_check_in_out_views, version: 6, revert_to_version: 5, materialized: true end end
class Desk < ApplicationRecord belongs_to :floor belongs_to :contestant, class_name: 'Person', required: false belongs_to :machine, required: false has_many :assignment_histories, class_name: 'DeskAssignmentHistory' around_save :create_assignment_history def create_assignment_history create_history = self.contestant_id_changed? || self.machine_id_changed? yield if create_history self.assignment_histories.create!( contestant_id: self.contestant_id, machine_id: self.machine_id, ) end end def contestant=(value) floor = case value when String Person.where(login: value).first else value end association(:contestant).writer(floor) end def machine=(value) machine = case value when String Machine.find_or_create_by!(mac: value) else value end association(:machine).writer(machine) end def floor=(value) floor = case value when String Floor.find_or_create_by!(name: value) else value end association(:floor).writer(floor) end end
FactoryGirl.define do factory :position_request do position status PositionRequest::STATUS_PENDING applicant "email" => "office@kolosek.com" end end
Rails.application.routes.draw do resources 'pacientes' resources 'anamneses' resources 'avaliacoes' resources 'tratamentos' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root :to => 'pacientes#index' get '/sign_in', :to => 'sessions#sign_in', :as => 'sign_in' get '/sign_out', :to => 'sessions#sign_out', :as => 'sign_out' post '/create_user_session', :to => 'sessions#new' end
require_relative 'curses_window' module Messenger class CursesSelect def self.select(options) result = nil begin result = new(options).select rescue Interrupt ensure Curses.close_screen end result end def initialize(options) @filtered_options = @options = options @selection = Selection.new @filtered_options, 0 Curses.init_screen Curses.start_color Curses.use_default_colors @list_window = CursesWindow.new(Curses.lines - 1, Curses.cols, 0, 0) @filter_window = CursesWindow.new(1, Curses.cols, Curses.lines - 1, 0) init_colors end def init_colors # Blue background color @list_window.add_color :selected, Curses::COLOR_WHITE, Curses::COLOR_BLUE end def select show_options selected = nil @filter_window.gets do |key, string| if key == :enter selected = @filtered_options[@selection.to_i] Curses.close_screen elsif key == :up @selection.prev elsif key == :down @selection.next end filter_options string.strip show_options @filtered_options true end selected end def show_options(options = nil) options ||= @options @list_window.clear if options.empty? @list_window.puts 'There is no chats for entered string' else options.each_with_index do |option, i| if i == @selection.to_i @list_window.colorize :selected do |w| w.puts option[:value] end else @list_window.puts option[:value] end end end @list_window.refresh end def filter_options(filter = nil) @filtered_options = @options if filter filter.downcase! @filtered_options = @options.reject { |o| filter and !o[:value].downcase.include?(filter) } end # Update selection options @selection.options = @filtered_options @filtered_options end class Selection attr_reader :position, :options def initialize(options = [], position = 0) @options = options self.position = position end def options=(options) @options = options # Reset position. It will be limited if position is out of options self.position = position end def position=(position) position = 0 if position < 0 position = @options.size - 1 if position >= @options.size @position = position end def method_missing(name, *args, &block) position.send(name, *args, &block) end def next self.position += 1 end def prev self.position -= 1 end end end end
Rails.application.routes.draw do devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" } resources :donations resources :pledges resources :carts resources :notes get 'charity/index' #resources :user, only: [:show, :edit, :update] get 'user/:id/profile' => 'user#profile', as: :profile get 'user/:id/project' => 'user#project', as: :user_project get 'user/:id/donation' => 'user#donation', as: :user_donation #get 'user' => 'user#index' # resources :projects do # get :who_donated, on: :member # end resources :projects, param: :slug do member do post 'like' get 'who_donated' end end namespace :api do namespace :v1 do resources :items, only: [:index, :create, :destroy, :update] end end namespace :admin do resources :users, except: [:new, :create] resources :projects, param: :slug, except: [:new, :create] resources :projects, only: [:archive, :unarchive] do post :archive post :unarchive post :faeture post :unfaeture post :watched post :unwatched end end # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' root 'charity#index', as: 'charity' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
# frozen_string_literal: true require 'healthcare_phony' require 'logger' require 'socket' def lambda_handler(event:, context:) return_message = '' logger = Logger.new($stdout) logger.info('## ENVIRONMENT VARIABLES') logger.info(ENV.to_a) logger.info('## EVENT') logger.info(event) event.to_a number_messages = ENV['NUMBER_MESSAGES'].to_i host = ENV['HOST'] port = ENV['PORT'] mllp_start = '0b' mllp_end = '1c0d' message_parameters = {} message_parameters[:message_sending_facility] = ENV['SENDING_FACILITY'] unless ENV['SENDING_FACILITY'].nil? message_parameters[:message_sending_application] = ENV['SENDING_APPLICATION'] unless ENV['SENDING_APPLICATION'].nil? message_parameters[:message_receiving_application] = ENV['RECEIVING_APPLICATION'] unless ENV['RECEIVING_APPLICATION'].nil? message_parameters[:message_receiving_facility] = ENV['RECEIVING_FACILITY'] unless ENV['RECEIVING_FACILITY'].nil? message_parameters[:message_version] = ENV['MESSAGE_VERSION'] unless ENV['MESSAGE_VERSION'].nil? message_parameters[:patient_class] = ENV['PATIENT_CLASS'] unless ENV['PATIENT_CLASS'].nil? message_parameters[:adt_events] = ENV['ADT_EVENTS'] unless ENV['ADT_EVENTS'].nil? message_parameters[:message_control_id_pattern] = ENV['CONTROL_ID_PATTERN'] unless ENV['CONTROL_ID_PATTERN'].nil? message_parameters[:message_processing_id] = ENV['PROCESSING_ID'] unless ENV['PROCESSING_ID'].nil? logger.info("Sending #{number_messages} messages to #{host}:#{port}") t = TCPSocket.new(host, port) number_messages.times do m = HealthcarePhony::Adt.new(message_parameters) t.send "#{[mllp_start].pack("H*")}#{m.to_s}#{[mllp_end].pack("H*")}", 0 logger.info("Message With ID #{m.hl7_message.message_control_id} sent...") reading_response = true ack_response = '' prev_read = '' while reading_response current_read = t.read(1) ack_response += current_read unless current_read.nil? reading_response = false if (prev_read+current_read == [mllp_end].pack("H*")) prev_read = current_read end logger.info("ACK: #{ack_response}") end t.close return_message end
require_relative 'binaryio' module Asciidoctor module Diagram module SVG def self.get_image_size(data) if m = START_TAG_REGEX.match(data) start_tag = m[0] if (w = WIDTH_REGEX.match(start_tag)) && (h = HEIGHT_REGEX.match(start_tag)) width = w[:value].to_i * to_px_factor(w[:unit]) height = h[:value].to_i * to_px_factor(h[:unit]) return [width.to_i, height.to_i] end if v = VIEWBOX_REGEX.match(start_tag) width = v[:width] height = v[:height] return [width.to_i, height.to_i] end end nil end private START_TAG_REGEX = /<svg[^>]*>/ WIDTH_REGEX = /width="(?<value>\d+)(?<unit>[a-zA-Z]+)"/ HEIGHT_REGEX = /height="(?<value>\d+)(?<unit>[a-zA-Z]+)"/ VIEWBOX_REGEX = /viewBox="\d+ \d+ (?<width>\d+) (?<height>\d+)"/ def self.to_px_factor(unit) case unit when 'pt' 1.33 else 1 end end end end end
class OrderMailer < ApplicationMailer default to: 'jan.hlavsa@seznam.cz' def order_mail @order = Order.new(params) mail(from: 'primluvysporilov@gmail.com', subject: 'Stránky Spořilov - prosba o přímluvu') end end
# encoding: utf-8 module StatisticsHelper ## # returns the occurences of the card in the group # * *Args* : # -+card+->: card instance # -+group+->: group instance # * *Returns* : # - number of ocurrences of card in group # def getOccurrences(card, group, cardsort, reviewer) count = 0 group.cardsort_results.each do |result| if reviewer == nil if (result.card == card && result.cardsort == cardsort) count += 1 end else if (result.card == card && result.cardsort == cardsort && result.reviewer == reviewer) count += 1 end end end return count end ## # returns list of groups and cards # * *Args* : # -+reviewer_infos+->: an array of reviewer infos # -+type+->: type of the chart # * *Returns* : # - an array of 2 arrays of the cards and groups with no duplicates # def getGroupsAndCards(results) groups = [] cards = [] results.each do |result| if !groups.include?(result.group) groups[groups.length] = result.group end if !cards.include?(result.card) cards[cards.length] = result.card end end return [groups, cards] end ## # uses googlechartsvisualr to make a pie chart of the questionnaire results # * *Args* : # -+question+->:an instance of Question # * *Returns* : # - a pie chart # def getQuestionResults(question, type) results = [] choices = question.choices choices.each_with_index do |choice, index| results[index] = 0 end if type == 3 question.answer_questionnaires.each do |answer| index= nil choices.each do |choice| if choice.body == answer.body index = choices.index(choice) end end results[index] += 1 end else question.answer_questionnaires.each do |answer| index = nil chosenchoices = answer.body.split(',') chosenchoices.each do |chosenchoice| choices.each do |choice| if choice.body == chosenchoice index = choices.index(choice) end end results[index] += 1 end end end data_table = GoogleVisualr::DataTable.new data_table.new_column('string', 'choice' ) data_table.new_column('number', 'value') results.each_with_index do |result, index| data_table.add_row([choices[index].body, result]) end option = { width: 500, height: 150, title: question.body, backgroundColor: "transparent", titleTextStyle: {color: "white"}, legend: {textStyle: {color: 'white'}}, colors: ['rgb(80,0,0)', 'rgb(0,0,80)', 'rgb(0,80,0)', '003333', '663366', '333366', '3366CC'], chartArea:{width:"100%",height:"80%"} } chart = GoogleVisualr::Interactive::PieChart.new(data_table, option) return chart end ## # uses googlechartsvisualr to make a pie chart of the given data # * *Args* : # -+reviewer_infos+->: an array of reviewer infos # -+type+->: type of the chart # * *Returns* : # - a pie chart # def drawPiechart(reviewer_infos, type) data_table = GoogleVisualr::DataTable.new data_table.new_column('string', type ) data_table.new_column('number', 'value') reviewer_infos[0].each_with_index do |info, index| data_table.add_row([reviewer_infos[0][index], reviewer_infos[1][index]]) end option = { width: 250, height: 150, title: type, backgroundColor: "transparent", titleTextStyle: {color: "white"}, legend: {textStyle: {color: 'white'}}, colors: ['rgb(80,0,0)', 'rgb(0,0,80)', 'rgb(0,80,0)', '003333', '663366', '333366', '3366CC'], chartArea:{width:"100%",height:"80%"} } chart = GoogleVisualr::Interactive::PieChart.new(data_table, option) return chart end ## # uses googlechartsvisualr to make a bar chart of the given data # * *Args* : # -+tasks+->: an array of all tasks # * *Returns* : # - a bar chart # def drawBarchart(tasks) data_table = GoogleVisualr::DataTable.new data_table.new_column('string', 'اسم المهمة' ) data_table.new_column('number', 'الوقت') data_table.new_column('number', 'نسبة النجاح') data_table.new_column('number', 'عدد المراجعين') resultsSummary = calculateAllTasksResultsSummary(tasks) tasks.each_with_index do |task, index| data_table.add_row([task.name,resultsSummary[0][index], resultsSummary[1][index], resultsSummary[2][index]]) end option = { width: 600, height: 350, title: "مقارنة بين المهام", backgroundColor: "transparent", titlePosition: 'in', titleTextStyle: {color: "white"}, legend: {position: 'bottom', textStyle: {color: 'white'}}, colors: ['rgb(80,0,0)', 'rgb(0,0,80)', 'rgb(0,80,0)', '003333', '663366', '333366', '3366CC'], hAxis: {textStyle: {color: 'white'}} } chart = GoogleVisualr::Interactive::ColumnChart.new(data_table, option) return chart end ## # uses googlechartsvisualr to make a line chart of the given data # * *Args* : # -+tasks+->: an array of tasks # -+title+->: title of the chart # -+resultsSummary+->: an array containing the data # * *Returns* : # - a line chart # def drawLinechart(resultsSummary, tasks, title) data_table = GoogleVisualr::DataTable.new data_table.new_column('number', 'عدد المراجعين') tasks.each do |task| data_table.new_column('number', task.name) end tasks.each_with_index do |task, index| resultsSummary[index].each_with_index do |time, timeindex| if data_table.rows[timeindex] == nil data_table.add_row() data_table.set_cell(timeindex, 0, timeindex) end data_table.set_cell(timeindex, index + 1, time) end end option = { width: 350, height: 150, title: title, backgroundColor: "transparent", titleTextStyle: {color: "white"}, legend: {textStyle: {color: 'white'}}, colors: ['rgb(80,0,0)', 'rgb(0,0,80)', 'rgb(0,80,0)', '003333', '663366', '333366', '3366CC'], hAxis: {textStyle: {color: 'white'}} } chart = GoogleVisualr::Interactive::LineChart.new(data_table, option) return chart end ## # calculates the results summary of all tasks # * *Args* : # -+tasks+->: an array of tasks # * *Returns* : # - an array containing 3 arrays that where each cell in those arrays represents # - either the average time or success or number of reviewers of one task # def calculateAllTasksResultsSummary(tasks) allTasksAverageTime = [] allTasksAverageSuccess = [] numberofReviewers = [] resultsSummary = [allTasksAverageTime, allTasksAverageSuccess, numberofReviewers] tasks.each do |task| if task.reviewers.length == 0 || task.task_results.length == 0 allTasksAverageTime[allTasksAverageTime.length] = 0 allTasksAverageSuccess[allTasksAverageSuccess.length] = 0 numberofReviewers[numberofReviewers.length] = 0 else allTasksAverageTime[allTasksAverageTime.length] = calculateAverageTime(task.task_results) allTasksAverageSuccess[allTasksAverageSuccess.length] = calculateAverageSuccess(task.task_results) numberofReviewers[numberofReviewers.length] = task.reviewers.length end end return resultsSummary end ## # calculates the average time taken by reviewers of a set of task results # * *Args* : # -+tasks+->: an array of tasks # * *Returns* : # - a value that represents the average time taken by reviewers of one task # def calculateAverageTime(task_results) averagetime = 0.0 counter = 0.0 task_results.each do |result| counter += 1.0 averagetime += result.time end averagetime /= counter return averagetime end ## # calculates the average success a set of task results # * *Args* : # -+tasks+->: an array of tasks # * *Returns* : # - a value that represents the average success of one task # def calculateAverageSuccess(task_results) averagesuccess = 0.0 counter = 0.0 task_results.each do |result| counter += 1.0 if result.success averagesuccess += 1.0 end end averagesuccess /= counter return averagesuccess end ## # calculates the accumulated average time taken by reviewers for a set of task results # * *Args* : # -+tasks+->: an array of tasks # * *Returns* : # - an array of 2 arrays, the first has an array of the accumulated averagetime of each task, # - while the second contains arrays of the accumulated averagesuccess of each task. # def calculateResultsSummary(tasks) allTasksAverageTime = [] allTasksAverageSuccess = [] resultsSummary = [allTasksAverageTime, allTasksAverageSuccess] tasks.each do |task| if task.reviewers.length == 0 return "لم يتم احد المهمة" end if task.task_results.length == 0 return "لا توجد نتائج" end allTasksAverageTime[allTasksAverageTime.length] = calculateAccumulatedAverageTime(task.task_results) allTasksAverageSuccess[allTasksAverageSuccess.length]= calculateAccumulatedAverageSuccess(task.task_results) end return resultsSummary end ## # calculates the accumulated average time taken by reviewers for a set of task results # * *Args* : # -+task_results+->: an array of task results # * *Returns* : # - an array of accumulated average time # def calculateAccumulatedAverageTime(task_results) accumulatedAverageTime = [0.0] task_results.each do |result| length = accumulatedAverageTime.length accumulatedAverageTime[length] = (accumulatedAverageTime[length-1] + result.time) / length end return accumulatedAverageTime end ## # calculates the accumulated average success for a set of task results # * *Args* : # -+task_results+->: an array of task results # * *Returns* : # - an array of accumulated average success # def calculateAccumulatedAverageSuccess(task_results) accumulatedAverageSuccess = [0.0] task_results.each do |result| length = accumulatedAverageSuccess.length if result.success accumulatedAverageSuccess[length] = (accumulatedAverageSuccess[length-1] + 1) / length else accumulatedAverageSuccess[length] = accumulatedAverageSuccess[length-1] / length end end return accumulatedAverageSuccess end ## # gets three arrays representing the reviewers info # * *Args* : # -+task+->: a certain task # * *Returns* : # - an array containing three arrays that have the data of the reviewer info # def getReviewerInfos(task) if task.reviewers.length == 0 return "لم يتم احد المهمة" else return [compareAge(task), compareCountry(task), compareGender(task)] end end ## # calculates the number of reviewers in each age category # * *Args* : # -+task+->: a certain task # * *Returns* : # - an array containing the number of reviewers in 4 age categories # def compareAge(task) agelessthan20 = agelessthan40 = agelessthan60 = agegreaterthan60 = 0 reviewers = task.reviewers numberofReviewerInfos = 0 reviewers.each do |reviewer| if reviewer.reviewer_info != nil numberofReviewerInfos += 1 if reviewer.reviewer_info.age != nil if reviewer.reviewer_info.age < 20 agelessthan20 += 1 elsif reviewer.reviewer_info.age < 40 agelessthan40 += 1 elsif reviewer.reviewer_info.age < 60 agelessthan60 += 1 else agegreaterthan60 += 1 end end end end if numberofReviewerInfos == 0 return "لم يستكمل أحد المراجعين استمارة المعلومات الشخصية" elsif agelessthan20 == 0 && agelessthan40 == 0 && agelessthan60 == 0 && agegreaterthan60 == 0 return "لم يجب أحد من المراجعين عن سنه" else return [['السن أقل من 20', 'السن أقل من 40', 'السن أقل من 60', 'السن أكثر من 60'], [agelessthan20, agelessthan40, agelessthan60, agegreaterthan60]] end end ## # calculates the number of reviewers in each country # * *Args* : # -+task+->: a certain task # * *Returns* : # - an array containing 2 arrays, one with the countries names and the other with the occurrences # def compareCountry(task) countries = [] occurrences = [] reviewers = task.reviewers numberofReviewerInfos = 0 reviewers.each do |reviewer| if (reviewer.reviewer_info != nil) numberofReviewerInfos += 1 if reviewer.reviewer_info.country != nil if countries.length == 0 countries[0] = reviewer.reviewer_info.country.capitalize occurrences[0] = 1 elsif countries.include?(reviewer.reviewer_info.country.capitalize) occurrences[countries.index(reviewer.reviewer_info.country.capitalize)] += 1 else countries[countries.length] = reviewer.reviewer_info.country.capitalize occurrences[occurrences.length] = 1 end end end end if numberofReviewerInfos == 0 return "لم يستكمل أحد المراجعين استمارة المعلومات الشخصية" elsif countries.length == 0 return "لم يجب أحد من المراجعين عن بلده" else return [countries, occurrences] end end ## # calculates the number of males and females in reviewers list # * *Args* : # -+task+->: a certain task # * *Returns* : # - an array containing the number of males and females # def compareGender(task) males = females = 0 reviewers = task.reviewers numberofReviewerInfos = 0 reviewers.each do |reviewer| if reviewer.reviewer_info != nil numberofReviewerInfos += 1 if reviewer.reviewer_info.gender != nil if reviewer.reviewer_info.gender == true males += 1 else females += 1 end end end end if numberofReviewerInfos == 0 return "لم يستكمل أحد المراجعين استمارة المعلومات الشخصية" elsif males == 0 && females == 0 return "لم يجب أحد من المراجعين عن نوعه" else return [['ذكر', 'أنثى'], [males, females]] end end end
require 'rails_helper' feature 'Log in with Auth0' do before do Capybara.register_driver :chrome do |app| Capybara::Selenium::Driver.new(app, browser: :chrome) end Capybara.javascript_driver = :chrome end given(:user) { create(:user) } context 'With valid credentials' do scenario 'Should successfully log in user' do # log_in(user) # expect(page).to have_content("Signed in!") end end context 'With invalid credentials' do scenario 'Should not log in user' do # log_in(user, true) # expect(page).to have_content('LOG IN') end end end
puts "Hi, there!" while true answer = gets.chomp if answer == "I'm a dummy" puts "I'm not stupid" break end puts answer end
class Hand_Type include Comparable attr_reader :ranking, :name def initialize(cards, ranking, name) @cards = cards @ranking = ranking @name = name end def <=> (other) if ranking == other.ranking compare_hands_of_same_rank(other) else compare_hands_of_different_rank(other) end end def cards @cards.dup end private def compare_hands_of_same_rank(other) raise "subclass must override" end def compare_hands_of_different_rank(other) ranking <=> other.ranking end end
class Squad < ApplicationRecord has_many :squad_members has_many :members, through: :squad_members end
class Node def initialize(value, next_node=nil) @value = value @next = next_node end def value @value end def get_next @next end def set_next(node) @next = node end def set_value(new_value) @value = new_value end end def create_list(arr = []) list = Node.new(0) dummy = list arr.each do |i| list.set_next Node.new(i) list = list.get_next end return dummy.get_next end def get_list(node) values = [] while node do values.append node.value node = node.get_next end return values end def merge_lists(list1, list2) unless list1 then return list2 end unless list2 then return list1 end new_list = Node.new(0) dummy = new_list while list1 or list2 do val1 = nil val2 = nil if list1 val1 = list1.value end if list2 val2 = list2.value end if list1 and list2 if val1 < val2 new_list.set_next Node.new(val1) list1 = list1.get_next else new_list.set_next Node.new(val2) list2 = list2.get_next end elsif list1 new_list.set_next Node.new(val1) list1 = list1.get_next elsif list2 new_list.set_next Node.new(val1) list2 = list2.get_next end new_list = new_list.get_next end return dummy.get_next end if __FILE__ == $0 then arr1 = [1, 3, 6, 9, 10] arr2 = [2, 4, 5, 7, 8] list1 = create_list(arr1) list2 = create_list(arr2) puts "merged arrays = #{get_list(merge_lists(list1, list2)).to_s}" puts "list1 null list2 = #{get_list(merge_lists(list1, nil)).to_s}" puts "list2 null list1 = #{get_list(merge_lists(nil, list2)).to_s}" puts "list2 null list1 null = #{get_list(merge_lists(nil, nil)).to_s}" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'permCheck/version' Gem::Specification.new do |spec| spec.name = PermCheck::PACKAGE spec.version = PermCheck::VERSION spec.authors = ["Gord Brown"] spec.email = ["gordon.brown@cruk.cam.ac.uk"] spec.summary = %q{Check permissions on a filesystem hierarchy, reporting sub-hierarchies that do not match permissions and/or group ownership.} spec.description = %q{Given a umask and group, traverse a filesystem hierarchy rooted at some path, reporting files and directories that do not match. The intent is to enforce standards for locking down shared directories so that they are not changed accidentally by users. In our case, the group policy is to have shared code paths read-only to owner and others, read-write to group sec-bioinf-softwareadmins, and group-owned by sec-bioinf-softwareadmins, so that we won't clobber anything accidentally, but instead have to change groups to sec-bioinf-softwareadmins to change anything.} spec.homepage = "https://github.com/crukci-bioinformatics/permCheck" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against " \ "public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "bin" spec.executables = ["permCheck"] spec.require_paths = ["lib"] spec.add_development_dependency "rake", "~> 13" spec.add_development_dependency "minitest", "~> 5.0" spec.add_runtime_dependency "mail", "~> 2.6" end
class Main helpers do def default_account_subdomain @account.username if @account && @account.respond_to?(:username) end def account_url(account_subdomain = default_account_subdomain, use_ssl = request.secure?) (use_ssl ? "https://" : "http://") + account_host(account_subdomain) end def account_host(account_subdomain = default_account_subdomain) account_host = "" account_host << account_subdomain + "." account_host << account_domain end def account_domain account_domain = "" account_domain << subdomains[1..-1].join(".") + "." if subdomains.size > 1 account_domain << domain + ':' + request.port.to_s end def account_subdomain subdomains.first end private def domain (request.host.split('.') - subdomains).join('.') end def subdomains(tld_len=1) host = request.host @subdomains ||= if (host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) [] else host.split('.')[0...(1 - tld_len - 2)] end end end end
# Run me with `rails runner db/data/20211124_create_implementing_organisation_participations.rb` ImplementingOrganisation.where.not(name: "0").each do |org| next unless org.activity unique_org = Organisation.find_matching(org.name) if unique_org puts "#{org.name} maps to Unique IO named #{unique_org.name}" begin org.activity.unique_implementing_organisations << unique_org rescue ActiveRecord::RecordNotUnique => _error puts " the 'Implementing' OrgParticipation already exists..." end else abort "There is no Unique Implementing Org matching #{org.name}" end end
# frozen_string_literal: true require 'serialization' require_relative 'pane_definition' require_relative 'panes/layout' module Build class Panes include Serialization readable( :definitions, default: [], loads: lambda { |defs| defs.map { |pane_def| PaneDefinition.new pane_def } } ) def layout @layout = Layout.new( @serialization_hash.fetch(:layout, {}).merge(definitions: definitions) ) end def session_id=(session_id) @session_id = session_id definitions.each { |definition| definition.session_id = session_id } end def window_id=(window_id) definitions.each { |definition| definition.window_id = window_id } end def seed_pane_id=(pane_id) definitions.first.id = pane_id if definitions.first end def build return unless definitions.any? percent_used = 0 last_pane_definition = definitions.first definitions[1..-1].each_with_index do |pane_definition, index| pane_percents = layout.pane_percents(pane: last_pane_definition, percent_used: percent_used) Build::Util.concurrency.with_lock(session_channel) do pane_definition.id = Build::Util.tmux.split_window( :"#{layout.direction}" => true, size: "#{pane_percents[:split_window]}%", start_directory: pane_definition.directory, target_pane: last_pane_definition.id, print_info: true, format: '"#{pane_id}"' ) end percent_used += pane_percents[:used] last_pane_definition = pane_definition end threads = definitions.map { |pane_definition| Thread.new { pane_definition.build } } threads.each(&:join) end def default @default ||= definitions.find(&:default) || definitions[0] end private def session_channel Build::Util.concurrency.session_channel(session_id: @session_id) end end end
class Talk < ActiveRecord::Base belongs_to :speaker, class_name: 'User' has_and_belongs_to_many :topics has_many :materials accepts_nested_attributes_for :materials, allow_destroy: true, reject_if: :all_blank validates :date, presence: true, uniqueness: true # TODO Take time zones into account? def self.by_semester(semester) where date: (semester.start...(semester.start >> 6)) end def self.before_semester(semester) where 'date < ?', semester.start end def semester Semester.new(date) end def in_semester?(semester) self.semester == semester end def before_semester?(semester) self.semester < semester end end
class LayoutGrid < Draco::Component attribute :orientation, default: :vertical attribute :space, default: :evenly attribute :align, default: :center attribute :padding, default: 0 end
class FavoritesController < ApplicationController before_filter :authenticate_user!, :except => :index before_filter :setup def index @favorite_chefs = @profile.favorite_chefs end def create current_profile.add_favorite_chef(@profile) redirect_to @profile end def destroy current_profile.remove_favorite_chef(@profile) redirect_to @profile end private def setup @profile = Profile.find(params[:profile_id]) end end
module Disposable def dispose test_disposed @disposed = true end def disposed? return @disposed == true end def test_disposed if disposed? raise "This class has been disposed, making this method inaccessible.\n\n" + caller.join("\n") end end end
class TicketsController < ApplicationController before_action :find_ticket, only: %i[show edit update destroy take_in_work resolved closed] before_action :owned_ticket, only: %i[edit update destroy] before_action :ticket, only: :new def index (@filterrific = initialize_filterrific( Ticket, params[:filterrific], select_options: { sorted_by: Ticket.options_for_sorted_by, with_type_of_ticket: %w[repaire service_request permisiion_request], with_status_of_ticket: %w[newly_created in_progress closed resolved], with_responsible_unit: %w[repair service security], with_priority: %w[low middle high], with_user_id: User.options_for_select }, default_filter_params: {}, available_filters: %i[sorted_by search_query with_type_of_ticket with_status_of_ticket with_responsible_unit with_priority with_user_id] )) || return @tickets = @filterrific.find.page(params[:page]) respond_to do |format| format.html format.js end rescue ActiveRecord::RecordNotFound => e logger.debug("Had to reset filterrific params: #{e.message}") redirect_to(reset_filterrific_url(format: :html)) && return end def show respond_to do |format| format.html format.js end end def new; end def create @ticket = current_user.tickets.new(ticket_params) @ticket.status_of_ticket = :newly_created if @ticket.save UserMailer.ticket_email(@current_user).deliver flash[:success] = 'Ticket created' redirect_to tickets_path else flash[:warning] = 'Ticket not created' render :new end end def edit; end def update if @ticket.update(ticket_params) flash[:success] = 'Ticket updated' redirect_to tickets_path else flash[:warning] = 'Ticket not updated' render 'edit' end end def destroy if @ticket.destroy flash[:success] = 'Ticket deleted' redirect_to tickets_path else flash[:warning] = "Ticket doesn't exist" end end def take_in_work if current_user.executor? && @ticket.newly_created? @ticket.update(executor: current_user.email, status_of_ticket: 'in_progress') find_user_and_send_email redirect_to ticket_path else flash[:warning] = 'Action is not avalible' redirect_to root_path end end def resolved if current_user.email == @ticket.executor && @ticket.in_progress? @ticket.update(status_of_ticket: 'resolved') find_user_and_send_email redirect_to ticket_path else flash[:warning] = 'Action is not avalible' redirect_to root_path end end def closed if current_user.id == @ticket.user_id && @ticket.in_progress? @ticket.update(status_of_ticket: 'closed') find_executor_and_send_email redirect_to ticket_path else flash[:warning] = 'Action is not avalible' redirect_to root_path end end private def find_ticket @ticket = Ticket.find(params[:id]) end def ticket_params params.require(:ticket).permit(:title, :detailed_description, :type_of_ticket, :executor, :deadline, :history, :status_of_ticket, :responsible_unit, :attachment, :priority) end def ticket @ticket ||= Ticket.new end def owned_ticket if current_user.id != @ticket.user_id flash[:alert] = "That ticket doesn't belong to you!" redirect_to root_path end end def find_user_and_send_email @user = User.find_by(id: @ticket.user_id) UserMailer.take_in_work_email(@user, @ticket).deliver end def find_executor_and_send_email @executor = User.find_by(email: @ticket.executor) UserMailer.closed_email(@executor, @ticket).deliver end end
class AddUpdatedAtIndex < ActiveRecord::Migration def change add_index :handles, :updated_at end end
class Api::V1::RandomCustomersController < Api::ApiController respond_to :json def show respond_with Customer.random end end
# -*- encoding : utf-8 -*- require 'helper' class StringToBoolTest < Test::Unit::TestCase context "String to_bool" do should "return true" do assert "true".to_bool, "true" assert "1".to_bool, "1" assert "t".to_bool, "t" assert "y".to_bool, "y" assert "yes".to_bool, "yes" end should "return false" do assert ! "false".to_bool, "false" assert ! "0".to_bool, "0" assert ! "f".to_bool, "f" assert ! "no".to_bool, "no" assert ! "n".to_bool, "n" assert ! "".to_bool, "blank string" end should "raise exception on unknown" do assert_raises ArgumentError do "unknown string".to_bool end end end end
unless Vagrant.has_plugin?("vagrant-dsc") raise 'vagrant-dsc plugin is not installed! Please install with: vagrant plugin install vagrant-dsc' end $shell_script = <<SCRIPT # config desired state . C:\\vagrant\\powershell\\manifests\\LCMConfig.ps1 LCMConfig Set-DscLocalConfigurationManager -Path ".\\LCMConfig" SCRIPT Vagrant.configure(2) do |config| config.vm.box = "D:/boxes/Windows-2012-R2-base.box" config.vm.guest = :windows config.vm.communicator = "winrm" config.vm.provider "virtualbox" do |v| v.gui = true v.memory = 2048 v.cpus = 2 v.customize ["modifyvm", :id, "--vram", "128"] end config.winrm.username = "vagrant" config.winrm.password = "vagrant" config.ssh.insert_key = false config.vm.network "forwarded_port", guest: 80, host: 5555 # Create a private network, which allows host-only access to the machine # using a specific IP. config.vm.network "private_network", ip: "192.168.50.10" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. config.vm.synced_folder "./", "/vagrant_data" config.vm.provision "shell", inline: $shell_script config.vm.provision :dsc do |dsc| dsc.configuration_data_file = "powershell/manifests/Vagrant.psd1" dsc.configuration_file = "powershell/Config.ps1" dsc.module_path = ["powershell/modules"] dsc.temp_dir = "c:/tmp/vagrant-dsc" end end
class ExpenseType < ApplicationRecord # Associations has_many :finances has_many :banks end
def source <<eos protocol MyAwesomeProtocol { var foo:Int{get} } eos end def expected_tokens [ T_PROTOCOL, T_WHITESPACES(' '), T_IDENTIFIER('MyAwesomeProtocol'), T_WHITESPACES(' '), T_OPEN_CURLY_BRACKET, T_WHITESPACES("\n "), T_VAR, T_WHITESPACES(' '), T_IDENTIFIER('foo'), T_COLON, T_IDENTIFIER('Int'), T_OPEN_CURLY_BRACKET, T_GET, T_CLOSE_CURLY_BRACKET, T_WHITESPACES("\n"), T_CLOSE_CURLY_BRACKET, T_WHITESPACES("\n") ] end def expected_ast { __type: 'program', body: [ { __type: 'protocol-declaration', name: { __type: 'identifier', value: 'MyAwesomeProtocol' }, inheritances: [], declarations: [ { __type: 'property-declaration', name: { __type: 'identifier', value: 'foo' }, type: { __type: 'identifier', value: 'Int' }, accessors: [ { __type: 'getter-accessor' } ] } ] } ] } end load 'spec_builder.rb'
class Assignment < ApplicationRecord belongs_to :question belongs_to :assigner, :class_name => "User" belongs_to :assignee, :class_name => "User" after_create :create_notifications private # assign하면 assign 받은 사람에게 보내지는 노티 생성. def create_notifications Notification.create(recipient: self.assignee, actor: self.assigner, target: self) end end
require_relative '../../lib/modules/method_missing' #### # # AgentWith # # Makes a Agent hold a unique identifier. # # Import records for Agents do not have a human_ref that identifies # them. The identifier, instead, comes from the Property's human_ref. # # Identifying a Agent by the human_ref is only needed during the # import process. To achieve this I associate the human id of the property # during the import with this service class. # #### # class AgentWithId include MethodMissing attr_accessor :human_ref def initialize agent = Agent.new @source = agent end end
assert("utc_offset") do time = Time.local(2000, 1, 1, 11, 11, 11, 111111) utc_offset = time.utc_offset assert_kind_of(Integer, utc_offset) # Calculate local time offset (e.g. -06:00 if local time is CST) for subsequent tests utc_offset_minutes, _ = utc_offset.divmod(60) utc_offset_hours, utc_offset_minutes = utc_offset_minutes.divmod(60) utc_offset_sign = utc_offset_hours >= 0 ? '+' : '-' utc_offset_hours = utc_offset_hours.abs.to_s.rjust(2, '0') utc_offset_minutes = utc_offset_minutes.to_s.rjust(2, '0') @utc_offset_iso8601 = "#{utc_offset_sign}#{utc_offset_hours}:#{utc_offset_minutes}" end assert("ISO8601 generation (local)") do time = Time.local(2000, 1, 1, 11, 11, 11, 111111) assert_equal("2000-01-01T11:11:11#{@utc_offset_iso8601}", time.iso8601) assert_equal("2000-01-01T11:11:11.111111#{@utc_offset_iso8601}", time.iso8601(6)) end assert("ISO8601 generation (UTC)") do time = Time.utc(2000, 1, 1, 11, 11, 11, 111111) assert_equal("2000-01-01T11:11:11Z", time.iso8601) assert_equal("2000-01-01T11:11:11.1111110Z", time.iso8601(7)) end assert("ISO8601 generation (maximum available precision)") do time = Time.utc(2000, 1, 1, 0, 0, 0, 1) time_iso8601 = time.iso8601(6) assert_equal('2000-01-01T00:00:00.000001Z', time_iso8601) end assert("ISO8601 generation (precision does not round)") do time = Time.utc(2000, 1, 1, 11, 11, 11, 190000) assert_equal("2000-01-01T11:11:11.1Z", time.iso8601(1)) end assert("ISO8601 generation (zero padding when sub-microsecond precision requested)") do time = Time.utc(2000, 1, 1, 11, 11, 11, 111111) assert_equal("2000-01-01T11:11:11.111111000Z", time.iso8601(9)) end assert("Parse ISO8601 timestamp (local)") do parsed_time = Time.parse("2000-01-01T11:11:11.111111#{@utc_offset_iso8601}") assert_equal(Time.local(2000, 1, 1, 11, 11, 11, 111111), parsed_time) end assert("Parse ISO8601 timestamp (UTC)") do parsed_time = Time.parse("2000-01-01T11:11:11.111111Z") assert_equal(Time.utc(2000, 1, 1, 11, 11, 11, 111111), parsed_time) end assert("Parse ISO8601 timestamp (precision)") do parsed_time = Time.parse("2000-01-01T11:11:11.111Z") assert_equal(Time.utc(2000, 1, 1, 11, 11, 11, 111000), parsed_time) end assert("Parse ISO8601 timestamp (no subsecond precision)") do parsed_time = Time.parse("2000-01-01T11:11:11Z") assert_equal(Time.utc(2000, 1, 1, 11, 11, 11, 0), parsed_time) end assert("Parse ISO8601 timestamp that is not UTC or local (not supported on MRuby)") do utc_offset = @utc_offset_iso8601.dup if utc_offset[0] == '+' utc_offset[0] = '-' else utc_offset[0] = '+' end assert_raise(ArgumentError) do Time.parse("2000-01-01T11:11:11#{utc_offset}") end end
class ApplicationController < ActionController::Base before_filter :authorize, :checkAccess protect_from_forgery INACTIVITY_PERIOD = 60 CLOSED_ACTION_LIMIT = 3 layout "WardAreaBook" def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.record end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to login_path return false end end def require_no_user if current_user store_location flash[:notice] = "You must be logged out to access this page" redirect_to account_url return false end end def store_location session[:return_to] = request.fullpath end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end def load_session() user = current_user user.logged_in_now = true if user.person == nil user.person = Person.find_by_email(user.email) user.save! end person = user.person uri = session[:requested_uri] session[:user_email] = user.email session[:access_level] = person.access_level session[:user_name] = person.full_name session[:first_name] = person.name session[:user_id] = person.id session[:family_id] = person.family_id refresh_session # Landing page # first go to the todo page if they have any outstanding action items # then go to any uri that they may have been trying to access # if not go to the wardlist hasActions = user.person.open_action_items.size > 0 if hasActions redirect_to(:controller => 'users', :action => 'todo') elsif (uri != nil) and (uri =~ /login/i) == nil redirect_to(uri) else redirect_to(:controller => 'families') end end protected def authorize if session[:user_email] == nil flash[:notice] = "Please log in. Or click on the 'Create a new Account' link to the left" session[:requested_uri] = request.fullpath redirect_to login_path return end if (session[:expiration] == nil) or (session[:expiration] < Time.now) reset_session session[:requested_uri] = request.fullpath flash[:notice] = "User Session Expired. Please login." redirect_to login_path return end # Refresh the activity period refresh_session end def refresh_session session[:expiration] = INACTIVITY_PERIOD.minutes.from_now end def checkAccess # Make the default the most restrictive if hasAccess(2) true else deny_access end end def hasAccess(value) session[:access_level] >= value end def deny_access flash[:notice] = "User '#{session[:user_name]}' does not have access to that page" if request.env["HTTP_REFERER"] and !request.env["HTTP_REFERER"].include?("login") redirect_to :back else redirect_to "/todo" end return false end end
module NavigationHelpers def path_to(page_name) case page_name when /a page/ '/' when /a protected page/ '/dashboard' when /the dashboard/ '/dashboard' when /the signup page/ '/signup' when /the login page/ '/login' when /the logout page/ '/logout' when /the forgot password page/ '/forgot' else raise "Can't find mapping from \"#{page_name}\" to a path.\n" + "Now, go and add a mapping in #{__FILE__}" end end end World(NavigationHelpers)
require "json" require "selenium-webdriver" require "test/unit" class LogIn < Test::Unit::TestCase def setup @driver = Selenium::WebDriver.for :chrome @base_url = "https://staging.shore.com/merchant/sign_in" @accept_next_alert = true @driver.manage.timeouts.implicit_wait = 30 @verification_errors = [] end def teardown @driver.quit assert_equal [], @verification_errors end def test_create_recurring_appt target_size = Selenium::WebDriver::Dimension.new(1420, 940) @driver.manage.window.size = target_size @driver.get "https://staging.shore.com/merchant/sign_in" @driver.find_element(:id, "merchant_account_email").clear @driver.find_element(:id, "merchant_account_email").send_keys "js@shore.com" @driver.find_element(:id, "merchant_account_password").clear @driver.find_element(:id, "merchant_account_password").send_keys "secret" @driver.find_element(:name, "button").click @driver.get "https://staging.shore.com/merchant/bookings" sleep 3 checkbox = @driver.find_element(:css, "#serviceStepsCheckbox"); if checkbox.selected? checkbox.click else @driver.find_element(:css, "div.service-steps-config > form.simple_form.form-horizontal > div.tile-footer > input.btn-blue").click end @driver.find_element(:css, "div.service-steps-config > form.simple_form.form-horizontal > div.tile-footer > input.btn-blue").click sleep 2 #recurring week end after x appt sleep 2 @driver.find_element(:css, "i.shore-icon-backend-new-appointment").click @driver.find_element(:name, "customerSummary").click sleep 2 @driver.find_element(:css, "div.list-group.search-results > a:nth-of-type(1)").click sleep 2 @driver.find_element(:name, "subject").clear @driver.find_element(:name, "subject").send_keys "Automatic generated" @driver.find_element(:css, "#widgetManagerContainer > div > div > div > div.tabs-component-container.tabs-at-left.tabs-dir-ltr > div.tabs-panels-container > div.tab-content.center-block.show > div > div > div > div > div.panel.panel-overlay > div.body-container.maw-create-widget > div > form > div.panel-body > div:nth-child(3) > div:nth-child(2) > div > input:nth-child(1)").click sleep 3 @driver.find_element(:name, "showReccurrence").click sleep 3 @driver.find_element(:id, "recurrence-interval").clear @driver.find_element(:id, "recurrence-interval").send_keys "2" @driver.find_element(:css, "div.form-group.row > div:nth-of-type(2) > div > a > span:nth-of-type(1)").click @driver.find_element(:css, "ul > li:nth-of-type(2) > div").click @driver.find_element(:css, "div.form-group.row > div:nth-of-type(3) > div > a > span:nth-of-type(2)").click @driver.find_element(:css, "ul > li:nth-of-type(2) > div").click @driver.find_element(:id, "recurrence-count").clear @driver.find_element(:id, "recurrence-count").send_keys "6" @driver.find_element(:css, "#widgetManagerContainer > div > div > div > div.tabs-component-container.tabs-at-left.tabs-dir-ltr > div.tabs-panels-container > div.tab-content.center-block.show > div > div > div > div > div.panel.panel-overlay > div.body-container.maw-create-widget > div > form > div.panel-footer > button.btn.btn-primary.pull-right").click sleep 2 @driver.find_element(:css, "div.panel-body > div:nth-of-type(4) > div > div.has-feedback > div > ul > li > input").send_keys "Silent" @driver.action.send_keys(:enter).perform @driver.find_element(:css, "div.panel-body > div:nth-of-type(5) > div > div.has-feedback > div > ul > li > input").send_keys "James" @driver.action.send_keys(:enter).perform sleep 2 @driver.find_element(:css, "button.btn.btn-primary").click #recurring month never ending sleep 2 @driver.find_element(:css, "i.shore-icon-backend-new-appointment").click @driver.find_element(:name, "customerSummary").click sleep 2 @driver.find_element(:css, "div.list-group.search-results > a:nth-of-type(3)").click sleep 2 @driver.find_element(:name, "subject").clear @driver.find_element(:name, "subject").send_keys "Automatic generated" @driver.find_element(:css, "#widgetManagerContainer > div > div > div > div.tabs-component-container.tabs-at-left.tabs-dir-ltr > div.tabs-panels-container > div.tab-content.center-block.show > div > div > div > div > div.panel.panel-overlay > div.body-container.maw-create-widget > div > form > div.panel-body > div:nth-child(3) > div:nth-child(2) > div > input:nth-child(1)").click sleep 3 @driver.find_element(:name, "showReccurrence").click sleep 3 @driver.find_element(:id, "recurrence-interval").clear @driver.find_element(:id, "recurrence-interval").send_keys "2" @driver.find_element(:css, "div.form-group.row > div:nth-of-type(2) > div > a > span:nth-of-type(1)").click @driver.find_element(:css, "ul > li:nth-of-type(3) > div").click @driver.find_element(:css, "div.form-group.row > div:nth-of-type(3) > div > a > span:nth-of-type(2)").click @driver.find_element(:css, "ul > li:first-child > div").click @driver.find_element(:css, "#widgetManagerContainer > div > div > div > div.tabs-component-container.tabs-at-left.tabs-dir-ltr > div.tabs-panels-container > div.tab-content.center-block.show > div > div > div > div > div.panel.panel-overlay > div.body-container.maw-create-widget > div > form > div.panel-footer > button.btn.btn-primary.pull-right").click sleep 2 @driver.find_element(:css, "div.panel-body > div:nth-of-type(4) > div > div.has-feedback > div > ul > li > input").send_keys "Silent" @driver.action.send_keys(:enter).perform @driver.find_element(:css, "div.panel-body > div:nth-of-type(5) > div > div.has-feedback > div > ul > li > input").send_keys "James" @driver.action.send_keys(:enter).perform sleep 2 @driver.find_element(:css, "button.btn.btn-primary").click #recurring day ends on date sleep 2 @driver.find_element(:css, "i.shore-icon-backend-new-appointment").click @driver.find_element(:name, "customerSummary").click sleep 2 @driver.find_element(:css, "div.list-group.search-results > a:nth-of-type(2)").click sleep 2 @driver.find_element(:name, "subject").clear @driver.find_element(:name, "subject").send_keys "Automatic generated" @driver.find_element(:css, "#widgetManagerContainer > div > div > div > div.tabs-component-container.tabs-at-left.tabs-dir-ltr > div.tabs-panels-container > div.tab-content.center-block.show > div > div > div > div > div.panel.panel-overlay > div.body-container.maw-create-widget > div > form > div.panel-body > div:nth-child(3) > div:nth-child(2) > div > input:nth-child(1)").click sleep 3 @driver.find_element(:name, "showReccurrence").click sleep 3 @driver.find_element(:id, "recurrence-interval").clear @driver.find_element(:id, "recurrence-interval").send_keys "2" @driver.find_element(:css, "div.form-group.row > div:nth-of-type(2) > div > a > span:nth-of-type(1)").click @driver.find_element(:css, "ul > li:first-child > div").click @driver.find_element(:css, "div.form-group.row > div:nth-of-type(3) > div > a > span:nth-of-type(2)").click @driver.find_element(:css, "ul > li:nth-of-type(3) > div").click @driver.find_element(:id, "recurrence-ends-at").clear @driver.find_element(:id, "recurrence-ends-at").send_keys "11.11.2020" @driver.action.send_keys(:enter).perform @driver.find_element(:css, "div.panel-body > div:nth-of-type(4) > div > div.has-feedback > div > ul > li > input").send_keys "Silent" @driver.action.send_keys(:enter).perform @driver.find_element(:css, "div.panel-body > div:nth-of-type(5) > div > div.has-feedback > div > ul > li > input").send_keys "James" @driver.action.send_keys(:enter).perform sleep 3 @driver.action.send_keys(:enter).perform end def verify(&blk) yield rescue Test::Unit::AssertionFailedError => ex @verification_errors << ex end end
class BankOperation attr_reader :date, :credit, :debit, :new_balance def initialize(date, credit, debit, new_balance) @date = date @credit = credit @debit = debit @new_balance = new_balance end end
module ReportsKit module Reports module FilterTypes class Boolean < Base DEFAULT_CRITERIA = { value: nil } def apply_conditions(records) case conditions when ::String records.where("(#{conditions}) #{sql_operator} true") when ::Hash boolean_value ? records.where(conditions) : records.not.where(conditions) when ::Proc conditions.call(records) else raise ArgumentError.new("Unsupported conditions type: '#{conditions}'") end end def boolean_value case value when true, 'true' true when false, 'false' false else raise ArgumentError.new("Unsupported value: '#{value}'") end end def sql_operator boolean_value ? '=' : '!=' end def valid? value.present? end def conditions settings[:conditions] || Data::Utils.quote_column_name(properties[:key]) end end end end end
class AddIsDeletedToUserGroups < ActiveRecord::Migration[5.1] def change unless column_exists? :user_groups, :is_deleted add_column :user_groups, :is_deleted, :boolean, default: false end end end
require 'test_helper' class PhotoTest < ActiveSupport::TestCase test "should create a new photo" do photo = Photo.new(:image_description =>"S", :image_name =>"S_1.png", :image_type =>1) assert photo.save end test "should not create a new photo" do photo = Photo.new(:image_description =>"S", :image_name =>"S_1.png", :image_type =>21) assert !photo.save, "validates_length_of: image_type" end test "should be 6" do assert_equal 6, Photo.count end test "should find a photo" do assert Photo.find(:first) end test "should find 2 photos" do photo1 = Photo.find(:first) photo2 = Photo.find(:last) assert_not_same( photo1, photo2) end test "should destroy a photo" do Photo.find(:first).destroy assert_equal 5, Photo.count end test "should require uniqueness of an image name" do photo1 = Photo.new(:image_name => "P_1.png", :image_description => "P", :image_type => 1) photo2 = Photo.new(:image_name => "P_2.png", :image_description => "P", :image_type => 2) assert photo1.save assert photo2.save end test "should create a valid photo" do photo = Photo.new(valid_photo_attribute) assert photo.save end test "should create a valid photo require name" do photo = Photo.new(valid_photo_attribute(:image_name =>nil)) assert !photo.save, "image_name is missing" end test "should create a photo with required name legth" do photo = Photo.new(valid_photo_attribute(:image_name =>"TS_1.png")) assert !photo.save, "image_name is too long" end test "should create a unique photo" do photo1 = Photo.new(valid_photo_attribute) assert photo1.save photo2 = Photo.new(valid_photo_attribute) assert !photo2.save end end
class ProductSearchTask < ApplicationRecord has_many :amazon_products scope :active, -> { where(running: true) } def soft_page_limit 10 end def self.run_random_active_job active_jobs = self.active if active_jobs.any? active_jobs.sample.tick! else puts "Found no active jobs" end end def serialize_request_data(request_data) self.request_data_as_json = request_data.to_json end def completed finished = self.last_page and (self.current_page > self.last_page) limit_reached = (self.current_page >= self.soft_page_limit) limit_reached or finished end def make_request params = JSON.parse(request_data_as_json) AmazonProductApi.get_api_response(params, self.current_page) end def tick! if (self.completed or !self.running) self.running = false self.save return "Completed" end response = self.make_request results = response["ItemSearchResponse"]["Items"]["Item"] unless results.nil? results.each do |result| self.amazon_products.create_by_asin_if_unique(result["ASIN"]) end self.current_page += 1 self.save "Got #{results.length} results!" else "No results #{self.completed}" end end end
class Admin::ForumPostsController < ApplicationController before_filter :login_required before_filter :find_forum # GET /forums/1/forum_posts # GET /forums/1/forum_posts.xml def index @forum_posts = @forum.forum_posts.find(:all) respond_to do |format| format.html # index.rhtml format.xml { render :xml => @forum_posts.to_xml } end end # GET /forums/1/forum_posts/1 # GET /forums/1/forum_posts/1.xml def show @forum_post = ForumPost.find(params[:id]) # want to be able to pull up post without knowing forum respond_to do |format| format.html # show.rhtml format.xml { render :xml => @forum_post.to_xml } end end # GET /forums/1/forum_posts/new def new @forum_post = ForumPost.new end # GET /forums/1/forum_posts/1;edit def edit @forum_post = ForumPost.find(params[:id]) end # POST /forums/1/forum_posts # POST /forums/1/forum_posts.xml def create @forum_post = ForumPost.new(params[:forum_post]) @forum_post.forum_id = @forum respond_to do |format| if @forum_post.save flash[:notice] = 'ForumPost was successfully created.' format.html { redirect_to forum_post_url(:forum_id => @forum, :id => @forum_post) } format.xml { head :created, :location => forum_post_url(:forum_id => @forum, :id => @forum_post) } else format.html { render :action => "new" } format.xml { render :xml => @forum_post.errors.to_xml } end end end # PUT /forums/1/forum_posts/1 # PUT /forums/1/forum_posts/1.xml def update @forum_post = ForumPost.find(params[:id]) respond_to do |format| if @forum_post.update_attributes(params[:forum_post]) flash[:notice] = 'ForumPost was successfully updated.' format.html { redirect_to forum_post_url(:forum_id => @forum, :id => @forum_post) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @forum_post.errors.to_xml } end end end # DELETE /forums/1/forum_posts/1 # DELETE /forums/1/forum_posts/1.xml def destroy @forum_post = ForumPost.find(params[:id]) @forum_post.destroy respond_to do |format| format.html { redirect_to forum_posts_url(:forum_id => @forum) } format.xml { head :ok } end end # PUT /forums/1/forum_posts/1;reply # PUT /forums/1/forum_posts/1.xml;reply def reply reply_to = ForumPost.find(params[:id]) @forum_post = ForumPost.new(:parent_id => reply_to.id) render :action => :new end private def find_forum @forum_id = params[:forum_id] redirect_to forums_url unless @forum_id @forum = Forum.find(@forum_id) end end
#Clean Final # require_relative 'environment' require 'active_record' class CreateTables < ActiveRecord::Migration[5.0] def up create_table :movies do |t| t.string :title end create_table :ratings do |t| t.belongs_to :movie t.integer :movie_id t.integer :user_id t.integer :score end add_foreign_key :ratings, :movies, column: :movie_id, primary_key: "id" end def down drop_table :ratings drop_table :movies end end def main action = (ARGV[0] || :up).to_sym CreateTables.migrate(action) end main if __FILE__ == $PROGRAM_NAME
require 'dragonfly' require 'rails' module Dragonfly class Railtie < ::Rails::Railtie initializer "dragonfly.railtie.initializer" do |app| app.middleware.insert_before 'ActionDispatch::Cookies', Dragonfly::CookieMonster end initializer "dragonfly.railtie.load_app_instance_data" do |app| Railtie.config do |config| config.app_root = app.root end app.class.configure do #Pull in all the migrations from Dragonfly to the application #config.paths['db/migrate'] += ['db/migrate'] config.paths['db/migrate'] += config.paths["vendor/plugins"].existent end end #initializer "dragonfly.railtie.load_static_assets" do |app| # app.middleware.use ::ActionDispatch::Static, "#{root}/public" #end end end
class DropAuthorsBooksTable < ActiveRecord::Migration[5.1] def change drop_table :authors_books end end
class GigsController < ApplicationController # GET /gigs # GET /gigs.json def index @gigs = Gig.all respond_to do |format| format.html # index.html.erb format.json { render json: @gigs } end end # GET /gigs/1 # GET /gigs/1.json def show @gig = Gig.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @gig } end end # GET /gigs/new # GET /gigs/new.json def new @gig = Gig.new respond_to do |format| format.html # new.html.erb format.json { render json: @gig } end end # GET /gigs/1/edit def edit @gig = Gig.find(params[:id]) end # POST /gigs # POST /gigs.json def create @gig = Gig.new(params[:gig]) respond_to do |format| if @gig.save format.html { redirect_to @gig, notice: 'Gig was successfully created.' } format.json { render json: @gig, status: :created, location: @gig } else format.html { render action: "new" } format.json { render json: @gig.errors, status: :unprocessable_entity } end end end # PUT /gigs/1 # PUT /gigs/1.json def update @gig = Gig.find(params[:id]) respond_to do |format| if @gig.update_attributes(params[:gig]) format.html { redirect_to @gig, notice: 'Gig was successfully updated.' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @gig.errors, status: :unprocessable_entity } end end end # DELETE /gigs/1 # DELETE /gigs/1.json def destroy @gig = Gig.find(params[:id]) @gig.destroy respond_to do |format| format.html { redirect_to gigs_url } format.json { head :ok } end end end
module ActsAsOpengraphHelper NON_ESCAPED_ATTRIBUTES = %w(og:image og:url) # Generates the opengraph meta tags for your views # # @param [Object, #opengraph_data] obj An instance of your ActiveRecord model that responds to opengraph_data # @return [String] A set of meta tags describing your graph object based on the {http://ogp.me/ opengraph protocol} # @raise [ArgumentError] When you pass an instance of an object that doesn't responds to opengraph_data (maybe you forgot to add acts_as_opengraph in your model) # @example # opengraph_meta_tags_for(@movie) def opengraph_meta_tags_for(obj) raise(ArgumentError.new, "You need to call acts_as_opengraph on your #{obj.class} model") unless obj.respond_to?(:opengraph_data) tags = obj.opengraph_data.map do |att| att_name = att[:name] == "og:site_name" ? att[:name] : att[:name].dasherize if NON_ESCAPED_ATTRIBUTES.include? att_name %(<meta property="#{att_name}" content="#{att[:value]}"/>) else %(<meta property="#{att_name}" content="#{Rack::Utils.escape_html(att[:value])}"/>) end end tags = tags.join("\n") tags.respond_to?(:html_safe) ? tags.html_safe : tags end # Displays the Facebook Like Button in your views. # # @param [Object, #opengraph_data] obj An instance of your ActiveRecord model that responds to opengraph_data # @param [Hash] options A Hash of {http://developers.facebook.com/docs/reference/plugins/like/ supported attributes}. Defaults to { :layout => :standard, :show_faces => false, :width => 450, :action => :like, :colorscheme => :light } # @return [String] An iFrame version of the Facebook Like Button # @raise [ArgumentError] When you pass an instance of an object that doesn't responds to opengraph_data (maybe you forgot to add acts_as_opengraph in your model) # @example # like_button_for(@movie) # like_button_for(@movie, :layout => :button_count, :display_faces => true) # @example Specifying href using rails helpers # like_button_for(@movie, :href => movie_url(@movie)) def like_button_for(obj, options = {}) raise(ArgumentError.new, "You need to call acts_as_opengraph on your #{obj.class} model") unless obj.respond_to?(:opengraph_data) href = options[:href] ? options[:href] : obj.opengraph_url return unless href.present? config = { :layout => :standard, :show_faces => false, :width => 450, :action => :like, :colorscheme => :light } config.update(options) if options.is_a?(Hash) o_layout = config[:layout].to_sym if o_layout == :standard config[:height] = config[:show_faces].to_s.to_sym == :true ? 80 : 35 elsif o_layout == :button_count config[:height] = 21 elsif o_layout == :box_count config[:height] = 65 end config[:locale] ||= 'en_US' if config[:xfbml] unless @fb_sdk_included content_for :javascripts, fb_javascript_include_tag( config[:locale], config[:appid] ) end %(<fb:like href="#{CGI.escape(href)}" layout="#{config[:layout]}" show_faces="#{config[:show_faces]}" action="#{config[:action]}" colorscheme="#{config[:colorscheme]}" width="#{config[:width]}" height="#{config[:height]}" font="#{config[:font]}"></fb:like>) else %(<iframe src="http://www.facebook.com/plugins/like.php?href=#{CGI.escape(href)}&amp;layout=#{config[:layout]}&amp;show_faces=#{config[:show_faces]}&amp;width=#{config[:width]}&amp;action=#{config[:action]}&amp;colorscheme=#{config[:colorscheme]}&amp;height=#{config[:height]}" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:#{config[:width]}px; height:#{config[:height]}px;" allowTransparency="true"></iframe>) end end def fb_javascript_include_tag(appid='', locale='en_US') @fb_sdk_included = true async_fb = <<-END <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({appId: '#{ appid }', status: true, cookie: true, xfbml: true}); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/#{locale}/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script> END async_fb.html_safe end end
require "sinatra" class Hivemind < Sinatra::Base get "/activity" do @latest = Event.last(25) erb :"events/index" end end class Event < Sequel::Model def nice case kind.to_sym when :uploaded_epub user_link = %(<a class="underline hover:text-indigo-500" href="/@#{user.username}">@#{user.username}</a>) epub_link = %(<a class="underline hover:text-indigo-500" href="/epubs/#{epub.id}">#{epub.title}</a>) "#{user_link} uploaded #{epub_link}" when :created_collection user_link = %(<a class="underline hover:text-indigo-500" href="/@#{user.username}">@#{user.username}</a>) collection_link = %(<a class="underline hover:text-indigo-500" href="/collections/#{collection.id}">#{collection.title}</a>) "#{user_link} created #{collection_link}" when :read_epub user_link = %(<a class="underline hover:text-indigo-500" href="/@#{user.username}">@#{user.username}</a>) epub_link = %(<a class="underline hover:text-indigo-500" href="/epubs/#{epub.id}">#{epub.title}</a>) "#{user_link} marked #{epub_link} as read" end end def relevant? case kind.to_sym when :uploaded_epub epub.nil? || user.nil? ? false : true when :created_collection collection.nil? || user.nil? ? false : true when :read_epub epub.nil? || user.nil? ? false : true end end def epub @epub ||= EPub.find(id: metadata[:epub_id]) end def user @user ||= User.find(id: metadata[:user_id]) end def collection @collection ||= Collection.find(id: metadata[:collection_id]) end end
require 'rails_helper' RSpec.describe ItemPurchase, type: :model do before do @item_purchase = FactoryBot.build(:item_purchase) end describe '商品購入機能' do context '購入がうまくいくとき' do it 'すべての値が正しく入力されていれば購入できる' do expect(@item_purchase).to be_valid end it '建物名が空でも購入できる' do @item_purchase.building_name = '' expect(@item_purchase).to be_valid end end context '購入がうまくいかないとき' do it 'postal_codeが空では購入できない' do @item_purchase.postal_code = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("郵便番号を入力してください", "郵便番号はハイフン(-)を入力し、半角数字で入力してください") end it 'postal_codeに(-)が含まれてないと購入できない' do @item_purchase.postal_code = '1111111' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include('郵便番号はハイフン(-)を入力し、半角数字で入力してください') end it 'postal_codeが全角数字では購入できない' do @item_purchase.postal_code = '111−1111' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include('郵便番号はハイフン(-)を入力し、半角数字で入力してください') end it 'prefectureが---のままでは購入できない' do @item_purchase.prefecture_id = 1 @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("都道府県を選択してください") end it 'municipalityが空では購入できない' do @item_purchase.municipality = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("市区町村を入力してください", "市区町村は全角文字で入力してください") end it 'municipalityに半角英数が含まれていると購入できない' do @item_purchase.municipality = 'abc123' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include('市区町村は全角文字で入力してください') end it 'house_numberが空では購入できない' do @item_purchase.house_number = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("番地を入力してください", "番地は全角文字で入力してください") end it 'house_numberに英数が含まれていると半角では購入できない' do @item_purchase.house_number = 'a1-1-1' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include('番地は全角文字で入力してください') end it 'phone_numberが空では購入できない' do @item_purchase.phone_number = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("電話番号を入力してください", "電話番号は半角数字のみで入力してください") end it 'phone_numberが全角数字では購入できない' do @item_purchase.phone_number = '09012345678' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include('電話番号は半角数字のみで入力してください') end it 'phone_numberに(-)が含まれていると購入できない' do @item_purchase.phone_number = '0120111-111' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include('電話番号は半角数字のみで入力してください') end it 'tokenが空では購入できない' do @item_purchase.token = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("クレジットカード情報を入力してください") end it '商品IDが空の場合購入できない' do @item_purchase.user_id = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Userを入力してください") end it 'ユーザーIDが空の場合購入できない' do @item_purchase.item_id = '' @item_purchase.valid? expect(@item_purchase.errors.full_messages).to include("Itemを入力してください") end end end end
class SetDefaultRatingToItems < ActiveRecord::Migration[5.0] def change change_column :items, :rating, :float, :default => 3.5 end end
require 'rails_helper' RSpec.describe CabinetController, type: :controller do describe "GET #dashboard" do login_user it "returns http success" do get :dashboard expect(response).to have_http_status(:success) end it "renders the dashboard template" do get :dashboard expect(response).to render_template("dashboard") expect(response.body).to eq "" end end describe "GET #profile" do login_user it "returns http success" do get :profile expect(response).to have_http_status(:success) end it "renders the profile template" do get :profile expect(response).to render_template("profile") expect(response.body).to eq "" end end describe "GET #personal_info" do login_user it "returns http success" do get :personal_info expect(response).to have_http_status(:success) end it "renders the personal_info template" do get :personal_info expect(response).to render_template("personal_info") expect(response.body).to eq "" end end describe "GET #basic_info" do login_user it "returns http success" do get :basic_info expect(response).to have_http_status(:success) end it "renders the basic_info template" do get :basic_info expect(response).to render_template("basic_info") expect(response.body).to eq "" end end describe "GET #photos" do login_user it "returns http success" do get :photos expect(response).to have_http_status(:success) end it "renders the photos template" do get :photos expect(response).to render_template("photos") expect(response.body).to eq "" end end describe "GET #description" do login_user it "returns http success" do get :description expect(response).to have_http_status(:success) end it "renders the description template" do get :description expect(response).to render_template("description") expect(response.body).to eq "" end end describe "GET #verifications" do login_user it "returns http success" do get :verifications expect(response).to have_http_status(:success) end it "renders the verifications template" do get :verifications expect(response).to render_template("verifications") expect(response.body).to eq "" end end describe "GET #favorited_me" do login_user it "returns http success" do get :favorited_me expect(response).to have_http_status(:success) end it "renders the favorited_me template" do get :favorited_me expect(response).to render_template("favorited_me") expect(response.body).to eq "" end end describe "GET #favorites" do login_user it "returns http success" do get :favorites expect(response).to have_http_status(:success) end it "renders the favorites template" do get :favorites expect(response).to render_template("favorites") expect(response.body).to eq "" end end end
require 'rails_helper' RSpec.describe FavouriteLanguageController, :type => :controller do describe 'GET favourite-language/:username' do let(:service_factory) { Github::FavouriteLanguageService } let(:service) { instance_double(service_factory) } let(:service_result) { double('Result') } before { allow(service_factory).to receive(:new).and_return(service) allow(service).to receive(:call).and_return(service_result) get :show, username: 'github-username' } it 'calls the service with the username' do expect(service).to have_received(:call).with('github-username') end it 'response with OK' do expect(response).to have_http_status(:ok) end it 'assigns @page_map' do expect(assigns(:language)).to eq service_result expect(assigns(:username)).to eq 'github-username' end it 'renders domains/assets/index template' do expect(response).to render_template('favourite_language/show') end end end
require 'rails_helper' RSpec.describe ChoicesController, type: :request do let(:user) { FactoryBot.create(:user, :with_motherboard) } let(:motherboard) { user.motherboards.first } context 'signed in' do before(:each) { sign_in user } describe '#create' do subject { post "/board/#{motherboard.id}/choices", params: { topic_id: 'ABC', option_id: '123' } } it 'should create a new choice with the given topic and option ids' do expect { subject }.to change(Choice, :count).by(1) expect(response.body).to eq({ option_id: '123' }.to_json) end end describe '#destroy' do before(:each) do motherboard.choices.create(topic_id: 'ABC', option_id: '123') motherboard.pins.create(topic_id: 'ABC') end subject { delete "/board/#{motherboard.id}/choices/ABC" } it 'should delete the choice record matching the given topic id' do expect { subject }.to change(Choice, :count).by(-1) expect(response).to have_http_status(:ok) end it 'should also destroy corresponding pin record if exists' do expect { subject }.to change(Pin, :count).by(-1) expect(response).to have_http_status(:ok) end end end end
class IntToDec < ActiveRecord::Migration[5.0] def change reversible do |x| x.up do change_column :parts, :quantity, :decimal end x.down do change_column :parts, :quantity, :integer end end end end
class AddCounterCacheFieldsToUsers < ActiveRecord::Migration[6.0] def change add_column :users, :collected_coins_count, :integer, default: 0 add_column :users, :deaths_count, :integer, default: 0 add_column :users, :killed_monsters_count, :integer, default: 0 end end
Pod::Spec.new do |s| s.name = "XWTagView" s.version = "1.0.2" s.summary = "XWTagView" s.description = "awesome! XWTagView" s.homepage = "https://github.com/jprothwell/XWTagView" s.license = "MIT" s.author = "Leon" s.source = { :git => "https://github.com/jprothwell/XWTagView.git", :tag => s.version } s.source_files = "XWTagView/XWTagView/XWTagView/*.{h,m}" s.ios.deployment_target = "9.0" s.dependency 'YYText' end
################################### # # vrrichedit.rb # Programmed by nyasu <nyasu@osk.3web.ne.jp> # Copyright 2000-2005 Nishikawa,Yasuhiro # # More information at http://vruby.sourceforge.net/index.html # ################################### VR_DIR="vr/" unless defined?(::VR_DIR) require VR_DIR+'vrcontrol' require VR_DIR+'rscutil' require 'Win32API' module WMsg EM_EXGETSEL = WM_USER+52 EM_EXLINEFROMCHAR= WM_USER+54 EM_EXSETSEL = WM_USER+55 EM_GETCHARFORMAT = WM_USER+58 EM_GETEVENTMASK = WM_USER+59 EM_GETPARAFORMAT = WM_USER+61 EM_SETBKGNDCOLOR = WM_USER+67 EM_SETCHARFORMAT = WM_USER+68 EM_SETEVENTMASK = WM_USER+69 EM_SETPARAFORMAT = WM_USER+71 EM_FINDTEXTEX = WM_USER+79 EM_SETLANGOPTIONS= WM_USER+120 end class VRRichedit < VRText =begin == VRRichedit This class represents RichEdit Control. The parent class is VRText and this also has the same methods and event handlers. === Overwritten Methods These methods are overwritten to support over64k texts. --- getSel --- setSel(st,en,noscroll=0) --- char2line(ptr) === Methods --- setTextFont(fontface,height=280,area=SCF_SELECTION) Sets the text font. ((|area|)) parameter limits the changed area. --- getTextFont(selarea=true) Gets the text font and its size of the area. If selarea is true, the area is the selected area and the other case, it means the default font. --- setTextColor(col,area=SCF_SELECTION) Sets the color of the text in the area. --- getTextColor(selarea=true) Gets the text color in the area which is same as ((<getTextFont>)). --- setBold(flag=true,area=SCF_SELECTION) Sets or resets the text style into BOLD. When ((|flag|)) is true, the text is set to bold style. --- setItalic(flag=true,area=SCF_SELECTION) Sets or resets the text style into ITALIC. --- setUnderlined(flag=true,area=SCF_SELECTION) Sets or resets the text style into UNDERLINED. --- setStriked(flag=true,area=SCF_SELECTION) Sets or resets the text style into STRIKE_OUT. --- bold?(selarea=true) Inspects whether the text style in the area is bold or not. If ((|selarea|)) is true, the area is selected area. --- italic?(selarea=true) Inspects whether the text style in the area is italic or not. --- underlined?(selarea=true) Inspects whether the text style in the area is underlined or not. --- striked?(selarea=true) Inspects whether the text style in the area is striked out or not. --- setAlignment(align) Sets text alignment of current paragraph. ((|align|)) can be PFA_LEFT, PFA_RIGHT or PFA_CENTER of VRRichedit constansts. --- bkcolor=(color) Sets the background color of the control. --- selformat(area=SCF_SELECTION) Gets the text format in ((|area|)). The return value is an instance of FontStruct defined in rscutil.rb. --- selformat=(format) Set the text format in the selected area. ((|format|)) must be an instance of FontStruct. --- charFromPos(x,y) retrieves information about the character closest to a specified point in the client area. ((x)) is the horizontal coordinate. ((y)) is the vertical coordinate. the return value specifies character index by Fixnum. --- charLineFromPos(x,y) retrieves information about the character closest to a specified point in the client area. ((x)) is the horizontal coordinate. ((y)) is the vertical coordinate. the return value specifies character index and line index by Array. first item means character index. second item means line index. =end CFM_BOLD = 0x00000001 CFM_ITALIC = 0x00000002 CFM_UNDERLINE = 0x00000004 CFM_STRIKEOUT = 0x00000008 CFM_PROTECTED = 0x00000010 CFM_LINK = 0x00000020 CFM_SIZE = 0x80000000 CFM_COLOR = 0x40000000 CFM_FACE = 0x20000000 CFM_OFFSET = 0x10000000 CFM_CHARSET = 0x08000000 CFE_BOLD = 0x0001 CFE_ITALIC = 0x0002 CFE_UNDERLINE = 0x0004 CFE_STRIKEOUT = 0x0008 CFE_PROTECTED = 0x0010 CFE_LINK = 0x0020 CFE_AUTOCOLOR = 0x40000000 SCF_SELECTION = 0x0001 SCF_WORD = 0x0002 SCF_DEFAULT = 0x0000 SCF_ALL = 0x0004 # not valid with SCF_SELECTION or SCF_WORD SCF_USEUIRULES= 0x0008 PFA_LEFT = 0x0001 PFA_RIGHT = 0x0002 PFA_CENTER= 0x0003 PFM_STARTINDENT = 0x00000001 PFM_RIGHTINDENT = 0x00000002 PFM_OFFSET = 0x00000004 PFM_ALIGNMENT = 0x00000008 PFM_TABSTOPS = 0x00000010 PFM_NUMBERING = 0x00000020 PFM_OFFSETINDENT= 0x80000000 module EventMaskConsts ENM_CHANGE = 0x00000001 ENM_UPDATE = 0x00000002 ENM_SCROLL = 0x00000004 end class EventMask < Flags CONSTMOD=EventMaskConsts private def integer_getter @win.sendMessage WMsg::EM_GETEVENTMASK,0,0 end def integer_setter(f) @win.sendMessage WMsg::EM_SETEVENTMASK,0,f end end CHARFORMATSIZE=60 MAX_TAB_STOPS=32 DEFAULTTABS=[4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76] private loadlib = Win32API.new("kernel32","LoadLibrary",["P"],"I") libhandle = 0 =begin oop #This causes GeneralProtectionViolation maybe for the late of RichEdit releasing. freelib = Win32API.new("kernel32","FreeLibrary",["I"],"") at_exit { freelib.call(libhandle) } =end def textlength sendMessage WMsg::WM_GETTEXTLENGTH,0,0 end # ooooops ! if (libhandle=loadlib.call("riched20"))!=0 then RICHVERSION=2 def self.Controltype() ["RICHEDIT20A",WStyle::ES_MULTILINE|WStyle::WS_VSCROLL,0x200]#EX_CLIENTEDGE end elsif (libhandle=loadlib.call("riched32"))!=0 then RICHVERSION=1 def self.Controltype() ["RICHEDIT",WStyle::ES_MULTILINE|WStyle::WS_VSCROLL,0x200] #EX_CLIENTEDGE end else raise "no richedit control found" end public def richeditinit sendMessage WMsg::EM_SETLANGOPTIONS,0,0 eventmask.enm_change=true end def vrinit super richeditinit end def text len=textlength+1 buffer = "\0"*len sendMessage WMsg::WM_GETTEXT,len,buffer buffer[0..-2].gsub(/\r\n/,$/) end # parameter order is not the same of the return value of getcharformat() def setcharformat(area,effects,col=0,mask=0xf800003f, font="System",height=280,off=0,pf=2,charset=128) buffer = [CHARFORMATSIZE,mask,effects, height,off,col,charset,pf].pack("LLLLLLCC") buffer += font.to_s + "\0" buffer += "\0"*(CHARFORMATSIZE-buffer.length) sendMessage(WMsg::EM_SETCHARFORMAT,area,buffer) end def getcharformat(mask=0xf800003f,selectionarea=true) buffer = [CHARFORMATSIZE,0,0,0,0,0].pack("LLLLLL") buffer += "\0"* (CHARFORMATSIZE-buffer.length) f = (selectionarea)? 1 : 0 sendMessage WMsg::EM_GETCHARFORMAT,f,buffer return buffer.unpack("LLLLLLCC") << buffer[26..-2].delete("\0") end def getparaformat size=4*7+4*MAX_TAB_STOPS buffer = ([size]+Array.new(39)).pack("LLLLLLIIL*") sendMessage WMsg::EM_GETPARAFORMAT,0,buffer return buffer.unpack("LLLLLLIIL*") end def setparaformat(mask=0x8000003f,numbering=false,startindent=0,rightindent=0, offset=0,align=PFA_LEFT,tabstops=DEFAULTTABS) size=4*7+4*MAX_TAB_STOPS fNumber= if numbering then 1 else 0 end tabcount = (tabstops.size>MAX_TAB_STOPS)? MAX_TAB_STOPS : tabstops.size buffer = [ size,mask,fNumber,startindent,rightindent,offset,align,tabcount ].pack("LLLLLLII") buffer += tabstops.pack("L*") sendMessage WMsg::EM_SETPARAFORMAT,0,buffer end ## ## ## ## def getSel charrange = [0,0].pack("LL") sendMessage WMsg::EM_EXGETSEL,0,charrange return charrange.unpack("LL") end def setSel(st,en,noscroll=0) charrange = [st,en].pack("LL") r=sendMessage WMsg::EM_EXSETSEL,0,charrange if(noscroll!=0 && noscroll) then scrolltocaret end return r end def char2line(pt) sendMessage WMsg::EM_EXLINEFROMCHAR,0,pt end def setTextFont(fontface,height=280,area=SCF_SELECTION) setcharformat(area,0,0,CFM_FACE|CFM_SIZE,fontface,height) end def getTextFont(selarea=true) r=getcharformat(CFM_FACE|CFM_SIZE,selarea) return r[3],r[8] end def setTextColor(col,area=SCF_SELECTION) setcharformat(area,0,col,CFM_COLOR) end def getTextColor(selarea=true) getcharformat(CFM_COLOR,selarea)[5] end def setBold(flag=true,area=SCF_SELECTION) f = (flag)? CFE_BOLD : 0 setcharformat(area,f,0,CFM_BOLD) end def setItalic(flag=true,area=SCF_SELECTION) f = (flag)? CFE_ITALIC : 0 setcharformat(area,f,0,CFM_ITALIC) end def setUnderlined(flag=true,area=SCF_SELECTION) f = (flag)? CFE_UNDERLINE : 0 setcharformat(area,f,0,CFM_UNDERLINE) end def setStriked(flag=true,area=SCF_SELECTION) f = (flag)? CFE_STRIKEOUT : 0 setcharformat(area,f,0,CFM_STRIKEOUT) end def bold?(selarea=true) r=getcharformat(CFM_BOLD,selarea)[2] if (r&CFE_BOLD)==0 then false else true end end def italic?(selarea=true) r=getcharformat(CFM_ITALIC,selarea)[2] if (r&CFE_ITALIC)==0 then false else true end end def underlined?(selarea=true) r=getcharformat(CFM_UNDERLINE,selarea)[2] if (r&CFE_UNDERLINE)==0 then false else true end end def striked?(selarea=true) r=getcharformat(CFM_STRIKEOUT,selarea)[2] if (r&CFE_STRIKEOUT)==0 then false else true end end def getAlignment return self.getparaformat[6] end def setAlignment(align) setparaformat(PFM_ALIGNMENT,false,0,0,0,align) end def selformat=(f) raise "format must be an instance of FontStruct" unless f.is_a?(FontStruct) effects = f.style*2 + if f.weight>400 then 1 else 0 end height = if f.height>0 then f.height else f.point*2 end offset=0 setcharformat SCF_SELECTION,effects,f.color,0xf800003f,f.fontface,height, offset,f.pitch_family,f.charset f end def selformat(option=SCF_SELECTION) r=getcharformat(option) weight = if (r[2] & 1)>0 then 600 else 300 end style = (r[2]/2) & 0xf #mask width = r[3]/2 # tekitou.... point = r[3]/2 FontStruct.new2([r[8],r[3],style,weight,width,0,0,r[7],r[6]],point,r[5]) end def bkcolor=(col) if col then sendMessage WMsg::EM_SETBKGNDCOLOR,0,col.to_i else sendMessage WMsg::EM_SETBKGNDCOLOR,1,0 end end def eventmask EventMask.new(self) end def charFromPos(x,y) # Thanks to yas return sendMessage 0x00D7,0,[x,y].pack('ll') #EM_CHARFROMPOS end def charLineFromPos(x,y) pos=charFromPos(x,y) ln=char2line(pos) return [pos,ln] end end
class RecipesController < ApplicationController include PublicIndex #load_and_authorize_resource before_action :find_recipe, only: [:show, :edit, :destroy, :update] before_action :build_comment, only: :show skip_before_action :authenticate_user!, only: [:index, :show] def index if params[:tag] @recipes = Recipe.tagged_with(params[:tag]).page(params[:page]).per(10) else @recipes = Recipe.order('created_at DESC').page(params[:page]).per(10) @loves = Recipe.order('created_at DESC').page(params[:page]).per(10) end end def new @recipe = Recipe.new respond_with(@purchase = Purchase.new) end def edit end def addtolove @recipe = Recipe.find(params[:format]) @recipe.love_id=current_user.id @recipe.save redirect_to recipes_path end def destroy @recipe.destroy redirect_to recipes_path end def create @recipe = Recipe.new(recipe_params) @recipe.owner_id = current_user.id #upload=Cloudinary::Uploader.upload(purchase_params[:image]) unless purchase_params[:image].blank? #@purchase.image_file_name=upload['url'] unless purchase_params[:image].blank? #@recipe.image.save if @recipe.save #lo redirect_to recipes_path else render 'new' end end def update if @recipe.update(recipe_params) redirect_to recipe_path(@recipe) else redirect_to edit_recipe_path(@recipe) end end def show @recipe = Recipe.find(params[:id]) end private def find_recipe @recipe = Recipe.find(params[:id]) end def recipe_params params.require(:recipe).permit(:name, :description, :image, :short, :tag_list) end def build_comment @new_comment = Comment.build_from(@recipe, current_user, '') end end
class GeneralSettingsController < ApplicationController def new @general_setting = current_user.general_setting end end
module Payment class BankSlip < Base include IuguBase def self.taxes 2.50 end private def payment_method 'bank_slip' end def taxes self.class.taxes end def due_date { due_date: Date.today.in_time_zone.strftime('%d/%m/%Y') } end def charge_param { method: 'bank_slip' } end end end
require 'rails_helper' describe Post do it { is_expected.to have_many(:comments).dependent(:destroy) } it {is_expected.to belong_to(:user) } 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) require 'faker' #create users 10.times do user = User.new( name: Faker::Name.name, email: Faker::Internet.email, password: Faker::Lorem.characters(10) ) user.skip_confirmation! user.save! end #create one user which I can access easily test_user = User.new( name: 'test', email: 'tpalid@gmail.com', password: 'helloworld' ) test_user.skip_confirmation! test_user.save! users = User.all #create items, randomly assigned to users 50.times do Item.create!( user: users.sample, body: Faker::Lorem.sentence, end_date: Date.today + 10.days, public: true ) end 50.times do Item.create!( user: users.sample, body: Faker::Lorem.sentence, created_at: Date.today - 10.days, end_date: Date.today + 10.days, public: true ) end #check that seeding was successful puts "Seed complete" puts "#{User.count} users created" puts "#{Item.count} items created"
class CoordinatorSemestersController < WebApplicationController before_action :set_coordinator_semester, only: [:show, :edit, :update, :destroy] # GET /coordinator_semesters # GET /coordinator_semesters.json def index @semester = ( params[:semester] == nil ? Semester.where( current: true ).first : Semester.find( params[:semester] ) ) @coordinator_semesters = CoordinatorSemester.where( semester: @semester ).order( created_at: :desc ) end # GET /coordinator_semesteres/current def current @semester = ( params[:semester] == nil ? @current_semester : Semester.find( params[:semester] ) ) render json: User.where( id: CoordinatorSemester.where( semester: @semester ).pluck( :coordinator_id ) ).select(:id, :name, :lastname).map { |c| { id: c.id, name: "#{c.name} #{c.lastname}"} }, status: 200 end # GET /coordinator_semesters/1 # GET /coordinator_semesters/1.json def show end # GET /coordinator_semesters/new def new @coordinator_semester = CoordinatorSemester.new end # GET /coordinator_semesters/1/edit def edit end # POST /coordinator_semesters # POST /coordinator_semesters.json def create @coordinator_semester = CoordinatorSemester.new(coordinator_semester_params) respond_to do |format| if @coordinator_semester.save format.html { redirect_to coordinator_semesters_url, notice: 'Coordinator semester was successfully created.' } format.json { render :show, status: :created, location: @coordinator_semester } else format.html { render :new } format.json { render json: @coordinator_semester.errors, status: :unprocessable_entity } end end end # PATCH/PUT /coordinator_semesters/1 # PATCH/PUT /coordinator_semesters/1.json def update respond_to do |format| if @coordinator_semester.update(coordinator_semester_params) format.html { redirect_to coordinator_semesters_url, notice: 'Coordinator semester was successfully updated.' } format.json { render :show, status: :ok, location: @coordinator_semester } else format.html { render :edit } format.json { render json: @coordinator_semester.errors, status: :unprocessable_entity } end end end # DELETE /coordinator_semesters/1 # DELETE /coordinator_semesters/1.json def destroy @coordinator_semester.destroy respond_to do |format| format.html { redirect_to coordinator_semesters_url, notice: 'Coordinator semester was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_coordinator_semester @coordinator_semester = CoordinatorSemester.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def coordinator_semester_params params.require(:coordinator_semester).permit(:coordinator_id, :semester_id, :notes) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Api::V1::StagingController do login_admin describe '#get_countries' do it 'returns a successful 200 response' do get :get_countries expect(response).to be_successful end it 'returns a set of country data that includes all Carmen countries' do country_count = Carmen::Country.all.size get :get_countries parsed_response = JSON.parse(response.body) expect(parsed_response['countries'].size).to eq(country_count) end it 'returns subregions for each country that include all Carmen subregions for that country' do us = Carmen::Country.coded('US') subregion_count = us.subregions.reject { |subregion| subregion.type == 'apo' }.size get :get_countries parsed_response = JSON.parse(response.body) us_subregions = parsed_response['countries'].find { |country| country['code'] == 'US' }['subregions'] expect(us_subregions.size).to eq(subregion_count) end end describe '#get_time_zones' do it 'returns a successful 200 response' do get :get_time_zones expect(response).to be_successful end it 'returns an array of all ActiveSupport::TimeZone names and offsets' do tz_count = ActiveSupport::TimeZone.all.size get :get_time_zones parsed_response = JSON.parse(response.body) expect(parsed_response['time_zones'].size).to eq(tz_count) end it 'returns both names and formatted offsets for each time zone' do eastern_time_zone_name = 'Eastern Time (US & Canada)' eastern = ActiveSupport::TimeZone[eastern_time_zone_name] get :get_time_zones parsed_response = JSON.parse(response.body) eastern_response = parsed_response['time_zones'].find { |tz| tz.first == eastern_time_zone_name } expect(eastern_response.last).to eq(eastern.formatted_offset) end end describe '#post_event_course_org' do let(:event) { create(:event, event_group: event_group, course: course) } let(:event_group) { create(:event_group, organization: organization) } let(:course) { create(:course) } let(:organization) { create(:organization) } let(:event_id) { event.to_param } let(:new_event_indicator) { 'new' } let(:existing_event_params) { event.attributes.with_indifferent_access.slice(*EventParameters.permitted) } let(:existing_event_group_params) { event_group.attributes.with_indifferent_access.slice(*EventGroupParameters.permitted) } let(:existing_course_params) { course.attributes.with_indifferent_access.slice(*CourseParameters.permitted) } let(:existing_organization_params) { organization.attributes.with_indifferent_access.slice(*OrganizationParameters.permitted) } let(:updated_event_params) { {} } let(:updated_event_group_params) { {} } let(:updated_course_params) { {} } let(:updated_organization_params) { {} } let(:params) { {event: event_params, event_group: event_group_params, course: course_params, organization: organization_params} } context 'when an existing event_id is provided' do let(:event_params) { existing_event_params.merge(updated_event_params) } let(:event_group_params) { existing_event_group_params.merge(updated_event_group_params) } let(:course_params) { existing_course_params.merge(updated_course_params) } let(:organization_params) { existing_organization_params.merge(updated_organization_params) } it 'returns a successful 200 response' do status, _ = post_with_params(event_id, params) expect(status).to eq(200) end context 'when attributes are provided for an existing organization' do let(:updated_organization_params) { {name: 'Updated Organization Name', description: 'Updated organization description'} } it 'updates provided attributes for an existing organization' do status, resources = post_with_params(event_id, params) expected_attributes = {organization: updated_organization_params} expect(status).to eq(200) validate_response(resources, expected_attributes) end end context 'when attributes are provided for an existing course' do let(:updated_course_params) { {name: 'Updated Course Name', description: 'Updated course description'} } it 'updates provided attributes for an existing course' do status, resources = post_with_params(event_id, params) expected_attributes = {course: updated_course_params} expect(status).to eq(200) validate_response(resources, expected_attributes) end end context 'when attributes are provided for an existing event' do let(:updated_event_params) { {short_name: 'Updated Short Name', laps_required: 3} } it 'updates provided attributes for an existing event' do status, resources = post_with_params(event_id, params) expected_attributes = {event: updated_event_params} expect(status).to eq(200) validate_response(resources, expected_attributes) end end context 'when attributes are provided for an existing event_group' do let(:new_event_group_params) { {name: 'Updated Event Group Name'} } it 'updates provided attributes for the existing event_group' do skip 'until front end is fully event_group aware' status, resources = post_with_params(event_id, params) expected_attributes = {event_group: updated_event_group_params} expect(status).to eq(200) validate_response(resources, expected_attributes) end end end context 'when a new event_id is provided' do let(:new_event_params) { {short_name: '50M', start_time: '2017-03-01 06:00:00', laps_required: 1} } let(:new_event_group_params) { {name: 'New Event Name', home_time_zone: 'Pacific Time (US & Canada)'} } let(:new_course_params) { {name: 'New Course Name', description: 'New course description.'} } let(:new_organization_params) { {name: 'New Organization Name'} } let(:event_id) { new_event_indicator } context 'when the event and event_group are new but the course and organization already exist' do let(:event_params) { new_event_params } let(:event_group_params) { new_event_group_params } let(:course_params) { existing_course_params } let(:organization_params) { existing_organization_params } it 'returns a successful 200 response' do status, _ = post_with_params(event_id, params) expect(status).to eq(200) end it 'creates an event and event_group using provided parameters and associates existing course and organization' do status, resources = post_with_params(event_id, params) expected_attributes = {event: new_event_params, event_group: new_event_group_params} expect(status).to eq(200) validate_response(resources, expected_attributes) expect(resources[:event].slug).to eq("#{new_event_group_params[:name]} #{new_event_params[:short_name]}".parameterize) end end context 'when the event is new but the event_group, course, and organization already exist' do let(:event_params) { new_event_params } let(:event_group_params) { existing_event_group_params } let(:course_params) { existing_course_params } let(:organization_params) { existing_organization_params } it 'creates an event using provided parameters and associates existing event_group, course, and organization' do skip 'until front end is fully event_group aware' status, resources = post_with_params(event_id, params) expected_attributes = {event: new_event_params, event_group: existing_event_group_params, course: existing_course_params, organization: existing_organization_params} expect(status).to eq(200) validate_response(resources, expected_attributes) expect(resources[:event].slug).to eq("#{existing_event_group_params[:name]} (#{new_event_params[:short_name]})".parameterize) end end context 'when the event_group, course, and organization are new' do let(:event_params) { new_event_params } let(:event_group_params) { new_event_group_params } let(:course_params) { new_course_params } let(:organization_params) { new_organization_params } it 'creates an event using provided parameters and associates newly created event_group, course, and organization' do status, resources = post_with_params(event_id, params) expected_attributes = {event: new_event_params, event_group: new_event_group_params} expect(status).to eq(200) validate_response(resources, expected_attributes) expect(resources[:event].slug).to eq("#{new_event_group_params[:name]} (#{new_event_params[:short_name]})".parameterize) end end context 'when the event cannot be created' do let(:event_params) { new_event_params.except(:start_time) } let(:event_group_params) { new_event_group_params } let(:course_params) { new_course_params } let(:organization_params) { new_organization_params } it 'returns a bad request message with descriptive errors and provided data and creates no resources' do status, _, parsed_response = post_with_params(event_id, params) expected_errors = [/Start time can't be blank/] expect(status).to eq(422) validate_errors(parsed_response, expected_errors) validate_no_resources_created end end context 'when the course cannot be created' do let(:event_params) { new_event_params } let(:event_group_params) { new_event_group_params } let(:course_params) { new_course_params.except(:name) } let(:organization_params) { new_organization_params } it 'returns a bad request message with descriptive errors and provided data and creates no resources' do status, _, parsed_response = post_with_params(event_id, params) expected_errors = [/Name can't be blank/] expect(status).to eq(422) validate_errors(parsed_response, expected_errors) validate_no_resources_created end end context 'when the organization cannot be created' do let(:event_params) { new_event_params } let(:event_group_params) { new_event_group_params } let(:course_params) { new_course_params } let(:organization_params) { new_organization_params.except(:name) } it 'returns a bad request message with descriptive errors and provided data and creates no resources' do status, _, parsed_response = post_with_params(event_id, params) expected_errors = [/Name can't be blank/] expect(status).to eq(422) validate_errors(parsed_response, expected_errors) validate_no_resources_created end end end def post_with_params(event_id, params) passed_params = {id: event_id, event_group: params[:event_group], event: params[:event], course: params[:course], organization: params[:organization]} post :post_event_course_org, params: passed_params status = response.status parsed_response = JSON.parse(response.body) if status == 200 resources = {event: Event.find_by(id: parsed_response['event']['id']), event_group: EventGroup.find_by(id: parsed_response['event_group']['id']), course: Course.find_by(id: parsed_response['course']['id']), organization: Organization.find_by(id: parsed_response['organization']['id'])} else resources = {} end [status, resources, parsed_response] end def validate_response(resources, expected_attributes) event = resources[:event] event_group = resources[:event_group] course = resources[:course] organization = resources[:organization] expect(event.event_group_id).to eq(event_group.id) expect(event.course_id).to eq(course.id) expect(event_group.organization_id).to eq(organization.id) expected_attributes.each do |class_name, attributes| attributes.each_key do |attribute_key| expect(resources[class_name].attributes.with_indifferent_access[attribute_key]) .to eq(attributes[attribute_key]) end end end def validate_errors(parsed_response, expected_errors) message_array = parsed_response['errors'].flat_map { |error| error['detail']['messages'] } expected_errors.each do |error_text| expect(message_array).to include(error_text) end end def validate_no_resources_created expect(Event.count).to eq(11) expect(Course.count).to eq(8) expect(Organization.count).to eq(4) expect(EventGroup.count).to eq(8) end end describe '#update_event_visibility' do subject(:make_request) { patch :update_event_visibility, params: {id: event.to_param, status: status} } let(:event_group) { event_groups(:dirty_30) } let(:organization) { event_group.organization } let(:event) { event_group.events.first } context 'when params[:status] == "public"' do let(:status) { 'public' } it 'returns a successful 200 response' do make_request expect(response).to be_successful end it 'sets concealed status of the event_group, organization, and people to false' do preset_concealed(true) make_request event_group.reload organization.reload expect(event_group.concealed).to eq(false) expect(organization.concealed).to eq(false) people = event_group.events.flat_map { |event| event.efforts.map(&:person) }.compact people.each do |person| expect(person.concealed).to eq(false) end end end context 'when params[:status] == "private"' do let(:event_group) { event_groups(:ramble) } let(:status) { 'private' } it 'returns a successful 200 response' do make_request expect(response).to be_successful end it 'sets concealed status of the event_group, organization, and people to true' do preset_concealed(false) make_request event_group.reload organization.reload expect(event_group.concealed).to eq(true) expect(organization.concealed).to eq(true) people = event_group.events.flat_map { |event| event.efforts.map(&:person) }.compact people.each do |person| expect(person.concealed).to eq(true) end end context 'for people that have other visible efforts' do let(:event_group) { event_groups(:dirty_30) } it 'does not make them private' do preset_concealed(false) make_request event_group.reload organization.reload expect(event_group.concealed).to eq(true) expect(organization.concealed).to eq(false) people = event_group.events.flat_map { |event| event.efforts.map(&:person) }.compact people.each do |person| if person.efforts.size == 1 expect(person.concealed).to eq(true) else expect(person.concealed).to eq(false) end end end end context 'when params[:status] is not "public" or "private"' do it 'returns a bad request response' do patch :update_event_visibility, params: {id: event.to_param, status: 'random'} expect(response).to be_bad_request end end context 'when the event_id does not exist' do it 'returns a not found response' do patch :update_event_visibility, params: {id: 123, status: 'public'} expect(response).to be_not_found end end end def preset_concealed(boolean) event_group.update(concealed: boolean) organization.update(concealed: boolean) people = event_group.events.flat_map { |event| event.efforts.map(&:person) }.compact people.each { |person| person.update(concealed: boolean) } end end end
require 'rails_helper' RSpec.describe PlayerSerializer, :type => :serializer do let(:organization) { build(:organization, :name => 'Save Dave') } let(:user) { build(:user, :name => 'John Doe', :image => 'ugly-picture.jpg') } let(:player) { build(:player, :organization => organization, :user => user, :finished_at => DateTime.current, :score => 5) } before { allow(player).to receive(:rounds_left).and_return(5) } before { allow(player).to receive(:winner?).and_return(true) } subject { serialize(player, PlayerSerializer, :include => 'organization') } it { is_expected.to serialize_attribute(:roundsLeft).with(5) } it { is_expected.to serialize_attribute(:organization).with('Save Dave') } it { is_expected.to serialize_attribute(:finished?).with(true) } it { is_expected.to serialize_attribute(:name).with('John Doe') } it { is_expected.to serialize_attribute(:image).with('ugly-picture.jpg') } it { is_expected.to serialize_attribute(:score).with(5) } it { is_expected.to serialize_attribute(:winner?).with(true) } it { is_expected.to serialize_included(organization).with(OrganizationSerializer) } end
class CreateEpisodes < ActiveRecord::Migration def change create_table :episodes do |t| t.integer :season t.integer :episode_number t.string :title t.date :airdate t.integer :show_id end add_index :episodes, :show_id end end
module Watchdog class Error < StandardError def initialize(meth, from, to) mtype = to.is_a?(Module) ? '#' : '.' super self.class::MESSAGE % [from, "#{to}#{mtype}#{meth}"] end end class MethodExistsError < Error MESSAGE = "%s not allowed to redefine existing method %s" end class ExtensionMethodExistsError < Error MESSAGE = "%s not allowed to redefine extension method from %s" end end
# == Schema Information # # Table name: projects # # id :integer not null, primary key # name :string(255) # created_at :datetime not null # updated_at :datetime not null # class Project < ActiveRecord::Base has_many :team_memberships, conditions: { invitation_accepted: true } has_many :users, through: :team_memberships has_many :issues attr_accessible :name validates :name, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false } def owner @owner ||= team_memberships.find_by_owner(true).user end def self.names Project.all.map(&:name) end def active_issues issues.find_all { |issue| !issue.closed? } end def closed_issues issues.find_all { |issue| issue.closed? } end def open_invitations TeamMembership.find_all_by_project_id(id).find_all { |tm| !tm.invitation_accepted? } end end
# ------------ # Question #1 # ------------ # class SecretFile # attr_accessor :log # attr_reader :data # def initialize(secret_data, log) # @data = secret_data # @log = log # end # def display_data # log.create_log_entry # puts data # end # end # class SecurityLogger # def create_log_entry # p @entry = Time.new # end # end # passwords = SecretFile.new('amazon: 12345', SecurityLogger.new) # passwords.display_data # ------------ # Question #2 # ------------ # module Fuelable # def fuel_specs(km_traveled_per_liter, liters_of_fuel_capacity) # @fuel_efficiency = km_traveled_per_liter # @fuel_capacity = liters_of_fuel_capacity # end # def range # @fuel_capacity * @fuel_efficiency # end # end # class WheeledVehicle # attr_accessor :speed, :heading # def tire_specs(tire_array) # @tires = tire_array # end # def tire_pressure(tire_index) # @tires[tire_index] # end # def inflate_tire(tire_index, pressure) # @tires[tire_index] = pressure # end # end # class Auto < WheeledVehicle # include Fuelable # def initialize # fuel_specs(50, 25.0) # # 4 tires are various tire pressures # tire_specs([30,30,32,32]) # end # end # class Motorcycle < WheeledVehicle # include Fuelable # def initialize # fuel_specs(80, 8.0) # # 2 tires are various tire pressures # tire_specs([20,20]) # end # end # class Catamaran # include Fuelable # attr_accessor :propeller_count, :hull_count, :speed, :heading # def initialize(num_propellers, num_hulls) # # fuel_specs(??, ??)... # end # end # ------------ # Question #3 # ------------ # module Moveable # attr_accessor :speed, :heading # attr_writer :fuel_capacity, :fuel_efficiency # def range # @fuel_capacity * @fuel_efficiency # end # end # class FloatedVehicle # include Moveable # attr_accessor :propeller_count, :hull_count # def initialize(km_traveled_per_liter, liters_of_fuel_capacity, num_propellers=1, num_hulls=1) # self.propeller_count = num_propellers # self.hull_count = num_hulls # self.fuel_efficiency = km_traveled_per_liter # self.fuel_capacity = liters_of_fuel_capacity # end # end # class WheeledVehicle # include Moveable # def initialize(tire_array, km_traveled_per_liter, liters_of_fuel_capacity) # @tires = tire_array # self.fuel_efficiency = km_traveled_per_liter # self.fuel_capacity = liters_of_fuel_capacity # end # def tire_pressure(tire_index) # @tires[tire_index] # end # def inflate_tire(tire_index, pressure) # @tires[tire_index] = pressure # end # end # class Auto < WheeledVehicle # def initialize # # 4 tires are various tire pressures # super([30,30,32,32], 50, 25.0) # end # end # class Motorcycle < WheeledVehicle # def initialize # # 2 tires are various tire pressures # super([20,20], 80, 8.0) # end # end # class Catamaran < FloatedVehicle # def initialize(km_traveled_per_liter, liters_of_fuel_capacity, num_propellers, num_hulls) # super(km_traveled_per_liter, liters_of_fuel_capacity, num_propellers, num_hulls) # end # end # class Motorboat < FloatedVehicle # def initialize(km_traveled_per_liter, liters_of_fuel_capacity) # super(km_traveled_per_liter, liters_of_fuel_capacity) # end # end # ------------ # Question #4 # ------------ module Moveable attr_accessor :speed, :heading, :range, :fuel_capacity, :fuel_efficiency def range @range += (@fuel_capacity * @fuel_efficiency) end end class FloatedVehicle include Moveable attr_accessor :propeller_count, :hull_count, :fuel_efficiency, :fuel_specs def initialize(km_traveled_per_liter, liters_of_fuel_capacity, num_propellers=1, num_hulls=1) self.propeller_count = num_propellers self.hull_count = num_hulls self.fuel_efficiency = km_traveled_per_liter self.fuel_capacity = liters_of_fuel_capacity @range = 10 end end class WheeledVehicle include Moveable def initialize(tire_array, km_traveled_per_liter, liters_of_fuel_capacity) @tires = tire_array self.fuel_efficiency = km_traveled_per_liter self.fuel_capacity = liters_of_fuel_capacity @range = 0 end def tire_pressure(tire_index) @tires[tire_index] end def inflate_tire(tire_index, pressure) @tires[tire_index] = pressure end end class Auto < WheeledVehicle def initialize # 4 tires are various tire pressures super([30,30,32,32], 50, 25.0) end end class Motorcycle < WheeledVehicle def initialize # 2 tires are various tire pressures super([20,20], 80, 8.0) end end class Catamaran < FloatedVehicle def initialize(km_traveled_per_liter, liters_of_fuel_capacity, num_propellers, num_hulls) super end end class Motorboat < FloatedVehicle def initialize(km_traveled_per_liter, liters_of_fuel_capacity) super end end p Motorboat.ancestors
class ServiceContractsController < ApplicationController breadcrumb "Service Contracts", :service_contracts_path, match: :exact before_action :get_service_contract, except: [:index, :new, :create] def index @service_contracts = ServiceContract.paginate(page: params[:page], per_page: 10) end def show breadcrumb @service_contract.source_headline, service_contract_path(@service_contract) end def new head(404) and return unless can?(current_user, :create) breadcrumb "New Service Contract", new_service_contract_path @service_contract = ServiceContract.new end def edit head(404) and return unless can?(current_user, :edit) breadcrumb @service_contract.source_headline, service_contract_path(@service_contract), match: :exact breadcrumb 'Edit', edit_service_contract_path(@service_contract) end def create head(404) and return unless can?(current_user, :create) @service_contract = ServiceContract.new(service_contract_params) respond_to do |format| if @service_contract.save format.html {redirect_to @service_contract, flash: {success: 'Service Contract Created Successfully'}} else format.json {render json: @service_contract.errors, status: :unprocessable_entity} end end end def update head(404) and return unless can?(current_user, :edit) respond_to do |format| if @service_contract.update(@service_contract_params) format.html {redirect_to @service_contract, flash: {success: 'Service Contract Updated Successfully'}} else format.json {render json: @service_contract.errors, status: :unprocessable_entity} end end end def destroy head(404) and return unless can?(current_user, :destroy) @service_contract.destroy respond_to do |format| format.html {redirect_to service_contracts_url, notice: 'Service Contract was successfully destroyed.'} format.json {head :ok} end end private def service_contract_params params.require(:service_contract).permit(:source_headline, :date, :link, :status, :sector, :lifecycle_phase, :contract_description, :duration, :currency, :contract_value,) end def get_service_contract @service_contract = ServiceContract.find(params[:id]) end end
# # Cookbook:: KafkaServer # Spec:: Install # # Copyright:: 2019, The Authors, All Rights Reserved. require 'spec_helper' describe 'KafkaServer::Install' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7') runner.converge(described_recipe) end it 'converges successfully' do expect { chef_run }.to_not raise_error end it 'installs java, git and tmux' do expect(chef_run).to install_package 'java-1.8.0-openjdk-devel, git, tmux' end it 'creates kafkaAdmin group' do expect(chef_run).to create_group('kafkaAdmin') end it 'creates kafkaAdmin user' do expect(chef_run).to create_user('kafkaAdmin').with( manage_home: false, shell: '/bin/nologin', group: 'kafkaAdmin', home: '/home/kafkaAdmin' ) end it 'creates kafka directory' do expect(chef_run).to create_directory('/opt/kafka_2.12-2.3.0').with( group: 'kafkaAdmin' ) end it 'gets kafka package' do expect(chef_run).to create_remote_file('/opt/kafka_2.12-2.3.0.tgz').with( source: 'https://www-eu.apache.org/dist/kafka/2.3.0/kafka_2.12-2.3.0.tgz' ) end it 'unpacks kafka package' do expect(chef_run).to run_execute('tar -xvf /opt/kafka_2.12-2.3.0.tgz -C /opt/kafka_2.12-2.3.0 --strip-components=1') end it 'creates symlink' do expect(chef_run).to run_execute('ln -s /opt/kafka_2.12-2.3.0 /opt/kafka') end it 'creates porper permissions' do expect(chef_run).to run_execute('chown -R kafkaAdmin:kafkaAdmin /opt/kafka*') end it 'creates zookeeper.service' do expect(chef_run).to create_template('/etc/systemd/system/zookeeper.service').with( source: 'zookeeper.service.erb', owner: 'root', group: 'root' ) end it 'creates kafka.service' do expect(chef_run).to create_template('/etc/systemd/system/kafka.service').with( source: 'kafka.service.erb', owner: 'root', group: 'root' ) end it 'reloads systemctl' do expect(chef_run).to run_execute('systemctl daemon-reload') end it 'starts zookeeper service' do expect(chef_run).to start_service 'zookeeper' end it 'starts kafka service' do expect(chef_run).to start_service 'kafka' end it 'cleans temp packages' do expect(chef_run).to delete_file('/opt/kafka_2.12-2.3.0.tgz') end end