text
stringlengths
10
2.61M
module Sentry class RequestInterface < Interface REQUEST_ID_HEADERS = %w(action_dispatch.request_id HTTP_X_REQUEST_ID).freeze IP_HEADERS = [ "REMOTE_ADDR", "HTTP_CLIENT_IP", "HTTP_X_REAL_IP", "HTTP_X_FORWARDED_FOR" ].freeze attr_accessor :url, :method, :data, :query_string, :cookies, :headers, :env def initialize self.headers = {} self.env = {} self.cookies = nil end private # See Sentry server default limits at # https://github.com/getsentry/sentry/blob/master/src/sentry/conf/server.py def read_data_from(request) if request.form_data? request.POST elsif request.body # JSON requests, etc data = request.body.read(4096 * 4) # Sentry server limit request.body.rewind data end rescue IOError => e e.message end def format_headers_for_sentry(env_hash) env_hash.each_with_object({}) do |(key, value), memo| begin key = key.to_s # rack env can contain symbols value = value.to_s next memo['X-Request-Id'] ||= Utils::RequestId.read_from(env_hash) if Utils::RequestId::REQUEST_ID_HEADERS.include?(key) next unless key.upcase == key # Non-upper case stuff isn't either # Rack adds in an incorrect HTTP_VERSION key, which causes downstream # to think this is a Version header. Instead, this is mapped to # env['SERVER_PROTOCOL']. But we don't want to ignore a valid header # if the request has legitimately sent a Version header themselves. # See: https://github.com/rack/rack/blob/028438f/lib/rack/handler/cgi.rb#L29 next if key == 'HTTP_VERSION' && value == env_hash['SERVER_PROTOCOL'] next if key == 'HTTP_COOKIE' # Cookies don't go here, they go somewhere else next unless key.start_with?('HTTP_') || %w(CONTENT_TYPE CONTENT_LENGTH).include?(key) # Rack stores headers as HTTP_WHAT_EVER, we need What-Ever key = key.sub(/^HTTP_/, "") key = key.split('_').map(&:capitalize).join('-') memo[key] = value rescue StandardError => e # Rails adds objects to the Rack env that can sometimes raise exceptions # when `to_s` is called. # See: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L134 Sentry.logger.warn(LOGGER_PROGNAME) { "Error raised while formatting headers: #{e.message}" } next end end end def format_env_for_sentry(env_hash) return env_hash if Sentry.configuration.rack_env_whitelist.empty? env_hash.select do |k, _v| Sentry.configuration.rack_env_whitelist.include? k.to_s end end end end
require File.dirname(__FILE__) + '/setup' require 'javaclass/string_hexdump' class TestStringHexdump < Test::Unit::TestCase def test_hexdump_empty assert_equal("00000000h: #{' '*16}; \n", ''.hexdump) end def test_hexdump_line assert_equal("00000000h: 61 #{' '*15}; a\n", 'a'.hexdump) end def test_hexdump_non_printable assert_equal("00000000h: 01 02 03 04 05 06 07 08 09 0A #{' '*6}; ..........\n", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a".hexdump) assert_equal("00000000h: FF FE FC #{' '*13}; ...\n", "\xff\xfe\xfc".hexdump) end def test_hexdump_more_lines assert_equal("00000000h: 00 00 ; ..\n00000002h: 00 00 ; ..\n", "\x00\x00\x00\x00".hexdump(2)); end def test_hexdump_whitespace assert_equal("00000000h: 20 00 65 00 #{' '*12}; .e.\n", " \x00e\x00".hexdump); end end
require 'mruby/bindings' # CTypes.define('Example') do # self.needs_unboxing = true # self.needs_boxing_cleanup = false # self.needs_unboxing_cleanup = false # self.needs_type_check = true # # self.recv_template = 'mrb_value %{value};' # self.format_specifier = 'o' # self.get_args_template = '&%{value}' # self.type_check_template = nil # self.invocation_arg_template = '%{value}' # self.field_swap_template = %{old} = %{new}; # # self.unboxing_fn.invocation_template = '%{as} = TODO_mruby_unbox_Example(%{unbox});' # self.unboxing_fn.cleanup_template = 'free(%{value});' # # self.boxing_fn.invocation_template = '%{as} = TODO_mruby_box_Example(%{box});' # self.boxing_fn.cleanup_template = 'free(%{value});' # end module MRuby::Bindings module CTypes class BoxingFn attr_accessor( # - Unused. Should remove :name, # - Required :invocation_template, # - Optional (default is no unboxing cleanup) :cleanup_template) def dup duplicate = CTypes::BoxingFn.new duplicate.invocation_template = self.invocation_template duplicate.cleanup_template = self.cleanup_template duplicate end end end module CTypes class Definition attr_accessor( # A key suitable for hashing to this CType :key, # - Optional (default = 'mrb_value %{value};') # - Template Args: value :recv_template, # - Optional (default = 'o') :format_specifier, # - Optional (default = '&%{value}') # - Template Args: value :get_args_template, # - Optional (default = "%{value}") :invocation_arg_template, # - Required :type_name, # - Semi-Optional (default is a TODO message) # - Template Args: box & as :boxing_fn, # - Semi-Optional (default is a TODO message) # - Template Args: unbox & as :unboxing_fn, # - Optional (default is no type check) # - Template Args: value :type_check_template, # - Optional (default is '%{old} = %{new};') # - Template Args: old, new :field_swap_template) def initialize(type_name, &block) # This is initially the same as self.type_name, # but type_name may be overridden in the provided # block (and commonly is, atm). Save this as # the "key" for this CType. self.key = type_name self.type_name = type_name self.recv_template = "mrb_value %{value};" self.get_args_template = "&%{value}" self.invocation_arg_template = "%{value}" self.format_specifier = "o" self.field_swap_template = "%{old} = %{new};" self.boxing_fn = BoxingFn.new boxing_fn.invocation_template = "mrb_value %{as} = TODO_mruby_box_#{MRuby::Bindings::Names.type_name_to_id(type_name).split(' ').join('_')}(%{box});" self.unboxing_fn = BoxingFn.new unboxing_fn.invocation_template = "#{type_name} %{as} = TODO_mruby_unbox_#{MRuby::Bindings::Names.type_name_to_id(type_name).split(' ').join('_')}(%{unbox});" self.instance_eval(&block) if block_given? end def aliased_as(t_name) duplicate = self.dup duplicate.key = t_name duplicate.type_name = t_name duplicate end def dup dup = Definition.new(type_name) self.instance_variables.each do |var| dup.instance_variable_set(var, self.instance_variable_get(var)) end dup.boxing_fn = boxing_fn.dup if boxing_fn dup.unboxing_fn = unboxing_fn.dup if unboxing_fn dup end def out_only=(val) @out_only = !!val end def needs_unboxing=(val) @needs_unboxing = !!val end def needs_boxing_cleanup=(val) @needs_boxing_cleanup = !!val end def needs_unboxing_cleanup=(val) @needs_unboxing_cleanup = !!val end def ignore=(val) @ignore = !!val end def unknown=(val) @unknown = !!val end # Template Interface # ------------------ def recv(arg) return '' unless recv_template recv_template % {value: recv_name(arg)} end def get_args_argv(arg) return '' unless get_args_template get_args_template % {value: recv_name(arg)} end def invocation_argv(arg) return '' unless invocation_arg_template invocation_arg_template % {value: native_name(arg)} end def type_check(arg) return '' unless type_check_template type_check_template % {value: recv_name(arg)} end def unbox(arg) return '' unless unboxing_fn.invocation_template unboxing_fn.invocation_template % {unbox: ruby_name(arg), as: native_name(arg)} end def box(arg) return '' unless boxing_fn.invocation_template boxing_fn.invocation_template % {box: native_name(arg), as: ruby_name(arg)} end def box_return(native, ruby) return '' unless boxing_fn.invocation_template boxing_fn.invocation_template % {box: native, as: ruby} end alias box_lit box_return def cleanup_return(name) return '' unless boxing_fn.cleanup_template boxing_fn.cleanup_template % {value: name} end def cleanup_out_param(arg) cleanup_return(native_name(arg)) end def cleanup_unboxing(arg) return '' unless unboxing_fn.cleanup_template unboxing_fn.cleanup_template % {value: native_name(arg)} end def swap_fields(old, new) return '' unless field_swap_template field_swap_template % {old: old, new: new} end def ignore? @ignore end def unknown? @unknown end def needs_unboxing? if @needs_unboxing.nil? !@out_only && self.format_specifier == 'o' else @needs_unboxing end end def needs_type_check? if @needs_type_check.nil? self.needs_unboxing? else @needs_type_check end end def needs_boxing_cleanup? if @needs_boxing_cleanup.nil? !!self.boxing_fn.cleanup_template else @needs_boxing_cleanup end end def needs_unboxing_cleanup? if @needs_unboxing_cleanup.nil? !!self.unboxing_fn.cleanup_template else @needs_unboxing_cleanup end end # Queries # ------- def recv_name(param_name) self.needs_unboxing? ? ruby_name(param_name) : native_name(param_name) end def native_name(param_name) "unboxed_#{param_name}" end def ruby_name(param_name) "boxed_#{param_name}" end def needs_type_check=(val) @needs_type_check = !!val end def out_only? @out_only end def inspect # Simple format for diagnostic output (keeps it cleaner) "#<CType[#{type_name}]>" end end end end
class AttachmentsController < ApplicationController before_action :authenticate_user! skip_before_filter :verify_authenticity_token, only: [:create] def index if params[:for_course] @course = Course.find_by course_code: params[:for_course] @attachments = @course.attachments.approved.page(params[:apage]).per(6) elsif params[:q] @attachments = Attachment.search(params[:q]).approved.page(params[:apage]).per(6) else @attachments = Attachment.all.approved.page(params[:apage]).per(6) end @type = "favourite" end def show attachment @report = @attachment.reports.build @attachments = Attachment.where(description: @attachment.description).page(params[:apage]).per(6) @attachments = @attachments.where.not(id: @attachment.id) respond_to do |format| format.js format.html end end def new @attachment = Attachment.new @attachments = Attachment.all respond_to do |format| format.html # new.html.erb format.json { render json: @attachment } end end def create find_attachable params[:uploads].each do |u| @attachment = Attachment.new(attachment_create_params) @attachment.user = current_user; @attachment.upload = u if @attachment.save flash[:success] = "Attachment(s) submitted for approval" else flash[:error] = "Unable to submit attachment(s)" end end redirect_to course_path(course_code: @attachable.course_code) end def destroy attachment find_attachable if params[:attachment] if user_permitted? if @attachment.destroy if !@attachable.nil? && @attachment.attachable_type == "Guide" flash[:success] = "Attachment successfully removed from guide" redirect_to edit_guide_path(id: params[:guide_id]) elsif !@attachable.nil? && @attachment.attachable_type == "Course" flash[:success] = "Attachment successfully removed from course" redirect_to @attachable elsif current_user.admin? redirect_to admin_feed_path, notice: "Attachment removed." end else flash[:error] = "Could not remove attachment" redirect_to root_path end else redirect_to root_path, notice: "You are not permitted to perform this action" end end def download attachment @attachment.download_count += 1 @attachment.save send_file @attachment.upload.path, filename: @attachment.upload_file_name, disposition: 'attachment' end private def attachment @attachment = Attachment.find(params[:id]) end def attachment_create_params params.require(:attachment).permit(:id, :course_id, :description, :attachable_type, :attachable_id) end def user_permitted? @attachment.user == current_user || current_user.admin? end def find_attachable if params[:attachment][:attachable_type] == "Course" return @attachable = Course.find(params[:attachment][:attachable_id]) elsif params[:attachment][:attachable_type] == "Guide" return @attachable = Guide.find(params[:attachment][:attachable_id]) end end end
# You have a bank of switches before you, numbered from 1 to n. Each switch is # connected to exactly one light that is initially off. You walk down the row # of switches and toggle every one of them. You go back to the beginning, and # on this second pass, you toggle switches 2, 4, 6, and so on. On the third # pass, you go back again to the beginning and toggle switches 3, 6, 9, and # so on. You repeat this process and keep going until you have been through n # repetitions. # Write a method that takes one argument, the total number of switches, and # returns an Array that identifies which lights are on after n repetitions. # Example with n = 5 lights: # round 1: every light is turned on # round 2: lights 2 and 4 are now off; 1, 3, 5 are on # round 3: lights 2, 3, and 4 are now off; 1 and 5 are on # round 4: lights 2 and 3 are now off; 1, 4, and 5 are on # round 5: lights 2, 3, and 5 are now off; 1 and 4 are on # The result is that 2 lights are left on, lights 1 and 4. The return value is # [1, 4]. # With 10 lights, 3 lights are left on: lights 1, 4, and 9. The return value is # [1, 4, 9]. # LOGICAL SYNTAX # START # Pass number to method # Convert 1..number to array # SET index = 1 # def switch_lights(num_of_lights) lights = {} 1.upto(num_of_lights) { |n| lights[n] = 'off' } num_of_lights.times do |i| lights.each do |light, state| if light % (i + 1) == 0 lights[light] = (state == 'on') ? 'off' : 'on' end end end lights.select { |light, state| state == 'on'}.keys end p switch_lights(5) p switch_lights(10)
class Crypto def initialize(text) @text = text @size = nil end def normalize_plaintext @text = @text.scan(/\w/).join.downcase end def size normalize_plaintext Math.sqrt(@text.size).ceil end def plaintext_segments normalize_plaintext @text.scan(/.{1,#{size}}/) end def ciphertext encode.join end def normalize_ciphertext encode.map(&:join).join(' ') end def encode cipher_text = [] arr_of_segments = plaintext_segments.map {|word| word.chars } until arr_of_segments.flatten.empty? cipher_text << arr_of_segments.map {|x| x.delete_at(0) } end cipher_text end end # crypto = Crypto.new('Vampires are people too!') # # p crypto.plaintext_segments # p crypto.ciphertext # p crypto.normalize_ciphertext
# Username Creator # [cool, coolbeans, cool, coolerbeans, coolbeans, cool, cool] # [cool, coolbeans, cool1, coolerbeans, coolbeans1, cool2, cool3] # want to add consecutive digits after the word if the name has occured already def username_creator(array) username_hash = {} results = [] array.each do |username| if username_hash[username] username += 1 else username_hash[username] = 1 end end username_hash.each do |key, value| results.push(key) end return results end
class Logger attr_reader :filename def initialize(filename) @filename = filename @file = File.open(filename, "a") end def log(message) @file.write(timestamp + " " + message + "\n") end private def timestamp "[" + Time.now.to_s + "]" end end
class EvenementsController < ApplicationController before_action :set_evenement, only: [:show, :edit, :update, :destroy] # GET /evenements # GET /evenements.json def index if user_signed_in? @categories = Category.all @organisateur = Organisateur.find_by(user_id: current_user.id) if @organisateur @events = Evenement.where(organisateur_id: @organisateur.id) else @events = [] end else redirect_to new_user_session_path end end # GET /evenements/1 # GET /evenements/1.json def show if user_signed_in? @evenement = Evenement.find(params[:id]) @comments = Commentaire.where(evenement_id: @evenement.id) else redirect_to new_user_session_path end end # GET /evenements/new def new @categories = Category.all if user_signed_in? @organisateurs = Organisateur.where(user_id: current_user.id) @statuses = Status.all @organisateur = Organisateur.new if @organisateurs != [] @evenement = Evenement.new else # redirect_to new_organisateur_path @evenement = Evenement.new @organisateur = Organisateur.new end else redirect_to new_user_session_path end end # GET /evenements/1/edit def edit if user_signed_in? @categories = Category.all @organisateurs = Organisateur.where(user_id: current_user.id) else redirect_to new_user_session_path end end # POST /evenements # POST /evenements.json def create @categories = Category.all @organisateurs = Organisateur.where(user_id: current_user.id) @evenement = Evenement.new(evenement_params) cat = Category.find(params[:category_id]) org = Organisateur.find(params[:organisateur_id]) @evenement.category = cat @evenement.organisateur = org respond_to do |format| if @evenement.save format.html { redirect_to event_show_path(@evenement.id), notice: 'Evenement was successfully created.' } format.json { render :show, status: :created, location: @evenement } else format.html { render :new } format.json { render json: @evenement.errors, status: :unprocessable_entity } end end end # PATCH/PUT /evenements/1 # PATCH/PUT /evenements/1.json def update respond_to do |format| if @evenement.update(evenement_params) format.html { redirect_to @evenement, notice: 'Evenement was successfully updated.' } format.json { render :show, status: :ok, location: @evenement } else format.html { render :edit } format.json { render json: @evenement.errors, status: :unprocessable_entity } end end end # DELETE /evenements/1 # DELETE /evenements/1.json def destroy comment = Commentaire.where(evenement_id: params[:id]) comment.each do |c| c.destroy end @evenement.destroy respond_to do |format| format.html { redirect_to evenements_url, notice: 'Evenement was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_evenement @evenement = Evenement.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def evenement_params params.require(:evenement).permit(:titre, :description, :date, :price, :picture, :lat, :lng) end end
require 'rails_helper' RSpec.describe AptSearch do context 'Parsing html from a passed in page' do let(:html){File.open(Rails.root.join('spec', 'stubs', 'html.txt'), 'r').read} it 'Correctly gets apartment info' do data = AptSearch.new.get_apartment_data_from_raw_html(html) expect(data.count).to eq(13) end it 'feeds into the PageResponseIterator' do data = AptSearch.new.get_apartment_data_from_raw_html(html) PageResponseIterator.iterate(data) expect(Apartment.count).to eq(13) end end end
class AdminsController < ApplicationController include AdminsHelper #page where admin can choose to login/signup def index logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the admin index page") session_check end #page after admin logs in def home logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the admin home page") session_check end #creating admins def create logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the create admin post_request page") session_check @user = User.new(params.require(:user).permit(:name, :email, :password, :password_confirmation)) if @user.save @admin = Admin.create(:predefined => 0, :user_id => @user.id) redirect_to manage_admins_url else render 'create_admin' end end # manage admins part ------------------------------------------------------------------------------------- def manage_admins logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the manage admins page") session_check end def create_admin logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the create admin page") session_check @user = User.new end def view_admins session_check logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering view admins page") @admins = Admin.all end def delete_admin logger.info("(#{self.class.to_s}) (#{action_name}) -- destroying an admin") session_check admin = Admin.find(params[:id]) if admin.predefined != 1 Admin.destroy(params[:id]) end #User.destroy(admin.user.id) respond_to do |format| format.html { redirect_to view_admins_url() } format.json { head :no_content } end end # manage users part ------------------------------------------------------------------------------------- def manage_users logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the manage users page") session_check end def view_users logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the view users page") session_check @users = User.all @users.each do |user| admin = Admin.find_by(:user_id => user.id) if admin.nil? user.is_admin = false user.admin = nil else user.is_admin = true user.admin = admin end #puts "ID-------------------#{user.admin}-----------" end @users end def destroy_user logger.info("(#{self.class.to_s}) (#{action_name}) -- destroying a user") session_check session[:return_to] ||= request.referer admin = Admin.where(user_id: params[:id]) Admin.destroy(admin[0].id) if !admin.empty? user = User.find(params[:id]) accounts = user.accounts # delete friends Friend.where(:user_id => user.id).delete_all Friend.where(:friend_id => user.id).delete_all # delete accounts and transactions of selected user if !accounts.nil? accounts.each do |each_account| transactions = each_account.transactions transactions.each do |each_transaction| transfer = Transfer.find_by(:transaction_id => each_transaction.id) if !transfer.nil? Transfer.destroy(transfer.id) end Transaction.destroy(each_transaction) end additional_transfer = Transfer.where(:account_id => each_account.id) additional_transfer.each do |each_transfer| Transfer.destroy(each_transfer) end Account.destroy(each_account) end end User.destroy(params[:id]) respond_to do |format| format.html { redirect_to session.delete(:return_to) } format.json { head :no_content } end end def view_transaction_history_of_user logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the view transaction history page") session_check @user = User.find(params[:id]) @accounts = @user.accounts end # manage accounts part ------------------------------------------------------------------------------------- def manage_accounts logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the manage accounts page") session_check end def create_accounts logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering the create accounts(approve request to create) page") session_check # get all the accounts with status pending(3) // active(1) closed(2) @accounts = Account.where(status: 3) end def approve_or_decline_account logger.info("(#{self.class.to_s}) (#{action_name}) -- approve_or_decline_account page") session_check @account = Account.find(params[:account_id]) puts "Admin decision: #{params[:decision]}" if params[:decision] == '1' @account.status = 1 @account.save else @account.status = 2 @account.save end respond_to do |format| format.html { redirect_to create_accounts_url() } format.json { head :no_content } end end def view_accounts logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering view_accounts page") session_check @accounts = Account.all end def view_account_details logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering view_account_details page") session_check @account = Account.find(params[:id]) @user = @account.user if !params[:decision].nil? puts "parameter : #{params[:decision]}" if !(1...3).include?(params[:decision].to_i) puts "need to redirect" redirect_to view_account_details_url(@account) else puts "no need to redirect" @account.status = params[:decision] @account.save end end end def view_transaction_history logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering view_transaction history page") session_check #puts debug(params) @account = Account.find(params[:id]) end def view_transaction_requests logger.info("(#{self.class.to_s}) (#{action_name}) -- Entering view_transaction_requests page") session_check @transactions = Transaction.where("status = 3") end def approve_or_decline_transaction logger.info("(#{self.class.to_s}) (#{action_name}) -- approve_or_decline_transaction page") session_check @transaction = Transaction.find(params[:transaction_id]) if params[:decision] == '1' @transaction.status = 1 @account = Account.find(@transaction.account_id) if @transaction.transaction_type == deposit_type @account.balance += @transaction.amount elsif @transaction.transaction_type == borrow_type if @account.balance >= @transaction.amount @account.balance -= @transaction.amount transfer = Transfer.find_by(:transaction_id => @transaction.id) transfer.account.balance += @transaction.amount transfer.account.save else flash[:danger] = "Unsuccessful due to Insufficient funds in the source account" 'redirect_to borrow_requests_url() and return' return end elsif @transaction.transaction_type == withdraw_type @account.balance -= @transaction.amount end if @account.save if @transaction.save if @transaction.transaction_type == deposit_type || @transaction.transaction_type == withdraw_type AdminMailer.transanction_status_mail(@transaction).deliver elsif @transaction.transaction_type == borrow_type AdminMailer.borrow_status_mail(@transaction, Transfer.find_by(:transaction_id => @transaction.id)).deliver AdminMailer.borrow_status_mail_friend(@transaction, Transfer.find_by(:transaction_id => @transaction.id)).deliver end end end flash[:success] = "Transaction approved successfully" else @transaction.status = 2 @transaction.save end if !params[:url].nil? && params[:url] == 'requests' respond_to do |format| format.html { redirect_to view_transaction_requests_url() } format.json { head :no_content } end elsif !params[:url].nil? && params[:url] == 'history1' respond_to do |format| format.html { redirect_to view_transaction_history_url(params[:account]) } format.json { head :no_content } end elsif !params[:url].nil? && params[:url] == 'history2' respond_to do |format| format.html { redirect_to view_transaction_history_of_user_url(params[:id]) } format.json { head :no_content } end elsif !params[:url].nil? && params[:url] == 'borrow' respond_to do |format| format.html { 'redirect_to borrow_requests_url() and return' } format.json { head :no_content } end else respond_to do |format| format.html { redirect_to view_accounts_url() } format.json { head :no_content } end end end def delete_account logger.info("(#{self.class.to_s}) (#{action_name}) -- delete account page") session_check account = Account.find(params[:id]) account.status = cancelled_status account.save respond_to do |format| format.html { redirect_to view_accounts_url() } format.json { head :no_content } end end private def admin_params params.require(:admin).permit(:transaction_id, :url, :decision, :user, :name, :email, :password, :password_confirmation) end end
class GroupGame < ActiveRecord::Base belongs_to :group belongs_to :game end
require 'rails_helper' RSpec.describe PieceSituation, type: :model do it 'has a valid factory' do expect(create :piece_situation).to be_valid end describe 'Validations' do it { should validate_presence_of :name } end end
module DidYouMean module Formatters class Plain def initialize(suggestions = []) @suggestions = suggestions end def to_s output = "\n\n" output << " Did you mean? #{format(@suggestions.first)}\n" output << @suggestions.drop(1).map{|word| "#{' ' * 18}#{format(word)}\n" }.join output << " " # for rspec end def format(name) case name when IvarName "@#{name}" when CvarName "@@#{name}" when MethodName "##{name}" when ColumnName "%{column}: %{type}" % { column: name, type: name.type } else name end end end class Pry def initialize(suggestions) @suggestions = suggestions end def to_s output = "\n\n" output << " " + red('Did you mean?') + " #{format(@suggestions.first)}\n" output << @suggestions.drop(1).map{|word| "#{' ' * 18}#{format(word)}\n" }.join output << " " end def format(name) case name when IvarName yellow("@#{name}") when CvarName yellow("@@#{name}") when MethodName "##{name}" when ClassName name.split("::").map do |constant| blue(underline(constant)) end.join("::") when ColumnName "%{column}: %{type}" % { column: magenda(name), type: name.type } else name end end def red(str); "\e[31m#{str}\e[0m" end def yellow(str); "\e[33m#{str}\e[0m" end def blue(str); "\e[34m#{str}\e[0m" end def magenda(str); "\e[35m#{str}\e[0m" end def underline(str); "\e[4m#{str}\e[0m" end end end end
class ShortenedUrl < ApplicationRecord validates :short_url, presence: true, uniqueness: true validates :long_url, presence: true validates :user_id, presence: true belongs_to :submitter, primary_key: :id, foreign_key: :user_id, class_name: :User has_many :visits, primary_key: :id, foreign_key: :shortened_url_id, class_name: :Visit has_many :visitors, Proc.new { distinct }, through: :visits, source: :user has_many :tag_topics, primary_key: :id, foreign_key: :url_id, class_name: :TagTopic def self.random_code short_url = SecureRandom::urlsafe_base64(16) while self.exists?(short_url) short_url = SecureRandom::urlsafe_base64(16) end short_url end def self.create_from_user(user, long_url) ShortenedUrl.create!( short_url: self.random_code, long_url: long_url, user_id: user.id ) end def num_clicks self.visits.count end def num_uniques self.visitors.count end def num_recent_uniques self.visits.select(:user_id).distinct.where(["created_at < ?", Time.now - 10]).count end end
Rails.application.routes.draw do get 'homes/show' get 'homes/index' get 'homes/new' get 'homes/edit' devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :books root 'homes#show' resources :users end
module ErrorHandler # 1. Please pay attention to the indentation. Many Ruby devs are very particular about it # 2. How come an ErrorHandler is responsible for printing the menu? This functionality has nothing # to do with error handling. PROGRAM_PHRASES = { "menu" => "\n\nEditor Commands as follow:\n > I M N - Create image MxN\n > C - Clear the image setting pixels to white (O)\n > L X Y C - Colours the pixel (X,Y) with colour C\n > V X Y1 Y2 C - Draw a vertical segment of colour C in column X between rows Y1 and Y2\n > H X1 X2 Y C - Draw a horizontal segment of colour C in row Y between columns X1 and X2\n > F X Y C - Fill the region R with the colour C. R is defined as: Pixel (X,Y) belongs to R. Any other pixel which is the same colour as (X,Y) and shares a common side with any pixel in R also belongs to this region.\n > B X Y C - Fill the regions Rs with the colour C. R is defined as: Pixels (X,Y) belongs to R. Any other pixels which is the same colour as (X,Y) and shares a common side with any pixels in R also belongs to this region.\n > S - Show the contents of the current image\n > R - Clear the console\n > X - Terminate the session\n", "p_command" => "\nChoose the command: ", "undef_command" => "\nEditor do not know this command, for help put -h \n ", "create_img" => "\nFirst create the image!\n", "bad_color" => "\nColor not valid\n", "bad_numeric" => "\nNumber does not valid! \n", "bad_img_range" => "\nImage must be in range 1 <= M,N <= 250 px\n", "x_bigger_y" => "\nBad coodinates range\n", "bad_args" => "\nBad arguments in Command\n", "out_range" => "\nNumber is out of range\n" } # Again, how come ErroHandler is responsible for the output? # Also, many developers would sneer at using a boolean argument to dramatically alter the # behaviour of the method (print vs raise). A better approach would me to split this method in two. #printing to console def user_output(phrase, error = false) phrase = PROGRAM_PHRASES[phrase] raise phrase if error == true print phrase if phrase end # Same problem as other methods that end in "?" def check_color?(color) color_template = /\A[A-Z]\z/ user_output("bad_color", true) unless color_template.match(color.to_s) return true end def is_numeric?(number) number_tempate = /\A\+?0*[1-9]\d*\Z/ # spelling: template user_output("bad_numeric", true) unless number_tempate.match(number.to_s) true end # This method raises an error or returns a number. It would be cleaner to return either true or false # depending if it's in the range and then raise the error elsewhere def check_coordinate(coordinate, size = 250) user_output("out_range", true) unless is_numeric?(coordinate) && coordinate.to_i <= size coordinate.to_i end # same problem as with other methods with "?" as well as the previous one def check_image_range?(m, n) n = n.to_i if is_numeric?(n.to_i) m = m.to_i if is_numeric?(m.to_i) # magic numbers again user_output("bad_img_range", true) if m < 1 || m > 250 || n < 1 || n > 250 true end # a method with a question mark should never raise an error def x_bigger_y?(x,y) user_output("x_bigger_y", true) if x > y true end # A method that ends with "?" should not do any work def check_arguments_number?(command, number) user_output("bad_args", true) if number != command.count true # I guess you're doing it because a method with "?" is supposed to always return a boolean but # a better solution would be to change the name of this method end # Same comment here (see above) def check_if_positive_integers?(number_list) number_list.each{|number| check_coordinate(number) } true end end
class Wordfreq STOP_WORDS = ['a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he', 'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were', 'will', 'with'] def initialize(filename) contents = File.read(filename).downcase.gsub("--", " ") contents = contents.gsub(/[^a-z0-9\s]/i, "") word_array = contents.split(" ") - STOP_WORDS @words = {} word_array.each do |word| if @words.include?(word) @words[word] += 1 else @words[word] = 1 end end top_words(5) end def frequency(word) if @words.has_key?(word) return frequencies[word] else 0 end end def frequencies @words end def top_words(number) @words.sort_by { |word, count| count }.reverse.take(5) end def print_report top10 = @words.sort_by { |word, count| count }.reverse.take(10).to_h top10.each { |word_and_count| stars = "*" * word_and_count[1] puts "#{word_and_count[0]} | #{word_and_count[1]} #{stars}" } end end if __FILE__ == $0 filename = ARGV[0] if filename full_filename = File.absolute_path(filename) if File.exists?(full_filename) wf = Wordfreq.new(full_filename) wf.print_report else puts "#{filename} does not exist!" end else puts "Please give a filename as an argument." end end
# == Schema Information # # Table name: assets # # id :integer not null, primary key # user_id :integer # photo_id :integer # source_id :integer # source_type :string(255) # source_asset_id :integer # archive_id :string(255) # state :string(255) default(""), not null # processed :integer default(0), not null # asset_type :string(255) default(""), not null # file_type :string(255) default(""), not null # file_path :text default(""), not null # secret :string(16) default(""), not null # name :string(255) default(""), not null # host :string(255) default(""), not null # size :integer default(0), not null # checksum :string(32) default(""), not null # taken_at :datetime # taken_at_old :datetime # metadata :text # exif_migrated :boolean default(FALSE), not null # created_at :datetime not null # updated_at :datetime not null # # TODO: drop source_asset_id (in lieu of source) require 'Cloud' require 'fileutils' require 'util' class Asset < ActiveRecord::Base processible_entity attr_accessible :user_id, :name, :host, :file_path, :checksum, :taken_at, :metadata, :exif_migrated serialize :metadata, JSON # various constants META_INDENT_SIZE = 2 # asset type TYPE_UNKNOWN = '' TYPE_RAW = 'raw' TYPE_JPG = 'jpg' TYPE_XMP = 'xmp' TYPE_EXIF = 'exif' # file extensions; most are RAW formats FILE_TYPE_NONE = '' FILE_TYPE_EXIF = 'exif' FILE_TYPE_JPG = 'jpg' FILE_TYPE_JPEG = 'jpeg' FILE_TYPE_XMP = 'xmp' FILE_TYPE_3FR = '3fr' FILE_TYPE_ARI = 'ari' FILE_TYPE_ARW = 'arw' FILE_TYPE_BAY = 'bay' FILE_TYPE_CRW = 'crw' FILE_TYPE_CR2 = 'cr2' FILE_TYPE_CAP = 'cap' FILE_TYPE_DCS = 'dcs' FILE_TYPE_DCR = 'dcr' FILE_TYPE_DNG = 'dng' FILE_TYPE_DRF = 'drf' FILE_TYPE_EIP = 'eip' FILE_TYPE_ERF = 'erf' FILE_TYPE_FFF = 'fff' FILE_TYPE_IIQ = 'iiq' FILE_TYPE_K25 = 'k25' FILE_TYPE_KDC = 'kdc' FILE_TYPE_MEF = 'mef' FILE_TYPE_MOS = 'mos' FILE_TYPE_MOV = 'mov' FILE_TYPE_MRW = 'mrw' FILE_TYPE_NEF = 'nef' FILE_TYPE_NRW = 'nrw' FILE_TYPE_OBM = 'obm' FILE_TYPE_ORF = 'orf' FILE_TYPE_PEF = 'pef' FILE_TYPE_PTX = 'ptx' FILE_TYPE_PXN = 'pxn' FILE_TYPE_R3D = 'r3d' FILE_TYPE_RAF = 'raf' FILE_TYPE_RAW = 'raw' FILE_TYPE_RWL = 'rwl' FILE_TYPE_RW2 = 'rw2' FILE_TYPE_RWZ = 'rwz' FILE_TYPE_SR2 = 'sr2' FILE_TYPE_SRF = 'srf' FILE_TYPE_SRW = 'srw' FILE_TYPE_THM = 'thm' FILE_TYPE_X3F = 'x3f' belongs_to :archive belongs_to :photo belongs_to :source, :polymorphic => true belongs_to :user has_many :dropbox_files has_many :props, :as => :propable, :dependent => :destroy has_many :queue_items, :as => :queueable, :dependent => :destroy has_many :uploaded_files has_one :derived_asset, :class_name => 'Asset', :as => :source has_one :exif scope :non_derived, where(:source_id => nil) scope :done_state, where(:state => QueueItem::STATE_DONE) scope :saved_state, where(:state => QueueItem::STATE_SAVE) scope :error_state, where(:state => QueueItem::STATE_ERROR) scope :processing, where("`assets`.`state` NOT IN (?)", [QueueItem::STATE_DONE, QueueItem::STATE_ERROR]) scope :processed, done_state.where("`assets`.`photo_id` IS NOT NULL") scope :exif_type, where(:asset_type => Asset::TYPE_EXIF) scope :jpg_type, where(:asset_type => Asset::TYPE_JPG) scope :raw_type, where(:asset_type => Asset::TYPE_RAW) scope :xmp_type, where(:asset_type => Asset::TYPE_XMP) scope :visible_type, where(:asset_type => [Asset::TYPE_JPG, Asset::TYPE_RAW, Asset::TYPE_XMP]) scope :valid_type, where(:asset_type => [Asset::TYPE_EXIF, Asset::TYPE_JPG, Asset::TYPE_RAW, Asset::TYPE_XMP]) after_save :after_save_hook after_destroy :after_destroy_hook class << self # create placeholder asset object def placeholder(user_id, file_name) o = nil # make sure we have a valid user and file name if User.find(user_id) && file_name.present? # save early to generate id o = Asset.new :user_id => user_id, :name => file_name.strip, :host => `hostname`.strip o.save # build basic properties o.detect_file_type o.detect_asset_type o.generate_secret o.generate_file_path o.save end o end # save file locally; add to queue # options: skip_queue def create(user_id, file, file_name, checksum, taken_at = nil, options = {}) raise Exceptions::InvalidParam.new "empty source file" if file.size <= 0 raise Exceptions::InvalidParam.new "missing user_id" if user_id.blank? raise Exceptions::InvalidParam.new "missing file name" if file_name.blank? raise Exceptions::InvalidParam.new "missing checksum" if checksum.blank? # make sure file_name is just name file_name = File.basename file_name # extract taken_at if it doesn't exist/bad taken_at = Util.calculate_taken_at(taken_at, file.path, file_name, options[:metadata]) # check for existing; ok if existing is in error state, or is a derived JPG existing_asset = Asset.existing(user_id, checksum, file_name, taken_at) raise Exceptions::AssetExists.new "asset exists" if existing_asset && !existing_asset.overwritable? # take over the existing asset, or create a placeholder obj = existing_asset || self.placeholder(user_id, file_name) # write the file locally unless Util.file_copy(file.path, obj.file_path) obj.destroy raise Exceptions::FileFailure.new "failed to write file" end # check local file obj.checksum = Util.file_checksum obj.file_path unless obj.checksum == checksum obj.destroy raise Exceptions::FileFailure.new "file write failed checksum" end # save info obj.taken_at = taken_at obj.size = options[:size] || File.size(obj.file_path) obj.state = QueueItem::STATE_SAVE obj.source = options[:source] if options[:source] obj.metadata = options[:metadata] || {} obj.save # push to cloud immediately so others have access to it unless Rails.env != 'production' || obj.source.try(:is_a?, BulkAsset) raise Exceptions::CloudFailure.new "failed to push to cloud" unless obj.aws_storage_put(:size => Photo::SIZE_ORIGINAL) end # queue up next state QueueItem.add obj unless options[:skip_queue] # mark derived? (for pre-generated thumbs) obj.prop(:derived, true) if options[:derived] # update user account stats obj.user.update_account_stats obj end # look for existing asset def existing(user_id, checksum, file_name, taken_at, id = nil) taken_at = Util.normalize_timestamp taken_at file_type = Util.file_extension(file_name) assets = Asset.where :user_id => user_id, :file_type => file_type, :checksum => checksum, :taken_at => taken_at assets.reject!{|asset| asset.id == id } if id assets.first end def file_types Asset.constants.map do |x| if x.match(/^FILE_TYPE_/) && x != :FILE_TYPE_NONE eval "Asset::#{x}" end end.uniq - [nil] end def raw_file_types Asset.constants.map do |x| if x.match(/^FILE_TYPE_/) && ![:FILE_TYPE_NONE, :FILE_TYPE_EXIF, :FILE_TYPE_JPG, :FILE_TYPE_JPEG, :FILE_TYPE_XMP].include?(x) eval "Asset::#{x}" end end.uniq - [nil] end def file_supported?(file_name) @supported_file_types ||= {}.tap do |hash| Asset.file_types.each do |x| hash[x] = true end end ext = File.extname(file_name)[1..10].downcase @supported_file_types[ext] end end def aws_path(options = {}) self.detect_file_type self.generate_secret options[:size] = Photo::SIZE_SMALL unless options[:size] hash = Digest::MD5.hexdigest "#{self.id}-3b70fb2b382a19a8852cf56820bf6c3d" path = "#{hash}x#{self.id}_" if self.asset_type == Asset::TYPE_JPG path += (options[:size] == Photo::SIZE_ORIGINAL ? self.secret : options[:size]) else path += self.secret.to_s end path += ".#{self.file_type}" path end def aws_src(options = {}) s = "https://s3.amazonaws.com/#{AWS[:bucket]}/#{self.aws_path(options)}" s += "?c=#{options[:checksum]}" if options[:checksum] s end def aws_storage_put(options = {}) begin raise "object id is required for S3 path" unless self.id path = options[:size] ? self.aws_path(:size => options[:size]) : self.aws_path file = options[:file] || File.open(self.file_path) # trigger download of originals or non-JPG headers = {} headers['Content-Disposition'] = "attachment; filename=#{self.name}" if self.asset_type != Asset::TYPE_JPG || options[:size] == Photo::SIZE_ORIGINAL # push to S3 Cloud.put_s3 file, path, headers # push to Glacier Cloud.put_glacier(self, file) return true rescue => e STDERR.puts "\tERROR: #{e.class}\n\t#{e.message}" end end def aws_storage_delete(options = {}) begin path = options[:size] ? self.aws_path(:size => options[:size]) : self.aws_path # delete from S3 Cloud.setup_s3.delete_object(AWS[:bucket], path) # TODO: delete from Glacier return true rescue => e STDERR.puts e.message end end # if a duplicate is uploaded, can it overwrite me? def overwritable? self.state == QueueItem::STATE_ERROR || self.derived_jpg? || self.asset_type == Asset::TYPE_EXIF end def processed?(size, set = false) if set self.processed |= Photo::SIZE_FLAGS[size] self.save end (self.processed & Photo::SIZE_FLAGS[size]) > 0 end def queueable_sub_type self.asset_type end def generate_size(size) if self.asset_type == Asset::TYPE_JPG @storage ||= Fog::Storage.new :provider => :AWS, :aws_access_key_id => AWS[:key], :aws_secret_access_key => AWS[:secret] if @storage # cap quality at 85 (non-large sizes) options = {:size => size} unless size == Photo::SIZE_LARGE options[:quality] = 85 if self.exif && self.exif.get(['Image', 'Quality']).to_i > 85 end file_path = Util.temp_file self.name Util.thumbnail self.file_path, file_path, self.asset_type, options file = File.open file_path if file.size > 0 if self.aws_storage_put(:size => size, :file => file) File.delete file.path self.processed?(size, true) return true end end end end false end def detect_file_type(force = false) if self.file_type.blank? || force extension = Util.file_extension(self.name) self.file_type = extension.blank? ? Asset::FILE_TYPE_NONE : extension end self.file_type end def detect_asset_type if self.asset_type.blank? || force case self.file_type when Asset::FILE_TYPE_CR2, Asset::FILE_TYPE_3FR, Asset::FILE_TYPE_ARI, Asset::FILE_TYPE_ARW, Asset::FILE_TYPE_BAY, Asset::FILE_TYPE_CRW, Asset::FILE_TYPE_CR2, Asset::FILE_TYPE_CAP, Asset::FILE_TYPE_DCS, Asset::FILE_TYPE_DCR, Asset::FILE_TYPE_DNG, Asset::FILE_TYPE_DRF, Asset::FILE_TYPE_EIP, Asset::FILE_TYPE_ERF, Asset::FILE_TYPE_FFF, Asset::FILE_TYPE_IIQ, Asset::FILE_TYPE_K25, Asset::FILE_TYPE_KDC, Asset::FILE_TYPE_MEF, Asset::FILE_TYPE_MOS, Asset::FILE_TYPE_MRW, Asset::FILE_TYPE_NEF, Asset::FILE_TYPE_NRW, Asset::FILE_TYPE_OBM, Asset::FILE_TYPE_ORF, Asset::FILE_TYPE_PEF, Asset::FILE_TYPE_PTX, Asset::FILE_TYPE_PXN, Asset::FILE_TYPE_R3D, Asset::FILE_TYPE_RAF, Asset::FILE_TYPE_RAW, Asset::FILE_TYPE_RWL, Asset::FILE_TYPE_RW2, Asset::FILE_TYPE_RWZ, Asset::FILE_TYPE_SR2, Asset::FILE_TYPE_SRF, Asset::FILE_TYPE_SRW, Asset::FILE_TYPE_X3F self.asset_type = Asset::TYPE_RAW when Asset::FILE_TYPE_JPG self.asset_type = Asset::TYPE_JPG when Asset::FILE_TYPE_XMP self.asset_type = Asset::TYPE_XMP when Asset::FILE_TYPE_EXIF self.asset_type = Asset::TYPE_EXIF else self.asset_type = Asset::TYPE_UNKNOWN end end self.asset_type end def generate_file_path(force = false) if self.file_path.blank? || force w = 3 d = 10 ** w self.file_path = "#{ASSETS_ROOT}/#{"%0#{w}d/%0#{w}d/%0#{4 * w}d.#{file_type}" %[id % d, (id / d) % d, id]}" FileUtils.mkdir_p(File.dirname(self.file_path)) end self.file_path end def generate_secret(force = false, length = 16) if self.secret.blank? || force self.secret = Util.signature("#{`rand`}#{self.id}#{self.created_at}", length) end self.secret end def set_taken_at(timestamp) # clean weird date format: YYYY:mm:dd timestamp = timestamp.sub(/\b(\d{4}):(\d{2}):(\d{2})\b/, '\1-\2-\3') if timestamp.is_a?(String) # set taken_at prop if Util.valid_timestamp?(timestamp) self.taken_at = DateTime.parse(timestamp).strftime('%Y-%m-%d %H:%M:%S') self.save end end def delegate if self.asset_type.present? require "#{self.asset_type}_asset" klass = "#{self.asset_type.capitalize}Asset".constantize klass.new self end end # TODO: download from S3/Glacier? def ensure_file return true if File.exists?(self.file_path) && File.size(self.file_path) > 0 # try to get it from the source host if self.host && self.file_path # if i'm not the host, then of course the file isn't there unless self.host == `hostname`.strip begin `mkdir -p #{File.dirname self.file_path}` `scp #{self.host}:#{self.file_path} #{self.file_path}` # check size size = File.size(self.file_path) raise "file size #{size} does not match" unless size == self.size rescue => e STDERR.puts "Asset::ensure_file: failed to copy file #{self.host}:#{self.file_path}: #{e.message}" end end end return true if File.exists?(self.file_path) && File.size(self.file_path) > 0 # pull down from the cloud if self.file_path begin require 'open-uri' `mkdir -p #{File.dirname self.file_path}` file = open self.file_path, 'wb' file << open(self.aws_src :size => Photo::SIZE_ORIGINAL).read # check size size = File.size(self.file_path) raise "file size #{size} does not match" unless size == self.size rescue => e STDERR.puts "Asset::ensure_file: failed to download file #{self.aws_src}: #{e.message}" end file.close if file end return true if File.exists?(self.file_path) && File.size(self.file_path) > 0 false end def is_valid? return false if self.destroyed? return false if self.asset_type.blank? || ![Asset::TYPE_EXIF, Asset::TYPE_JPG, Asset::TYPE_RAW, Asset::TYPE_XMP].include?(self.asset_type) return false if self.file_path.blank? || self.checksum.blank? || self.size == 0 true end def derived_jpg? self.asset_type == Asset::TYPE_JPG \ && (self.source.try(:is_a?, Asset) || self.prop(:derived)) end def migrate_exif return if self.exif_migrated? # convert props to hash data = {} deletes = [] self.props.each do |p| next unless p.propable_type == Asset.to_s next if %w[aperture camera derived focal_length height iso lens name rating shutter width].include? p.name path = p.name.split ': ' Exif.set_data data, p.value, path deletes << p end # create exif and cleanup props exif = Exif.create(self, data) if exif self.update_column :exif_migrated, true if deletes.present? Asset.connection.execute "INSERT INTO `props_old` SELECT * FROM `props` WHERE `id` IN (#{deletes.map(&:id).join(',')})" Asset.connection.execute "DELETE FROM `props` WHERE `id` IN (#{deletes.map(&:id).join(',')})" end end end def name_plain(default = 'Untitled') n = File.basename(self.name, '.*') n.present? ? n : default end protected def after_save_hook if self.photo # make sure proper JPG is set self.photo.jpg(true) # make sure photo visibility is updated self.photo.check_visibility if self.asset_type == Asset::TYPE_JPG # force re-cache assets self.photo.assets_cached(true) end end def after_destroy_hook # same stuff as after save self.after_save_hook # cleanup local files self.cleanup end def cleanup begin File.delete(self.file_path) rescue end if self.asset_type == Asset::TYPE_JPG Photo.sizes.each do |size| self.aws_storage_delete :size => size end else self.aws_storage_delete end end end
FactoryBot.define do domain = Faker::Internet.domain_name factory :ldap do name { "Active Directory" } host { Faker::Internet.private_ip_v4_address } port { 389 } domain { domain } username { "administrator" } password { "Pa$$word" } tree_base { domain } company end end
# frozen_string_literal: true class EtsPdf::Parser::ParsedLine LINE_TYPES = %w[course group period].map do |type| [type, "EtsPdf::Parser::ParsedLine::#{type.classify}".constantize] end.to_h def initialize(line) @line = line @types = {} end attr_reader :line LINE_TYPES.each do |type, klass| define_method(type) { @types[type] ||= klass.new(@line) } end def parsed? LINE_TYPES.keys.any? { |type| type?(type) } end def type?(name) LINE_TYPES.keys.include?(name.to_s) ? public_send(name).parsed? : false end end
class InventoryShow < Demo def self.title "Inventory show command" end def run @prompt.say(<<~INTRO) Bolt has a subcommand 'inventory show', which accepts a target specification and returns the targets that exist in the inventory and match the spec. For example, {{bolt inventory show -t localhost}} will return just 'localhost' if it's in the inventory, and nothing if it isn't. You can also use {{-n all}}, {{--rerun failure}}, or {{-q query}} to get lists of nodes. Try it out: {{bolt inventory show -t all}} INTRO @prompt.run_command(/bolt inventory show -t all/) @prompt.say("You can also try specifying just a group name, like {{bolt inventory show -t vms}}") @prompt.run_command(/bolt inventory show -t vms/) end end
# frozen_string_literal: true RSpec.describe 'Videos' do resource 'Admin videos' do let!(:video1) { create(:video) } let!(:video2) { create(:video) } let!(:video3) { create(:video, :with_category) } let!(:video4) { create(:video, :deleted) } # NOTE: Deleted records are not returned by default let!(:coach1) { create(:coach) } let!(:coach2) { create(:coach) } let!(:coaches_video) { create(:coaches_video, video: video1, coach: coach1) } let!(:category1) { create(:video_category, name: FFaker::Name.name) } let!(:category2) { create(:video_category, name: FFaker::Name.name) } # IDEA: This should be somehow be improved/replaced # In current way it only polutes `route` param for us(devs) # As all possible sorting, filtering, and pagination params are known # We need to somehow overrided this method to rebuild first param # In the needed direction # As as it grows it will becam too long # Example for what we have now: # '/api/v1/admin/videos{?include}{?sort}{?filter[name]}{?page[number]}{?page[size]}' route '/api/v1/admin/videos{?include}{?sort}', 'Admin Videos endpoint' do get 'All videos' do parameter :page parameter :sort, example: 'created_at' parameter :filter parameter :include, example: 'category' with_options scope: :page do parameter :number, required: true parameter :size, required: true end with_options scope: :filter do parameter :name parameter :duration parameter :coach parameter :category end with_options scope: %i[filter duration] do parameter :from parameter :to end context 'not authenticated' do example 'Responds with 401' do do_request expect(status).to eq(401) end end context 'authenticated user', :authenticated_user do example 'Responds with 403' do do_request expect(status).to eq(403) end end context 'authenticated admin', :authenticated_admin do example 'Responds with 200' do do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 3 end end context 'with category include', :authenticated_admin do let(:include) { 'category' } example 'Responds with 200' do do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 3 expect(parsed_body[:included].count).to eq 1 expect(parsed_body[:included][0][:attributes][:name]).to eq VideoCategory.first.name end end context 'paginated', :authenticated_admin do let(:number) { 2 } let(:size) { 1 } example 'Responds with 200' do do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 1 expect(parsed_body[:meta]).to be_paginated_resource_meta expect(parsed_body[:meta]).to eq( current_page: 2, next_page: 3, prev_page: 1, page_count: 3, record_count: 3 ) end end context 'sorted', :authenticated_admin do let(:sort) { '-created_at' } example 'Responds with 200' do do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 3 end end context 'filtered', :authenticated_admin do context 'by duration' do let(:from) { 0 } let(:to) { 1 } example 'Responds with 200' do video1.update(duration: 1) do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 1 end end context 'by category' do let(:category) { [category1.id, category2.id] } example 'Responds with 200' do video2.update(category: category2) do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 1 expect(parsed_body[:data][0][:id]).to eq_id video2.id end end context 'by coach' do let(:coach) { [coach1.id, coach2.id] } example 'Responds with 200' do do_request expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data].count).to eq 1 expect(parsed_body[:data][0][:id]).to eq_id video1.id end end end end post 'Create video' do parameter :type, scope: :data, required: true with_options scope: %i[data attributes] do parameter :url, required: true parameter :description, required: true parameter :name, required: true parameter :content_type, required: true end let(:type) { 'users' } let(:name) { FFaker::Video.name } let(:url) { 'http://127.0.0.1:3000/video.mp4' } let(:content_type) { ::SixByThree::Constants::AVAILABLE_UPLOAD_VIDEO_CONTENT_TYPES.sample } let(:description) { FFaker::Book.description } context 'not authenticated' do example 'Responds with 401' do do_request expect(status).to eq(401) end end context 'authenticated user', :authenticated_user do example 'Responds with 403' do do_request expect(status).to eq(403) end end context 'authenticated admin', :authenticated_admin do example 'Responds with 201' do do_request expect(status).to eq(201) expect(response_body).to match_response_schema('v1/videos/index') expect(parsed_body[:data][:attributes][:name]).to eq name end end context 'when params are invalid', :authenticated_admin do let(:name) { nil } example 'Responds with 422' do do_request expect(status).to eq(422) expect(response_body).to match_response_schema('v1/error') end end context 'when invalid video type', :authenticated_admin do let(:content_type) { 'lorem/ipsum' } example 'Responds with 422' do do_request expect(status).to eq(422) expect(response_body).to match_response_schema('v1/error') end end end delete 'Destroy video' do parameter :data, type: :array, items: {type: :object}, required: true let!(:video1) { create(:video) } let!(:video2) { create(:video) } let(:data) do [ {type: 'videos', id: video1.id}, {type: 'videos', id: video2.id} ] end context 'not authenticated' do example 'Responds with 401' do do_request expect(status).to eq(401) end end context 'not admin', :authenticated_user do example 'Responds with 403' do do_request expect(status).to eq(403) end end context 'is admin', :authenticated_admin do example 'Responds with 204' do do_request expect(status).to eq(204) end end end end route '/api/v1/admin/videos/:id', 'Admin Video endpoint' do get 'Single video' do let!(:video) { create(:video) } let(:id) { video.id } context 'not authenticated' do example 'Responds with 401' do do_request expect(status).to eq(401) end end context 'authenticated user', :authenticated_user do example 'Responds with 403' do do_request expect(status).to eq(403) end end context 'video was not found', :authenticated_admin do let(:id) { 0 } example 'Responds with 404' do do_request expect(status).to eq(404) expect(response_body).to be_empty end end context 'authenticated admin', :authenticated_admin do example 'Responds with 200' do do_request expect(status).to eq(200) expect(response_body).to match_response_schema('v1/video') end end end put 'Update video' do parameter :type, scope: :data, required: true with_options scope: %i[data attributes] do parameter :name parameter :description parameter :lesson_date end with_options scope: %i[data relationships category data] do parameter :id, method: :category_id parameter :type, method: :category_type end with_options scope: %i[data relationships coaches] do parameter :data, type: :array, items: {type: :object}, method: :coaches_data, required: true end let(:type) { 'videos' } let!(:video) { create(:video) } let(:id) { video.id } context 'not authenticated' do let(:name) { FFaker::Name.name } example 'Responds with 401' do do_request expect(status).to eq(401) end end context 'not admin', :authenticated_user do let(:name) { FFaker::Name.name } example 'Responds with 403' do do_request expect(status).to eq(403) end end context 'params are invalid', :authenticated_admin do let(:name) { nil } example 'Responds with 422' do do_request expect(status).to eq(422) expect(response_body).to match_response_schema('v1/error') end end context 'params are valid', :authenticated_admin do let(:name) { FFaker::Name.name } let(:description) { FFaker::Book.description } let(:lesson_date) { Time.current } example 'Responds with 200' do do_request expect(status).to eq(200) expect(response_body).to match_response_schema('v1/video') end end context 'association video category', :authenticated_admin do let(:category_id) { category1.id } let(:category_type) { 'categories' } example 'Responds with 200' do do_request video.reload expect(status).to eq(200) expect(response_body).to match_response_schema('v1/video') expect(video.category).to eq category1 expect(category1.videos).to eq [video] end end context 'video can have multiple coaches', :authenticated_admin do let!(:coach1) { create(:coach) } let!(:coach2) { create(:coach) } let(:coaches_data) do [ {type: 'coaches', id: coach1.id}, {type: 'coaches', id: coach2.id} ] end example 'Responds with 200' do do_request expect(status).to eq(200) expect(response_body).to match_response_schema('v1/video') expect(coach1.video_pks).to eq [video1.id, video.id] expect(coach2.video_pks).to eq [video.id] expect(video.coach_pks).to eq [coach1.id, coach2.id] end end end delete 'Destroy video' do let!(:video) { create(:video) } let(:id) { video.id } context 'not authenticated' do example 'Responds with 401' do do_request expect(status).to eq(401) end end context 'not admin', :authenticated_user do example 'Responds with 403' do do_request expect(status).to eq(403) end end context 'is admin', :authenticated_admin do example 'Responds with 204' do do_request expect(status).to eq(204) end end end end end end
module Tools def convert_node_to_index node case node when "A" 0 when "B" 1 when "C" 2 when "D" 3 when "E" 4 end end end class Station include Tools def initialize to_station_A, to_station_B, to_station_C, to_station_D, to_station_E @to_station_A = to_station_A @to_station_B = to_station_B @to_station_C = to_station_C @to_station_D = to_station_D @to_station_E = to_station_E end def print_all_distances p "The distance to station A is: #{@to_station_A}" p "The distance to station B is: #{@to_station_B}" p "The distance to station C is: #{@to_station_C}" p "The distance to station D is: #{@to_station_D}" p "The distance to station E is: #{@to_station_E}" end def distance_array [ @to_station_A, @to_station_B, @to_station_C, @to_station_D, @to_station_E ] end def print_distance_to node distances = distance_array index = convert_node_to_index(node) distances[index] end end class Conductor include Tools def initialize station_A, station_B, station_C, station_D, station_E @station_A = station_A @station_B = station_B @station_C = station_C @station_D = station_D @station_E = station_E end def build_matrix a = @station_A.distance_array b = @station_B.distance_array c = @station_C.distance_array d = @station_D.distance_array e = @station_E.distance_array matrix = [a, b, c, d, e] end def calculate_distances *nodes total = 0 nodes.each_index do |index| if index > 0 temp = distance_between(nodes[index-1], nodes[index]) if temp.nil? total = "NO SUCH ROUTE" elsif total += temp end end end total end def distance_between node_1, node_2 node_1 = convert_node_to_index(node_1) node_2 = convert_node_to_index(node_2) matrix = build_matrix matrix[node_1][node_2] end def possible_routes origin, destination matrix = build_matrix origin = convert_node_to_index(origin) destination = convert_node_to_index(destination) matrix[origin].each_with_index do |distance, destination| if (distance != nil) && (distance != 0) first_jump = destination p "from Station #{origin}, we can go to #{first_jump}" end end end end # Create Station objects station_A = Station.new(0, 5, nil, 5, 7) station_B = Station.new(nil, 0, 4, nil, nil) station_C = Station.new(nil, nil, 0, 8, 2) station_D = Station.new(nil, nil, 8, 0, 6) station_E = Station.new(nil, 3, nil, nil, 0) # Create Conductor objects conductor = Conductor.new(station_A, station_B, station_C, station_D, station_E) # Ask Conductor questions # puts "1. #{conductor.calculate_distances('A', 'B', 'C')}" # puts "2. #{conductor.calculate_distances('A', 'D')}" # puts "3. #{conductor.calculate_distances('A', 'D', 'C')}" # puts "4. #{conductor.calculate_distances('A', 'E', 'B', 'C', 'D')}" # puts "5. #{conductor.calculate_distances('A', 'E', 'D')}" # puts "6." # puts "7." # puts "8." # puts "9." # puts "10." conductor.possible_routes("A", "C")
class AddHoursBreak < ActiveRecord::Migration[5.1] def change add_column :timelogs, :total_break_hours, :decimal, precision: 2, scale: 2 add_column :timelogs, :total_hours, :decimal, precision: 2, scale: 2 remove_column :timelogs, :returned remove_column :timelogs, :sample remove_column :timelogs, :total_of_hours end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty32" config.vm.hostname = "webserver.dev" # Static IP address config.vm.network "public_network", ip: "192.168.2.10" # Assemption, one machine per project config.vm.synced_folder "./projects/", "/var/www/", id: "vagrant-root", :owner => "vagrant", :group => "www-data", create: true, :mount_options => ['dmode=775', 'fmode=775'] config.vm.provider "virtualbox" do |vb| # Customize the amount of memory on the VM: vb.memory = "1024" end # Shell commands to execute within the guest virtual machine config.vm.provision :shell, path: "shell_provisioning/shell_provisioning.sh" end
class CreateAnswers < ActiveRecord::Migration def change create_table :answers do |t| t.string :text t.boolean :best, default: false t.integer :user_id t.integer :question_id end add_column(:users, :created_at, :datetime) add_column(:users, :updated_at, :datetime) change_column_default :questions, :complete, false end end
require 'minitest/autorun' require 'teebo' class CreditCardTest < MiniTest::Test # Verifies that the length of a string generated by the 'CreditCard.number_to_digits' method # matches the length passed in. def test_cc_generate_length assert_equal 13, Teebo::CreditCard.number_with_length(13).length assert_equal 20, Teebo::CreditCard.number_with_length(20).length assert_equal 23, Teebo::CreditCard.number_with_length(23).length end # Verifies that the 'Luhn Algorithm' function generates the correct output - signifying that the # check digit for generated credit card numbers will be valid. def test_luhn_algorithm assert_equal '4', Teebo::CreditCard.luhn_algorithm(4034424) assert_equal '9', Teebo::CreditCard.luhn_algorithm(32474445663225447) assert_equal '0', Teebo::CreditCard.luhn_algorithm(344564322742543) end # Verifies that the last_digit_validation function properly replaces the last digit in a string # with the appropriate check digit generated by the luhn algorithm. def test_last_digit_validation assert_equal '477222147225', Teebo::CreditCard.last_digit_validation('477222147224') assert_equal '26', Teebo::CreditCard.last_digit_validation('24') assert_equal '21454476127445730757', Teebo::CreditCard.last_digit_validation('21454476127445730752') end def test_benford_dist sum = 0 (1...10000).each do number = Teebo::Number.benford_dist(1000) puts number sum += number end puts sum / 10000 end end
FactoryGirl.define do factory :product do name "Tecnica Moon Boots" description "The one and only Stanton—our casual weather-beaten short in a classic fit with a twist" price_in_cents 790000 end end
module Merb module Static class Cookie # :api: private attr_reader :name, :value # :api: private def initialize(raw, default_host) # separate the name / value pair from the cookie options @name_value_raw, options = raw.split(/[;,] */n, 2) @name, @value = Merb::Parse.query(@name_value_raw, ';').to_a.first @options = Merb::Parse.query(options, ';') @options.delete_if { |k, v| !v || v.empty? } @options["domain"] ||= default_host end # :api: private def raw @name_value_raw end # :api: private def empty? @value.nil? || @value.empty? end # :api: private def domain @options["domain"] end # :api: private def path @options["path"] || "/" end # :api: private def expires Time.parse(@options["expires"]) if @options["expires"] end # :api: private def expired? expires && expires < Time.now end # :api: private def valid?(uri) uri.host =~ Regexp.new("#{Regexp.escape(domain)}$") && uri.path =~ Regexp.new("^#{Regexp.escape(path)}") end # :api: private def matches?(uri) ! expired? && valid?(uri) end # :api: private def <=>(other) # Orders the cookies from least specific to most [name, path, domain.reverse] <=> [other.name, other.path, other.domain.reverse] end end end end
class ApplicationController < App helpers AppHelper get "/" do @page = Page.find_by_slug_cached "home" erb :"pages/show" end # CLEAR CACHE post "/publish" do App.cache.flush redirect "/" end # Bypasses cache to show current changes # but does not clear the cache get "/preview" do @editing = true @page = Page.find_by_slug "home" erb :"pages/show" end # Bypasses cache to show current changes # but does not clear the cache get "/preview/:slug" do @editing = true @page = Page.find_by_slug params[:slug] erb :"pages/show" end get "/forms/:form" do if request.xhr? erb :"forms/#{form_from_params}", layout: false else erb :"forms/#{form_from_params}" end end post "/forms/signup" do # process signup form, save it to airtable @signup = Signup.new(signup_params) if @signup.save erb :"forms/thanks" else erb :"forms/signup" end end # shows the cached version of any page get "/:slug" do @page = Page.find_by_slug_cached(params[:slug]) || halt(404, erb(:"pages/404")) erb :"pages/show" end private def form_from_params if %w(signup).include?(params[:form]) params[:form] else halt 404 end end def signup_params params[:record].select{|key, val| ["Name", "Role", "School Name", "City", "Email", "Services"].include? key } end end
class AddExhibisionStateToItems < ActiveRecord::Migration[5.2] def change add_column :items,:exhibision_state, :integer,null:false end end
class AddScreenNameAndLocationToUsers < ActiveRecord::Migration def change change_table(:users) do |t| t.column :screen_name, :string, limit: 18 t.column :location, :string end end end
class AddEmailSnippetToOrdersAndGroups < ActiveRecord::Migration def change add_column :order_groups, :email_snippet, :text add_column :orders, :email_snippet, :text end end
Rails.application.routes.draw do get 'pages/aboutus' get 'pages/contact' devise_for :users, :controllers => { registrations: 'registrations' }, path: 'auth', path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unblock', registration: 'register', sign_up: 'cmon_let_me_in' } root :to => 'pages#home' get '/index' => 'pages#home' get '/links' => 'pages#links' get '/aboutus' => 'pages#aboutus' get '/contact' => 'pages#contact' get '/edit_user' => 'users#edit' get '/pages/display_selection' => 'pages#display_selection' get '/games/result' => 'games#result' get '/events/finishmatch' => 'events#finishmatch' post '/users' => 'pages#home' post '/edit_user' => 'users#edit' post '/events/:id' => 'events#finishmatch' resources :users # match 'users/:id', :to => 'users#show', :as => :profile # resources :edit_user resources :events resources :games resources :charges resources :chat_rooms, only: [:new, :create, :show, :index, :destroy] mount ActionCable.server => '/cable' root 'chat_rooms#index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require_relative "board" require_relative "piece" require_relative "human_player" require_relative "networked_player" class Checkers def initialize(player1, player2) @board = Board.new @color_of_current_player = :white @players = [player1, player2] end def run until game_over? @board.display move_loop @board.update @players.rotate! switch(@color_of_current_player) end @board.display puts "#{@players.first.name}, of the color #{@color_of_current_player}, has been defeated." end private def move_loop begin move = @players.first.choose_move(@board) from = move[0] raise "You're trying to move nothing..." if @board[from].nil? raise "Move your own piece!" if @board[from].color != @color_of_current_player @board.make_move(move) rescue StandardError => e puts e retry end end def switch(color) @color_of_current_player = (@color_of_current_player == :white) ? :black : :white end def game_over? # when there are no more pieces of color @color_of_current_player !@board.pieces.any? { |piece| piece.color == @color_of_current_player } end end if __FILE__ == $PROGRAM_NAME h1 = NetworkedPlayer.new("Mickey") h2 = NetworkedPlayer.new("Networked Player") Checkers.new(h1,h2).run end
module OpenActions class OpenAction # @private def self.demodulize(name) name.split('::').last end def self.inherited(klass) OpenActions.actions[demodulize(klass.to_s)] = klass end # @return [Hash] Accumulated config for this action type. def self.config @config ||= {} end # Declare a dependency on an auth provider. def self.user_auth(provider) config[:user_auth] ||= [] config[:user_auth] << provider end # Declare the structure of the form shown to leaders when creating the # action. The block is evaluated in the context of an OpenActions::FormSpec # object. def self.leader_fields(&block) fs = FormSpec.new fs.instance_eval(&block) config[:leader_fields] = fs.to_a end # Declare the structure of the form shown to users who are taking the # action. The block is evaluated in the context of an OpenActions::FormSpec # object. def self.action_taker_fields(&block) fs = FormSpec.new fs.instance_eval(&block) config[:action_taker_fields] = fs.to_a end # Declare strings of copy to be shown in the interface. The block is # evaluated in the context of an OpenActions::OpenAction::CopyDefinition # object. # TODO: Document which strings are needed. def self.copy_strings(&block) cd = CopyDefinition.new cd.instance_eval(&block) config[:copy_strings] = cd.to_h end # If an action needs to validate its leader fields or action-taker fields, # it can add errors in this method. # @param [Hash] data Data about the action, in the same format as # `take_action!`'s `data` parameter. # @param [ActiveModel::Errors] errors An object to add errors to. def validate_data(data, errors) # No-op by default -- subclasses should override. end # This method is given a data hash (with the same format as take_action!) # and an empty ActiveModel::Errors object. If an action needs to validate # its leader fields or action-taker fields, it can add errors in this # method. # @param [Hash] data Data about the action. This hash has keys for: # * each leader_field and action_taker_field. If there's a field repeated # between the two sets, we only pass in the action-taker value. # * each user_auth provider. For example, if the action contains # `user_auth :twitter`, the data hash will have a `:twitter` key whose # data is a hash of twitter-specific auth information (?). def take_action!(data) # No-op by default -- subclasses should override. end # @private class CopyDefinition def initialize @copy_strings = {} end def method_missing(name, str, *) @copy_strings[name] = str end def to_h @copy_strings end end end end
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Tests the LoggingInterceptor class. require 'minitest/autorun' require 'google/ads/google_ads' require 'google/ads/google_ads/interceptors/logging_interceptor' require 'google/ads/google_ads/v3/services/media_file_service_services_pb' class TestLoggingInterceptor < Minitest::Test attr_reader :sio attr_reader :logger attr_reader :li def setup @sio = StringIO.new @logger = Logger.new(sio) @li = Google::Ads::GoogleAds::Interceptors::LoggingInterceptor.new(logger) end def test_logging_interceptor_logs_na_customer_id_with_missing_customer_id li.request_response( request: make_request_with_no_customer_id, call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "CID: N/A") end def test_logging_interceptor_logs_customer_id customer_id = "123" li.request_response( request: make_request(customer_id: customer_id), call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "CID: #{customer_id}") end def test_logging_interceptor_logs_host host = "example.com" li.request_response( request: make_request, call: make_fake_call(host: host), method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "Host: #{host}") end def test_logging_interceptor_logs_method method = :method li.request_response( request: make_request, call: make_fake_call, method: method, ) do end sio.rewind assert_includes(sio.read, "Method: #{method}") end def test_logging_interceptor_inspects_request li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "Google::Ads::GoogleAds::V3::Services::MutateMediaFilesRequest") end def test_logging_interceptor_logs_isfault_no li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "IsFault: no") end def test_logging_interceptor_logs_isfault_yes_when_call_explodes li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do raise "boom" end rescue Exception => e if e.message != "boom" raise end sio.rewind assert_includes(sio.read, "IsFault: yes") end def test_logging_interceptor_logs_response li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do Google::Protobuf::StringValue.new(value: "some data") end sio.rewind assert_includes(sio.read, JSON.dump("some data")) end def test_logging_interceptor_logs_some_error_details_if_v3_error li.request_response( request: make_small_request, call: make_fake_call, method: :doesnt_matter, ) do raise make_realistic_error("v3") end rescue GRPC::InvalidArgument sio.rewind assert_includes(sio.read, "InvalidArgument(3:bees)") end def test_logging_interceptor_logs_error_details_if_partial_failure li.request_response( request: make_small_request, call: make_fake_call, method: :doesnt_matter, ) do make_realistic_response_with_partial_error end sio.rewind data = sio.read assert_includes(data, "Partial failure errors: ") assert_includes(data, "required field was not specified") end def test_logging_interceptor_can_serialize_images # this test segfaults the ruby virtual machine before c26ae44 li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter ) do end end def make_fake_call(host: "peer") Class.new do def initialize(host) @wrapped = Struct.new(:peer).new(host) end end.new(host) end def make_request_with_no_customer_id # this can be literally any protobuf type, because the class's descriptor # is the only method we cal Google::Protobuf::StringValue.new(value: "bees") end def make_realistic_response_with_partial_error Google::Ads::GoogleAds::V3::Services::MutateMediaFilesResponse.new( results: [], partial_failure_error: Google::Rpc::Status.new( code: 13, message: "Multiple errors in ‘details’. First error: A required field was not specified or is an empty string., at operations[0].create.type", details: [ Google::Protobuf::Any.new( type_url: "type.googleapis.com/google.ads.googleads.v3.errors.GoogleAdsFailure", value: "\nh\n\x03\xB0\x05\x06\x129A required field was not specified or is an empty string.\x1A\x02*\x00\"\"\x12\x0E\n\noperations\x12\x00\x12\b\n\x06create\x12\x06\n\x04type\n=\n\x02P\x02\x12\x1FAn internal error has occurred.\x1A\x02*\x00\"\x12\x12\x10\n\noperations\x12\x02\b\x01".b ) ] ) ) end def make_small_request(customer_id: "123") Google::Ads::GoogleAds::V3::Services::MutateMediaFilesRequest.new( customer_id: customer_id, operations: [ Google::Ads::GoogleAds::V3::Services::MediaFileOperation.new( create: Google::Ads::GoogleAds::V3::Resources::MediaFile.new( image: Google::Ads::GoogleAds::V3::Resources::MediaImage.new( data: Google::Protobuf::BytesValue.new( value: File.open("test/fixtures/sam.jpg", "rb").read[0..10] ) ) ) ) ] ) end def make_realistic_error(version) GRPC::InvalidArgument.new( "bees", make_error_metadata(version), ) end def make_error_metadata(version) { "google.rpc.debuginfo-bin" => "\x12\xA9\x02[ORIGINAL ERROR] generic::invalid_argument: Invalid customer ID 'INSERT_CUSTOMER_ID_HERE'. [google.rpc.error_details_ext] { details { type_url: \"type.googleapis.com/google.ads.googleads.v3.errors.GoogleAdsFailure\" value: \"\\n4\\n\\002\\010\\020\\022.Invalid customer ID \\'INSERT_CUSTOMER_ID_HERE\\'.\" } }", "request-id" =>"btwmoTYjaQE1UwVZnDCGAA", } end def make_request(customer_id: "123123123") Google::Ads::GoogleAds::V3::Services::MutateMediaFilesRequest.new( customer_id: customer_id, operations: [ Google::Ads::GoogleAds::V3::Services::MediaFileOperation.new( create: Google::Ads::GoogleAds::V3::Resources::MediaFile.new( image: Google::Ads::GoogleAds::V3::Resources::MediaImage.new( data: Google::Protobuf::BytesValue.new(value: File.open("test/fixtures/sam.jpg", "rb").read) ) ) ) ] ) end end
require 'mp3info' module Mediabumper # ID3 tags parsing library abstraction class TaggedFile def initialize(path) Mp3Info.open(path) do |mp3info| [:title, :artist, :album, :year].each do |key| instance_variable_set :"@#{key}", mp3info.tag.send(key) self.class.send :attr_reader, :"#{key}" end [:bitrate, :length, :vbr].each do |key| instance_variable_set :"@#{key}", mp3info.send(key) self.class.send :attr_reader, :"#{key}" end end end end end
# frozen_string_literal: true class User < ApplicationRecord authenticates_with_sorcery! has_many :body_scales, dependent: :destroy end # == Schema Information # # Table name: users # # id :integer not null, primary key # email :string not null # crypted_password :string # salt :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_users_on_email (email) UNIQUE #
if Rails.env.production? protocol = "https" end C2::Application.config.action_mailer.default_url_options ||= { host: AppParamCredentials.default_url_host, protocol: protocol || "http" } # indicate that this is not a real request in the email subjects, # if we are running in non-production env. # NOTE that staging uses Rails.env.production, so cannot rely on that config. unless ENV["DISABLE_SANDBOX_WARNING"] == "true" class PrefixEmailSubject def self.delivering_email(mail) mail.subject = "[TEST] " + mail.subject end end ActionMailer::Base.register_interceptor(PrefixEmailSubject) end # Register custom SES delivery method ActionMailer::Base.add_delivery_method :ses_mail_delivery, ::SesMailDelivery
module Wizardry module Questions # Ask a question that can be answered with one line of text class ShortAnswer < Wizardry::Questions::Answer def initialize(name) Rails.logger.debug("🧙 Adding short question '#{name}'") super end def form_method :govuk_text_field end end end end
class Translation < ActiveRecord::Base def translate! self.input_text ||= "" self.output_text = "" wordcount = input_text.split(" ").count (wordcount / 1.2).ceil.times do self.output_text += Emoji.random end return self.output_text end end
class EventsController < ApplicationController before_action :authenticate def index @events = Event.where('start_time > ?', Time.zone.now).order(:start_time) end def new @event = current_user.created_events.build end def create @event = current_user.created_events.build(event_parmas) if @event.save redirect_to @event, notice: 'Created event' else render :new end end def show @event = Event.find(params[:id]) end def edit @event = current_user.created_events.find(params[:id]) end def update @event = current_user.created_events.find(params[:id]) if @event.update(event_params) redirect_to @event, notice: 'Updated' else render :edit end end def destroy @event = current_user.created_events.find(params[:id]) @event.destroy! redirect_to root_path, notice: 'Deleted' end private def event_parmas params.require(:event).permit( :name, :place, :content, :start_time, :end_time ) end end
require 'formula' class Bwa < Formula homepage 'http://bio-bwa.sourceforge.net/' url 'http://downloads.sourceforge.net/project/bio-bwa/bwa-0.6.2.tar.bz2' sha1 'fd3d0666a89d189b642d6f1c4cfa9c29123c12bc' head 'https://github.com/lh3/bwa.git' # These inline functions cause undefined symbol errors with CLANG. # Fixed upstream for next release. See: # https://github.com/lh3/bwa/pull/11 def patches; DATA; end def install system "make", "CC=#{ENV.cc}", "CFLAGS=#{ENV.cflags}" bin.install "bwa" man1.install "bwa.1" end end __END__ diff --git a/bwt.c b/bwt.c index fcc141e..966b718 100644 --- a/bwt.c +++ b/bwt.c @@ -95,7 +95,7 @@ static inline int __occ_aux(uint64_t y, int c) return ((y + (y >> 4)) & 0xf0f0f0f0f0f0f0full) * 0x101010101010101ull >> 56; } -inline bwtint_t bwt_occ(const bwt_t *bwt, bwtint_t k, ubyte_t c) +bwtint_t bwt_occ(const bwt_t *bwt, bwtint_t k, ubyte_t c) { bwtint_t n, l, j; uint32_t *p; @@ -121,7 +121,7 @@ inline bwtint_t bwt_occ(const bwt_t *bwt, bwtint_t k, ubyte_t c) } // an analogy to bwt_occ() but more efficient, requiring k <= l -inline void bwt_2occ(const bwt_t *bwt, bwtint_t k, bwtint_t l, ubyte_t c, bwtint_t *ok, bwtint_t *ol) +void bwt_2occ(const bwt_t *bwt, bwtint_t k, bwtint_t l, ubyte_t c, bwtint_t *ok, bwtint_t *ol) { bwtint_t _k, _l; _k = (k >= bwt->primary)? k-1 : k; @@ -158,7 +158,7 @@ inline void bwt_2occ(const bwt_t *bwt, bwtint_t k, bwtint_t l, ubyte_t c, bwtint ((bwt)->cnt_table[(b)&0xff] + (bwt)->cnt_table[(b)>>8&0xff] \ + (bwt)->cnt_table[(b)>>16&0xff] + (bwt)->cnt_table[(b)>>24]) -inline void bwt_occ4(const bwt_t *bwt, bwtint_t k, bwtint_t cnt[4]) +void bwt_occ4(const bwt_t *bwt, bwtint_t k, bwtint_t cnt[4]) { bwtint_t l, j, x; uint32_t *p; @@ -178,7 +178,7 @@ inline void bwt_occ4(const bwt_t *bwt, bwtint_t k, bwtint_t cnt[4]) } // an analogy to bwt_occ4() but more efficient, requiring k <= l -inline void bwt_2occ4(const bwt_t *bwt, bwtint_t k, bwtint_t l, bwtint_t cntk[4], bwtint_t cntl[4]) +void bwt_2occ4(const bwt_t *bwt, bwtint_t k, bwtint_t l, bwtint_t cntk[4], bwtint_t cntl[4]) { bwtint_t _k, _l; _k = (k >= bwt->primary)? k-1 : k; diff --git a/bwt_lite.c b/bwt_lite.c index dd411e1..902e0fc 100644 --- a/bwt_lite.c +++ b/bwt_lite.c @@ -65,7 +65,7 @@ inline uint32_t bwtl_occ(const bwtl_t *bwt, uint32_t k, uint8_t c) if (c == 0) n -= 15 - (k&15); // corrected for the masked bits return n; } -inline void bwtl_occ4(const bwtl_t *bwt, uint32_t k, uint32_t cnt[4]) +void bwtl_occ4(const bwtl_t *bwt, uint32_t k, uint32_t cnt[4]) { uint32_t x, b; if (k == (uint32_t)(-1)) { @@ -80,7 +80,7 @@ inline void bwtl_occ4(const bwtl_t *bwt, uint32_t k, uint32_t cnt[4]) x -= 15 - (k&15); cnt[0] += x&0xff; cnt[1] += x>>8&0xff; cnt[2] += x>>16&0xff; cnt[3] += x>>24; } -inline void bwtl_2occ4(const bwtl_t *bwt, uint32_t k, uint32_t l, uint32_t cntk[4], uint32_t cntl[4]) +void bwtl_2occ4(const bwtl_t *bwt, uint32_t k, uint32_t l, uint32_t cntk[4], uint32_t cntl[4]) { bwtl_occ4(bwt, k, cntk); bwtl_occ4(bwt, l, cntl);
module Troles::Adapters::ActiveRecord module Strategy module BaseMany # @param [Class] the role subject class for which to include the Role strategy (fx User Account) # def self.included(base) base.send :include, Troles::Strategy::BaseMany end end end end
class CreateThings < ActiveRecord::Migration def change create_table :things do |t| t.string :description t.integer :vote_code, :null => false t.boolean :active, :default => true t.timestamps end add_index :things, :vote_code end end
class Event < ActiveRecord::Base attr_accessible :event_date, :event_address, :event_name, :event_end, :event_url, :event_author, :event_state, :event_zip_code, :event_description, :event_origin, :latitude, :longitude extend Geocoder::Model::ActiveRecord geocoded_by :full_address after_validation :geocode validates :event_name, :uniqueness => {:scope => :event_date} def full_address "#{event_address} #{event_state}" end def self.spn_events spn_events = [] spn_array = Event.where(event_origin: 'Silicon_Prairie_News').order(:event_date) spn_array.each do |event| if Time.now.yesterday <= event.event_date.to_s.slice(0..9) spn_events << event else next end end spn_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.lincoln_events lincoln_events = [] lincoln_array = Event.where(event_origin: 'Startup_Lincoln').order(:event_date) lincoln_array.each do |event| if Time.now.yesterday <= event.event_date.to_s.slice(0..9) lincoln_events << event else next end end lincoln_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.tech_omaha_events tech_omaha_events = [] tech_omaha_array = Event.where(event_origin: 'Tech_Omaha').order(:event_date) tech_omaha_array.each do |event| if Time.now.yesterday <= event.event_date.to_s.slice(0..9) tech_omaha_events << event else next end end tech_omaha_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.all_events all_events = [] Event.all.each do |event| if Time.now.yesterday <= event.event_date.to_s.slice(0..9) all_events << event else next end end all_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.same_week rest_of_weeks_events = [] Event.all.each do |event| if Time.now.yesterday <= event.event_date.to_s.slice(0..9) && event.event_date.to_s.slice(0..9) < Time.now.end_of_week rest_of_weeks_events << event else next end end rest_of_weeks_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.week_of_events weeks_events = [] Event.all.each do |event| if event.event_date.to_s.slice(0..9).between?(Time.now.beginning_of_week, Time.now.end_of_week) weeks_events << event else next end end weeks_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.events_today todays_events = [] Event.all.each do |event| if event.event_date.to_s.slice(0..9) >= Time.now.yesterday && event.event_date.to_s.slice(0..9) <= Time.now.tomorrow todays_events << event else next end end todays_events.sort { |a, b| a.event_date. <=> b.event_date } end def self.events_this_month months_events = [] Event.all.each do |event| if event.event_date.to_s.slice(5..6) == Time.now.month.to_s months_events << event else next end end months_events.sort { |a, b| a.event_date <=> b.event_date } end def self.events_by_month(month) events_for_month = [] Event.all.each do |event| if event.event_date.to_s.slice(5..6) == month.to_s events_for_month << event else next end end events_for_month.sort { |a, b| a.event_date. <=> b.event_date } end def self.past_events past_events = [] Event.all.each do |event| if event.event_date.to_s.slice(0..9) < Time.now past_events << event else next end end past_events.sort { |a, b| a.event_date. <=> b.event_date } end end
class Awarding < ActiveRecord::Base validates_presence_of :award, :year belongs_to :award module PeopleExtensions define_method("as") do |role| return self if role_name.blank? role_name = RoleType.its_name(role) self.scoped( # PostgreSQL doesn't allow forward references to joined tables. # Unfortunately, ActiveRecord merges the many scoped joins # in an unsuitable order. # We'll work around this with a CROSS JOIN + WHERE clause. #:joins => 'INNER JOIN role_types ON roles.role_type_id = role_types.id', #:conditions => { :role_types => { :name => role_name } }) :joins => [ 'CROSS JOIN role_types', 'CROSS JOIN awardings_movies' ], :conditions => [%{ awardings_movies.awarding_id = awardings_people.awarding_id AND awardings_movies.movie_id = roles.movie_id AND roles.role_type_id = role_types.id AND role_types.name = ?}, role_name] ) end include RoleTypeAssociationExtensions::Shortcuts end has_and_belongs_to_many :people, :include => :roles, :extend => PeopleExtensions has_and_belongs_to_many :movies named_scope :for_award, lambda { |award| { :joins => :award, :conditions => { :award_id => Award.awardize(award).self_and_descendants } } } def name "#{award.fullname} (#{year})" end def requirements award ? award.requirements : [] end def validate award.try(:validate_awarding, self) end def before_validation if year.blank? if movie = single_movie self.year = movie.release_year end end end def after_find readonly! end def single_movie return movies[0] if movies.size == 1 end private def create_or_update Awarding.transaction(:requires_new => true) do # The nested transaction is required as otherwise the failing # INSERT aborts the entire (outer) transaction. super end rescue ActiveRecord::RecordNotUnique => e errors.add_to_base('The award can only be given once per year.') false end end
class AddPokeTypeToCampaign < ActiveRecord::Migration def change add_column :campaigns, :poke_type, :string, default: 'email' end end
class UsersController < ApplicationController skip_before_action :verify_authenticity_token def new @user = User.new respond_to do |format| format.json { render json: {user: @user}, status: :ok } end end def show begin @user = User.find(params[:id]) respond_to do |format| format.json { render json: {user:@user}, status: :ok } end rescue ActiveRecord::RecordNotFound => e respond_to do |format| format.json { render json: {error:e.message}, status: :not_found} end end end def create @user = User.new(bank_params) respond_to do |format| if @user.save format.json { render json: { user: @user}, status: :created } else format.json { render json: @user.errors, status: :unprocessable_entity } end end end def destroy begin @user = User.find(params[:id]) respond_to do |format| @user.destroy format.json { render json: {}, status: :ok } end rescue ActiveRecord::RecordNotFound => e respond_to do |format| format.json { render json: {error:e.message}, status: :unprocessable_entity } end end end def index @user = User.all respond_to do |format| format.json { render json: {user:@user}, status: :ok } end end def edit begin @user = User.find(params[:id]) respond_to do |format| format.json { render json: {user:@user}, status: :ok } end rescue ActiveRecord::RecordNotFound => e respond_to do |format| format.json { render json: {error:e.message}, status: :not_found } end end end def update begin @user = User.find(params[:id]) respond_to do |format| if @user.update(bank_params) format.json { render json: {user:@user}, status: :ok } else format.json { render json: @user.errors, status: :unprocessable_entity } end end rescue => e respond_to do |format| format.json { render json: {error:e.message}, status: :unprocessable_entity } end end end private def user_params params.require(:user).permit(:name, :address, :phone_no) end end
require_relative './../../spec_helper.rb' describe MessageModule::RemoveService do describe '#call' do context "Valid ID" do before do message = create(:message) @removeService = MessageModule::RemoveService.new({"id" => message.id}) end it "Return success message" do response = @removeService.call() expect(response).to match("deleted successfully!") end it "Remove Message from database" do expect(Message.all.count).to eq(1) response = @removeService.call() expect(Message.all.count).to eq(0) end end context "Invalid ID" do it "return error message" do @removeService = MessageModule::RemoveService.new({"id" => rand(1..9999)}) response = @removeService.call() expect(response).to match("Invalid Question, verify ID!") end end end end
class Puppet::Provider::Rbac_api < Puppet::Provider require 'net/https' require 'uri' require 'json' require 'openssl' require 'yaml' CONFIGFILE = "#{Puppet.settings[:confdir]}/classifier.yaml" confine :exists => CONFIGFILE # This is autoloaded by the master, so rescue the permission exception. @config = YAML.load_file(CONFIGFILE) rescue {} @config = @config.first if @config.class == Array def self.build_auth(uri) https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true if Puppet::Util::Package.versioncmp(Puppet.version, '6.0') https.ssl_version = :TLSv1_2 else https.ssl_version = :TLSv1 end https.ca_file = Puppet.settings[:localcacert] https.key = OpenSSL::PKey::RSA.new(File.read(Puppet.settings[:hostprivkey])) https.cert = OpenSSL::X509::Certificate.new(File.read(Puppet.settings[:hostcert])) https.verify_mode = OpenSSL::SSL::VERIFY_PEER https end def self.make_uri(path, prefix = '/rbac-api/v1') uri = URI.parse("https://#{@config['server']}:#{@config['port']}#{prefix}#{path}") uri end def self.fetch_redirect(uri_str, limit = 10) raise ArgumentError, 'HTTP redirection has reached the limit beyond 10' if limit == 0 uri = make_uri(uri_str, nil) https = build_auth(uri) Puppet.debug "RBAC API: REDIRECT #{uri.request_uri}" request = Net::HTTP::Get.new(uri.request_uri) res = https.request(request) case res when Net::HTTPSuccess then res when Net::HTTPRedirection then fetch_redirect(res['location'], limit - 1) else raise Puppet::Error, "An RBAC API error occured: HTTP #{res.code}, #{res.to_hash.inspect}" end end def self.get_response(endpoint) uri = make_uri(endpoint) https = build_auth(uri) Puppet.debug "RBAC API: GET #{uri.request_uri}" request = Net::HTTP::Get.new(uri.request_uri) request['Content-Type'] = "application/json" res = https.request(request) raise Puppet::Error, "An RBAC API error occured: HTTP #{res.code}, #{res.body}" unless ['200'].include? res.code res_body = JSON.parse(res.body) res_body end def self.delete_response(endpoint) uri = make_uri(endpoint) https = build_auth(uri) Puppet.debug "RBAC API: DELETE #{uri.request_uri}" request = Net::HTTP::Delete.new(uri.request_uri) request['Content-Type'] = "application/json" res = https.request(request) raise Puppet::Error, "An RBAC API error occured: HTTP #{res.code}, #{res.body}" unless ['200', '204'].include? res.code end def self.put_response(endpoint, request_body) uri = make_uri(endpoint) https = build_auth(uri) Puppet.debug "RBAC API: PUT #{uri.request_uri}" request = Net::HTTP::Put.new(uri.request_uri) request['Content-Type'] = "application/json" request.body = request_body.to_json res = https.request(request) raise Puppet::Error, "An RBAC API error occured: HTTP #{res.code}, #{res.body}" unless ['200'].include? res.code end def self.post_response(endpoint, request_body) limit = 10 uri = make_uri(endpoint) https = build_auth(uri) Puppet.debug "RBAC API: POST #{uri.request_uri}" request = Net::HTTP::Post.new(uri.request_uri) request['Content-Type'] = "application/json" request.body = request_body.to_json res = https.request(request) case res when Net::HTTPSuccess then res when Net::HTTPRedirection then fetch_redirect(res['location'], limit - 1) else raise Puppet::Error, "An RBAC API error occured: HTTP #{res.code}, #{res.to_hash.inspect}" end end end
require_relative '../backend/rsync' module Susanoo module ServerSync module Syncers class Base include ActiveSupport::Configurable include ServerSync::Helpers::Loggable attr_accessor :server, :sync_files %i(src dest user priority).each do |attr| config_accessor attr define_method("#{attr}_with_proc") do val = self.send "#{attr}_without_proc" if val.respond_to?(:call) val.arity == 0 ? val.call : val.call(self) else val end end alias_method_chain attr, :proc end self.priority = 20 # Default def initialize(server, options = {}) @server = server @sync_files = Array(options[:sync_files]) end def run res = true log_prefix = "#{self.class.name}#run: Sync: Server '#{server}'" if sync_files.blank? logger.info("#{log_prefix}: Skip") else logger.info("#{log_prefix}: Begin") files = [] sync_files.each do |sync_file| sync_file = sync_file .gsub(%r{(?<!\*)\*\Z}, '**') .gsub(%r{(?<!/)/+\Z}, '/**') Pathname.new(sync_file).descend{|v| files << v.to_s} end files.uniq! rsync = ServerSync::Backend::Rsync.new(src: src, dest: dest) rsync_options = [] rsync_options << %Q{-aLz} # 15秒間隔で接続確認。3回失敗した場合は ssh を切断する。 rsync_options << %Q{-e 'ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=3'} rsync_options << %Q{--delete-after} rsync_options << %Q{--include-from=-} rsync_options << %Q{--exclude=*} result = rsync.push({server: server, user: user, options: rsync_options}, stdin_data: files.join("\n")) if result.success? res = true logger.info("#{log_prefix}: Done") else res = false logger.error("#{log_prefix}: Failed (exitcode #{result.exitcode})") unless result.output.blank? result.output.each_line do |line| logger.error(line.chop) end end end end res end end end end end
require 'spec_helper' describe Crypto::SecretBox do let (:key) { [0x1b,0x27,0x55,0x64,0x73,0xe9,0x85,0xd4,0x62,0xcd,0x51,0x19,0x7a,0x9a,0x46,0xc7, 0x60,0x09,0x54,0x9e,0xac,0x64,0x74,0xf2,0x06,0xc4,0xee,0x08,0x44,0xf6,0x83,0x89].pack('c*') } # from the nacl distribution context "new" do it "accepts strings" do expect { Crypto::SecretBox.new(key) }.to_not raise_error(Exception) end it "raises on a nil key" do expect { Crypto::SecretBox.new(nil) }.to raise_error(Crypto::LengthError, "Secret key was nil \(Expected #{Crypto::NaCl::SECRETKEYBYTES}\)") end it "raises on a short key" do expect { Crypto::SecretBox.new("hello") }.to raise_error(Crypto::LengthError, "Secret key was 5 bytes \(Expected #{Crypto::NaCl::SECRETKEYBYTES}\)") end end include_examples "box" do let(:box) { Crypto::SecretBox.new(key) } end end
class AssignmentsController < ApplicationController load_and_authorize_resource # GET /assignments # GET /assignments.json def index respond_to do |format| format.html # index.html.erb format.json { render json: @assignments } end end # GET /assignments/1 # GET /assignments/1.json def show @class_section = ClassSection.find(params[:class_section_id]) @role = Role.find(params[:role]) if !current_user.has_role(@role, @class_section) redirect_to '/error' return end @assignment = Assignment.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @assignment } end end # GET /assignments/1/edit def edit @assignment = Assignment.find(params[:assignment_id]) @role = Role.find(params[:role_id]) @class_section = ClassSection.find(params[:class_section_id]) if !current_user.has_role(@role, @class_section) redirect_to '/error' return end end # POST /assignments # POST /assignments.json def create @weight = Weight.find(params[:weight_id]) @assignment = Assignment.new(:title => params[:name], :weight => @weight) @role = Role.where(:id => params[:role_id]).first if !current_user.has_role(@role, @weight.class_section) redirect_to '/error' return end respond_to do |format| if @assignment.save format.html { redirect_to edit_assignment_with_params_path(@weight.class_section,@role,@assignment), notice: 'Assignment was successfully created.' } format.json { render json: @assignment, status: :created, location: @assignment } else format.html { render action: "new" } format.json { render json: @assignment.errors, status: :unprocessable_entity } end end end # PUT /assignments/1 # PUT /assignments/1.json def update @assignment = Assignment.find(params[:id]) if params[:assignment][:due_date] params[:assignment][:due_date] = Date.strptime(params[:assignment][:due_date], "%m/%d/%Y").strftime("%Y-%m-%d") end if params[:assignment][:weight] params[:assignment][:weight] = Weight.find(params[:assignment][:weight].to_i) end respond_to do |format| if @assignment.update_attributes(params[:assignment]) format.html { redirect_to @assignment, notice: 'Assignment was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @assignment.errors, status: :unprocessable_entity } end end end # DELETE /assignments/1 # DELETE /assignments/1.json def destroy @assignment = Assignment.find(params[:id]) @assignment.destroy respond_to do |format| format.html { redirect_to assignments_url } format.json { head :no_content } end end end
require 'test/unit' require 'cgiext' require 'cgi' class CGIExtTest < Test::Unit::TestCase def test_escape_html ## escape html characters input = '<>&"\'' expected = '&lt;&gt;&amp;&quot;\'' actual = CGIExt.escape_html(input) assert_equal(expected, actual) assert_equal(CGI.escapeHTML(input), actual) ## if no html characters found, return the passed argument as is input = 'foobar' expected = input actual = CGIExt.escape_html(input) assert_equal(expected, actual) assert_same(expected, actual) ## when non-string is passed, error raised input = nil assert_raise(TypeError) do CGIExt.escape_html(input) end input = 123 assert_raise(TypeError) do CGIExt.escape_html(input) end end def test_escape_html! ## escape html characters input = '<>&"\'' expected = '&lt;&gt;&amp;&quot;\'' actual = CGIExt.escape_html!(input) assert_equal(expected, actual) assert_equal(CGI.escapeHTML(input), actual) ## if no html characters found, return the string as is input = 'foobar' expected = input actual = CGIExt.escape_html!(input) assert_equal(expected, actual) assert_same(expected, actual) ## non-string value are converted into string input = nil expected = '' actual = CGIExt.escape_html!(input) assert_equal(expected, actual) input = 123 expected = '123' actual = CGIExt.escape_html!(input) assert_equal(expected, actual) end def test_unescape_html ## unescape html characters [ ## html entities ('<>&"') ['&lt;&gt;&amp;&quot;', '<>&"'], ## other html entities (ex. '&copy;') ['&copy;&heart;', '&copy;&heart;'], ## '&#99' format ['&#34;&#38;&#39;&#60;&#62;', '"&\'<>'], ## '&#x9999' format ['&#x0022;&#x0026;&#x0027;&#x003c;&#x003E;', '"&\'<>'], ## invalid format ['&&lt;&amp&gt;&quot&abcdefghijklmn', '&<&amp>&quot&abcdefghijklmn'], ].each do |input, expected| actual = CGIExt.unescape_html(input) assert_equal(expected, actual) assert_equal(CGI.unescapeHTML(input), actual) end ## return as-is when no html entity found input = "foobar" expected = input actual = CGIExt.unescape_html(input) assert_equal(expected, actual) assert_same(expected, actual) ## when non-string is passed, error raised input = nil assert_raise(TypeError) do CGIExt.unescape_html(input) end input = 123 assert_raise(TypeError) do CGIExt.unescape_html(input) end end TESTDATA_FOR_ESCAPE_URL = [ ## example data ["'Stop!' said Fred._-+", '%27Stop%21%27+said+Fred._-%2B'], ## characters not to be escaped ["abcdefgxyzABCDEFGXYZ0123456789_.-", "abcdefgxyzABCDEFGXYZ0123456789_.-"], ## characters to be escaped [' !"#$%&\'()*+,/:;<=>?@[\\]^`{|}~', "+%21%22%23%24%25%26%27%28%29%2A%2B%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D%7E"], ## '%' format ["k[]", 'k%5B%5D'], ## unicode characters ["\244\242\244\244\244\246\244\250\244\252", "%A4%A2%A4%A4%A4%A6%A4%A8%A4%AA"], ] def test_escape_url ## encode url string testdata = TESTDATA_FOR_ESCAPE_URL + [ ## containing '%' character ["%XX%5%%%", "%25XX%255%25%25%25"], ] testdata.each do |input, expected| actual = CGIExt.escape_url(input) assert_equal(expected, actual) assert_equal(CGI.escape(input), actual) #assert_equal(expected, CGI.escape(input)) end ## error when non-string assert_raise(TypeError) do CGIExt.escape_url(nil) end assert_raise(TypeError) do CGIExt.escape_url(123) end end def test_unescape_url ## decode url string testdata = TESTDATA_FOR_ESCAPE_URL + [ ## invalid '%' format ["%XX%5%%%", "%XX%5%%%"], ## combination of lower case and upper case ["\244\252", "%a4%Aa"], ] testdata.each do |expected, input| actual = CGIExt.unescape_url(input) assert_equal(expected, actual) assert_equal(CGI.unescape(input), actual) #assert_equal(expected, CGI.unescape(input)) end ## error when non-string assert_raise(TypeError) do CGIExt.unescape_url(nil) end assert_raise(TypeError) do CGIExt.unescape_url(123) end end def test_parse_query_string actual = nil ## equal with CGI.parse() [ ## '&' separator ['a=10&b=20&key1=val1', {'a'=>['10'], 'b'=>['20'], 'key1'=>['val1']} ], ## ';' separator ['a=10;b=20;key1=val1', {'a'=>['10'], 'b'=>['20'], 'key1'=>['val1']} ], ## same keys ['a=1&a=2&a=3', {'a'=>['1', '2', '3']} ], ## no value ['key=&key=', {'key'=>['', '']} ], ## unescape ascii string ['k%5B%5D=%5B%5D%26%3B', {'k[]'=>['[]&;']} ], ## unescape unicode string ["%A4%A2%a4%a4=%A4%a6%A4%A8%A4%Aa", {"\244\242\244\244"=>["\244\246\244\250\244\252"]} ], ## invalid '%' format ['k%XX%5=%%%', {'k%XX%5'=>['%%%']} ], ].each do |input, expected| actual = CGIExt.parse_query_string(input) assert_equal(expected, actual) assert_equal(CGI.parse(input), actual) end ## different with CGI.parse() [ ## without '=' (CGI: {"a"=>[nil], "b"=>[nil]}) ['a&b', {'a'=>[''], 'b'=>['']} ], ## no key (CGI: {""=>["a", "b"], nil=>[nil]}) ['&=a&=b', {''=>['', 'a', 'b']} ], ## invalid format (CGI: {"a"=>[""], "b"=>[nil]}) ['a=&b&&', {'a'=>[''], 'b'=>[''], ''=>['', '']} ], ].each do |input, expected| actual = CGIExt.parse_query_string(input) assert_equal(expected, actual) #assert_equal(CGI.parse(input), actual) end ## default value is frozen empty array assert_equal(actual['unknownkey'], []) assert_raise(TypeError) do actual['unknownkey'] << 'foo' end end def test_rparse_query_string actual = nil ## equal with CGI.parse() [ ## '&' separator ['a=10&b=20&key1=val1', {'a'=>'10', 'b'=>'20', 'key1'=>'val1'} ], ## ';' separator ['a=10;b=20;key1=val1', {'a'=>'10', 'b'=>'20', 'key1'=>'val1'} ], ## same keys ['a=1&a=2&a=3', {'a'=>'1'} ], ## no value ['key=&key=', {'key'=>''} ], ## unescape ascii string ['k%5B%5D=%5B%5D%26%3B', {'k[]'=>'[]&;'} ], ## unescape unicode string ["%A4%A2%a4%a4=%A4%a6%A4%A8%A4%Aa", {"\244\242\244\244"=>"\244\246\244\250\244\252"} ], ## invalid '%' format ['k%XX%5=%%%', {'k%XX%5'=>'%%%'} ], ].each do |input, expected| actual = CGIExt.rparse_query_string(input) assert_equal(expected, actual) #assert_equal(CGI.parse(input), actual) end ## different with CGI.parse() [ ## without '=' (CGI: {"a"=>nil, "b"=>nil}) ['a&b', {'a'=>'', 'b'=>''} ], ## invalid format (CGI: {"a"=>[""], "b"=>[nil]}) ['a=&b&&', {'a'=>'', 'b'=>'', ''=>''} ], ].each do |input, expected| actual = CGIExt.rparse_query_string(input) assert_equal(expected, actual) #assert_equal(CGI.parse(input), actual) end ## default value is frozen empty array assert_equal(actual['unknownkey'], []) assert_raise(TypeError) do actual['unknownkey'] << 'foo' end end end
class PriorityQueue def initialize @heap = [] end def add!(x) @heap << x sift_up(@heap.length - 1) self end def peek @heap[0] end def remove!() raise RuntimeError, "Empty Queue" if @heap.length == 0 if @heap.length == 1 @heap = [] else @heap[0] = @heap.pop sift_down(0) end self end def to_s @heap.to_s end private # Sift up the element at index i def sift_up(i) parent = (i - 1) / 2 if parent >= 0 and @heap[parent] > @heap[i] @heap[parent], @heap[i] = @heap[i], @heap[parent] sift_up(parent) end end # Sift down the element at index i def sift_down(i) child = (i * 2) + 1 return if child >= @heap.length child += 1 if child + 1 < @heap.length and @heap[child] > @heap[child+1] if @heap[i] > @heap[child] @heap[child], @heap[i] = @heap[i], @heap[child] sift_down(child) end end end
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'rubygems' require 'rest_client' require 'cgi' require 'yaml' module Mediawiki VERSION = '0.0.4' def self.search_for_html(wiki_host, term) RestClient.get "#{wiki_host}/wiki/Special:Search?search=#{URI.encode(term)}" end def self.article_properties(wiki_host, page) YAML.load(RestClient.get api_url(wiki_host, "query", "titles=#{URI.encode(page)}", "prop=info")) end def self.last_modified(wiki_host, page) # can't seem to find evidence that the query will ever return # more than one page. Conveniently returns nil on pages that # do not exist/throw errors. self.article_properties(wiki_host, page)["query"]["pages"][0]["lastrevid"] end def self.login(wiki_host, user, password) result = YAML.load RestClient.post api_url(wiki_host, "login"), :lgname => user, :lgpassword => password return nil unless result["login"]["result"] == "Success" result = result["login"] prefix = result["cookieprefix"] # http://www.mediawiki.org/wiki/API:Login # And, lo, I pronounce thee "#{prefix}UserName=#{result["lgusername"]}; " + "#{prefix}UserId=#{result["lguserid"].strip}; " + "#{prefix}Token=#{result["lgtoken"]}; "+ "#{prefix}_session=#{result["sessionid"]}" end # currently, #edit & #markup are less than awesome: these will # fail silently if the title you're looking up has any redirects, # and they will not warn you about disambiguations. Ideally, # (aka later on), these methods will only take pageids after a # lookup and/or disambiguation is performed def self.edit(wiki_host, title, text, summary, cookie) e_title = URI::escape(title) token = YAML.load(RestClient.get api_url(wiki_host, "query", "prop=info%7Crevisions", "intoken=edit", "titles=#{e_title}"), :Cookie => cookie)["query"]["pages"][0]["edittoken"] e_token, e_text, e_summary = CGI::escape(token), CGI::escape(text), CGI::escape(summary) server_response = RestClient.post(api_url(wiki_host, "edit", "title=#{e_title}", "text=#{e_text}", "token=#{e_token}"), "", :Cookie => cookie) # basically, the only way for this to fail is if you have a wrong cookie return nil unless server_response.include?("Success") server_response end # http://www.mediawiki.org/wiki/API:Query_-_Properties#revisions_.2F_rv def self.markup(wiki_host, title) response = YAML.load(RestClient.get(api_url(wiki_host, "query", "prop=revisions", "titles=#{URI::escape(title)}", "rvprop=content"))) # we only request one page, and only one revision # returns nil on errors response["query"]["pages"][0]["revisions"][0]['*'] end private def self.api_url(wiki_host, action, *options) if options.first.is_a? Hash options = options.first.collect do |key, value| "#{key}=#{CGI::escape(value)}" end end # combine the options with an ampersand extra_url_params_string = options.collect { |i| "&" + i }.to_s return "#{wiki_host}/w/api.php?action=#{action}&format=yaml" + extra_url_params_string end end
module Boilerpipe::SAX class BoilerpipeHTMLParser def self.parse(text) # strip out tags that cause issues text = Preprocessor.strip(text) # use nokogiri to fix any bad tags, errors - keep experimenting with this text = Nokogiri::HTML(text).to_html handler = HTMLContentHandler.new noko_parser = Nokogiri::HTML::SAX::Parser.new(handler) noko_parser.parse(text) handler.text_document end end end
module Errors class AuthenticationMissing < StandardError; end class AppMissing < StandardError; end end
class InstructorsController < ApplicationController def show @instructor = Instructor.find(params[:id]) @courses = @instructor.courses end end
class StoresController < ApplicationController def index @stores = Store.all end def new @store = Store.new end def create @store= Store.new(store_params) if @store.save redirect_to stores_url else puts @store.errors.full_messages render :edit end end def edit @store = Store.find(params[:id]) end def update @store = Store.find(params[:id]) @store.update(store_params) if @store.save redirect_to stores_url else puts @store.errors.full_messages render :edit end end private def store_params params.require(:store).permit(:name) end end
require './input_functions' require 'colorize' # gem install colorize require 'spreadsheet' # gem install spreadsheet class Track attr_accessor :id, :title, :location def initialize (id, title, location) @id = id @title = title @location = location end end class Album attr_accessor :id, :title, :artist, :genre, :tracks, :updated def initialize (id, title, artist, genre, tracks) @id = id @title = title @artist = artist @genre = genre @tracks = tracks @updated = false end end # ============================================================= # Menu # ============================================================= # Main menu def main_menu finished = false begin puts ' Text Music Player '.colorize(:color => :black, :background => :yellow) puts puts ' Main Menu: '.colorize(:color => :while, :background => :blue) puts '1 - Read in Album '.colorize(:color => :black, :background => :white) puts '2 - Display Albums Info '.colorize(:color => :black, :background => :white) puts '3 - Play Album '.colorize(:color => :black, :background => :white) puts '4 - Update Album '.colorize(:color => :black, :background => :white) puts '5 - Exit '.colorize(:color => :black, :background => :white) choice = read_integer_in_range("Option: ", 1, 5) case choice when 1 database_file = read_file albums = read_albums(database_file) when 2 if validate(albums) print_albums_info(albums) end when 3 if validate(albums) play_album(albums) end when 4 if validate(albums) select_update_album(albums) end else if isUpdated(albums) puts 'Updating album file infomation..' end finished = true end end until finished end # Read File def read_file system "clear" or system "cls" finished = false begin puts " Enter Album ".colorize(:color => :white, :background => :blue) puts " Enter the filename of the music library ".colorize(:color => :black, :background => :white) puts Spreadsheet.client_encoding = 'UTF-8' location = read_string("File name: ") database = Spreadsheet.open location puts "Music Library Loaded ".colorize(:color => :green) read_string("Press ENTER.... ") finished = true system "clear" or system "cls" end until finished database end # ============================================================= # Read Album Data # ============================================================= # Album # Read Albums def read_albums database_file album_database = database_file.worksheets albums = Array.new count = album_database.length.to_i i = 0 while i < count album = read_album(album_database[i]) albums << album i += 1 end albums end # Read Album def read_album album_data album_id = album_data[0,1].to_i #=> 0: Row - 1:Column album_title = album_data[0,2].to_s album_artist = album_data[0,3].to_s album_genre = album_data[0,4].to_s tracks = read_tracks(album_data) album = Album.new(album_id ,album_title, album_artist, album_genre, tracks) album end # Track # Read Tracks def read_tracks album_data count = album_data[0,0].to_i + 1 tracks = Array.new i = 1 while i < count track = read_track(i, album_data) tracks << track i += 1 end tracks end def read_track (index, album_data) id = album_data[index, 0].to_i title = album_data[index, 1].to_s location = album_data[index, 2].to_s track = Track.new(id, title, location) track end # ============================================================= # Display Album Data # ============================================================= # Album def print_albums_info albums system "clear" or system "cls" puts add_space(' Albums').colorize(:color => :white, :background => :blue) i = 0 while i < albums.length album = albums[i] id = ' Album ID: ' + album.id.to_s genre = ' -= ' + album.genre + ' =-' title = ' > ' + album.title + ' by ' + album.artist puts add_space(' ').colorize(:color => :black, :background => :white) puts add_space(id).colorize(:color => :black, :background => :white) puts add_space(genre).colorize(:color => :red, :background => :white) puts add_space(title).colorize(:color => :red, :background => :white) i+=1 end read_string("Press ENTER to continue.... ") system "clear" or system "cls" end def print_album_info album system "clear" or system "cls" puts add_space(' Albums').colorize(:color => :white, :background => :blue) id = ' Album ID: ' + album.id.to_s genre = ' -= ' + album.genre + ' =-' title = ' > ' + album.title + ' by ' + album.artist puts add_space(' ').colorize(:color => :black, :background => :white) puts add_space(id).colorize(:color => :black, :background => :white) puts add_space(genre).colorize(:color => :red, :background => :white) puts add_space(title).colorize(:color => :red, :background => :white) read_string("Press ENTER to continue.... ") system "clear" or system "cls" end def print_track_list album system "clear" or system "cls" puts add_space(' Track List').colorize(:color => :white, :background => :blue) i = 0 while i < album.tracks.length track = album.tracks[i] text = ' ' + track.id.to_s + ' - ' + track.title puts add_space(text).colorize(:color => :red, :background => :white) i += 1 end end def add_space string added_space_string = string if string.length < 60 count = 60 - string.length i = 0 while i < count added_space_string += ' ' i += 1 end end added_space_string end # ============================================================= # Play Album # ============================================================= def play_album albums id = read_integer('Album ID: ') valid, index = validate_id(id ,albums) if valid album = albums[index] print_track_list(album) play_track(album) else system "clear" or system "cls" end end def play_track (album) selected_track = read_integer_in_range("Play Track: ", 1, album.tracks.length) track = album.tracks[selected_track - 1] system "clear" or system "cls" puts add_space(' Playing').colorize(:color => :white, :background => :blue) puts add_space(' ').colorize(:color => :black, :background => :white) puts add_space(' ALBUM: ' + album.title).colorize(:color => :black, :background => :white) puts add_space(' ' + track.title).colorize(:color => :black, :background => :white) puts add_space(' ').colorize(:color => :black, :background => :white) command_string = 'open ' + track.location system(command_string) read_string("Press ENTER to continue.... ") system "clear" or system "cls" end # ============================================================= # Update Album # ============================================================= def select_update_album albums system "clear" or system "cls" puts add_space(' Update Album').colorize(:color => :white, :background => :blue) puts add_space(' ').colorize(:color => :black, :background => :white) puts add_space(' Update an album\'s info.').colorize(:color => :black, :background => :white) puts add_space(' ').colorize(:color => :black, :background => :white) album_id = read_integer('Album ID: ') i = 0 found = false while i < albums.length if album_id == albums[i].id found = true update_album(albums[i]) end i += 1 end if found == false puts "Unable to find an album with id: " + album_id.to_s read_string("Press ENTER to go back.... ") end system "clear" or system "cls" finished = true end def update_album album system "clear" or system "cls" finished = false begin puts add_space(' Update Album').colorize(:color => :white, :background => :blue) puts add_space('1 - Update Title').colorize(:color => :black, :background => :white) puts add_space('2 - Update Genre').colorize(:color => :black, :background => :white) puts add_space('3 - Update ID').colorize(:color => :black, :background => :white) puts add_space('4 - Back').colorize(:color => :black, :background => :white) choice = read_integer_in_range("Option: ", 1, 4) case choice when 1 update_album_title(album) when 2 update_album_genre(album) when 3 update_album_id(album) else finished = true end end until finished end def update_album_title album new_title = read_string('New Title: ') album.title = new_title album.updated = true print_album_info(album) end def update_album_genre album new_genre = read_string('New Genre: ') album.genre = new_genre album.updated = true print_album_info(album) end def update_album_id album new_id = read_integer('New ID: ') album.id = new_id album.updated = true print_album_info(album) end def isUpdated albums i = 0 updated = false if albums != nil count = albums.length while i < count if albums[i].updated == true updated = true end i += 1 end end updated end def validate albums valid = false if albums != nil valid = true else puts 'Please "Read in Album" first.' valid = false end valid end def validate_id (id, albums) valid = false index = -1 i = 0 count = albums.length while i < count if albums[i].id == id valid = true index = i break end i += 1 end return valid, index end def main system "clear" or system "cls" main_menu end main
class ChangeColumnsOnInvoicesForCurrency < ActiveRecord::Migration def change remove_column :invoices, :exchange_rate add_column :invoices, :exchange_rate, :decimal end end
module SecureAttachable extend ActiveSupport::Concern included do before_save :assign_asset_key end def assign_asset_key # self.asset_key ||= generate_asset_key end def generate_asset_key SecureRandom.hex(10) end module ClassMethods def validates_image_attachment attribute validates_attachment_content_type attribute, content_type: /\Aimage\/.*\Z/ end end end
class RemoveProfileFromSchoolChild < ActiveRecord::Migration[5.1] def change remove_reference :school_children, :profile, foreign_key: true end end
require 'csv' require 'xmlsimple' # Compare XML and CSV Result module ParseFile def ParseFile.parser_csv_by_filename filename start_parse = false result = [] CSV.foreach(filename) do |row| if start_parse == true result.push(row.drop(1)) elsif row.length > 1 start_parse = true end end result.uniq! end def ParseFile.parser_xml_by_filename filename ignore_row_header = ['Report Name', 'Period', 'Time', 'Resource Name', 'TopN', 'Counter', 'Granularity'] data = XmlSimple.xml_in(filename, { 'KeyAttr' => {'Worksheet' => 'ss:Name'}, 'GroupTags' => { 'Row' => 'Cell' }, 'ForceArray' => false}) result = {} worksheet_list = data['Worksheet'].select{|key, value| key.include?('Last')} worksheet_list.each do |name, worksheet| result[name] = [] row_list = worksheet['Table']['Row'] row_list.each do |row| ary = [] row['Cell'].each do |cell| break if ignore_row_header.include?(cell['Data']['content']) ary << cell['Data']['content'] end result[name] << ary if !ary.empty? end end result end private def print_msg data, level return if level > 3 def handle_value key, value, level if value.is_a?(String) puts " " * level << "%s -- %s" % [key, value] elsif value.is_a?(Hash) puts " " * level << "%s => {" % key print_msg value, level+1 puts " " * level << "}" elsif value.is_a?(Array) puts " " * level << "%s => [" % key print_msg value, level+1 puts " " * level << "]" end end if data.is_a?(Hash) data.each{|key, value| handle_value(key, value, level)} elsif data.is_a?(Array) data.each{|value| handle_value(nil, value, level)} end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "nritholtz/ubuntu-14.04.1" config.vm.hostname = "Teamscale-DEMO-VM" #Display settings config.vm.provider "virtualbox" do |vb| #Display the VirtualBox GUI when booting the machine vb.gui = true # Customize the amount of memory on the VM and disable USB vb.memory = "2048" vb.name = "teamscale" vb.customize ["modifyvm", :id, "--clipboard", "bidirectional"] vb.customize ["modifyvm", :id, "--usb", "off"] vb.customize ["modifyvm", :id, "--usbehci", "off"] end #Provisions to be added to the VM config.vm.provision "shell", privileged: false, inline: <<-SHELL #ubuntu update and install desktop sudo apt-get update -y # Remove unwanted icons from Launcher cd /usr/share/applications && sudo rm -f libreoffice-writer.desktop libreoffice-calc.desktop libreoffice-impress.desktop ubuntu-software-center.desktop ubuntu-amazon-default.desktop #java, maven and eclipse install sudo echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections sudo add-apt-repository ppa:webupd8team/java -y sudo apt-get install oracle-java8-installer -y sudo wget --no-check-certificate https://github.com/aglover/ubuntu-equip/raw/master/equip_java8.sh && bash equip_java8.sh sudo apt-get install maven -y sudo wget -O /opt/eclipse-java-luna-SR2-linux-gtk.tar.gz http://ftp.fau.de/eclipse/technology/epp/downloads/release/luna/SR2/eclipse-java-luna-SR2-linux-gtk.tar.gz cd /opt/ && sudo tar -zxvf eclipse-*.tar.gz #teamscale installation sudo wget -O /home/vagrant/teamscale-v1.6.0.zip https://www.cqse.eu/download/teamscale/teamscale-v1.6.0.zip unzip /home/vagrant/teamscale-v1.6.0.zip -d /home/vagrant/Desktop/teamscale-v1.6.0 wget -O /home/vagrant/Desktop/teamscale-v1.6.0/teamscale/teamscale.license https://raw.githubusercontent.com/SoftwareEngineeringToolDemos/ICSE-2014-Teamscale/master/build-vm/teamscale.license #extract VM files to desktop sudo chmod 777 /vagrant/* sudo cp /vagrant/*.jar /opt/eclipse/plugins/ unzip /vagrant/Teamscale_VM_Desktop_Files.zip -d /home/vagrant/Desktop/ chmod +x /home/vagrant/Desktop/*.desktop # Import spring-petclinic Project to Eclipse mkdir /home/vagrant/workspace/ sudo apt-get install git -y cd /home/vagrant/ && git clone https://github.com/spring-projects/spring-petclinic.git cd /home/vagrant/spring-petclinic/ && mvn eclipse:eclipse # Add Eclipse to startup applications before reloading VM sudo chfn -f "vagrant" vagrant mkdir -p /home/vagrant/.config/autostart/ cp /home/vagrant/Desktop/Eclipse.desktop /home/vagrant/.config/autostart/ mv /home/vagrant/Desktop/teamscale*.desktop /home/vagrant/.config/autostart/ SHELL config.vm.provision :reload end
require './square.rb' # Represents the chessboard, containing individual squares class Board attr_accessor :squares, :visited, :edge_to # Creates the board with the necessary connections def initialize @squares = [] @visited = [] @edge_to = {} for i in 0..7 for j in 0..7 @squares << Square.new([i, j]) end end @squares.each {|square| square.generate_connections} end def square_coordinate(coordinates) @squares.each {|square| return square if square.coordinates == coordinates} end def bfs(start) # First step: Put the first node into a queue and mark it as visited queue = [] queue << square_coordinate(start) @visited << square_coordinate(start) # Second step: Repeat until the queue is empty: # - Remove the least recently added node n # - add each of n's unvisited connections to the queue and mark them as visited while queue.any? current_node = queue.shift current_node.connections.each do |adjacent_node| next if @visited.include? square_coordinate(adjacent_node) queue << square_coordinate(adjacent_node) @visited << square_coordinate(adjacent_node) @edge_to[square_coordinate(adjacent_node)] = current_node end end end def knight_moves(start_coordinates, target_coordinates) bfs(start_coordinates) path = [] start = square_coordinate(start_coordinates) current = square_coordinate(target_coordinates) while current.coordinates != start.coordinates do path.unshift(current) # Unshift adds the node to the beginning of the array current = @edge_to[current] end path.unshift(start) puts path end end
class CreateBottoms < ActiveRecord::Migration[6.0] def change create_table :bottoms do |t| t.string :clothing t.timestamps end end end
class Admin::UserKidsController < Admin::BaseController def new @kid = Kid.find(params[:kid_id]) @user_kid = UserKid.new() @users = User.all end def create kid = Kid.find(params[:user_kid][:kid_id]) new_link = UserKid.new(user_kid_params) unless new_link.save flash.alert = "User could not be saved!" end redirect_to admin_kid_path(kid) end def destroy kid = Kid.find(params[:kid_id]) user = User.find(params[:user_id]) user_kid = UserKid.find_by(user_id: user.id, kid_id: kid.id) if user_kid.delete flash.notice = "User removed from this kid." else flash.alert = "Could not remove user, please try again." end redirect_to admin_kid_path(kid) end private def user_kid_params params.require(:user_kid).permit(:user_id, :kid_id) end end
Gem::Specification.new do |s| s.name = 'random_string_generator' s.version = '0.0.1' s.date = '2014-01-11' s.summary = "A gem to generate random strings" s.description = "This gem is a great way to generate random strings in Ruby" s.authors = ["Anuja Kelkar"] s.email = 'anujamkelkar@gmail.com' s.files = ["lib/random_string_generator.rb"] s.homepage = 'http://rubygems.org/gems/random_string_generator' s.add_development_dependency 'rspec' end
default['vault_certificate'] = { # The cipher that will be used to encrypt the key when :key_encryption_password is set. 'key_encryption_cipher' => 'AES-256-CBC', 'always_ask_vault' => false, # The owner of the subfolders, the certificate, the chain and the private key 'owner' => 'root', # The group of the subfolders, the certificate, the chain and the private key 'group' => 'root', } default['vault_certificate']['ssl_path'] = case node['platform_family'] when 'rhel', 'fedora' '/etc/pki/tls' when 'smartos' '/opt/local/etc/openssl' else '/etc/ssl' end
require 'spec_helper' describe RCI do it 'has a version number' do expect(RCI::VERSION).not_to be nil end end
class Entity < ActiveRecord::Base has_many :transactions has_one :company, :through => :transactions has_many :sales, :foreign_key => :seller_id, :class_name => "Transaction" has_many :sellers, :through => :sales has_many :securities, :through => :transactions has_one :pass has_one :ce_link def sec #entitiy's securities' id's if self.name == "Option Pool" self.securities.uniq.map {|i| i.id} else self.securities.uniq.map {|i| i.id}.select{|j| Security.find(j).shares(self.id) > 0} end end #does the entity have shares? def has_shares? if self.name == "Option Pool" self.sec.size > 0 else self.sec.map{|s| Security.find(s).shares(self.id)}.sum > 0 end end #shares in company on fully diluted basis def shares self.securities.uniq.map{|i| i.shares(self.id)}.sum end # % ownership in company on fully diluted basis def percent 100*(self.shares/self.company.shares.to_f) end end
namespace :dev do def show_sppiner(msg_start, msg_end = "Concluído!") spinner = TTY::Spinner.new("[:spinner] #{msg_start}...") spinner.auto_spin yield spinner.success("(#{msg_end})") end desc 'Popula banco de dados' task popula_db: :environment do if Rails.env.development? # Popula --------- show_sppiner("Adicionando Categorias...") do %x{rails dev:add_categories} end show_sppiner("Adicionando Serviços...") do %x{rails dev:add_services} end end end desc 'Cadastro de Orgaos' task add_orgaos: :environment do orgaos = [ { description: 'SEFAZ' }, { description: 'SEMAH' } ] orgaos.each do |orgao| Orgao.find_or_create_by!(orgao) end end desc 'Cadastro de Categories' task add_categories: :environment do categories = [ { description: 'Agricultura e Pecuária' }, { description: 'Assistência Social' }, { description: 'Ciência e Tecnologia' }, { description: 'Comunicações e Transparência Pública' }, { description: 'Cultura, Artes, História e Esportes' }, { description: 'Educação e Pesquisa' }, { description: 'Empresa, Indústria e Comércio' }, { description: 'Energia, Minerais e Combustíveis' }, { description: 'Finanças, Impostos e Gestão Pública' }, { description: 'Forças Armadas e Defesa Civil' }, { description: 'Justiça e Segurança' }, { description: 'Meio Ambiente e Clima' }, { description: 'Saúde e Vigilância Sanitária' }, { description: 'Trabalho e Previdência' }, { description: 'Trânsito e Transportes' }, { description: 'Viagens e Turismo' } ] categories.each do |category| Category.find_or_create_by!(category) end end desc 'Cadastro de Serviços' task add_services: :environment do services_params = [] (1..10).each do |i| orgao = Orgao.all.select {|o| o.desc_unid_gestora != "-"}.sample services_params << { "id_unid_gestora" => orgao.id_unid_gestora, "sigla_orgao" => orgao.sigla, "orgao_name" => orgao.desc_unid_gestora, "title" => "Titulo do Serviço s#{i}", "category_ids" => Category.all.limit(3).map {|c| c.id}, "service_type" => "digital", "main_link" => "https://www.google.com/", "status" => "ativo", "visibility" => "externo", "responsible" => "responsável", "witch_is" => "O que é o serviço s#{i}", "how_to_use" => ".", "who_can_use" => ".", "eventuais_custos" => ".", "principais_etapas" => ".", "previsao_prazo" => ".", "formas_consultar_andamento" => ".", "informacoes_necessarias" => ".", "canais_reclamacao_sugestao" => ".", "formas_comunicao_com_solicitante" => ".", "prioridade_atendimento" => ".", "previsao_tempo_espera" => ".", "mecanismos_comunicao_usuario" => ".", "procedimentos_receber_responder_manifestacoes_usuario" => ".", "more_info" => "." } end services_params.each do |service_params| service = Service.new(service_params) service.save! end end end
# frozen_string_literal: true require File.expand_path('config/application', __dir__) Demo::Application.load_tasks namespace :demo do task limit: :environment do puts '=> Creating sidekiq tasks' 100.times do SlowWorker.perform_async FastWorker.perform_async end run_sidekiq_monitoring run_sidekiq_workers config: <<-YAML :verbose: false :concurrency: 4 :queues: - slow - fast :limits: slow: 1 YAML end task blocking: :environment do puts '=> Creating sidekiq tasks' AWorker.perform_async BWorker.perform_async CWorker.perform_async run_sidekiq_monitoring run_sidekiq_workers config: <<-YAML :verbose: false :concurrency: 4 :queues: - a - b - c :blocking: - a YAML end task advanced_blocking: :environment do puts '=> Creating sidekiq tasks' AWorker.perform_async BWorker.perform_async CWorker.perform_async run_sidekiq_monitoring run_sidekiq_workers config: <<-YAML :verbose: false :concurrency: 4 :queues: - a - b - c :blocking: - [a, b] YAML end def with_sidekiq_config(config) whitespace_offset = config[/\A */].size config.gsub!(/^ {#{whitespace_offset}}/, '') puts "=> Use sidekiq config:\n#{config}" File.write 'config/sidekiq.yml', config yield ensure FileUtils.rm 'config/sidekiq.yml' end def run_sidekiq_monitoring require 'sidekiq/web' Thread.new do Rack::Server.start app: Sidekiq::Web, Port: 3000 end sleep 1 Launchy.open 'http://127.0.0.1:3000/busy?poll=true' end def run_sidekiq_workers(options) require 'sidekiq/cli' cli = Sidekiq::CLI.instance %w[validate! boot_system].each do |stub| cli.define_singleton_method(stub) {} # rubocop:disable Lint/EmptyBlock end with_sidekiq_config options[:config] do cli.send :setup_options, [] end cli.run end end
require_relative '../spec_helper' describe "user can edit from index" do it "they see the form" do Condition.create(date: "01/05/2017", max_temperature_f: "90", mean_temperature_f: "75", min_temperature_f: "19", mean_humidity: "0.50", mean_visibility: "1", mean_wind_speed: "10", precipitation_inches: "4") visit("/conditions") click_on("Edit") expect(current_path).to eq("/conditions/1/edit") fill_in("condition[mean_humidity]", with: "0.7") fill_in("condition[max_temperature_f]", with: "99") click_on("Submit") expect(current_path).to eq("/conditions/1") within("#weather") do expect(page).to have_content("99") expect(page).to have_content("0.7") end end end describe "user can edit from show" do it "they see the form" do weather = Condition.create(date: "01/05/2017", max_temperature_f: "90", mean_temperature_f: "75", min_temperature_f: "19", mean_humidity: "0.50", mean_visibility: "1", mean_wind_speed: "10", precipitation_inches: "4") visit("/conditions/#{weather.id}") click_on("Edit") expect(current_path).to eq("/conditions/#{weather.id}/edit") fill_in("condition[min_temperature_f]", with: "25") fill_in("condition[precipitation_inches]", with: "1") click_on("Submit") expect(current_path).to eq("/conditions/1") within("#weather") do expect(page).to have_content("25") expect(page).to have_content("1") end end end
class VehicleConsumption < ActiveRecord::Base belongs_to :vehicle belongs_to :desk_supplie belongs_to :driver end
require_relative 'spec_helper' require 'tdd' require 'rspec' describe '#my_uniq' do let(:test) {(0..4).to_a} let(:testB) { [1,2,1,3,3] } it 'should not remove unique values' do expect(test.my_uniq).to eq([0,1,2,3,4]) end it 'should remove non unique values' do expect(testB.my_uniq).to eq([1,2,3]) end it 'should return a new array' do expect(testB.my_uniq).to_not be(testB) end end describe 'Array#two_sum' do let(:test) { (-2..2).to_a } it 'returns indices summing to 0' do expect(test.two_sum).to eq([[0,4], [1,3]]) end it 'returns empty array if none sum to 0' do expect([].two_sum).to eq([]) end end describe 'Array#my_transpose' do let(:test) { [ [0, 1, 2], [3, 4, 5], [6, 7, 8]] } it 'should return a transposed array' do expect(test.my_transpose).to eq([[0, 3, 6],[1, 4, 7],[2, 5, 8]]) end it 'should return nil for a 1-d Array' do expect([1].my_transpose).to eq(nil) end end describe 'Array#stock_picker' do let(:test){[100,10,5000,2]} it 'returns nil for arrays smaller than 2' do expect([1].stock_picker).to be(nil) end it 'returns the highest margin' do expect(test.stock_picker).to eq([1,2]) end end describe Towers_of_hanoi do let(:test) {Towers_of_hanoi.new(3) } describe 'Initialize' do it 'initializes with a size' do expect { Towers_of_hanoi.new(3)}.not_to raise_error end it 'sets the tower height to that size' do expect(test.board.first.size).to eq(3) end it 'fills the first tower in ascending order' do expect(test.board.first).to eq([3, 2, 1]) end end describe '#move_disc' do it 'takes in starting and ending towers' do expect {test.move_disc(0,1)}.not_to raise_error end it 'returns an error if starting tower is empty' do expect {test.move_disc(1,0)}.to raise_error("your starting tower is empty!") end it 'moves the disc' do test.move_disc(0,1) expect(test.board.first).to eq([3,2]) expect(test.board[1]).to eq([1]) end it 'returns an error if move is invalid' do test.move_disc(0,1) expect {test.move_disc(0,1) }.to raise_error("invalid move") end end describe '#won?' do it 'returns false if you havent won' do expect(test.won?).to be(false) end it 'returns true if you win' do test.move_disc(0,2) test.move_disc(0,1) test.move_disc(2,1) test.move_disc(0,2) test.move_disc(1,0) test.move_disc(1,2) test.move_disc(0,2) expect(test.won?).to be(true) end end end
class ContestsController < AuthController before_filter :admin_filter, only: ['new','edit', 'create', 'update'] before_filter :check_attendance, only: ['show'] # GET /contests def index # 開催期間に当てはまるコンテストだけ表示する @contests = Contest.order(:start_time) end # GET /contests/1 def show @contest = Contest.find(params[:id]) raise InvalidContestError, 'contest is not started yet' unless @contest.started? end # GET /contests/1/attend def attend @contest = Contest.find(params[:id]) @current_user.attend(@contest) unless @current_user.attended? @contest redirect_to :controller=> "contests/problems", :action=> "index", :contest_id=> params[:id] end def check_attendance @contest = Contest.find(params[:id]) redirect_to contests_path unless @current_user.attended? @contest end end
module TicTacToeRZ module Exceptions class GameRuleViolationError < StandardError end end end
# Longest Vowel Chain =begin problem: Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring. Vowels are any of aeiou. =end def find_substrings(str) substrings = [] (0...str.size).each do |start| (start...str.size).each do |end_idx| substrings << str[start..end_idx] if str[start..end_idx].chars.all? { |l| l =~ /[aeiou]/} end end substrings end def solve(str) substrings = find_substrings(str) #["o", "e", "a", "i", "io", "o"] substrings.max_by(&:size).size end p solve("codewarriors") == 2 p solve("suoidea") == 3 p solve("iuuvgheaae") == 4 p solve("ultrarevolutionariees") == 3 p solve("strengthlessnesses") == 1 p solve("cuboideonavicuare") == 2 p solve("chrononhotonthuooaos") == 5 p solve("iiihoovaeaaaoougjyaw") == 8
class Api::AreasController < ApplicationController respond_to :json def index @areas = Area.all.map { |i| AreaSerializer.new(i).serializable_hash } render json: { success: true, response: @areas } end def events @events = @areas.events.map { |a| eventserializer.new(a).serializable_hash } if @areas.errors.empty? render json: { success: true, response: @events } else render json: { success: false, info: @areas.errors.to_json } end end def users @users = @areas.users.map { |a| userserializer.new(a).serializable_hash } if @areas.errors.empty? render json: { success: true, response: @users } else render json: { success: false, info: @areas.errors.to_json } end end def create @areas = Area.new(area_params) if @areas.save render json: { success: true, response: @areas } else render json: { success: false, info:@areas.errors.to_json } end end private def area_params params.permit(:name) end end
require "application_system_test_case" class MainModelsTest < ApplicationSystemTestCase setup do @main_model = main_models(:one) end test "visiting the index" do visit main_models_url assert_selector "h1", text: "Main Models" end test "creating a Main model" do visit main_models_url click_on "New Main Model" fill_in "Title", with: @main_model.title click_on "Create Main model" assert_text "Main model was successfully created" click_on "Back" end test "updating a Main model" do visit main_models_url click_on "Edit", match: :first fill_in "Title", with: @main_model.title click_on "Update Main model" assert_text "Main model was successfully updated" click_on "Back" end test "destroying a Main model" do visit main_models_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Main model was successfully destroyed" end end
require 'spec_helper' describe Line do it 'initializes a line instance with a name' do test_line = Line.new({'name' => 'blue'}) test_line.should be_an_instance_of Line end it 'gives the line a name' do test_line = Line.new({'name' => 'blue', 'id' => 2}) test_line.name.should eq 'blue' test_line.id.should be_an_instance_of Fixnum end describe '.create' do it 'creates and saves a new line' do test_line = Line.create({'name' => 'blue', 'id' => 2}) Line.all.should eq [test_line] end end describe '.all' do it 'starts empty' do Line.all.should eq [] end end describe '#save' do it 'saves a new line' do test_line = Line.new({'name' => 'blue', 'id' => 2}) test_line.save Line.all.should eq [test_line] end end describe '#==' do it 'recognizes two lines with the same name and id are the same line' do test_line1 = Line.new({'name' => 'blue', 'id' => 2}) test_line2 = Line.new({'name' => 'blue', 'id' => 2}) test_line1.should eq test_line2 end end describe '.stations_served_by_line' do it 'shows the stations for a line' do test_station = Station.create({'location' => 'Rose Quarter', 'id' => 2}) test_line = Line.create({'name' => 'blue', 'id' => 1}) test_station.create_stop(test_line.id) Line.stations_served_by_line(test_line.id)[0].should be_an_instance_of Station end end describe '#create_stop' do it 'assigns stations to a line' do test_station = Station.new({'location' => 'Rose Quarter', 'id' => 2}) test_station.create_stop(1) result = DB.exec("SELECT * FROM stops WHERE station_id = #{test_station.id};") result[0]['line_id'].to_i.should eq 1 end end describe '.update' do it 'updates the name of a line' do test_line = Line.create({'name' => 'blue', 'id' => 1}) Line.update(test_line.id, "Red") result = DB.exec("SELECT * FROM lines WHERE id = #{test_line.id}") result[0]['name'].should eq "Red" end end describe '.delete' do it 'deletes a line' do test_line1 = Line.create({'name' => 'red', 'id' => 1}) test_line2 = Line.create({'name' => 'blue', 'id' => 2}) Line.delete(test_line1.id) result = DB.exec("SELECT * FROM lines;") result[0]['name'].should eq 'blue' end end end
# == Schema Information # # Table name: posts # # id :integer not null, primary key # content :text not null # created_at :datetime not null # updated_at :datetime not null # user_id :integer not null # # Indexes # # index_posts_on_user_id (user_id) # index_posts_on_user_id_and_created_at (user_id,created_at) # # Foreign Keys # # user_id (user_id => users.id) # require 'rails_helper' RSpec.describe Post, type: :model do describe 'default scope' do let!(:first_post) { FactoryBot.create(:post) } let!(:second_post) { FactoryBot.create(:post) } it 'orders posts by creation date descending' do posts = [] Post.all.each { |post| posts << post } expect(posts).to eq([second_post, first_post]) end end describe 'validations' do it { is_expected.to validate_presence_of(:user_id) } it { is_expected.to validate_presence_of(:content) } it { is_expected.to validate_length_of(:content).is_at_most(150) } end end
module GplusStats module Matchers end end module GplusStats::Matchers::Match def call(html) matches(html) || 0 end protected def matchers private_methods.map(&:to_s).select {|m| m =~ /match_/} end def matches(html) results = matchers.map {|matcher| send(matcher, html) } results.compact.any? ? results[0] : nil end end
module BadgeConcerns module UserBadgeable extend ActiveSupport::Concern include BadgeConcerns::SimpleBadgeable included do after_update :award_on_profile_complete end private def award_on_profile_complete award_to(self, :complete_profile) if profile_complete? end end end
require 'rails_helper' RSpec.feature "Users", type: :feature do # テスト実行前に送信メールをクリアする background do ActionMailer::Base.deliveries.clear end def confirmation_url(mail) body = mail.body.encoded body[/http[^"]+/] end scenario "to move sign up" do visit root_path expect(page).to have_http_status :ok click_on "ユーザー登録" expect(page).to have_content("ユーザー登録") end scenario "to move sign in" do visit root_path expect(page).to have_http_status :ok click_on "ユーザーログイン" expect(page).to have_content("ログイン") end scenario "to registrate new user" do user = FactoryBot.build(:user, username: "test", full_name: "テスト", email: "test@example.org", address: "東京都", password: "password", password_confirmation: "password") visit new_user_registration_path expect(page).to have_http_status :ok fill_in "ユーザー名", with: user.username fill_in "氏名", with: user.full_name fill_in "メールアドレス", with: user.email fill_in "住所(発送先)", with: user.email fill_in "パスワード", with: user.password fill_in "パスワード確認", with: user.password_confirmation expect { click_button 'ユーザー登録' }.to change { ActionMailer::Base.deliveries.size }.by(1) expect(page).to have_content '本人確認用のメールを送信しました。メール内のリンクからアカウントを有効化させてください。' mail = ActionMailer::Base.deliveries.last url = confirmation_url(mail) visit url change(User, :count).to(1) expect(page).to have_content 'アカウントを登録しました。' end scenario "to show error message" do visit new_user_registration_path expect(page).to have_http_status :ok fill_in "ユーザー名", with: " " fill_in "氏名", with: " " fill_in "メールアドレス", with: " " fill_in "住所(発送先)", with: " " fill_in "パスワード", with: " " fill_in "パスワード確認", with: " " click_button "ユーザー登録" expect(page).to have_content("を入力してください") end end
class PartyHasntPaid < ActiveModel::Validator def validate(order) if order.party.has_paid order.errors[:base] << "This party has already paid." end end end class Order < ActiveRecord::Base belongs_to(:food) belongs_to(:party) validates_with PartyHasntPaid end
require 'rspec' require 'onlyoffice_api' require_relative '../../../libs/app_manager' current_device = 'samsung_s4W' main_page = nil folder_name = nil describe 'open files' do before :all do current_device = AppManager.initial_device(current_device) user_data = AppManager.get_user_data(current_device.name) AppManager.delete_temp_data(current_device.ip, :onlyoffice) folder_name = AppManager.create_scr_result_folder(current_device.name) login_page = current_device.run_app(:onlyoffice) main_page = login_page.login(:portal_name => PortalData::PORTAL_NAME, :email => user_data['user_name'], :password => user_data['pwd']) File.open(folder_name + '/table.txt', 'w'){ |file| file.write "base filename, last_filename \n" } OnlyOfficeApi.configure do |config| config.server = PortalData::FULL_PORTAL_NAME config.username = user_data['user_name'] config.password = user_data['pwd'] end end Dir['/media/flamine/BC64BA2564B9E276/files/DOCX/*'].each do |filepath| it "open file #{filepath}" do FileHelper.delete_all_files(OnlyOfficeApi) OnlyOfficeApi.files.upload_to_my_docs(filepath) main_page = main_page.update_file_list file_result = main_page.open_file_by_name(File.basename(filepath)) last_filename = Time.now.nsec create_file_table(filepath, last_filename, folder_name) AdbHelper.get_screenshot(current_device.ip, "#{folder_name}/#{last_filename}.png") expect(file_result).to be_truthy end end def create_file_table(base_filename, filename, folder_name) File.open(folder_name + '/table.txt', 'a'){ |file| file.write "#{base_filename}, #{filename} \n" } end after :each do AdbHelper.push_button(current_device.ip, :esc) sleep 1 AdbHelper.push_button(current_device.ip, :esc) current_device.run_app(:onlyoffice) end after :all do AppManager.delete_temp_data(current_device.ip, :onlyoffice) end end
require 'rubygems' require 'bundler/setup' require 'gosu' ROOT_PATH = File.dirname(File.expand_path(__FILE__)) $LOAD_PATH.unshift(File.join(ROOT_PATH, 'lib')) require 'camera' require 'level/base' require 'config' require 'image_registry' require 'hud/debug' require 'hud/info' require 'hud/health' require 'hud/gameover' class Window < Gosu::Window attr_reader :level attr_accessor :camera def initialize(width, height) @width = width @height = height super(width, height, false) self.caption = 'Jump, jump!' Game::Config.set_up @camera = Camera.new(self) @font = Gosu::Font.new(self, 'Courier New', 18) @image_registry = ImageRegistry.new(self, '/media/images') end def update return if @error if left_pressed? player.go_left elsif right_pressed? player.go_right end if up_pressed? player.jump end if not right_pressed? and not left_pressed? and not up_pressed? player.stand end level.move_all camera.target(player) level.clear_destroyed end def reload @level.reload @camera.target(player) end def right_pressed? button_down? Gosu::KbRight or button_down? Gosu::GpRight end def left_pressed? button_down? Gosu::KbLeft or button_down? Gosu::GpLeft end def up_pressed? button_down? Gosu::KbUp or button_down? Gosu::GpButton0 end def draw if @error draw_error! else translate(-camera.rectangle.left, -camera.rectangle.top) do player.draw level.each_object do |o| o.draw if camera.can_see?(o) end end draw_debug! end draw_info! draw_health! draw_gameover! if player.dead? end def draw_debug! @debug ||= Hud::Debug.new(self, @font) @debug.draw end def draw_error! @font.draw(@error, 350, 350, 0) end def draw_info! @info ||= Hud::Info.new(self, @font) @info.draw end def draw_health! @health ||= Hud::Health.new(self, @image_registry) @health.draw end def draw_gameover! @gameover_message ||= Hud::Gameover.new(self, @image_registry) @gameover_message.draw end def load_level(number) @current_level = number path = "levels/#{@current_level}" @error = nil begin @level = Level::Base.new(path, @image_registry) @camera.target(player) rescue Level::NotFound => e @error = e.message end end def player level.player end def object_list level.object_list end def button_down(id) if id == Gosu::KbEscape close elsif id == Gosu::KbR reload elsif id == Gosu::KbN next_level elsif id == Gosu::KbP previous_level end end def previous_level load_level(@current_level - 1) end def next_level load_level(@current_level + 1) end end window = Window.new(1024, 768) window.load_level(1) window.show
class ModifyUserIdOnItem < ActiveRecord::Migration[6.1] def change remove_column :items, :seller_id add_reference :items, :user, index: true end end
class UsersController < ApplicationController before_action :hide_blogroll, only: [:show] before_action :signed_in_user, only: [:edit, :update, :destroy] #before_action :signed_out_user, only: [:new, :create] before_action :correct_user, only: [:edit, :update, :mood] before_action :admin_user, only: [:destroy, :new, :create] def index @users = User.paginate(page: params[:page]) end def show @user = User.find(params[:user_alias]) if @user.nil? redirect_to root_url end end def blog @user = User.find(params[:user_alias]) @page = current_user.pages.build if signed_in? @display = true if current_user?(@user) @feed_items = @user.feed.paginate(page: params[:page]) else # Only show public pages to the public. @feed_items = @user.feed.where("public = ?", true).paginate(page: params[:page]) end end def feed @user = User.find(params[:user_alias]) @title = @user.name + "'s blog" @feed_items = @user.feed @updated = @feed_items.first.updated_at unless @feed_items.empty? respond_to do |format| format.atom { render :layout => false } # we want the RSS feed to redirect permanently to the ATOM feed format.rss { redirect_to feed_path(:format => :atom), :status => :moved_permanently } end end def new @user = User.new end def create # TODO: Fix messaging system. @user = User.new(user_params) if @user.save sign_in @user flash[:success] = "Welcome!" redirect_to username_url(@user.user_alias) else render 'new' end end def edit end def update # TODO: Fix messaging system. if @user.update_attributes(user_params) flash[:success] = "Profile updated" redirect_to username_url(@user.user_alias) else render 'edit' end end def mood @user = User.find(params[:user_alias]) @new_mood = @user.moods.build Mood.init(@user.id) end def destroy # TODO: Fix messaging system. @user = User.find(params[:user_alias]) if @user.nil? redirect_to root_url elsif current_user?(@user) redirect_to root_url else @user.destroy flash[:success] = "User deleted." redirect_to users_url end end private def user_params params.require(:user).permit(:name, :user_alias, :email, :password, :password_confirmation, :icon, :sidebar, :bio) end # Before filters def signed_out_user unless !signed_in? redirect_to root_url end end def correct_user @user = User.find(params[:user_alias]) redirect_to(root_url) unless current_user?(@user) end def admin_user redirect_to(root_url) unless current_user.admin? end def hide_blogroll @display = false end end
require 'forced_notification_to_owner/patches/issue_patch' Redmine::Plugin.register :redmine_forced_notification_to_owner do name 'Redmine Forced Notification To Owner plugin' author 'Max Konin' description 'This is a plugin for Redmine' version '0.0.1' end
require 'rails_helper' describe Assessment do it {should have_many(:indications)} it {should have_many(:feelings)} it {should have_many(:competencies)} it {should have_many(:providers)} it {should validate_presence_of(:word)} it {should validate_uniqueness_of(:word)} end
class AddFootballClubs < ActiveRecord::Migration def up create_table :football_clubs do |t| t.string :name t.string :alias t.integer :league t.text :description t.string :web_site t.string :logo t.timestamps end end def down drop_table :football_clubs end end
#!/usr/bin/env ruby # /r/dailyprogrammer 119 Intermediate # Nothing clever, just A*, not short at all... # - UziMonkey class Map attr_accessor :map, :width, :height attr_accessor :start, :end def initialize(ascii) size,map = ascii.split("\n",2) @map = map.split("\n").map do|line| line.split('').map do|c| {val:c, f:0, g:0, h:0, parent:nil} end end @width = @height = size.to_i @start = @map.flatten.find_index{|x| x[:val] == "S" } @start = [@start % width, @start / width] @end = @map.flatten.find_index{|x| x[:val] == "E" } @end = [@end % width, @end / width] end def to_s str = '' @map.flatten.map{|a| a[:val] }.each_slice(@width) do|s| str << s.join << "\n" end return str end def mark_path current = @end until current.nil? self[current][:val] = '*' current = self[current][:parent] end end def [](a) x, y = *a @map[y][x] end def neighbors(a) x, y = *a [ [-1,0], [1,0], [0,-1], [0,1] ].select do|delta| (0...@width).include?(x+delta[0]) && (0...@height).include?(y+delta[1]) end.map do|delta| [x+delta[0], y+delta[1]] end end def parents(a) p = 0 until self[a][:parent].nil? p = p+1 a = self[a][:parent] end return p end def f(a) (a[0] - @end[0]).abs + (a[1] - @end[1]).abs end def g(a) parents(a) end def recalculate(a) self[a][:f] = f(a) self[a][:g] = g(a) self[a][:h] = self[a][:f] + self[a][:g] end end map = Map.new(STDIN.read) open = [] closed = [] open << map.start until open.empty? || closed.include?(map.end) open.sort!{|a,b| map[a][:f] <=> map[b][:f] } current = open.pop closed << current map.neighbors(current).each do|n| next if map[n][:val] == 'W' || closed.include?(n) if open.include?(n) if map[current][:g] + 1 < map[n][:g] map[n][:parent] = current map.recalculate(n) end else map[n][:parent] = current map.recalculate(n) open << n end end end if closed.include? map.end puts "True, #{map.parents(map.end)}" else puts "False" end if ARGV.include? "-p" map.mark_path puts map end