text
stringlengths
10
2.61M
class CreateStallions < ActiveRecord::Migration[5.0] def change create_table :stallions do |t| t.string :name t.integer :age t.string :color t.string :registry_tattoo t.string :link_to_pedigree_url t.string :img_url t.decimal :stud_fee t.integer :stakes_winner_progeny t.timestamps end end end
# frozen_string_literal: true module Brcobranca module Remessa module Cnab400 class Santander < Brcobranca::Remessa::Cnab400::Base # Código de Transmissão # Consultar seu gerente para pegar esse código. Geralmente está no e-mail enviado pelo banco. attr_accessor :codigo_transmissao attr_accessor :codigo_carteira validates_presence_of :documento_cedente, :codigo_transmissao, message: 'não pode estar em branco.' validates_presence_of :digito_conta, message: 'não pode estar em branco.', if: :conta_padrao_novo? validates_length_of :documento_cedente, minimum: 11, maximum: 14, message: 'deve ter entre 11 e 14 dígitos.' validates_length_of :carteira, maximum: 3, message: 'deve ter no máximo 3 dígitos.' validates_length_of :codigo_transmissao, maximum: 20, message: 'deve ter no máximo 20 dígitos.' def initialize(campos = {}) campos = { aceite: 'N', carteira: '101', codigo_carteira: '1' }.merge!(campos) super(campos) end def cod_banco '033' end def nome_banco 'SANTANDER'.format_size(15) end def codigo_transmissao=(valor) @codigo_transmissao = valor.to_s.strip.rjust(20, '0') if valor end # Informacoes do Código de Transmissão # # @return [String] # def info_conta # CAMPO TAMANHO # codigo_transmissao 20 codigo_transmissao end # Zeros do header # # @return [String] # def zeros ''.ljust(16, '0') end # Complemento do header # # @return [String] # def complemento ''.ljust(275, ' ') end # Numero da versão da remessa # # @return [String] # def versao '058' end def monta_header # CAMPO TAMANHO VALOR # tipo do registro [1] 0 # operacao [1] 1 # literal remessa [7] REMESSA # Código do serviço [2] 01 # cod. servico [15] COBRANCA # info. conta [20] # empresa mae [30] # cod. banco [3] # nome banco [15] # data geracao [6] formato DDMMAA # zeros [16] # complemento registro [275] # versao [3] # num. sequencial [6] 000001 "01REMESSA01COBRANCA #{info_conta}#{empresa_mae[0..29].to_s.ljust(30, ' ')}#{cod_banco}#{nome_banco}#{data_geracao}#{zeros}#{complemento}#{versao}000001" end # Detalhe do arquivo # # @param pagamento [PagamentoCnab400] # objeto contendo as informacoes referentes ao boleto (valor, vencimento, cliente) # @param sequencial # num. sequencial do registro no arquivo # # @return [String] # def monta_detalhe(pagamento, sequencial) raise Brcobranca::RemessaInvalida, pagamento if pagamento.invalid? detalhe = '1' # identificacao transacao 9[01] detalhe += Brcobranca::Util::Empresa.new(documento_cedente).tipo # tipo de identificacao da empresa 9[02] detalhe << documento_cedente.to_s.rjust(14, '0') # cpf/cnpj da empresa 9[14] detalhe << codigo_transmissao # Código de Transmissão 9[20] detalhe << pagamento.documento_ou_numero.to_s.ljust(25, ' ') # identificacao do tit. na empresa X[25] detalhe << pagamento.nosso_numero.to_s.rjust(8, '0') # nosso numero 9[8] detalhe << pagamento.formata_data_segundo_desconto # data limite para o segundo desconto 9[06] detalhe << ''.rjust(1, ' ') # brancos X[1] detalhe << pagamento.codigo_multa # Com multa = 4, Sem multa = 0 9[1] detalhe << pagamento.formata_percentual_multa # Percentual multa por atraso % 9[6] detalhe << '00' # Unidade de valor moeda corrente = 00 9[2] detalhe << '0'.rjust(13, '0') # Valor do título em outra unidade 9[15] detalhe << ''.rjust(4, ' ') # brancos X[4] detalhe << pagamento.formata_data_multa # Data para cobrança de multa 9[6] # codigo da carteira # 1 = ELETRÔNICA COM REGISTRO # 3 = CAUCIONADA ELETRÔNICA # 4 = COBRANÇA SEM REGISTRO # 5 = RÁPIDA COM REGISTRO # (BLOQUETE EMITIDO PELO CLIENTE) 6 = CAUCIONADA RAPIDA # 7 = DESCONTADA ELETRÔNICA detalhe << codigo_carteira # codigo da carteira 9[01] # Código da ocorrência: # 01 = ENTRADA DE TÍTULO # 02 = BAIXA DE TÍTULO # 04 = CONCESSÃO DE ABATIMENTO # 05 = CANCELAMENTO ABATIMENTO # 06 = PRORROGAÇÃO DE VENCIMENTO # 07 = ALT. NÚMERO CONT.CEDENTE # 08 = ALTERAÇÃO DO SEU NÚMERO # 09 = PROTESTAR # 18 = SUSTAR PROTESTO detalhe << pagamento.identificacao_ocorrencia # identificacao ocorrencia 9[02] detalhe << pagamento.numero.to_s.rjust(10, '0') # numero do documento X[10] detalhe << pagamento.data_vencimento.strftime('%d%m%y') # data do vencimento 9[06] detalhe << pagamento.formata_valor # valor do documento 9[13] detalhe << cod_banco # codigo banco 9[03] detalhe << ''.rjust(5, '0') # agencia cobradora - deixar zero 9[05] # Espécie de documento: # 01 = DUPLICATA # 02 = NOTA PROMISSÓRIA # 03 = APÓLICE / NOTA DE SEGURO # 05 = RECIBO # 06 = DUPLICATA DE SERVIÇO # 07 = LETRA DE CAMBIO detalhe << pagamento.especie_titulo # Espécie de documento 9[02] detalhe << aceite # aceite (A/N) X[01] detalhe << pagamento.data_emissao.strftime('%d%m%y') # data de emissao 9[06] # Instrução cobrança # 00 = NÃO HÁ INSTRUÇÕES # 02 = BAIXAR APÓS QUINZE DIAS DO VENCIMENTO # 03 = BAIXAR APÓS 30 DIAS DO VENCIMENTO # 04 = NÃO BAIXAR # 06 = PROTESTAR (VIDE POSIÇÃO392/393) # 07 = NÃO PROTESTAR # 08 = NÃO COBRAR JUROS DE MORA detalhe << pagamento.cod_primeira_instrucao # primeira instrução 9[02] detalhe << pagamento.cod_segunda_instrucao # segunda instrução 9[02] detalhe << pagamento.formata_valor_mora # valor mora ao dia 9[13] detalhe << pagamento.formata_data_desconto # data limite para desconto 9[06] detalhe << pagamento.formata_valor_desconto # valor do desconto 9[13] detalhe << pagamento.formata_valor_iof # valor do iof 9[13] detalhe << pagamento.formata_valor_abatimento # valor do abatimento 9[13] detalhe << pagamento.identificacao_sacado # identificacao do pagador 9[02] detalhe << pagamento.documento_sacado.to_s.rjust(14, '0') # documento do pagador 9[14] detalhe << pagamento.nome_sacado.format_size(40) # nome do pagador X[40] detalhe << pagamento.endereco_sacado.format_size(40) # endereco do pagador X[40] detalhe << pagamento.bairro_sacado.format_size(12) # bairro do pagador X[12] detalhe << pagamento.cep_sacado # cep do pagador 9[08] detalhe << pagamento.cidade_sacado.format_size(15) # cidade do pagador X[15] detalhe << pagamento.uf_sacado # uf do pagador X[02] detalhe << pagamento.nome_avalista.format_size(30) # Sacador/Mensagens X[30] detalhe << ''.rjust(1, ' ') # Brancos X[1] detalhe << identificador_movimento_complemento # Identificador do Complemento X[1] detalhe << movimento_complemento # Complemento 9[2] detalhe << ''.rjust(6, ' ') # Brancos X[06] # Se identificacao_ocorrencia = 06 detalhe << pagamento.dias_protesto.rjust(2, '0') # Número de dias para protesto 9[02] detalhe << ''.rjust(1, ' ') # Brancos X[1] detalhe << sequencial.to_s.rjust(6, '0') # numero do registro no arquivo 9[06] detalhe end def identificador_movimento_complemento return 'I' if conta_padrao_novo? ''.rjust(1, ' ') end def movimento_complemento return "#{conta_corrente[8]}#{digito_conta}" if conta_padrao_novo? ''.rjust(2, ' ') end def conta_padrao_novo? !conta_corrente.blank? && conta_corrente.length > 8 end # Valor total de todos os títulos # # @return [String] # def total_titulos total = format '%.2f', pagamentos.sum(&:valor) total.to_s.somente_numeros.rjust(13, '0') end # Trailer do arquivo remessa # # @param sequencial # num. sequencial do registro no arquivo # # @return [String] # def monta_trailer(sequencial) # CAMPO TAMANHO VALOR # código registro [1] 9 # quant. documentos [6] # valor total titulos [13] # zeros [374] 0 # num. sequencial [6] "9#{sequencial.to_s.rjust(6, '0')}#{total_titulos}#{''.rjust(374, '0')}#{sequencial.to_s.rjust(6, '0')}" end end end end end
module Globalize mattr_accessor :available_locales def self.valid_locale?(loc) return false unless loc available_locales.include?(loc.to_sym) end end Globalize::ActiveRecord::ClassMethods.module_eval do def translations_accessor_with_locale_suffix_accessors(name) translations_accessor_without_locale_suffix_accessors(name) Globalize.available_locales.each do |locale| define_method :"#{name}_#{locale}" do read_attribute(name, {locale: locale}) end define_method :"#{name}_#{locale}=" do |value| changed_attributes[:"#{name}_#{locale}"] = value unless value == read_attribute(name, {locale: locale}) write_attribute(name, value, {locale: locale}) end end end alias_method_chain :translations_accessor, :locale_suffix_accessors end
# @author Ido Efrati class SessionsController < ApplicationController # Checks if user already signed in (i.e there is a session). If there is a session the user will be redirected to his/her notes # else the user will be redirected to login page def new if signed_in? redirect_to trips_path end end # Authenticate user email and password. If sucessful then create a session for the user, otherwise alert error message. def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) sign_in user redirect_to trips_path else redirect_to signin_path, :flash => { :error => "Invalid email/password combination" } end end # Destroy the session and redirect the user to the login page def destroy sign_out redirect_to root_url end end
require_relative 'gimme_proxy.rb' require_relative 'proxy_store.rb' require_relative 'proxy_verifier.rb' class ProxyFinder DEFAULT_ATTEMPTS_LIMIT = 8 PROXY_STORE = ProxyStore.new('.seed_proxies') PTC_VERIFIER = PTCProxyVerifier.new NIANTIC_VERIFIER = NianticProxyVerifier.new def self.next_proxy(attempts_limit = DEFAULT_ATTEMPTS_LIMIT) attempts = 0 while attempts < attempts_limit seed_proxy = (!PROXY_STORE.empty? ? PROXY_STORE.next : nil) begin proxy = GimmeProxy.next seed_proxy rescue GimmeProxy::RequestFailed, GimmeProxy::UnexpectedResponseFormat attempts = attempts + 1 else PROXY_STORE << seed_proxy if seed_proxy PROXY_STORE << proxy return proxy end end raise ProxyNotFound.new("A proxy could not be found after " + "#{attempts + 1} tries.") end def self.next_valid_proxy(attempts_limit = DEFAULT_ATTEMPTS_LIMIT, verifiers = [PTC_VERIFIER, NIANTIC_VERIFIER]) attempts = 0 while attempts < attempts_limit proxy = next_proxy return proxy if verifiers.collect { |v| v.verify proxy }.all? attempts = attempts + 1 end raise ValidProxyNotFound.new("A valid proxy could not be found after " + "#{attempts + 1} tries.") end class ProxyNotFound < StandardError; end class ValidProxyNotFound < StandardError; end end
class PostsController < ApplicationController def index @post = Post.all() end def edit @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if(@post.update(posts_params)) redirect_to @post # this will redirect it to show view!!! else render 'edit' end end def new @post=Post.new end def show @post = Post.find(params[:id]) end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to posts_path end def create # here we can just render post param where post is the ID of that form # render plain: params[:post].inspect # here @ is used to define a variable and it is cool and easy # in Post.new(); Post represent the modal and i new we can pass in the params # @post = Post.new(params[:post]); @post = Post.new(posts_params); if(@post.save) redirect_to @post # this will redirect it to show view!!! else render 'new' end end private def posts_params params.require(:post).permit(:title, :body) end end
# adventure_worker.rb class AdventuresWorker include Sidekiq::Worker def get_adventures id library = Library.find(id) if library request = Typhoeus.get(library.url+"/adventures.json") result = JSON.parse(request.body) if result result['adventures'].each do |adventure| existing_story = Adventure.find_by(guid: adventure.guid) if existing_story existing_story.update_attributes(adventure) else library.adventures.create(adventure) end end end end end end
class DepartmentsController < ApplicationController # GET /departments def index @departments = Department.all render json: @departments end end
require "zlib" require File.dirname(__FILE__) + '/../../../spec_helper' require File.dirname(__FILE__) + '/../../../fixtures/class' require File.dirname(__FILE__) + '/fixtures/classes' describe "Zlib::GzipReader.wrap" do before :each do @io = ClassSpecs::StubReaderWithClose.new GzipReaderSpecs::GzippedLoremIpsum end it "can be called without a block" do Zlib::GzipReader.wrap(@io).should be_kind_of(Zlib::GzipReader) end it "raises NoMethodError if argument does not have a write method" do lambda { Zlib::GzipReader.wrap(nil) { } }.should raise_error(NoMethodError) lambda { Zlib::GzipReader.wrap(mock("dummy")) { } }.should raise_error(NoMethodError) end it "invokes the block with an instance of GzipReader" do Zlib::GzipReader.wrap(@io) do |gz| gz.should be_kind_of Zlib::GzipReader end end it "returns the instance of GzipReader" do ret = Zlib::GzipReader.wrap(@io) do |gz| ScratchPad.record gz end ret.should equal(ScratchPad.recorded) end it "allows the GzipReader instance to be closed in the block" do ScratchPad.clear ret = Zlib::GzipReader.wrap(@io) do |gz| gz.close ScratchPad.record :after_close end ScratchPad.recorded.should == :after_close end it "calls io#close once for a trivial block" do @io.should_receive(:close) Zlib::GzipReader.wrap(@io) { } end it "allows IO objects without a close method" do io = mock("io") io.should_receive(:read).any_number_of_times.and_return(GzipReaderSpecs::GzippedLoremIpsum, nil) Zlib::GzipReader.wrap(io) { |gz| gz.read } end it "propagates Exceptions thrown from the block after calling io#close" do @io.should_receive(:close) lambda { Zlib::GzipReader.wrap(@io) { raise "error from block" } }.should raise_error(RuntimeError) end end
require_dependency 'annotable/application_controller' module Annotable class ReportsController < ApplicationController before_action :organization before_action :set_report, only: %i[show update destroy].freeze class << self # Define which resources are the authorized to be included # @return [Array] def allowed_includes %i[organization].freeze end # Define which fields can be use as filters # @return [Array] def allowed_filterables %i[created_at updated_at organization_id title content].freeze end end # GET /reports # @return [String] Json Response def index reports = @organization.reports.all jsonapi_filter(reports, self.class.allowed_filterables) do |filtered_organizations| jsonapi_paginate(filtered_organizations.result) do |paginated_organizations| render jsonapi: paginated_organizations end end end # GET /reports/<UUID> # @return [String] Json Response def show render jsonapi: @report end # POST /reports # @return [String] Json Response def create report = @organization.reports.build(report_params) if report.save render jsonapi: report, status: :created, location: organization_report_url(@organization, report) else render jsonapi_errors: report.errors, status: :unprocessable_entity end end # PATCH/PUT /reports/<UUID> # @return [String] Json Response def update if @report.update(report_params) render jsonapi: @report else render jsonapi_errors: @report.errors, status: :unprocessable_entity end end # DELETE /reports/<UUID> # @return [String] Empty Body def destroy @report.destroy end private # Use callbacks to share common setup or constraints between actions # @return [[]] def set_report @report = @organization.reports.find(params[:id]) end # Only allow a trusted parameter "white list" through # @return [ActionController::Parameters] def report_params jsonapi_deserialize(params, only: %i[name content organization_id]) end # Scope to the Annotable::Organization # @return [Annotable::Organization] def organization @organization = Organization.find(params.require(:organization_id)) end end end
# frozen_string_literal: true class OrganizationsPresenter < BasePresenter attr_reader :organizations def initialize(organizations, params, current_user) @organizations = organizations @params = params @current_user = current_user end def events_count(organization) events(organization).size end private attr_reader :params, :current_user def events(organization) grouped_event_groups[organization.id]&.flat_map(&:events) || [] end def grouped_event_groups event_groups.group_by(&:organization_id) end def event_groups @event_groups ||= EventGroupPolicy::Scope.new(current_user, EventGroup).viewable.includes(:events) end end
class StudyPassagesController < ApplicationController before_action :set_study_passage, only: [:show, :edit, :update, :destroy] # GET /study_passages # GET /study_passages.json def index @study_passages = StudyPassage.all end # GET /study_passages/1 # GET /study_passages/1.json def show end # GET /study_passages/new def new @study_passage = StudyPassage.new end # GET /study_passages/1/edit def edit end # POST /study_passages # POST /study_passages.json def create parser = VerseParser.new(params[:query]) parser.validate @study_passage = StudyPassage.new(parser.to_study_passage_attributes.merge(study_id: params[:study_id])) respond_to do |format| if @study_passage.save format.html { redirect_to :back} format.json { render :show, status: :created, location: @study_passage } end end end # PATCH/PUT /study_passages/1 # PATCH/PUT /study_passages/1.json def update respond_to do |format| if @study_passage.update(study_passage_params) format.html { redirect_to @study_passage, notice: 'Study passage was successfully updated.' } format.json { render :show, status: :ok, location: @study_passage } else format.html { render :edit } format.json { render json: @study_passage.errors, status: :unprocessable_entity } end end end # DELETE /study_passages/1 # DELETE /study_passages/1.json def destroy @study_passage.destroy respond_to do |format| format.html { redirect_to :back } end end private # Use callbacks to share common setup or constraints between actions. def set_study_passage @study_passage = StudyPassage.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def study_passage_params params.require(:study_passage).permit(:study_id, :bible_book, :chapter_start, :verse_start, :chapter_end, :verse_end, :bible_translation_id, :position, :bible_passage_annotation_id, :duration_in_minutes) end end
class Genre < ActiveRecord::Base validates :name, presence: true, uniqueness: true has_many :characterizations, dependent: :destroy has_many :movies, through: :characterizations end
require 'spec_helper' describe Game do it { should have_many(:players).through(:game_players) } it { should have_many(:comments) } it "saves itself" do game = Game.new(location: "Seward Park", price: 15, daytime: Time.now) game.save expect(Game.first).to eq(game) end it "does not save a game without a location" do game = Game.new(price: 15, daytime: Time.now) game.save expect(Game.count).to eq(0) end it "does not save a game without a price" do game = Game.new(location: "Seward Park", daytime: Time.now) game.save expect(Game.count).to eq(0) end it "does not save a game without a time" do game = Game.new(location: "Seward Park", price: 15) game.save expect(Game.count).to eq(0) end it "price must be a number" do game = Game.new(location: "Seward Park", price: "fifteen", daytime: Time.now) game.save expect(Game.count).to eq(0) end it "price must be less than or equal to 20" do game = Game.new(location: "Seward Park", price: 21, daytime: Time.now) game.save expect(Game.count).to eq(0) end it "returns games from earliest time forward" do game2 = Game.new(location: "Seward Park", price: 15, daytime: Time.now + 10*60) game2.save game1 = Game.new(location: "Seward Park", price: 15, daytime: Time.now) game1.save expect(Game.all).to eq([game1, game2]) end describe "max 10 players" do context "when invalid" do let (:game) do Fabricate.build(:game) do players { Fabricate.times(11, :player)} end end it {expect(game).to be_invalid} it "sets the errors on game" do game.valid? expect(game.errors.full_messages).to include "Players - There are too many players." end 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) Role.create(name: :admin) Role.create(name: :user) Role.create(name: :company_user) User.delete_all user1 = User.create!(email: 'admin@roulette.test', password: 'admintest', password_confirmation: 'admintest', first_name: 'Admin', last_name: 'Admin', birth: '01-06-2019', avatar: File.new("public/images/medium/admin.png")) user1.remove_role(:user) user1.add_role(:admin) user2 = User.create!(email: 'user@roulette.test', password: 'usertest', password_confirmation: 'usertest', first_name: 'User', last_name: 'Roulette', birth: '01-06-2019', avatar: File.new("public/images/medium/user.png")) user2.add_role(:user) user3 = User.create!(email: 'vip@roulette.test', password: 'viptest', password_confirmation: 'viptest', first_name: 'Vip', last_name: 'Roulette', birth: '01-06-2019', avatar: File.new("public/images/medium/company_user.png")) user3.remove_role(:user) user3.add_role(:company_user) video1 = Video.create!(videoid: 'dQw4w9WgXcQ', addedby: 'admin', number: 1) video2 = Video.create!(videoid: 'd1YBv2mWll0', addedby: 'admin', number: 2)
module Voted extend ActiveSupport::Concern def create_vote @object = controller_name.classify.constantize.find(params[:id]) authorize! :create_vote, @object @vote = @object.vote(current_user, params[:value]) respond_to do |format| format.json { render json: { vote: @vote, rating: @object.rating } } end end end
class ModuloCalificadasController < ApplicationController before_action :set_modulo_calificada, only: [:show, :edit, :update, :destroy] respond_to :html, :xml, :json def index @modulo_calificadas = ModuloCalificada.all respond_with(@modulo_calificadas) end def show respond_with(@modulo_calificada) end def new @modulo_calificada = ModuloCalificada.new respond_with(@modulo_calificada) end def edit end def create @modulo_calificada = ModuloCalificada.new(modulo_calificada_params) @modulo_calificada.save respond_with(@modulo_calificada) end def update @modulo_calificada.update(modulo_calificada_params) respond_with(@modulo_calificada) end def destroy @modulo_calificada.destroy respond_with(@modulo_calificada) end private def set_modulo_calificada @modulo_calificada = ModuloCalificada.find(params[:id]) end def modulo_calificada_params params.require(:modulo_calificada).permit(:paciente_id, :nombre_completo, :genero, :tipo_documento, :numero_identificacion, :fecha_nacimiento, :edad, :lugar_nacimiento, :estrato_economico, :nivel_ingresos, :etapa_ciclo_vital, :ciudad, :departamento, :direccion, :telefono, :email, :nivel_escolaridad, :estado_civil, :afiliacion, :motivo_calificacion) end end
require 'user' describe User do it 'can be create a new user' do user = User.add(name: 'user1', username: 'user100', email: 'user1@gmail.com', password: '123') expect(user.name).to eq 'user1' end it 'should be able to list all the user' do expect { User.add(name: 'user1', username: 'user100', email: 'user1@gmail.com', password: '123') }.to change { User.list.count }.by 1 end it 'should encrypt the password' do user = User.add(name: 'user1', username: 'user100', email: 'user1@gmail.com', password: '123') expect(user.password).to_not eq '123' 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) # ['Politics', 'Sports', 'News', 'Education', 'Games'].each do |c| # Category.create!(name: c) # end # 20.times do |index| # User.create!(name: Faker::Name.first_name, # email: Faker::Internet.email, # password: 123456 # ) # end # 50.times do |post| # Post.create!( # caption: Faker::HarryPotter.spell, # content: Faker::HarryPotter.quote, # user: User.find(rand(1..User.count)), # category: Category.find(rand(1..Category.count)) # ) # end 30.times do |post| Follow.create!( follower: User.find(3), followed: User.find(rand(10..User.count)) ) end
# TODO: cash_transactions probably needs to be a model of its own. class User < ActiveRecord::Base include Uuid include Persona include Notify::Receiver has_many :identities belongs_to :partner has_many :tips has_many :purchases has_many :withdrawals has_one :reputation has_many :sales, through: :tips, source: :purchases has_many :iap_receipt_verifications has_many :purchased_tips, through: :purchases, source: :tip, inverse_of: :purchasers, class_name: "Tip" has_many :follows has_many :recommendations, as: :receiver # Accounting associations belongs_to :customer_account # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :omniauthable, :trackable, :rememberable, :confirmable validates_presence_of :username validates_uniqueness_of :email, allow_blank: true validates_uniqueness_of :username, allow_blank: true validates_format_of :email, with: /.+@.+/, allow_blank: true validates_format_of :paypal_email, with: /.+@.+/, allow_blank: true validates_with ProtectedUsernamesValidator validates_presence_of :email, unless: :confirmation_required? validates_each :email do |record, attr, value| # Email presence must take confirmation status into consideration if record.send(:confirmation_required?) && value.blank? && record.unconfirmed_email.blank? record.errors.add attr, :required end end # validates_presence_of :unconfirmed_email, if: :confirmation_required? # Scopes scope :admins, -> { where admin: true } # Helper methods def full_name "#{self.first_name} #{self.last_name}" end def account_balance @account_balance ||= AccountBalance.new(self) end def cash_transactions # UPDATE THIS TO BE A MODEL IN BETWEEN THEM ALL # this combines purchases and sales, which are both purchase models. the diff is the user association to them. (purchases + sales).sort_by(&:created_at).reverse end # Public. Calculates the current cost of purchasing a tip with reputation. # Currently, the calculation is 1/100th of the user's reputation. If the user # has zero reputation, 0 is returned. def reputation_tip_cost (self.reputation.balance * 0.01).to_f.ceil.to_i end # Callbacks after_create do unless self.reputation self.reputation = Reputation.create(user: self) end unless self.customer_account self.update_attributes! customer_account: CustomerAccount.create!(user: self) end end # Find a useable username for the user for now. before_validation do if self.username.blank? self.username = "#{self.first_name}#{self.last_name}#{SecureRandom.hex(4)}" end end # Override how devise sends notifications. # def send_devise_notification(notification, *args) # message = devise_mailer.send(notification, self, *args) # # Remove once we move to Rails 4.2+ only. # if message.respond_to?(:deliver_now) # message.deliver_now # else # message.deliver # end # end # Public. Assign the given username, but add characters to the end of it if # any other user currently has the username. def safely_assign_username(username) username = full_name.parameterize if username.blank? username = email.gsub(/@.*/, '').parameterize if username.blank? try_username = username num = 0 while User.exists?(username: try_username) num += 1 try_username = "#{username}-#{num}" end self.username = try_username self.username end end
class User < ApplicationRecord has_many :lists has_many :tasks def self.guest find_or_create_by!(nickname: 'ゲスト', email: 'guest@example.com') do |user| user.password = SecureRandom.urlsafe_base64 end end # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :nickname, presence: true validates :password, format: { with: /\A(?=.*?[a-z])(?=.*?[\d])[a-z\d]{6,}+\z/i, message: ' Include both letters and numbers' } end
class AddFileFieldsToAvatarVideos < ActiveRecord::Migration def change add_column :avatar_videos, :media_type, :string, null: false add_column :avatar_videos, :content_type, :string, null: false add_column :avatar_videos, :file_size, :integer, null: false add_column :avatar_videos, :preview_width, :integer add_column :avatar_videos, :preview_height, :integer end end
namespace :easyproject do namespace :easy_money do desc <<-END_DESC Recalculates time entry expenses on project Example: bundle exec rake easyproject:easy_money:recalculate_time_entry_expenses_on_project RAILS_ENV=production END_DESC task :recalculate_time_entry_expenses_on_project => :environment do puts '' print 'Enter project ID to recalculate (if no ID will be specified than all projects will be recalculated): ' project_id = STDIN.gets.to_s.strip project = nil recalculate_subprojects = false if project_id.blank? print 'Are you sure to recalculate all projects? [y/n]' exit unless STDIN.gets.match(/^y$/i) else project = Project.where(:id => project_id).first if project.nil? print 'Project not found.' exit end if project.self_and_descendants.has_module(:easy_money).size > 0 print "Do you want to recalculate subprojects of ##{project.id} - #{project.name}? [y/n]" recalculate_subprojects = !STDIN.gets.match(/^y$/i).nil? else print 'This project or subproject has not enabled Easy Money module.' exit end end puts '' if project_id.blank? project_ids = Project.non_templates.active.has_module(:easy_money).pluck(:id) else if recalculate_subprojects project_ids = project.self_and_descendants.active.has_module(:easy_money).pluck(:id) else project_ids = [project_id.to_i] end end puts 'Recalculating started ...' i = 0 project_ids.each do |pid| i += 1 p = Project.where(:id => pid).select([:id, :name]).first puts "#{i}/#{project_ids.size} recalculating ##{p.id} - #{p.name}" EasyMoneyTimeEntryExpense.update_project_time_entry_expenses(pid) end puts 'Recalculating finished.' end end end
class CommentsController < ApplicationController def new @speak = Speak.find(params[:speak_id]) @comment = Comment.new @comment.speak_id = @speak.id end def create @comment = Comment.create(create_params) end def destroy @comment = Comment.find(params[:id]) if ad_user_signed_in? @comment.destroy if current_ad_user.id == @comment.ad_user.id redirect_to (speak_path(@comment.speak)) end if st_user_signed_in? @comment.destroy if current_st_user.id == @comment.st_user.id redirect_to (speak_path(@comment.speak)) end end private def create_params if st_user_signed_in? params.require(:comment).permit(:text,:log_grade,:exp_grade,:cre_grade,:speak_id).merge(st_user_id: current_st_user.id) else ad_user_signed_in? params.require(:comment).permit(:text,:log_grade,:exp_grade,:cre_grade,:speak_id).merge(ad_user_id: current_ad_user.id) end end end
# coding: utf-8 require_relative "sha256lib.rb" # --------- # Constants - K # --------- # SHA256 uses the same sequence of sixty-four constant 32-bit words. # # These words represent the first thirty-two bits of the fractional parts of the cube roots of the first sixty-four prime numbers. These are "nothing up my sleeve" constants. # The first sixty-four primes primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311] # Store results for display later roots = []; constants = []; hexs = []; # For each prime number primes.each do |prime| # Get the cube root of the prime root = prime ** (1/3.0) roots << root # Get fractional part of the number fractional = root - root.floor # Convert fractional part to hexadecimal # # Example: # # 3√2 = 1.259921049895 # 0.259921049895 <- fractional part is what we want # # Keep multiplying the fractional part by 16 and taking the integer as the next hex character. # # 0.259921049895 * 16 <- multiply by 16 # = 4.15873679832 <- the integer part is used for the hexadecimal result # # 0.15873679832 * 16 # = 2.53978877312 # # 0.53978877312 * 16 # = 8.63662036992 # # ... # # Hex: 428a2f98 # # In other words, you multiply the fractional part by 2^32, floor it, then convert to hexadecimal. # hex = "" 8.times do # 32 bits = 8 hex characters product = fractional * 16 # multiply fraction by 16 carry = product.floor # the integer part of the product is used for the next hexadecimal character fractional = product - product.floor # the fractional part of the product is used for next round hex << carry.to_s(16) end # Save results hexs << hex constants << hex.to_i(16) end # --------- # Animation # --------- system "clear" puts "-------------" puts "constants (K)" puts "-------------" sleep 0.1 (64+1+3).times do |i| # extra 3 iterations to see through system "clear" puts "-------------" puts "constants (K)" puts "-------------" i.times do |j| # 3 or more behind if j <= i-4 puts "#{j.to_s.ljust(2, " ")} = #{bits(constants[j])}" end # 2 behind if j == i-3 puts "#{j.to_s.ljust(2, " ")} = 3√#{primes[j].to_s.ljust(3, " ")} = #{bits(constants[j])}" end # 1 behind if j == i-2 puts "#{j.to_s.ljust(2, " ")} = 3√#{primes[j].to_s.ljust(3, " ")} = #{(roots[j] - roots[j].floor).to_s[2..-1]}" end # current if j == i-1 puts "#{j.to_s.ljust(2, " ")} = 3√#{primes[j].to_s.ljust(3, " ")} = #{roots[j]}" end # dont try and show trailing 64, 65, 66 (this is just to format last 3) break if j >= 63 end sleep 0.1 end sleep 1
# == Schema Information # # Table name: microposts # # id :integer not null, primary key # user_id :integer not null # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_microposts_on_user_id_and_created_at (user_id,created_at) # # content :string in translations table require 'spec_helper' describe Micropost do let(:user) { create(:user) } let(:micropost) { build(:micropost, user: user) } subject { micropost } specify "Globalize3 model attributes" do should respond_to(:translations) should respond_to(:content) end specify "accessible attributes" do should_not allow_mass_assignment_of(:user) end describe "associations" do it { should belong_to(:user) } its(:user) { should == user } end describe "class level" do subject { micropost.class } specify "methods" do should respond_to(:from_users_actively_followed_by).with(1).argument should respond_to(:eagerly_paginate).with(1).argument end end describe "initial state" do it { should be_valid } end specify "validations" do should validate_presence_of(:user) should validate_presence_of(:content) should_not allow_value(" ").for(:content) should ensure_length_of(:content).is_at_most(140) end # self.from_users_actively_followed_by(user) tested in user_spec status end
module HTTP class Evaluations < Authenticated OVERALL_PROMPT = 'Overall rating of subject' RESPONSE_PROMPT = 'Response rate' METRICS = { "expectations were clearly defined" => "expectations_clear", "expectations were made clear" => "expectations_clear", "learning objectives were met" => "learning_objectives_met", "Assignments contributed to my learning" => "assigments_useful", "Grading thus far has been fair" => "grading_fair", "The pace of the class" => "pace", "Average hours you spent per week on this subject in the classroom" => "classroom_hours", "Average hours you spent per week on this subject outside of the classroom" => "home_hours", "Lab hours" => "classroom_hours", "Prep hours" => "home_hours" } domain 'edu-apps.mit.edu' def evaluation(mit_class) get '/ose-rpt/subjectEvaluationSearch.htm' set 'termId', mit_class.semester set 'subjectCode', mit_class.number set 'instructorName', mit_class.instructor submit extract_evaluations if click_link { |l| l.href.include?('subjectEvaluationReport.htm') } end private def extract_evaluations METRICS.each_with_object({}).each do |(description, key), hash| match = search("a:contains('#{description}')").first.try(:parent) match ||= search("td:contains('#{description}')").first hash[key] = match.next.next.text.to_f if match.present? end.tap do |hash| hash['percent_response'] = search("strong:contains('#{RESPONSE_PROMPT}')"). first.next.text.strip.split.first.to_f hash['rating'] = search("strong:contains('#{OVERALL_PROMPT}')"). first.next.text.strip.split.first.to_f end end end end
class AddStuffToMAkerStorefronts < ActiveRecord::Migration def change add_column :storefronts, :ships, :boolean add_column :storefronts, :pickup, :boolean end end
# frozen_string_literal: true module Quilt class InstallGenerator < Rails::Generators::Base def run_all_generators generate("quilt:rails_setup") generate("quilt:react_setup") generate("quilt:react_app") end end end
# Given an array of integers, find the first missing positive integer # in linear time and constant space. In other words, find the lowest # positive integer that does not exist in the array. The array can # contain duplicates and negative numbers as well. # For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] # should give 3. # You can modify the input array in-place. require 'rspec/autorun' def missing_positive(arr) contains = 0 arr.each { |num| if num == 1 contains += 1 break end } return 1 if contains == 0 arr.each_with_index { |num, index| arr[index] = 1 if num <= 0 || arr[index] > arr.count } arr.each { |num| arr[num.abs-1] = -arr[num.abs-1].abs } arr.each_with_index { |num, index| return index+1 if num > 0 } arr.count + 1 end RSpec.describe 'Function' do it 'returns first missing positive within array' do expect(missing_positive([3, 4, -1, 1])).to eq(2) end it 'returns first missing positive outside of array' do expect(missing_positive([1, 2, 0])).to eq(3) end end
Rails.application.routes.draw do resources :satellite_trackers, only: [:index] post '/', to: 'satellite_trackers#index', as: 'satellite_tracker' end
require 'rails_helper' context "User 1 and User 2 are already playing a game" do it "does not allow them to begin a new game" do user_1 = create(:user) user_2 = create(:user2) game_1 = Game.create(player_1_board: Board.new(4), player_2_board: Board.new(4), player_1_turns: 0, player_2_turns: 0, current_turn: "player 1", player_1_id: user_1.id, player_2_id: user_2.id ) game_2 = Game.create(player_1_board: Board.new(4), player_2_board: Board.new(4), player_1_turns: 0, player_2_turns: 0, current_turn: "player 1", player_1_id: user_1.id, player_2_id: user_2.id) #ATTEMPT AT USING A SPY # game_2 = spy('game_2') # game_2.deliver # expect(game_2).to have_received(:deliver) # binding.pry # expect(game_2).to_not be_valid end end
# -*- coding: utf-8 -*- # Send SIP "NOTIFY" "check-sync" events. require 'socket' require 'securerandom' require 'rbconfig' require 'bindata' class SipNotifyError < RuntimeError; end class SipNotify REQUEST_METHOD = 'NOTIFY'.freeze VIA_BRANCH_TOKEN_MAGIC = 'z9hG4bK'.freeze # http://tools.ietf.org/html/rfc3261#section-8.1.1.7 # Whether the length in a raw IP packet must be little-endian # (i.e. native-endian) and the Kernel auto-reverses the value. # IP spec. says big-endian (i.e. network order). RAW_IP_PKT_LITTLE_ENDIAN_LENGTH = !! ::RbConfig::CONFIG['host_os'].to_s.match( /\A darwin/xi ) # Whether the fragment offset in a raw IP packet must be # little-endian (i.e. native-endian) and the Kernel # auto-reverses the value. IP spec. says big-endian (i.e. # network order). RAW_IP_PKT_LITTLE_ENDIAN_FRAG_OFF = !! ::RbConfig::CONFIG['host_os'].to_s.match( /\A darwin/xi ) SOCK_OPT_LEVEL_IP = ( if defined?( ::Socket::SOL_IP ) ::Socket::SOL_IP # Linux else ::Socket::IPPROTO_IP # Solaris, BSD, Darwin end ) # Pre-defined event types. # EVENT_TEMPLATES = { # Compatibility. # The most widely implemented event: :'compat-check-cfg' => { :event => 'check-sync' }, # Snom: :'snom-check-cfg' => { :event => 'check-sync;reboot=false' }, :'snom-reboot' => { :event => 'reboot' }, # Polycom: # In the Polycom's sip.cfg make sure that # voIpProt.SIP.specialEvent.checkSync.alwaysReboot="0" # (0 will only reboot if the files on the settings server have changed.) :'polycom-check-cfg' => { :event => 'check-sync' }, :'polycom-reboot' => { :event => 'check-sync' }, # Aastra: :'aastra-check-cfg' => { :event => 'check-sync' }, :'aastra-reboot' => { :event => 'check-sync' }, :'aastra-xml' => { :event => 'aastra-xml' }, # triggers the XML SIP NOTIFY action URI # Sipura by Linksys by Cisco: :'sipura-check-cfg' => { :event => 'resync' }, :'sipura-reboot' => { :event => 'reboot' }, :'sipura-get-report' => { :event => 'report' }, # Linksys by Cisco: :'linksys-check-cfg' => { :event => 'restart_now' }, # warm restart :'linksys-reboot' => { :event => 'reboot_now' }, # cold reboot # Cisco: # In order for "cisco-check-cfg"/"cisco-reboot" to work make # sure the syncinfo.xml has a different sync number than the # phone's current sync number (e.g. by setting the "sync" # parameter to "0" and having "1" in syncinfo.xml). If that # is the case the phone will reboot (no check-sync without # reboot). # # http://dxr.mozilla.org/mozilla-central/media/webrtc/signaling/src/sipcc/core/sipstack/ccsip_task.c#l2358 # http://dxr.mozilla.org/mozilla-central/media/webrtc/signaling/src/sipcc/core/sipstack/h/ccsip_protocol.h#l196 # http://dxr.mozilla.org/mozilla-central/media/webrtc/signaling/src/sipcc/core/sipstack/h/ccsip_protocol.h#l224 # http://dxr.mozilla.org/mozilla-central/media/webrtc/signaling/src/sipcc/core/sipstack/ccsip_pmh.c#l4978 # https://issues.asterisk.org/jira/secure/attachment/32746/sip-trace-7941-9-1-1SR1.txt # telnet: "debug sip-task" :'cisco-check-cfg' => { :event => 'check-sync' }, :'cisco-reboot' => { :event => 'check-sync' }, # Phone must be in CCM (Cisco Call Manager) registration # mode (TCP) for "service-control" events to work, and the # firmware must be >= 8.0. 7905/7912/7949/7969. # Causes the phone to unregister, request config file # (SIP{mac}.cnf), register. :'cisco-sc-restart-unregistered' => { :event => 'service-control', :content_type => 'text/plain', :content => [ 'action=' + 'restart', 'RegisterCallId=' + '{' + '' + '}', # not registered 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', '', ].join("\r\n"), }, #:'cisco-sc-restart' => { :event => 'service-control', # :content_type => 'text/plain', # :content => [ # 'action=' + 'restart', # # 'RegisterCallId=' + '{' + '${SIPPEER(${PEERNAME},regcallid)}' '}', # 'RegisterCallId=' + '{0022555d-aa850002-a2b54180-bb702fe7@192.168.1.130}', # #00119352-91f60002-1df7530e-4190441e@192.168.1.130 # #00119352-91f60041-4a7455b9-00e0f121@192.168.1.130 # 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', # 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', # 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', # '', # ].join("\r\n"), #}, # Causes the phone to unregister and do a full reboot cycle. :'cisco-sc-reset-unregistered' => { :event => 'service-control', :content_type => 'text/plain', :content => [ 'action=' + 'reset', 'RegisterCallId=' + '{' + '' + '}', # not registered 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', '', ].join("\r\n"), }, #:'cisco-sc-reset' => { :event => 'service-control', # :content_type => 'text/plain', # :content => [ # 'action=' + 'reset', # # 'RegisterCallId=' + '{' + '${SIPPEER(${PEERNAME},regcallid)}' '}', # 'RegisterCallId=' + '{123}', # 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', # 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', # 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', # '', # ].join("\r\n"), #}, # Causes the phone to unregister, request dialplan # (dialplan.xml) and config file (SIP{mac}.cnf), register. # This is the action to send if the config "file" on the # TFTP server changes. :'cisco-sc-check-unregistered' => { :event => 'service-control', :content_type => 'text/plain', :content => [ 'action=' + 'check-version', 'RegisterCallId=' + '{' + '' + '}', # not registered 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', '', ].join("\r\n"), }, #:'cisco-sc-apply-config' => { :event => 'service-control', # :content_type => 'text/plain', # :content => [ # 'action=' + 'apply-config', # 'RegisterCallId=' + '{' + '' + '}', # not registered # 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', # 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', # 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', # 'FeatureControlVersionStamp=' + '{' + '0000000000000000' + '}', # 'CUCMResult=' + '{' + 'config_applied' + '}', # "no_change" / "config_applied" / "reregister_needed" # 'FirmwareLoadId=' + '{' + 'SIP70.8-4-0-28S' + '}', # 'LoadServer=' + '{' + '192.168.1.97' + '}', # 'LogServer=' + '{' + '192.168.1.97' + '}', # <ipv4 address or ipv6 address or fqdn> <port> // This is used for ppid # 'PPID=' + '{' + 'disabled' + '}', # "enabled" / "disabled" // peer-to-peer upgrade # '', # ].join("\r\n"), #}, #:'cisco-sc-call-preservation' => { :event => 'service-control', # :content_type => 'text/plain', # :content => [ # 'action=' + 'call-preservation', # 'RegisterCallId=' + '{' + '' + '}', # not registered # 'ConfigVersionStamp=' + '{' + '0000000000000000' + '}', # 'DialplanVersionStamp=' + '{' + '0000000000000000' + '}', # 'SoftkeyVersionStamp=' + '{' + '0000000000000000' + '}', # '', # ].join("\r\n"), #}, # Grandstream: :'grandstream-check-cfg' => { :event => 'sys-control' }, :'grandstream-reboot' => { :event => 'sys-control' }, :'grandstream-idle-screen-refresh' => { :event => 'x-gs-screen' }, # Gigaset (Pro Nxxx): :'gigaset-check-cfg' => { :event => 'check-sync;reboot=false' }, :'gigaset-reboot' => { :event => 'check-sync;reboot=true' }, # Siemens (Enterprise Networks) OpenStage: :'siemens-check-cfg' => { :event => 'check-sync;reboot=false' }, :'siemens-reboot' => { :event => 'check-sync;reboot=true' }, # Yealink: :'yealink-check-cfg' => { :event => 'check-sync;reboot=true' }, #OPTIMIZE can do without reboot? :'yealink-reboot' => { :event => 'check-sync;reboot=true' }, # Thomson (ST2030?): :'thomson-check-cfg' => { :event => 'check-sync;reboot=false' }, :'thomson-reboot' => { :event => 'check-sync;reboot=true' }, :'thomson-talk' => { :event => 'talk' }, :'thomson-hold' => { :event => 'hold' }, # Misc: # :'mwi-clear-full' => { :event => 'message-summary', :content_type => 'application/simple-message-summary', :content => [ 'Messages-Waiting: ' + 'no', # "yes"/"no" # 'Message-Account: sip:voicemail@127.0.0.1', 'voice-message' + ': 0/0 (0/0)', 'fax-message' + ': 0/0 (0/0)', 'pager-message' + ': 0/0 (0/0)', 'multimedia-message' + ': 0/0 (0/0)', 'text-message' + ': 0/0 (0/0)', 'none' + ': 0/0 (0/0)', '', ],#.join("\r\n"), }, :'mwi-clear-simple' => { :event => 'message-summary', :content_type => 'application/simple-message-summary', :content => [ 'Messages-Waiting: ' + 'no', # "yes"/"no" # 'Message-Account: sip:voicemail@127.0.0.1', 'voice-message' + ': 0/0', '', ],#.join("\r\n"), }, :'mwi-test-full' => { :event => 'message-summary', :content_type => 'application/simple-message-summary', :content => [ 'Messages-Waiting: ' + 'yes', # "yes"/"no" # 'Message-Account: sip:voicemail@127.0.0.1', 'voice-message' + ': 3/4 (1/2)', 'fax-message' + ': 3/4 (1/2)', 'pager-message' + ': 3/4 (1/2)', 'multimedia-message' + ': 3/4 (1/2)', 'text-message' + ': 3/4 (1/2)', 'none' + ': 3/4 (1/2)', '', ],#.join("\r\n"), }, :'mwi-test-simple' => { :event => 'message-summary', :content_type => 'application/simple-message-summary', :content => [ 'Messages-Waiting: ' + 'yes', # "yes"/"no" # 'Message-Account: sip:voicemail@127.0.0.1', 'voice-message' + ': 3/4', '', ],#.join("\r\n"), }, } def initialize( host, opts=nil ) re_initialize!( host, opts ) end def re_initialize!( host, opts=nil ) @opts = { :host => host, :domain => host, :port => 5060, :user => nil, :to_user => nil, :verbosity => 0, :via_rport => true, :event => nil, :content_type => nil, :content => nil, }.merge( opts || {} ) self end def self.event_templates EVENT_TEMPLATES end # DSCP value (Differentiated Services Code Point). # def ip_dscp @ip_dscp ||= 0b110_000 # == 48 == 0x30 == DSCP CS6 ~= IP Precedence 5 end # IP ToS value (Type of Service). # def ip_tos @ip_tos ||= (ip_dscp << 2) end # Create a socket. # def socket if @socket if @socket_is_raw if (! @opts[:spoof_src_addr]) || @opts[:spoof_src_addr].empty? @socket = nil end else if @opts[:spoof_src_addr] @socket = nil end end end if @opts[:spoof_src_addr] unless @raw_socket #local_addr, local_port = * our_addr #if @opts[:spoof_src_addr] != local_addr puts "Spoofing source IP address: #{@opts[:spoof_src_addr].inspect}." if @opts[:verbosity] >= 1 @raw_socket = raw_socket #end end @socket = @raw_socket @socket_is_raw = true return @raw_socket end unless @socket begin ::BasicSocket.do_not_reverse_lookup = true @socket = ::Socket.new( ::Socket::AF_INET, ::Socket::SOCK_DGRAM ) @socket.setsockopt( ::Socket::SOL_SOCKET, ::Socket::SO_REUSEADDR, 1 ) @socket.setsockopt( SOCK_OPT_LEVEL_IP, ::Socket::IP_TOS, ip_tos ) @socket.setsockopt( SOCK_OPT_LEVEL_IP, ::Socket::IP_TTL, 255 ) # default 64 #@socket.settimeout( 1.0 ) rescue ::SystemCallError, ::SocketError, ::IOError => e socket_destroy! raise ::SipNotifyError.new( "Failed to create socket: #{e.message} (#{e.class.name})" ) end begin sock_addr = ::Socket.sockaddr_in( @opts[:port], @opts[:host] ) @socket.connect( sock_addr ) rescue ::SystemCallError, ::SocketError, ::IOError => e socket_destroy! raise ::SipNotifyError.new( "Failed to connect socket to %{addr}: #{e.message} (#{e.class.name})" % { :addr => ip_addr_and_port_url_repr( @opts[:host], @opts[:port] ), }) end end @socket_is_raw = false return @socket end private :socket # Close and unset the socket. # def socket_destroy! @socket.close() if @socket && ! @socket.closed? @socket = nil end # Create a raw socket. # def raw_socket begin ::BasicSocket.do_not_reverse_lookup = true #sock = ::Socket.new( ::Socket::PF_INET, ::Socket::SOCK_RAW, ::Socket::IPPROTO_RAW ) sock = ::Socket.new( ::Socket::PF_INET, ::Socket::SOCK_RAW, ::Socket::IPPROTO_UDP ) # Make sure IP_HDRINCL is set on the raw socket, # otherwise the kernel would prepend outbound packets # with an IP header. # https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man4/ip.4.html # so = sock.getsockopt( SOCK_OPT_LEVEL_IP, ::Socket::IP_HDRINCL ) if so.bool == false || so.int == 0 || so.data == [0].pack('L') #puts "IP_HDRINCL is supposed to be the default for IPPROTO_RAW." # ... not on Darwin though. sock.setsockopt( SOCK_OPT_LEVEL_IP, ::Socket::IP_HDRINCL, true ) end sock.setsockopt( ::Socket::SOL_SOCKET, ::Socket::SO_REUSEADDR, 1 ) rescue ::Errno::EPERM => e $stderr.puts "Must be run as root." raise ::SipNotifyError.new( "Failed to create socket: #{e.message} (#{e.class.name})" ) rescue ::SystemCallError, ::SocketError, ::IOError => e raise ::SipNotifyError.new( "Failed to create socket: #{e.message} (#{e.class.name})" ) end return sock end # The socket type. # # `nil` if no socket. # 1 = Socket::SOCK_STREAM # 2 = Socket::SOCK_DGRAM # 3 = Socket::SOCK_RAW # 4 = Socket::SOCK_RDM # 5 = Socket::SOCK_SEQPACKET # def socket_type @socket ? @socket.local_address.socktype : nil end # The UDP source port number to use for spoofed packets. # def spoof_src_port # Note: # Port 5060 is likely to cause the actual PBX/proxy receive # responses for out NOTIFY requests. # Port 0 is a valid port to use for UDP if responses are to # be irgnored, but is likely to be taken for an invalid port # number in devices. 65535 end private :spoof_src_port # Return out address. # def our_addr if @opts[:spoof_src_addr] @our_addr = [ @opts[:spoof_src_addr], spoof_src_port ] end unless @our_addr our_sock_addr = socket.getsockname() local_port, local_addr = * ::Socket.unpack_sockaddr_in( our_sock_addr ) @our_addr = [ local_addr, local_port ] end @our_addr end private :our_addr # Returns an IP address (or hostname) in URL representation. # I.e. an IPv6 address will be enclosed in "["..."]". # def self.ip_addr_url_repr( host ) host.include?(':') ? "[#{host}]" : host.to_s end # Shortcut as an instance method # def ip_addr_url_repr( host ) self.class.ip_addr_url_repr( host ) end # Returns an IP address (or hostname) and port number in URL # representation. # I.e. an IPv6 address will be enclosed in "["..."]". # def self.ip_addr_and_port_url_repr( host, port ) "%{addr}:%{port}" % { :addr => ip_addr_url_repr( host ), :port => port } end # Shortcut as an instance method # def ip_addr_and_port_url_repr( host, port ) self.class.ip_addr_and_port_url_repr( host, port ) end # Send the SIP NOTIFY message. # def send begin sip_msg = to_s if @opts[:verbosity] >= 3 puts "-----------------------------------------------------------------{" puts sip_msg.gsub( /\r\n/, "\n" ) puts "-----------------------------------------------------------------}" end socket # Touch socket case socket_type when ::Socket::SOCK_DGRAM num_bytes_written = nil 2.times { num_bytes_written = socket.write( sip_msg ) } when ::Socket::SOCK_RAW #local_addr, local_port = * our_addr ::BasicSocket.do_not_reverse_lookup = true src_addr = @opts[:spoof_src_addr] src_addr_info = (::Addrinfo.getaddrinfo( src_addr, 'sip', nil, :DGRAM, ::Socket::IPPROTO_UDP, ::Socket::AI_V4MAPPED || ::Socket::AI_ALL ) || []).select{ |a| a.afamily == ::Socket::AF_INET }.first src_sock_addr = src_addr_info.to_sockaddr src_addr_ipv4_packed = src_sock_addr[4,4] src_port_packed = src_sock_addr[2,2] dst_addr = @opts[:host] dst_addr_info = (::Addrinfo.getaddrinfo( dst_addr, 'sip', nil, :DGRAM, ::Socket::IPPROTO_UDP, ::Socket::AI_V4MAPPED || ::Socket::AI_ALL ) || []).select{ |a| a.afamily == ::Socket::AF_INET }.first dst_sock_addr = dst_addr_info.to_sockaddr dst_addr_ipv4_packed = dst_sock_addr[4,4] dst_port_packed = dst_sock_addr[2,2] #udp_pkt = UdpPktBitStruct.new { |b| # b.src_port = spoof_src_port # b.dst_port = 5060 # b.body = sip_msg.to_s # b.udp_len = b.length # b.udp_sum = 0 #} udp_pkt = UdpPktBinData.new udp_pkt.src_port = spoof_src_port udp_pkt.dst_port = 5060 udp_pkt.data = sip_msg.to_s udp_pkt.len = 4 + udp_pkt.data.bytesize udp_pkt.checksum = 0 # none. UDP checksum is optional. #ip_pkt = IpPktBitStruct.new { |b| # # ip_v and ip_hl are set for us by IpPktBitStruct class # b.ip_tos = ip_tos # b.ip_id = 0 # b.ip_off = 0 # b.ip_ttl = 255 # default: 64 # b.ip_p = ::Socket::IPPROTO_UDP # b.ip_src = @opts[:spoof_src_addr] # b.ip_dst = @opts[:host] # b.body = udp_pkt.to_s # b.ip_len = b.length # b.ip_sum = 0 # Linux/Darwin will calculate this for us (QNX won't) #} ip_pkt = IpPktBinData.new ip_pkt.hdr_len = 5 # 5 * 8 bytes == 20 bytes ip_pkt.tos = ip_tos ip_pkt.ident = 0 # kernel sets appropriate value ip_pkt.flags = 0 frag_off = 0 if RAW_IP_PKT_LITTLE_ENDIAN_FRAG_OFF && frag_off != 0 ip_pkt.frag_os = [ frag_off ].pack('n').unpack('S').first else ip_pkt.frag_os = frag_off end ip_pkt.ttl = 255 # default: 64 ip_pkt.proto = ::Socket::IPPROTO_UDP ip_pkt.src_addr = src_addr_ipv4_packed .unpack('N').first ip_pkt.dst_addr = dst_addr_ipv4_packed .unpack('N').first ip_pkt.data = udp_pkt.to_binary_s #len = (ip_pkt.hdr_len * 8) + ip_pkt.data.bytesize len = ip_pkt.to_binary_s.bytesize if RAW_IP_PKT_LITTLE_ENDIAN_LENGTH ip_pkt.len = [ len ].pack('n').unpack('S').first else ip_pkt.len = len end ip_pkt.checksum = 0 # Linux/Darwin will calculate this for us (QNX won't) #puts "-" * 80, # "UDP packet:", # udp_pkt.inspect, # "-" * 80, # udp_pkt.to_binary_s.inspect, # "-" * 80 #puts "-" * 80, # "IP packet:", # ip_pkt.inspect, # "-" * 80, # ip_pkt.to_binary_s.inspect, # "-" * 80 sock_addr = ::Socket.sockaddr_in( @opts[:port], @opts[:host] ) # Send 2 times. (UDP is an unreliable transport.) num_bytes_written = nil 2.times { num_bytes_written = socket.send( ip_pkt.to_binary_s, 0, sock_addr ) } else raise ::SipNotifyError.new( "Socket type not supported." ) end puts "Sent NOTIFY to #{@opts[:host]}." if @opts[:verbosity] >= 1 return num_bytes_written rescue ::SystemCallError, ::SocketError, ::IOError => e socket_destroy! return false end end # Generate a random token. # def self.random_token( num_bytes=5 ) ::SecureRandom.random_bytes( num_bytes ).unpack('H*').first end # Shortcut as an instance method. # def random_token self.class.random_token end private :random_token # Build the SIP message. # def to_s local_addr, local_port = * our_addr local_ip_addr_and_port_url_repr = ip_addr_and_port_url_repr( local_addr, local_port ) puts "Local address is: #{local_ip_addr_and_port_url_repr}" if @opts[:verbosity] >= 2 now = ::Time.now() transport = 'UDP' # "UDP"/"TCP"/"TLS"/"SCTP" ra = 60466176 # 100000 (36) rb = 2000000000 # x2qxvk (36) via_branch_token = VIA_BRANCH_TOKEN_MAGIC + '_' + random_token() ruri_scheme = 'sip' # "sip"/"sips" if @opts[:user] == nil ruri_userinfo = '' elsif @opts[:user] == '' ruri_userinfo = "#{@opts[:user]}@" # This isn't a valid SIP Request-URI as the user must not be # empty if the userinfo is present ("@"). else ruri_userinfo = "#{@opts[:user]}@" end ruri_hostport = ip_addr_and_port_url_repr( @opts[:host], @opts[:port] ) ruri = "#{ruri_scheme}:#{ruri_userinfo}#{ruri_hostport}" from_display_name = 'Provisioning' from_scheme = 'sip' from_user = '_' from_userinfo = "#{from_user}@" #from_hostport = domain # should be a domain from_hostport = ip_addr_url_repr( local_addr ) from_uri = "#{from_scheme}:#{from_userinfo}#{from_hostport}" from_tag_param_token = random_token() to_scheme = 'sip' #to_hostport = domain to_hostport = ip_addr_url_repr( @opts[:host] ) if @opts[:to_user] != nil to_userinfo = "#{@opts[:to_user]}@" # Even for to_user == '' (which is invalid). else if @opts[:user] == nil to_userinfo = '' elsif @opts[:user] == '' to_userinfo = '@' # This isn't a valid SIP To-URI as the user must not be # empty if the userinfo is present ("@"). else to_userinfo = "#{@opts[:user]}@" end end to_uri = "#{to_scheme}:#{to_userinfo}#{to_hostport}" contact_display_name = from_display_name contact_scheme = 'sip' contact_user = '_' contact_userinfo = "#{contact_user}@" contact_hostport = local_ip_addr_and_port_url_repr contact_uri = "#{contact_scheme}:#{contact_userinfo}#{contact_hostport}" call_id = "#{random_token()}@#{local_ip_addr_and_port_url_repr}" cseq_num = 102 cseq = "#{cseq_num} #{REQUEST_METHOD}" max_forwards = 70 unless @opts[:event] event_package = 'check-sync' event_type = event_package + '' @opts[:event] = "#{event_type};reboot=false" end if @opts[:content] if @opts[:content].kind_of?( ::Array ) body = @opts[:content].map(& :to_s).join("\r\n") else body = @opts[:content].to_s end else body = '' end body.encode!( ::Encoding::UTF_8, { :undef => :replace, :invalid => :replace }) sip_msg = [ '%{request_method} %{ruri} SIP/2.0', 'Via: SIP/2.0/%{transport} %{via_hostport}' + ';branch=%{via_branch_token}' + '%{rport_param}', 'From: %{from_display_name} <%{from_uri}>' + ';tag=%{from_tag_param_token}', 'To: <%{to_uri}>', 'Contact: %{contact_display_name} <%{contact_uri}>', 'Call-ID: %{call_id}', 'CSeq: %{cseq}', 'Date: %{date}', 'Max-Forwards: %{max_forwards}', # 'Allow: %{allow}', 'Subscription-State: %{subscription_state}', 'Event: %{event}', (@opts[:content_type] ? 'Content-Type: %{content_type}' : nil), 'Content-Length: %{content_length}', '', body, ].compact.join("\r\n") % { :request_method => REQUEST_METHOD, :ruri => ruri, :transport => transport, :via_hostport => local_ip_addr_and_port_url_repr, :via_branch_token => via_branch_token, :rport_param => (@opts[:via_rport] ? ';rport' : ''), :from_display_name => from_display_name, :from_uri => from_uri, :from_tag_param_token => from_tag_param_token, :to_uri => to_uri, :contact_display_name => contact_display_name, :contact_uri => contact_uri, :call_id => call_id, :cseq => cseq, :date => now.utc.strftime('%c') +' GMT', # must be "GMT" :max_forwards => max_forwards, # :allow => [ 'ACK' ].join(', '), :subscription_state => 'active', :event => @opts[:event].to_s, :content_type => @opts[:content_type].to_s.gsub(/\s+/, ' '), :content_length => body.bytesize.to_s, } sip_msg.encode!( ::Encoding::UTF_8, { :undef => :replace, :invalid => :replace }) sip_msg end # Send variations of the SIP message. # def self.send_variations( host, opts=nil ) opts ||= {} opts[:domain] ||= host # Create a single SipNotify instance so it will reuse the # socket. notify = ::SipNotify.new( nil ) if opts[:user] && ! opts[:user].empty? # Send NOTIFY with user: puts "Sending NOTIFY with user ..." if opts[:verbosity] >= 1 notify.re_initialize!( host, opts.merge({ })).send end #if true # Send NOTIFY without user: puts "Sending NOTIFY without user ..." if opts[:verbosity] >= 1 notify.re_initialize!( host, opts.merge({ :user => nil, })).send #end #if true # Send invalid NOTIFY with empty user ("") in Request-URI: puts "Sending invalid NOTIFY with empty user ..." if opts[:verbosity] >= 1 notify.re_initialize!( host, opts.merge({ :user => '', })).send #end #if true # Send invalid NOTIFY with empty user ("") in Request-URI # but non-empty user in To-URI: # (for Cisco 7960/7940) puts "Sending invalid NOTIFY with empty user in Request-URI but non-empty user in To-URI ..." if opts[:verbosity] >= 1 notify.re_initialize!( host, opts.merge({ :user => '', :to_user => '_', })).send #end notify.socket_destroy! nil end end # An IP paket. # class IpPktBinData < BinData::Record endian :big bit4 :vers, :value => 4 # IP version bit4 :hdr_len # header length uint8 :tos # TOS / DiffServ uint16 :len # total length uint16 :ident # identifier bit3 :flags # flags bit13 :frag_os # fragment offset uint8 :ttl # time-to-live uint8 :proto # IP protocol uint16 :checksum # checksum uint32 :src_addr # source IP address uint32 :dst_addr # destination IP address string :options, :read_length => :options_length_in_bytes string :data, :read_length => lambda { total_length - header_length_in_bytes } def header_length_in_bytes hdr_len * 4 end def options_length_in_bytes header_length_in_bytes - 20 end end # An UDP packet (payload in an IP packet). # class UdpPktBinData < BinData::Record endian :big uint16 :src_port uint16 :dst_port uint16 :len uint16 :checksum string :data, :read_length => :len end # vim:noexpandtab:
@default_driver = 'phantom.js' @browsers = %w(phantomjs firefox chrome) def use_driver(driver) ENV['DRIVER'] = driver || @default_driver end def run(driver, suite) use_driver driver puts "Running using #{ENV['DRIVER']}" system('cucumber -t @' + suite +' -t ~@ignore') fail 'build failed!' unless $?.exitstatus == 0 end def parallel_run(driver, suite) use_driver driver puts "Running in parallel using #{ENV['DRIVER']}" system('bundle exec parallel_cucumber ./ -o "-t @' + suite + ' -t ~@ignore"') fail 'build failed!' unless $?.exitstatus == 0 end task :phantomjs, [:arg1] do |t, args| run 'phantomjs', args.arg1 end task :firefox, [:arg1] do |t, args| run 'firefox', args.arg1 end task :chrome, [:arg1] do |t, args| run 'chrome', args.arg1 end task :browserstack, [:arg1] do |t, args| run 'browserstack', args.arg1 end task :crossbrowser, [:arg1] do |t, args| @browsers.each { |browser| Rake::Task[browser].invoke args.arg1} end task :parallel_phantomjs, [:arg1] do |t, args| parallel_run 'phantomjs', args.arg1 end task :parallel_firefox, [:arg1] do |t, args| parallel_run 'firefox', args.arg1 end task :parallel_chrome, [:arg1] do |t, args| parallel_run 'chrome', args.arg1 end task :parallel_crossbrowser, [:arg1] do |t, args| @browsers.each { |browser| Rake::Task['parallel_' + browser].invoke args.arg1} end
class Region < ActiveRecord::Base has_many :station_joins has_many :profiles, :through => :station_joins # for named urls def link_name self.name.gsub(/\s/,"_").downcase end # setup script calls this to associate # states with profiles. def create_profile_for(profile_name) prof = Profile.new(:name => profile_name) prof.save yield prof self.profiles << prof end end
# 引数に対する依存を取り除く class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end end Gear.new( :chainring => 52, :cog => 11, :wheel => Wheel.new(26, 1.5).gear_inches # Gearが外部インターフェースの一部分 module SomeFramework class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end end end # 外部のインターフェースをラップし、自身の変更から守る module GearWrapper def self.gear(args) SomeFramework::Gear.new(args[:chainring], args[:cog], args[:wheel]) end end # 引数を持つハッシュを渡すことでGearのインスタンスを作成できるようになった GearWrapper.gear( :chainring => 52, :cog => 11, :wheel => Wheel.new(26, 1.5).gear_inches
class CreateDecision1s < ActiveRecord::Migration def change create_table :decision1s do |t| t.string :d5 t.string :d6 t.references :decision, index: true, foreign_key: true t.timestamps null: false end end end
class Wishlist < ApplicationRecord belongs_to :person, foreign_key: "person_id", class_name: "Person" end
json.videos @videos do |video| json.id video.id json.title video.title json.description video.description json.url video.url end
require 'rails_helper' RSpec.describe "host/rooms/show", type: :view do before(:each) do @host_room = assign(:host_room, Host::Room.create!) end it "renders attributes in <p>" do render end end
class Book < ActiveRecord::Base attr_reader :avatar_remote_url has_many :book_places, dependent: :destroy has_many :places, -> { uniq }, through: :book_places validates :isbn, :isbn_format => true validates_uniqueness_of :isbn validates_presence_of :title has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/book-6x.png" validates_attachment_content_type :avatar, :content_type => [ "application/octet-stream", /\Aimage\/.*\Z/ ] def avatar_remote_url(url_value) self.avatar = URI.parse(url_value) @avatar_remote_url = url_value end def add(place) self.places << place end def toss(place) self.places.destroy(place) end def previous self.class.where('title < ?', title).order(title: :desc).first end def next self.class.where('title > ?', title).order(title: :asc).first end def self.search(query) where("title ~~* ?", "%#{query}%") end def prettify self.title.titleize end def self.to_csv CSV.generate do |csv| csv << column_names all.each do |book| csv << book.attributes.values_at(*column_names) end end end def self.import(file) CSV.foreach(file.path, headers: true) do |row| Book.create! row.to_hash end end end
require 'spec_helper' describe "Order Summary" do context "When I am on the order summary page" do let!(:user) { Fabricate(:user) } before(:each) do login end it "shows the shipping address for the order" do visit new_billing_address_path fill_in "First name", :with => "Jeff" fill_in "Last name", :with => "Casimir" fill_in "Company", :with => "Jumpstart Lab" fill_in "Street", :with => "1445 New York Ave NW" fill_in "Apt/Suite", :with => "First Floor!" fill_in "City", :with => "Washington" fill_in "State", :with => "DC" fill_in "Zipcode", :with => "20005" fill_in "Phone Number", :with => "555-555-5555" click_button("Create Billing address") current_path.should == new_shipping_address_path fill_in "First name", :with => "Jeff" fill_in "Last name", :with => "Casimir" fill_in "Company", :with => "Jumpstart Lab" fill_in "Street", :with => "1445 New York Ave NW" fill_in "Apt/Suite", :with => "First Floor!" fill_in "City", :with => "Washington" fill_in "State", :with => "DC" fill_in "Zipcode", :with => "20005" fill_in "Phone Number", :with => "555-555-5555" click_button("Create Shipping address") current_path.should == new_transaction_path end end end
class Admin::ProductAnswersController < Admin::BaseController permit "superuser" layout 'admin/base' # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html) verify :method => :post, :only => [:update], :redirect_to => { :controller => 'home' } def list params[:page] ||= 1 params[:per_page] ||= 20 @product_answers = ProductAnswer.paginate(:conditions => "product_answers.status = 'proposed'", :order => 'product_id ASC, product_questions.position ASC', :include => [:product, :question], :page => params[:page], :per_page => params[:per_page]) end # this method actually updates a list of ProductAnswers def update to_approve, to_deny = [], [] params[:approve].each do |id, approve| (approve == '1' ? to_approve : to_deny) << id end flash[:notice] = '' unless to_approve.blank? answers = ProductAnswer.find to_approve successes, failures = ProductAnswer.promote answers, true flash[:notice] << "Approved #{successes.size} out of #{answers.size}" flash[:notice] << " with #{failures.size} errors" unless failures.blank? flash[:notice] << ". " end unless to_deny.blank? answers = ProductAnswer.find to_deny denied_cnt, denied_err_cnt = 0, 0 answers.each do |answer| if answer.update_attribute :status, :denied denied_cnt += 1 else denied_err_cnt += 1 end end flash[:notice] << "Denied #{denied_cnt} out of #{answers.size}" flash[:notice] << " with #{denied_err_cnt} errors" unless denied_err_cnt == 0 flash[:notice] << ". " end redirect_to :action => 'list' end end
class CreateFoods < ActiveRecord::Migration[6.1] def change create_table :foods do |t| t.string :name, null: false t.string :group, null: false t.text :nutrition t.integer :calories t.text :category t.string :image t.timestamps end end end
class ContactsController < ApplicationController before_action :authenticate_user! before_action :redirect_cancel, only: [:create, :update] def create params.permit! @contact = Contact.new(params[:contact]) @contact.user_id = current_user.id if @contact.save flash[:notice] = "Contact was successfully created!" redirect_to :action => :index else render :action => :new end end def edit @contact = Contact.find(params[:id]) validate_user end def index @contacts = Contact.all.where(user_id: current_user) end def new @contact = Contact.new end def show @contact = Contact.find(params[:id]) validate_user end def update params.permit! @contact = Contact.find(params[:id]) if params[:contact] if @contact.update_attributes(params[:contact]) flash[:notice] = "Contact was successfully updated!" redirect_to :action => :show, :id => @contact and return else render :action => :edit and return end end end private def redirect_cancel redirect_to(action: :show, id: params[:id]) if params[:commit] == "Cancel" && params[:id] redirect_to(action: :index) end def validate_user if @contact.user_id != current_user.id flash[:error] = "There is no contact with that Id" redirect_to action: :index and return end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Orders::Create, type: :action do describe 'Inputs' do subject { described_class.inputs } it { is_expected.to include(attributes: { type: Hash }) } end describe 'Outputs' do subject { described_class.outputs } it { is_expected.to include(order: { type: Order }) } end describe '#call' do subject(:result) { described_class.result(attributes: attributes) } let(:user) { create(:user) } context 'when attributes are valid' do let(:attributes) do { imei: 448_674_528_976_410, annual_price: 1000, device_model: 'Iphone', installments: 4, user_id: user.id } end let(:user_params) { { user: user.attributes } } it { is_expected.to be_success } it 'creates order' do expect { result }.to change(Order.all, :count).by(1) end it 'creates order with given attribute' do expect(result.order.attributes).to include( 'imei' => attributes[:imei], 'annual_price' => attributes[:annual_price], 'device_model' => attributes[:device_model], 'installments' => attributes[:installments], 'user_id' => attributes[:user_id] ) end end context 'when attributes are valid' do let(:attributes) do { imei: 448_674_528_976_410, annual_price: 1000, device_model: 'Iphone', installments: 4, user: { name: 'Name', cpf: '329.726.820-41', email: 'tes@tes.com' } } end it { is_expected.to be_success } it 'creates order' do expect { result }.to change(Order.all, :count).by(1) end it 'creates order with given attribute' do expect(result.order.attributes).to include( 'imei' => attributes[:imei], 'annual_price' => attributes[:annual_price], 'device_model' => attributes[:device_model], 'installments' => attributes[:installments] ) end end context 'when attributes are invalid' do let(:attributes) { { imei: 123_123_123_123 } } it { expect { result }.to raise_error(ActiveRecord::RecordInvalid) } end context 'when tier doesn`t exist' do let(:attributes) { {} } it { expect { result }.to raise_error(ActiveRecord::RecordInvalid) } end end end
require 'github_api' module GithubApi @github = Github.new oauth_token: ENV['GITHUB_TOKEN'] def self.list_releases(owner, repo) @github.repos.releases.list owner, repo end def self.create_release(owner, repo, tag) @github.repos.releases.create owner, repo, tag, tag_name: tag, target_commitish: 'master', name: tag, body: 'Features and fixes.', draft: false, prerelease: false end end
class RenameClassesToLectures < ActiveRecord::Migration def change rename_table :classes, :lectures add_column :lectures, :meeting_id, :integer end end
=begin Description : Table of contents. write a program that will display a table of contents so that it looks like this: Table of Contents Chapter 1: Getting Started page 1 Chapter 2: Numbers page 9 Chapter 3: Letters page 13 page 9 page 13 Hint Use center ,ljust and rJust. =end title = 'Table of contents'.center(60) chap_1 = "Chapter 1: Getting started".ljust(30)+'page 1'.rjust(20); chap_2 = "Chapter 2: Numbers".ljust(30)+'page 9'.rjust(20); chap_3 = "Chapter 3: Letters".ljust(30)+'page 13'.rjust(21); puts(title,"") puts(chap_1) puts(chap_2) puts(chap_3)
require 'test/unit' class TC_ExceptionTest < Test::Unit::TestCase def setup @message = AccountError::NO_ACCOUNT_MESSAGE @info = AccountError::CONFIGURE_ACCOUNT_INFO App.stubs(:configure_account) end def test_message err = AccountError.new(@message) assert_equal(@message, err.message) err.informative_text = @info assert_equal(@info, err.informative_text) end def test_whats_next App.expects(:configure_account).with(App) err = AccountError.new(@message) err.whats_next end def set_account_error_expectation alert = stub() App.stubs(:alert).returns(alert) alert.expects(:messageText=).with(@message) alert.expects(:informativeText=).with(@info) alert.expects(:addButtonWithTitle).with("OK") alert.expects(:runModal) App.expects(:configure_account) end def test_show_alert set_account_error_expectation err = AccountError.new(@message) err.informative_text = @info err.show_alert end # Should be OK to call show_alert on any Excetion def test_show_alert2 err = RuntimeError.new assert_nothing_raised do err.show_alert end end class Sample def initialize(foo) @foo = foo end def hello_world(sender) raise sender if sender.is_a?(Exception) sender + @foo end error_handler :hello_world end def test_hello s = Sample.new(" world!") # check wrapped method's functionality assert_equal("hello world!", s.hello_world("hello")) # check error handling behavior set_account_error_expectation err = AccountError.new(@message) err.informative_text = @info assert_nothing_raised { s.hello_world(err) } end end
# 5 stars is a common ranking use case. They are not given at specified # actions like badges, you should define a cron job to test if ranks are to be # granted. # # +set_rank+ accepts: # * :+level+ ranking level (greater is better) # * :+to+ model or scope to check if new rankings apply # * :+level_name+ attribute name (default is empty and results in 'level' # attribute, if set it's appended like 'level_#{level_name}') module Merit class RankRules include Merit::RankRulesMethods def initialize # i stars for i chars name (1..5).each do |i| set_rank level: i, to: User do |user| user.name.length == i end end end end end
# coding: utf-8 require 'test_helper' class TasksControllerTest < ActionController::TestCase fixtures :tasks setup do session[:user_id] = users(:one).id end test "should get new" do get :new assert_response :success end test 'should get edit' do get :edit, id: users(:one) assert_response :success end test 'should post create' do post :create, task: { name: 'shopping', deadline: 2.days.since, priority: 1 } assert_response :redirect assert !assigns[:task].new_record? end test 'should delete destroy' do assert_difference('Task.count', -1) do delete :destroy, id: tasks(:one) end end test 'should get index' do get :index assert_response :success assert_template :index assert_select 'h1', 'Tasks#index' assert_select 'table' do |elements| assert_select elements.first, 'th', 4 assert_select 'tr', 3 end end end
class AddSatAndSunToSchedule < ActiveRecord::Migration def change add_column :schedules, :satStart, :time add_column :schedules, :satEnd, :time add_column :schedules, :satOpen, :boolean add_column :schedules, :sunStart, :time add_column :schedules, :sunEnd, :time add_column :schedules, :sunOpen, :boolean end end
class RemoveProductAndBankCodes < ActiveRecord::Migration[5.0] def change remove_column :card_products, :code, :string, null: false remove_column :banks, :personal_code, :string, null: false end end
class CreateCfsFileInfos < ActiveRecord::Migration def change create_table :cfs_file_infos do |t| t.string :path t.text :fits_xml t.timestamps end add_index :cfs_file_infos, :path, :unique => true end end
require 'wordnik' require 'open-uri' require 'twitter' Wordnik.configure do |config| config.api_key = ENV['wordnik_api_key'] end class BotMeByYourBot VERB_LIST_URL = 'https://gist.githubusercontent.com/farisj/f2ebb73fabfa20dfc40e7fa9de72ddd8/raw'.freeze def tweet phrase = verb + " me by your " + noun + " and i'll " + verb + " you by mine" client.update(phrase) end def verb @verb ||= verb_list.sample end def verb_list @verb_list ||= open(VERB_LIST_URL).read.split("\n") end def noun return @noun if @noun potential_nouns = response.map{ |items| items['word']} noun = potential_nouns.find do |noun| noun == noun.downcase end @noun = noun || 'name' end def response Wordnik.words.get_random_words(params) end def params { has_dictionary_def: true, min_corpus_count: 4000, include_part_of_speech: 'noun', exclude_part_of_speech: 'proper-noun,proper-noun-plural,proper-noun-posessive,noun-plural' } end def client @client ||= Twitter::REST::Client.new do |config| config.consumer_key = ENV["consumer_key"] config.consumer_secret = ENV["consumer_secret"] config.access_token = ENV["access_token"] config.access_token_secret = ENV["access_token_secret"] end end end BotMeByYourBot.new.tweet
# == Schema Information # # Table name: companies # # id :integer not null, primary key # company_name :string(255) # signup_code :string(255) # owner_id :integer # created_at :datetime not null # updated_at :datetime not null # class Company < ActiveRecord::Base attr_accessible :company_name, :signup_code, :owner_id has_many :users has_many :joblistings end
class User < ApplicationRecord devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable has_many :bookmarks belongs_to :user end
require 'json' require 'pp' module Ruboty module Jenkins module Actions class Build < Base def call build report end private def build curl = Curl::Easy.new(ENV["JENKINS_URL"]) curl.http_auth_types = :basic curl.username = ENV["JENKINS_USER_ID"] curl.password = ENV["JENKINS_API_TOKEN"] curl.http_post(curl.url, "repository=#{given_repository}", "branch=#{given_branch}", "platform=#{given_platform}", "env=#{given_env}", "editor_version=#{given_editor_version}", "requested_user=#{sender_name}" ) end def post_options { repository: given_repository, branch: given_branch, platform: given_platform, env: given_env, editor_version: given_editor_version } end def report message.reply("Now building... #{given_repository}/#{given_branch}") end def given_repository message[:repo] end def given_branch message[:branch] || "master" end def given_platform message[:platform] || "" end def given_env message[:env] || "" end def given_editor_version message[:editor_version] || "" end end end end end
require 'rake/testtask' require 'rake/clean' require 'spec/rake/spectask' CLOBBER.include('dist') task :default => [:spec, :dist] desc 'Package the FlexUtils scripts as a single file' task :dist => 'dist/flexutils.rb' file 'dist/flexutils.rb' => ['lib/flexutils/FlexUtils.rb'] + FileList['lib/flexutils/*.rb'].exclude('lib/flexutils/FlexUtils.rb') do |t| mkdir_p 'dist' File.open(t.name, 'w') do |destination_file| destination_file.puts("module FlexUtils") t.prerequisites.each do |script| code = File.read(script) offset = code.index('module FlexUtils') + 16 length = code.rindex('end') - offset code = code.slice(offset, length) destination_file.puts(code) end destination_file.puts("end") end end desc "Run the specifications" Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/*_spec.rb'] t.libs = [File.dirname(__FILE__) + '/lib'] t.spec_opts = ['--require', 'lib/flexutils', '--format', 'specdoc', '--color'] t.fail_on_error = true t.failure_message = 'Tests failed' end
require 'rails_helper' RSpec.describe Integrations::AwardWallet::User::Refresh do include AwardWalletMacros include SampleDataMacros let(:op) { described_class } let(:account) { create_account(:onboarded) } let(:owner) { account.owner } let(:json) { sample_json('award_wallet_user') } before { stub_award_wallet_api(sample_json('award_wallet_user')) } let(:user) { get_award_wallet_user_from_callback(account) } example 'initial load' do result = op.(user: user) expect(result.success?).to be true user = result['model'] # see the specs for the Update op for the full test of user attrs being set expect(user.loaded).to be true expect(user.syncing).to be false expect(user.full_name).to eq 'John Smith' owners = user.award_wallet_owners expect(owners.length).to eq 2 expect(owners.map(&:name)).to match_array ['John Smith', 'Fred Bloggs'] john = owners.detect { |o| o.name == 'John Smith' } fred = owners.detect { |o| o.name == 'Fred Bloggs' } # owner.person is owner by default: expect(john.person).to eq owner expect(fred.person).to eq owner expect(john.award_wallet_accounts.length).to eq 3 expect(fred.award_wallet_accounts.length).to eq 1 expect(john.award_wallet_accounts.map(&:display_name)).to eq( [ 'British Airways (Executive Club)', 'Amex (Membership Rewards)', 'American Airlines (AAdvantage)', ], ) expect(fred.award_wallet_accounts[0].display_name).to eq( 'American Airlines (AAdvantage)', ) end example 'user no longer found on AwardWallet' example 'we have accounts and owners not present in API data' do result = op.(user: user) user = result['model'].reload owner = user.award_wallet_owners.first owner.update!(name: 'Deleteme') acc = user.award_wallet_owners.last.award_wallet_accounts.first acc.update!(aw_id: 987654321) result = op.(user: user) expect(result.success?).to be true user = result['model'] expect(user.award_wallet_owners.count).to eq 2 expect(user.award_wallet_accounts.count).to eq 4 expect(AwardWalletOwner.find_by_id(owner.id)).to be nil expect(AwardWalletAccount.find_by_id(acc.id)).to be nil end example 'user is syncing' do aw_user = run!(op, user: user)['model'].reload aw_user.update!(syncing: true) result = op.(user: user) expect(result.success?).to be true expect(aw_user.reload.syncing).to be false end example 'when an existing owner is not assigned to a person' do owners = op.(user: user)['model'].award_wallet_owners john = owners.detect { |o| o.name == 'John Smith' } fred = owners.detect { |o| o.name == 'Fred Bloggs' } run!( Integrations::AwardWallet::Owner::UpdatePerson, { id: john.id, person_id: nil }, 'current_account' => account, ) # refresh again: op.(user: user) john.reload fred.reload expect(john.person).to be nil expect(fred.person).to eq owner end example '::Job' do expect(op).to receive(:call).with(user: user) described_class::Job.perform_now('id' => user.id) end end
class LocationGraderService GRADES = %w(A+ A A- B+ B B- C+ C C- D+ D D- F).freeze WEIGHTS = [2.5, 1.75, 1.25, 1, 0.8, 0.65].freeze def initialize(location) @scores = location_item_comments location end def grade divisor = find_divisor apply_divisor divisor, sum_averages end def to_alphabetic return '' if grade.round < 1 || grade.round > 13 GRADES[grade.round-1] end private def sum_averages @scores.reduce(0) do |accumulator, (age, values)| average = sum_by_age(values) / values.count weighted_average = apply_weight(age, average) accumulator += weighted_average end end def sum_by_age(values) values.reduce(0) do |accumulator, value| accumulator += value end end def months_back(date) date2 = Time.now (date2.year * 12 + date2.month) - (date.year * 12 + date.month) end def location_item_comments(location) @_location_item_comments ||= location.grades .map { |comment| { months_back(comment.updated_at) => comment.rating } } # make hash of month to rating .group_by{ |e| e.keys.first } # group hash keys by first key .map{|key, array| [key, array.map{|hash| hash.values.first}] }.to_h end def find_divisor divisor = @scores.keys.reduce(0) do |accumulator, age| accumulator += find_weight age end divisor.zero? ? 1 : divisor end def find_weight age if age <= 5 WEIGHTS[age] else WEIGHTS[5] end end def apply_divisor(divisor, value) value / divisor end def apply_weight(age, value) value * find_weight(age) end end
require 'rails_helper' RSpec.describe "Plants", type: :request do let(:plant1) { create(:plant, light: 6) } let(:plant2) { create(:plant) } describe 'GET /plants' do it 'returns all plants' do [plant1, plant2] get '/plants' expect(response).to have_http_status(200) expect(json['data'][0]['type']).to eq('plant') expect(json['data'].map{|d| d['id'].to_i}).to eq([plant1.id, plant2.id]) end end describe 'GET /plants/:id' do it 'returns proper attributes' do get "/plants/#{plant1.id}" expect(response).to have_http_status(200) expect(json['data']['type']).to eq('plant') expect(attr['light']).to eq(6) expect(attr.keys).to match_array(%w{ common-name scientific-name light}) end end end
require 'brewery_db/webhooks/base' require 'app/models/location' module BreweryDB module Webhooks class Location < Base def process self.send(@action) end private def edit(attributes = nil) location = ::Location.find_or_initialize_by(brewerydb_id: @brewerydb_id) attributes ||= @client.get("/location/#{@brewerydb_id}").body['data'] location.assign_attributes({ name: attributes['name'], category: attributes['locationTypeDisplay'], primary: attributes['isPrimary'] == 'Y', in_planning: attributes['inPlanning'] == 'Y', public: attributes['openToPublic'] == 'Y', closed: attributes['isClosed'] == 'Y', street: attributes['streetAddress'], street2: attributes['extendedAddress'], city: attributes['locality'], region: attributes['region'], postal_code: attributes['postalCode'], country: attributes['countryIsoCode'], latitude: attributes['latitude'], longitude: attributes['longitude'], phone: attributes['phone'], website: attributes['website'], hours: attributes['hoursOfOperation'], created_at: attributes['createDate'], updated_at: attributes['updateDate'] }) if brewery = ::Brewery.find_by(brewerydb_id: attributes['breweryId']) location.brewery = brewery location.save! return location else raise OrderingError, 'Got a location before we had its brewery!' end end alias :insert :edit def delete ::Location.find_by(brewerydb_id: @brewerydb_id).destroy! end end end end
require 'rails_helper' feature 'Create badge' do background do create(:video, name: 'Rails1') end scenario 'new badge with a min_views condition' do visit new_badge_url within 'form' do fill_in 'badge_name', with: 'Expert' fill_in 'badge_fa_symbol', with: 'user' fill_in 'badge_min_views', with: 3 click_button 'Create Badge' end expect(page).to have_content('Badge was successfully created.') badge = Badge.last expect(badge.name).to eq('Expert') expect(badge.fa_symbol).to eq('user') expect(badge.min_views).to eq(3) end scenario 'new badge with a min_views condition' do visit new_badge_url within 'form' do fill_in 'badge_name', with: 'Expert' fill_in 'badge_fa_symbol', with: 'user' select('Rails1', from: 'badge_video_id') click_button 'Create Badge' end expect(page).to have_content('Badge was successfully created.') badge = Badge.last expect(badge.name).to eq('Expert') expect(badge.fa_symbol).to eq('user') expect(badge.video_id).to_not be_nil end scenario 'new badge with 2 conditions' do visit new_badge_url within 'form' do fill_in 'badge_name', with: 'Expert' fill_in 'badge_fa_symbol', with: 'user' select('Rails1', from: 'badge_video_id') fill_in 'badge_min_views', with: 3 click_button 'Create Badge' end expect(page).to have_content('Please add ONE condition for this Badge') expect(Badge.count).to eq(0) end scenario 'new badge with without condition' do visit new_badge_url within 'form' do fill_in 'badge_name', with: 'Expert' fill_in 'badge_fa_symbol', with: 'user' click_button 'Create Badge' end expect(page).to have_content('Please add ONE condition for this Badge') expect(Badge.count).to eq(0) end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ereignishorizont/client' Gem::Specification.new do |spec| spec.name = "ereignishorizont-client" spec.version = Ereignishorizont::Client::VERSION spec.authors = ["Susanne Dewein", "Tam Eastley", "Carsten Zimmermann"] spec.email = ["susanne.dewein@gmail.com", "tam.eastley@gmail.com", "cz@aegisnet.de"] spec.description = %q{Ruby client library to connect to ereignishorizont app} spec.summary = %q{Ruby client library to connect to ereignishorizont app} spec.homepage = "https://github.com/Absolventa/ereignishorizont-client" spec.license = "MIT" spec.required_ruby_version = '>= 2.1' spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", ">= 1.3" spec.add_development_dependency "rspec", "~> 2.14" spec.add_development_dependency "rake" spec.add_development_dependency "webmock" end
require 'spec_helper' describe DataTypesController do login_user let(:data_type) { create(:data_type) } let(:valid_template) { build(:data_type) } let(:invalid_template) { build(:data_type, name: nil) } describe "GET index" do it "assigns all data_types as @data_types" do data_types = create_list(:data_type, 5) get :index data_types.each {|o| expect(assigns(:data_types)).to include(o)} end end describe "GET show" do it "assigns the requested data_type as @data_type" do get :show, {:id => data_type.to_param} expect(assigns(:data_type)).to eq(data_type) end end describe "GET new" do it "assigns a new data_type as @data_type" do get :new expect(assigns(:data_type)).to be_a_new(DataType) end end describe "GET edit" do it "assigns the requested data_type as @data_type" do get :edit, {:id => data_type.to_param} expect(assigns(:data_type)).to eq(data_type) end end describe "POST create" do describe "with valid params" do it "creates a new data_type, assigns it as @data_type, and redirects to show page" do expect { post :create, {:data_type => valid_template.attributes} }.to change(DataType, :count).by(1) expect(assigns(:data_type)).to be_a(DataType) expect(assigns(:data_type)).to be_persisted expect(response).to redirect_to(DataType.last) end end describe "with invalid params" do it "assigns a newly created but unsaved data_type as @data_type and re-renders the 'new' template" do post :create, {:data_type => invalid_template.attributes} expect(assigns(:data_type)).to be_a_new(DataType) expect(response).to render_template("new") end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted #DataType.any_instance.stub(:save).and_return(false) post :create, {:data_type => invalid_template.attributes} expect(response).to render_template("new") end end end describe "PUT update" do describe "with valid params" do it "updates the requested data_type, assigns it as @data_type, and redirects to show page" do put :update, {:id => data_type.to_param, :data_type => valid_template.attributes} expect(assigns(:data_type)).to eq(data_type) expect(response).to redirect_to(data_type) end end describe "with invalid params" do it "assigns the data_type as @data_type and re-renders the 'edit' template" do put :update, {:id => data_type.to_param, :data_type => invalid_template.attributes} expect(assigns(:data_type)).to eq(data_type) expect(response).to render_template("edit") end end end describe "DELETE destroy" do it "destroys the requested data_type" do expect(data_type).to be_persisted expect { delete :destroy, {:id => data_type.to_param} }.to change{DataType.current.count}.by(-1) end it "redirects to the data_types list" do delete :destroy, {:id => data_type.to_param} expect(response).to redirect_to(data_types_url) end end end
require "mengpaneel/delayer" module Mengpaneel class Replayer attr_reader :manager def initialize(manager) @manager = manager end def run return unless manager.controller delayed_calls = Delayer.new(manager.controller).load! Manager::MODES.each do |mode| next unless delayed_calls.has_key?(mode) calls = delayed_calls[mode] || [] manager.send(mode) do replay_calls(calls) end end end private def replay_calls(calls) proxy = manager.call_proxy calls.each do |method_names, args| method_name = method_names.pop object = method_names.inject(proxy) { |object, method_name| object.public_send(method_name) } object.public_send(method_name, *args) end end end end
class IncidentfollowupsController < ApplicationController before_action :set_incidentfollowup, only: [:show, :edit, :update, :destroy] # GET /incidentfollowups # GET /incidentfollowups.json def index @incidentfollowups = Incidentfollowup.all # @incident = Incident.incidentcategory.all end # GET /incidentfollowups/1 # GET /incidentfollowups/1.json def show end # GET /incidentfollowups/new def new @incidentfollowup = Incidentfollowup.new # @incident = Incident.incidentcategory.new end # GET /incidentfollowups/1/edit def edit end # POST /incidentfollowups # POST /incidentfollowups.json def create @incidentfollowup = Incidentfollowup.new(incidentfollowup_params) incident = @incidentfollowup.incident incident.status = @incidentfollowup.status incident.save respond_to do |format| if @incidentfollowup.save format.html { redirect_to @incidentfollowup.incident, notice: 'Incidentfollowup was successfully created.' } format.json { render :show, status: :created, location: @incidentfollowup } else format.html { render :new } format.json { render json: @incidentfollowup.errors, status: :unprocessable_entity } end end end # PATCH/PUT /incidentfollowups/1 # PATCH/PUT /incidentfollowups/1.json def update respond_to do |format| if @incidentfollowup.update(incidentfollowup_params) format.html { redirect_to @incidentfollowup, notice: 'Incidentfollowup was successfully updated.' } format.json { render :show, status: :ok, location: @incidentfollowup } else format.html { render :edit } format.json { render json: @incidentfollowup.errors, status: :unprocessable_entity } end end end # DELETE /incidentfollowups/1 # DELETE /incidentfollowups/1.json def destroy @incidentfollowup.destroy respond_to do |format| format.html { redirect_to incidentfollowups_url, notice: 'Incidentfollowup was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_incidentfollowup @incidentfollowup = Incidentfollowup.find(params[:id]) end # Only allow a list of trusted parameters through. def incidentfollowup_params params.require(:incidentfollowup).permit(:incident_id, :status, :comment, :date) end end
require 'capybara/rspec' require 'selenium-webdriver' RSpec.configure do |config| config.include Capybara::DSL end Capybara.configure do |config| config.run_server = false config.default_driver = :selenium config.app_host = 'https://twitter.com/' end Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end describe "Twitter home" do before do visit '/' end subject { page } describe "visit root page" do it { should have_title('Twitterへようこそ') } end end
# frozen_string_literal: true puts '**** Running seeds...' user = User.find_or_create_by!(email: 'admin@email.com') do |user| user.name = 'admin' user.password = 'password' user.password_confirmation = 'password' user.admin = true user.save end # Post Types SeedsHelper.count_records_for(PostType) do names = [ 'TIL', 'Merit', 'Praise', 'Gratitude' ] names.each do |name| user.post_types.find_or_create_by!(name: name) end end # Categories SeedsHelper.count_records_for(Category) do names = [ 'Citizenship', 'Leadership', 'Skills & Competencies' ] names.each do |name| user.categories.find_or_create_by!(name: name) end end # Posts SeedsHelper.count_records_for(Post) do posts = [] 10.times do publish_date = Faker::Date.between(from: 30.days.ago, to: Date.current) post = { post_type_id: user.post_types.sample.id, bookmarked: [true, false, false].sample, date: publish_date, url: ['', '', '', Faker::Internet.url].sample, given_by: ['', Faker::Name.first_name].sample, description: [Faker::Lorem.paragraph(sentence_count: 10), Faker::Markdown.block_code].sample, created_at: publish_date, updated_at: publish_date } posts << post end Post.insert_all(posts) end sample_size = Post.count * 0.7 Post.all.sample(sample_size).each do |post| category = Category.all.sample post.categories << category end
class TemplateOptions < ActiveRecord::Migration def self.up add_column :mail_templates, :processor, :string add_column :mail_templates, :charset, :string add_column :mail_templates, :content_type, :string add_column :mail_templates, :reply_to, :string add_column :mail_templates, :mime_version, :string end def self.down remove_column :mail_templates, :processor remove_column :mail_templates, :charset remove_column :mail_templates, :content_type remove_column :mail_templates, :reply_to remove_column :mail_templates, :mime_version end end
# # Basic Dialog allows JQuery UI Widgets to interact # with the basic dialogs that JQueryUI pops up. # # NOTE: JQueryUI Widgets are very customizable, # so we've kept the functionality for the dialogs # class as rudimentary as possible, to allow the # end user to build up any functionality they # require, and customize the class to suit their # particular needs. # class JQueryUIWidgets::BasicDialog < PageObject::Elements::Div # # Generates three methods # # The {NAME}title method grabs the span element of the title # bar in the UI dialog and returns the text. # # {NAME}_content method will return the entire text of # the JQuery UI dialog box. # # close_{NAME} method will, of course, click the button # labeled close. # def self.accessor_methods(accessor, name) accessor.send :define_method, "#{name}_title" do dialog = self.send "#{name}_element" dialog.div_element(:class => 'ui-dialog-titlebar').span_element.text end accessor.send :define_method, "#{name}_content" do dialog = self.send "#{name}_element" dialog.div_element(:class => 'ui-dialog-content').text end accessor.send :define_method, "close_#{name}" do dialog = self.send "#{name}_element" dialog.button_element(:class => 'ui-dialog-titlebar-close').click end end end
require 'rails_helper' RSpec.describe ListsController, type: :controller do let(:list) { create(:list)} describe 'GET #show' do sign_in_user before { get :show, id: list } it 'assigns new remark to @list' do expect(assigns(:remark)).to be_a_new(Remark) end it 'assigns new confirm to @list' do expect(assigns(:confirm)).to be_a_new(Confirm) end end describe 'POST #create' do sign_in_user it 'assigns to create new @confirm' do expect{ post :confirm, id: list, user_id: @user, format: :js }.to change(Confirm, :count).by(1) end end end
class TestDescription < ActiveRecord::Base has_many :test_runs def summary @summary ||= description.split("\n").first end end
Rails.application.routes.draw do namespace :api do namespace :v1 do resources :logs resources :actions resources :evaluations resources :measurements resources :species resources :plants resources :groups patch "/users/edit", to: "users#update" resources :users post "/login", to: "auth#login" get "/auto_login", to: "auth#auto_login" end end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class Comment < ApplicationRecord belongs_to :post belongs_to :user has_many :replies, class_name: "Comment",foreign_key: "scid" end
# frozen_string_literal: true Barong::App.define do |config| config.set(:required_docs_expire, true) end
class MensajesController < ApplicationController def index @mensajes = Mensaje.all end def update @mensaje = Mensaje.find([:id]) end def new @mensaje = Mensaje.new end def create @mensaje = Mensaje.new(mensaje_params) @mensaje.save redirect_to @mensaje end def show @mensaje = Mensaje.find(params[:id]) end private def mensaje_params params.require(:mensaje).permit(:mensaje) end end
class AddRtidToEvent < ActiveRecord::Migration def change add_column :events, :rt_id, :integer end end
require "semantic_navigation/version" require 'semantic_navigation/core' require 'semantic_navigation/renderers' require "semantic_navigation/configuration" require 'semantic_navigation/railtie' if defined?(Rails) module SemanticNavigation def self.deprecation_message(type, deprecated_object, new_object, action = nil) if SemanticNavigation::Configuration.display_deprecation_messages message = ["DEPRECATION WARNING:", "You are using deprecated #{type} `#{deprecated_object}`"] if action message[-1] += " for #{action}." else message[-1] += '.' end message += ["That #{type} will be depreacted soon.", "Please use `#{new_object}` instead."] puts message.join("\n") end end def self.actual_config_location locations = ["#{Rails.root}/config/initializers/semantic_navigation.rb", "#{Rails.root}/config/semantic_navigation.rb"] actual_location = locations.find{|l| File.exists?(l)} raise ["Please create a semantic_navigation configuration", "(rails g semantic_navigation:install)", "file before starting the project!"].join(" ") unless actual_location puts "DEPRECATION WARNING: Please move the configuration file from #{locations.second} to #{locations.first}! Current configuration file path will be deprecated soon!" if locations.find_index(actual_location) == 1 actual_location end end
Spree::Admin::BaseHelper.class_eval do def delivery_data(order) info = "" adr = order.bill_address info += "#{adr.first_name}, " unless adr.first_name.blank? info += "#{adr.address1}, " unless adr.address1.blank? info += "#{adr.phone}, " unless adr.phone.blank? info += "#{adr.comment} ," unless adr.comment.blank? info += "#{adr.payment_type.name}, " if adr.payment_type info += "#{adr.delivery_type.name}" if adr.delivery_type end def display_price(price) ActionController::Base.helpers.number_with_delimiter(price.to_i, delimiter: " ") end end
class CodeController < ApplicationController # GET / def index @code = 'Code controller' respond_to do |format| format.html # index.html.erb end end # GET /1 def show @code = 'Code controller with show' respond_to do |format| format.html # home#index end end end
module ItemsHelper def full_image_url(image) if Rails.env.development? "#{request.protocol}#{request.host.present? ? request.host + ':' : '' }#{request.port}#{image.image.url}" || '' else image.image.url end end end
MESSAGES = { auth_error: 'Please log in.', access_error: 'You do not have access to the requested resource.', not_found: 'The resource you are looking for does not exist.' }
require 'rails_helper' RSpec.describe PlayersController, type: :controller do describe "GET index" do subject { get :index } let(:players) { FactoryGirl.create_list :player, 3 } specify { expect(subject.status).to eq 200 } it { is_expected.to render_template :index } it "assigns all players as @players" do subject expect(assigns(:players)).to eq players.sort_by(&:name) end end describe "GET show" do subject { get :show, params: { id: player.to_param } } let(:player) { FactoryGirl.create :player } let(:stats) { instance_double Stats::Personal } before do expect(Stats::Personal). to receive(:new). with(player). and_return(stats) end specify { expect(subject.status).to eq 200 } it { is_expected.to render_template :show } it "assigns the player as @player" do subject expect(assigns(:player)).to eq player end it "assigns the personal stats as @stats" do subject expect(assigns(:stats)).to eq stats end end end
# == Schema Information # # Table name: question_categories # # id :integer not null, primary key # name :string(255) # created_at :datetime # updated_at :datetime # exam_id :integer # require 'rails_helper' RSpec.describe QuestionCategory, :type => :model do describe 'validation' do it { is_expected.to validate_presence_of :name } it { is_expected.to validate_presence_of :exam } it { is_expected.to validate_uniqueness_of(:name).scoped_to([:exam_id]) } end end
module UsersHelper include Avatar::View::ActionViewSupport USERS_DEFAULT_AVATAR = "#{SITE_URL}images/no-avatar.gif" USERS_DEFAULT_AVATAR_SMALL = "#{SITE_URL}images/no-avatar-small.gif" def avatar_for(user, args = {}) opts = { :size => 100, :default => USERS_DEFAULT_AVATAR }.update(args) avatar_tag(user, {:size => opts[:size], :gravatar_default_url => opts[:default]}) end end
class User #criado uma classe que possui um metodo chamado add e outro chamado hello def add(name) #adicionado o parametro 'name' ao metodo add @name = name puts "User adicionado" hello end def hello puts "Seja bem vindo, #{@name}!" end end user = User.new user.add('Joao')
class Language < ActiveRecord::Base belongs_to :user has_many :dictionaries, foreign_key: "language_id", dependent: :destroy #validation validates :name, presence: true, length: {maximum: 25} end
class ContactPolicy < ApplicationPolicy attr_reader :user, :contact class Scope < Scope def resolve scope.all end end def initialize(user, contact) @user = user @contact = contact end def new? true end def create? true end def edit? true end def update? true end def destroy? @user.admin? end def settings? user.admin? end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe 'Auto Encryption' do require_libmongocrypt min_server_fcv '4.2' require_enterprise include_context 'define shared FLE helpers' include_context 'with local kms_providers' context 'with an invalid mongocryptd spawn path' do let(:client) do new_local_client( SpecConfig.instance.addresses, SpecConfig.instance.test_options.merge( auto_encryption_options: { kms_providers: kms_providers, key_vault_namespace: key_vault_namespace, schema_map: { 'auto_encryption.users' => schema_map }, extra_options: { mongocryptd_spawn_path: 'echo hello world', mongocryptd_spawn_args: [] } }, database: 'auto_encryption' ), ) end let(:server_selector) { double("ServerSelector") } let(:cluster) { double("Cluster") } before do key_vault_collection.drop key_vault_collection.insert_one(data_key) allow(server_selector).to receive(:name) allow(server_selector).to receive(:server_selection_timeout) allow(server_selector).to receive(:local_threshold) allow(cluster).to receive(:summary) # Raise a server selection error on intent-to-encrypt commands to mock # what would happen if mongocryptd hadn't already been spawned. It is # necessary to mock this behavior because it is likely that another test # will have already spawned mongocryptd, causing this test to fail. allow_any_instance_of(Mongo::Database) .to receive(:command) .with( hash_including( 'insert' => 'users', 'ordered' => true, 'lsid' => kind_of(Hash), 'documents' => kind_of(Array), 'jsonSchema' => kind_of(Hash), 'isRemoteSchema' => false, ), { execution_options: { deserialize_as_bson: true } }, ) .and_raise(Mongo::Error::NoServerAvailable.new(server_selector, cluster)) end it 'raises an exception when trying to perform auto encryption' do expect do client['users'].insert_one(ssn: ssn) end.to raise_error( Mongo::Error::MongocryptdSpawnError, /Failed to spawn mongocryptd at the path "echo hello world" with arguments/ ) end end end
class AttendancesController < ApplicationController def new @event = Event.find_by_slug(params[:id]) @user = User.find_by(params[:user_id]) @attendance = Attendance.new end def create if current_user @attendance = Attendance.new(attendance_params) @user = User.find_by(params[:user_id]) @event = Event.find_by_slug(params[:id]) if @attendance.save @event.attendances << @attendance @current_user.attendances << @attendance @event.save @current_user.save flash[:notice] = "Thank you for joining " + @event.title redirect_to @event elsif @attendance.destroy flash[:error] = "There was a problem, try again" redirect_to @event else flash[:error] = "You must be logged in to join events" redirect_to new_attendance_path end end end def edit attendance_id = params[:id] @attendance = Attendance.find_by_id(attendance_id) render :edit end def update get_id.update_attributes(attendance_params) redirect_to user_path(user) end def destroy get_id.destroy redirect_to user_path end private def attendance_params params.require(:attendance).permit(:user_id, :event_id, :contribution) end def set_user @user = @attendance.user_id end end
class StudentAnswersController < ApplicationController # GET /student_answers # GET /student_answers.json def index @student_answers = StudentAnswer.all respond_to do |format| format.html # index.html.erb format.json { render :json => @student_answers } end end # GET /student_answers/1 # GET /student_answers/1.json def show @student_answer = StudentAnswer.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render :json => @student_answer } end end # GET /student_answers/new # GET /student_answers/new.json def new @student_answer = StudentAnswer.new respond_to do |format| format.html # new.html.erb format.json { render :json => @student_answer } end end # GET /student_answers/1/edit def edit @student_answer = StudentAnswer.find(params[:id]) end # POST /student_answers # POST /student_answers.json def create @student_answer = StudentAnswer.where(:studentID => session[:account].netid, :questionID => params[:student_answer][:questionID]).first if @student_answer @student_answer.number = params[:student_answer][:number] else @student_answer = StudentAnswer.new(params[:student_answer]) end respond_to do |format| if @student_answer.save @student_answer.studentID = session[:account].netid @student_answer.save format.js { render :js => "$('#answer_feedback_#{@student_answer.questionID}').html('<img height=50px width=50px src=\"http://www-03.ibm.com/software/lotus/symphony/gallery.nsf/GalleryClipArtAll/9137EB48252D3ABA8525759600316C70/$File/Sign-CheckBox01.png\" />').fadeIn().fadeOut(5000)"} format.html { redirect_to @student_answer, :notice => 'Student answer was successfully created.' } format.json { render :json => @student_answer, :status => :created, :location => @student_answer } else format.html { render :action => "new" } format.json { render :json => @student_answer.errors, :status => :unprocessable_entity } end end end # PUT /student_answers/1 # PUT /student_answers/1.json def update @student_answer = StudentAnswer.find(params[:id]) respond_to do |format| if @student_answer.update_attributes(params[:student_answer]) format.html { redirect_to @student_answer, :notice => 'Student answer was successfully updated.' } format.json { head :no_content } else format.html { render :action => "edit" } format.json { render :json => @student_answer.errors, :status => :unprocessable_entity } end end end # DELETE /student_answers/1 # DELETE /student_answers/1.json # Test def destroy @student_answer = StudentAnswer.find(params[:id]) @student_answer.destroy respond_to do |format| format.js { render :js => "redirect('"+student_answers_path+"', '"+"Answer Was Successfully Deleted"+"');"} format.html { redirect_to student_answers_url } format.json { head :no_content } end end end
require 'pg' require 'set' # IMPORTANT NOTE: change the file path on lines 23 and 324 or the code will not run. $capitalized_words_and_phrases = {} # this will hold all words and phrases that are capitalized even once $descriptions_to_correct = [] # this will hold objects corresponding to entries that need correction (with id + description) $all_correct_descriptions = "" # this will hold a string containing all unaffected descriptions $dictionary = File.open("./words.txt").read.split("\n").to_set # this is a set of 350,000 English words File.open('./corrected_descriptions.txt', 'w') {|file| file.truncate(0) } # clears our corrected_descriptions.txt file File.open('./updated_csv_file.csv', 'w') {|file| file.truncate(0) } # clears our new .csv file # ------------------------------------------------------------------ # the following code converts the data in the csv file to a postgresql database def create_db puts "\nCreating database...\n" conn = PG.connect(dbname: 'postgres') conn.exec("CREATE DATABASE healthifycodingchallenge") conn = PG.connect(dbname: 'healthifycodingchallenge') conn.exec("CREATE TABLE orgs ( id INT, description VARCHAR, PRIMARY KEY (id) )") conn.exec("COPY orgs(id, description) FROM '/Users/appacademy/Desktop/healthify-coding-challenge/jr_data_engineer_assignment.csv' DELIMITER ',' CSV HEADER") end # ------------------------------------------------------------------ # this code drops the database (it's easier than doing it manually every time I rerun the code) def drop_db conn = PG.connect(dbname: 'postgres') conn.exec("DROP DATABASE IF EXISTS healthifycodingchallenge") end # ------------------------------------------------------------------ def check_rows puts "\nProcessing entries...\n\n" # queries the database for all rows conn = PG.connect(dbname: 'healthifycodingchallenge') result = conn.exec("SELECT * FROM orgs") current_percent = 0 total_keys = 20000 # iterates over every row result.each_with_index do |row,idx| # prints current progress if idx > (current_percent * total_keys / 100) puts "#{current_percent}% checked..." current_percent += 1 end # each row is first sent through the process_description method # if it's affected, it is added to the $descriptions_to_correct array # if it's unaffected, the capitalized words/phrases in it are added to $capitalized_words_and_phrases # and the entire description is added to $all_correct_descriptions process_description(row["id"], row["description"]) end puts "\nEntries processed!\n" # once all entries have either been set aside for correction or added to the master description string # all words / phrases that are capitalized even once get checked against the master description string # to see how they are most frequently capitalized (ex: "nyc" => "NYC", "orange county" => "Orange County") check_frequencies # then, each affected description is corrected $descriptions_to_correct.each do |organization| fix_description(organization[:id], organization[:description]) end end # ------------------------------------------------------------------ def process_description(id, description) # separates description based on punctuation sentences = split_into_sentences(description) # needs_correcting is initially set to true. # it will be switched to false if even one lowercase word is encountered needs_correcting = true # this will hold all words and subphrases that are capitalized cap_words_and_phrases = [] sentences.each do |sentence| sentence = sentence.split(" ") phrase = "" sentence.each_with_index do |word,idx| # we are trying to identify any words or phrases that are capitalized. # capitalized words are added to the phrase string until a lowercase word is identified # at which point the phrase is added to the cap_words_and_phrases array and reset to an empty string if word == word.downcase && word.to_i == 0 && idx == 1 # it's important to check word.to_i == 0 because, for example, "8" == "8.downcase" # so, for a while, affected descriptions (ex: "Food Pantry Available For 75210 Only.") were marked as unaffected # also, we are checking for idx == 1 because the first word in a sentence is always capitalized. # if the second word (at idx 1) is also capitalized, I assume that it and the first word are part of a phrase # otherwise, I reset the phrase string needs_correcting = false phrase = "" elsif word == word.downcase && word.to_i == 0 needs_correcting = false if phrase.length > 0 # slice is used to trim the final space from the phrase cap_words_and_phrases << phrase.slice(0...-1) phrase = "" end else phrase += word += " " end end # adds current phrase to the master array if it's not an empty string phrase.length > 0 ? cap_words_and_phrases << phrase.slice(0...-1) : nil end if needs_correcting # if no lowercase words were encountered, the id and description are addeded to $descriptions_to_correct $descriptions_to_correct << {id: id, description: description} else # otherwise, the description is added to $all_correct_descriptions # it's important to only add UNAFFECTED descriptions to this because it will be used to analyze correct capitalization sentences.each do |sentence| sentence = sentence.split(" ") # for a while, the program was assuming that words like "provides", "offers" and "serves" should be capitalized # because they're disproportionately likely to be the first word in the description (and therefore capitalized) # I addressed that by making the first letter in a sentence lowercase (unless the second word is also capitalized) if sentence[1] && (sentence[1] == sentence[1].downcase) sentence[0][0] = sentence[0][0].downcase end $all_correct_descriptions += sentence.join(" ") + " " end # and finally, all capitalized words/phrases are added to the masterlist for processing cap_words_and_phrases.each { |word| $capitalized_words_and_phrases[word.downcase] = word } end end # ------------------------------------------------------------------ # description is separated by punctuation ("!"/"."/","/"?") # separated strings are returned in an array # the point of this is to identify the limits of capitalized phrases # because a phrase will not continue past a punctuation mark # (ex: "University Of California, Orange County" == 2 separate phrases) def split_into_sentences(description) description = description.split(". ") description.map! { |sentence| sentence.split("! ") }.flatten! description.map! { |sentence| sentence.split("? ") }.flatten! description.map! { |sentence| sentence.split(", ") }.flatten! # this removes the final punctuation mark (if it exists) /\?|\.|\!/.match(description[-1][-1]) ? description[-1] = description[-1].slice(0...-1) : nil description end # ------------------------------------------------------------------ # this method checks all words + phrases that are capitalized even once against the master description string # to see what the most frequent capitalization is def check_frequencies puts "\nChecking for capitalization frequencies...\n\n" current_percent = 0 total_keys = $capitalized_words_and_phrases.keys.length # I create a new, empty hash so as to not edit the original hash while iterating over it new_cap_words_and_phrases = {} $capitalized_words_and_phrases.keys.each_with_index do |phrase,idx| # This method is the performance bottleneck. It takes about eight minutes. # Printing progress updates shows that the program hasn't just frozen. if idx > (current_percent * total_keys / 100) puts "#{current_percent}% checked..." current_percent += 1 end phrase = phrase.split(" ") if phrase.length == 1 # if a phrase is only one word long, I search the correct descriptions for the phrase with a space on either side # because words like "NY" or "GED" will return a lot of false positives otherwise (ex: company, many, challenged, managed) phrase = phrase[0] downcase = $all_correct_descriptions.scan(/(?=#{" " + phrase.downcase + " "})/).count capitalized = $all_correct_descriptions.scan(/(?=#{" " + phrase.capitalize + " "})/).count uppercase = $all_correct_descriptions.scan(/(?=#{" " + phrase.upcase + " "})/).count phrase = phrase.split(" ") else # the point of this is essentially to search all the unaffected descriptions (~19,000) for the number of # lowercase, uppercase, and titlecase instances of each phrase. (ex: "nyc", "NYC", and "Nyc") downcase = $all_correct_descriptions.scan(/(?=#{phrase.map(&:downcase).join(" ")})/).count capitalized = $all_correct_descriptions.scan(/(?=#{phrase.map(&:capitalize).join(" ")})/).count uppercase = $all_correct_descriptions.scan(/(?=#{phrase.map(&:upcase).join(" ")})/).count end # then, each word or phrase is added to the hash. the key is the lowercase word/phrase # and the value is its most common form (either lower, upper or titlecase) if (capitalized >= downcase) && (capitalized >= uppercase) new_cap_words_and_phrases[phrase.join(" ")] = phrase.map(&:capitalize).join(" ") elsif (uppercase >= downcase) && (uppercase >= capitalized) new_cap_words_and_phrases[phrase.join(" ")] = phrase.map(&:upcase).join(" ") else new_cap_words_and_phrases[phrase.join(" ")] = phrase.map(&:downcase).join(" ") end end puts "\nFrequency checking complete!\n" # then, the global variable is reset to the new hash $capitalized_words_and_phrases = new_cap_words_and_phrases end # ------------------------------------------------------------------ # in this method, affected descriptions are corrected def fix_description(id, description) new_description = description # returns unpunctuated sentence and a hash of punctuation # the point of trimming punctuation is that sometimes a phrase will appear at the end of a sentence # (ex: "I attend New York University.") and it won't be properly identified with punctuation attached desc_and_punc = trim_punctuation(new_description) # iterates through all substrings of the sentence checking if they occur in $capitalized_words_and_phrases sentences = sentence_subsets(desc_and_punc[:description]) # sends back corrected sentence and punctuation hash to restore punctuation new_description = restore_punctuation(sentences, desc_and_punc[:punctuation]) next_word_caps = true # the first word in the description should always be capitalized new_description = new_description.split(" ") # finally, we ensure that the first word of each sentence in the new description is capitalized. new_description.each_with_index do |word,idx| if next_word_caps word[0] = word[0].upcase # word gets capitalized if it's at beginning of a new sentence next_word_caps = false # this variable resets end /\?|\.|\!/.match(word[-1]) ? next_word_caps = true : nil # if a word ends in "?", ".", or "!", we know it's at the end of a sentence, and the next word should be capitalized new_description[idx] = word # finally, we replace the word in the description with the corrected word end # the corrected description is appended to our text file of all corrected descriptions File.open('./corrected_descriptions.txt', 'a') do |file| file.puts("ID: #{id}\nORIGINAL DESCRIPTION: #{description}\nCORRECT DESCRIPTION: #{new_description.join(" ")}\n\n") end # sends the updated description to be updated in the database insert_correct_description(id, new_description.join(" ")) end # ------------------------------------------------------------------ # this method trims punctuation from a string and sends back an unpunctuated string and a punctuation hash # the punctuation hash's keys are the indexes of the words in the string # and the values are any punctuation at the end of those words # ex: trim_punctuation("I like oranges, apples, and cake!") returns # { description: ("I like oranges apples and cake"), # punctuation: {0: "", 1: "", 2: ",", 3: ",", 4: "", 5: "!"} } def trim_punctuation(description) description = description.split(" ") punctuation = {} description.each_with_index do |word,idx| /\?|\.|\!|\,/.match(word[-1]) ? letter = word.slice!(-1) : letter = "" punctuation[idx] = letter end { description: description.join(" "), punctuation: punctuation } end # ------------------------------------------------------------------ # this reverses the above function by iterating over each word and adding the corresponding # string from the punctuation hash. (if it's unpunctuated, it just adds an empty string) def restore_punctuation(description, punctuation) description = description.split(" ") description.each_with_index do |word,idx| description[idx] = word + punctuation[idx] end description.join(" ") end # ------------------------------------------------------------------ # this splits each sentence EVERY POSSIBLE SUBSET and checks to see # if the subset occurs in $capitalized_words_and_phrases # ex: "i love nyc" breaks down into six subsets: # "i" / "i love" / "i love nyc" / "love" / "love nyc" / "nyc" def sentence_subsets(description) # every word in the description is downcased because keys in $capitalized_words_and_phrases are all lowercase description = description.split(" ").map(&:downcase) idx1 = 0 while idx1 < description.length idx2 = idx1 while idx2 < description.length subset = description[idx1..idx2].join(" ").downcase # checks the dictionary for the current subset correct_subset = $capitalized_words_and_phrases[subset] # if subset exists, updates the description with the correct subset if correct_subset correct_subset.split(" ").each_with_index do |word,idx| description[idx1 + idx] = word end # if subset does NOT exist in $capitalized_words_and_phrases, AND it's only one word long # the dictionary (a txt file of 350k english words) is checked for the word. # if it isn't in the dictionary, it's capitalized. # this is a good way of capitalizing, for example, place names that only occur once (ex: "Lemoore", "Sendero") elsif idx1 == idx2 description[idx1] = subset.capitalize unless $dictionary.include?(subset) end idx2 += 1 end idx1 += 1 end description.join(" ") end # ------------------------------------------------------------------ # updates the database with the corrected description def insert_correct_description(id, description) $conn.exec("UPDATE orgs SET description = '#{description}' WHERE id = #{id}") end # ------------------------------------------------------------------ # and finally, export the corrected table to a new .csv file def export_db_to_csv $conn.exec("COPY (SELECT * FROM orgs) TO '/Users/appacademy/Desktop/healthify-coding-challenge/updated_csv_file.csv' DELIMITER ',' CSV HEADER") puts "\nProcessing complete! Exported to updated_csv_file.csv." end # ------------------------------------------------------------------ drop_db create_db $conn = PG.connect(dbname: 'healthifycodingchallenge') # set this to a global so we don't have to reconnect 1,000+ times check_rows export_db_to_csv
require 'spec_helper' require 'jshint' describe Jshint do describe ".class methods" do it "should return the root path of the gem" do expect(described_class.root).to eq(File.expand_path('../..', __FILE__)) end end end
require 'csv' require_relative 'merchant_repository' require_relative 'merchant' require_relative 'item_repository' require_relative 'item' require_relative 'invoice_repository' require_relative 'invoice' require_relative 'transaction' require_relative 'transaction_repository' require_relative 'invoice_item_repository' require_relative 'invoice_item' require_relative 'customer' require_relative 'customer_repository' require_relative 'sales_analyst' class SalesEngine def self.from_csv(file_hash) items = [] CSV.foreach(file_hash[:items], headers: true, header_converters: :symbol) do |row| items << Item.new(row) end merchants = [] CSV.foreach(file_hash[:merchants], headers: true, header_converters: :symbol) do |row| merchants << Merchant.new(row) end invoices = [] CSV.foreach(file_hash[:invoices], headers: true, header_converters: :symbol) do |row| invoices << Invoice.new(row) end transactions = [] CSV.foreach(file_hash[:transactions], headers: true, header_converters: :symbol) do |row| transactions << Transaction.new(row) end invoice_items = [] CSV.foreach(file_hash[:invoice_items], headers: true, header_converters: :symbol) do |row| invoice_items << InvoiceItem.new(row) end customers = [] CSV.foreach(file_hash[:customers], headers: true, header_converters: :symbol) do |row| customers << Customer.new(row) end SalesEngine.new(items, merchants, invoices, transactions, invoice_items, customers) end attr_reader :items, :merchants, :invoices, :transactions, :invoice_items, :customers def initialize(items, merchants, invoices, transactions, invoice_items, customers) @items = ItemRepository.new(items) @merchants = MerchantRepository.new(merchants) @invoices = InvoiceRepository.new(invoices) @transactions = TransactionRepository.new(transactions) @invoice_items = InvoiceItemRepository.new(invoice_items) @customers = CustomerRepository.new(customers) end def analyst SalesAnalyst.new(@items, @merchants, @invoices, @transactions, @invoice_items, @customers) end end
module BlueprintAgreement class MethodNotFound < StandardError; end class EndpointNotFound < StandardError attr :request, :response def initialize(request) @request = request @response = request end def message %{ Response: uri: #{response.uri} code: #{response.code} body: #{response.msg} } end end end
module ApplicationHelper def modal_dialog content_tag :div, "", id: "modal-new-element", class: "modal fade", style: "display: none;", tabindex: "-1" end def flash_key key if key == "notice" "info" elsif key == "alert" "danger" else key end end def home_path if current_user.try(:instructor_profile).try(:persisted?) profile_path current_user.instructor_profile.profile_path else root_path end end def current_year Time.current.strftime "%Y" end def contact_address ContactService.instance.contact_address end def sorted_records records, key records.sort do |a, b| a.send(key) <=> b.send(key) end end end
class Post < ApplicationRecord acts_as_votable belongs_to :user has_many :comments has_attached_file :image, styles: { medium: "600x400#", small: "250x150>" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ end