text
stringlengths
10
2.61M
hours_in_a_year = 24 * 365 puts "There are #{hours_in_a_year} hours in a year." minutes_in_a_decade = (hours_in_a_year * 60) * 10 puts "There are #{minutes_in_a_decade} minutes in a decade." seconds_per_year = ((hours_in_a_year * 60) * 60) age_in_seconds = seconds_per_year * 31 puts "I am approximately #{age_in_seconds} seconds old." chris_pine_age_in_seconds = 1160000000 puts "Chris Pine is #{chris_pine_age_in_seconds / seconds_per_year} years old."
class AddOenologistRefToWineOenologist < ActiveRecord::Migration[6.0] def change add_reference :wine_oenologists, :oenologist, null: false, foreign_key: true end end
class CreateIngestStatuses < ActiveRecord::Migration def change create_table :ingest_statuses do |t| t.string :state t.string :staff t.date :date t.text :notes t.integer :collection_id t.timestamps end end end
require 'rails_helper' RSpec.describe "books/new", type: :view do before(:each) do assign(:book, Book.new( title: "MyString", description: "MyText", edition: 1, pages: 1, format: "MyString", availability: false, author: nil, publisher: nil, category: nil )) end it "renders new book form" do render assert_select "form[action=?][method=?]", books_path, "post" do assert_select "input[name=?]", "book[title]" assert_select "textarea[name=?]", "book[description]" assert_select "input[name=?]", "book[edition]" assert_select "input[name=?]", "book[pages]" assert_select "input[name=?]", "book[format]" assert_select "input[name=?]", "book[availability]" assert_select "input[name=?]", "book[author_id]" assert_select "input[name=?]", "book[publisher_id]" assert_select "input[name=?]", "book[category_id]" end end end
# frozen_string_literal: true require 'ripper' # A lot of the rules use pattern matching to match against ripper's statements, # so it's kind of annoying to get constant warnings about pattern matching being # experimental. Turning it off here. Warning.singleton_class.prepend( Module.new do def warn(warning) super unless warning.include?('experimental') end end ) require 'rblint/version' require 'rblint/parser' require 'rblint/rules' require 'rblint/reporter' require 'rblint/runner' module RbLint def self.lint(pattern, config = {}) Runner.new.run(pattern, config) end end
# frozen_string_literal: true module Catalog class AutocompletesController < ApplicationController NUM_RESULTS = 10 def show render json: serialized_taxa end private def serialized_taxa taxa.map do |taxon| Autocomplete::TaxonSerializer.new(taxon).as_json(include_protonym: include_protonym?) end end def taxa Autocomplete::TaxaQuery[search_query, rank: rank, per_page: NUM_RESULTS] end def search_query params[:q] || params[:qq] || '' end def rank params[:rank] end def include_protonym? params[:include_protonym].present? end end end
class Administration::ProvisionsController < ApplicationController before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ] protect_from_forgery with: :null_session, :only => [:destroy, :delete] def index @provision = Provision.where('order_id IS NOT NULL') render layout: false end def show @provision = Provision.find(params[:id]) @total_without_igv = 0 @igv = 0 @total_with_igv = 0 @provision.provision_direct_purchase_details.each do |provision_detail| @total_without_igv += provision_detail.unit_price_before_igv.to_f @igv += provision_detail.quantity_igv.to_f @total_with_igv += (provision_detail.unit_price_before_igv.to_f+provision_detail.quantity_igv.to_f-provision_detail.discount_after.to_f).to_f end render layout: false end def new @provision = Provision.new @documentProvisions = DocumentProvision.all @cost_center = get_company_cost_center("cost_center") render layout: false end def create # Si es una provision de Compra Directa provision = Provision.new(provision_direct_purchase_parameters) flag = Provision.where("entity_id = ? AND series = ? AND number_document_provision = ? AND document_provision_id = 1", provision.entity_id, provision.series,provision.number_document_provision) if flag.count == 0 if provision.save provision.provision_direct_purchase_details.each do |pdpd| if pdpd.type_order == "purchase_order" pod = PurchaseOrderDetail.find(pdpd.order_detail_id) if pdpd.amount.to_f == pod.amount.to_f pod.update_attributes(:received_provision => 1) else pod.update_attributes(:received_provision => nil) end elsif pdpd.type_order == "service_order" ood = OrderOfServiceDetail.find(pdpd.order_detail_id) if pdpd.amount.to_f == ood.amount.to_f ood.update_attributes(:received => 1) else ood.update_attributes(:received => nil) end end end flash[:notice] = "Se ha creado correctamente la nueva provision." redirect_to :controller => :provision_articles, :action => :index else provision.errors.messages.each do |attribute, error| flash[:error] = flash[:error].to_s + error.to_s + " " end # Load new() @provision = provision redirect_to :controller => :provision_articles, :action => :new end else flash[:error] = "Ya existe esa factura registrada" # Load new() @provision = Provision.new(provision_direct_purchase_parameters) redirect_to :controller => :provision_articles, :action => :new end end def edit @provision = Provision.find(params[:id]) @documentProvisions = DocumentProvision.all @account_accountants = AccountAccountant.where("code LIKE '_______'") @reg_n = ((Time.now.to_f)*100).to_i @action = 'edit' render layout: false end def update provision = Provision.find(params[:id]) ver_ids = Array.new ver_type = Array.new provision.provision_direct_purchase_details.each do |det| ver_ids << det.order_detail_id ver_type << det.type_order end provision.update_attributes(provision_direct_purchase_parameters) if !ver_ids.include?(nil) ver_ids.each do |vid| if provision.provision_direct_purchase_details.where("order_detail_id = " + vid.to_s).empty? if ver_type[ver_ids.index(vid)] == "purchase_order" PurchaseOrderDetail.find(vid).update_attributes(:received_provision => nil) elsif ver_type[ver_ids.index(vid)] == "service_order" OrderOfServiceDetail.find(vid).update_attributes(:received => nil) end end end provision.provision_direct_purchase_details.each do |det| if det.type_order == "purchase_order" order = PurchaseOrderDetail.find(det.order_detail_id) if order.amount == det.amount order.update_attributes(:received_provision => 1) else order.update_attributes(:received_provision => nil) end elsif det.type_order == "service_order" order = OrderOfServiceDetail.find(det.order_detail_id) if order.amount == det.amount order.update_attributes(:received => 1) else order.update_attributes(:received => nil) end end end end flash[:notice] = "Se ha actualizado correctamente los datos." redirect_to :controller => :provision_articles, :action => :index rescue ActiveRecord::StaleObjectError provision.reload flash[:error] = "Alguien más ha modificado los datos en este instante. Intente Nuevamente." redirect_to :action => :index, company_id: params[:company_id] end def destroy provision = Provision.find(params[:id]) # BEGIN Return all Orders to Received Null order_ids = provision.provision_details.select(:order_detail_id).map(&:order_detail_id) if provision.provision_details.first.type_of_order == 'purchase_order' PurchaseOrderDetail.where(:id => order_ids).each do |purchase_order_detail| purchase_order_detail.update_attributes(:received_provision => nil) end elsif provision.provision_details.first.type_of_order == 'service_order' OrderOfService.where(:id => order_ids).each do |order_service| order_service.update_attributes(:received => nil) end end # END Return all Orders to Received Null provision.provision_details.destroy_all provision_destroyed = Provision.destroy(params[:id]) flash[:notice] = "Se ha eliminado correctamente." render :json => provision end #CUSTOM METHODS def display_orders supplier = params[:supplier] @supplier_obj = Entity.find(supplier) @orders_po = ActiveRecord::Base.connection.execute("SELECT DISTINCT po.id, po.date_of_issue, po.code, po.description FROM purchase_orders po, purchase_order_details pod, delivery_order_details dod WHERE po.state = 'approved' AND po.id = pod.purchase_order_id AND pod.delivery_order_detail_id = dod.id AND pod.received_provision IS NULL AND po.cost_center_id = " + get_company_cost_center('cost_center').to_s + " AND po.entity_id = " + supplier.to_s) @orders_oos = ActiveRecord::Base.connection.execute("SELECT DISTINCT po.id, po.date_of_issue, po.code, po.description FROM order_of_services po, order_of_service_details pod WHERE po.state = 'approved' AND po.id = pod.order_of_service_id AND pod.received IS NULL AND po.cost_center_id = " + get_company_cost_center('cost_center').to_s + " AND po.entity_id = " + supplier.to_s) render(:partial => 'table_list_orders', :layout => false) end def display_details_orders orders = params[:data_orders] @data_orders = Array.new @igv = FinancialVariable.where("name LIKE '%IGV%'").first.value # IGV in Percent if !orders.nil? orders.each do |ord| type = ord.split("-") if type[0]=="OC" if PurchaseOrder.find(type[1]).approved? PurchaseOrder.find(type[1]).purchase_order_details.each do |purchase_detail| if !purchase_detail.received_provision detail_order = purchase_detail.delivery_order_detail # Lo que falta Atender pending = 0 current_amount = 0 currency = '' provision = ProvisionDirectPurchaseDetail.where(order_detail_id: purchase_detail.id) if provision.count > 0 provision.each do |prov| current_amount += prov.amount end pending = purchase_detail.amount.to_f - current_amount.to_f else pending = purchase_detail.amount.to_f end currency = purchase_detail.purchase_order.money.symbol data_pod = PurchaseOrderDetail.calculate_amounts(purchase_detail.id, pending, purchase_detail.unit_price, @igv) order_code = "OC - " + purchase_detail.purchase_order.code if pending.to_f > 0.0 @data_orders << [ detail_order.article.code, detail_order.article.name, purchase_detail.amount, data_pod[5].round(2), purchase_detail.unit_price, purchase_detail.description, purchase_detail.id, pending, currency, 'purchase', (purchase_detail.quantity_igv.to_f).round(2), data_pod[3].round(2), order_code ] end end end end elsif type[0]=="OS" if OrderOfService.find(type[1]).approved? OrderOfService.find(type[1]).order_of_service_details.each do |service_detail| if !service_detail.received # Lo que falta Atender pending = 0 current_amount = 0 currency = '' provision = ProvisionDetail.where(order_detail_id: service_detail.id) if provision.count > 0 provision.each do |prov| current_amount += prov.amount end pending = service_detail.amount - current_amount else pending = service_detail.amount end currency = service_detail.order_of_service.money.symbol rescue 'S/.' order_code = "OS - " + service_detail.order_of_service.code @data_orders << [ service_detail.article.code, service_detail.article.name, service_detail.amount, (service_detail.unit_price_igv.to_f + service_detail.discount_after.to_f), service_detail.unit_price_before_igv.to_f, service_detail.description, service_detail.id, pending, currency, 'service', (service_detail.quantity_igv.to_f*-1).round(2), service_detail.unit_price_before_igv.to_f.round(2), order_code ] end end end end end end render(:partial => 'table_list_details_orders', :layout => false) end def puts_details_in_provision @data_orders = Array.new order_detail_ids = params[:ids_orders_details] # @type_of_order_name = params[:type_of_order] # = hidden_field_tag 'provision[provision_details_attributes][' + @reg_n.to_s + '][type_of_order]', @type_of_order_name @reg_n = ((Time.now.to_f)*100).to_i @account_accountants = AccountAccountant.where("code LIKE '_______'") @sectors = Sector.where("code LIKE '__' AND cost_center_id = " + get_company_cost_center('cost_center').to_s) @phases = Phase.getSpecificPhases(get_company_cost_center('cost_center')).sort order_detail_ids.each do |order_detail_id| data = order_detail_id.split('-') if data[1]!="" if data[1]== 'purchase' @order = PurchaseOrderDetail.find(data[0]) @order_ec = @order.purchase_order_extra_calculations.where("apply LIKE 'before' AND extra_calculation_id = 1") @type_order = "purchase_order" @article_id = @order.delivery_order_detail.article.id @article_code = @order.delivery_order_detail.article.code @article_name = @order.delivery_order_detail.article.name @article_unit = @order.delivery_order_detail.article.unit_of_measurement.symbol @money = @order.purchase_order.money.symbol @sector = @order.delivery_order_detail.sector_id @phase = @order.delivery_order_detail.phase_id @code = @order.purchase_order.code.to_s.rjust(5, '0') @money_id = @order.purchase_order.money_id @exchange_rate = @order.purchase_order.exchange_of_rate elsif data[1]== 'service' @order = OrderOfServiceDetail.find(data[0]) @order_ec = @order.order_service_extra_calculations.where("apply LIKE 'before' AND extra_calculation_id = 1") @type_order = "service_order" @article_id = @order.article.id @article_code = @order.article.code @article_name = @order.article.name @article_unit = @order.article.unit_of_measurement.symbol @money = @order.order_of_service.money.symbol @sector = @order.sector_id @phase = @order.phase_id @code = @order.order_of_service.code.to_s.rjust(5, '0') @money_id = @order.order_of_service.money_id @exchange_rate = @order.order_of_service.exchange_of_rate end end if @order.igv @igv = 0.18 else @igv = 0 end # Lo que falta Atender pending = 0 total = 0 provision = ProvisionDirectPurchaseDetail.where("order_detail_id = "+ @order.id.to_s) if provision.count > 0 amount = 0 provision.each do |pd| amount += pd.amount.to_f end pending = @order.amount.to_f - amount.to_f else pending = @order.amount end con_igv = pending.to_f*@order.unit_price.to_f discounts_before = 0 @order_ec.each do |extra_calculation| if extra_calculation.type == 'percent' value = extra_calculation.value.to_f/100 if extra_calculation.operation == "sum" discounts_before += (con_igv*value)*-1 else discounts_before += con_igv*value end elsif extra_calculation.type == 'soles' value = extra_calculation.value.to_f if extra_calculation.operation == "sum" discounts_before += (value*-1) else discounts_before += value end end end if @igv > 0.00 quantity_igv = (con_igv.to_f-discounts_before.to_f)*@igv.to_f else quantity_igv = 0 end @data_orders << [ @order.id, @article_code, @article_name, @article_unit, pending, @order.unit_price, discounts_before, (con_igv.to_f-discounts_before.to_f).round(4).round(2), @igv, quantity_igv.round(4).round(2), ((con_igv.to_f-discounts_before.to_f)*(1+@igv.to_f)).round(4).round(2), @money, @article_id, @code, @sector, @phase, @type_order, @money_id, @exchange_rate ] end render(:partial => 'row_detail_provision', :layout => false) end def get_tc_with_date tc = ExchangeOfRate.where("day = ?",params[:date]) @tc = Array.new tc.each do |tc| @tc << {'value'=>tc.value, 'flag'=>true} end render json: {:tc => @tc} end def get_suppliers_by_type_order str_options = '' aux = Array.new if params[:type] == 'purchase_order' PurchaseOrder.all.each do |purchase| if !aux.include? purchase.entity.id aux << purchase.entity.id str_options += ('<option value=' + purchase.entity.id.to_s + '>' + purchase.entity.ruc.to_s + ' - ' + purchase.entity.name.to_s + ' ' + purchase.entity.paternal_surname.to_s + ' ' + purchase.entity.maternal_surname.to_s + '</option>') end end elsif params[:type] == 'service_order' OrderOfService.all.each do |service| if !aux.include? service.entity.id aux << service.entity.id str_options += ('<option value=' + service.entity.id.to_s + '>' + service.entity.ruc.to_s + ' - ' + service.entity.name.to_s + ' ' + service.entity.paternal_surname.to_s + ' ' + service.entity.maternal_surname.to_s + '</option>') end end end render json: {:suppliers => str_options} end private def provision_direct_purchase_parameters params.require(:provision).permit( :cost_center_id, :entity_id, :document_provision_id, :lock_version, :number_document_provision, :accounting_date, :series, :rendicion, :description, :number_of_guide, :money_id, :exchange_of_rate, provision_direct_purchase_details_attributes: [ :id, :provision_id, :article_id, :sector_id, :phase_id, :account_accountant_id, :amount, :price, :lock_version, :unit_price_before_igv, :igv, :quantity_igv, :flag, :type_order, :order_detail_id, :discount_before, :unit_price_igv, :description, :_destroy, provision_direct_extra_calculations_attributes: [ :id, :provision_direct_purchase_detail_id, :extra_calculation_id, :value, :apply, :operation, :type, :_destroy ] ] ) end end
# https://groups.google.com/forum/#!msg/rubyonrails-security/ANv0HDHEC3k/mt7wNGxbFQAJ module ActiveSupport module SecurityUtils def secure_compare(a, b) return false unless a.bytesize == b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end module_function :secure_compare def variable_size_secure_compare(a, b) secure_compare(::Digest::SHA256.hexdigest(a), ::Digest::SHA256.hexdigest(b)) end module_function :variable_size_secure_compare end end module ActionController class Base def self.http_basic_authenticate_with(options = {}) before_action(options.except(:name, :password, :realm)) do authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password| # This comparison uses & so that it doesn't short circuit and # uses `variable_size_secure_compare` so that length information # isn't leaked. ActiveSupport::SecurityUtils.variable_size_secure_compare(name, options[:name]) & ActiveSupport::SecurityUtils.variable_size_secure_compare(password, options[:password]) end end end end end
require 'sinatra/base' require 'mongo' require 'erb' require 'oauth2' require_relative 'helpers' $temp_table = $db_client[:temp] def get_client OAuth2::Client.new(ENV['BUFFER_CLIENT_ID'], ENV['BUFFER_CLIENT_ID'], site: 'https://bufferapp.com', authorize_url: '/oauth2/authorize', token_url: 'https://api.bufferapp.com/1/oauth2/token.json' ) end # Buffer uses OAuth2 for user authentication. class BufferAuth < Sinatra::Base # I want to use sessions, but I can't. Use mongo instead. get '/install_buffer/:team_id/:channel_id' do # TODO validate that these are team_ids and channel_ids we've seen before! team_id = params[:team_id] channel_id = params[:channel_id] client = get_client redirect client.auth_code.authorize_url(redirect_uri: 'https://' + ENV['HOST'] + '/install_buffer/finish/'+team_id+'/'+channel_id) end get '/install_buffer/finish/:team_id/:channel_id' do team_id = params[:team_id] channel_id = params[:channel_id] client = get_client access_token = client.auth_code.get_token(params[:code], client_id: ENV['BUFFER_CLIENT_ID'], client_secret: ENV['BUFFER_CLIENT_SECRET'], redirect_uri: 'https://' + ENV['HOST'] + '/install_buffer/finish/'+team_id+'/'+channel_id ) # Store the token that we need to make API calls doc = $tokens.find({team_id: params[:team_id]}).first doc['buffer_tokens'][params[:channel_id]] = {oauth_token: access_token.token} $tokens.update_one({team_id: params[:team_id]}, doc) status 200 body "Buffer configured!" end end
require 'rails_helper' describe Product do describe '#to_request' do it 'returns an instance of Prestashop Mapper' do product = Product.new(name: 'Foo', price: 1000) expect(product.to_request).to be_an_instance_of Prestashop::Mapper::Product end end end
require 'test/unit' $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'dieroll.rb' class TestOdds< Test::Unit::TestCase def setup @d4 = Dieroll::Odds.new [1,1,1,1] @two_d4 = @d4 * @d4 end def teardown end def test_init assert_equal [1, 1, 1, 1], @d4.instance_variable_get("@combinations_array") assert_equal 4, @d4.instance_variable_get("@combinations_total") assert_equal [0.25, 0.25, 0.25, 0.25], @d4.instance_variable_get("@odds_array") assert_equal 8, @two_d4.instance_variable_get("@max_result") assert_equal 5, @two_d4.instance_variable_get("@mean") assert_equal 2.5, @two_d4.instance_variable_get("@variance") assert_equal 1.5811, @two_d4.instance_variable_get("@standard_deviation"). round(4) end def test_equal assert_equal 0.25, @d4.equal(1) assert_equal 0, @d4.equal(6) end def test_greater_than assert_equal 0.75, @d4.greater_than(1) assert_equal 0, @d4.greater_than(4) end def test_greater_than_or_equal assert_equal 1.00, @d4.greater_than_or_equal(1) assert_equal 0.25, @d4.greater_than_or_equal(4) end def test_less_than assert_equal 0, @d4.less_than(1) assert_equal 0.75, @d4.less_than(4) end def test_less_than_or_equal assert_equal 0.25, @d4.less_than_or_equal(1) assert_equal 1.00, @d4.less_than_or_equal(4) end def test_multiply assert_equal [0.0625, 0.125, 0.1875, 0.25, 0.1875, 0.125, 0.0625], @two_d4.instance_variable_get("@odds_array") end def test_exponentiate assert_equal [0.0625, 0.125, 0.1875, 0.25, 0.1875, 0.125, 0.0625], (@d4**2).instance_variable_get("@odds_array") end def test_add assert_equal [0.25, 0.25, 0.25, 0.25], (@d4+1).instance_variable_get("@odds_array") assert_equal 2, (@d4+1).instance_variable_get("@offset") assert_equal [0.25, 0.25, 0.25, 0.25], (@d4+(-1)).instance_variable_get("@odds_array") assert_equal 0, (@d4+(-1)).instance_variable_get("@offset") end def test_subtract assert_equal [0.25, 0.25, 0.25, 0.25], (@d4-1).instance_variable_get("@odds_array") assert_equal 0, (@d4-1).instance_variable_get("@offset") assert_equal [0.25, 0.25, 0.25, 0.25], (@d4-(-1)).instance_variable_get("@odds_array") assert_equal 2, (@d4-(-1)).instance_variable_get("@offset") end def test_table end end
#Simple Calculator Program #Tealeaf April 2013 Cohort - 1st Cohort #Janie Kashiwa Li puts "What is the first number?" num1 = gets.chomp puts "What is the second number?" num2 = gets.chomp puts "The two numbers are #{num1} and #{num2}. " puts "What operation would you like to perform? 1) add 2)subtract 3)multiply 4) divide" operator = gets.chomp puts "You chose to #{operator}" if operator == '1' result = num1.to_i + num2.to_i elsif operator == '2' result = num1.to_i - num2.to_i elsif operator == '3' result = num1.to_i * num2.to_i elsif operator == '4' result = num1.to_f / num2.to_f end puts "Nice, you chose #{operator} and you got #{result}"
class Metadato < ActiveRecord::Base before_save :valida_object_name after_save :asocia_metadatos has_many :metadato_especies, :class_name => 'MetadatoEspecie', :foreign_key => 'metadato_id', :dependent => :destroy def valida_object_name # Quita las siguientes cadenas: sp.$ | sp. | ssp. | sp$ | ssp$ | sp..$ | ssp..$ object = [] # Lo separo por comas porque puede haber mas de una especie object_name.split(',').each do |obj| object << obj.squeeze('.').gsub(/( ssp.$)|( ssp. )|( ssp.)|( ss[p.]$)|( ss[p.] )|( sp$)|( sp )/, ' subsp. ').squeeze(' ').strip end self.object_name=object.join(',') end def asocia_metadatos object_name.split(',').each do |obj| next unless taxon = Especie.where(:nombre_cientifico => obj).first next if MetadatoEspecie.where(:especie_id => taxon, :metadato_id => self).first me = MetadatoEspecie.new(:especie_id => taxon.id, :metadato_id => id) me.save usuario = Usuario.where(:usuario => CONFIG.usuario.to_s).first.id me.fotos_bi(usuario.id) end end end
# frozen_string_literal: true module Aws module SQS module Plugins # @api private class QueueUrls < Seahorse::Client::Plugin # Extract region from a provided queue_url class Handler < Seahorse::Client::Handler def call(context) if (queue_url = context.params[:queue_url]) update_endpoint(context, queue_url) update_region(context, queue_url) end @handler.call(context) end def update_endpoint(context, url) context.http_request.endpoint = url end # If the region in the queue url is not the configured # region, then we will modify the request to have # a sigv4 signer for the proper region. def update_region(context, queue_url) if (queue_region = parse_region(queue_url)) if queue_region != context.config.region config = context.config.dup config.region = queue_region config.sigv4_region = queue_region config.sigv4_signer = Aws::Plugins::SignatureV4.build_signer(config) context.config = config end end end private # take the first component after the SQS service component # Will return us-east-1 for: # https://sqs.us-east-1.amazonaws.com/1234567890/demo # https://vpce-x-y.sqs.us-east-1.vpce.amazonaws.com/1234567890/demo # Will not return for: # https://localstack-sqs.example.dev/queue/example def parse_region(url) parts = URI.parse(url).host.split('.') parts.each_with_index do |part, index| if part == 'sqs' # assume region is the part right after the 'sqs' part return parts[index + 1] end end nil # no region found end end handler(Handler) end end end end
# frozen_string_literal: true class BerlinTransitTicket attr_accessor :starting_station, :ending_station def fare if ending_station == 'Leopoldplatz' 2.7 elsif ending_station == 'Birkenwerder' 3.3 end end end RSpec.describe BerlinTransitTicket do starting_station = '' ending_station = '' let(:ticket) { BerlinTransitTicket.new } before do ticket.starting_station = starting_station ticket.ending_station = ending_station end let(:fare) { ticket.fare } context 'when starting in zone A' do let(:starting_station) { 'Bundestag' } context 'and ending in zone B' do let(:ending_station) { 'Leopoldplatz' } it 'cost $2.70' do expect(fare).to eq 2.7 end end end context 'and ending in zone C' do let(:ending_station) { 'Birkenwerder' } it 'cost $3.30' do expect(fare).to eq 3.3 end end end RSpec.describe BerlinTransitTicket do def fare_for(starting_station, ending_station) ticket = BerlinTransitTicket.new ticket.starting_station = starting_station ticket.ending_station = ending_station ticket.fare end context 'when starting in zone A and ending in zone B' do it 'costs $2.70' do expect(fare_for('Bundestag', 'Leopoldplatz')).to eq 2.7 end end context 'when starting in zone A and ending in zone B' do it 'costs $3.30' do expect(fare_for('Bundestag', 'Birkenwerder')).to eq 3.3 end end end
# @author Carlos Arvelo Garcia (alu0100943849) require 'nutrientes/version' #Struct Node almacena los datos antropometricos Node = Struct.new(:value, :next, :prev) #Clase DlinkedList almacena los datos en una lista class DlinkedList include Enumerable attr_reader :head, :tail def initialize() @head = @tail = nil end # Inserta por la cola de la lista un nodo # # == Parameters: # Recive un valor o dato que se quiera insertar # # == Returns: # No retorna nada def insertTail(value) n = Node.new(value) if @head.nil? @tail = n @head = @tail else @tail.next = n n.prev = @tail @tail = n end end # Inserta por la cabeza de la lista un nodo # # == Parameters: # Recive un valor o dato que se quiera insertar # # == Returns: # No retorna nada def insertHead(value) n = Node.new(value) if @head.nil? @head = n @tail = @head else @head.next = n n.prev = @head @head = n end end # Extrae por la cabeza de la lista un nodo # # == Parameters: # No recibe nada # # == Returns: # Retorna el nodo extraido def popHead unless @head.nil? aux = @head unless @head.next.nil? @head.next.prev = nil @head = @head.next else @head = nil @tail = nil end aux end end # Extrae por la cola de la lista un nodo # # == Parameters: # No recibe nada # # == Returns: # Retorna el nodo extraido def popTail unless @tail.nil? aux = @tail unless @tail.prev.nil? @tail.prev.next = nil @tail = @tail.prev else @head = nil @tail = nil end aux end end # Extrae por la cabeza de la lista todos los nodos que quedan en la lista si no esta vacia # # == Parameters: # No recibe nada # # == Returns: # Retorna los nodos extraidos def removeAll unless @head.nil? while @head != nil aux = @head.next self.popHead @head = aux aux end end end # Recorre la lista desde la cabeza hasta a cola # # == Parameters: # No recibe nada # # == Returns: # No retorna nada def each nodo = @head while nodo != nil yield nodo.value nodo = nodo.next end end # Define el metodo para imprimir por pantalla # # == Parameters: # No recibe ninguno # # == Returns: # Un string con el contenido de las variables def to_s each {|x| puts x} end end
require_relative 'person' class Employee < Person field :category, type: String field :desired_AC_temperature, type: Integer end
# Used in generator_example_helpers_spec.rb # set_shell_prompt_responses requires a generator w/ a shell # as an argument. This class defines that generator w/ a shell. class MockGenerator attr_accessor :shell def initialize @shell = Object.new end end
module Moveable attr_accessor :speed, :heading attr_writer :fuel_capacity, :fuel_efficiency def range @fuel_capacity * @fuel_efficiency 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 Seacraft include Moveable attr_reader :propeller_count, :hull_count def initialize(num_propellers, num_hulls, km_traveled_per_liter, liters_of_fuel_capacity) self.fuel_efficiency = km_traveled_per_liter self.fuel_capacity = liters_of_fuel_capacity @propeller_count = num_propellers @hull_count = num_hulls end def range super + 10 end end class Catamaran < Seacraft end class Motorboat < Seacraft def initialize(km_traveled_per_liter, liters_of_fuel_capacity) super(1, 1, km_traveled_per_liter, liters_of_fuel_capacity) end end auto = Auto.new cycle = Motorcycle.new cata = Catamaran.new(2, 3, 10.0, 10.0) boat = Motorboat.new(12.0, 12.0) p auto.range p cycle.range p cata.range p boat.range
# frozen_string_literal: true require 'impraise/worker/requirements' module Impraise module Worker class Logger def initialize @config = Impraise::Worker::Config.new @dns = Impraise::Worker::DNS # discover redis service and setup client host, port = @dns.disco('redis') @redis = ::Redis.new(host: host, port: port, db: 0) end def channel 'impraise-debug' end def publish(message) @redis.publish(channel, sanitize(hostname: Socket.gethostname, body: message)) end private def sanitize(message) json = JSON.parse(JSON.generate(message)) json.each { |key, value| json[key] = ERB::Util.html_escape(value) } JSON.generate(json) end end end end
# require all the possible functions Dir[File.dirname(__FILE__) + '/transform_functions/*.rb'].each {|file| require file } module D2L module TransformFunctions # Find the correct transform function. # Functions can be added inside transform_functions directory def self.find_for(dataclip) available_functions.each do |f| function = self.const_get(f).new return function if function.accepts?(dataclip) end # Default return function TransformFunctions::Default.new end def self.available_functions TransformFunctions.constants.select do |c| Class === TransformFunctions.const_get(c) && c =~ /Func$/ end end end end
require 'oncotrunk/version' module Oncotrunk autoload :Client, 'oncotrunk/client' autoload :Settings, 'oncotrunk/settings' autoload :Syncer, 'oncotrunk/syncer' autoload :UI, 'oncotrunk/ui' autoload :Watcher, 'oncotrunk/watcher' class OncotrunkError < StandardError def self.status_code(code) define_method(:status_code) { code } end end class ConfigCreatedError < OncotrunkError status_code(2) end class ConfigBrokenError < OncotrunkError status_code(3) end class JabberError < OncotrunkError status_code(4) end class SyncFailedError < OncotrunkError status_code(5) end class << self attr_writer :ui def ui @ui ||= UI.new end def settings @settings ||= Settings.new end def cachedir_name ".oncotrunk" end def cachedir_path File.join(File.expand_path(Oncotrunk.settings['local']), Oncotrunk.cachedir_name) end end end
class MainController < ApplicationController helper :composer, :work, :instrument def welcome logger.debug "logger test" @composers = Composer.all.sort_by { |c| [c.last_name, c.first_name, c.middle_name] } if (check_data(@composers) == false) welcome else return @composers end @periods = Work.all_periods @instruments = Instrument.all.order("name ASC") end def show_period @period = params[:id] works = Work.all.select do |work| (work.period == @period) || (work.century == @period) end @editions = Edition.of_works(works) end def check_data(composers) if composers.size == 0 MainController.init_data return false else return true end end def self.init_data add_composer("Johannes", "Brahms") add_composer("Claude", "Debussy") add_work(1,"Sonata for Cello and Piano in F Major") add_work(2,"String Quartet") add_edition(1, "Facsimile", "D. Black Music House", 1998, 21.95) add_edition(1, "Urtext", "RubyTunes, Inc.", 1977, 23.50) add_edition(1, "ed. Y.Matsumoto", "RubyTunes, Inc.", 2001, 22.95) add_edition(2, "", "D. Black Music House", 1995, 39.95) add_edition(2, "Reprint of 1894 ed.", "RubyTunes, Inc.", 2003, 35.95) end def self.add_composer(first_name, last_name) composer = Composer.new composer.first_name = first_name composer.last_name = last_name composer.save end def self.add_work(composer_id, title) work = Work.new work.composer_id = composer_id work.title = title work.save end def self.add_edition(work_id, description, publisher, year, price) edition = Edition.new edition.work_id = work_id edition.description = description edition.publisher = publisher edition.year = year edition.price = price edition.save end end
class Dashboard::MedicationDispensationComponent < ApplicationComponent attr_reader :data attr_reader :region attr_reader :period def initialize(data:, region:, period:) @data = data @region = region @period = period end def graph_data data[:medications_dispensation] end end
# frozen_string_literal: true require 'dry/transaction' module IndieLand module Service # Analyzes contributions to a project # :reek:InstanceVariableAssumption # :reek:TooManyStatements # :reek:UncommunicativeVariableName # :reek:FeatureEnvy # :reek:DuplicateMethodCall # :reek:UtilityFunction class ListEvents include Dry::Transaction step :find_events_from_culture_api step :write_back_to_database step :find_future_events private MINISTRY_OF_CULTURE_API_ERR = "Error occurs at fetching Ministry of Culture's api" WRITE_EVENT_DB_ERR = 'Error occurs at writing events back to the database' FINDING_EVENTS_ERR = 'Error occurs at finding events' def find_events_from_culture_api(input) input[:logger].info('Getting events from the culture api') events = MinistryOfCulture::MusicEventsMapper.new.find_events Success(events: events, logger: input[:logger]) rescue StandardError => e input[:logger].error(e.backtrace.join("\n")) Failure(Response::ApiResult.new(status: :internal_error, message: MINISTRY_OF_CULTURE_API_ERR)) end def write_back_to_database(input) input[:logger].info('Writting events back to the database') Repository::For.entity(input[:events][0]).create_many(input[:events]) Success(logger: input[:logger]) rescue StandardError => e input[:logger].error(e.backtrace.join("\n")) Failure(Response::ApiResult.new(status: :internal_error, message: WRITE_EVENT_DB_ERR)) end def find_future_events(input) input[:logger].info('Finding future events from the database') future_events = Repository::Events.future_events range_events = get_range_events(future_events) Response::RangeEvents.new(range_events) .then do |range_events_response| Success(Response::ApiResult.new(status: :ok, message: range_events_response)) end rescue StandardError => e input[:logger].error(e.backtrace.join("\n")) Failure(Response::ApiResult.new(status: :internal_error, message: FINDING_EVENTS_ERR)) end def get_range_events(future_events) future_dates = future_events.future_dates future_dates.map do |date| brief_hashes = future_events.events_on_this_date(date) Response::DailyEvents.new(date, get_daily_events(brief_hashes)) end end def get_daily_events(brief_hashes) brief_hashes.map do |event_hash| Response::Event.new(event_hash[:event_id], event_hash[:event_name], event_hash[:session_id]) end end end end end
require 'ehonda/message_sanitizer' module Ehonda class TypedMessage def initialize(message) @message = message end def id headers['id'] end def type headers['type'] end def version headers['version'] end def headers hash['header'] end def header headers end def body hash['body'] end def to_h hash end private def convert_active_attr_model_to_hash model topic_name = model.class.to_s.underscore.dasherize.sub(/-message$/, '') headers = { id: SecureRandom.uuid, type: topic_name, version: 1 } attrs = model.respond_to?(:to_h) ? model.to_h : model.attributes { header: headers, body: attrs } end def hash @hash ||= begin h = if @message.is_a?(TypedMessage) @message.to_h elsif defined?(::Aws::SQS::Message) && @message.is_a?(::Aws::SQS::Message) parse_raw_text @message.body elsif defined?(::Shoryuken::Message) && @message.is_a?(::Shoryuken::Message) parse_raw_text @message.body elsif defined?(::ActiveAttr) && @message.is_a?(::ActiveAttr::Model) convert_active_attr_model_to_hash @message elsif @message.is_a?(Hash) unwrap_non_raw_message_format @message else parse_raw_text @message end sanitizer.sanitize(h).with_indifferent_access end end def parse_raw_text raw_text unwrap_non_raw_message_format ActiveSupport::JSON.decode(raw_text.to_s) end def sanitizer @sanitizer ||= MessageSanitizer.new end # if the queue this message was received from was not configured # for raw message delivery, we will need to double-decode the # actual message body.... def unwrap_non_raw_message_format hash hash = ActiveSupport::JSON.decode(hash['Message']) if hash.key?('Message') hash end end end
module Fastxl require "fastxl/version" require 'fastxl/workbook' require 'zip' require 'nokogiri' def self.create open(File.join(File.dirname(__FILE__), 'templates', 'one_sheet.xlsx')) end def self.open(file_path) Fastxl::Workbook.new(Zip::File.open(file_path)) end end
class Window WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 BIT_PER_PIXEL = 0 def initialize SDL.init(SDL::INIT_EVERYTHING) @screen = SDL.set_video_mode(WINDOW_WIDTH,WINDOW_HEIGHT,BIT_PER_PIXEL,SDL::SWSURFACE) showImage(SDL::Surface.load("load.gif"),0,0) refresh end def refresh @screen.update_rect(0,0,0,0) end def showImage(image,x,y) @screen.put(image,x,y) end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :character_version do character_id 1 version 1 csv "v4|Eleanor Bludsturm|Mistress of Blood|Ancient|Faer|Villain|Woman|7|6|8|4|3|2|2|2|2|8|8|2|7|7|2|2|0|0|0|0|0|-|0|0|0|0|||0|0|0||0|0|0|Can fly.|10|0|0|25|Enthrall: Mental ability. Free action: check luck; if 9, choose target enemy character within 6 aura. As long as Eleanor and target are in 6 aura of contact, the target is on Eleanor's side.|10|10|10|10|Fury: At the beginning of the game, randomly choose another allied character. If that character is killed or imprisoned, deal 1 damage to Eleanor and she becomes a hunter for the character responsible with speed 12, melee 7, power 4.|-10|10|0|-10" end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Order, type: :model do describe 'associations' do subject(:order) { build :order } it do expect(order).to have_many(:order_products) expect(order).to have_many(:products) end end describe 'default status is pending' do subject(:order) { create :order_with_products } it { expect(order.status).to eq('pending') } end describe 'update to paid' do describe 'when order contains products' do let(:order) { create :order_with_products } describe 'effective status change' do before { order.update! status: :paid } it { expect(order.status).to eq('paid') } end describe 'bill creation' do before { order.update! status: :paid } it { expect(Bill.last&.order_id).to eq(order.id) } end end describe 'when order does not contain products' do let(:order) { create :order } it { expect { order.update! status: :paid }.to raise_error(ActiveRecord::RecordInvalid) } end describe 'when order is canceled' do let(:order) { create :order, status: :canceled } it { expect { order.update!(status: :pending) }.to raise_error(ActiveRecord::ReadOnlyRecord) } end end describe 'create order with products' do subject(:order) { Order.create!(order_products_attributes: order_products) } describe 'all products exist' do let(:products) { create_list :product, 2 } let(:order_products) do [ { product_id: products[0].id, quantity: 1 }, { product_id: products[1].id, quantity: 3 } ] end it do expect(order).to be_an(Order) expect(order.products.count).to eq(2) expect(order.order_products.map(&:quantity)).to eq([1, 3]) end end describe 'one product does not exist' do let(:order_products) do [ { product_id: 999, quantity: 1 } ] end it { expect { order }.to raise_error(ActiveRecord::RecordInvalid) } end end describe 'compute attributes before saving' do let(:order_products) do [ { product_id: product1.id, quantity: 1 }, { product_id: product2.id, quantity: 2 } ] end let!(:order) { Order.create!(order_products_attributes: order_products) } describe 'when products have a regular price and are light' do let(:product1) { create :product, price: 10, weight: 10 } let(:product2) { create :product, price: 20, weight: 5 } it 'has neither a discount nor a shipment amount' do expect(order.shipment_amount).to eq(0) expect(order.total_amount).to eq(50) expect(order.weight).to eq(20) end end describe 'when products have a high price and are heavy' do let(:product1) { create :product, price: 400, weight: 30 } let(:product2) { create :product, price: 500, weight: 25 } # TODO: Check if shipment amount should be added to total amount or not it 'has a 5% discount and a shipment amount' do expect(order.shipment_amount).to eq(30) expect(order.total_amount).to eq(1330.0) expect(order.weight).to eq(80) end end end end
require_relative './dance_module.rb' require_relative './class_methods_module.rb' module Dance def twirl "I'm twirling!" end def jump "Look how high I'm jumping!" end def pirouette "I'm doing a pirouette" end def take_a_bow "Thank you, thank you. It was a pleasure to dance for you all." end end # We'll code our `Dance` module inside the `lib/dance_module.rb` file. Open up that file and define your module with the following code: # ```ruby # module Dance # end # ``` # Let's give our `Dance` module some fabulous moves: # ```ruby # module Dance # def twirl # "I'm twirling!" # end # def jump # "Look how high I'm jumping!" # end # def pirouette # "I'm doing a pirouette" # end # def take_a_bow # "Thank you, thank you. It was a pleasure to dance for you all." # end # end # ```
# +JMJ+ # Paul A Maurais # 2019 require_relative 'Card' # A players hand (wrapper for a card array) class Hand def initialize @cards = [] end def add_card(card) @cards.push(card) end def rem_card(card) if card.is_a?(Integer) @cards.delete_at(card) else @cards.delete(card) end end def [](index) @cards[index] end def each(&block) @cards.each(&block) end def to_s string_list = [] @cards.each do |card| string_list.push(card.to_s) end string_list.to_s end end # +JMJ+
class AppMailer < ActionMailer::Base def send_welcome(user) @user = user mail from: 'info@myflix.com', to: Rails.env.staging? ? ENV['TEST_EMAIL'] : user.email, subject: 'Welcome to MyFlix!' end def send_password_reset(user) @user = user mail from: 'info@myflix.com', to: Rails.env.staging? ? ENV['TEST_EMAIL'] : user.email, subject: 'Reset Your Myflix Password' end def send_friend_signup(invitation) @invitation = invitation mail from: 'info@myflix.com', to: Rails.env.staging? ? ENV['TEST_EMAIL'] : @invitation.invitee_email, subject: "#{@invitation.inviter.full_name} wants you to join MyFlix..." end end
require 'singleton' # The Jak module. module Jak # Contains a list of "shivs", or pre-defined roles and their permission sets # @!attribute shivs # The container of shivs for default Jak Permission Sets class Sheath include Singleton attr_accessor :shivs # Default it to an empty array def initialize self.shivs ||= [] end # Define a new shiv # param role_name [String] The name of the Jak Permission Set to create. # @param [Hash] options Various options to pass into the Jak Shiv. # @option options [String] :role_name The name of the role. # @option options [Array<Hash>] :spine An array of Hash items for each permission set being granted to the Jak Shiv. def shiv(role_name, options={}, &block) # Don't add existing Default Permission Sets unless Jak.sheath.include?(role_name) new_shiv = Jak::Shiv.new(role_name, options, &block) Jak.sheath.add(new_shiv) end end # Let us configure this shiv by a block def setup yield self end # Let us search through the Sheath for a specific Shiv # @param thing [String] The name of the Jak Shiv to test for inclusion def include?(thing) shivs.map(&:role_name).include?(thing) end # Let us find a specific Shiv # @param name_of_shiv [String] The name of the Jak Shiv to find. def find(name_of_shiv) shivs.select { |k| (k.role_name == name_of_shiv) }.first end # Let me add a Shiv # @param shiv [String] The name of the Jak Shiv to add. def add(shiv) self.shivs.push(shiv) unless shivs.include?(shiv) end # Let me remove a Shiv # @param shiv [String] The name of the Jak Shiv to remove. def remove(shiv) self.shivs.delete_at(shivs.index(shiv)) if shivs.include?(shiv) end end end
require "test_helper" class AdminTest < ActiveSupport::TestCase def setup @admin = Admin.new @admins = Admin.all @admin_accounts = AdminAccount.all end def test_initialize_admin_account assert_equal @admins.count.to_i, @admin_accounts.count.to_i end end
class AddDescToArticles < ActiveRecord::Migration[5.2] def change add_column :articles, :desc, :text add_column :articles,:created_at,:datetime add_column :articles, :updated_at,:datetime end end
module Concept module Validations extend ActiveSupport::Concern included do validates :origin, presence: true, on: :update validate :pref_label_in_primary_thesaurus_language validate :unique_pref_label_language validate :exclusive_top_term validate :rooted_top_terms validate :valid_rank_for_ranked_relations validate :unique_pref_labels validate :exclusive_pref_and_alt_labels_per_concept validate :unique_alt_labels validate :exclusive_broader_and_narrower_concepts validate :no_self_reference_concept_relation end # top term and broader relations are mutually exclusive def exclusive_top_term if validatable_for_publishing? if top_term? && broader_relations.any? errors.add :base, I18n.t('txt.models.concept.top_term_exclusive_error') end end end # top terms must never be used as descendants (narrower relation targets) # NB: for top terms themselves, this is covered by `ensure_exclusive_top_term` def rooted_top_terms if validatable_for_publishing? if narrower_relations.includes(:target). # XXX: inefficient? select { |rel| rel.target && rel.target.top_term? }.any? errors.add :base, I18n.t('txt.models.concept.top_term_rooted_error') end end end def pref_label_in_primary_thesaurus_language if validatable_for_publishing? labels = pref_labels.select{ |l| l.published? } if labels.none? errors.add :base, I18n.t('txt.models.concept.no_pref_label_error') elsif not labels.map(&:language).map(&:to_s).include?(Iqvoc::Concept.pref_labeling_languages.first.to_s) errors.add :base, I18n.t('txt.models.concept.main_pref_label_language_missing_error') end end end def unique_pref_label_language # We have many sources a prefLabel can be defined in pls = pref_labelings.map(&:target) + send(Iqvoc::Concept.pref_labeling_class_name.to_relation_name).map(&:target) + labelings.select{ |l| l.is_a?(Iqvoc::Concept.pref_labeling_class) }.map(&:target) languages = {} pls.compact.each do |pref_label| lang = pref_label.language.to_s origin = (pref_label.origin || pref_label.id || pref_label.value).to_s if (languages.keys.include?(lang) && languages[lang] != origin) # there are at least two pref labels for one specific language errors.add :pref_labelings, I18n.t('txt.models.concept.pref_labels_with_same_languages_error') break end languages[lang] = origin end end def unique_pref_labels if validatable_for_publishing? # checks if any other concept already owns the chosen pref labels conflicting_pref_labels = pref_labels.select do |l| Iqvoc::Concept.base_class.joins(:pref_labels).where(labels: { value: l.value, language: l.language }).where('labelings.owner_id != ?', id).where('concepts.origin != ?', origin).any? end if conflicting_pref_labels.any? if conflicting_pref_labels.one? errors.add :base, I18n.t('txt.models.concept.pref_label_not_unique', label: conflicting_pref_labels.last.value) else errors.add :base, I18n.t('txt.models.concept.pref_labels_not_unique', label: conflicting_pref_labels.map(&:value).join(', ')) end end end end def exclusive_pref_and_alt_labels_per_concept if validatable_for_publishing? alt_labels = alt_labelings.collect { |l| l.target } pref_labels.each do |pref_label| if alt_labels.include? pref_label errors.add :base, I18n.t('txt.models.concept.pref_label_defined_in_alt_labels', label: pref_label.value) end end end end def unique_alt_labels if validatable_for_publishing? alt_labels = alt_labelings.collect { |l| l.target } duplicate = alt_labels.detect { |e| alt_labels.select {|al| al.published? }.count(e) > 1 } if duplicate errors.add :base, I18n.t('txt.models.concept.alt_labels_not_unique', label: duplicate.value) end end end def valid_rank_for_ranked_relations if validatable_for_publishing? relations.each do |relation| if relation.class.rankable? && !(0..100).include?(relation.rank) errors.add :base, I18n.t('txt.models.concept.invalid_rank_for_ranked_relations', relation: relation.class.model_name.human.downcase, relation_target_label: relation.target.pref_label.to_s) end end end end def exclusive_broader_and_narrower_concepts if validatable_for_publishing? relations_union = broader_relations.map { |b| b.target } & narrower_relations.map { |n| n.target } if relations_union.any? errors.add :base, I18n.t('txt.models.concept.no_narrower_and_broader_relations', concepts: relations_union.each { |u| u.narrower_relations.map{ |r| r.owner.pref_labels.first } }.flatten.join(', ')) end end end def no_self_reference_concept_relation if validatable_for_publishing? # check all related concepts (e.g. skos:broader, skos:narrower, skos:related) if related_concepts.include?(self) errors.add :base, I18n.t('txt.models.concept.no_self_reference') end end end end end
require 'httparty' require 'pp' class Intelipost::ShipmentOrderApi include HTTParty format :json def initialize(shop) @base_uri = "api.intelipost.com.br" @shop = shop @token = shop.intelipost_token @headers = { "Content-Type"=> "application/json", "Accept"=> "*/*", "api-key"=> @token } end def shipment_order(id) get("https://#{@base_uri}/api/v1/shipment_order/#{id}") end def read_quote(id) get("https://#{@base_uri}/api/v1/quote/#{id}") end def delivery_methods get("https://#{@base_uri}/api/v1/info") end def create(params) post("https://#{@base_uri}/api/v1/shipment_order", mount_intelipost_order(params)) end def shipped(params) content = {} content[:order_number] = [@shop.order_prefix, params["code"]].join("") content[:event_date] = params["shipped_at"].to_date.strftime("%Y-%m-%d") post("https://#{@base_uri}/api/v1/shipment_order/multi/shipped/with_date", [JSON.parse(content.to_json)]) end def mount_intelipost_order(json) params = {} if json["extra"] and json["extra"]["cotation_id"] params[:quote_id] = json["extra"]["cotation_id"].to_i quote = read_quote(params[:quote_id]) unless quote["status"] == "ERROR" quote = read_quote(params[:quote_id])["content"]["delivery_options"] quote = quote.select{|d| d if d["delivery_method_name"].downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') == json["shipping_method"]}.last params[:delivery_method_id] = quote["delivery_method_id"].to_i end end params[:estimated_delivery_date] = (Date.current + json["delivery_days"].days).strftime("%Y-%m-%d") if json["delivery_days"].to_i > 0 params[:order_number] = [@shop.order_prefix, json["code"]].join("") params[:customer_shipping_costs] = json["shipping_price"] params[:end_customer] = {} params[:end_customer][:first_name] = json["first_name"] params[:end_customer][:last_name] = json["last_name"] params[:end_customer][:email] = json["email"] params[:end_customer][:phone] = "#{json['phone_area']} #{json['phone']}".squish params[:end_customer][:is_company] = false params[:end_customer][:shipping_address] = json["shipping_address"]["street_name"] params[:end_customer][:shipping_number] = json["shipping_address"]["street_number"] params[:end_customer][:shipping_additional] = json["shipping_address"]["complement"] params[:end_customer][:shipping_quarter] = json["shipping_address"]["neighborhood"] params[:end_customer][:shipping_city] = json["shipping_address"]["city"] params[:end_customer][:shipping_state] = json["shipping_address"]["state"] params[:end_customer][:shipping_zip_code] = json["shipping_address"]["zip"] params[:end_customer][:shipping_country] = "BR" params[:shipment_order_volume_array] = [] json["items"].each do |i| item = {} item[:shipment_order_volume_number] = i["sku"] item[:name] = i["product_name"] item[:weight] = i["weight"] item[:volume_type_code] = "box" item[:width] = i["width"] item[:height] = i["height"] item[:length] = i["length"] item[:products_quantity] = i["quantity"] item[:products_nature] = "household appliance" item[:is_icms_exempt] = false item[:tracking_code] = json["tracking_code"] item[:shipment_order_volume_invoice] = {} item[:shipment_order_volume_invoice][:invoice_series] = "1" item[:shipment_order_volume_invoice][:invoice_number] = "1000" item[:shipment_order_volume_invoice][:invoice_key] = "41140502834982004563550010000084111000132317" item[:shipment_order_volume_invoice][:invoice_date] = Date.current.strftime("%Y-%m-%d").to_s item[:shipment_order_volume_invoice][:invoice_total_value] = i["total"].to_s item[:shipment_order_volume_invoice][:invoice_products_value] = i["subtotal"].to_s item[:shipment_order_volume_invoice][:invoice_cfop] = "2809" params[:shipment_order_volume_array] << item end JSON.parse(params.to_json) end def get(url) response = self.class.get(url, {headers: @headers}) JSON.parse(response.body) end def post(url, params) JSON.parse(self.class.post(url, :body => params.to_json, :headers => @headers).body) end def put(url, params) self.class.put(url, :body => params.to_json, :headers => @headers).body end end
class SpentTimeHooks < Redmine::Hook::ViewListener render_on :view_layouts_base_body_bottom, partial: 'spent_time_menu/update_menu' def view_layouts_base_html_head(_context = {}) o = '' if User.current.logged? && User.current.hours_per_day.present? o = stylesheet_link_tag('spent_time', plugin: 'redmine_spent_time') o << javascript_include_tag('spent_time', plugin: 'redmine_spent_time') end o end def view_users_form(context = {}) begin return %( <p>#{context[:form].text_field :hours_per_day}</p> ) rescue => e Rails.logger.error e return "<pre>#{e}</pre>" end end end
require 'spec_helper' module Alf module Tools describe TupleHandle do let(:handle){ TupleHandle.new } it "should install methods properly" do handle.set(:hello => "a", :world => "b") handle.should respond_to(:hello) handle.should respond_to(:world) end it "should behave correctly" do handle.set(:hello => "a", :world => "b") handle.hello.should == "a" handle.world.should == "b" handle.set(:hello => "c", :world => "d") handle.hello.should == "c" handle.world.should == "d" end it "should allow instance evaluating on exprs" do handle.set(:tested => 1) handle.instance_eval{ tested < 1 }.should be_false end it "should support an attribute called :path" do handle.set(:path => 1) handle.instance_eval{ path < 1 }.should be_false end describe "evaluate" do before{ handle.set(:a => 1, :b => 2) } it "should allow a String" do handle.evaluate("a").should == 1 end it "should allow a Symbol" do handle.evaluate(:a).should == 1 end it "should allow a Proc" do handle.evaluate(lambda{ a }).should == 1 end end end end end
module Clicksign class Service attr_reader :request_signature_keys attr_reader :signer_keys attr_reader :document_key def initialize(document) @document = document @document_key = nil @signer_keys = [] @request_signature_keys = [] end def run create_document create_signers add_signers_to_document rescue Exception => e puts e Rollbar.error(e) end def keys { document_key: @document_key, request_signature_keys: @request_signature_keys, } end private def create_document url = "#{host}/api/v1/documents#{request_params}" body = { "document": { "path": "/#{@document.filename}", "content_base64": "#{base64_prefix}#{@document.to_base_64}", "deadline_at": @document.deadline, "auto_close": true, "locale": "pt-BR" } }.to_json serialized_response = RestClient.post(url, body, header) response = JSON.parse(serialized_response).deep_symbolize_keys @document_key = response[:document][:key] puts "*** Document key: #{@document_key}" end def create_signers puts "*** Signatários a serem criados: #{@document.signers}" @document.signers.each do |signer| create_signer(signer) end end def create_signer(signer) url = "#{host}/api/v1/signers#{request_params}" body = { "signer": { "email": signer[:email], "phone_number": signer[:mobile], "auths": [ "sms" ], "name": signer[:name], "documentation": signer[:documentation], "birthday": signer[:birthdate], "has_documentation": true } }.to_json serialized_response = RestClient.post(url, body, header) response = JSON.parse(serialized_response).deep_symbolize_keys @signer_keys << { email: signer[:email], signer_key: response[:signer][:key] } puts "*** Signatário criado: #{@signer_keys}" end def add_signers_to_document @document.signers.each do |signer| signer[:sign_as].each do |sign_type| signer_key = @signer_keys.detect {|signer_key| signer_key[:email] == signer[:email]}.fetch(:signer_key) add_signer_to_document(signer[:email], signer_key , sign_type) end end puts @request_signature_keys end def add_signer_to_document(signer_email, signer_key, sign_type) url = "#{host}/api/v1/lists#{request_params}" body = { "list": { "document_key": @document_key, "signer_key": signer_key, "sign_as": sign_type } }.to_json serialized_response = RestClient.post(url, body, header) response = JSON.parse(serialized_response).deep_symbolize_keys new_signature_key = { email: signer_email, signature_key: response[:list][:request_signature_key] } unless @request_signature_keys.any? {|signature_key| signature_key[:email] == new_signature_key[:email]} @request_signature_keys << new_signature_key puts "*** Signatário adicionado ou documento: #{new_signature_key}" end end #TODO: trocar após o teste def host Rails.env.development? ? "https://sandbox.clicksign.com" : "https://app.clicksign.com" end # TODO this method doesn't work and I don't know why # def create_documents_path # "api\/v1\/documents" # end # def create_signer_path # "api\/v1\/signers" # end # def add_signers_to_document_path # "api\/v1\/lists" # end #TODO: trocar credentials após o teste def request_params "?access_token=#{Rails.application.credentials[Rails.env.to_sym][:clicksign][:access_token]}" end def header {:Content_Type => "application/json", :Accept => "application/json"} end # This part is required by Clicksign def base64_prefix "data:application/pdf;base64," end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # # Vagrantfile Deploying 2 nodes in order to compare pgsql and cockroachdb backends # DEBUG = false G5K_USER = "acarat" Vagrant.configure(2) do |config| # Configuration for VirtualBox config.vm.provider :virtualbox do |vb, override| vb.cpus = 6 vb.memory = 8192 override.vm.synced_folder "./", "/vagrant_data", owner: "vagrant", group: "vagrant" end #vb # Configuration for G5k config.vm.provider "g5k" do |g5k, override| # This is mandatory for the shared folders to work correctly override.nfs.functional = false # vagrant-g5k only supports rsync shared folders override.vm.synced_folder ".", "/vagrant", type: "rsync", disabled: false #override.ssh.username = 'root' override.ssh.insert_key = false # project id must be unique accross all # your projects using vagrant-g5k to avoid conflict # on vm disks g5k.project_id = "cockroach-os" g5k.site = "rennes" g5k.username = G5K_USER g5k.gateway = "access.grid5000.fr" g5k.walltime = "07:30:00" #g5k.private_key = "your private key" # Image backed on the frontend filesystem g5k.image = { :path => "/home/acarat/debian-8.7-amd64-bento.qcow2", :backing => "snapshot" } ## Nat network : VMs will only have access to the external world ## Forwarding ports will allow you to access services hosted inside the ## VM. g5k.net = { :type => "nat", :ports => ["2222-:22", "8080-:8080", "8888-:80"] } ## OAR selection of resource g5k.oar = "virtual != 'none'" #g5k.oar = "virtual != 'None' and network_address in ('paranoia-2.rennes.grid5000.fr')" #g5k.oar = "network_address in ('igrida12-12.irisa.fr')" ## VM size customization default values are g5k.resources = { :cpu => 4, :mem => 4096 } end #g5k # VM for CockroachDB backend config.vm.define "cockroachdb" do |roach| roach.vm.box = "debian/contrib-jessie64" roach.vm.provision :ansible_local do |ansible| ansible.install_mode = "pip" ansible.version = "2.3.1.0" ansible.playbook = "provision.yml" # ansible.verbose = "-vvvv" ansible.extra_vars = { :debug => DEBUG } end end end
class Requests::Withdraw < ActiveRecord::Base include AASM include Requests::Transactable include Requests::Transferable include Requests::Messageable include Comments::CommentableMethods include Tracking::Trackable include Notifications::Notifiable acts_as_commentable can_be_notified sender_notification: :who_send_notification, recipients_notification: :who_receive_notification, notifiable_attributes: [state: ['canceled', 'rejected', 'succeed']] aasm column: :state do state :pending, initial: true state :canceled state :rejected state :succeed event :cancel, after: :cancel_transaction do transitions to: :canceled, from: [:pending] end event :approve, after: :perform_transaction do transitions to: :succeed, from: [:pending] end event :reject, after: :cancel_transaction do transitions to: :rejected, from: [:pending] end end validates :amount, presence: true, numericality: {greater_than: 0, less_than: ::Proc.new {|w| (w.transaksi && w.transaksi.balance) ? w.transaksi.balance.actual_proposed_amount : 0 }} attr_accessor :account_number, :bank def is_eligible_to_be_processed? persisted? and succeed? end protected def who_send_notification if self.last_changes_by.present? self.last_changes_by end end def who_receive_notification recipients = [] if self.last_changes_by.present? receiver = self.last_changes_by.super_admin?? self.transaksi.balance.user : User.first recipients << receiver.notification_receipts.new(route: admin_balances_requests_withdraw_path(self.transaksi)) end recipients end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_many :wikis, dependent: :destroy has_many :collaborators def admin? role = 'admin' end def collaborator? role = 'collaborator' end def moderator? role = 'moderator' end def role?(base_role) role.nil? ? false : ROLES.index(base_role.to_s) <= ROLES.index(role) end def account?(base_account) account_type == base_account.to_s end def set_member self.role = 'collaborator' end end
class User < ApplicationRecord validates_presence_of :name, :birthday, :number, :description def self.import(file) if File.extname(file.original_filename) != ".csv" return false else CSV.foreach(file.path, headers: true) do |row| name, birthday, number, description = row.to_hash['name'], row.to_hash['date'],row.to_hash['number'],row.to_hash['description'] User.find_or_create_by(name:name, birthday:birthday,number:number,description:description) end return true end end end
ActiveAdmin.register Purchase do belongs_to :user, optional: :true # belongs_to :tip, optional: :true # :( :( can't use the same config at two different routes :( actions :index, :show filter :service, as: :check_boxes, collection: Purchase::SERVICES filter :created_at filter :updated_at scope :all, default: true scope "IAPs", :iap scope :reputation index do id_column column(:service) { |purchase| status_tag purchase.service} column :transaction_id column :transaction_timestamp column :purchaser column :seller column :tip column(:created) { |purchase| span "#{time_ago_in_words purchase.created_at} ago", title: purchase.created_at } end show do attributes_table do row :id row("transaction id") { purchase.transaction_id } row :transaction_timestamp row :tip row :purchaser row :seller row :iap_receipt_verification row :purchase_entry row(:created) { |purchase| span "#{time_ago_in_words purchase.created_at} ago", title: purchase.created_at } row(:updated) { |purchase| span "#{time_ago_in_words purchase.updated_at} ago", title: purchase.updated_at } end panel "Receipt Verification" do attributes_table_for purchase.iap_receipt_verification do row :id row(:service) { |v| status_tag v.service } row(:successful) { |v| status_tag(v.successful? ? "yes" : "no")} row :result_message row :request_metadata end end # TODO: Affect on reputation? # TODO: More money info # TODO: links to ensuing discussion end end
Pod::Spec.new do |s| s.name = "MLSDurexKit" s.version = "1.0.0" s.summary = "防止崩溃容错处理" s.description = <<-DESC Hack并exchange系统方法,拦截崩溃,例如字典set nil 等 DESC s.homepage = "https://www.minlison.cn" s.license = "MIT" s.author = { "Minlison" => "yuanhang.1991@163.com" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/Minlison/MLSDurexKit.git", :tag => "v#{s.version}" } s.requires_arc = true s.documentation_url = "https://www.minlison.cn" s.static_framework = true mrc_files = "Classes/MRC/*.{h,m}" s.subspec 'MRC' do |ss| ss.source_files = mrc_files ss.public_header_files = "Classes/MRC/*.h" end s.subspec 'Core' do |ss| ss.exclude_files = mrc_files ss.source_files = "Classes/**/*.{h,m}" ss.public_header_files = "Classes/**/*.h" end end
class UsersController < Clearance::UsersController before_filter :authorize load_and_authorize_resource def index @total_users = User.all.size @users = User.joins(:players).where("team_name != 'Temp'").order("players.cups DESC, players.medals DESC, players.rosettes DESC, created_at DESC").paginate(page: params[:page]) end def show @user = User.find(params[:id]) unless @user.favorite_club.blank? @club = Club.find(@user.favorite_club) end end def edit @user = User.find(params[:id]) @clubs = Club.order('club_name ASC') end def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) redirect_to user_path(current_user), notice: I18n.t('.user.updated') else render action: "edit" end end def destroy user = User.find(params[:id]) user.destroy redirect_to users_path, notice: "User #{I18n.t('.destroyed.success')}" end def silent @users = User.where("team_name = 'Temp'").order('base_nr ASC').paginate(page: params[:page]) end end
require 'bundler' Bundler.setup Bundler.require(:default) # In order not to pollute the global namespace with our methods # and routes, let's subclass the Sinatra::Base classe. class EvilLeague < Sinatra::Base # Let's define a route for the home screen here get '/' do erb :'default.html', :layout => false end get '/members' do erb :'members.html', :layout => false end post '/add' do evil_member = EvilUser.new(params) if evil_member.save flash[:notice] = "Welcome to the evil league, #{params[:name]}!" else flash[:error] = "Sorry, try again." end redirect '/' end end # Let's describe a member of the evil league class EvilUser include DataMapper::Resource property :id, Serial property :name, String, :required => true, :unique => true, :length => 3..50 end require_relative 'config/config.rb' DataMapper.finalize
class TopicsController < ApplicationController before_action :set_topic, only: [:show, :edit, :update, :destroy] def search if(params[:search] && params[:search] != '') @topics = Topic.search(params[:search]).order("updated_at DESC").paginate(per_page: 15, page: params[:page]) end end def like @topic = Topic.find(params[:id]) @topic.liked_by current_user @users = @topic.votes.up.by_type(User).voters respond_to do |format| format.html { redirect_to board_topic_path(@topic.board, @topic) } format.js end end def unlike @topic = Topic.find(params[:id]) @topic.unliked_by current_user @users = @topic.votes.up.by_type(User).voters respond_to do |format| format.html { redirect_to board_topic_path(@topic.board, @topic) } format.js end end # GET /topics # GET /topics.json def index if(params[:tag]) @topics = Topic.tagged_with(params[:tag]).paginate(per_page: 15, page: params[:page]) else @topics = Topic.paginate(per_page: 15, page: params[:page]) end end # GET /topics/1 # GET /topics/1.json def show load_board @topic = Topic.find(params[:id]) @topic.board = @board @comments = @topic.comments @users = @topic.votes.up.by_type(User).voters @topic.keyword_list = @topic.keyword_list[0..4] end # GET /topics/new def new load_board @topic = Topic.new end # GET /topics/1/edit def edit @topic.keyword_list = @topic.keyword_list[0..4] end # POST /topics # POST /topics.json def create load_board @topic = Topic.new(topic_params) @topic.user_id = current_user.id @topic.board = @board @topic.keyword_list = @topic.keyword_list[0..4] if current_user && @topic.save flash[:success] = "Topic was successfuly created." respond_to do |format| format.html { redirect_to :controller => 'topics', :action => 'show', :id => @topic.id } format.js end else render action: "new" end end # PATCH/PUT /topics/1 # PATCH/PUT /topics/1.json def update if @topic.update(topic_params) flash[:success] = "Topic was successfuly updated." redirect_to board_topic_path(@topic.board.id, @topic.id) else end end # DELETE /topics/1 # DELETE /topics/1.json def destroy @board = @topic.board @topic.destroy flash[:success] = "Topic was successfuly deleted." redirect_to :controller => 'boards', :action => 'show', :id => @board.id end private # Use callbacks to share common setup or constraints between actions. def set_topic @topic = Topic.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def topic_params params.require(:topic).permit(:title, :subtitle, :user_id, :board_id, :keyword_list) end def load_board if Board.exists?(params[:board_id]) @board = Board.find(params[:board_id]) end unless @board redirect_to(boards_path, :notice => "Please specify a valid board" ) end end end
Pod::Spec.new do |s| s.name = "Default" s.version = "3.0.0" s.summary = "Modern interface to UserDefaults + Codable support" s.description = <<-DESC Modern interface to UserDefaults + Codable support please refer to README.md for usage details. DESC s.homepage = "https://github.com/Nirma/Default" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Nicholas Maccharoli " => "nmaccharoli@gmail.com" } s.social_media_url = "http://twitter.com/din0sr" s.platform = :ios, "9.0" s.ios.deployment_target = "9.0" s.osx.deployment_target = "10.10" s.watchos.deployment_target = "4.0" s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/Nirma/Default.git", :tag => "#{s.version}" } s.source_files = 'Sources/*.swift' end
require "tictactoe" require "mocks/printer" describe TicTacToe do before do STDOUT.stub(:print) end let(:game) {TicTacToe.new(:human_vs_human, MockPrinter.new)} describe "#initialize" do it "should expect a game type when instantiating" do lambda { TicTacToe.new }.should raise_error end it "should not accept improper game types" do lambda { TicTacToe.new(:cat_vs_mouse) }.should raise_error end it "should accept proper game types" do lambda { TicTacToe.new(:human_vs_human) }.should_not raise_error lambda { TicTacToe.new(:human_vs_ai) }.should_not raise_error lambda { TicTacToe.new(:ai_vs_human) }.should_not raise_error lambda { TicTacToe.new(:ai_vs_ai) }.should_not raise_error end it "should properly set the players" do game.x.class.should == Human game.o.class.should == Human end end it "should be able to start a game with two players and have a winner" do x = Human.new("x") o = Human.new("o") x.stub(:puts) o.stub(:puts) x.stub(:gets).and_return('0','1','2','3') o.stub(:gets).and_return('4','5','7') game.board.set_players(x,o) game.start game.board.winner.should == "x" end it "should ask user to try again if spot is taken" do x = Human.new("x") o = Human.new("o") x.stub(:puts) o.stub(:puts) x.stub(:gets).and_return('0','4','1','2','3') o.stub(:gets).and_return('4','5','7','8') game.board.set_players(x,o) game.start game.board.winner.should == "x" end end
# # Represents a recommendation a user has made. Does not require a receiver # to be present, but does at least require a receiver email. class Recommendation < ActiveRecord::Base include Uuid KINDS = %w{follow} belongs_to :user belongs_to :target, polymorphic: true belongs_to :receiver, polymorphic: true validates_presence_of :user validates_presence_of :kind validates_inclusion_of :kind, in: KINDS, allow_blank: true validates_presence_of :receiver_email before_validation do self.kind = self.kind.to_s if self.kind.is_a?(Symbol) end # Public. A quick lookup to find out whether the receiver accepted the reccommendation. def successful case self.kind.to_sym when :follow if user = User.find_by(email: self.receiver_email) user.follows.exists?(target: self.target) else false end else false end end end
require 'stringio' module OptionList @@usage = "" @@option_list = [] def self.clear_options @@option_list = [] end def self.register_usage str @@usage = str end def self.register_options long, short, arg, desc @@option_list.push [ long, short, arg, desc ] end def self.push_separator @@option_list.push :separator end def self.options ( @@option_list - [ :separator ] ).collect do | long, short, arg, | [ long, short, arg ? GetoptLong::REQUIRED_ARGUMENT : GetoptLong::NO_ARGUMENT ] end end def self.option_desc_tab ( @@option_list - [ :separator ] ).collect do | long, short, arg, desc | if arg long.size + arg.size else long.size end end.sort.reverse[ 0 ] + 10 end def self.usage out = StringIO.new( "" ) out.puts "usage: " + @@usage out.puts out.puts "Options:" @@option_list.each do | each | if each == :separator out.puts next else long, short, arg, desc = each out.print( if arg sprintf " %-#{ option_desc_tab }s", "#{ short }, #{ long } #{ arg }" else sprintf " %-#{ option_desc_tab }s", "#{ short }, #{ long } " end ) desc = desc.split( "\n" ) out.puts desc.shift desc.each do | each | puts( ' ' * ( option_desc_tab + 2 ) + each ) end end end out.string end end ### Local variables: ### mode: Ruby ### coding: utf-8 ### indent-tabs-mode: nil ### End:
class AddNeedsDiscoveredToOpportunities < ActiveRecord::Migration def change add_column :opportunities, :need, :text end end
class ForecastSerializer include FastJsonapi::ObjectSerializer attributes :timezone, :current_temp, :current_summary, :current_time, :current_humidity, :current_uv, :current_visibility, :feels_like, :hourly_data set_id :timezone end
class OrderItem < ActiveRecord::Base belongs_to :order, counter_cache: :items_count belongs_to :wesell_item belongs_to :category has_many :order_item_options, dependent: :destroy has_many :wesell_item_options, through: :order_item_options validates :quantity, presence: true, numericality: true validates_numericality_of :quantity, greater_than: 0 validates :wesell_item_id, :presence => true, :uniqueness => {:scope => :order_id} before_create :set_item_attrs delegate :monetary_unit, :monetary_tag, to: :wesell_item def human_price "#{monetary_tag}#{unit_price}/#{unit_name}" end def calculate_order_amount self.order.reload.calculate_amount end def total_price price = unit_price order_item_options.each do |option| price += option.price end total = price * quantity end def set_item_attrs self.name = wesell_item.name self.category_id = wesell_item.category_id self.unit_price = wesell_item.price self.unit_name = wesell_item.unit_name end def set_options option_ids option_ids.each do |i| wesell_item_option = WesellItemOption.find i order_item_option = self.order_item_options.find_or_initialize_by wesell_item_option_id: i order_item_option.update_attributes price: wesell_item_option.price, name: wesell_item_option.name end calculate_order_amount end end
class Cart < ActiveRecord::Base attr_accessible :session_token belongs_to :user has_many :cart_items def generate_token(column) begin self[column] = SecureRandom.urlsafe_base64 end while Cart.exists?(column => self[column]) end def total_items cart_items.blank? ? 0 : cart_items.sum(&:quantity) end def total_sum cart_items.collect{|ci| ci.quantity*ci.price}.sum end end
class CreateRounds < ActiveRecord::Migration def change create_table :rounds do |t| t.integer :number t.datetime :date t.integer :casino_id t.timestamps null: false end end end
class FriendRequestsController < ApplicationController def create params[:friend_request][:user_id] = current_user.id @friend_request = FriendRequest.new(params[:friend_request]) if @friend_request.save flash.now[:success] = "friend added successfully!" # redirect_to users_url render json: @friend_request else errors = @friend_request.errors.full_messages flash.now[:errors] = errors # redirect_to users_url render json: true end end def destroy request = FriendRequest.find_by_user_id_and_friend_id(current_user.id, params[:friend_id]) request.destroy puts "\n\n\n friend request destroyed! \n\n\n" # redirect_to users_url render json: request end end
class Api::V1::EventSerializer < ActiveModel::Serializer attributes :id, :name, :description, :start_date, :end_date, :status, :primary_color, :logo, :image1, :image2, :image3, :slug has_many :projects def logo object.header_logo.attachment.service_url if object.header_logo.attached? end def primary_color object.accent_color end def image1 object.image1.attachment.service_url if object.image1.attached? end def image2 object.image2.attachment.service_url if object.image2.attached? end def image3 object.image3.attachment.service_url if object.image3.attached? end end
require 'rails_helper' describe Lsi::BatchWriter do let (:batch) do Timecop.freeze(DateTime.parse('2016-03-02 06:30:42 CST')) do FactoryGirl.create(:batch, orders: [order]) end end let (:shipping_address) do FactoryGirl.create :address, line_1: '1234 Main St', line_2: 'Apt 227', city: 'Dallas', state: 'TX', postal_code: '75200', country_code: 'US' end let (:order) do FactoryGirl.create :order, order_date: '2016-02-27', customer_name: 'John Doe', telephone: '214-555-1212', shipping_address: shipping_address end let!(:item) do FactoryGirl.create(:order_item, order: order, line_item_no: 1, sku: '325253259-X', quantity: 1, unit_price: 19.99, discount_percentage: 0.10, tax: 1.65) end let (:expected_output_path) do path = Rails.root.join('spec', 'fixtures', 'files', 'lsi_batch_writer_expected_output.txt') end let (:writer) { Lsi::BatchWriter.new(batch) } describe '#write' do it 'writes the batch content to the specified IO object' do io = StringIO.new writer.write io io.rewind File.open(expected_output_path) do |f| f.each_line do |l| expect(io.readline).to eq l end end end end describe '#alpha_of_length' do it 'up-cases and right-pads the value with blank spaces if it is shorter than the specified length' do expect(writer.alpha_of_length("test", 6)).to eq "TEST " end it 'truncates the value if it is longer than the specified length' do expect(writer.alpha_of_length("thisistoolong", 4)).to eq "THIS" end it 'returns the value as-if if it is extactly the specified length' do expect(writer.alpha_of_length("justright", 9)).to eq "JUSTRIGHT" end end describe '#number_of_length' do it 'returns a string' do expect(writer.number_of_length(10, 2)).to be_a String end it 'left-pads the value with zeros if it is shorter than the specified length' do expect(writer.number_of_length(1, 5)).to eq "00001" end it 'raises and exception if the value is longer than the specified length' do expect do writer.number_of_length(100, 2) end.to raise_error ArgumentError, "The value 100 is longer than the specified length 2" end end end
require 'bundler/gem_tasks' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) task default: :spec require 'sdoc' RDoc::Task.new(:doc) do |rdoc| rdoc.rdoc_dir = 'doc' rdoc.title = 'RailsStuff' rdoc.options << '--markup' << 'markdown' rdoc.options << '-e' << 'UTF-8' rdoc.options << '--format' << 'sdoc' rdoc.options << '--template' << 'rails' rdoc.options << '--all' rdoc.rdoc_files.include('README.md') rdoc.rdoc_files.include('lib/**/*.rb') end
ActiveAdmin.register User do permit_params :email , :role remove_filter :encrypted_password,:reset_password_token, :reset_password_sent_at, :remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip, :created_at, :updated_at index do selectable_column column :name column :id column :email column :role actions end action_item :Allot do link_to "Allot classes" ,manage_teachers_path end batch_action :Add_as_teacher, form: { } do |ids| # inputs is a hash of all the form fields you requested redirect_to add_as_teacher_path params: {id: ids} end form do |f| f.inputs "Users" do f.input :name f.input :email f.input :school_id, :as => :select, :collection => School.all.collect { |school| [school.name, school.id] } f.input :role , as: :select, collection: ['Teacher','Admin','RB User'] end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) p "Destroying channels" Channel.destroy_all p "Destroying Users" User.destroy_all p "Destroying Messages" Message.destroy_all p "creating channels" general = Channel.create(name: "general") paris = Channel.create(name: "paris") react = Channel.create(name: "react") p "creating users" user1 = User.create( email: "test@test.com", password: "123123") user2 = User.create( email: "test1@test.com", password: "123123") p "creating messages" Message.create( user: user1, channel: general, content: "Welcome to #general!") Message.create( user: user2, channel: general, content: "Hello how are you all doing?") Message.create( user: user1, channel: paris, content: "Welcome to #paris!") Message.create( user: user2, channel: paris, content: "Hello how are you all doing?") Message.create( user: user1, channel: react, content: "Welcome to #react!") Message.create( user: user2, channel: react, content: "Hello how are you all doing?") p "#{Channel.count} channels created" p "#{User.count} users created" p "#{Message.count} messages created"
class AddFieldsToLegoSet < ActiveRecord::Migration[5.1] def change add_column :lego_sets, :number_variant, :string add_column :lego_sets, :brickset_url, :string add_column :lego_sets, :minifig_count, :integer add_column :lego_sets, :released, :boolean add_column :lego_sets, :packaging_type, :string add_column :lego_sets, :instructions_count, :integer add_index :lego_sets, [:number, :number_variant], unique: true end end
require 'newrelic_rpm' require 'new_relic/agent/instrumentation/controller_instrumentation' module Ehonda module Middleware module Server class NewRelic include ::NewRelic::Agent::Instrumentation::ControllerInstrumentation def call(worker, queue, sqs_msg, _body) trace_args = if worker.respond_to?(:newrelic_trace_args) worker.newrelic_trace_args(worker, queue, sqs_msg) else self.class.default_trace_args(worker, queue, sqs_msg) end perform_action_with_newrelic_trace(trace_args) do if ::NewRelic::Agent.config[:'shoryuken.capture_params'] ::NewRelic::Agent.add_custom_parameters( message_attributes: sqs_msg.message_attributes, message_body: sqs_msg.body) end yield end end def self.default_trace_args(worker, queue, _sqs_msg) { name: 'perform', class_name: worker.class, category: 'OtherTransaction/ShoryukenJob', params: { queue: queue } } end end end end end
#!/usr/bin/env ruby # This script runs once every few mins and pings all probe nodes $stdout.sync = true require 'net/ping' require 'net/http' require 'logger' require 'mixlib/shellout' require 'ostruct' require 'json' LOGGER = Logger.new(STDOUT) LOGGER.info("Logger Level: #{ENV['LOGGER_LEVEL']}") LOGGER.level = ENV['LOGGER_LEVEL'] PROBE_SITE = ENV['PROBE_SITE'] MASTER_HOST = ENV['MASTER_HOST'] MASTER_PORT = ENV['MASTER_PORT'] PROBE_SECRET = ENV['PROBE_SECRET'] def send_pang uri = URI("http://#{MASTER_HOST}:#{MASTER_PORT}/pang") begin res = Net::HTTP.post_form(uri, 'name' => 'pang', 'site' => PROBE_SITE, 'secret' => PROBE_SECRET) if res.code == "200" return true else return false end rescue LOGGER.error("send_pang timed out") return false end end def get_probe_sites uri = URI("http://#{MASTER_HOST}:#{MASTER_PORT}/get_probes") probe_sites = {} begin res = Net::HTTP.post_form(uri, 'secret' => PROBE_SECRET) probe_sites = JSON.parse(res.body) rescue LOGGER.error("get_probe_sites timed out") end return probe_sites end def send_ping_metric(ping_vals) LOGGER.debug("Sending ping metric") LOGGER.debug("METRIC: #{ping_vals}") uri = URI("http://#{MASTER_HOST}:#{MASTER_PORT}/send_metric") begin res = Net::HTTP.post_form(uri, 'name' => 'ping', 'source_site' => PROBE_SITE, 'site' => ping_vals.site, 'ip' => ping_vals.ip, 'transmitted' => ping_vals.transmitted, 'received' => ping_vals.received, 'packet_loss' => ping_vals.packet_loss, 'min' => ping_vals.min, 'avg' => ping_vals.avg, 'max' => ping_vals.max, 'mdev' => ping_vals.mdev, 'time' => Time.now().to_i, 'secret' => PROBE_SECRET) LOGGER.debug("Result body: #{res.body}") rescue => e LOGGER.error("send_ping_metric errored out - #{e.inspect}") end end def send_traceroute_metric(site, ip, traceroute_out) LOGGER.info("Sending traceroute metric") uri = URI("http://#{MASTER_HOST}:#{MASTER_PORT}/send_metric") LOGGER.debug("URL: #{uri}") begin res = Net::HTTP.post_form(uri, 'name' => 'traceroute', 'source_site' => PROBE_SITE, 'site' => site, 'ip' => ip, 'traceroute' => traceroute_out, 'time' => Time.now().to_i, 'secret' => PROBE_SECRET) LOGGER.debug("Result body: #{res.body}") rescue => e LOGGER.error("send_traceroute_metric errored out - #{e.inspect}") end end # Make sure required vars are set if MASTER_HOST.nil? || MASTER_HOST.empty? puts "ERROR, MASTER_HOST is not set! Exiting..." exit 1 end while true # Send pang to master server along with secret LOGGER.info("Sending pang") if !send_pang LOGGER.info('Error, cannot reach master or secret failed!') else # We got a pung back, let's get all sites # Parse returned json from master probe_sites = get_probe_sites() # Let's loop through the sites and ping ips probe_sites.each do |site, ip| unless site == PROBE_SITE LOGGER.info("Pinging #{site} - #{ip}") ping_cmd = "ping -c 5 -i 1 #{ip}" ping = Mixlib::ShellOut.new(ping_cmd) ping.run_command # Parse out the output ping_out = OpenStruct.new ping_out.site = site ping_out.ip = ip ping.stdout.each_line do |line| line.chomp! if line.include?("packet loss") /^(\d+) packets transmitted, (\d+) packets received, ([0-9\.\-\/]+)\% packet loss/.match(line) ping_out.transmitted = $1 ping_out.received = $2 ping_out.packet_loss = $3 elsif line.start_with?("round-trip") /^round-trip min\/avg\/max \= ([0-9\.\-\/]+)\/([0-9\.\-\/]+)\/([0-9\.\-\/]+) ms$/.match(line) ping_out.min = $1 ping_out.avg = $2 ping_out.max = $3 ping_out.mdev = $4 end end #2 packets transmitted, 2 packets received, 0% packet loss #round-trip min/avg/max = 0.639/1.122/1.606 ms send_ping_metric(ping_out) LOGGER.info("Tracerouting #{site} - #{ip}") traceroute_cmd = "traceroute #{ip}" traceroute = Mixlib::ShellOut.new(traceroute_cmd) traceroute.run_command send_traceroute_metric(site, ip, traceroute.stdout) LOGGER.debug("OUT: #{traceroute.stdout}") end end end # Sleep for a bit before checking again sleep(60) end
module Ricer::Plugins::Note class Note < Ricer::Plugin def plugin_revision; 3; end def upgrade_1; Message.upgrade_1; end def upgrade_2; Message.upgrade_2; end def upgrade_3; Message.upgrade_3; end def ricer_on_user_loaded deliver_messages unless Ricer::Irc::User.current.registered? end def ricer_on_user_authenticated deliver_messages end private def unread Ricer::Plugins::Note::Message.uncached do Ricer::Plugins::Note::Message.inbox(Ricer::Irc::User.current).unread.count end end def deliver_messages count = unread Ricer::Irc::User.current.send_message(t(:msg_new_notes, count: count)) if count > 0 end end end
class EventInterestsController < ApplicationController def index @events = Event.joins(:event_interests).where(event_interests: {volunteer_id: current_volunteer, match: true}) end end
require 'helper' class TestLocation < Test::Unit::TestCase def setup VCR.use_cassette('location_search') do @results = Retailigence::Location.search( userlocation: '37.3323,-122.0312', requestorid: 'test', keywords: 'Volkswagen' ) end @first_result = @results.first @first_location = @first_result.locations.first end def test_search assert_equal Retailigence::SearchResult, @results.class end def test_locations assert_equal Retailigence::Location, @first_location.class end def test_distance assert_equal 3.683537289443949, @first_location.distance.distance assert_equal 'miles', @first_location.distance.units end def test_retailer assert_equal 'Frys', @first_location.retailer.name end def test_location_coordinates assert_equal 37.380241, @first_location.latitude assert_equal -122.00187, @first_location.longitude end def test_address address = @first_location.address assert_equal '1077 E Arques Ave', address.address1 assert_equal 'Sunnyvale', address.city assert_equal 'CA', address.state assert_equal '94085', address.postal assert_equal 'US', address.country end end
class Chef <ApplicationRecord validates_presence_of :name has_many :dishes def all_ingredients ingredients = [] self.dishes.each do |dish| dish.ingredients.each do |ingredient| ingredients << ingredient.name end end ingredients.uniq! end end
class Number_to_words def initialize(number) @number = number end def number @number end def get_ones ones = { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine"} ones_place = ones.fetch(@number) ones_place end def get_teens teens = { 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen"} teens_place = teens.fetch(@number) teens_place end def get_tenths tenths = { 20 => "twenty", 30 => "thirty", 40 => "fourty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80=> "eighty", 90 => "ninety" } tenths_place = tenths.fetch(@number) tenths_place end end # Doesn't currently work but includes if statements for future # # def num_words # ones = { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine"} # teens = { 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen"} # tenths = { 20 => "twenty", 30 => "thirty", 40 => "fourty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80=> "eighty", 90 => "ninety" } # # if (@number.length === 1) # ones_place = ones.fetch(@number) # elsif(@number.length === 2) # # end # # def get_teens # teens = { 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen"} # # teens_place = teens.fetch(@number) # teens_place # end # # def get_tenths # tenths = { 20 => "twenty", 30 => "thirty", 40 => "fourty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80=> "eighty", 90 => "ninety" } # # tenths_place = tenths.fetch(@number) # tenths_place # end # end
FactoryGirl.define do factory :hospital do provider_id 1 provider_name 'Mercy Hospital' provider_street_address '1234 Mercy Way' provider_city 'Chicago' provider_state 'IL' provider_zip_code 60669 hrr 'Chicagoland' total_discharges 100 count_drgs 50 average_covered_charges 1200.20 average_total_payments 120.20 latitude 83.2123 longitude 21.2432 # total_cost_index 20 end end
# # Cookbook Name:: mysql01 # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # execute 'apt-get update' do command 'apt-get update' ignore_failure true end execute 'update-locale' do command 'update-locale LANG="ja_JP.UTF-8" LANGUAGE="ja_JP:ja"' ignore_failure true end %w{ nmon language-pack-ja-base language-pack-ja mysql-server }.each do |pkgname| package "#{pkgname}" do action :install end end service "mysql" do action [ :enable, :start] end template "mysql_cnf" do path "/etc/mysql/my.cnf" source "my.cnf.erb" owner "root" group "root" mode 0644 notifies :restart, "service[mysql]" end template "mysql_character_set_cnf" do path "/etc/mysql/conf.d/character-set.cnf" source "character-set.cnf.erb" owner "root" group "root" mode 0644 notifies :restart, "service[mysql]" end template "engine_cnf" do path "/etc/mysql/conf.d/engine.cnf" source "engine.cnf.erb" owner "root" group "root" mode 0644 notifies :restart, "service[mysql]" end template "mysqld_safe_syslog_cnf" do path "/etc/mysql/conf.d/mysqld_safe_syslog.cnf" source "mysqld_safe_syslog.cnf.erb" owner "root" group "root" mode 0644 notifies :restart, "service[mysql]" end p "--------------------------------" p Chef::Config[:cookbook_path] p Chef::Config[:file_cache_path] p "--------------------------------" # secure install root_password = node["mysql"]["root_password"] execute "secure_install" do command "/usr/bin/mysql -u root < #{Chef::Config[:file_cache_path]}/secure_install.sql" action :nothing only_if "/usr/bin/mysql -u root -e 'show databases;'" ignore_failure true end template "#{Chef::Config[:file_cache_path]}/secure_install.sql" do owner "root" group "root" mode 0644 source "secure_install.sql.erb" variables({ :root_password => root_password, }) notifies :run, "execute[secure_install]", :immediately end # create database db_name = node["mysql"]["db_name"] execute "create_db" do command "/usr/bin/mysql -u root -p#{root_password} < #{Chef::Config[:file_cache_path]}/create_db.sql" action :nothing not_if "/usr/bin/mysql -u root -p#{root_password} -D #{db_name}" end template "#{Chef::Config[:file_cache_path]}/create_db.sql" do owner "root" group "root" mode 0644 source "create_db.sql.erb" variables({ :db_name => db_name, }) notifies :run, "execute[create_db]", :immediately end # create user user_name = node["mysql"]["user"]["name"] user_password = node["mysql"]["user"]["password"] execute "create_user" do command "/usr/bin/mysql -u root -p#{root_password} < #{Chef::Config[:file_cache_path]}/create_user.sql" action :nothing not_if "/usr/bin/mysql -u #{user_name} -p#{user_password} -D #{db_name}" end template "#{Chef::Config[:file_cache_path]}/create_user.sql" do owner "root" group "root" mode 0644 source "create_user.sql.erb" variables({ :db_name => db_name, :username => user_name, :password => user_password, }) notifies :run, "execute[create_user]", :immediately end
module ApplicationHelper def nav_link(text, path) cls = current_page?(path) ? 'active' : nil content_tag(:li, :class => cls) do link_to text, path end end end
class API::V1::LocationsController < ApplicationController before_action :authenticate_user_from_token!, except: :current def index @locations = Location.includes(:experiences) .where('experiences_count > ?', 0).all @experiences = Experience.all end def show @location = Location.includes(:state, experiences: :user).find(params[:id]) end def current @location = Location.current end end
class Post < ApplicationRecord belongs_to :authors has_one :authors end
class AddModifiedToDistributions < ActiveRecord::Migration def change add_column :distributions, :modified, :datetime end end
require 'spec_helper' describe Payoneer::System do describe '.status' do let(:parsed_response) { { 'Status' => '000', 'Description' => 'All good', } } let(:response) { Payoneer::Response.new('000', 'All good') } before do allow(Payoneer).to receive(:make_api_request).with('Echo') { parsed_response } end it 'returns a ResponseStatus object from the Payoneer response' do expect(described_class.status).to eq response end end end
require 'ostruct' module BlameGun module Statistics class CalculatedComposite attr_reader :hash_composite, :calculation def initialize(hash_composite, &calculation) @hash_composite = hash_composite @calculation = calculation end def collect(*args) hash_composite.collect(*args) end def result hash_composite.result.map_scores do |inner_stat| apply_calculation(inner_stat) end end private def apply_calculation(inner_stat) OpenStruct.new(inner_stat).instance_eval &calculation end end end end
class AddDefaultValueToMessageRead < ActiveRecord::Migration def change remove_column :messages,:read add_column :messages, :read, :boolean, :default => false end end
require 'test_helper' include SessionsHelper class UsersControllerTest < ActionController::TestCase setup do @user = users(:user1) @admin_user = users(:admin_user) @regular_user = users(:regular_user) end teardown do log_out end test 'admin should get index' do log_in(@admin_user) get :index assert_response :success assert_not_nil assigns(:users) end test 'regular user should get redirected' do log_in(@regular_user) get :index assert_nil assigns(:users) assert_redirected_to root_path end test 'anonymous user should get redirected' do assert_equal false, logged_in? get :index assert_nil assigns(:users) assert_redirected_to root_path end test "should get new" do get :new assert_response :success end test "should create user" do assert_difference('User.count') do post :create, user: {email: 'test_email@cloudhaus.org', first_name: @user.first_name, last_name: @user.last_name, password: 'test_password', password_confirmation: 'test_password'} end assert_redirected_to user_path(assigns(:user)) end test 'admins can show users' do log_in(@admin_user) get :show, id: @user assert_response :success end test 'regular users can show self' do log_in(@regular_user) get :show, id: @regular_user assert_response :success end test 'regular users can not show others' do log_in(@regular_user) get :show, id: @user assert_redirected_to root_path end test 'anonymous can not show users' do get :show, id: @user assert_redirected_to root_path end test 'admin should get edit' do log_in(@admin_user) get :edit, id: @user assert_response :success end test 'regular users should get edit for self' do log_in(@regular_user) get :edit, id: @regular_user assert_response :success end test 'regular users can\'t get edit for others' do log_in(@regular_user) get :edit, id: @user assert_redirected_to root_path end test 'anonymous can\'t get edit' do get :edit, id: @user assert_redirected_to root_path end test 'admin should be able to update user' do log_in(@admin_user) patch :update, id: @user, user: {email: @user.email, first_name: 'NewFirstName', id: @user.id, last_name: @user.last_name} assert_equal User.find(@user[:id]).first_name, 'NewFirstName' assert_redirected_to user_path(assigns(:user)) end test 'regular users should be able to update self' do log_in(@regular_user) patch :update, id: @regular_user, user: {email: @regular_user.email, first_name: 'NewFirstName', id: @regular_user.id, last_name: @regular_user.last_name} assert_equal @regular_user.reload.first_name, 'NewFirstName' assert_redirected_to user_path(assigns(:user)) end test 'regular users should not be able to update others' do log_in(@regular_user) old_first_name = @user.first_name patch :update, id: @user, user: {email: @user.email, first_name: 'NewFirstName', id: @user.id, last_name: @user.last_name} assert_equal @user.reload.first_name, old_first_name assert_redirected_to root_path end test 'anonymous should not be able to update others' do old_first_name = @user.first_name patch :update, id: @user, user: {email: @user.email, first_name: 'NewFirstName', id: @user.id, last_name: @user.last_name} assert_equal @user.reload.first_name, old_first_name assert_redirected_to root_path end test 'admin should be able to destroy user' do log_in(@admin_user) assert_difference('User.count', -1) do delete :destroy, id: @user end assert_redirected_to users_path end test 'regular users should not be able to destroy self' do log_in(@regular_user) assert_difference('User.count', 0) do delete :destroy, id: @regular_user end assert_redirected_to root_path end test 'regular users should not be able to destroy other user' do log_in(@regular_user) assert_difference('User.count', 0) do delete :destroy, id: @user end assert_redirected_to root_path end test 'anonymouse users should not be able to destroy user' do assert_difference('User.count', 0) do delete :destroy, id: @user end assert_redirected_to root_path end end
class CurrencyExchange < ApplicationRecord has_paper_trail require 'uri' require 'csv' require 'roo' validates :currency_from, presence: true validates :currency_to, presence: true def self.download_exchange_rates uri = URI.parse("#{ENV['APILAYER_HOST']}#{ENV['APILAYER_LIVE_URI']}?access_key=#{ENV['APILAYER_ACCESS_KEY']}") response = Net::HTTP.get_response(uri) json_data = JSON.parse(response.body) if json_data["success"] == true timestamp = json_data["timestamp"] effective_date = Time.at(timestamp).to_datetime quotes = json_data["quotes"] quotes.each do |quote| quote_data = quote[0].scan /.{3}/ currency_from = quote_data[0] currency_to = quote_data[1] currency_exchange = CurrencyExchange.where('currency_from = ? AND currency_to = ?', currency_from, currency_to).last effective_exchg_rate = 0 if currency_exchange.blank? CurrencyExchange.create(value: BigDecimal(quote[1].to_s), effective_date: effective_date, active: true, currency_from: currency_from, currency_to: currency_to) else currency_exchange.update(value: BigDecimal(quote[1].to_s), effective_date: effective_date) end end end self.setup_effective_exchange_rate end def self.setup_effective_exchange_rate xlsx = Roo::Spreadsheet.open('public/csv-exchange-rate/exchange-rate.xlsx') xlsx.each_row_streaming do |row| if row[0].value == 'USD' currency_from = row[0].value.to_s currency_to = row[1].value.to_s money_gram = row[2].value western_union = row[3].value exchg = CurrencyExchange.find_by(currency_from: currency_from, currency_to: currency_to) if exchg mid_market_rate = exchg.value avg = (money_gram + western_union) / 2.0 effective_rate = avg > mid_market_rate ? mid_market_rate : avg exchg.update(money_gram_rate: money_gram, western_union_rate: western_union, effective_exchange_rate: effective_rate) end end end # csv_text = File.read(Rails.root.join('public', 'csv-exchange-rate', 'exchange-rate.csv')) # csv = CSV.parse(csv_text, :headers => true) # csv.each do |row| # currency_from = row[0].to_s # currency_to = row[1].to_s # money_gram = row[2].to_f # western_union = row[3].to_f # exchg = CurrencyExchange.find_by(currency_from: currency_from, currency_to: currency_to) # if exchg # mid_market_rate = exchg.value # avg = (money_gram + western_union) / 2.0 # effective_rate = avg > mid_market_rate ? mid_market_rate : avg # exchg.update(money_gram_rate: money_gram, western_union_rate: western_union, effective_exchange_rate: effective_rate) # end # end end def self.get_exchange_rate(currency_from, currency_to) currency_exchange = CurrencyExchange.where('currency_from = ? AND currency_to = ?', currency_from, currency_to).last if currency_exchange.blank? return 0 else currency_exchange.value end end end
require 'delegate' module ActiveRemote::Cached class Cache < ::SimpleDelegator attr_reader :cache_provider def initialize(new_cache_provider) @cache_provider = new_cache_provider @nested_cache_provider = ::ActiveSupport::Cache::NullStore.new validate_provider_method_present(:delete) validate_provider_method_present(:exist?) validate_provider_method_present(:fetch) validate_provider_method_present(:read) validate_provider_method_present(:write) super(@cache_provider) end def delete(*args) nested_cache_provider.delete(*args) super end def enable_nested_caching! @nested_cache_provider = ::ActiveSupport::Cache::MemoryStore.new end def exist?(*args) nested_cache_provider.exist?(*args) || super end def fetch(name, options = {}) fetch_value = nested_cache_provider.fetch(name, options) { super } unless valid_fetched_value?(fetch_value, options) delete(name) end return fetch_value end def read(*args) nested_cache_provider.read(*args) || super end def write(*args) nested_cache_provider.write(*args) super end private def nested_cache_provider @nested_cache_provider end def valid_fetched_value?(value, options = {}) return false if value.nil? && !options.fetch(:allow_nil, false) return false if !options.fetch(:allow_empty, false) && value.respond_to?(:empty?) && value.empty? return true end def validate_provider_method_present(method_name) unless self.cache_provider.respond_to?(method_name) raise <<-CACHE_METHOD ActiveRemote::Cached::Cache must respond_to? #{method_name} in order to be used as a caching interface for ActiveRemote CACHE_METHOD end end end end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :nick_name t.integer :country_id t.string :address t.date :birthday t.integer :gender_id t.integer :occupation_id t.string :mail t.integer :uid, :limit => 8 t.boolean :friend_allow_flg, :default => false t.boolean :closed_flg, :default => false t.text :self_introduction, :limit => 64.kilobytes + 1 t.string :access_token t.datetime :oauth_expires_at t.timestamps end add_index :users, :country_id add_index :users, :gender_id add_index :users, :occupation_id add_index :users, :uid add_index :users, :friend_allow_flg add_index :users, :closed_flg add_index :users, :oauth_expires_at end end
require 'rethinkdb' class GetInstance include RethinkDB::Shortcuts def id(id:) @id = id end def execute(connection:) r.table('instance').get(@id).run(connection) end end
require 'time' class RemindersController < ApplicationController def new @reminder = Reminder.new end def create @reminder = Reminder.new(params[:reminder]) if @reminder.date.to_s.to_time < Time.now flash[:error] = "Reminder Date cannot be less than the current date!" redirect_to new_reminder_path else @reminder.save @reminder.update_attribute(:phone_number, "+#{@reminder.phone_number}") @reminder.update_attribute(:reminder_number, random_string(5)) send_verification_to_number(@reminder.phone_number, @reminder.id) redirect_to @reminder end end def show @reminder = Reminder.find(params[:id]) end def random_string(length) rand(36**length).to_s(36) end def index @reminders = Reminder.all end def edit @reminder = Reminder.find(params[:id]) end def send_verification_to_number(number, rid) pn = number twilio_client = Twilio::REST::Client.new TWILIO_CONFIG['sid'], TWILIO_CONFIG['token'] twilio_client.account.sms.messages.create( :from => TWILIO_CONFIG['from'], :to => pn, :body => "Hello. This is your reminder confirmation. Please reply with your reminder id which is: #{rid}. If you do not reply, your reminder will not be saved!" ) end end
require 'spec_helper' describe Intown::Event do let(:response) { stub(:code => 200, :body => '{"foo":"bar"}') } context "searching by artist id" do it "should format the proper artist term in the url" do Intown::Event.should_receive(:get).with(/artists\/Radiohead\/events/, anything).and_return(response) Intown::Event.list(:name => "Radiohead") end end context "Searching by date range" do before :each do Intown::Event.should_receive(:get).with(anything, hash_including(expected_params)).and_return(response) end context "single date" do let(:expected_params) {{ :date => '2013-03-02' }} let(:input_params) {{ :name => "Radiohead", :date => Time.new(2013, 3, 2) }} it "should format the date in the url" do Intown::Event.list(input_params) end end context "date range" do let(:expected_params) {{ :date => '2013-03-02,2013-03-08' }} let(:input_params) {{ :name => "Radiohead", :from => Time.new(2013, 3, 2), :to => Time.new(2013, 3, 8)}} it "should format the date range from to/from date params" do Intown::Event.list(input_params) end end context "upcoming" do let(:expected_params) {{ :date => 'upcoming' }} let(:input_params) {{ :name => "Radiohead", :upcoming => true}} it "should set the date parameter to upcoming" do Intown::Event.list(input_params) end end context "all" do let(:expected_params) {{ :date => 'all' }} let(:input_params) {{ :name => "Radiohead", :all => true}} it "should set the date parameter to all" do Intown::Event.list(input_params) end end end end
class ClassTemplatesByStudioController < ApplicationController before_action :find_studio def show @class_templates = StudioClassTemplateService.instance.class_templates_by_studio @studio end private def find_studio @studio = Studio.find_by id: params[:studio_id] end end
# frozen_string_literal: true require 'spec_helper' describe Diplomat::Autopilot do let(:faraday) { fake } context 'autopilot' do it 'gets the configuration' do json = JSON.generate( { 'CleanupDeadServers' => true, 'LastContactThreshold' => '200ms', 'MaxTrailingLogs' => 250, 'ServerStabilizationTime' => '10ms', 'RedundancyZoneTag' => '', 'DisableUpgradeMigration' => false, 'UpgradeVersionTag' => '', 'CreateIndex' => 4, 'ModifyIndex' => 4 } ) faraday.stub(:get).and_return(OpenStruct.new(body: json)) autopilot = Diplomat::Autopilot.new(faraday) expect(autopilot.get_configuration['CleanupDeadServers']).to eq(true) end it 'gets the health' do json = JSON.generate( { 'Healthy' => true, 'FailureTolerance' => 0, 'Servers' => [{ 'ID' => 'e349749b-3303-3ddf-959c-b5885a0e1f6e', 'Name' => 'node1', 'Address' => '127.0.0.1:8300', 'SerfStatus' => 'alive', 'Version' => '0.7.4', 'Leader' => true, 'LastContact' => '0s', 'LastTerm' => 2, 'LastIndex' => 46, 'Healthy' => true, 'Voter' => true, 'StableSince' => '2017-03-06T22:07:51Z' }] } ) faraday.stub(:get).and_return(OpenStruct.new(body: json)) autopilot = Diplomat::Autopilot.new(faraday) expect(autopilot.get_health['Healthy']).to eq(true) end end end
# The story # # You are a rogue black-hat developer who needs access to some pieces of sensitive information. # # The information you need is kept in a database on a heavily secured system. Luckily, you have managed to sneak your way inside the company who does the maintenance. After several tough interviews, you got a position as a Ruby frontend developer and part of the UI team. # # Little do they know that you’re on this project for a reason. # # Your secret objective: # # Implement the given_credentials method in a way that permanently changes the system’s administrator password to h4xx0r3d. # # The assignment: # # Today is your first day at the project. # # Dave, the lead UI developer, has just assigned you your first task. "I want you to implement this method called given_credentials," says Dave. "This should be straightforward, you know." # # The method is supposed to fetch the given username and password from the login screen and then pass it on as a SecureCredentials object. # # An example implementation would be: # # def given_credentials # SecureCredentials.new('francesca', 'pasta43vr') # end # Your method will be called by the SecureLogin class. The SecureLogin class will then check the credentials against the database and give the user access to the system if successful. # # The vulnerable code you want to exploit # # This is the vulnerable code you want to break into: SecureCredentials = Struct.new(:username, :password) class SecureLogin ADMIN = SecureCredentials.new('admin', 'yoAQNi6fKeC9I') # Gets all users from the database def self.users from_json = ->(data) { SecureCredentials.new(data['user'], data['pw']).freeze } credentials = JSON.load(USER_DATA).map(&from_json).to_set credentials << ADMIN credentials.freeze end def logged_in? !user.nil? end def admin? user == ADMIN end def login! @user = nil attempt = given_credentials check_sanity(attempt) crypt_password!(attempt) check_credentials!(attempt) puts welcome end private # Make sure we’re not dealing with malicious objects def check_sanity(given) fail unless String(given.username) == given.username fail unless String(given.password) == given.password end # Calculate the password hash to be checked against the DB def crypt_password!(given) given.password = given.password.crypt(SALT) end # Check username and password against the DB def check_credentials!(given) all_users = self.class.users if all_users.include?(given) user = all_users.find { |u| u.username == given.username } @user = user if (user.password == given.password) end end def user @user ||= nil end def welcome if logged_in? msg = "Welcome, #{user.username}." msg << (admin? ? " You have administrator rights." : "") else "Login denied" end end end SALT = 'you_cannot_break_this' USER_DATA = <<-EOF [ { "user": "adrian", "pw": "yo1QEK9HWD6qI" }, { "user": "becky", "pw": "yoZ.8wHD5w8ws" }, { "user": "claire", "pw": "yohqIFtr/D1uY" }, { "user": "duncan", "pw": "yoJ.ue1CIy0O." }, { "user": "eric", "pw": "yobdrAbdHVHnQ" } ] EOF
class AddCouponCodeForEvents < ActiveRecord::Migration def self.up add_column :articles, :coupon_code, :string, :default=>nil add_column :articles, :coupon_expiration, :datetime, :default=>nil end def self.down remove_column :articles, :coupon_code remove_column :articles, :coupon_expiration end end
require 'test/unit' require 'rubygems' require 'reactor' require 'helpers' require 'dummy_parser' # Test case for the <tt>ChainReaction::Reaction</tt> class. class TestReactor < Test::Unit::TestCase include ChainReactor::TestHelpers def test_address_not_allowed_by_default reactor = ChainReactor::Reactor.new get_logger assert_equal false, reactor.address_allowed?('192.168.0.1') end def test_adding_reaction_makes_address_allowable reactor = ChainReactor::Reactor.new get_logger reactor.add(['127.0.0.1'],{:parser => :dummy},Proc.new {}) assert reactor.address_allowed? '127.0.0.1' end def test_react_raises_error reactor = ChainReactor::Reactor.new get_logger assert_raises RuntimeError, 'Address is not allowed' do reactor.react('127.0.0.1',{:parser => :dummy}) end end def test_react_calls_block reactor = ChainReactor::Reactor.new get_logger block = Proc.new { |d| 'block has been called' } reactor.add(['127.0.0.1'],{:parser => :dummy},block) reactions = reactor.reactions_for('127.0.0.1') reactor.react('127.0.0.1','This is a string') assert_equal 'block has been called', reactions[0].previous_result end def test_react_calls_multiple_blocks reactor = ChainReactor::Reactor.new get_logger block1 = Proc.new { |d| 'block1' } block2 = Proc.new { |d| 'block2' } reactor.add(['127.0.0.1'],{:parser => :dummy},block1) reactor.add(['127.0.0.1'],{:parser => :dummy},block2) reactor.react('127.0.0.1','This is a string') reactions = reactor.reactions_for('127.0.0.1') assert_equal 'block1', reactions[0].previous_result assert_equal 'block2', reactions[1].previous_result end def test_react_catches_exceptions reactor = ChainReactor::Reactor.new get_logger block = Proc.new { |d| raise 'Block has been called' } reactor.add(['127.0.0.1'],{:parser => :dummy},block) reactor.reactions_for('127.0.0.1') assert_nothing_raised do reactor.react('127.0.0.1','This is a string') end end end
# frozen_string_literal: true # A class for defining global constants in a central place. class AppConst # Client-specific code CLIENT_CODE = ENV.fetch('CLIENT_CODE') IMPLEMENTATION_OWNER = ENV.fetch('IMPLEMENTATION_OWNER') # Constants for roles: ROLE_IMPLEMENTATION_OWNER = 'IMPLEMENTATION_OWNER' # ROLE_CUSTOMER = 'CUSTOMER' # ROLE_SUPPLIER = 'SUPPLIER' # ROLE_TRANSPORTER = 'TRANSPORTER' # Routes that do not require login: BYPASS_LOGIN_ROUTES = [].freeze # Menu FUNCTIONAL_AREA_RMD = 'RMD' # Logging FIELDS_TO_EXCLUDE_FROM_DIFF = %w[label_json png_image].freeze # MesServer LABEL_SERVER_URI = ENV.fetch('LABEL_SERVER_URI') POST_FORM_BOUNDARY = 'AaB03x' # Labels SHARED_CONFIG_HOST_PORT = ENV.fetch('SHARED_CONFIG_HOST_PORT') # LABEL_LOCATION_BARCODE = 'KR_PM_LOCATION' # From ENV? / Big config gem? # LABEL_SKU_BARCODE = 'KR_PM_SKU' # From ENV? / Big config gem? # Printers PRINTER_USE_INDUSTRIAL = 'INDUSTRIAL' PRINTER_USE_OFFICE = 'OFFICE' # PRINT_APP_LOCATION = 'Location' # PRINT_APP_MR_SKU_BARCODE = 'Material Resource SKU Barcode' PRINTER_APPLICATIONS = [ # PRINT_APP_LOCATION, # PRINT_APP_MR_SKU_BARCODE ].freeze # These will need to be configured per installation... BARCODE_PRINT_RULES = { # location: { format: 'LC%d', fields: [:id] }, # sku: { format: 'SK%d', fields: [:sku_number] }, # delivery: { format: 'DN%d', fields: [:delivery_number] }, # stock_adjustment: { format: 'SA%d', fields: [:stock_adjustment_number] } }.freeze BARCODE_SCAN_RULES = [ # { regex: '^LC(\\d+)$', type: 'location', field: 'id' }, # { regex: '^(\\D\\D\\D)$', type: 'location', field: 'location_short_code' }, # { regex: '^(\\D\\D\\D)$', type: 'dummy', field: 'code' }, # { regex: '^SK(\\d+)', type: 'sku', field: 'sku_number' }, # { regex: '^DN(\\d+)', type: 'delivery', field: 'delivery_number' }, # { regex: '^SA(\\d+)', type: 'stock_adjustment', field: 'stock_adjustment_number' } ].freeze # Per scan type, per field, set attributes for displaying a lookup value below a scan field. # The key matches a key in BARCODE_PRINT_RULES. (e.g. :location) # The hash for that key is keyed by the value of the BARCODE_SCAN_RULES :field. (e.g. :id) # The rules for that field are: the table to read, the field to match the scanned value and the field to display in the form. BARCODE_LOOKUP_RULES = { location: { id: { table: :locations, field: :id, show_field: :location_long_code }, location_short_code: { table: :locations, field: :location_short_code, show_field: :location_long_code } } }.freeze # Que QUEUE_NAME = ENV.fetch('QUEUE_NAME', 'default') # Mail ERROR_MAIL_RECIPIENTS = ENV.fetch('ERROR_MAIL_RECIPIENTS') ERROR_MAIL_PREFIX = ENV.fetch('ERROR_MAIL_PREFIX') SYSTEM_MAIL_SENDER = ENV.fetch('SYSTEM_MAIL_SENDER') USER_EMAIL_GROUPS = [].freeze # Business Processes # PROCESS_DELIVERIES = 'DELIVERIES' # PROCESS_VEHICLE_JOBS = 'VEHICLE JOBS' # PROCESS_ADHOC_TRANSACTIONS = 'ADHOC TRANSACTIONS' # PROCESS_BULK_STOCK_ADJUSTMENTS = 'BULK STOCK ADJUSTMENTS' # Locations: Location Types # LOCATION_TYPES_RECEIVING_BAY = 'RECEIVING BAY' # ERP_PURCHASE_INVOICE_URI = ENV.fetch('ERP_PURCHASE_INVOICE_URI', 'default') end
# == Schema Information # # Table name: galleries # # id :integer not null, primary key # name :string default("") # created_at :datetime # updated_at :datetime # user_id :integer # require "rails_helper" describe Gallery, type: :model do let(:gallery) { create(:gallery) } describe "associations" do it "should belong to a user" do assoc = Gallery.reflect_on_association(:user).macro expect(assoc).to eq :belongs_to end it "should have many images" do assoc = Gallery.reflect_on_association(:images).macro expect(assoc).to eq :has_many end end describe "validations" do describe "name" do it "should require a name" do gallery.name = "" expect(gallery).to_not be_valid end end end describe "#is_owned_by?" do let(:user) { create(:user) } it "should return false for non-associated user" do expect(gallery.is_owned_by?(user)).to eq false end it "should return true for an associated user" do gallery.user_id = user.id expect(gallery.is_owned_by?(user)).to eq true end end end
namespace :db do desc 'Fill database with sample data' task populate: :environment do fake_users fake_questions fake_answers end def fake_users 99.times do |n| name = Faker::Name.name email = "example-#{n+1}@example.com" password = "password" biography = Faker::Lorem.sentence(6) User.create!(name: name, email: email, password: password, password_confirmation: password, bio: biography) end end def fake_questions User.all.each do |user| [*0..5].sample.times do |n| title = Faker::Lorem.sentence([*5..10].sample).sub('.', '?') content = Faker::Lorem.sentence([*8..20].sample) user.questions.create!( title: title, content: content) end end end def fake_answers 200.times do |n| question = Question.all.sample content = Faker::Lorem.sentence([*8..20].sample) Answer.create!(content: content, user: User.all.sample, question: question) end end end
class Vote < ActiveRecord::Base belongs_to :vote_option,required: false end
class Messaging::Twilio::Whatsapp < Messaging::Twilio::Api # This number comes from https://www.twilio.com/docs/whatsapp/sandbox#what-is-the-twilio-sandbox-for-whatsapp TWILIO_TEST_WHATSAPP_NUMBER = "+14155238886" def send_message(recipient_number:, message:) super(recipient_number: whatsapp_format(recipient_number), message: message) end def self.communication_type Communication.communication_types[:whatsapp] end def sender_number number = if test_mode? TWILIO_TEST_WHATSAPP_NUMBER else ENV.fetch("TWILIO_PHONE_NUMBER") end whatsapp_format(number) end def whatsapp_format(number) "whatsapp:#{number}" end end
class UsersController < ApplicationController get '/registration/signup' do erb :'/registration/signup' end post '/registration' do user = User.new(params) if user.save session[:user_id] = user.id redirect '/user/home' else @error = "Invalid credentials" erb :'/registration/signup' end end get '/user/home' do if logged_in? @user = User.find(session[:user_id]) @vacations = Vacation.select{|v| v.user_id == session[:user_id]} erb :'/user/home' else redirect '/' end end end