text
stringlengths
10
2.61M
class Notification < ApplicationRecord # Events define the types of notifications. DO NOT CHANGE EXISTING EVENTS enum event: { system_message: 0, follow_request: 1, user_message: 2, group_invite: 3, group_invite_request: 4, event_invite: 5, event_update: 6 } belongs_to :entity, polymorphic: true, optional: true belongs_to :sender, class_name: "User", foreign_key: "sender_id", optional: true, default: -> { Current.user } belongs_to :receiver, class_name: "User", foreign_key: "receiver_id" scope :unread, -> { where(viewed: false) } validates :event, uniqueness: { scope: [:receiver_id, :sender_id, :entity_id, :message], message: "This notification already exists" } def self.send_event_invite(invite) Notification.create( receiver: invite.user, event: :event_invite, entity: invite ) end def self.send_event_update(user, event) Notification.create( receiver: user, event: :event_update, entity: event, message: "The event \"#{event.name}\" has been updated. Review the event in your schedule." ) end end
class Like < ApplicationRecord belongs_to :error, counter_cache: :likes_count belongs_to :user end
class Alliance < ActiveRecord::Base belongs_to :client_supplier, class_name: 'Client', foreign_key: 'client_supplier_id' belongs_to :client_recipient, class_name: 'Client', foreign_key: 'client_recipient_id' belongs_to :supply belongs_to :demand end
class RinventorsController < ApplicationController before_action :set_rinventor, only: [:show, :edit, :update, :destroy] # GET /rinventors # GET /rinventors.json def index @rinventors = Rinventor.all end # GET /rinventors/1 # GET /rinventors/1.json def show end # GET /rinventors/new def new @rinventor = Rinventor.new end # GET /rinventors/1/edit def edit end # POST /rinventors # POST /rinventors.json def create @rinventor = Rinventor.new(rinventor_params) respond_to do |format| if @rinventor.save format.html { redirect_to @rinventor, notice: 'Rinventor was successfully created.' } format.json { render :show, status: :created, location: @rinventor } else format.html { render :new } format.json { render json: @rinventor.errors, status: :unprocessable_entity } end end end # PATCH/PUT /rinventors/1 # PATCH/PUT /rinventors/1.json def update respond_to do |format| if @rinventor.update(rinventor_params) format.html { redirect_to @rinventor, notice: 'Rinventor was successfully updated.' } format.json { render :show, status: :ok, location: @rinventor } else format.html { render :edit } format.json { render json: @rinventor.errors, status: :unprocessable_entity } end end end # DELETE /rinventors/1 # DELETE /rinventors/1.json def destroy @rinventor.destroy respond_to do |format| format.html { redirect_to rinventors_url, notice: 'Rinventor was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_rinventor @rinventor = Rinventor.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def rinventor_params params.require(:rinventor).permit(:update_date, :rproductid, :starting_amount, :added_amount, :threshold, :sold_amount, :actual_amount, :theoretical_ending_inventory) end end
require "dynamics_crm/version" # CRM require "dynamics_crm/xml/message_builder" require 'dynamics_crm/xml/message_parser' require "dynamics_crm/xml/fault" require "dynamics_crm/xml/attributes" require "dynamics_crm/xml/column_set" require "dynamics_crm/xml/criteria" require "dynamics_crm/xml/query" require "dynamics_crm/xml/fetch_expression" require "dynamics_crm/xml/entity" require "dynamics_crm/xml/entity_reference" require "dynamics_crm/response/result" require "dynamics_crm/response/retrieve_result" require "dynamics_crm/response/retrieve_multiple_result" require "dynamics_crm/response/create_result" require "dynamics_crm/response/execute_result" # Metadata require "dynamics_crm/metadata/xml_document" require "dynamics_crm/metadata/entity_metadata" require "dynamics_crm/metadata/attribute_metadata" require "dynamics_crm/metadata/retrieve_all_entities_response" require "dynamics_crm/metadata/retrieve_entity_response" require "dynamics_crm/metadata/retrieve_attribute_response" # Model require "dynamics_crm/model/entity" require "dynamics_crm/model/opportunity" # Client require "dynamics_crm/client" require 'bigdecimal' require 'base64' require "rexml/document" require 'mimemagic' require 'curl' module DynamicsCRM class StringUtil def self.underscore(str) str.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end
require 'test_helper' class CompanyMembershipsControllerTest < ActionController::TestCase setup do @company_membership = company_memberships(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:company_memberships) end test "should get new" do get :new assert_response :success end test "should create company_membership" do assert_difference('CompanyMembership.count') do post :create, company_membership: { user_id: @company_membership.user_id } end assert_redirected_to company_membership_path(assigns(:company_membership)) end test "should show company_membership" do get :show, id: @company_membership assert_response :success end test "should get edit" do get :edit, id: @company_membership assert_response :success end test "should update company_membership" do put :update, id: @company_membership, company_membership: { user_id: @company_membership.user_id } assert_redirected_to company_membership_path(assigns(:company_membership)) end test "should destroy company_membership" do assert_difference('CompanyMembership.count', -1) do delete :destroy, id: @company_membership end assert_redirected_to company_memberships_path end end
puts 'Gerenciador de Eventos inicializado!' contents = File.read 'event_attendees.csv' #Lê o arquivo inteiro puts contents lines = File.readlines 'event_atendees.csv' #Lê arquivo linha por linha lines.each_with_index do |line, index| next if index == 0 # Passa para a próxima linha se index for igual a zero - para passar o cabeçalho e pegar o conteúdo columns = line.split(',') #Cria array separando as colunas do csv name = columns[2] # Captura valor da coluna nome puts name end def clean_zipcode(zipcode) if zipcode.nil? zipcode = '00000' elsif zipcode.length < 5 # Se zipcodes forem menor do que 5, acrescenta zeros zipcode = zipcode.rjust 5, '0' elsif zipcode.length > 5 # Se forem maior que 5 pega os primeiros 5 digitos zipcode = zipcode[0..4] end end
class ResumesController < ApplicationController before_action :authenticate_entity! # Definition: Lists all resumes. # Input: void. # Output: @resumes. # Author: Essam Azzam. def index @resumes = Resume.all end # Definition: Lists all resumes. # Input: resume. # Output: void. # Author: Essam Azzam. def new @resume = Resume.new end # Definition: Creates a new record in the Resume model. # Input: resume_params. # Output: void. # Author: Essam Azzam. def create @resume = Resume.new(resume_params) if @resume.save redirect_to resumes_path, notice: "The resume #{@resume.name} has been uploaded." else render "new" end end # Definition: Deletes the chosen resume. # Input: resume. # Output: void. # Author: Essam Azzam. def destroy @resume = Resume.find(params[:id]) @resume.destroy redirect_to resumes_path, notice: "The resume #{@resume.name} has been deleted." end # Definition: returns the resume given the name and attachment. # Input: name, attachment. # Output: resume. # Author: Essam Azzam. private def resume_params params.require(:resume).permit(:name, :attachment) end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # # Be sure to restart your server when you modify this file. # These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. if defined?(ActiveRecord) # Include Active Record class name as root for JSON serialized output. ActiveRecord::Base.include_root_in_json = true # Store the full class name (including module namespace) in STI type column. ActiveRecord::Base.store_full_sti_class = true end ActionController::Routing.generate_best_match = false # Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true # Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false
class AccountsController < ApplicationController before_action :authenticate_user!, except: [:avatar, :show] before_action :set_account, only: [:destroy, :set_default, :show, :update, :avatar] before_action :ensure_account_is_mine, only: [:destroy, :set_default, :update] def index @accounts = current_user.accounts.includes(:user).order_by_battletag end def set_default current_user.default_account = @account if current_user.save flash[:notice] = "Your default account is now #{@account}." else flash[:error] = 'Could not update your default account at this time.' end redirect_to accounts_path end def update @account.assign_attributes account_params if @account.save flash[:notice] = "Successfully updated #{@account}." else flash[:error] = "Could not update #{@account}: " + @account.errors.full_messages.join(', ') end redirect_to accounts_path end def destroy unless @account.can_be_unlinked? flash[:error] = "#{@account} cannot be unlinked from your account." return redirect_to(accounts_path) end @account.user = nil if @account.save flash[:notice] = "Successfully disconnected #{@account}." else flash[:error] = "Could not disconnect #{@account}." end redirect_to accounts_path end private def account_params params.require(:account).permit(:platform) end end
# frozen_string_literal: true class Ticket < ApplicationRecord extend Enumerize belongs_to :event belongs_to :reservation, required: false validates :selling_option, :amount, presence: true validates_inclusion_of :paid, in: [true, false] scope :available, -> { where(paid: false) } scope :not_booked, -> { where(reservation_id: nil) } enumerize :selling_option, in: Tickets::Constants::SELLING_OPTIONS end
module Blower # Raised when a task isn't found. class TaskNotFound < RuntimeError; end # Raised when a command returns a non-zero exit status. class FailedCommand < RuntimeError; end class ExecuteError < RuntimeError attr_accessor :status def initialize (status) @status = status end end end
require "csv" require "google/apis/civicinfo_v2" require "erb" require "date" def clean_zipcode(zipcode) zipcode.to_s.rjust(5, "0")[0..4] end def clean_phone_numbers(phone_number) phone_number = phone_number.to_s.gsub(/[^0-9]/, "") if phone_number.length < 10 || phone_number.length >= 11 phone_number = "1234567890" elsif phone_number.length == 11 && phone_number[0] == 1 phone_number = phone_number[1..10] else phone_number end end def legislators_by_zipcode(zip) civic_info = Google::Apis::CivicinfoV2::CivicInfoService.new civic_info.key = 'your api key' begin civic_info.representative_info_by_address( address: zip, levels: 'country', roles: ['legislatorUpperBody', 'legislatorLowerBody'] ).officials rescue "You can find your representatives by visiting www.commoncause.org/take-action/find-elected-officials" end end def save_thank_you_letters(id, form_letter) Dir.mkdir("output") unless Dir.exists?("output") filename = "output/thanks_#{id}.html" File.open(filename, 'w') do |file| file.puts form_letter end end def clean_registration_date(registration) registration_time = registration.split(" ")[1].to_s.rjust(4, "0") registration_date = registration.split(" ")[0].to_s registration_date = registration_date.split("/") month_day = registration_date[1].rjust(2, "0") month = registration_date[0].rjust(2, "0") year = registration_date[2].rjust(4, "20") registration_date = "#{month_day}-#{month}-#{year}" registration_date = DateTime.strptime("#{registration_date} #{registration_time}", '%d-%m-%Y %H:%M') end def populate_hour_counter(my_hash) 24.times do |index| my_hash_index = index.to_s.rjust(2, "0") my_hash[my_hash_index] = 0 end my_hash end def populate_weekday_counter(my_hash) my_hash["Monday"] = 0 my_hash["Tuesday"] = 0 my_hash["Wednesday"] = 0 my_hash["Thursday"] = 0 my_hash["Friday"] = 0 my_hash["Saturday"] = 0 my_hash["Sunday"] = 0 my_hash end puts "EventManager initialized." contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol template_letter = File.read "../form_letter.erb" erb_template = ERB.new template_letter registration_hour_counter = populate_hour_counter(Hash.new) registration_weekday_counter = populate_weekday_counter(Hash.new) contents.each do |row| id = row[0] name = row[:first_name] zipcode = clean_zipcode(row[:zipcode]) phone_number = clean_phone_numbers(row[:homephone]) legislators = legislators_by_zipcode(zipcode) registration_date = clean_registration_date(row[:regdate]) registration_hour = registration_date.hour.to_s.rjust(2, "0") registration_hour_counter[registration_hour] += 1 registration_weekday = registration_date.strftime('%A') registration_weekday_counter[registration_weekday] += 1 form_letter = erb_template.result(binding) save_thank_you_letters(id, form_letter) end puts "The best hour to target with ads is #{registration_hour_counter.max_by{|k,v| v}[0]}:00" puts "The best day of the week to target with ads is #{registration_weekday_counter.max_by{|k,v| v}[0]}"
class AccessoryItemsController < ApplicationController before_action :set_accessory_item, only: [:show, :update, :destroy] before_action :authenticate_user, only: [:create, :update, :destroy] def index @category = ItemCategory.find(params[:category_id]) if params[:category_id] @accessory_items = @category ? @category.items : AccessoryItem.all paginate json: @accessory_items.includes(:category) end def show render json: @accessory_item end def create @accessory_item = AccessoryItem.new(accessory_item_params) authorize @accessory_item if @accessory_item.save render json: @accessory_item, status: :created, location: item_url(@accessory_item) else render json: @accessory_item.errors, status: :unprocessable_entity end end def update authorize @accessory_item if @accessory_item.update(accessory_item_params) render json: @accessory_item else render json: @accessory_item.errors, status: :unprocessable_entity end end def destroy authorize @accessory_item @accessory_item.destroy end private def set_accessory_item @accessory_item = AccessoryItem.find(params[:id]) end def accessory_item_params params.require(:accessory_item).permit(:name, :description, :price_cents, :stock, :item_category_id) end end
#!/usr/bin/env ruby #encoding: UTF-8 require 'mechanize' require 'cgi' require File.join('.', File.dirname(__FILE__), 'config/environment.rb') pp DateTime.now class Vacancy < ActiveRecord::Base end agent = Mechanize.new search_periods = { '7' => 'за неделю', '3' => 'за 3 дня', '1' => 'за сутки' } search_strings = ['c++', 'c#', 'ruby', 'python', 'perl', 'java', 'php', 'javascript', 'lisp', 'erlang'] puts "=" * 7 + " " + Time.now.to_s + " " + "=" * 7 search_strings.each do |keyword| search_periods.keys.each do |period| search_url = "http://hh.ru/search/vacancy?only_with_salary=false&specialization=1&area=1&no_magic=true&search_period=#{period}&clusters=true&text=#{CGI.escape(keyword)}&salary=&currency_code=RUR" page = agent.get search_url result_count = page.search(".//div[@class='resumesearch__result-count']").inner_text result_count = '0' if result_count.empty? Vacancy.create do |v| v.period = period v.keyword = keyword v.parse_time = DateTime.now v.result_count = result_count.match(/\d+/)[0] end puts "#{keyword.capitalize} вакансий: #{result_count} #{search_periods[period]}!" end end
# 5.2 Assignment =begin Write a program that will allow an interior designer to enter the details of a given client: the client's name, age, number of children, decor theme, and whether they're doing full house update =end # Prompt designer for information # Convert user input to appropriate data type # Print hash back when designer has answered all questions # Give the user an opportunity to update a key (no loop necessary) # Turn user input string into symbol # Print the latest version of the hash # Exit the program # 5.2 Assignment =begin Write a program that will allow an interior designer to enter the details of a given client: the client's name, age, number of children, decor theme, and whether they're doing full house update =end # Prompt designer for information # Convert user input to appropriate data type # Print hash back when designer has answered all questions # Give the user an opportunity to update a key (no loop necessary) # Turn user input string into symbol # Print the latest version of the hash # Exit the program client_details = { name: "", age: "", children: "", decor_theme: "", full_house_remodel: "", } puts "What is your name?" client_name = gets.chomp.to_s client_details[:name] = client_name puts "What's your age?" client_age = gets.chomp.to_i client_details[:age] = client_age puts "How many children do you have?" client_children = gets.chomp.to_i client_details[:children] = client_children puts "What's your decor theme?" client_decor_theme = gets.chomp.to_s client_details[:decor_theme] = client_decor_theme puts "Will you be doing a full-house remodel?" client_full_house_remodel = gets.chomp case client_full_house_remodel when "no" || "No" || "n" || "N" then client_full_house_remodel = false when "yes" || "Yes" || "y" || "Y" then client_full_house_remodel = true end client_details[:full_house_remodel] = client_full_house_remodel def update_data(hash) puts "Would you like to update any information? Type 'name', 'age', 'children', 'decor_theme', or 'full_house_remodel' to update any information. If you're done, please type 'done'." user_update = gets.chomp if user_update == "done" puts hash else field_key = user_update.to_sym puts "What would you like to change #{user_update} to?" new_value = gets.chomp hash[field_key] = new_value hash end end update_data(client_details)
require 'aruba/cucumber' Before do @aruba_timeout_seconds = 15 if ENV['DEBUG'] @puts = true @announce_stdout = true @announce_stderr = true @announce_cmd = true @announce_dir = true @announce_env = true end end
class AddIndexToCommentLog < ActiveRecord::Migration[5.1] def change add_index :comment_logs, [:owner_id, :post_id, :account_id] end end
class Animate < Draco::System filter Animated, Sprite, Visible def tick(args) entities.each do |entity| entity.animated.current_frame += 1 entity.sprite.path = get_current_frame(entity.animated) end end def get_current_frame(animated) total_frames = animated.frames.reduce(0) { |total, frame| total + frame[:frames] } current_frame = animated.current_frame % total_frames frame_count = 0 timings = animated.frames.reduce({}) do |h, frame| h[frame_count] = frame[:path] frame_count += frame[:frames] h end timings.reduce { |path, frame| current_frame >= frame[0] ? frame : path }[1] end end
class AuthenticationsController < InheritedResources::Base before_filter :authenticate_user! def index @authentications = current_user.authentications if current_user end def create auth = request.env["omniauth.auth"] authentication = current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'], auth['uid']) flash[:notice] = "Authentication successful." authentication.auth_token = auth['provider']=="facebook" ? auth["credentials"]["token"] : auth["extra"]["access_token"].token authentication.auth_secret = auth['provider']=="facebook" ? nil : auth["extra"]["access_token"].secret authentication.user_name = auth['provider']=="facebook" ? auth["extra"]["raw_info"]["email"] : (auth['provider']=="twitter" ? auth["extra"]["raw_info"]["screen_name"] : nil) authentication.save! redirect_to admin_path end def destroy @authentication = current_user.authentications.find(params[:id]) @authentication.destroy flash[:notice] = "Successfully Disconnected." redirect_to admin_path end def failure flash[:alert] = "Sorry, You din't authorize" redirect_to admin_path end end
class CreateGrantApplications < ActiveRecord::Migration def change create_table :grant_applications do |t| t.references :user, index: true t.string :contact_person t.string :contact_email t.string :contact_phone t.boolean :sf_bay t.text :grant_request t.text :comments t.timestamps null: false end add_foreign_key :grant_applications, [:user_id, :created_at] end end
class AddEmpresaIdToUsuario < ActiveRecord::Migration def change add_column :usuarios, :empresa_id, :integer add_index :usuarios, :empresa_id end end
Rails.application.routes.draw do get 'users/create' get 'users/destroy' get 'users/my_projects', to: 'users#my_projects', as: 'my_projects' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'home#index' resources :estimation_sessions, :partial_estimations, :stories, :users, :home, :share post '/saveconfig', to: 'home#saveConfig' get '/trello_boards', to: 'home#trello_boards' post '/trello_stories', to: 'home#trello_stories' post '/estimation_sessions/add_story', to: 'estimation_sessions#add_story' post '/estimation_sessions/resolve_conflicts', to: 'estimation_sessions#resolve_conflicts' post '/estimation_sessions/resolve_majority_conflict', to: 'estimation_sessions#resolve_majority_conflict' post '/estimation_sessions/add_story', to: 'estimation_sessions#add_story' post '/estimation_sessions/notify', to: 'estimation_sessions#notify' post '/estimation_sessions/checkin', to: 'estimation_sessions#checkin' post '/estimation_sessions/estimate_story', to: 'estimation_sessions#estimate_story' post '/estimation_sessions/final_estimation', to: 'estimation_sessions#apply_consensus' post '/estimation_sessions/unite', to: 'estimation_sessions#unite' get '/users/new', to: 'users#new' get '/projects/:id/share', to: 'projects#share' get 'auth/google_oauth2/callback', to: 'users#create' get 'auth/trello/callback', to: 'users#create_external' get 'auth/failure', to: redirect('/') get 'signout', to: 'users#destroy', as: 'signout' resources :sessions, only: [:create, :destroy] resources :projects, only: [:create, :update] # resource :home, only: [:show] get '/estimation_sessions/:id/estimation_page', to: 'projects#estimation_page', defaults: { format: 'json' } get '/estimation_sessions/:id/start', to: 'estimation_sessions#start' get '/estimation_sessions/:id/:format', to: 'estimation_sessions#report' end
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.timestamps null: false end end end t.references :project, index: true t.integer :hours t.integer :minutes t.text :comments t.datetime :date t.timestamps null: false
module Transfers extend ActiveSupport::Concern include Secured include Activities::Breadcrumbed included do before_action :can_create_transfer? end def new @transfer = transfer_model.new prepare_default_activity_trail(target_activity, tab: "transfers") add_breadcrumb t("breadcrumb.#{transfer_type}.new"), new_path end def edit @transfer = transfer_model.find(params[:id]) authorize @transfer prepare_default_activity_trail(target_activity, tab: "transfers") add_breadcrumb t("breadcrumb.#{transfer_type}.edit"), edit_path end def create @transfer = transfer_model.new if target_activity.project? || target_activity.third_party_project? @transfer.report = Report.editable_for_activity(target_activity) end @transfer.assign_attributes(transfer_params) if params[transfer_type][:confirm] confirm_or_edit(t("action.#{transfer_type}.create.success")) else set_confirmation_url show_confirmation_or_errors end end def update @transfer = transfer_model.find(params[:id]) authorize @transfer @transfer.assign_attributes(transfer_params) if params[transfer_type][:confirm] confirm_or_edit(t("action.#{transfer_type}.update.success")) else set_confirmation_url show_confirmation_or_errors end end private def confirm_or_edit(success_message) if params[:edit] render edit_or_new else @transfer.save flash[:notice] = success_message redirect_to organisation_activity_transfers_path(target_activity.organisation, target_activity) end end def show_confirmation_or_errors if @transfer.valid? @transfer_presenter = TransferPresenter.new(@transfer) prepare_default_activity_trail(target_activity, tab: "transfers") add_breadcrumb t("breadcrumb.#{transfer_type}.confirm"), @confirmation_url render :confirm else render edit_or_new end end def edit_or_new (action_name == "create") ? :new : :edit end def set_confirmation_url @confirmation_url = (action_name == "create") ? show_path : edit_path end def edit_path send("activity_#{transfer_type}_path", target_activity, @transfer) end def show_path send("activity_#{transfer_type.to_s.pluralize}_path", target_activity) end def new_path send("new_activity_#{transfer_type}_path", target_activity) end def transfer_type transfer_model.to_s.underscore.to_sym end end
class CategoriesController < ApplicationController respond_to :html, :xml def index @categories = Category.find(:all, :include => :posts) respond_with @categories end def show @category = Category.find(params[:id]) respond_with @category end end
#!/usr/bin/env ruby require 'fileutils' require 'open-uri' require 'open_uri_redirections' require './lib/sequence_generator.rb' require './lib/sequence_store.rb' # Print welcome statement and prompt user for a URL or file path to parse puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "X" puts "X Welcome to the 'Words Challenge' program by Tom Geer" puts "X" puts "X For information on this program please see: " puts "X https://github.com/tag78/words/blob/master/README.md" puts "X" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n\n" print "Please enter a URL or file path to parse: " url = STDIN.gets.strip! store = SequenceStore.new open(url, :allow_redirections => :safe) do |f| # Loop through all words in the file f.each_line do |word| word.strip! # Use the generator to get all sequences, then add them to the store SequenceGenerator.parse(word, 4).each do |seq| store.push seq, word end end end FileUtils.mkdir_p 'out' # Create output dir if it doesn't exist # Open both output files for writing File.open('out/words', 'w') do |words_file| File.open('out/sequences', 'w') do |seq_file| # Loop through unique sequences and write them to output files store.unique_sequences.each do |seq_word_pair| seq_file.write seq_word_pair.first + "\n" words_file.write seq_word_pair.last + "\n" end end end
class AddDefaultToVoteUpAndVoteDownAttributes < ActiveRecord::Migration def change change_column_default :articles, :up_vote, 0 change_column_default :articles, :down_vote, 0 end end
require 'rails_helper' RSpec.describe UrlShortenerController, type: :request do describe 'post #new' do before { post '/', params: { url: 'http://farmdrop.com' } } it 'returns http success' do expect(response.content_type).to eq 'application/json; charset=utf-8' end it 'returns the short code and url' do expect(JSON.parse(response.body)['url']).to eq('http://farmdrop.com') end end describe 'get #index' do it 'returns http success' do get '/' expect(response).to have_http_status(:success) end end describe 'GET #code' do before do UrlShortenerService::URL_STORE = [{ short_url: 'abc123', url: 'http://farmdrop.com' }] end it 'returns http redirect' do get '/abc123' expect(response).to redirect_to('http://farmdrop.com') end end end
module DashboardHelper def filter_path(entity, options={}) exist_opts = { state: params[:state], scope: params[:scope], project_id: params[:project_id], } options = exist_opts.merge(options) path = request.path path << "?#{options.to_param}" path end def entities_per_project(project, entity) #FIXME remove 0 end def projects_dashboard_filter_path(options={}) exist_opts = { sort: params[:sort], scope: params[:scope], group: params[:group], } options = exist_opts.merge(options) path = request.path path << "?#{options.to_param}" path end end
# Copyright 2011-2013 innoQ Deutschland GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require File.join(File.expand_path(File.dirname(__FILE__)), '../integration_test_helper') class SearchTest < ActionDispatch::IntegrationTest setup do @pagination_setting = Kaminari.config.default_per_page Kaminari.config.default_per_page = 5 @concepts = %w("Tree"@en "Forest"@en).map do |literal| Concept::SKOS::Base.new.tap do |c| RDFAPI.devour c, 'skos:prefLabel', literal c.publish c.save end end @collection = Collection::SKOS::Unordered.new.tap do |c| RDFAPI.devour c, 'skos:prefLabel', '"Alpha"@en' c.publish c.save end # assign concepts to collection @concepts.each do |c| RDFAPI.devour @collection, 'skos:member', c end end teardown do Kaminari.config.default_per_page = @pagination_setting end test 'searching' do visit search_path(lang: 'en', format: 'html') [{ type: 'Labels', query: 'Forest', query_type: 'contains', amount: 1, result: 'Forest' }].each { |q| find('#t').select q[:type] fill_in 'Search term(s)', with: q[:query] find('#qt').select q[:query_type] # select all languages page.all(:css, '.lang_check').each do |cb| check cb[:id] end click_button('Search') assert page.has_css?('.search-result', count: q[:amount]), "Page has #{page.all(:css, '.search-result').count} '.search-result' nodes. Should be #{q[:amount]}." within('.search-result') do assert page.has_content?(q[:result]), "Could not find '#{q[:result]}' within '.search-result'." end } end test 'collection/concept filter' do visit search_path(lang: 'en', format: 'html') find('#t').select 'Labels' find('#qt').select 'contains' fill_in 'Search term(s)', with: 'Alpha' click_button('Search') assert page.has_css?('.search-result', count: 1) choose 'Concepts' click_button 'Search' assert page.has_no_css?('.search-result') choose 'Collections' click_button 'Search' assert page.has_css?('.search-result') end test 'date filter' do login 'administrator' visit new_concept_path(lang: 'en', format: 'html', published: 0) fill_in 'concept_labelings_by_text_labeling_skos_pref_labels_en', with: 'Water' click_button 'Save' visit new_concept_path(lang: 'en', format: 'html', published: 0) fill_in 'concept_labelings_by_text_labeling_skos_pref_labels_en', with: 'Air' click_button 'Save' Iqvoc::Concept.base_class.third.update(published_at: Date.today) Iqvoc::Concept.base_class.fourth.update(published_at: Date.today) Note::Annotated::Base.where(predicate: "created").first.update(value: (Date.today - 10.days).to_s) visit search_path(lang: 'en', format: 'html') find('#t').select 'Labels' find('#change_note_type').select 'creation date' fill_in 'change_note_date_from', with: Date.today click_button('Search') refute page.find('.search-results').has_content?('Water') assert page.find('.search-results').has_content?('Air') end test 'searching within collections' do visit search_path(lang: 'en', format: 'html') find('#t').select 'Labels' find('#qt').select 'contains' fill_in 'Search term(s)', with: 'res' find('#c').select @collection.to_s # select all languages page.all(:css, '.lang_check').each do |cb| check cb[:id] end click_button('Search') assert page.has_css?('.search-result', count: 1) assert page.find('.search-results').has_content?('Forest') # TTL & RDF/XML ttl_uri = page.find('#rdf_link_ttl')[:href] xml_uri = page.find('#rdf_link_xml')[:href] visit ttl_uri assert page.has_content?('search:result1 a sdc:Result') assert page.has_no_content?('search:result2 a sdc:Result') assert page.has_content?("sdc:link :#{@concepts[1].origin}") assert page.has_content?('skos:prefLabel "Forest"@en') visit xml_uri assert page.source.include?(@concepts[1].origin) assert page.source.include?("<skos:prefLabel xml:lang=\"en\">#{@concepts[1].to_s}</skos:prefLabel>") end test 'searching specific classes within collections' do concept = Concept::SKOS::Base.new.tap do |c| RDFAPI.devour c, 'skos:definition', '"lorem ipsum"@en' c.publish c.save end RDFAPI.devour @collection, 'skos:member', concept visit search_path(lang: 'en', format: 'html') find('#t').select 'Notes' find('#qt').select 'contains' fill_in 'Search term(s)', with: 'ipsum' find('#c').select @collection.to_s # select all languages page.all(:css, '.lang_check').each do |cb| check cb[:id] end click_button('Search') assert page.has_css?('.search-result', count: 1) assert page.find('.search-results').has_content?(concept.pref_label.to_s) end test 'empty query with selected collection should return all collection members' do visit search_path(lang: 'en', format: 'html') find('#t').select 'Labels' find('#qt').select 'exact match' fill_in 'Search term(s)', with: '' find('#c').select @collection.to_s # select all languages page.all(:css, '.lang_check').each do |cb| check cb[:id] end click_button('Search') assert page.has_css?('.search-result', count: 2) assert page.find('.search-results').has_content?('Tree') assert page.find('.search-results').has_content?('Forest') end test 'pagination' do # create a large number of concepts 1.upto(12) do |i| Concept::SKOS::Base.new.tap do |c| RDFAPI.devour c, 'skos:prefLabel', "\"sample_#{sprintf('_%04d', i)}\"@en" c.publish c.save end end visit search_path(lang: 'en', format: 'html') find('#t').select 'Labels' find('#qt').select 'contains' fill_in 'Search term(s)', with: 'sample_' click_button('Search') assert page.has_css?('.search-result', count: 5) assert page.has_css?('.pagination .page-item', count: 5) find('.pagination').all('.page-item').last.find('a').click assert page.has_css?('.search-result', count: 2) # TTL & RDF/XML ttl_uri = page.find('#rdf_link_ttl')[:href] xml_uri = page.find('#rdf_link_xml')[:href] visit ttl_uri assert page.has_content?('sdc:totalResults 12;') assert page.has_content?('sdc:itemsPerPage 5;') assert page.has_content?('search:result1 a sdc:Result;') assert page.has_content?('search:result2 a sdc:Result;') assert page.has_no_content?('search:result3 a sdc:Result;') # we're on page 3/3 visit xml_uri assert page.source.include?('<sdc:totalResults rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">12</sdc:totalResults>') assert page.source.include?('<sdc:itemsPerPage rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">5</sdc:itemsPerPage>') assert page.source.include?('#result1">') assert page.source.include?('#result2">') assert !page.source.include?('#result3">') # we're on page 3/3 end end
require 'test_helper' class CreateParticipationTest < Capybara::Rails::TestCase include Warden::Test::Helpers Warden.test_mode! after do Warden.test_reset! end feature 'Destroy' do scenario 'destroys a participation if admin' do user = create :user, :admin pres = create(:presentation, title: "user's presentation") create(:participation, user_id: user.id, presentation_id: pres.id) login_as(user, scope: :user) visit presentation_path(pres) within '#participation-form-modal' do page.uncheck user.full_name end find('#submit-capybara', visible: false).click within '.attendees' do refute page.has_content? user.email end end scenario 'unable to destroy a participation if non-admin' do user = create :user pres = create(:presentation, title: "user's presentation") login_as(user, scope: :user) create(:participation, user_id: user.id, presentation_id: pres.id) visit presentation_path(pres) refute page.has_content? 'Edit Participants' end end end
describe ManageIQ::Providers::Amazon::ContainerManager::Refresher do it ".ems_type" do expect(described_class.ems_type).to eq(:eks) end describe "#refresh" do let(:zone) do _guid, _server, zone = EvmSpecHelper.create_guid_miq_server_zone zone end let!(:ems) do hostname = Rails.application.secrets.amazon_eks[:hostname] cluster_name = Rails.application.secrets.amazon_eks[:cluster_name] FactoryBot.create(:ems_amazon_eks, :hostname => hostname, :port => 443, :uid_ems => cluster_name, :zone => zone).tap do |ems| client_id = Rails.application.secrets.amazon_eks[:client_id] client_key = Rails.application.secrets.amazon_eks[:client_secret] ems.update_authentication(:default => {:userid => client_id, :password => client_key}) end end it "will perform a full refresh" do 2.times do VCR.use_cassette(described_class.name.underscore) { EmsRefresh.refresh(ems) } ems.reload assert_table_counts assert_specific_container_project assert_specific_container_group assert_specific_container end end def assert_table_counts expect(ems.container_projects.count).to eq(4) expect(ems.container_nodes.count).to eq(0) expect(ems.container_groups.count).to eq(2) expect(ems.containers.count).to eq(2) end def assert_specific_container_project container_project = ems.container_projects.find_by(:name => "kube-system") expect(container_project).to have_attributes( :name => "kube-system", :resource_version => "4" ) end def assert_specific_container_group container_group = ems.container_groups.find_by(:name => "coredns-c79dcb98c-v6chb") expect(container_group).to have_attributes( :ems_ref => "8bca6c7d-b5a0-48f1-a8a7-984586bd80a6", :name => "coredns-c79dcb98c-v6chb", :resource_version => "1066525", :restart_policy => "Always", :dns_policy => "Default", :type => "ManageIQ::Providers::Amazon::ContainerManager::ContainerGroup", :container_project => ems.container_projects.find_by(:name => "kube-system"), :phase => "Pending" ) end def assert_specific_container container = ems.containers.find_by(:name => "coredns", :container_group => ems.container_groups.find_by(:name => "coredns-c79dcb98c-v6chb")) expect(container).to have_attributes( :ems_ref => "8bca6c7d-b5a0-48f1-a8a7-984586bd80a6_coredns_602401143452.dkr.ecr.us-east-1.amazonaws.com/eks/coredns:v1.7.0-eksbuild.1", :name => "coredns", :type => "ManageIQ::Providers::Amazon::ContainerManager::Container", :request_cpu_cores => 0.1, :request_memory_bytes => 73_400_320, :limit_cpu_cores => nil, :limit_memory_bytes => 178_257_920, :image => "602401143452.dkr.ecr.us-east-1.amazonaws.com/eks/coredns:v1.7.0-eksbuild.1", :image_pull_policy => "IfNotPresent", :memory => nil, :cpu_cores => 0.0, :container_group => ems.container_groups.find_by(:name => "coredns-c79dcb98c-v6chb"), :capabilities_add => "NET_BIND_SERVICE", :capabilities_drop => "all" ) end end end
class Checkouts::KwkController < ApplicationController before_action :ensure_sale_is_ongoing private def ensure_sale_is_ongoing redirect_to root_url, error: t("checkouts.no_ongoing_sales") unless current_kwk_sales? end end
#!/usr/bin/env ruby # encoding: utf-8 # Ruby Styles https://github.com/bbatsov/ruby-style-guide # * Arrays.transpose, quickfind_first, find_occurences, min_out_of_cycle, index_out_of_cycle # * Strings.min_window_span, index_of_by_rabin_karp, and combine_parens # * SNode.find_cycle; Numbers.divide, sum, minmax, and abs. # * Miller-Rabin's primality test, 1 = a**(n-1) % n, when a is in (2..n-2). # * Data Structures: Trie, BinaryHeap, LRUCache, CircularBuffer, and MedianBag # * Graph: has_cycle? topological_sort that pushes v onto a stack on vertex exit. # * Binary Tree: path_of_sum, common_ancestors, diameter, successor, and last(k). # * integer partition & composition, and set partition by restricted growth string. # * DP.optimal_tour (TSP), optimal_BST, edit distance, partition_bookshelf, subset sum. %w{test/unit stringio set}.each { |e| require e } # http://en.wikipedia.org/wiki/Patricia_trie # https://raw.github.com/derat/trie/master/lib/trie.rb # https://raw.github.com/dustin/ruby-trie/master/lib/trie.rb class Trie # constructs in O(n^2) time & O(n^2) space; O(n) time & space if optimized. def []=(key, value) key = key.split('') if key.is_a?(String) if key.empty? @value = value else (@children[key[0]] ||= Trie.new)[key[1..-1]] = value end end def [](key = []) key = key.split('') if key.is_a?(String) if key.empty? @value elsif @children[key[0]] @children[key[0]][key[1..-1]] end end def of(key) key = key.split('') if key.is_a?(String) if key.empty? self elsif @children[key[0]] @children[key[0]].of(key[1..-1]) end end def values @children.values.reduce([@value]) { |a, c| c.values.reduce(a) { |a, v| a << v } }.compact end def dfs(enter_v_iff = nil, exit_v = nil, key = []) if enter_v_iff.nil? || enter_v_iff.call(key, self) @children.keys.each do |k| @children[k].dfs(enter_v_iff, exit_v, key + [k]) end exit_v and exit_v.call(key, self) end end def initialize @value = nil @children = {} end attr_reader :value, :children end class BinaryHeap # min-heap by default, http://en.wikipedia.org/wiki/Binary_heap # http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html # a binary heap is a complete binary tree, where all levels but the last one are fully filled, and # each node is smaller than or equal to each of its children according to a comparer specified. # In Java, new PriorityQueue<Node>(capacity, new Comparator<Node>() { # public int compare(Node a, Node b) { return a.compareTo(b) } # }); def initialize(comparer = lambda { |a, b| a <=> b }) # min-heap by default @heap = [] @comparer = comparer end def offer(e) @heap << e bubble_up(@heap.size - 1) self # works as a fluent interface. end def peek @heap[0] end def poll unless @heap.empty? @heap[0], @heap[-1] = @heap[-1], @heap[0] head = @heap.pop bubble_down(0) head end end def bubble_up(n) if n > 0 p = (n-1)/2 # p: parent if @comparer.call(@heap[p], @heap[n]) > 0 @heap[p], @heap[n] = @heap[n], @heap[p] bubble_up(p) end end end def bubble_down(n) if n < @heap.size c = [n] c << 2*n + 1 if 2*n + 1 < @heap.size c << 2*n + 2 if 2*n + 2 < @heap.size c = c.min {|a,b| @comparer.call(@heap[a], @heap[b])} if c != n @heap[n], @heap[c] = @heap[c], @heap[n] bubble_down(c) end end end def empty?() @heap.empty? end def size() @heap.size end def to_a() @heap end end # LRUCache is comparable to this linked hashmap in Java. # public static class LinkedHashMap<K, V> { # private final LinkedList<Pair<K, V>> list = LinkedList.of(capacity); # private final Map<K, LinkedList.Node<Pair<K, V>>> map = HashMap.of(capacity); # } class LRUCache def initialize(capacity = 1) @capacity = capacity @hash = {} @head = @tail = nil end def put(k, v) @hash[k] and delete_node(@hash[k]) push_node(DNode.new([k, v])) @hash[k] = @tail @hash.delete(shift_node.value[0]) while @hash.size > @capacity self end def get(k) if @hash[k] delete_node(@hash[k]) push_node(@hash[k]) @tail.value[1] end end def delete_node(node) if @head != node node.prev_.next_ = node.next_ else (@head = @head.next_).prev_ = nil end if @tail != node node.next_.prev_ = node.prev_ else (@tail = @tail.prev_).next_ = nil end self end def push_node(node) # push at tail node.next_ = nil node.prev_ = @tail if @tail @tail.next_ = node @tail = @tail.next_ else @head = @tail = node end self end def shift_node # pop at head if @head head = @head if @head.next_ @head = @head.next_ @head.prev_ = nil else @head = @tail = nil end head end end def to_a() @head.to_a end def to_s() @head.to_s end private :delete_node, :push_node, :shift_node end class CircularBuffer def initialize(capacity) @ary = Array.new(capacity+1) @head = @tail = 0 end def enq(v) raise RuntimeError, "This buffer is full." if full? @ary[@tail] = v @tail = (@tail+1) % @ary.size self end def deq raise RuntimeError, "This buffer is empty." if empty? v = @ary[@head] @head = (@head+1) % @ary.size v end def empty?() @head == @tail end def full?() @head == (@tail+1) % @ary.size end end module DP # http://basicalgos.blogspot.com/search/label/dynamic%20programming def self.optimal_tour(g) # TSP http://www.youtube.com/watch?v=aQB_Y9D5pdw memos = Array.new(g.size) { {} } map = lambda do |v, s| # optimal tour from v to 0 through all vertices in S. h = s.keys.sort.reduce(0) { |h, e| h = 31*h + e } memos[v][h] ||= case when s.empty? 0 == g[v][0] ? [nil, Float::MAX] : [0, g[v][0]] else s.keys.reject { |w| 0 == g[v][w] }. map { |w| [w, g[v][w] + map.call(w, s.reject { |k,_| k == w })[1]] }. min_by { |e| e[1] } end end reduce = lambda do |v, s| h = s.keys.sort.reduce(0) { |h, e| h = 31*h + e } if s.empty? [memos[v][h][0]] else w = memos[v][h][0] [w] + reduce.call(w, s.reject { |k,_| k == w }) end end s = (1...g.size).reduce({}) { |h, k| h.merge(k => k) } [map.call(0, s)[1], [0] + reduce.call(0, s)] end def self.optimal_binary_search_tree(keys, probs) memos = [] map = lambda do |i, j| memos[i] ||= {} memos[i][j] ||= case when i > j 0 else probs_ij = (i..j).map { |k| probs[k] }.reduce(:+) comparisons = (i..j).map { |k| map.call(i, k-1) + map.call(k+1, j) + probs_ij }.min end end map.call(0, keys.size-1) end # http://basicalgos.blogspot.com/2012/03/35-matrix-chain-multiplication.html # http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Dynamic/chainMatrixMult.htm def self.order_matrix_chain_multiplication(p) memos = [] map = lambda do |i, j| memos[i] ||= [] memos[i][j] ||= if i == j [nil, 0] # i.e. [move, cost] else (i...j).map { |k| # maps a range of k to an enumerable of [move, cost]. [k, map.call(i, k)[1] + map.call(k+1, j)[1] + p[i] * p[k+1] * p[j+1]] }.min_by { |e| e[1] } end end reduce = lambda do |i,j| k = memos[i][j][0] # note: k is nil when i == j k ? reduce.call(i,k) + reduce.call(k+1, j) + [k] : [] end n = p.size - 1 [map.call(0, n-1)[1], reduce.call(0, n-1)] end def self.partition_bookshelf(ary, n) # Partition S into k or fewer ranges, to minimize the maximum sum # over all the ranges, without reordering any of the numbers. memos = [] map = lambda do |m, k| memos[m] ||= [] memos[m][k] ||= case when k == 1 [m, (0...m).map { |j| ary[j] }.reduce(:+)] when m == 1 [1, ary[0]] else (1...m).map { |i| [i, [ map.call(i, k-1)[1], ary[i...m].reduce(:+) ].max ] }.min_by { |e| e[1] } end end reduce = lambda do |m, k| case when k == 1 [ary[0...m]] when m == 1 [ary[0..0]] else reduce.call(memos[m][k][0], k-1) + [ary[memos[m][k][0]...m]] end end map.call(ary.size, n) reduce.call(ary.size, n) end def self.subset_of_sum(ary, k, n = ary.size, memos = []) memos[n] ||= [] memos[n][k] ||= case when n == 0 then [] else s = [] s += [[ary[n-1]]] if ary[n-1] == k s += subset_of_sum(ary, k - ary[n-1], n-1, memos).map { |e| e + [ary[n-1]] } if ary[n-1] <= k s += subset_of_sum(ary, k, n-1, memos) end end def self.ordinal_of_sum(m, k, n = m) # sum up to m with k out of n numbers. if k == 1 (1..n).select { |e| e == m }.map { |e| [e] } || [] elsif n == 0 [] else s = [] s += ordinal_of_sum(m-n, k-1, n-1).map { |e| e + [n] } if n < m s += ordinal_of_sum(m, k, n-1) end end # Given two strings of size m, n and set of operations replace (R), insert (I) and delete (D) all at equal cost. # Find minimum number of edits (operations) required to convert one string into another. def self.edit(s, t, whole = true, indel = lambda {1}, match = lambda {|a,b| a == b ? 0 : 1}) # cf. http://en.wikipedia.org/wiki/Levenshtein_distance moves = [] # moves with costs compute_move = lambda do |i, j| moves[i] ||= [] moves[i][j] ||= case when 0 == i then whole ? [j > 0 ? :insert : nil, j] : [nil, 0] when 0 == j then [i > 0 ? :delete : nil, i] else [ [:match, compute_move.call(i-1, j-1)[-1] + match.call(s[i-1], t[j-1])], [:insert, compute_move.call(i, j-1)[-1] + indel.call(t[j-1])], [:delete, compute_move.call(i-1, j)[-1] + indel.call(s[i-1])] ].min_by { |e| e.last } end end compute_path = lambda do |i, j| case moves[i][j][0] when :match then compute_path.call(i-1,j-1) + (s[i-1] == t[j-1] ? 'M' : 'S') when :insert then compute_path.call(i, j-1) + 'I' when :delete then compute_path.call(i-1, j) + 'D' else '' end end cost = compute_move.call(s.size, t.size)[-1] [cost, compute_path.call(s.size, t.size)] end # comparable to http://en.wikipedia.org/wiki/Levenshtein_distance def self.edit_distance(s, t, whole = true, i = s.size, j = t.size, memos = {}) memos[i] ||= {} memos[i][j] ||= case when 0 == i then whole ? j : 0 when 0 == j then i else [ edit_distance(s, t, i-1, j, memos) + 1, edit_distance(s, t, i, j-1, memos) + 1, edit_distance(s, t, i-1, j-1, memos) + (s[i-1] == t[j-1] ? 0 : 1) ].min end end # http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence # http://en.wikipedia.org/wiki/Longest_increasing_subsequence # http://stackoverflow.com/questions/4938833/find-longest-increasing-sequence/4974062#4974062 # http://wordaligned.org/articles/patience-sort def self.longest_increasing_subsequence(ary) memos = ary.each_index.reduce([]) do |memos, i| j = memos.rindex { |m| m.last <= ary[i] } || -1 memos[j+1] = -1 != j ? memos[j] + [ary[i]] : [ary[i]] memos end memos.last # e.g. memos: [[1], [1, 2], [1, 3, 3]] end def self.longest_increasing_subsequence_v2(ary) memos = [] map = lambda do |i| memos[i] ||= (0...i). map { |k| v = map.call(k)[1]; [k, 1 + v] }. select { |e| ary[e[0]] <= ary[i] }. max_by { |e| e[1] } || [nil, 1] end map.call(ary.size-1) k = memos.each_index.to_a.max_by { |k| memos[k][1] } answer = [] while k answer.unshift(ary[k]) k = memos[k][0] end answer end # http://en.wikipedia.org/wiki/Longest_common_substring_problem def self.longest_common_substring(a, b) # best solved by suffix tree n, m = a.size, b.size memos = [] longest = [] 1.upto(n) do |i| 1.upto(m) do |j| if a[i-1] == b[j-1] l = memos[i][j] = 1 + (memos[i-1][j-1] || 0) s = a[i-l, l] longest << s if longest.empty? || l == longest[0].size longest.replace([s]) if l > longest[0].size end end end longest end # http://www.algorithmist.com/index.php/Longest_Common_Subsequence # http://en.wikipedia.org/wiki/Longest_common_subsequence_problem # http://wordaligned.org/articles/longest-common-subsequence # http://rosettacode.org/wiki/Longest_common_subsequence#Dynamic_Programming_7 def self.longest_common_subsequence(s, t) memos = [] map = lambda do |i, j| memos[i] ||= [] memos[i][j] ||= case when 0 == i || 0 == j then 0 when s[i-1] == t[j-1] then 1 + map.call(i-1, j-1) else [map.call(i, j-1), map.call(i-1, j)].max end end sequences = [] reduce = lambda do |i, j| (sequences[i] ||= {})[j] ||= case when 0 == i || 0 == j then [''] when s[i-1] == t[j-1] reduce.call(i-1,j-1).product([s[i-1, 1]]).map { |e| e.join } when memos[i-1][j] > memos[i][j-1] then reduce.call(i-1, j) when memos[i-1][j] < memos[i][j-1] then reduce.call(i, j-1) else a = reduce.call(i-1, j) + reduce.call(i, j-1) a.reduce({}) { |h,k| h.merge(k => nil) }.keys end end map.call(s.size, t.size) reduce.call(s.size, t.size) end # http://wn.com/programming_interview_longest_palindromic_subsequence_dynamic_programming # http://tristan-interview.blogspot.com/2011/11/longest-palindrome-substring-manachers.html def self.longest_palindromic_subsequence(s) memos = [] map = lambda do |i, j| # map i, j to longest. memos[i] ||= [] memos[i][j] ||= case when j == i 1 when j == i+1 s[i] == s[j] ? 2 : 1 when s[i] == s[j] map.call(i+1, j-1) + 2 else [ map.call(i, j-1), map.call(i+1, j) ].max end end map.call(0, s.size-1) end def self.minimal_coins(k, denominations, memos = {0 => []}) memos[k] ||= denominations. select { |d| d <= k }. map { |d| [d] + minimal_coins(k-d, denominations, memos) }. min_by { |coins| coins.size } end def self.knapsack_unbounded(skus, capacity) memos = [] # maximum values by k capacity. map = lambda do |w| memos[w] ||= if w == 0 [nil, 0] else skus.each_index.map { |i| w >= skus[i][1] ? [i, skus[i][0] + map.call(w - skus[i][1])[1]] : [nil, 0] }.max_by { |e| e[1] } end end reduce = lambda do |w| if w == 0 then [] else i = memos[w][0] [i] + reduce.call(w-skus[i][1]) end end [map.call(capacity)[1], reduce.call(capacity)] end def self.jump_game2(ary, n = ary.size) memos = [] map = lambda do |i| memos[i] ||= case when ary[i] >= n-1-i then [n-1-i] # takes at most n-1-i steps. when ary[i] == 0 then [0] # the last '0' means it's unreachable. else (1..ary[i]). map { |j| [j] + map.call(i + j) }. # concatenates two arrays. min_by { |e| e.size } # finds the minimun-size array. end end map.call(0) end def self.knapsack01(skus, capacity) memos = [] # maximum values by i items, and w capacity. map = lambda do |n, w| memos[n] ||= [] memos[n][w] ||= case when n == 0 then 0 # for any weight w when skus[n-1][1] > w then map.call(n-1, w) else [ map.call(n-1, w), skus[n-1][0] + map.call(n-1, w - skus[n-1][1]) ].max end end reduce = lambda do |n, w| case when n == 0 then [] when memos[n][w] == memos[n-1][w] reduce.call(n-1, w) else [n-1] + reduce.call(n-1, w - skus[n-1][1]) end end [map.call(skus.size, capacity), reduce.call(skus.size, capacity)] end def self.cut_rod(prices, lengths, length) memos = [] map = lambda do |l| memos[l] ||= if l == 0 [nil, 0] else (1..[l, lengths.size].min).map { |k| [k, map.call(l - k)[1] + prices[k-1]] }.max_by { |e| e[1] } end end reduce = lambda do |l| if l == 0 then [] else k = memos[l][0] [k] + reduce.call(l-k) end end [map.call(length)[1], reduce.call(length)] end def self.balanced_partition(ary) memos = [] map = lambda do |n, k| memos[n] ||= [] memos[n][k] ||= case when 0 == n then 0 when ary[n-1] > k map.call(n-1, k) else [ map.call(n-1, k), ary[n-1] + map.call(n-1, k - ary[n-1]) ].max end end reduce = lambda do |n, k| case when n == 0 then [] when memos[n][k] == memos[n-1][k] then reduce.call(n-1, k) else [ary[n-1]] + reduce.call(n-1, k - ary[n-1]) end end map.call(ary.size, ary.reduce(:+)/2) reduce.call(ary.size, ary.reduce(:+)/2) end def self.floyd_warshal(graph) d = graph.dup # distance matrix n = d.size n.times do |k| n.times do |i| n.times do |j| if i != j && d[i][k] && d[k][j] via_k = d[i][k] + d[k][j] d[i][j] = via_k if d[i][j].nil? || via_k < d[i][j] end end end end d end end class Array def bsearch_range_by(&block) if first = bsearch_first_by(&block) first..bsearch_last_by(first...self.size, &block) end end def bsearch_first_by(range = 0...self.size, &block) if range.count > 1 mid = range.minmax.reduce(:+) / 2 case block.call(self[mid]) when -1 then bsearch_first_by(range.min...mid, &block) when 1 then bsearch_first_by(mid+1..range.max, &block) else bsearch_first_by(range.min..mid, &block) end else range.min if 0 == block.call(self[range.min]) end end def bsearch_last_by(range = 0...self.size, &block) if range.count > 1 mid = (1 + range.minmax.reduce(:+)) / 2 case block.call(self[mid]) when -1 then bsearch_last_by(range.min...mid, &block) when 1 then bsearch_last_by(mid+1..range.max, &block) else bsearch_last_by(mid..range.max, &block) end else range.min if 0 == block.call(self[range.min]) end end def quicksort_k!(k = 0, left = 0, right = self.size-1, &block) quickfind_k!(k, left, right, true, &block) self end def quickfind_k!(k = 0, left = 0, right = self.size-1, sort = false, &block) # http://en.wikipedia.org/wiki/Selection_algorithm#Optimised_sorting_algorithms if right > left pivot = partition(left, right, block_given? ? block : proc { |a, b| a <=> b }) quickfind_k!(k, left, pivot-1, sort, &block) if sort || pivot > k quickfind_k!(k, pivot+1, right, sort, &block) if pivot < k end self end def partition(left, right, comparer) pivot = left + rand(right - left + 1) # select pivot between left and right self[pivot], self[right] = self[right], self[pivot] pivot = left (left...right).each do |i| if comparer.call(self[i], self[right]) < 0 self[pivot], self[i] = self[i], self[pivot] pivot += 1 end end self[pivot], self[right] = self[right], self[pivot] pivot end end module Arrays def self.max_area_in_histogram(heights) l = [] max_area = 0 area = lambda do |r| # exclusive right end h, w = heights[l.pop], r - (l.empty? ? 0 : l.last+1) h * w end heights.each_index do |r| until l.empty? || heights[r] > heights[l.last] max_area = [max_area, area.call(r)].max end l.push(r) end max_area = [max_area, area.call(heights.size)].max until l.empty? max_area end def self.three_sum_closest(ary, q = 0, n = ary.size) ary = ary.sort tuples = [] min_diff = nil n.times do |i| # 0...n pivot, l, r = ary[i], i+1, n-1 while l < r tuple = [pivot, ary[l], ary[r]] diff = (q - tuple.reduce(:+)).abs case when min_diff.nil? || diff < min_diff tuples = [tuple]; min_diff = diff when diff == min_diff tuples << tuple end case q <=> tuple.reduce(:+) when -1 then l += 1 when 1 then r -= 1 else l += 1; r -= 1 end end end tuples end def self.three_sum(ary, q = 0, n = ary.size) # q is the target number. ary = ary.sort tuples = [] n.times do |i| # 0...n pivot, l, r = ary[i], i+1, n-1 while l < r tuple = [pivot, ary[l], ary[r]] case q <=> tuple.reduce(:+) when -1 then l += 1 when 1 then r -= 1 else l += 1; r -= 1; tuples << tuple end end end tuples end # http://discuss.leetcode.com/questions/1070/longest-consecutive-sequence def self.longest_ranges(ary) h = ary.reduce({}) do |h, e| ub = e + h[e+1].to_i # upper bound lb = e - h[e-1].to_i # lower bound h[lb] = h[ub] = ub - lb + 1 h end h.group_by { |_,v| v }.max_by { |k,v| k }[1].map { |e| e[0] }.sort end # http://en.wikipedia.org/wiki/In-place_matrix_transposition # http://stackoverflow.com/questions/9227747/in-place-transposition-of-a-matrix def self.transpose_to_v1(a, n_c) # to n columns case a.size when n_c * n_c # square n = n_c for r in 0..n-2 for c in r+1..n-1 v = r*n + c; w = c*n + r a[v], a[w] = a[w], a[v] end end else transpose = lambda do |i, m_n, n_c| i * n_c % (m_n-1) # mod by m x n - 1. end h = [] # keeps track of what elements are already transposed. m_n = a.size (1...m_n-1).each do |i| unless h[i] j = i until i == (j = transpose.call(i, m_n, n_c)) a[j], a[i] = a[i], a[j] # swaps elements by parallel assignment. h[j] = true end end end end a end def self.transpose_to(a, n_c) # to n columns transpose = lambda do |i, m_n, n| i * n_c % (m_n-1) # mod by m x n - 1. end tranposed_yet = lambda do |i, m_n, n_c| min = i # i must be minimum. loop do break i == min if min >= (i = transpose.call(i, m_n, n_c)) end end m_n = a.size # a.size equals to m x n. transposed = 2 # a[0], and a[m_n-1] are transposed. (1..m_n-2).each do |i| if 1 == i || (transposed < m_n && tranposed_yet.call(i, m_n, n_c)) j = i until i == (j = transpose.call(j, m_n, n_c)) a[j], a[i] = a[i], a[j] # swaps elements by parallel assignment. transposed += 1 end transposed += 1 end end a end def self.min_out_of_cycle(ary, left = 0, right = ary.size - 1) # also called the smallest from a rotated list of sorted numbers. if right == left ary[left] else pivot = (left + right)/2 if ary[right] < ary[pivot] min_out_of_cycle(ary, pivot + 1, right) else min_out_of_cycle(ary, left, pivot) end end end def self.index_out_of_cycle(ary, key, left = 0, right = ary.size-1) while left <= right pivot = (left + right) / 2 if key == ary[pivot] return pivot else if ary[left] <= ary[pivot] if ary[pivot] < key || key < ary[left] left = pivot + 1 else right = pivot - 1 end else if key < ary[pivot] || key > ary[left] right = pivot - 1 else left = pivot + 1 end end end end end def self.find_occurences(ary, key) first_index = first_index(ary, key) if first_index first_index .. last_index(ary, key, first_index...ary.size) end end def self.first_index(ary, key, range = 0...ary.size) if range.count > 1 pivot = range.minmax.reduce(:+) / 2 case key <=> ary[pivot] when -1 then first_index(ary, key, range.min..pivot-1) when 1 then first_index(ary, key, pivot+1..range.max) else first_index(ary, key, range.min..pivot) # up to pivot index end else range.min if key == ary[range.min] # nil otherwise end end def self.last_index(ary, key, range = 0...ary.size) if range.count > 1 pivot = (1 + range.minmax.reduce(:+)) / 2 case key <=> ary[pivot] when -1 then last_index(ary, key, range.min..pivot-1) when 1 then last_index(ary, key, pivot+1..range.max) else last_index(ary, key, pivot..range.max) end else key == ary[range.min] ? range.min : nil end end def self.pairs_of_sum(ary, sum) h = {} ary.each do |x| if h.has_key?(x) h[sum - x] = x else h[sum - x] = nil unless h.has_key?(sum - x) end end h.each.select { |k, v| v } end def self.sort_using_stack!(a) s = [] until a.empty? e = a.pop a.push(s.pop) until s.empty? || s.last < e s.push(e) end a.replace(s) # returns s end def self.indexes_out_of_matrix(m, x) row = 0 col = m[0].size - 1 while row < m.size && col >= 0 return [row, col] if x == m[row][col] if (m[row][col] > x) col -= 1 else row += 1 end end [-1, -1] end def self.merge_sort!(ary = [], range = 0...ary.size, tmp = Array.new(ary.size)) if range.max - range.min > 0 pivot = (range.min + range.max) / 2 merge_sort!(ary, range.min..pivot, tmp) merge_sort!(ary, pivot+1..range.max, tmp) merge!(ary, range.min, pivot+1, range.max, tmp) end end def self.merge!(ary, left, left2, right2, tmp) left1 = left right1 = left2 - 1 last = 0 while left1 <= right1 && left2 <= right2 if ary[left1] < ary[left2] tmp[last] = ary[left1]; last += 1; left1 += 1 else tmp[last] = ary[left2]; last += 1; left2 += 1 end end while left1 <= right1 do tmp[last] = ary[left1]; last += 1; left1 += 1 end while left2 <= right2 do tmp[last] = ary[left2]; last += 1; left2 += 1 end ary[left..right2] = tmp[0..last-1] end def self.max_profit(ary) # from a list of stock prices. left = 0; max_left = max_right = -1; max_profit = 0 ary.each_index do |right| if ary[right] < ary[left] left = right elsif (profit = ary[right] - ary[left]) >= max_profit max_left = left; max_right = right; max_profit = profit end end [max_profit, [max_left, max_right]] end def self.maxsum_subarray(a) # Kadane's algorithm http://en.wikipedia.org/wiki/Maximum_subarray_problem left = 0; max_left = max_right = -1; sum = max_sum = 0 a.size.times do |right| if sum > 0 sum = sum + a[right] else left = right; sum = a[right] end if sum >= max_sum max_left = left; max_right = right; max_sum = sum end end [max_sum, [max_left, max_right]] end def self.maxsum_submatrix(m) prefix_sums_v = Array.new(m.size) { Array.new(m[0].size, 0) } # vertically m.size.times do |r| m[0].size.times do |c| prefix_sums_v[r][c] = (r > 0 ? prefix_sums_v[r - 1][c] : 0) + m[r][c] end end max_top = 0, max_left = 0, max_bottom = 0, max_right = 0; max_sum = m[0][0]; m.size.times do |top| # O (n*(n+1)/2) * O(m) for n * m matrix (top...m.size).each do |bottom| sum = 0; left = 0; m[0].size.times do |right| # O(m) given m columns sum_v = prefix_sums_v[bottom][right] - (top > 0 ? prefix_sums_v[top-1][right] : 0) if sum > 0 sum += sum_v else sum = sum_v; left = right end if sum >= max_sum max_top = top; max_bottom = bottom; max_left = left; max_right = right; max_sum = sum; end end end end [max_sum, [max_top, max_left, max_bottom, max_right]] end def self.max_size_subsquare(m = [[1]]) m.size.times do |r| raise "row[#{r}].size must be '#{m.size}'." unless m.size == m[r].size end prefix_sums_v = Array.new(m.size) { [] } # vertically prefix_sums_h = Array.new(m.size) { [] } # horizontally m.size.times do |r| m.size.times do |c| prefix_sums_v[r][c] = (r > 0 ? prefix_sums_v[r - 1][c] : 0) + m[r][c] prefix_sums_h[r][c] = (c > 0 ? prefix_sums_h[r][c - 1] : 0) + m[r][c] end end max_r = max_c = max_size = -1 m.size.times do |r| m.size.times do |c| (m.size - [r, c].max).downto(1) do |size| if size > max_size && forms_border?(r, c, size, prefix_sums_v, prefix_sums_h) max_r = r; max_c = c; max_size = size end end end end [max_size, [max_r, max_c]] end def self.forms_border?(r, c, s, prefix_sums_v, prefix_sums_h) s == prefix_sums_h[r][c+s-1] - (c > 0 ? prefix_sums_h[r][c-1] : 0) && s == prefix_sums_v[r+s-1][c] - (r > 0 ? prefix_sums_v[r-1][c] : 0) && s == prefix_sums_h[r+s-1][c+s-1] - (c > 0 ? prefix_sums_h[r+s-1][c-1] : 0) && s == prefix_sums_v[r+s-1][c+s-1] - (r > 0 ? prefix_sums_v[r-1][c+s-1] : 0) end def self.peak(ary, range = 0...ary.size) if range.min # nil otherwise k = (range.min + range.max) / 2 case when ary[k-1] < ary[k] && ary[k] > ary[k+1] # at peak k when ary[k-1] < ary[k] && ary[k] < ary[k+1] # ascending peak(ary, k+1..range.max) else # descending peak(ary, range.min..k-1) end end end def self.minmax(ary, range = 0...ary.size) if range.min >= range.max [ary[range.min], ary[range.max]] else pivot = [range.min, range.max].reduce(:+) / 2 mm1 = minmax(ary, range.min..pivot) mm2 = minmax(ary, pivot+1..range.max) [[mm1[0], mm2[0]].min, [mm1[1], mm2[1]].max] end end def self.exclusive_products(ary) # exclusive products without divisions. prefix_products = ary.reduce([]) { |a,e| a + [(a[-1] || 1) * e] } postfix_products = ary.reverse_each.reduce([]) { |a,e| [(a[0] || 1) * e] + a } (0...ary.size).reduce([]) { |a,i| a + [(i > 0 ? prefix_products[i-1] : 1) * (postfix_products[i+1] || 1)] } end def self.find_odd(ary) ary.group_by { |e| e }.detect { |k, v| v.size % 2 == 1 }[0] end def self.missing_numbers(ary) minmax = ary.minmax # by divide and conquer in O(log N) h = ary.reduce({}) { |h,e| h.merge(e => 1 + (h[e] || 0)) } (minmax[0]..minmax[1]).select { |i| !h.has_key?(i) } end def self.find_modes_using_map(ary) max_occurence = 0 # it doesn't matter whether we begin w/ 0, or 1. occurrences = {} ary.reduce([]) do |a,e| occurrences[e] = 1 + (occurrences[e] || 0) if occurrences[e] > max_occurence max_occurence = occurrences[e] a = [e] elsif occurrences[e] == max_occurence a <<= e else a end end end def self.find_modes_using_array(ary) if ary min = ary.min max_hits = 1 modes = [] hits_by_number = [] ary.each do |i| hits_by_number[i-min] = 1 + (hits_by_number[i-min] || 0) if hits_by_number[i-min] > max_hits modes.clear max_hits = hits_by_number[i-min] end modes << i if hits_by_number[i-min] == max_hits end modes end end def self.move_disk(from, to, which) puts "move disk #{which} from #{from} to #{to}" end def self.move_tower(from, to, spare, n) if 1 == n move_disk(from, to, 1) else move_tower(from, spare, to, n-1) move_disk(from, to, n) move_tower(spare, to, from, n-1) end end end # end of Arrays module Strings def self.min_window(positions) # e.g. [[0, 89, 130], [95, 123, 177, 199], [70, 105, 117]], O(L*logK) min_window = window = positions.map { |e| e.shift } # [0, 95, 70] heap = BinaryHeap.new(lambda { |a, b| a[1]<=>b[1] }) heap = window.each_index.reduce(heap) { |h, i| h.offer([i, window[i]]) } until positions[i = heap.poll[0]].empty? window[i] = positions[i].shift min_window = [min_window, window].min_by { |w| w.minmax.reduce(:-).abs } heap.offer([i, window[i]]) end min_window.minmax end def self.min_window_string(text, pattern) # O(|text| + |pattern| + |indices| * log(|pattern|)) p = pattern.each_char.reduce({}) { |h, e| h.merge(e => 1+(h[e]||0)) } # O(|pattern|) t = text.size.times.reduce({}) { |h, i| (h[text[i, 1]] ||= []) << i if p[text[i, 1]]; h } # O(|text|) heap = BinaryHeap.new(lambda { |a, b| a[1] <=> b[1] }) # comparator on found indices. heap = p.reduce(heap) { |h, (k, v)| v.times { h.offer([k, t[k].shift]) }; h } # offers key-index pairs. min_window = window = heap.to_a.map { |kv| kv[1] }.minmax until t[k = heap.poll[0]].empty? heap.offer([k, t[k].shift]) # offers a key-index pair for the min-index key. window = heap.to_a.map { |kv| kv[1] }.minmax min_window = [min_window, window].min_by { |w| w.last - w.first } end text[min_window.first..min_window.last] end def self.index_of_by_rabin_karp(t, p) n = t.size m = p.size hash_p = hash(p, 0, m) hash_t = hash(t, 0, m) return 0 if hash_p == hash_t a_to_m = 31 ** m (0...n-m).each do |offset| hash_t = hash_succ(t, offset, m, a_to_m, hash_t) return offset+1 if hash_p == hash_t end -1 end def self.hash_succ(chars, offset, length, a_to_m, hash) hash = (hash << 5) - hash hash - a_to_m * chars[offset] + chars[offset+length] end def self.hash(chars, offset, length) (offset...offset+length).reduce(0) { |h,i| ((h << 5) - h) + chars[i] } end def self.regex_match?(text, pattern, i = text.size-1, j = pattern.size-1) case when j == -1 i == -1 when i == -1 j == -1 || (j == 1 && pattern[1].chr == '*') when pattern[j].chr == '*' regex_match?(text, pattern, i, j-2) || (pattern[j-1].chr == '.' || pattern[j-1] == text[i]) && regex_match?(text, pattern, i-1, j) when pattern[j].chr == '.' || pattern[j] == text[i] regex_match?(text, pattern, i-1, j-1) else false end end def self.wildcard_match?(text, pattern) case when pattern == '*' true when text.empty? || pattern.empty? text.empty? && pattern.empty? when pattern[0].chr == '*' wildcard_match?(text, pattern[1..-1]) || wildcard_match?(text[1..-1], pattern) when pattern[0].chr == '?' || pattern[0] == text[0] wildcard_match?(text[1..-1], pattern[1..-1]) else false end end def self.bracket_match?(s) a = [] s.each_char do |c| case c when '(' then a.push(')') when '[' then a.push(']') when '{' then a.push('}') when ')', ']', '}' return false if a.empty? || c != a.pop end end a.empty? end def self.combine_parens(n) answers = [] expand_out = lambda do |a| opens = a.last[1] case when a.size == 2*opens then [['(', 1+opens]] # open when n == opens then [[')', opens]] # close else [['(', 1+opens], [')', opens]] # open, or close end end reduce_off = lambda do |a| answers << a.map { |e| e[0] }.join if a.size == 2*n end Search.backtrack([['(', 1]], expand_out, reduce_off) answers end def self.interleave(a, b) answers = [] expand_out = lambda do |s| e = s.last [ [e[0]+1, e[1]], [e[0], e[1]+1] ].select { |e| e[0] < a.size && e[1] < b.size } end reduce_off = lambda do |s| if s.size-1 == a.size + b.size answers << (1...s.size).reduce('') { |z,i| z += a[s[i][0], 1] if s[i-1][0] != s[i][0] z += b[s[i][1], 1] if s[i-1][1] != s[i][1] z } end end Search.backtrack([[-1, -1]], expand_out, reduce_off) answers end def self.anagram?(lhs, rhs) # left- and right-hand sides return true if lhs.equal?(rhs) # reference-equals return false unless lhs.size == rhs.size # value-equals counts = lhs.each_char.reduce({}) { |h, c| h.merge(c => 1 + (h[c] || 0)) } rhs.each_char do |c| return false unless counts.has_key? c counts[c] -= 1 end counts.empty? || counts.values.all? { |e| 0 == e } end def self.non_repeated(s) h = s.each_char.reduce({}) { |h, e| h.merge(e => 1 + (h[e] || 0)) } h.keys.select { |k| h[k] == 1 }.sort.join end def self.lcp(strings = []) # LCP: longest common prefix # strings.reduce { |l,s| l.chop! until l==s[0...l.size]; l } strings.reduce { |l,s| k = 0; k += 1 while l[k] == s[k]; l[0...k] } end @@thirty1 = 31 end class BNode attr_accessor :value, :left, :right, :parent def initialize(value = nil, left = nil, right = nil, parent = nil) @value = value @left = left @right = right @parent = parent end def self.max_sum_of_path(node) if node lsum, lmax_sum = max_sum_of_path(node.left) rsum, rmax_sum = max_sum_of_path(node.right) sum = node.value + [lsum, rsum, 0].max max_sum = [lmax_sum, rmax_sum, sum, node.value + lsum + rsum].compact.max [sum, max_sum] else [0, nil] end end def self.path_of_sum(node, sum, breadcrumbs = [], prefix_sums = [], sum_begins_from = { sum => [0] }) return [] if node.nil? paths = [] breadcrumbs << node.value prefix_sums << node.value + (prefix_sums[-1] || 0) (sum_begins_from[prefix_sums[-1] + sum] ||= []) << breadcrumbs.size (sum_begins_from[prefix_sums[-1]] || []).each do |from| paths += [breadcrumbs[from..-1].join(' -> ')] end paths += path_of_sum(node.left, sum, breadcrumbs, prefix_sums, sum_begins_from) paths += path_of_sum(node.right, sum, breadcrumbs, prefix_sums, sum_begins_from) sum_begins_from[prefix_sums[-1] + sum].pop prefix_sums.pop breadcrumbs.pop paths end def self.common_ancestors(root, p, q) found = 0 breadcrumbs = [] # contains ancestors. enter = lambda do |v| if found < 2 # does not enter if 2 is found. breadcrumbs << v if 0 == found found += [p, q].count { |e| v.value == e } true end end exit = lambda do |v| breadcrumbs.pop if found < 2 && breadcrumbs[-1] == v end dfs(root, enter, exit) # same as follows: order(root, nil, enter, exit) breadcrumbs end def self.succ(node) case when node.nil? then raise ArgumentError, "'node' must be non-null." when node.right then smallest(node.right) else while node.parent break node.parent if node == node.parent.left node = node.parent end end end def self.smallest(node) node.left ? smallest(node.left) : node end def self.insert_in_order(tree, value) if tree.value < value if tree.right insert_in_order(tree.right, value) else tree.right = BNode.new(value) end else if tree.left insert_in_order(tree.left, value) else tree.left = BNode.new(value) end end end def self.last(v, k, a = [k]) # solves the k-th largest element. if v (a[0] > 0 ? last(v.right, k, a) : []) + (a[0] > 0 ? [v.value] : []) + ((a[0] -= 1) > 0 ? last(v.left, k, a) : []) else [] end end def self.last2(v, k) # solves the k-th largest element. a = [] reverse(v, lambda { |v| a << v.value }, lambda { |v| a.size < k }, nil) a end def self.reverse(v, process, enter_iff = nil, exit = nil) if v && (enter_iff.nil? || enter_iff.call(v)) reverse(v.right, process, enter_iff, exit) process and process.call(v) reverse(v.left, process, enter_iff, exit) exit and exit.call(v) end end def self.order(v, process, enter_iff = nil, exit = nil) if v && (enter_iff.nil? || enter_iff.call(v)) order(v.left, process, enter_iff, exit) process and process.call(v) order(v.right, process, enter_iff, exit) exit and exit.call(v) end end def self.order_by_stack(v, process) stack = [] while v || !stack.empty? if v stack.push(v) v = v.left else v = stack.pop process.call(v) v = v.right end end end def self.dfs(v, enter_iff = nil, exit = nil) if enter_iff.nil? || enter_iff.call(v) [v.left, v.right].compact.each { |w| dfs(w, enter_iff, exit) } exit and exit.call(v) end end def self.bfs(v, enter_iff = nil, exit = nil) q = [] q << v # enque, or offer until q.empty? v = q.shift # deque, or poll if enter_iff.nil? || enter_iff.call(v) [v.left, v.right].compact.each { |w| q << w } exit and exit.call(v) end end end def self.maxsum_subtree(v) maxsum = 0 sums = {} exit = lambda do |v| sums[v] = [v.left, v.right].compact.reduce(v.value) do |sum, e| sum += sums[e]; sums.delete(e); sum end maxsum = [maxsum, sums[v]].max end dfs(v, nil, exit) maxsum end def self.parse(preorder, inorder, range_in_preorder = 0..preorder.size-1, range_in_inorder = 0..inorder.size-1) # http://www.youtube.com/watch?v=PAYG5WEC1Gs&feature=plcp if range_in_preorder.count > 0 v = preorder[range_in_preorder][0..0] pivot = inorder[range_in_inorder].index(v) n = BNode.new(v) n.left = parse(preorder, inorder, range_in_preorder.begin+1..range_in_preorder.begin+pivot, range_in_inorder.begin..range_in_inorder.begin+pivot-1) n.right = parse(preorder, inorder, range_in_preorder.begin+pivot+1..range_in_preorder.end, range_in_inorder.begin+pivot+1..range_in_inorder.end) n end end def self.balanced?(tree) max_depth(tree) - min_depth(tree) <= 1 end def self.diameter(tree, memos = {}) if tree [ max_depth(tree.left) + max_depth(tree.right) + 1, self.diameter(tree.left, memos), self.diameter(tree.right, memos) ].max else 0 end end def self.min_depth(tree) tree ? 1 + [min_depth(tree.left), min_depth(tree.right)].min : 0 end def self.max_depth(tree) tree ? 1 + [max_depth(tree.left), max_depth(tree.right)].max : 0 end def self.size(tree) tree ? tree.left.size + tree.right.size + 1 : 0 end def self.sorted?(tree) sorted = true prev_value = nil process_v_iff = lambda do |v| sorted &&= prev_value.nil? || prev_value <= v.value prev_value = v.value end order(tree, process_v_iff, lambda { sorted }, nil) sorted end def self.sorted_by_minmax?(tree, min = nil, max = nil) if tree (min.nil? || tree.value >= min) && (max.nil? || tree.value <= max) && sorted_by_minmax?(tree.left, min, tree.value) && sorted_by_minmax?(tree.right, tree.value, max) else true end end def self.parent!(node) [node.left, node.right].compact.each do |child| child.parent = node parent!(child) end end def self.include?(tree, subtree) return true if subtree.nil? return false if tree.nil? return true if start_with?(tree, subtree) return include?(tree.left, subtree) || include?(tree.right, subtree) end def self.start_with?(tree, subtree) return true if subtree.nil? return false if tree.nil? return false if tree.value != subtree.value return start_with?(tree.left, subtree.left) && start_with?(tree.right, subtree.right) end def self.eql?(lhs, rhs) return true if lhs.nil? && rhs.nil? return false if lhs.nil? || rhs.nil? return false if lhs.value != rhs.value return eql?(lhs.left, rhs.left) && eql?(lhs.right, rhs.right) end def self.of(values, lbound = 0, rbound = values.size - 1) return nil if lbound > rbound pivot = (lbound + rbound) / 2; bnode = BNode.new(values[pivot]) bnode.left = of(values, lbound, pivot - 1) bnode.right = of(values, pivot + 1, rbound) bnode end def self.to_doubly_linked_list(v) head = pred = nil exit = lambda do |v| if pred pred.right = v else head = v end v.left = pred v.right = nil pred = v end bfs(v, nil, exit) head end end class Graph def self.max_flow(source, sink, edges, capacites) # http://en.wikipedia.org/wiki/Edmonds-Karp_algorithm # http://en.wikibooks.org/wiki/Algorithm_Implementation/Graphs/Maximum_flow/Edmonds-Karp paths = [] flows = Array.new(edges.size) { Array.new(edges.size, 0) } loop do residuals = [] # residual capacity minima. residuals[source] = Float::MAX parents = [] entered = [] enter_v_iff = lambda { |v| entered[v] = true if !entered[sink] && !entered[v] && residuals[v] } cross_e = lambda do |x, e| residual = capacites[x][e.y] - flows[x][e.y] if !entered[sink] && !entered[e.y] && residual > 0 parents[e.y] = x residuals[e.y] = [ residuals[x], residual ].min end end bfs(source, edges, enter_v_iff, nil, cross_e) if parents[sink] path = [v = sink] while parents[v] u = parents[v] flows[u][v] += residuals[sink] flows[v][u] -= residuals[sink] path.unshift(v = u) end paths << [residuals[sink], path] else break; end end paths end def self.has_cycle?(edges, directed) edges.each_index.any? do |v| entered = [] exited = [] tree_edges = [] # keyed by children; also called parents map. back_edges = [] # keyed by ancestors, or the other end-point. enter = lambda { |v| entered[v] = true unless entered[v] } exit = lambda { |v| exited[v] = true } cross = lambda do |x, e| if not entered[e.y] tree_edges[e.y] = x elsif (!directed && tree_edges[x] != e.y) || (directed && !exited[x]) (back_edges[e.y] ||= []) << x # x = 1, e.y = 0 end end Graph.dfs(v, edges, enter, nil, cross) !back_edges.empty? end end def self.dijkstra(u, edges) # http://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode # http://www.codeproject.com/Questions/294680/Priority-Queue-Decrease-Key-function-used-in-Dijks parents = [] distances = [] distances[u] = 0 BinaryHeap q = BinaryHeap.new(lambda { |a, b| a[1] <=> b[1] }) q.offer([u, 0]) loop do begin end while (ud = q.poll) && distances[ud[0]] != ud[1] break if ud.nil? edges[u].each do |e| via_u = distances[u] + e.y if distances[y].nil? || distances[y] > via_u distances[y] = via_u parents[y] = u q.offer([v, via_u]) end end end parents end def self.prim(u, edges) parents = [] distances = [] distances[u] = 0 BinaryHeap q = BinaryHeap.new(lambda { |a, b| a[1] <=> b[1] }) q.offer([u, 0]) loop do begin end while (ud = q.poll) && distances[ud[0]] != ud[1] break if ud.nil? edges[u].each do |v| via_u = v.y if distances[v].nil? || distances[v] > via_u distances[v] = via_u parents[v] = u q.offer([v, via_u]) end end end parents end def self.topological_sort(edges) sort = [] entered = [] enter_v_iff = lambda { |v| entered[v] = true if not entered[v] } exit_v = lambda { |v| sort << v } edges.size.times do |v| Graph.dfs(v, edges, enter_v_iff, exit_v) unless entered[v] end sort end def self.find_all(source, edges) all = {} entered = [] enter_v_iff = lambda do |v| entered[v] = true if not entered[v] end cross_e = lambda do |x, e| all[e.y] = true end Graph.dfs(source, edges, enter_v_iff, nil, cross_e) all.keys end def self.color_vertex(graph) answers = [] expand_out = lambda do |a| v = a.size (0..a.max).select { |c| (0...v).all? { |w| (0 == graph[v][w]) or (c != a[w]) } } + [a.max+1] end reduce_off = lambda do |a| answers << [a.max+1, a.dup] if a.size == graph.size end Search.backtrack([0], expand_out, reduce_off) answers.min_by { |e| e[0] } end def self.two_colorable?(v, edges) # two-colorable? means is_bipartite? bipartite = true entered = [] colors = [] enter_v_iff = lambda { |v| entered[v] = true if bipartite && !entered[v] } cross_e = lambda do |x, e| bipartite &&= colors[x] != colors[e.y] colors[e.y] = !colors[x] # inverts the color end edges.each_index do |v| if !entered[v] colors[v] = true bfs(v, edges, enter_v_iff, nil, cross_e) colors = [] end end bipartite end def self.navigate(v, w, edges) paths = [] entered = {} expand_out = lambda do |path| entered[path[-1]] = true edges[path[-1]].map { |e| e.y }.select { |y| not entered[y] } end reduce_off = lambda do |path| paths << path.dup if path[-1] == w end Search.backtrack([v], expand_out, reduce_off) paths end def self.dfs(v, edges, enter_v_iff = nil, exit_v = nil, cross_e = nil) if enter_v_iff.nil? || enter_v_iff.call(v) (edges[v] or []).each do |e| cross_e.call(v, e) if cross_e dfs(e.y, edges, enter_v_iff, exit_v, cross_e) end exit_v.call(v) if exit_v end end def self.bfs(v, edges, enter_v_iff = nil, exit_v = nil, cross_e = nil) q = [] q << v # enque, or offer until q.empty? v = q.shift # deque, or poll if enter_v_iff.nil? || enter_v_iff.call(v) (edges[v] or []).each do |e| cross_e and cross_e.call(v, e) q << e.y end exit_v and exit_v.call(v) end end end end class Edge attr_accessor :y, :weight def initialize(y, weight = 1) @y = y; @weight = weight end def to_s() y end end module Partitions def self.int_partition(n = 0) # http://en.wikipedia.org/wiki/Partition_(number_theory) # e.g., the seven distinct integer partitions of 5 are 5, 4+1, 3+2, 3+1+1, 2+2+1, 2+1+1+1, and 1+1+1+1+1. case when 0 == n then [] when 1 == n then [[1]] else int_partition(n-1).reduce([]) do |a,p| a << p[0..-2] + [p[-1]+1] if p[-2].nil? || p[-2] > p[-1] a << p + [1] # evaluates to self. end end end def self.int_composition(n, k = 1..n) # http://en.wikipedia.org/wiki/Composition_(number_theory) case when 0 == k then [] when 1 == k then [[n]] when k.respond_to?(:reduce) k.reduce([]) { |a, e| a += int_composition(n, e) } else (1...n).reduce([]) { |a, i| a += int_composition(n-i, k-1).map { |c| [i] + c } } end end def self.set_partition(ary = []) # http://oeis.org/wiki/User:Peter_Luschny/SetPartitions prefix_maximums = Array.new(ary.size, 0) restricted_keys = Array.new(ary.size, 0) partitions = [] while succ!(restricted_keys, prefix_maximums) partitions << ary.each_index.reduce([]) { |p, i| (p[restricted_keys[i]] ||= []) << ary[i]; p } end partitions end def self.succ!(restricted_keys, prefix_maximums) k = (restricted_keys.size - 1).downto(0) do |k| break k if 0 == k || restricted_keys[k] < prefix_maximums[k - 1] + 1 end if k > 0 # else nil restricted_keys[k] += 1 prefix_maximums[k] = [prefix_maximums[k], restricted_keys[k]].max (k + 1).upto(restricted_keys.size - 1) do |i| restricted_keys[i] = 0 prefix_maximums[i] = prefix_maximums[i - 1] end restricted_keys end end end module Search def self.backtrack(candidate, expand_out, reduce_off) unless reduce_off.call(candidate) expand_out.call(candidate).each do |e| candidate.push e backtrack(candidate, expand_out, reduce_off) candidate.pop end end end def self.solve_boggle(d, m, k, n = m.size) # k is a max length of a word. words = [] branch_out = lambda do |a| # branches out from the last position (p) p = a[-1] [ # branches out in 8 directions [p[0], p[1]-1], [p[0], p[1]+1], [p[0]-1, p[1]], [p[0]+1, p[1]], [p[0]-1, p[1]-1], [p[0]-1, p[1]+1], [p[0]+1, p[1]-1], [p[0]+1, p[1]+1] ].reject { |q| # rejects invalid branches q[0] < 0 || q[0] >= n || q[1] < 0 || q[1] >= n || p[-1][n*q[0]+q[1]] }.map { |q| # attaches a hash of encountered positions q << p[-1].merge(n*q[0]+q[1] => true) } end reduce_off = lambda do |a| w = a.map { |e| m[e[0]][e[1]] }.join # joins chars into a word words << w if d[w] # collects a dictionary word a.size >= k # tells when to stop backtracking end n.times { |i| n.times { |j| backtrack([[i, j, {n*i+j => true}]], branch_out, reduce_off) } } words end # a k-combination of a set S is a subset of k distinct elements of S, and # the # of k-combinations is equals to the binomial coefficient, n! / (k! * (n-k)!). def self.combination(ary, k = nil, n = ary.size) nCk = [] expand_out = lambda { |c| [ary[c.size], nil] } reduce_off = lambda { |c| nCk << c.compact if c.size == n } Search.backtrack([], expand_out, reduce_off) (k ? nCk.select { |c| c.size == k } : nCk).uniq end # a k-permutation of a set S is an ordered sequence of k distinct elements of S, and # the # of k-permutation of n objects is denoted variously nPk, and P(n,k), and its value is given by n! / (n-k)!. def self.permutation(ary, n = ary.size) nPn = [] indices = (0...n).to_a expand_out = lambda { |p| indices - p } reduce_off = lambda { |p| nPn << p.map { |i| ary[i] } if p.size == n } Search.backtrack([], expand_out, reduce_off) nPn.uniq end def self.permutate(ary, n = ary.size) if 1 == n [ ary.dup ] else h = {} (0...n). select { |i| h[ary[i]] = true unless h[ary[i]] }. map do |i| ary[n-1], ary[i] = ary[i], ary[n-1] p = permutate(ary, n-1) ary[n-1], ary[i] = ary[i], ary[n-1] p end.reduce(:+) end end def self.permutate_succ(ary, n = ary.size) (n-1).downTo(1) do |i| if ary[i] > ary[i-1] ((n-i)/2).times { |j| ary[i+j], ary[n-1-j] = ary[n-1-j], ary[i+j] } (i...n).each { |j| if ary[j] > ary[i-1]; ary[i], ary[j] = ary[j], ary[i]; return end } end end (n/2).times { |j| ary[j], ary[n-1-j] = ary[n-1-j], ary[j] } end # http://www.youtube.com/watch?v=p4_QnaTIxkQ def self.queens_in_peace(n) answers = [] peaceful_at = lambda do |queens, c| queens.each_with_index { |e, i| e != c && queens.size - i != (e - c).abs } end expand_out = lambda do |queens| n.times.select { |c| peaceful_at.call(queens, c) } end reduce_off = lambda do |queens| answers << queens.dup if queens.size == n end Search.backtrack([], expand_out, reduce_off) answers end end module Math def self.negate(a) neg = 0 e = a < 0 ? 1 : -1 while a != 0 a += e neg += e end neg end def self.subtract(a, b) a + negate(b) end def self.abs(a) a < 0 ? negate(a) : a end def self.multiply(a, b) if abs(a) < abs(b) multiply(b, a) else v = abs(b).times.reduce(0) { |v, _| v += a } b < 0 ? negate(v) : v end end def self.different_signs(a, b) a < 0 && b > 0 || a > 0 && b < 0 ? true : false end def self.divide(a, b) if a < 0 && b < 0 divide(negate(a), negate(b)) elsif a < 0 negate(divide(negate(a), b)) elsif b < 0 negate(divide(a, negate(b))) else quotient = 0 divisor = negate(b) until a < b a += divisor quotient += 1 end quotient end end def self.integer_of_prime_factors(k, factors = [3, 5, 7]) queues = factors.map { |e| [e] } x = nil k.times do j = queues.each_index.reduce(0) { |j, i| queues[j][0] < queues[i][0] ? j : i } x = queues[j].shift (j...queues.size).each { |i| queues[i] << x * factors[i] } end x end end class String def self.longest_unique_charsequence(s) offset, length = 0, 1 h = {} n = s.size i = 0 n.times do |j| if h[s[j]] offset, length = i, j-i if j-i > length h[s[i]], i = false, i+1 until s[i] == s[j] i += 1 else h[s[j]] = true end end offset, length = i, n-i if n-i > length s[offset, length] end def self.longest_common_substring(ary) # of k strings suffix_tree = ary.each_index.reduce(Trie.new) do |trie, k| (0...ary[k].size).reduce(trie) { |trie, i| trie[ary[k][i..-1]] = k; trie } end memos = {} exit_v = proc do |key, trie| h = trie.value ? {trie.value => nil} : {} h = trie.children.values.map { |c| memos[c][1] }.reduce(h) { |h, e| h.merge(e) } memos[trie] = [key.join, h] end suffix_tree.dfs(nil, exit_v, []) # to process in postorder. commons = memos.values.select { |v| v[1].size == ary.size }.map { |v| v[0] } commons.group_by { |e| e.size }.max.last end end class Integer def self.gcd_e(a, b) # http://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations if b == 0 a else gcd_e(b, a % b) end end def factorize(m = 2) # http://benanne.net/code/?p=9 @factors ||= case when 1 == self then [] when 0 == self % m then [m] + (self / m).factorize(m) when Math.sqrt(self) <= m then [self] else factorize(m + (m == 2 ? 1 : 2)) end end def factorize2 n, m = self, 2 factors = [] loop do if 1 == n break factors elsif n % m == 0 factors << m n /= m elsif Math.sqrt(n) <= m break factors << n else m += (m == 2 ? 1 : 2) end end end end ########################################################### # Test Cases of algorithm design manual & exercises ########################################################### class TestCases < Test::Unit::TestCase def test_largest_rectangle_in_histogram h = [0, 3, 2, 1, 4, 7, 9, 6, 5, 4, 3, 2] # heights max_area = Arrays.max_area_in_histogram(h) assert_equal 24, max_area end def test_multiply_two_strings # https://gist.github.com/pdu/4978107 end def test_sum_two_strings a = '12345'.reverse b = '123456789'.reverse c = '' zero = '0'.each_byte.next tens = ones = 0 [a.size, b.size].max.times do |i| ones = tens ones += a[i,1].each_byte.next - zero if i < a.size ones += b[i,1].each_byte.next - zero if i < b.size tens, ones = ones / 10, ones % 10 c += (ones + zero).chr end c += (tens + zero).chr if tens > 0 c = c.reverse assert_equal '123469134', c end def test_rain_water a = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] prefix_m = a.reduce([]) { |p, e| p.push(p.empty? ? e : [p.last, e].max) } suffix_m = a.reverse_each.reduce([]) { |p, e| p.push(p.empty? ? e : [p.last, e].max) }.reverse maxima = a.each_index.map { |i| [prefix_m[i], suffix_m[i]].min } volume = a.each_index.map { |i| maxima[i] - a[i] } assert_equal 6, volume.reduce(:+) end def test_longest_ranges assert_equal [1, 4], Arrays.longest_ranges([100, 4, 200, 1, 3, 2]) assert_equal [1, 3, 5, 7], Arrays.longest_ranges([6, 7, 3, 9, 5, 1, 2]) assert_equal [[-1, -1, 2], [-1, 0, 1]], Arrays.three_sum([-1, 0, 1, 2, -1, -4]) assert_equal [[-1, 1, 2]], Arrays.three_sum_closest([-1, 2, 1, -4]) end def test_solve_boggle m = [ ['D', 'G', 'H', 'I'], ['K', 'L', 'P', 'S'], ['Y', 'E', 'U', 'T'], ['E', 'O', 'R', 'N'] ] d = ['SUPER', 'LOB', 'TUX', 'SEA', 'FAME', 'HI', 'YOU', 'YOUR', 'I'] d = d.reduce({}) { |h, e| h[e] = 0; h } # dictionary assert_equal ['HI', 'I', 'SUPER', 'YOU', 'YOUR'], Search.solve_boggle(d, m, 5) # max length (5) end def test_10_x_gcd_n_lcm assert_equal [2, 2, 3], 12.factorize assert_equal [2, 2, 3, 3], 36.factorize assert_equal [2, 2, 3, 3, 3], 108.factorize assert_equal [2, 2, 2, 3, 3], 72.factorize2 assert_equal [2, 2, 2, 3], 24.factorize2 assert_equal [101], 101.factorize2 assert_equal 2**2 * 3**2, Integer.gcd_e(108, 72) end def test_traveling_salesman_problem # Problem: Robot Tour Optimization # Input: A set S of n points in the plane. # Output: What is the shortest cycle tour that visits each point in the set S? graph = [] graph[0] = [0, 10, 15, 20] graph[1] = [5, 0, 9, 10] graph[2] = [6, 13, 0, 12] graph[3] = [8, 8, 9, 0] assert_equal [35, [0, 1, 3, 2, 0]], DP.optimal_tour(graph) end def test_max_flow_ford_fulkerson @@bipartite = <<HERE A0 -⟶ B1 ⟶ D3 ↘ ↘ ↘ C2 ⟶ E4 ⟶ F5 HERE edges = [] edges[0] = [Edge.new(1), Edge.new(2)] edges[1] = [Edge.new(3), Edge.new(4)] edges[2] = [Edge.new(4)] edges[3] = [Edge.new(5)] edges[4] = [Edge.new(5)] edges[5] = [] capacities = [] capacities[0] = [0, 1, 1, 0, 0, 0] capacities[1] = [0, 0, 0, 1, 1, 0] capacities[2] = [0, 0, 0, 0, 1, 0] capacities[3] = [0, 0, 0, 0, 0, 1] capacities[4] = [0, 0, 0, 0, 0, 1] capacities[5] = [0, 0, 0, 0, 0, 0] max_flow = Graph.max_flow(0, 5, edges, capacities) assert_equal 2, max_flow.reduce(0) { |max, e| max += e[0] } assert_equal [[1, "A→C→E→F"], [1, "A→B→D→F"]], max_flow.map { |e| [e[0]] + [e[1].map { |c| ('A'[0] + c).chr }.join('→')] } @@graph = <<HERE A0 ---⟶ D3 ⟶ F5 │ ↖ ↗ │ │ │ C2 │ │ ↓ ↗ ↘ ↓ ↓ B1 ⟵--- E4 ⟶ G6 HERE edges = [] edges[0] = [Edge.new(1), Edge.new(3)] edges[1] = [Edge.new(2)] # B1 → C2 edges[2] = [Edge.new(0), Edge.new(3), Edge.new(4)] # C2 → A0, D3, D4 edges[3] = [Edge.new(4), Edge.new(5)] # D3 → E4, F5 edges[4] = [Edge.new(1), Edge.new(6)] # E4 → B1, G6 edges[5] = [Edge.new(6)] edges[6] = [] capacities = [] capacities[0] = [0, 3, 0, 3, 0, 0, 0] capacities[1] = [0, 0, 4, 0, 0, 0, 0] capacities[2] = [3, 0, 0, 1, 2, 0, 0] capacities[3] = [0, 0, 0, 0, 2, 6, 0] capacities[4] = [0, 1, 0, 0, 0, 0, 1] capacities[5] = [0, 0, 0, 0, 0, 0, 9] capacities[6] = [0, 0, 0, 0, 0, 0, 0] max_flow = Graph.max_flow(0, 6, edges, capacities) assert_equal 5, max_flow.reduce(0) { |max, e| max += e[0] } assert_equal [[3, "A→D→F→G"], [1, "A→B→C→D→F→G"], [1, "A→B→C→E→G"]], max_flow.map { |e| [e[0]] + [e[1].map { |c| ('A'[0] + c).chr }.join('→')] } end def test_graph_coloring # http://www.youtube.com/watch?v=Cl3A_9hokjU graph = [] graph[0] = [0, 1, 0, 1] graph[1] = [1, 0, 1, 1] graph[2] = [0, 1, 0, 1] graph[3] = [1, 1, 1, 0] assert_equal [3, [0, 1, 0, 2]], Graph.color_vertex(graph) graph = [] graph[0] = [0, 1, 1, 0, 1] graph[1] = [1, 0, 1, 0, 1] graph[2] = [1, 1, 0, 1, 0] graph[3] = [0, 0, 1, 0, 1] graph[4] = [1, 1, 0, 1, 0] assert_equal [3, [0, 1, 2, 0, 2]], Graph.color_vertex(graph) end def test_subset_of_sum # http://www.youtube.com/watch?v=WRT8kmFOQTw&feature=plcp # suppose we are given N distinct positive integers # find subsets of these integers that sum up to m. assert_equal [[2, 5], [3, 4], [1, 2, 4]], DP.subset_of_sum([1, 2, 3, 4, 5], 7) assert_equal [[1, 2, 3]], DP.ordinal_of_sum(6, 3) assert_equal [[1, 5], [2, 4]], DP.ordinal_of_sum(6, 2) end def test_make_equation # Given N numbers, 1 _ 2 _ 3 _ 4 _ 5 = 10, # Find how many ways to fill blanks with + or - to make valid equation. end def test_bookshelf_partition assert_equal [[1, 2, 3, 4, 5], [6, 7], [8, 9]], DP.partition_bookshelf([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) end def test_optimal_binary_search_tree keys = [5, 9, 12, 16, 25, 30, 45] probs = [0.22, 0.18, 0.20, 0.05, 0.25, 0.02, 0.08] assert_equal 1000, (1000 * probs.reduce(:+)).to_i assert_equal 2150, (1000 * DP.optimal_binary_search_tree(keys, probs)).to_i end def test_maze maze = [] maze[0] = [1, 1, 1, 1, 1, 0] maze[1] = [1, 0, 1, 0, 1, 1] maze[2] = [1, 1, 1, 0, 0, 1] maze[3] = [1, 0, 0, 1, 1, 1] maze[4] = [1, 1, 0, 1, 0, 0] maze[5] = [1, 1, 0, 1, 1, 1] answers = [] entered = [] # maze.size * r + c, e.g. 6*r + c expand_out = lambda do |a| r, c = a[-1] (entered[r] ||= [])[c] = true [[r-1, c], [r+1, c], [r, c-1], [r, c+1]].select { |p| p[0] > -1 && p[0] < maze.size && p[1] > -1 && p[1] < maze[0].size }.select { |p| !(entered[p[0]] ||= [])[p[1]] && 1 == maze[p[0]][p[1]] } end reduce_off = lambda do |a| answers << a.dup if a[-1][0] == maze.size-1 && a[-1][1] == maze[0].size-1 end Search.backtrack([[0, 0]], expand_out, reduce_off) # a, i, input, branch, reduce assert_equal 1, answers.size assert_equal [5, 5], answers.last.last end def test_diameter_of_btree # tree input: a # b # c f # d g # e tree = BNode.parse('abcdefg', 'cdebfga') assert_equal 6, BNode.diameter(tree) end def test_minmax_by_divide_n_conquer assert_equal 6, Arrays.peak([1, 5, 7, 9, 15, 18, 21, 19, 14]) assert_equal [1, 9], Arrays.minmax([1, 3, 5, 7, 9, 2, 4, 6, 8]) assert_equal [0, [0, 0]], Arrays.max_profit([30]) assert_equal [30, [2, 3]], Arrays.max_profit([30, 40, 20, 50, 10]) end def test_topological_sort # graph: D3 ⇾ H7 # ↑ # ┌──────── B1 ⇾ F5 # ↓ ↑ ↑ # J9 ⇽ E4 ⇽ A0 ⇾ C2 ⇾ I8 # ↓ # G6 edges = [] edges[0] = [Edge.new(1), Edge.new(2), Edge.new(4), Edge.new(6)] # 1, 2, 4, and 6 edges[1] = [Edge.new(3), Edge.new(5), Edge.new(9)] # 3, 5, and 9 edges[2] = [Edge.new(5), Edge.new(8)] # 5, 8 edges[3] = [Edge.new(7)] # 7 edges[4] = [Edge.new(9)] # 9 edges[5] = edges[6] = edges[7] = edges[8] = edges[9] = [] assert_equal [7, 3, 5, 9, 1, 8, 2, 4, 6, 0], Graph.topological_sort(edges) end def test_navigatable_n_two_colorable # Given a undirected graph based on a set of nodes and links, # write a program that shows all the possible paths from a source node to a destination node. # It is up to you to decide what kind of structure you want to use to represent the nodes and links. # A path may traverse any link at most once. # # e.g. a --- d # | X | # b --- c edges = [] # a composition of a graph edges[0] = [Edge.new(1), Edge.new(2), Edge.new(3)] edges[1] = [Edge.new(0), Edge.new(2), Edge.new(3)] edges[2] = [Edge.new(0), Edge.new(1), Edge.new(3)] edges[3] = [Edge.new(0), Edge.new(1), Edge.new(2)] paths = Graph.navigate(0, 3, edges) assert_equal [[0, 1, 2, 3], [0, 1, 3], [0, 2, 3], [0, 3]], paths assert_equal ["a→b→c→d", "a→b→d", "a→c→d", "a→d"], paths.map {|a| a.map { |e| ('a'[0] + e).chr }.join('→') } # graph: B1 ― A0 # | | # C2 ― D3 edges = [] edges << [Edge.new(1), Edge.new(3)] # A0 - B1, A0 - D3 edges << [Edge.new(0), Edge.new(2)] # B1 - A0, B1 - C2 edges << [Edge.new(1), Edge.new(3)] # C2 - B1, C2 - D3 edges << [Edge.new(0), Edge.new(2)] # D3 - A0, D3 - C2 assert Graph.two_colorable?(0, edges) # graph: B1 ― A0 # | X # C2 ― D3 edges = [] edges << [Edge.new(1), Edge.new(2)] # A0 - B1, A0 - C2 edges << [Edge.new(0), Edge.new(2), Edge.new(3)] # B1 - A0, B1 - C2, B1 - D3 edges << [Edge.new(0), Edge.new(1), Edge.new(3)] # C2 - A0, C2 - B1, C2 - D3 edges << [Edge.new(1), Edge.new(2)] # D3 - B1, D3 - C2 assert !Graph.two_colorable?(0, edges) end def test_prime? assert Numbers.prime?(2) assert Numbers.prime?(3) assert Numbers.prime?(101) assert_equal 11, Numbers.prime(9) end def test_saurab_peaceful_queens assert_equal [[1, 3, 0, 2], [2, 0, 3, 1]], Search.queens_in_peace(4) end def test_order_matrix_chain_multiplication assert_equal [4500, [0, 1]], DP.order_matrix_chain_multiplication([10, 30, 5, 60]) assert_equal [3500, [1, 0]], DP.order_matrix_chain_multiplication([50, 10, 20, 5]) end def test_longest_common_n_increasing_subsequences assert_equal ["eca"], DP.longest_common_subsequence('democrat', 'republican') assert_equal ["1", "a"], DP.longest_common_subsequence('a1', '1a').sort assert_equal ["ac1", "ac2", "bc1", "bc2"], DP.longest_common_subsequence('abc12', 'bac21').sort assert_equal ["aba", "bab"], DP.longest_common_substring('abab', 'baba') assert_equal ["abacd", "dcaba"], DP.longest_common_substring('abacdfgdcaba', 'abacdgfdcaba') assert_equal 5, DP.longest_palindromic_subsequence('xaybzba') assert_equal [1, 3, 3], DP.longest_increasing_subsequence([1, 3, 3, 2]) assert_equal [1, 2, 3], DP.longest_increasing_subsequence([7, 8, 1, 5, 6, 2, 3]) assert_equal [1, 5, 6], DP.longest_increasing_subsequence_v2([7, 8, 1, 5, 6, 2, 3]) end def test_edit_distance assert_equal [3, "SMMMSMI"], DP.edit('kitten', 'sitting') end def test_LRU_cache c = LRUCache.new(3).put(1, 'a').put(2, 'b').put(3, 'c') assert_equal 'a', c.get(1) assert_equal [[2, "b"], [3, "c"], [1, "a"]], c.to_a assert_equal 'b', c.get(2) assert_equal [[3, "c"], [1, "a"], [2, "b"]], c.to_a assert_equal [[1, "a"], [2, "b"], [4, "d"]], c.put(4, 'd').to_a assert_equal nil, c.get(3) assert_equal 'a', c.get(1) assert_equal [[2, "b"], [4, "d"], [1, "a"]], c.to_a end def test_one_sided_binary_search # algorithm design manual 4.9.2 # find the exact point of transition within an array that contains a run of 0's and an unbounded run of 1's. # return 1 if 1 == ary[1] # return 1..∞ { |n| break (Arrays.first_index(ary, 2 ** (n-1) + 1, 2 ** n) if 1 == ary[2 ** n]) } end def test_ebay_sales_fee # http://pages.ebay.com/help/sell/fees.html # http://www.ruby-doc.org/gems/docs/a/algorithms-0.5.0/Containers/RubyRBTreeMap.html # http://www.ruby-doc.org/gems/docs/a/algorithms-0.5.0/Containers/RubySplayTreeMap.html # the basic cost of selling an item is the insertion fee plus the final value fee. # * $0.5 for buy it now or fixed price format listings # * 7% for initial $50 (max: $3.5), 5% for next $50 - $1000 (max: $47.5), and 2% for the remaining. # http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html # formulas = new TreeMap() {{ put($0, Pair.of($0, 7%)); put($50, Pair.of($3.5, 5%)); put($1000, Pair.of($51, 2%)) }} # sale = $1100; formula = formulas.floorEntry(sale); # fees = 0.5 /* insertion */ + formula.value().first() /* final base */ + formula.value().second() * (sale - formula.key()) /* final addition */ end def test_reverse_decimal assert_equal 321, Numbers.reverse_decimal(123) assert_equal 21, Numbers.reverse_decimal(120) assert_equal 1, Numbers.reverse_decimal(100) end # def test_circular_buffer # buffer = CircularBuffer.new(3) # assert buffer.empty? && !buffer.full? # buffer.enq(10).enq(20).enq(30) # assert_raise(RuntimeError) { buffer.enq(40) } # assert buffer.full? # # assert_equal 10, buffer.deq # assert_equal 20, buffer.deq # assert_equal 30, buffer.deq # assert_raise(RuntimeError) { buffer.deq } # assert buffer.empty? # end def test_non_repeated assert_equal 'abc', Strings.non_repeated('abc') assert_equal 'a', Strings.non_repeated('abcbcc') end def test_transpose_matrix_in_1d_array assert_equal [0, 3, 6, 1, 4, 7, 2, 5, 8], Arrays.transpose_to_v1((0...9).to_a, 3) # square matrix assert_equal [0, 4, 1, 5, 2, 6, 3, 7], Arrays.transpose_to((0...8).to_a, 2) assert_equal [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11], Arrays.transpose_to((0...12).to_a, 3) assert_equal [0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11], Arrays.transpose_to((0...12).to_a, 4) end def test_exclusive_products assert_equal [120, 60, 40, 30, 24], Arrays.exclusive_products([1, 2, 3, 4, 5]) end def test_priority_heap h = BinaryHeap.new h.offer(40).offer(50).offer(80).offer(60).offer(20).offer(30).offer(10).offer(90).offer(70) assert_equal 10, h.peek assert_equal 10, h.poll assert_equal 20, h.poll assert_equal 30, h.poll assert_equal 40, h.poll assert_equal 50, h.poll assert_equal 60, h.poll assert_equal 70, h.poll assert_equal 80, h.poll assert_equal 90, h.poll assert_equal nil, h.poll end def test_partition assert_equal [[5]], Partitions.int_composition(5, 1) assert_equal [[1,4],[2,3],[3,2],[4,1]], Partitions.int_composition(5, 2) assert_equal [[1,1,3],[1,2,2],[1,3,1],[2,1,2],[2,2,1],[3,1,1]], Partitions.int_composition(5, 3) assert_equal [[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1]], Partitions.int_composition(5, 4) assert_equal [[1,1,1,1,1]], Partitions.int_composition(5, 5) assert_equal 16, Partitions.int_composition(5).size assert_equal [[1]], Partitions.int_partition(1) assert_equal [[2], [1, 1]], Partitions.int_partition(2) assert_equal [[3], [2, 1], [1, 1, 1]], Partitions.int_partition(3) assert_equal [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]], Partitions.int_partition(4) assert_equal ['{a,b}, {c}', '{a,c}, {b}', '{a}, {b,c}', '{a}, {b}, {c}'], Partitions.set_partition(['a', 'b', 'c']).map {|p| p.map {|a| "{#{a.join(',')}}"}.join(', ') } # http://code.activestate.com/recipes/577211-generate-the-partitions-of-a-set-by-index/history/1/ # http://oeis.org/wiki/User:Peter_Luschny/SetPartitions # http://en.wikipedia.org/wiki/Partition_(number_theory) # http://mathworld.wolfram.com/RestrictedGrowthString.html # http://oeis.org/wiki/User:Peter_Luschny end def test_from_strings # preorder: abcdefg # inorder: cdebagf # tree: a # b f # c g # d # e # tree = BNode.parse('abcdefg', 'cdebagf') assert_equal 'a', tree.value assert_equal 'b', tree.left.value assert_equal 'c', tree.left.left.value assert_equal 'd', tree.left.left.right.value assert_equal 'e', tree.left.left.right.right.value assert_equal 'f', tree.right.value assert_equal 'g', tree.right.left.value assert_equal nil, tree.left.right assert_equal nil, tree.left.left.left assert_equal nil, tree.left.left.right.left assert_equal nil, tree.left.left.right.right.left assert_equal nil, tree.left.left.right.right.right assert_equal nil, tree.right.right assert_equal nil, tree.right.left.left assert_equal nil, tree.right.left.right end def test_knapsack skus = [[2, 2], [1, 1], [10, 4], [2, 1], [4, 12]] assert_equal [36, [2, 2, 2, 3, 3, 3]], DP.knapsack_unbounded(skus, 15) # max sum = 36 assert_equal [15, [3, 2, 1, 0]], DP.knapsack01(skus, 15) # max sum = 15 # http://www.youtube.com/watch?v=ItF22I8f3Xs&feature=plcp assert_equal [1, 2, 1], DP.balanced_partition([5, 1, 2, 1]) assert_equal [8, 4, 5], DP.balanced_partition([7, 11, 5, 4, 8]) assert_equal [3, 0], DP.jump_game2([3, 2, 1, 0, 4]) assert_equal [1, 3], DP.jump_game2([2, 3, 1, 1, 4]) prices = [1, 5, 8, 9, 10, 17, 17, 20] lengths = [1, 2, 3, 4, 5, 6, 7, 8] assert_equal [5, [2]], DP.cut_rod(prices, lengths, 2) assert_equal [13, [2, 3]], DP.cut_rod(prices, lengths, 5) assert_equal [27, [2, 2, 6]], DP.cut_rod(prices, lengths, 10) end def test_find_modes_n_missing_numbers assert_equal [3, 4], Arrays.find_modes_using_map([1, 2, 3, 4, 2, 3, 4, 3, 4]) assert_equal [3, 4], Arrays.find_modes_using_array([1, 2, 3, 4, 2, 3, 4, 3, 4]) assert_equal [], Arrays.missing_numbers([1, 2, 3]) assert_equal [2, 4, 5], Arrays.missing_numbers([1, 3, 6]) end def test_index_of_by_rabin_karp assert_equal 1, Strings.index_of_by_rabin_karp("aabab", "ab") assert_equal 2, Strings.index_of_by_rabin_karp("aaabcc", "abc") assert_equal 2, Strings.index_of_by_rabin_karp("aaabc", "abc") assert_equal 0, Strings.index_of_by_rabin_karp("abc", "abc") assert_equal 0, Strings.index_of_by_rabin_karp("abcc", "abc") assert_equal -1, Strings.index_of_by_rabin_karp("abc", "xyz") assert_equal -1, Strings.index_of_by_rabin_karp("abcc", "xyz") end def test_quickfind_n_mergesort assert_equal 1, [9, 8, 7, 6, 5, 4, 3, 2, 1, 0].quickfind_k!(1)[1] assert_equal 2, [9, 8, 7, 4, 5, 6, 3, 2, 1, 0].quickfind_k!(2)[2] assert_equal 3, [9, 8, 7, 6, 5, 4, 1, 2, 3, 0].quickfind_k!(3)[3] assert_equal [0, 1, 2, 3], [9, 8, 7, 6, 5, 4, 1, 2, 3, 0].quicksort_k!(3)[0..3] # http://en.wikipedia.org/wiki/Merge_sort assert_equal [0, 2, 3, 5, 6, 8, 9], Arrays.merge_sort!([3, 6, 9, 2, 5, 8, 0]) end def test_bsearch a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 4] assert_equal 5, a.bsearch_last_by { |e| 3 <=> e } assert_equal nil, a.bsearch_last_by { |e| 5 <=> e } assert_equal 9, a.bsearch_last_by { |e| 4 <=> e } assert_equal 2, a.bsearch_last_by { |e| 2 <=> e } assert_equal 1, a.bsearch_last_by { |e| 1 <=> e } assert_equal nil, a.bsearch_last_by { |e| 0 <=> e } assert_equal nil, a.bsearch_range_by { |e| 5 <=> e } assert_equal 6..9, a.bsearch_range_by { |e| 4 <=> e } assert_equal 3..5, a.bsearch_range_by { |e| 3 <=> e } assert_equal 2..2, a.bsearch_range_by { |e| 2 <=> e } assert_equal 0..1, a.bsearch_range_by { |e| 1 <=> e } assert_equal nil, a.bsearch_range_by { |e| 0 <=> e } end def test_bracket_n_wildcard_match? assert !Strings.regex_match?('c', 'a') assert !Strings.regex_match?('aa', 'a') assert Strings.regex_match?("aa","aa") assert !Strings.regex_match?("aaa","aa") assert Strings.regex_match?("aa", "a*") assert Strings.regex_match?("aa", ".*") assert Strings.regex_match?("ab", ".*") assert Strings.regex_match?("cab", "c*a*b") assert Strings.wildcard_match?('q', '?') assert Strings.wildcard_match?('', '*') assert !Strings.wildcard_match?('x', '') assert Strings.wildcard_match?('c', '*') assert Strings.wildcard_match?('ba', '*') assert Strings.wildcard_match?('cbax', '*x') assert Strings.wildcard_match?('xcba', 'x*') assert Strings.wildcard_match?('abxcdyef', '*x*y*') assert Strings.bracket_match?("{}") assert Strings.bracket_match?("[]") assert Strings.bracket_match?("()") assert Strings.bracket_match?("[ { ( a + b ) * -c } % d ]") end def test_from_to_excel_column assert_equal 'ABC', Numbers.to_excel_column(731) assert_equal 731, Numbers.from_excel_column(Numbers.to_excel_column(731)) end def test_fibonacci assert_equal 0, Numbers.fibonacci(0) assert_equal 1, Numbers.fibonacci(1) assert_equal 8, Numbers.fibonacci(6) end def test_manual_1_28_divide # 1-28. Write a function to perform integer division w/o using either the / or * operators. assert_equal 85, Numbers.divide(255, 3) assert !Numbers.power_of_2?(5) assert Numbers.power_of_2?(4) assert Numbers.power_of_2?(2) assert Numbers.power_of_2?(1) assert !Numbers.power_of_2?(0) assert_equal 5, Numbers.abs(-5) assert_equal 7, Numbers.abs(7) assert_equal [1, 11], Numbers.minmax(1, 11) assert_equal [-2, 0], Numbers.minmax(0, -2) assert Numbers.opposite_in_sign?(-10, 10) assert !Numbers.opposite_in_sign?(-2, -8) end # 1-29. There are 25 horses. At most, 5 horses can race together at a time. You must determine the fastest, second fastest, and third fastest horses. Find the minimum number of races in which this can be done. # 2-43. You are given a set S of n numbers. You must pick a subset S' of k numbers from S such that the probability of each element of S occurring in S' is equal (i.e., each is selected with probability k / n). You may make only one pass over the numbers. What if n is unknown? # 2-47. You are given 10 bags of gold coins. Nine bags contain coins that each weigh 10 grams. One bag contains all false coins that weigh one gram less. You must identify this bag in just one weighing. You have a digital balance that reports the weight of what is placed on it. # 2-51. Six pirates must divide $300 dollars among themselves. The division is to proceed as follows. The senior pirate proposes a way to divide the money. Then the pirates vote. If the senior pirate gets at least half the votes he wins, and that division remains. If he doesn't, he is killed and then the next senior-most pirate gets a chance to do the division. Now you have to tell what will happen and why (i.e., how many pirates survive and how the division is done)? All the pirates are intelligent and the first priority is to stay alive and the next priority is to get as much money as possible. # 3-21. Write a function to compare whether two binary trees are identical. Identical trees have the same key value at each position and the same structure. # 3-22. Write a program to convert a binary search tree into a linked list. # 3-28. You have an unordered array X of n integers. Find the array M containing n elements where Mi is the product of all integers in X except for Xi. You may not use division. You can use extra memory. (Hint: There are solutions faster than O(n2).) # 3-29. Give an algorithm for finding an ordered word pair (e.g., New York) occurring with the greatest frequency in a given webpage. Which data structures would you use? Optimize both time and space. def test_manual_4_45_smallest_snippet_of_k_words # Given a search string of three words, find the smallest snippet of the document that contains all three of # the search words --- i.e. the snippet with smallest number of words in it. You are given the index positions # where these words occur in search strings, such as word1: (1, 4, 5), word2: (3, 9, 10), word3: (2, 6, 15). # Each of the lists are in sorted order as above. # http://rcrezende.blogspot.com/2010/08/smallest-relevant-text-snippet-for.html # http://blog.panictank.net/tag/algorithm-design-manual/ assert_equal [117, 130], Strings.min_window([[0, 89, 130], [95, 123, 177, 199], [70, 105, 117]]) assert_equal 'adab', Strings.min_window_string('abracadabra', 'abad') end # 4-45. Given 12 coins. One of them is heavier or lighter than the rest. Identify this coin in just three weightings. # http://learntofish.wordpress.com/2008/11/30/solution-of-the-12-balls-problem/ def test_manual_7_14_permutate # 7-14. Write a function to find all permutations of the letters in a particular string. permutations = ["aabb", "abab", "abba", "baab", "baba", "bbaa"] assert_equal permutations, Search.permutate('aabb'.chars.to_a).map { |p| p.join }.sort assert_equal permutations, Search.permutation('aabb'.chars.to_a).map { |p| p.join }.sort end def test_manual_7_15_k_element_subsets # 7-15. Implement an efficient algorithm for listing all k-element subsets of n items. assert_equal ['abc'], Search.combination('abc'.chars.to_a, 3).map { |e| e.join } assert_equal ['ab', 'ac', 'bc'], Search.combination('abc'.chars.to_a, 2).map { |e| e.join } assert_equal [''], Search.combination('cba'.chars.to_a, 0).map { |e| e.join } assert_equal ['abb', 'ab', 'a', 'bb', 'b', ''], Search.combination('abb'.chars.to_a).map { |e| e.join } end # 7-16. An anagram is a rearrangement of the letters in a given string into a sequence of dictionary words, # like Steven Skiena into Vainest Knees. Propose an algorithm to construct all the anagrams of a given string. # 7-17. Telephone keypads have letters on each numerical key. Write a program that generates all possible words # resulting from translating a given digit sequence (e.g., 145345) into letters. # 7-18. You start with an empty room and a group of n people waiting outside. At each step, # you may either admit one person into the room, or let one out. Can you arrange a sequence of 2n steps, # so that every possible combination of people is achieved exactly once? # 7-19. Use a random number generator (rng04) that generates numbers from {0, 1, 2, 3, 4} with equal probability # to write a random number generator that generates numbers from 0 to 7 (rng07) with equal probability. # What are expected number of calls to rng04 per call of rng07? # 8-24. Given a set of coin denominators, find the minimum number of coins to make a certain amount of change. def test_manual_8_24_make_change assert_equal [], DP.minimal_coins(0, [1, 5, 7]) assert_equal [5, 5], DP.minimal_coins(10, [1, 5, 7]) assert_equal [1, 5, 7], DP.minimal_coins(13, [1, 5, 7]) assert_equal [7, 7], DP.minimal_coins(14, [1, 5, 7]) end # 8-25. You are given an array of n numbers, each of which may be positive, negative, # or zero. Give an efficient algorithm to identify the index positions i and j to the # maximum sum of the ith through jth numbers. # 8-26. Observe that when you cut a character out of a magazine, the character on the # reverse side of the page is also removed. Give an algorithm to determine whether # you can generate a given string by pasting cutouts from a given magazine. Assume # that you are given a function that will identify the character and its position on # the reverse side of the page for any given character position. def test_1_3_anagram? # Given two strings, write a method to determine if one is a permutation of the other. assert Strings.anagram?(nil, nil) assert Strings.anagram?("", "") assert !Strings.anagram?("", "x") assert Strings.anagram?("a", "a") assert Strings.anagram?("ab", "ba") assert Strings.anagram?("aab", "aba") assert Strings.anagram?("aabb", "abab") assert !Strings.anagram?("a", "b") assert !Strings.anagram?("aa", "ab") end def test_2_5_sum_of_2_single_linked_lists # 524 + 495 = 1019 # There are two decimal numbers represented by a linked list, where each node contains a single digit. # The digits are stored in reverse order, such that the 1's digit is at the head of the list. # Write a function that adds the two numbers and returns the sum as a linked list. i524 = SNode.new(4, SNode.new(2, SNode.new(5))) i495 = SNode.new(5, SNode.new(9, SNode.new(4))) assert_equal "9 → 1 → 0 → 1 → ⏚", SNode.sum(i524, i495).to_s end def test_2_6_find_cycle_n_reverse_every2! # Given a linked list with a cycle, implement an algorithm which returns the node at the beginning of the loop. l = SNode.new([1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e']) e = l.last e.next_ = l.next(7) assert_equal 'e', SNode.find_cycle(l).value # has a back-link to cut off. assert_equal nil, SNode.find_cycle(SNode.new([1, 2, 3])) end def test_reverse_every2! assert SNode.eql?(SNode.new([5, 4, 3, 2, 1]), SNode.reverse!(SNode.new([1, 2, 3, 4, 5]))) assert_equal "2 → 1 → ⏚", SNode.reverse_every2!(SNode.new([1, 2])).to_s assert_equal "2 → 1 → 3 → ⏚", SNode.reverse_every2!(SNode.new([1, 2, 3])).to_s assert_equal "2 → 1 → 4 → 3 → ⏚", SNode.reverse_every2!(SNode.new([1, 2, 3, 4])).to_s assert_equal "2 → 1 → 4 → 3 → 5 → ⏚", SNode.reverse_every2!(SNode.new([1, 2, 3, 4, 5])).to_s end def test_3_2_min_stack # Design and implement a stack of integers that has an additional operation 'minimum' besides 'push' and 'pop', # that all run in constant time, e.g., push(2), push(3), push(2), push(1), pop, pop, and minimum returns 2. stack = MinMaxStack.new assert stack.minimum.nil? stack.push 2 # [nil, 2] stack.push 3 # [nil, 2, 3] stack.push 2 # [nil, 2, 3, 2, 2] stack.push 1 # [nil, 2, 3, 2, 2, 2, 1] assert_equal 1, stack.minimum assert_equal 1, stack.pop # [nil, 2, 3, 2, 2] assert_equal 2, stack.minimum assert_equal 2, stack.pop # [nil, 2, 3] assert_equal 2, stack.minimum assert_equal 3, stack.pop # [nil, 2] assert_equal 2, stack.minimum assert_equal 2, stack.pop # [] assert stack.minimum.nil? end def test_3_4_hanoi Arrays.move_tower('A', 'C', 'B', 3) # from 'A' to 'C' via 'B'. end def test_3_5_queque_by_good_code_coverage # this test case satisfies condition & loop coverage(s). http://en.wikipedia.org/wiki/Code_coverage # Implement a queue using two stacks. q = Queueable.new # stack1: [ ], stack2: [ ] q.enq 1 # stack1: [1], stack2: [ ] q.enq 2 # stack1: [1, 2], stack2: [ ] assert_equal 1, q.deq # stack1: [ ], stack2: [2], coverage: true, and 2 iterations assert_equal 2, q.deq # stack1: [ ], stack2: [ ], coverage: false q.enq 3 # stack1: [3], stack2: [ ] assert_equal 3, q.deq # stack1: [ ], stack2: [ ], coverage: true, and 1 iteration assert_equal nil, q.deq # stack1: [ ], stack2: [ ], coverage: true, and 0 iteration end def test_3_6_sort_by_stack assert_equal [-4, -3, 1, 2, 5, 6], Arrays.sort_using_stack!([5, -3, 1, 2, -4, 6]) end def test_4_1_balanced_n_4_5_binary_search_tree? # 4.1. Implement a function to check if a binary tree is balanced. # 4.5. Implement a function to check if a binary tree is a binary search tree. assert BNode.balanced?(BNode.of([1, 3, 4, 7, 2, 5, 6])) assert BNode.sorted?(BNode.of([1, 2, 3, 4, 5, 6, 7])) assert !BNode.sorted?(BNode.of([1, 2, 3, 4, 8, 6, 7])) assert BNode.sorted_by_minmax?(BNode.of([1, 2, 3, 4, 5, 6, 7])) assert !BNode.sorted_by_minmax?(BNode.of([1, 2, 3, 4, 8, 6, 7])) values = [] BNode.order_by_stack(BNode.of([1, 2, 3, 4, 8, 6, 7]), lambda {|v| values << v.value}) assert_equal [1, 2, 3, 4, 8, 6, 7], values end def test_has_cycle_in_directed_n_undirected_graphs # graph: B1 ← C2 → A0 # ↓ ↗ # D3 ← E4 edges = [] edges << [] # out-degree of 0 edges << [Edge.new(3, 4)] # B1 → D3 edges << [Edge.new(0, 4), Edge.new(1, 6)] # C2 → A0, C2 → B1 edges << [Edge.new(2, 9)] # D3 → C2 edges << [Edge.new(3, 3)] # E4 → D3 assert Graph.has_cycle?(edges, true) # graph: B1 ← C2 → A0 # ↓ ↓ # D3 ← E4 edges = [] edges << [] edges << [Edge.new(3)] edges << [Edge.new(0), Edge.new(1), Edge.new(4)] edges << [] edges << [Edge.new(3)] assert Graph.has_cycle?(edges, true) # undirected graph: A0 - B1 - C2 edges = [] edges[0] = [Edge.new(1)] # A0 - B1 edges[1] = [Edge.new(0), Edge.new(2)] # B1 - A0, B1 - C2 edges[2] = [Edge.new(1)] # C2 - B1 assert !Graph.has_cycle?(edges, false) # undirected graph: A0 - B1 - C2 - A0 edges[0] << Edge.new(2) # A0 - C2 edges[2] << Edge.new(0) # C2 - A0 assert Graph.has_cycle?(edges, false) end def test_4_2_reachable? # Given a directed graph, design an algorithm to find out whether there is a route between two nodes. # http://iamsoftwareengineer.blogspot.com/2012/06/given-directed-graph-design-algorithm.html # graph: B1 ← C2 → A0 # ↓ ↗ # D3 ← E4 edges = [] edges << [] # out-degree of 0 edges << [Edge.new(3)] # B1 → D3 edges << [Edge.new(0), Edge.new(1)] # C2 → A0, C2 → B1 edges << [Edge.new(2)] # D3 → C2 edges << [Edge.new(3)] # E4 → D3 can_reach = lambda do |source, sink| all = Graph.find_all(source, edges) all.index(sink) end assert can_reach.call(4, 0) assert !can_reach.call(0, 4) assert !can_reach.call(3, 4) end def test_4_3_to_binary_search_tree # Given a sorted (increasing order) array, implement an algorithm to create a binary search tree with minimal height. # tree: 4 # 2 6 # 1 3 5 7 expected = BNode.new(4, BNode.new(2, BNode.new(1), BNode.new(3)), BNode.new(6, BNode.new(5), BNode.new(7))) assert BNode.eql?(expected, BNode.of([1, 3, 5, 7, 2, 4, 6].sort)) end def test_convert_binary_tree_to_doubly_linked_list # http://www.youtube.com/watch?v=WJZtqZJpSlQ # http://codesam.blogspot.com/2011/04/convert-binary-tree-to-double-linked.html # tree: 1 # 2 3 # 4 5 6 7 tree = BNode.of([4, 2, 5, 1, 6, 3, 7]) head = read = BNode.to_doubly_linked_list(tree) assert_equal nil, head.left values = [] while read values << read.value read = read.right end assert_equal [1, 2, 3, 4, 5, 6, 7], values end def test_4_6_successor_in_order_traversal # tree: f # a # b # e # d # c c = BNode.new('c') d = BNode.new('d', c, nil) e = BNode.new('e', d, nil) b = BNode.new('b', nil, e) a = BNode.new('a', nil, b) f = BNode.new('f', a, nil) BNode.parent!(f) assert_equal 'c', BNode.succ(b).value assert_equal 'f', BNode.succ(e).value assert_equal 'b', BNode.succ(a).value assert_equal 'd', BNode.succ(c).value assert_equal 'e', BNode.succ(d).value assert_equal nil, BNode.succ(f) assert_equal ["f"], BNode.last(f, 1) assert_equal ["f", "e", "d"], BNode.last(f, 3) assert_equal ["f", "e", "d", "c", "b", "a"], BNode.last(f, 6) assert_equal ["f", "e", "d", "c", "b", "a"], BNode.last(f, 7) assert_equal ["f"], BNode.last2(f, 1) assert_equal ["f", "e", "d", "c", "b", "a"], BNode.last2(f, 7) end def test_dfs_in_binary_trees # tree: a # b # c # d e d = BNode.new('d') e = BNode.new('e') c = BNode.new('c', d, e) b = BNode.new('b', c, nil) a = BNode.new('a', nil, b) preorder = [] postorder = [] bfs = [] BNode.dfs(a, lambda { |v| preorder << v.value }) BNode.dfs(a, nil, lambda { |v| postorder << v.value }) BNode.bfs(a, lambda { |v| bfs << v.value }, nil) assert_equal 'abcde', preorder.join assert_equal 'decba', postorder.join assert_equal 'abcde', bfs.join end def test_maxsum_subtree # tree: -2 # 1 # 3 -2 # -1 e = BNode.new(-1) c = BNode.new(3, e, nil) d = BNode.new(-2, nil, nil) b = BNode.new(1, c, d) a = BNode.new(-2, b, nil) assert_equal 2, BNode.maxsum_subtree(a) end def test_4_7_lowest_common_ancestor_in_linear_time # tree a # b # c # d e d = BNode.new('d') e = BNode.new('e') c = BNode.new('c', d, e) b = BNode.new('b', c, nil) a = BNode.new('a', nil, b) assert_equal c, BNode.common_ancestors(a, 'd', 'e')[-1] assert_equal c, BNode.common_ancestors(a, 'c', 'd')[-1] assert_equal c, BNode.common_ancestors(a, 'c', 'e')[-1] assert_equal b, BNode.common_ancestors(a, 'b', 'e')[-1] assert_equal nil, BNode.common_ancestors(a, 'b', 'x')[-1] assert_equal nil, BNode.common_ancestors(a, 'x', 'y')[-1] end def test_4_8_binary_tree_value_include tree = BNode.new('a', nil, BNode.new('b', BNode.new('c', nil, BNode.new('d')), nil)) assert BNode.include?(tree, nil) assert BNode.include?(tree, tree) assert !BNode.include?(tree, BNode.new('e')) assert !BNode.include?(tree, BNode.new('c', nil, BNode.new('e'))) assert BNode.include?(tree, BNode.new('b')) assert BNode.include?(tree, BNode.new('c')) assert BNode.include?(tree, BNode.new('d')) assert BNode.include?(tree, tree.right) assert BNode.include?(tree, tree.right.left) assert BNode.include?(tree, tree.right.left.right) assert BNode.include?(tree, BNode.new('a')) assert BNode.include?(tree, BNode.new('a', nil, BNode.new('b'))) assert BNode.include?(tree, BNode.new('a', nil, BNode.new('b', BNode.new('c'), nil))) end def test_4_9_find_path_of_sum_in_linear_time # You are given a binary tree in which each node contains a value. # Design an algorithm to print all paths which sum up to that value. # Note that it can be any path in the tree - it does not have to start at the root. # # tree: -1 # ↘ # 3 # ↙ # -1 # ↙ ↘ # 2 3 tree = BNode.new(-1, nil, BNode.new(3, BNode.new(-1, BNode.new(2), BNode.new(3)), nil)) assert_equal ["-1 -> 3", "3 -> -1", "2", "-1 -> 3"], BNode.path_of_sum(tree, 2) # -5 # -3 4 # 2 8 # -6 # 7 9 tree = BNode.new(-5, BNode.new(-3, BNode.new(2, BNode.new(-6, BNode.new(7), BNode.new(9)), nil), BNode.new(8)), BNode.new(4)) assert_equal 10, BNode.max_sum_of_path(tree)[1] tree = BNode.new(-3, BNode.new(-2, BNode.new(-1), nil), nil) assert_equal -1, BNode.max_sum_of_path(tree)[1] tree = BNode.new(-1, BNode.new(-2, BNode.new(-3), nil), nil) assert_equal -1, BNode.max_sum_of_path(tree)[1] end def test_7_7_kth_integer_of_prime_factors_3_5_n_7 assert_equal 45, Math.integer_of_prime_factors(10) end def test_8_5_combine_parenthesis # Write a program that returns all valid combinations of n-pairs of parentheses that are properly opened and closed. # input: 3 (e.g., 3 pairs of parentheses) # output: ()()(), ()(()), (())(), ((())) assert_equal ["((()))", "(()())", "(())()", "()(())", "()()()"], Strings.combine_parens(3) assert_equal ["ab12", "a1b2", "a12b", "1ab2", "1a2b", "12ab"], Strings.interleave('ab', '12') assert_equal 20, Strings.interleave('abc', '123').size end def test_9_3_min_n_index_out_of_cycle assert_equal 10, Arrays.index_out_of_cycle([10, 14, 15, 16, 19, 20, 25, 1, 3, 4, 5, 7], 5) assert_equal 7, Arrays.index_out_of_cycle([16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14, 15], 5) assert_equal 0, Arrays.index_out_of_cycle([5, 7, 10, 14, 15, 16, 19, 20, 25, 1, 3, 4], 5) assert_equal 5, Arrays.index_out_of_cycle([20, 25, 1, 3, 4, 5, 7, 10, 14, 15, 16, 19], 5) assert_equal 6, Arrays.min_out_of_cycle([6]) assert_equal 6, Arrays.min_out_of_cycle([6, 7]) assert_equal 6, Arrays.min_out_of_cycle([7, 6]) assert_equal 6, Arrays.min_out_of_cycle([38, 40, 55, 89, 6, 13, 20, 23, 36]) assert_equal 6, Arrays.min_out_of_cycle([6, 13, 20, 23, 36, 38, 40, 55, 89]) assert_equal 6, Arrays.min_out_of_cycle([13, 20, 23, 36, 38, 40, 55, 89, 6]) assert_equal 5, Arrays.last_index([1, 3, 3, 5, 5, 5, 7, 7, 9], 5) assert_equal 3, Arrays.first_index([1, 3, 3, 5, 5, 5, 7, 7, 9], 5) assert_equal 1..2, Arrays.find_occurences([1, 3, 3, 5, 5, 5, 7, 7, 9], 3) assert_equal 6..7, Arrays.find_occurences([1, 3, 3, 5, 5, 5, 7, 7, 9], 7) assert_equal 0..0, Arrays.find_occurences([1, 3, 3, 5, 5, 5, 7, 7, 9], 1) assert_equal nil, Arrays.find_occurences([1, 3, 3, 5, 5, 5, 7, 7, 9], 0) assert_equal nil, Arrays.find_occurences([1, 3, 3, 5, 5, 5, 7, 7, 9], 10) end def test_9_6_indexes_out_of_matrix m = [ [11, 23, 35, 47], [22, 34, 38, 58], [33, 39, 57, 62], [44, 45, 61, 69] ] assert_equal [0, 3], Arrays.indexes_out_of_matrix(m, 47) assert_equal [3, 3], Arrays.indexes_out_of_matrix(m, 69) assert_equal [0, 0], Arrays.indexes_out_of_matrix(m, 11) assert_equal [3, 0], Arrays.indexes_out_of_matrix(m, 44) assert_equal [2, 1], Arrays.indexes_out_of_matrix(m, 39) assert_equal [3, 2], Arrays.indexes_out_of_matrix(m, 61) end def test_10_4_arithmetic_operations # 10-4. Write a method to implement *, - , / operations. You should use only the + operator. assert_equal -7, Math.negate(7) assert_equal 0, Math.negate(0) assert_equal -4, Math.subtract(3, 7) assert_equal 10, Math.subtract(3, -7) assert_equal -21, Math.multiply(3, -7) assert_equal 21, Math.multiply(-3, -7) assert_equal -3, Math.divide(11, -3) assert_equal 3, Math.divide(-11, -3) end def test_10_5_line_of_cutting_two_squares # 10-5. Given two squares on a two dimensional plane, find a line that would cut these two squares in half. r1, r2 = [4, 0, 0, 6], [6, 0, 0, 4] # top, left, bottom, right center_of = proc { |r| [(r[1] + r[3])/2.0, (r[0] + r[2])/2.0] } center1, center2 = center_of[r1], center_of[r2] line_of = proc { |p, q| x, y = p[0] - q[0], p[1] - q[1] case when x == 0 && y == 0 then nil when x == 0 then [p[0], nil] when y == 0 then [nil, p[1]] else s = y * 1.0 / x # scope [p[0] - p[1] * 1/s, p[1] - p[0] * s] end } assert_equal [5.0, 5.0], line_of[center1, center2] end def test_10_3_n_10_6_line_of_most_points # 10-3. Given two lines on a Cartesian plane, determine whether the two lines'd intersect. # 10-6. Given a two dimensional graph with points on it, find a line which passes the most number of points. a = [[1, 2], [2, 4], [6, 12], [3, 2], [4, 0], [3, 2], [5, -2]] n = a.size h = {} line_of = proc do |p, q| x, y = p[0] - q[0], p[1] - q[1] case when x == 0 && y == 0 then nil when x == 0 then [p[0], nil] when y == 0 then [nil, p[1]] else s = y * 1.0 / x # scope [p[0] - p[1] * 1/s, p[1] - p[0] * s] end end assert_equal [1.75, -7.0], line_of[[3, 5], [2, 1]] (0...n).each do |i| (i+1...n).each do |j| line = line_of[a[i], a[j]] (h[line] ||= {})[a[i]] = 1; (h[line] ||= {})[a[j]] = 1; end end h = h.values. reject { |s| s.size == 2 }. map { |h| h.keys }. map { |z| [z.size, z] } h = h.group_by { |e| e[0] }.max.last assert_equal [[4, [[2, 4], [3, 2], [4, 0], [5, -2]]]], h end def test_10_7_kth_number_of_prime_factors # 10-7. Design an algorithm to find the kth number such that the only prime factors are 3, 5, and 7. end # 11-7. In a B+ tree, in contrast to a B-tree, all records are stored at the leaf level of the tree; only keys are stored in interior nodes. # The leaves of the B+ tree in a linked list makes range queries or an (ordered) iteration through the blocks simpler & more efficient. # 13-2. hashmap vs. treemap that is a Red-Black tree based NavigableMap implementation that provides guaranteed log(n) time cost for operations. # 13-3. virtual functions & destructors, overloads, overloads, name-hiding, and smart pointers in C++? # RFC 2581: slow start, congestion avoidance, fast retransmit and recovery http://www.ietf.org/rfc/rfc2581.txt, http://msdn.microsoft.com/en-us/library/ms819737.aspx # Slow Start: When a connection is established, TCP starts slowly at first so as to assess the bandwidth of the connection and # to avoid overflowing the receiving host or any other devices or links in the connection path. # If TCP segments are acknowledged, the window size is incremented again, and so on # until the amount of data being sent per burst reaches the size of the receive window on the remote host. # Congestion Avoidance: If the need to retransmit data happens, the TCP stack acts under the assumption that network congestion is the cause. # The congestion avoidance algorithm resets the receive window to half the size of the send window at the point when congestion occurred. # TCP then enlarges the receive window back to the currently advertised size more slowly than the slow start algorithm. # Fast Retransmit & Recovery: To help make the sender aware of the apparently dropped data as quickly as possible, # the receiver immediately sends an acknowledgment (ACK), with the ACK number set to the sequence number that seems to be missing. # The receiver sends another ACK for that sequence number for each additional TCP segment in the incoming stream # that arrives with a sequence number higher than the missing one. def test_18_3_singleton # double-check locking end def test_19_2_is_tic_tac_toe_over # Design an algorithm to figure out if someone has won in a game of tic-tac-toe. end def test_19_7_maxsum_subarray assert_equal [5, [1, 7]], Arrays.maxsum_subarray([-2, 1, 3, -3, 4, -2, -1, 3]) end def test_19_10_test_rand7 100.times { r = Numbers.rand7; raise "'r' must be 1..7." unless r >= 1 && r <= 7 } end def test_19_11_pairs_of_sum pairs = Arrays.pairs_of_sum([1, 2, 1, 5, 5, 5, 3, 9, 9, 8], 10) expected = [[5, 5], [1, 9], [2, 8]] assert expected.eql?(pairs) end def test_20_1_addition assert_equal 1110 + 323, Numbers.sum(1110, 323) end def test_20_2_knuth_shuffle ary = Numbers.knuth_suffle!((1..52).to_a) # shuffles a deck of 52 cards assert_equal 52, ary.size end def test_20_3_reservoir_samples_n_weighted_choice io = StringIO.new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n") assert_equal 3, Numbers.reservoir_samples(io, 3).size assert -1 < Numbers.weighted_choice([10, 20, 30, 40]) end def test_20_7_find_longest_compound_words # Given a list of words, write a program that returns the longest word made of other words. # e.g. return "doityourself" given a list, "doityourself", "do", "it", "yourself", "motherinlaw", "mother", "in", "law". w = %w(approximation do it yourself doityourself motherinlaw mother in law).sort_by { |s| -s.size } d = w.reduce({}) { |h,k| h.merge(k => nil) } s = w.detect do |word| Partitions.int_composition(word.size, 2..3).any? do |composition| prefix_sums = composition.reduce([]) { |a,e| a + [e + (a.last || 0)] } words = (0...prefix_sums.size).map { |j| word[(j > 0 ? prefix_sums[j-1] : 0)...prefix_sums[j]] } words.all? { |k| d.has_key?(k) } end end assert_equal 'doityourself', s end def test_20_8_find_query_strings # Given a string s and an array of smaller strings Q, write a program that searches s for each string in Q. # a suffix tree of bananas s = 'bananas' suffix_tree = (0...s.size).reduce(Trie.new) { |trie, i| trie[s[i..-1]] = i; trie } # a trie of suffixes assert_equal (0..6).to_a, suffix_tree.values.sort # all indices of query strings q = %w(b ba n na nas s bas) indices_of = lambda { |q| (trie = suffix_tree.of(q)) ? trie.values : nil } assert_equal [[0], [0], [4, 2], [4, 2], [4], [6], nil], q.reduce([]) { |a, q| a << indices_of[q] }.sort # auto-complete a prefix d = %w(the they they their they're them) trie = d.reduce(Trie.new) { |t, w| t[w] = w; t } assert_equal ["the", "them", "their", "they", "they're"], trie.of("the").values assert_equal "they", trie["they"] # longest common substring, or palindrome assert_equal ["anana"], String.longest_common_substring(['bananas', 'bananas'.reverse]) assert_equal ["aba", "bab"], String.longest_common_substring(['abab', 'baba']).sort assert_equal ["ab"], String.longest_common_substring(['abab', 'baba', 'aabb']) assert_equal ["ab"], String.longest_common_substring(['abab', 'baba', 'aabb']) assert_equal "abc", String.longest_unique_charsequence('abcabcbb') end def test_20_9_median bag = MedianBag.new bag.offer(30).offer(50).offer(70) assert_equal [50], bag.median assert_equal [30, 50], bag.offer(10).median assert_equal [30], bag.offer(20).median assert_equal [30, 50], bag.offer(80).median assert_equal [50], bag.offer(90).median assert_equal [50, 60], bag.offer(60).median assert_equal [60], bag.offer(100).median end def test_20_10_trans_steps_of_2_words # Given two words of equal length that are in a dictionary, # design a method to transform one word into another word by changing only one letter at a time. # The new word you get in each step must be in the dictionary. d = %w{CAMP DAMP LAMP RAMP LIMP LUMP LIMO LITE LIME LIKE}.reduce({}) { |h, k| h.merge(k => nil) } reproduced = {} solutions = [] branch_out = lambda do |a| candidates = [] a.last.size.times do |i| s = a.last.dup ('A'..'Z').each do |c| s[i] = c if !reproduced.has_key?(s) && d.has_key?(s) candidates.push(s.dup) reproduced[candidates.last] = nil end end end candidates end reduce_off = lambda do |a| solutions.push(a.dup) if a.last.eql?('LIKE') end reproduced['DAMP'] = nil Search.backtrack(['DAMP'], branch_out, reduce_off) assert_equal ['DAMP', 'LAMP', 'LIMP', 'LIME', 'LIKE'], solutions.last end def test_20_11_max_size_subsquare # Imagine you have a square matrix, where each cell is filled with either black (1) or white (0). # Design an algorithm to find the maximum sub-square such that all four borders are filled with black pixels. m = [ [0, 1, 1, 0, 1, 0], [1, 1, 1, 1, 0, 1], [1, 1, 0, 1, 1, 0], [1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0] ] assert_equal [3, [3, 2]], Arrays.max_size_subsquare(m) end def test_20_12_maxsum_submatrix m = [ # 4 x 3 matrix [ 1, 0, 1], [ 0, -1, 0], [ 1, 0, 1], [-5, 2, 5] ] assert_equal [8, [2, 1, 3, 2]], Arrays.maxsum_submatrix(m) assert_equal [3, [0, 0, 0, 1]], Arrays.maxsum_submatrix([[1, 2, -1], [-3, -1, -4], [1, -5, 2]]) end end ########################################################### # Miscellaneous Modules & Classes: SNode, and DNode ########################################################### module Kernel def enum(*symbols) symbols.each { |s| const_set(s, s.to_s) } const_set(:DEFAULT, symbols.first) unless symbols.nil? end end class SNode attr_accessor :value, :next_ def initialize(value, next_ = nil) if value.is_a?(Array) value.reverse_each do |v| next_ = SNode.new(v, next_) end @value = next_.value @next_ = next_.next_ else @value = value; @next_ = next_ end end # Given a list (where k = 7, and n = 5), 1 2 3 4 5 6 7 a b c d e a. # 1. do find the length of the loop, i.e. n = 5. # 2. begin w/ u = 1, v = 6; advance them k times until they collide. def self.find_cycle(head) p1 = p2 = head while p2 && p2.next_ p1 = p1.next_ p2 = p2.next_.next_ break if p1 == p2 end return unless p1 == p2 n = 1; p1 = p1.next_ until p1 == p2 n += 1; p1 = p1.next_ end pk = head; pn_1 = head.next(n-1) until pk == pn_1.next pk = pk.next; pn_1 = pn_1.next end pn_1 end def self.sum(lhs, rhs, ones = 0) return nil if lhs.nil? && rhs.nil? && 0 == ones ones += lhs.value if lhs ones += rhs.value if rhs SNode.new(ones % 10, SNode.sum(lhs ? lhs.next_ : nil, rhs ? rhs.next_ : nil, ones / 10)) end def self.reverse!(current) head = nil while current save = current.next_ current.next_ = head head = current current = save end head end def self.reverse_every2!(head) if head.nil? || head.next.nil? head else next2 = head.next_.next_ head.next_.next_, head = head, head.next_ head.next_.next_ = reverse_every2!(next2) head end end def last last = self last = last.next_ while last.next_ last end def next(n = 1) next_ = self n.times { next_ = next_.next_ } next_ end def self.eql?(lhs, rhs) return true if lhs.nil? && rhs.nil? return false if lhs.nil? || rhs.nil? return false if lhs.value != rhs.value eql?(lhs.next_, rhs.next_) end def to_s "#{[value, next_.nil? ? '⏚' : next_].join(' → ')}" end end class DNode attr_accessor :value, :prev_, :next_ def initialize(value, next_ = nil, prev_ = nil) @value = value; @prev_ = prev_; @next_ = next_ end def to_a @next_ ? [value] + @next_.to_a : [value] end def to_s "#{[value, next_ ? next_.to_s: 'nil'].join(' -> ')}" end end class MedianBag def initialize @min_heap = BinaryHeap.new @max_heap = BinaryHeap.new(lambda { |a,b| b <=> a }) end def offer(v) if @max_heap.size == @min_heap.size if @min_heap.peek.nil? || v <= @min_heap.peek @max_heap.offer(v) else @max_heap.offer(@min_heap.poll) @min_heap.offer(v) end else if @max_heap.peek <= v @min_heap.offer(v) else @min_heap.offer(@max_heap.poll) @max_heap.offer(v) end end self end def median if @max_heap.size == @min_heap.size [@max_heap.peek, @min_heap.peek] else [@max_heap.peek] end end def to_a [@max_heap.to_a, @min_heap.to_a] end end class MinMaxStack def initialize @stack = [] @minimum = nil end def push(element) if @minimum.nil? || element <= @minimum @stack.push @minimum @minimum = element end @stack.push element end def pop element = @stack.pop @minimum = @stack.pop if @minimum == element element end def minimum @minimum end end class Queueable def initialize @stack1 = [] @stack2 = [] end def enq(element) @stack1.push element self end def deq # a good degree of code coverage might be satified by 4 test distinct cases (or a big one). return @stack2.pop unless @stack2.empty? # condition coverage is satisfied by false, and true. @stack2.push @stack1.pop until @stack1.empty? # loop coverage is satisfied by 0, 1, and 2 iterations. @stack2.pop end end module Numbers # discrete maths and bit twiddling http://graphics.stanford.edu/~seander/bithacks.html def self.prime?(n) n == 2 || n.odd? && 2.step(Math.sqrt(n).floor, 2).all? { |a| 0 != a % n } end def self.prime(n, certainty = 5) # returns when the probability that the number is prime exceeds 96.875% (1 - 0.5 ** certainty) # http://rosettacode.org/wiki/Miller-Rabin_primality_test#Ruby if n < 4 n else n += 1 if n.even? logN = Math.log(n).ceil loop do break n if certainty.times.all? do a = 2 + rand(n - 3) # i.e. a is in range (2..n-2). 1 == a ** (n-1) % n # Miller-Rabin primality test end break nil if n > n + logN*3/2 n += 2 end end end def self.abs(i) negative1or0 = i >> (0.size * 8 - 1) # 63 (i + negative1or0) ^ negative1or0 end def self.minmax(a, b) negative1or0 = a - b >> (0.size * 8 - 1) [ b ^ ((a ^ b) & negative1or0), a ^ ((a ^ b) & negative1or0) ] end def self.sum(a, b) if 0 == b a else units = (a ^ b) carry = (a & b) << 1 sum(units, carry) end end def self.divide(dividend, divisor) # implement division w/o using the divide operator, obviously. bit = 1 while divisor <= dividend divisor <<= 1 bit <<= 1 end quotient = 0 while bit > 0 divisor >>= 1 bit >>= 1 if dividend >= divisor dividend -= divisor quotient |= bit end end quotient end def self.opposite_in_sign?(a, b) a ^ b < 0 end def self.power_of_2?(x) x > 0 && (0 == x & x - 1) end def self.knuth_suffle!(ary, n = ary.size) ary.each_index do |i| j = i + rand(n - i) # to index: i + ary.size - i - 1 ary[j], ary[i] = ary[i], ary[j] end ary end def self.reservoir_samples(io, k = 1) samples = [] count = 0 until io.eof? do count += 1 if samples.size < k samples << io.gets.chomp else s = rand(count) samples[s] = io.gets.chomp if s < k end end samples end def self.weighted_choice(weights) sum = weights.reduce(:+) pick = rand(sum) weights.size.times do |i| pick -= weights[i] return i if pick < 0 end end def self.rand7() begin rand21 = 5 * (rand5 - 1) + rand5 end until rand21 <= 21 rand21 % 7 + 1 # 1, 2, ..., 7 end def self.rand5() rand(5) + 1 end def self.from_excel_column(s) columns = 0; cases = 26 (s.size - 1).times do columns += cases; cases *= 26 end ord_a = 'A'.bytes.to_a[0] bytes = s.bytes.to_a cases = 1 -1.downto(-s.size) do |k| columns += cases * (bytes[k] - ord_a); cases *= 26 end columns + 1 end def self.to_excel_column(n) k = 0; cases = 26 while n > cases n -= cases; cases *= 26; k += 1 end n -= 1 s = '' ord_a = 'A'.bytes.to_a[0] (k + 1).times do s = (n % 26 + ord_a).chr + s n /= 26 end s end def self.reverse_decimal(n) reversed = 0 while n > 0 reversed *= 10 reversed += n % 10 n /= 10 end reversed end def self.fibonacci(k, memos = [0, 1]) # F0 = 0, F1 = 1, ... memos[k] ||= fibonacci(k - 1, memos) + fibonacci(k - 2, memos) if k >= 0 end end ########################################################### # System and Object-Oriented Design ########################################################### module JukeboxV1 # a design consists of key components & their responsibilities, interactions, and services. # http://alistair.cockburn.us/Coffee+machine+design+problem,+part+2 # http://codereview.stackexchange.com/questions/10700/music-jukebox-object-oriented-design-review # http://www.simventions.com/whitepapers/uml/3000_borcon_uml.html class JukeboxEngine # coordinates all activities. def play(track) end; def choose_track() end; def show_welcome() end attr_reader :current_account, :current_track attr_reader :now_playing, :most_played, :recently_played, :recently_added attr_reader :account_dao, :album_dao, :playlist_dao end class CardReader # reads magnetic account id cards. def load_account() end end class Playlist # keeps track of most-played, recently-played, and now-playing lists. def initialize(capacity, mode = :LRU_CACHE) end def enqueue(track) end # reordering occurs in LRU-CACHE mode. def dequeue() end # bubbling down happens in MIN-HEAP mode. def move_up(track) end def move_down(track) end def size() end end class AudioCDPlayer # controls actual audio CD player. def play(track) end def pause() end def resume() end def stop() end def set_volume() end def get_volume() end def mute() end def unmute() end end class Account # keeps track of user account. attr_accessor :credit, :most_played, :recent_played end class Album # location: a certain tray id. attr_reader :label, :artists, :release_date, :genre, :subgenre, :tracks, :location end class Track # location: a certain track id. attr_reader :title, :duration, :location end class AccountDAO # (same as AlbumDAO and PlaylistDAO) def save(entity) end # create and update def find(id) end def find_all(example = nil) end def count(example = nil) end def exists?(example = nil) end def delete(id) end def delete_all(example = nil) end # delete end end module CardGame # http://math.hws.edu/javanotes/c5/s4.html class Card attr_accessor :suit, :value end class Deck def suffle() end def cards_left() end def deal_card() end # raises illegal state. end class Hand def add_card(card) end def remove_card(card) end # raises no such item found. def remove_card(position) end # raises index out of bounds. def get_card(position) end def clear_cards() end def sort_by_suit() end def sort_by_value() end attr_accessor :cards end class Game def games_played() end def scores_achieved() end def set_up() end def tear_down() end attr_accessor :deck, :hands end end module TetrisV1 class TetrisEngine def set_up() end; def tear_down() end; def clear() end def move_piece() end; def update_state() end; def remove_lines; end attr_reader :current_piece, :pieces_in_queue, :board_array, :game_state attr_reader :current_level, :current_score, :games_palyed, :best_scores end class TetrisBlock < Struct.new(:shape, :color, :orientation, :location); end module TetrisShape # http://www.freewebs.com/lesliev/rubyenums.html enum :SQUARE, :LINE, :T, :L, :REVERSE_L, :Z, :REVERSE_Z end end module XMPP # http://en.wikipedia.org/wiki/Extensible_Messaging_and_Presence_Protocol # http://weblog.raganwald.com/2006/06/my-favourite-interview-question.html # http://www.12planet.com/en/software/chat/whatis.html # http://tianrunhe.wordpress.com/2012/03/21/design-an-online-chat-server/ # http://tianrunhe.wordpress.com/tag/object-oriented-design/ # http://tianrunhe.wordpress.com/2012/03/page/2/ # http://www.thealgorithmist.com/archive/index.php/t-451.html?s=b732f53954d644b5ebacc77460396c19 # https://www.google.com/#q=interview+chat+server+design&hl=en&prmd=imvns&ei=lhM3UK33A8SQiQLO-4CAAQ&start=90&sa=N&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&fp=f0056a833a456726&biw=838&bih=933 end
require 'spec_helper' describe 'congress' do shared_examples 'congress' do context 'with default parameters' do let :params do {} end it 'contains deps class' do is_expected.to contain_class('congress::deps') end it { is_expected.to contain_package('congress-common').with( :ensure => 'present', :name => platform_params[:congress_package], :tag => ['openstack', 'congress-package'] )} it 'configures rabbit' do is_expected.to contain_congress_config('DEFAULT/transport_url').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('DEFAULT/rpc_response_timeout').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('DEFAULT/control_exchange').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_rabbit/heartbeat_timeout_threshold').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_rabbit/heartbeat_in_pthread').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_rabbit/kombu_compression').with_value('<SERVICE DEFAULT>') end it { is_expected.to contain_oslo__messaging__notifications('congress_config').with(:transport_url => '<SERVICE DEFAULT>') } it { is_expected.to contain_oslo__messaging__notifications('congress_config').with(:topics => '<SERVICE DEFAULT>') } it { is_expected.to contain_oslo__messaging__notifications('congress_config').with(:driver => '<SERVICE DEFAULT>') } end context 'with overridden parameters' do let :params do { :rabbit_ha_queues => true, :rabbit_heartbeat_timeout_threshold => '60', :rabbit_heartbeat_rate => '10', :rabbit_heartbeat_in_pthread => true, :kombu_compression => 'gzip', } end it 'configures rabbit' do is_expected.to contain_congress_config('oslo_messaging_rabbit/rabbit_ha_queues').with_value(true) is_expected.to contain_congress_config('oslo_messaging_rabbit/heartbeat_timeout_threshold').with_value('60') is_expected.to contain_congress_config('oslo_messaging_rabbit/heartbeat_rate').with_value('10') is_expected.to contain_congress_config('oslo_messaging_rabbit/heartbeat_in_pthread').with_value(true) is_expected.to contain_congress_config('oslo_messaging_rabbit/kombu_compression').with_value('gzip') is_expected.to contain_congress_config('oslo_messaging_rabbit/kombu_reconnect_delay').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_rabbit/kombu_failover_strategy').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_rabbit/amqp_durable_queues').with_value('<SERVICE DEFAULT>') is_expected.to contain_oslo__messaging__rabbit('congress_config').with( :rabbit_use_ssl => '<SERVICE DEFAULT>', ) end end context 'with default_transport_url parameter' do let :params do { :default_transport_url => 'rabbit://user:pass@host:1234/virtualhost', :rpc_response_timeout => '120', :control_exchange => 'congress', } end it 'configures rabbit' do is_expected.to contain_congress_config('DEFAULT/transport_url').with_value('rabbit://user:pass@host:1234/virtualhost') is_expected.to contain_congress_config('DEFAULT/rpc_response_timeout').with_value('120') is_expected.to contain_congress_config('DEFAULT/control_exchange').with_value('congress') end end context 'with notification_transport_url parameter' do let :params do { :notification_transport_url => 'rabbit://user:pass@host:1234/virtualhost', :notification_topics => 'openstack', :notification_driver => 'messagingv1', } end it 'configures rabbit' do is_expected.to contain_oslo__messaging__notifications('congress_config').with( :transport_url => 'rabbit://user:pass@host:1234/virtualhost' ) is_expected.to contain_oslo__messaging__notifications('congress_config').with(:topics => 'openstack') is_expected.to contain_oslo__messaging__notifications('congress_config').with(:driver => 'messagingv1') end end context 'with kombu_reconnect_delay set to 5.0' do let :params do { :kombu_reconnect_delay => '5.0' } end it 'configures rabbit' do is_expected.to contain_congress_config('oslo_messaging_rabbit/kombu_reconnect_delay').with_value('5.0') end end context 'with rabbit_ha_queues set to true' do let :params do { :rabbit_ha_queues => 'true' } end it 'configures rabbit' do is_expected.to contain_congress_config('oslo_messaging_rabbit/rabbit_ha_queues').with_value(true) end end context 'with amqp_durable_queues parameter' do let :params do { :amqp_durable_queues => 'true' } end it 'configures rabbit' do is_expected.to contain_congress_config('oslo_messaging_rabbit/rabbit_ha_queues').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_rabbit/amqp_durable_queues').with_value(true) is_expected.to contain_oslo__messaging__rabbit('congress_config').with( :rabbit_use_ssl => '<SERVICE DEFAULT>', ) end end context 'with rabbit ssl enabled with kombu' do let :params do { :rabbit_use_ssl => true, :kombu_ssl_ca_certs => '/etc/ca.cert', :kombu_ssl_certfile => '/etc/certfile', :kombu_ssl_keyfile => '/etc/key', :kombu_ssl_version => 'TLSv1', } end it 'configures rabbit' do is_expected.to contain_oslo__messaging__rabbit('congress_config').with( :rabbit_use_ssl => true, :kombu_ssl_ca_certs => '/etc/ca.cert', :kombu_ssl_certfile => '/etc/certfile', :kombu_ssl_keyfile => '/etc/key', :kombu_ssl_version => 'TLSv1', ) end end context 'with rabbit ssl enabled without kombu' do let :params do { :rabbit_use_ssl => true, } end it 'configures rabbit' do is_expected.to contain_oslo__messaging__rabbit('congress_config').with( :rabbit_use_ssl => true, :kombu_ssl_ca_certs => '<SERVICE DEFAULT>', :kombu_ssl_certfile => '<SERVICE DEFAULT>', :kombu_ssl_keyfile => '<SERVICE DEFAULT>', :kombu_ssl_version => '<SERVICE DEFAULT>', ) end end context 'with amqp default parameters' do it 'configures amqp' do is_expected.to contain_congress_config('oslo_messaging_amqp/server_request_prefix').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/broadcast_prefix').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/group_request_prefix').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/container_name').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/idle_timeout').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/trace').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_ca_file').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_cert_file').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_key_file').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_key_password').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/allow_insecure_clients').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/sasl_mechanisms').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/sasl_config_dir').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/sasl_config_name').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/username').with_value('<SERVICE DEFAULT>') is_expected.to contain_congress_config('oslo_messaging_amqp/password').with_value('<SERVICE DEFAULT>') end end context 'with overridden amqp parameters' do let :params do { :amqp_idle_timeout => '60', :amqp_trace => true, :amqp_ssl_ca_file => '/etc/ca.cert', :amqp_ssl_cert_file => '/etc/certfile', :amqp_ssl_key_file => '/etc/key', :amqp_username => 'amqp_user', :amqp_password => 'password', } end it 'configures amqp' do is_expected.to contain_congress_config('oslo_messaging_amqp/idle_timeout').with_value('60') is_expected.to contain_congress_config('oslo_messaging_amqp/trace').with_value('true') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_ca_file').with_value('/etc/ca.cert') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_cert_file').with_value('/etc/certfile') is_expected.to contain_congress_config('oslo_messaging_amqp/ssl_key_file').with_value('/etc/key') is_expected.to contain_congress_config('oslo_messaging_amqp/username').with_value('amqp_user') is_expected.to contain_congress_config('oslo_messaging_amqp/password').with_value('password') end end end on_supported_os({ :supported_os => OSDefaults.get_supported_os }).each do |os,facts| context "on #{os}" do let (:facts) do facts.merge!(OSDefaults.get_facts()) end let(:platform_params) do case facts[:osfamily] when 'Debian' { :congress_package => 'congress-server' } when 'RedHat' { :congress_package => 'openstack-congress' } end end it_behaves_like 'congress' end end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/rack-chain/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Nick Sieger"] gem.email = ["nick@nicksieger.com"] gem.description = %q{Rack::Chain builds a Rack application that runs each middleware in its own fiber to minimize stack depth. } gem.summary = %q{Rack::Chain uses fibers to minimize stack depth in Rack applications.} gem.homepage = "https://github.com/nicksieger/rack-chain" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "rack-chain" gem.require_paths = ["lib"] gem.version = Rack::Chain::VERSION gem.add_runtime_dependency "rack", [">= 1.4.0"] gem.add_development_dependency "rspec", [">= 2.8.0"] end
class HelpCommand < Command::Base self.revealed = false def output @output ||= commands.any? ? list_commands : no_commands end private def commands Command.revealed end def list_commands '<p>Here are the available commands:</p>' + "<p style='padding-left: 20px;'>#{commands.join(' ')}</p>" end def no_commands 'There are no commands loaded.' end end
class Api::V1::MeaningsController < ApplicationController def index @meanings = Meaning.all render json: @meanings end def show @meaning = Meaning.find(params[:id]) render json: @meaning end end
class AddSpecializationToSpecialist < ActiveRecord::Migration[5.0] def change add_column :specialists, :specialization, :string add_column :specialists, :hourly_rate, :integer end end
class Image < ActiveRecord::Base attr_accessible :name, :image, :area_id, :order # Associations belongs_to :area, :include => :area_category, :counter_cache => true # Callbacks before_save :update_image_attributes # carrierwave mount_uploader :image, MapUploader # Validates validates :image, :area_id, :presence => true with_options :if => :name? do |name| name.validates :name, :length => { :within => 2..30 } end with_options :if => :order? do |order| order.validates :order, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 999 } end with_options :if => :image? do |image| image.validates :image, :file_size => { :maximum => 5.megabytes.to_i } end # scopes scope :order_asc, order("`order` ASC") scope :created_desc, order("created_at DESC") scope :newest, lambda { |count| limit(count).includes(:area) } # Methods def update_image_attributes Rails.logger.debug image.file.basename if image.present? && image_changed? self.name = image.file.basename self.image_size = image.file.size self.image_content_type = image.file.content_type end end def to_jq_upload { "id" => read_attribute(:id), "size" => image.size, "url" => image.url, "thumbnail_url" => image.thumb_small.url } end end
class ProductrequestsController < ApplicationController layout 'productrequest' http_basic_authenticate_with name: "admin", password: "1af2af3af4af5", except: [:new, :create] before_action :set_productrequest, only: [:show, :edit, :update, :destroy] helper_method :set_fullfilled # GET /productrequests # GET /productrequests.json def index @productrequests = Productrequest.where("status = ?", "active") respond_to do |format| format.html format.csv do headers['Content-Disposition'] = "attachment; filename=\"product-requests.csv\"" headers['Content-Type'] ||= 'text/csv' end end end # GET /productrequests/1 # GET /productrequests/1.json def show end # GET /productrequests/new def new @productrequest = Productrequest.new end # GET /productrequests/1/edit def edit end # POST /productrequests # POST /productrequests.json def create @productrequest = Productrequest.new(productrequest_params) @productrequest.status = "active" respond_to do |format| if @productrequest.save format.html { flash[:success] = "Your product request has been created" #SENDING EMAIL TO ADMIN THAT REQUEST HAS BEEN SUBMITED ProductrequestMailer.productrequest_email(@productrequest).deliver #SENDING EMAIL TO CUSTOMER THAT WE HAVE RECEIVED YOUR EMAIL ProductrequestMailer.productrequest_inprogress_email(@productrequest).deliver begin #BELOW IS CODE FOR SUBSCRIBING USER TO OUR MAILCHIMP LIST USING GIBBON gb = Gibbon::API.new("93f3019f32a6215c04959711c63d894e-us3") gb.lists.subscribe({:id => '8bacae7aa7', :email => {:email => @productrequest.email}, :merge_vars => {:FNAME => 'First Name', :LNAME => 'Last Name'}, :double_optin => false}) rescue Gibbon::MailChimpError => e # do something with e.message here end redirect_to new_productrequest_path } format.json { render :show, status: :created, location: @productrequest } else format.html { render :new } format.json { render json: @productrequest.errors, status: :unprocessable_entity } end end end # PATCH/PUT /productrequests/1 # PATCH/PUT /productrequests/1.json def update respond_to do |format| if @productrequest.update(productrequest_params) format.html { redirect_to @productrequest, notice: 'Productrequest was successfully updated.' } format.json { render :show, status: :ok, location: @productrequest } else format.html { render :edit } format.json { render json: @productrequest.errors, status: :unprocessable_entity } end end end # DELETE /productrequests/1 # DELETE /productrequests/1.json def destroy @productrequest.destroy respond_to do |format| format.html { redirect_to productrequests_url, notice: 'Productrequest was successfully destroyed.' } format.json { head :no_content } end end def set_fullfilled @productrequest = Productrequest.find(params[:pid]) @productrequest.status = "fullfilled" if @productrequest.save ProductrequestMailer.productrequest_fullfilled_email(@productrequest).deliver redirect_to productrequests_url, notice: 'Product Request was Fullfilled.' end end def set_notfullfilled @productrequest = Productrequest.find(params[:pid]) @productrequest.status = "notfullfilled" if @productrequest.save ProductrequestMailer.productrequest_notfullfilled_email(@productrequest).deliver redirect_to productrequests_url, notice: 'Product Request was set to NotFullfilled.' end end private # Use callbacks to share common setup or constraints between actions. def set_productrequest @productrequest = Productrequest.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def productrequest_params params.require(:productrequest).permit(:name, :email, :phone, :fullfilled, :location) end end
class Api::V1::ProjectSerializer < ActiveModel::Serializer attributes :accessible, :address1, :address2, :age_ranges, :campuses, :categories, :checkin_end, :checkin_start, :city, :coleaders, :description, :end_date, :end_time, :id, :latitude, :leader_email, :leader_id, :leader_name, :longitude, :multi_day, :name, :organization_id, :organization_name, :people_needed, :percent_full, :skills, :slug, :start_date, :start_time, :state, :status, :supplies, :tools, :walk_ons, :zip def coleaders object.coleaders.map{|s| {id: s.id, name: s.name, email: s.email, image: s.image} } end def skills resource_formatter(object.project_skills) end def supplies resource_formatter(object.project_supplies) end def tools resource_formatter(object.project_tools) end def resource_formatter(resources) resources.map{|s| {id: s.resource.id, name: s.resource.name, qty_needed: s.quantity, slug: s.resource.slug, confirmed: object.resource_user_links.where(resource_id: s.resource.id).map{|t| {user: t.user.name, qty: t.quantity} } } } end def leader_name object.leader.name end def leader_email object.leader.email end def leader_id object.leader.id end def organization_name object.organization.name end def organization_id object.organization.id end def leader u = object.user {id: u.try(:id), name: u.try(:name), email: u.try(:email)} end def organization u = object.organization {id: u.try(:id), name: u.try(:name)} end def multi_day start_date != end_date end def start_date object.start_date&.strftime('%m/%d/%Y') end def end_date object.end_date&.strftime('%m/%d/%Y') end def start_time object.start_date&.strftime('%l:%M%P') end def end_time object.end_date&.strftime('%l:%M%P') end end
class Entry < ActiveRecord::Base default_scope lambda { order 'published_at DESC' } attr_accessor :authors belongs_to :author, foreign_key: :author_id, class_name: 'Author', autosave: true before_save do author = Author.find_by_uid self.authors[0] author ||= self.create_author uid: self.authors[0] self.author = author end def entry=(entry) self.authors = entry.author.split self.uid = entry.id self.url = entry.url self.title = entry.title self.content = entry.content self.published_at = entry.date_published end end
require 'socket' require 'timeout' require 'optparse' opts = OptionParser.new opts.on("-H HOSTNAME", "--hostname NAME", String, "Hostname of Server (Required)") { |v| @hostname = v } opts.on("-P PORT", "--port PORT", String, "Port number to test (Required)") { |v| @portnumber = v } opts.on("-h", "--help", "Display this screen") { puts opts exit } begin opts.parse!(ARGV) rescue OptionParser::ParseError => e puts e end #raise OptionParser::MissingArgument, "Hostname [-H]" if @hostname.nil? #raise OptionParser::MissingArgument, "Port Number [-P]" if @portnumber.nil? def is_port_open?(ip, port) begin Timeout::timeout(1) do begin s = TCPSocket.new(ip, port) s.close return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH return false end end rescue Timeout::Error end return false end if @hostname.nil? || @hostname.empty? print "Enter the hostname: " @hostname = gets.chomp() end if @portnumber.nil? || @portnumber.empty? print "Enter the port number: " @portnumber = gets.chomp() end puts is_port_open?(@hostname, @portnumber) puts "Press ENTER to continue..." gets.chomp()
# frozen_string_literal: true Rails.application.routes.draw do root to: 'home#index' namespace :api do namespace :v1, defaults: { format: :json } do resources :products, only: %i[index show create update destroy] resources :orders, only: %i[index show create update destroy] resources :bills, only: %i[index show] match '*path', to: 'api#not_found', via: :all end end match '*path', to: 'application#not_found', via: :all # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class CommentsController < ApplicationController before_action :verify_authorized def create @comment = current_user.comments.new(safe_params) if @comment.save redirect_to :posts, notice: 'Comment saved.' else render :new end end def edit @comment = Comment.find(params[:id]) deny_access unless @comment.user_id == current_user.id || current_user.parent? end def update @comment = Comment.find(params[:id]) if @comment.update(safe_params) redirect_to :posts, notice: 'Comment updated.' else render :edit end end def destroy @comment = Comment.find(params[:id]) @comment.destroy redirect_to :posts, notice: 'Comment deleted.' end private def safe_params params.require(:comment).permit(:post_id, :body) end def authorized? current_user.present? end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. class Target::MysqlController < Target::BaseController module_require_dependency :mysql, 'target' def set_snapshot if @snapshot = @target.full_snapshots.find(params[:snapshot_id]) @tsession[:snapshot_id] = params[:snapshot_id] @tsession[:browse_server].set_snapshot(@snapshot) end render :update do |page| page.replace_html 'targetpanel', :partial => partial_path('browse') end end def browser_show_table_info table_id = params[:table_id].to_i @table = @target.tables.find(table_id) @log = @table.log_for_snapshot(@snapshot) render :update do |page| page.replace_html :browser_object_info_content, :partial => partial_path('browse_table_info'), :locals => {:table => @table, :log => @log} page << 'show_info();' end end protected def setup_panel super case @tsession[:panel] when 'browse' @tsession[:browse_server] = MysqlTargetTree::Server.new(@target, @snapshot) when 'settings' setup_settings_browser when 'restore' end end def setup_settings_browser @tsession[:settings_browser] = MysqlSettingsTree::Server.new(@target) end def find_tree(id) if id == 'settings_browser_root' @tsession[:settings_browser] elsif id == 'server' @tsession[:browse_server] end end def update_target_options super @target.hostname = params[:target][:hostname] @target.port = params[:target][:port] @target.username = params[:target][:username] @target.password = params[:target][:password] setup_settings_browser end end
class KeysController < ApplicationController def create @key = Key.new(key_params) if @key.save render json: @key, status: :created else render json: @key.errors, status: :unprocessable_entity end end private def key_params params.permit(:password) end end
require "menthol/provider" require "menthol/account" module Menthol class UOBAM < Provider private def login_url "https://echannel.uobam.co.th/fundcyber/Account/Login" end def login sleep 1 submit_credentials({ username: "UserName", password: "Password", button: browser.button(id: "btnLogin"), }) button = browser.button(id: "btnOkTermCondition") browser.scroll.to :bottom button.click button.wait_while_present end def find_amount(type) case type when :ltf then ltf end end def logout button = browser.link(href: /logout/) sleep 1 button.click button.wait_while_present end def ltf row = browser.tr(css: "#grid100125031720 tbody tr") cell = row[3] cell.text end end end
class AddDueDatetimeToTasks < ActiveRecord::Migration def change add_column :tasks, :due_datetime, :datetime end end
class TurnsController < ApplicationController def create @game = Game.find(params[:game_id]) if @game.take_turn(params[:square]) @game.process_ai_turns! if @game.over? flash[:notice] = "Game Over!" end redirect_to game_path(@game) else flash[:error] = "Error! Still #{Game::PLAYER_MAP[@game.current_player]}'s turn" redirect_to game_path(@game) end end end
class AnimalsController < ApplicationController before_action :set_animal, only: [:show, :update, :destroy] load_and_authorize_resource # GET /animals def index @animals = Animal.all render json: @animals end # GET /animals/1 def show render json: @animal end # POST /animals def create @animal = Animal.new(animal_params) if @animal.save render json: @animal, status: :created, location: @animal else render json: @animal.errors, status: :unprocessable_entity end end # PATCH/PUT /animals/1 def update if @animal.update(edit_params) render json: @animal else render json: @animal.errors, status: :unprocessable_entity end end # DELETE /animals/1 def destroy @animal.destroy end def animal_page page = params[:page].to_i - 1 page = 0 if page < 0 animals_per_page = 15 start = page * animals_per_page animals = Animal.where(status: "lost") animals_recent_add = animals.reverse animals_to_page = animals_recent_add.slice(start, animals_per_page) render json: {animals: animals_to_page} end def answer unless params[:message].present? return render json: {error: "A mensagem é obrigatória"}, status: 400 end animal = Animal.find_by(id: params[:animal]) unless animal.present? return render json: {error: "Animal não encontrado"}, status: 404 end unless animal.status == 'lost' return render json: {error: "Animal não se encontra desaparecido"}, status: 400 end answer = Answer.create!(user_id: current_user.id, animal_id: animal.id, message: params[:message]) animal.update_attributes(status: 1) AnswerMailer.with(informant: current_user, animal: animal, message: params[:message], url: request.base_url).notice.deliver_now render json: {answer: answer}, status:201 end private # Use callbacks to share common setup or constraints between actions. def set_animal @animal = Animal.find(params[:id]) end # Only allow a trusted parameter "white list" through. def animal_params params.permit(:photo, :name, :age, :description, :city, :state, :user_id) end def edit_params params.permit(:photo, :name, :age, :description, :city, :state, :status) end def answer_params params.permit(:message) end end
class SubjectGroup < ActiveRecord::Base ## # Associations has_many :subjects, :through => :subjects_subject_groups has_many :subjects_subject_groups ## # Attributes # attr_accessible :description, :name, :subject_ids ## # Callbacks ## # Concerns include Loggable, Indexable, Deletable ## # Database Settings ## # Scopes scope :search, lambda { |term| search_scope([:name, :description], term) } ## # Validations validates_presence_of :name validates_uniqueness_of :name, scope: :deleted ## # Class Methods ## # Instance Methods end
class TwitterUser < ActiveRecord::Base ###------------------------------------------------------------------------------- # Initializers ###------------------------------------------------------------------------------- attr_accessible :description, :location, :name, :profile_image_url, :protected, :screen_name, :user_id, :user_id_str, :utc_offset @@client = Twitter::Client.new( :consumer_key => ENV['TWITTER_CONSUMER_KEY'], :consumer_secret => ENV['TWITTER_CONSUMER_SECRET'], :oauth_token => ENV['TWITTER_OAUTH_TOKEN'], :oauth_token_secret => ENV['TWITTER_TOKEN_SECRET'] ) ###------------------------------------------------------------------------------- # Relationships ###------------------------------------------------------------------------------- has_many :tweets, :dependent => :destroy has_many :statements, :dependent => :destroy ###------------------------------------------------------------------------------- # Validations ###------------------------------------------------------------------------------- ###------------------------------------------------------------------------------- # Public Methods ###------------------------------------------------------------------------------- def self.store_user(u) TwitterUser.create( :description => u.description, :location => u.location, :name => u.name, :profile_image_url => u.profile_image_url, :protected => u.protected, :screen_name => u.screen_name, :user_id => u.id, :utc_offset => u.utc_offset ) end def self.check_mentions if !ENV['LAST_UPDATE'] || (Time.now > Time.parse(ENV['LAST_UPDATE']) + 45.seconds) begin @@client.mentions_timeline.each do |mention| unless Mention.find_by_mention_id(mention.id) || mention.user.screen_name == 'mashifesto' our_mention = Mention.build_from_api(mention) Resque.enqueue(LoadTweets, our_mention) end end rescue Twitter::Error::TooManyRequests logger.debug 'TWITTER EXCEPTION RESCUED :: API Rate limit exceeded in TwitterUser::check_mentions' rescue ActiveRecord::StatementInvalid => e logger.debug "ACTIVE RECORD EXCEPTION RESCUED :: Could be that we\'ve hit a DB limit on Heroku :: #{e.message}" end ENV['LAST_UPDATE'] = Time.now.to_s end end end
require_relative "account" module Bank class SavingsAccount < Account def initialize(id, balance) @id = id @balance = balance raise ArgumentError.new("balance must be >= 10") if balance < 10 end def withdraw(amount) amount += 2 raise ArgumentError.new("withdrawal amount must be >= 0") if amount < 0 if (@balance - amount) < 10 puts "whoops! you don't have that much money in your account! your balance is #{@balance}." return @balance else return @balance -= amount end end def add_interest(rate) raise ArgumentError.new("interest rate must be > 0") if rate < 0 interest = @balance * rate/100 @balance += interest return interest end end end # account = Bank::SavingsAccount.new(33, 330) # Bank:: SavingsAccount.all
# refresh the rank from another API class Tasks::Cron::RefreshMarketCoinsRanks def initialize puts "Task initialized." end def perform MarketCoin.all.each do |market_coin| if ranks[market_coin.symbol].present? market_coin.update!(rank: ranks[market_coin.symbol]) puts "[OK] MarketCoin `#{market_coin.code}` rank is #{market_coin.rank}" else puts "[KO] MarketCoin `#{market_coin.code}` has no rank" end end puts "Task performed." end private def ranks @ranks ||= begin fetch = CoinmarketcapApi.new.fetch fetch.reduce({}) do |acc, coin| symbol = coin[:symbol] acc[symbol] = coin[:rank] acc end end end end
json.array!(@admins) do |admin| json.extract! admin, :id, :rut, :nombre, :telefono, :direccion json.url admin_url(admin, format: :json) end
require_dependency 'issue_query' module IssueQueryPatch def self.included(base) # :nodoc: base.send(:include, InstanceMethods) base.class_eval do unloadable alias_method_chain :available_columns, :patch alias_method_chain :initialize_available_filters, :patch self.available_columns.concat([ QueryColumn.new(:total_estimate_hours, :sortable => "COALESCE((SELECT SUM(hours) FROM #{EstimateEntry.table_name} WHERE #{EstimateEntry.table_name}.issue_id = #{Issue.table_name}.id), 0)"), QueryColumn.new(:total_accepted_estimate_hours, :sortable => "COALESCE((SELECT SUM(hours) FROM #{EstimateEntry.table_name} WHERE #{EstimateEntry.table_name}.issue_id = #{Issue.table_name}.id), 0)") ]) end end module InstanceMethods def initialize_available_filters_with_patch # взято из версии 3.х.х add_available_filter "status_id", :type => :list_status, :values => lambda { issue_statuses_values } add_available_filter("project_id", :type => :list, :values => lambda { project_values } ) if project.nil? add_available_filter "tracker_id", :type => :list, :values => trackers.collect{|s| [s.name, s.id.to_s] } add_available_filter "priority_id", :type => :list, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } add_available_filter("author_id", :type => :list, :values => lambda { author_values } ) add_available_filter("assigned_to_id", :type => :list_optional, :values => lambda { assigned_to_values } ) add_available_filter("member_of_group", :type => :list_optional, :values => lambda { Group.givable.visible.collect {|g| [g.name, g.id.to_s] } } ) add_available_filter("assigned_to_role", :type => :list_optional, :values => lambda { Role.givable.collect {|r| [r.name, r.id.to_s] } } ) add_available_filter "fixed_version_id", :type => :list_optional, :values => lambda { fixed_version_values } add_available_filter "fixed_version.due_date", :type => :date, :name => l(:label_attribute_of_fixed_version, :name => l(:field_effective_date)) add_available_filter "fixed_version.status", :type => :list, :name => l(:label_attribute_of_fixed_version, :name => l(:field_status)), :values => Version::VERSION_STATUSES.map{|s| [l("version_status_#{s}"), s] } add_available_filter "category_id", :type => :list_optional, :values => lambda { project.issue_categories.collect{|s| [s.name, s.id.to_s] } } if project add_available_filter "subject", :type => :text add_available_filter "description", :type => :text add_available_filter "created_on", :type => :date_past add_available_filter "updated_on", :type => :date_past add_available_filter "closed_on", :type => :date_past add_available_filter "start_date", :type => :date add_available_filter "due_date", :type => :date add_available_filter "estimated_hours", :type => :float add_available_filter "done_ratio", :type => :integer # добавлено мной в соответствии с анализом что добавлялось для версии 2.х.х add_available_filter "total_estimate_hours", :type => :float # if User.current.allowed_to?(:set_issues_private, nil, :global => true) || User.current.allowed_to?(:set_own_issues_private, nil, :global => true) add_available_filter "is_private", :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]] end add_available_filter "attachment", :type => :text, :name => l(:label_attachment) if User.current.logged? add_available_filter "watcher_id", :type => :list, :values => [["<< #{l(:label_me)} >>", "me"]] end add_available_filter("updated_by", :type => :list, :values => lambda { author_values } ) add_available_filter("last_updated_by", :type => :list, :values => lambda { author_values } ) if project && !project.leaf? add_available_filter "subproject_id", :type => :list_subprojects, :values => lambda { subproject_values } end add_custom_fields_filters(issue_custom_fields) # последенне поле добавлено add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version, :estimate_entries IssueRelation::TYPES.each do |relation_type, options| add_available_filter relation_type, :type => :relation, :label => options[:name], :values => lambda {all_projects_values} end add_available_filter "parent_id", :type => :tree, :label => :field_parent_issue add_available_filter "child_id", :type => :tree, :label => :label_subtask_plural add_available_filter "issue_id", :type => :integer, :label => :label_issue Tracker.disabled_core_fields(trackers).each {|field| delete_available_filter field } end def available_columns_with_patch # Добавляю available_columns как в версии 3.х.х return @available_columns if @available_columns @available_columns = self.class.available_columns.dup @available_columns += issue_custom_fields.visible.collect {|cf| QueryCustomFieldColumn.new(cf) } if User.current.allowed_to?(:view_time_entries, project, :global => true) # insert the columns after total_estimated_hours or at the end index = @available_columns.find_index {|column| column.name == :total_estimated_hours} index = (index ? index + 1 : -1) subselect = "SELECT SUM(hours) FROM #{TimeEntry.table_name}" + " JOIN #{Project.table_name} ON #{Project.table_name}.id = #{TimeEntry.table_name}.project_id" + " WHERE (#{TimeEntry.visible_condition(User.current)}) AND #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id" @available_columns.insert index, QueryColumn.new(:spent_hours, :sortable => "COALESCE((#{subselect}), 0)", :default_order => 'desc', :caption => :label_spent_time, :totalable => true ) subselect = "SELECT SUM(hours) FROM #{TimeEntry.table_name}" + " JOIN #{Project.table_name} ON #{Project.table_name}.id = #{TimeEntry.table_name}.project_id" + " JOIN #{Issue.table_name} subtasks ON subtasks.id = #{TimeEntry.table_name}.issue_id" + " WHERE (#{TimeEntry.visible_condition(User.current)})" + " AND subtasks.root_id = #{Issue.table_name}.root_id AND subtasks.lft >= #{Issue.table_name}.lft AND subtasks.rgt <= #{Issue.table_name}.rgt" @available_columns.insert index+1, QueryColumn.new(:total_spent_hours, :sortable => "COALESCE((#{subselect}), 0)", :default_order => 'desc', :caption => :label_total_spent_time ) end # добавлено как пододие предыдущего блока subselect с заменой на :field_total_estimate_hours if User.current.allowed_to?(:view_time_entries, project, :global => true) # insert the columns after total_estimated_hours or at the end index = @available_columns.find_index {|column| column.name == :total_estimated_hours} index = (index ? index + 1 : -1) subselect = "SELECT SUM(hours) FROM #{EstimateEntry.table_name}" + " JOIN #{Project.table_name} ON #{Project.table_name}.id = #{EstimateEntry.table_name}.project_id" + " WHERE (#{EstimateEntry.visible_condition(User.current)}) AND #{EstimateEntry.table_name}.issue_id = #{Issue.table_name}.id" @available_columns.insert index, QueryColumn.new(:total_estimate_hours, :sortable => "COALESCE((#{subselect}), 0)", :default_order => 'desc', :caption => :field_total_estimate_hours, :totalable => true ) # # end if User.current.allowed_to?(:set_issues_private, nil, :global => true) || User.current.allowed_to?(:set_own_issues_private, nil, :global => true) @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private", :groupable => true) end disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')} @available_columns.reject! {|column| disabled_fields.include?(column.name.to_s) } @available_columns end #def available_columns_with_patch end end #module IssueQueryPatch
module GroupDocs class Signature::Role < Api::Entity # # Returns array of predefined roles. # # @param [Hash] options Hash of options # @option options [String] :id Filter by identifier # @param [Hash] access Access credentials # @option access [String] :client_id # @option access [String] :private_key # @return [Array<GroupDocs::Signature::role>] # def self.get!(options = {}, access = {}) api = Api::Request.new do |request| request[:access] = access request[:method] = :GET request[:path] = '/signature/{{client_id}}/roles' end api.add_params(options) json = api.execute! json[:roles].map do |role| new(role) end end # @attr [String] id attr_accessor :id # @attr [String] name attr_accessor :name # @attr [Integer] canEdit attr_accessor :canEdit # @attr [Integer] canSign attr_accessor :canSign # @attr [Integer] canAnnotate attr_accessor :canAnnotate # @attr [Integer] canDelegate attr_accessor :canDelegate # Human-readable accessors alias_accessor :can_edit, :canEdit alias_accessor :can_sign, :canSign alias_accessor :can_annotate, :canAnnotate alias_accessor :can_delegate, :canDelegate # Boolean methods for Ruby DSL alias_method :can_edit?, :can_edit alias_method :can_sign?, :can_sign alias_method :can_annotate?, :can_annotate alias_method :can_delegate?, :can_delegate end # Signature::Role end # GroupDocs
require 'rubygems' require 'rspec' require 'pry-debugger' require_relative '../war.rb' <<<<<<< HEAD describe 'Card' do describe 'initialize' do it "initializes as a 'Node' with an in_front and in_back pointer" do card = Card.new(2, 2, "Spades") expect(card.class).to eq(Card) expect(card.in_front).to eq(nil) expect(card.in_back).to eq(nil) end end end describe 'Deck' do before(:each) do @deck = Deck.new # @deck_array = @deck.deck end describe 'initialize' do it 'initializes as a new LinkedList' do expect(@deck.deck.class).to eq(LinkedList) end end describe 'add_card' do it "Adds card to bottom of deck/back of the LinkedList" do card1 = Card.new("J", 11, "Spades") card2 = Card.new("A", 14, "Clubs") @deck.add_card(card1) @deck.add_card(card2) expect(@deck.deck.front).to eq(card1) expect(@deck.deck.back).to eq(card2) end end describe "create_shuffled_deck" do it "makes a 52 card deck/LinkedList" do expect(@deck.create_shuffled_deck).to eq(52) end it "rearranges the order of the cards" do @deck.create_shuffled_deck deck1 = Deck.new deck1.create_shuffled_deck expect(@deck.deck.front).to_not eq(deck1.deck.front) end end describe "deal_card" do it "deals the top card in the deck/changes the front pointer of the LinkedList" do card1 = Card.new("J", 11, "Spades") card2 = Card.new("A", 14, "Clubs") @deck.add_card(card1) @deck.add_card(card2) test = @deck.deal_card expect(test.class).to eq(Card) expect(@deck.deck.front).to_not eq(card1) expect(@deck.deck.back).to eq(card2) end end end describe 'Player' do before(:each) do @ashley = Player.new("Ashley") end describe "initialize" do it "initializes with a name" do expect(@ashley.name).to eq("Ashley") end it "initializes with an empty hand" do expect(@ashley.hand.deck.front).to eq(nil) expect(@ashley.hand.deck.front).to eq(nil) end end end describe "War" do describe "initialize" do it "creates a 52 card deck and shuffles it" do war = War.new("ashley", "Clay") expect(war.deck.deck.front.class).to eq(Card) end end describe "deal_cards" do it "deals a hand of 26 cards to each player" do war = War.new("ashley", "Clay") temp_deck = war.deck.deck war.deal_cards p1_hand = war.player1.hand.deck p2_hand = war.player2.hand.deck expect(p1_hand.front.class).to eq(Card) expect(p1_hand.back.class).to eq(Card) expect(p2_hand.front.class).to eq(Card) expect(p2_hand.back.class).to eq(Card) expect(p1_hand.front).to_not eq(p2_hand.front) expect(temp_deck.front).to eq(nil) expect(temp_deck.back).to eq(nil) end end end ======= >>>>>>> f45e33c8e8ce818ab53aeecf746490ad4f6106d2
class Parsers::Utporn::Daily < ApplicationRecord def self.run start_time = Time.now log = Log.create(title: 'Daily Parser - UtPorn', body: "Start Job - #{start_time}<br>") require 'open-uri' tube = Tube.find_by_name('utPorn') return 'No Tube' if tube.nil? # download dump log.write_to_log("Download Dump - ") dump_url = "https://www.utporn.com/feeds/5days.txt" dump = open(dump_url) {|f| f.read } log.write_to_log("ok<br>Start each line:<br>") #ID|URL|TITLE|THUMBS|DURATION INT|PUBDATE|MP4_URL|TAGS dump.each_line do |line| row = line.split('|') puts row[0] next if row[0] == 'ID' source_id = row[0] url = row[1] embed = nil title = row[2] slug = row[2].parameterize duration_int = row[4] duration_str = Parsers::Utporn::Daily.duration_int_to_str(duration_int) pubdate = row[5] if row[7].empty? tag_info = 'free porn,sex' else tag_info = row[7].strip.downcase end content = tube.contents.new( source_id: source_id, url: url, embed: embed, title: title, duration_str: duration_str, duration_int: duration_int, pubdate: pubdate, tag_info: tag_info, slug: slug ) if content.save log.write_to_log("#{source_id} ") threads = [] thumbs = row[3].split(',') thumbs.each do |thumb| threads << Thread.new do |t| rand_str = rand(1000..9999) FileUtils.mkdir_p("#{Setting.first.dir_for_thumbs}/thumbs/#{content.id/1000}/#{content.id}") unless File.exists?("#{(Rails.root + "public").to_s}/thumbs/#{content.id/1000}/#{content.id}") open("#{Setting.first.dir_for_thumbs}/thumbs/#{content.id/1000}/#{content.id}/#{rand_str}.jpg" , 'wb') do |file| file << open(thumb).read end content.thumbs.create(path: "/thumbs/#{content.id/1000}/#{content.id}/#{rand_str}.jpg") end threads.each {|t| t.join} end else log.write_to_log(". ") end end log.write_to_log("<br>End. Work time - #{Time.now-start_time} sec") end private def self.duration_int_to_str(duration_int) m = duration_int.to_i/60 s = duration_int.to_i%60 return m.to_s + "m" + s.to_s + "s"; end end
class SoupBroadcastJob < ApplicationJob queue_as :default def perform(soup) ActionCable.server.broadcast("soup_#{soup.id}_channel", type: "soup") end end
class ToolPhotosController < ApplicationController before_action :authenticate def create blob_name = build_blob_name container = 'tool-images' blob_url = container + '/' + blob_name image = {data: Base64.decode64(params[:tool][:image][:data]), filesize: params[:tool][:image][:filesize], fileName: params[:tool][:image][:fileName]} upload_blob(image, container, blob_name) @tool_photo = ToolPhoto.create(tool_id: params[:tool][:id], url: blob_url) if @tool_photo.save render json: @tool_photo, status: :created else render json: @tool_photo.errors, status: :unprocessable_entity end end private def build_blob_name # Find number of tool_photos and + 1 to incriment a new one tool_photo_number = Tool.find(params[:tool][:id]).tool_photos.length + 1 # "(TOOL_ID)/photo(num_tool_photo).(file_extension)" "#{params[:tool][:id]}/photo#{tool_photo_number}.#{params[:tool][:fileExt]}" end def upload_blob(image, container, blob_name) client = Azure::Storage::Client.create(:storage_account_name => "borostorage", :storage_access_key => "X9WSR1/ynmhy0FidgABmWGR3t5vmjgft46RJ7KAz5svGM1a7s4PbNy/Cq76dy3hbZZpESPr7OjktPoEhr+6x+A==") options = { :client => client } blobs = Azure::Storage::Blob::BlobService.new options content = File.open(image[:fileName], 'rb') { |f| f.read } blobs.create_block_blob(container, blob_name, content) end end
# lib/king.rb class King < Piece def move?(dst_x, dst_y) dx = (dst_x - @pos_x).abs dy = (dst_y - @pos_y).abs if (dx == 0 || dx == 1) && (dy == 0 || dy == 1) true else false end end end
require "aethyr/core/actions/commands/command_action" module Aethyr module Core module Actions module Fill class FillCommand < Aethyr::Extend::CommandAction def initialize(actor, **data) super(actor, **data) end def action event = @data room = $manager.get_object(@player.container) object = @player.search_inv(event[:object]) || room.find(event[:object]) from = @player.search_inv(event[:from]) || room.find(event[:from]) if object.nil? @player.output("What would you like to fill?") return elsif not object.is_a? LiquidContainer @player.output("You cannot fill #{object.name} with liquids.") return elsif from.nil? @player.output "There isn't any #{event[:from]} around here." return elsif not from.is_a? LiquidContainer @player.output "You cannot fill #{object.name} from #{from.name}." return elsif from.empty? @player.output "That #{object.generic} is empty." return elsif object.full? @player.output("That #{object.generic} is full.") return elsif object == from @player.output "Quickly flipping #{object.name} upside-down then upright again, you manage to fill it from itself." return end end #Display time. end end end end end
require "test_helper" class AdminEditsItemTest < ActionDispatch::IntegrationTest test "admin edits item" do admin = create(:admin) stache = create(:stache, name: "Chaplin", price: 4, description: "kljdf", retired: false) ApplicationController.any_instance.stubs(:current_user).returns(admin) visit admin_staches_path click_on "Edit" assert_equal edit_admin_stache_path(stache), current_path fill_in "Name", with: "Dictator" fill_in "Price", with: 55 fill_in "Description", with: "You know..." css_cat_1 = "#stache_retired[value='1']" find(:css, css_cat_1).set(true) click_on "Update Stache" assert page.has_content?("Dictator") assert page.has_content?("55") assert page.has_content?("You know...") assert page.has_content?("Retired") end end
class MessageBroadcastJob < ApplicationJob queue_as :default def perform(message) ActionCable.server.broadcast "room_channel_#{message.room_id}", mymessage: render_message(message, true), othersmessage: render_message(message, false), id: message.user.id end # ビミョ!! private def render_message(message, mymessage) renderer = ApplicationController.renderer_with_signed_in_user(message.user) renderer.render(partial: mymessage ? 'messages/message' : 'messages/others_message', locals: {message: message}) end end
require 'spec_helper' describe Resty::Factory do let(:transport) { mock('transport') } let(:factory) { Resty::Factory.new(transport) } describe "initialization" do subject { factory } its(:transport) { should == transport } end describe "#from" do let(:data) { { 'a' => 12 } } subject { factory.from(data) } it { should be_a(Resty) } it { subject._attributes.factory.should == factory } it { subject._attributes.data.should == data } end describe "#wrap" do ["string", 0, nil, true, false].each do |input| it "should return #{input.to_json} as itself" do factory.wrap(input).should eql(input) end end it "should wrap object into a Resty" do factory.wrap({}).should be_a(Resty) end it "should wrap array into a Resty" do factory.wrap([]).should be_a(Resty) end end describe "#from_param" do it "should decode the param and create a new Resty" do href = "http://bob.bob/" factory.from_param(Resty.encode_param(href))._href.should == href end it "should return a non-url resty for nil param" do factory.from_param(nil)._href.should be_nil end end end
# frozen_string_literal: true RSpec.describe 'kiosk_layouts/show', type: :view do before do assign(:kiosk_layout, create(:kiosk_layout)) render end it { expect(rendered).to match(/touch/) } end
require 'graphviz' require 'erb' module Designer module Graph GRAPH_ATTRIBUTES = { :rankdir => :LR, :ranksep => 0.5, :nodesep => 0.4, :pad => "0.4,0.4", :margin => "0,0", :concentrate => true, :labelloc => :t, :fontsize => 13, :fontname => "Arial Bold" } # Default node attributes. NODE_ATTRIBUTES = { :shape => "Mrecord", :fontsize => 10, :fontname => "Arial", :margin => "0.07,0.05", :penwidth => 1.0 } # Default edge attributes. EDGE_ATTRIBUTES = { :fontname => "Arial", :fontsize => 8, :dir => :both, :arrowsize => 0.9, :penwidth => 1.0, :labelangle => 32, :labeldistance => 1.8, :fontsize => 7 } NODE_WIDTH = 130 def self.entity_template ERB.new(File.read(File.expand_path("templates/entity.erb", File.dirname(__FILE__))), nil, "<>") end def self.erd_plot(model, opts={}) graph = GraphViz.digraph(opts[:title] || '') # Graphviz defaults # GRAPH_ATTRIBUTES.each { |attribute, value| graph[attribute] = value } NODE_ATTRIBUTES.each { |attribute, value| graph.node[attribute] = value } EDGE_ATTRIBUTES.each { |attribute, value| graph.edge[attribute] = value } draw_nodes graph, model graph.output(:png => 'test.png') end def self.node_exists?(graph, node_name) !!graph.get_node(node_name) end def self.edge_style { :color => :grey60, :arrowtail => :onormal, :arrowhead => :none, :arrowsize => 1.2 } end def self.draw_nodes(graph, model) model.to_node(graph) model_module = const_get(model.name.split('::').first) model.relations.each { |r| begin relation_class = model_module.const_get(r.to_klass) next if node_exists?(graph, relation_class.entity_name) draw_nodes(graph, relation_class) graph.add_edges graph.get_node(relation_class.entity_name), graph.get_node(model.entity_name), edge_style rescue NameError warn "WARN: #{r.to_klass} model definition not found. Skipping..." end } end end end
class AdministratorPolicy < ApplicationPolicy include Roles attr_reader :user, :administrator def initialize(user, administrator) @user = user @administrator = administrator end def show? is_admin? user end def home? user == @administrator end end
class CreateDealDetails < ActiveRecord::Migration def self.up create_table :deal_details do |t| t.string :company_name t.string :merchant_name t.string :deal_name t.string :date_to_run t.string :deal_expiration_date t.integer :max_total_purchase t.integer :max_customer_purchase t.decimal :regular_price t.decimal :sale_price t.text :restrictions t.text :highlights t.text :full_detail t.string :sales_representative t.integer :phone t.decimal :teir_rate t.timestamps end end def self.down drop_table :deal_details end end
class TicketsController < ApplicationController def index @event = Event.find(params[:event_id]) end def new @event = Event.find(params[:event_id]) end def create @ticket_type = TicketType.new ticket_params @ticket_type.event_id = params[:event_id] case when exist_price?(@ticket_type) redirect_to :back, notice: "price existed" when exist_max_quantity?(@ticket_type) redirect_to :back, notice: "max quantity existed" else if @ticket_type.save redirect_to new_event_ticket_path(params[:event_id]), notice: "Added successfully" else redirect_to :back, notice: "Added error" end end end private def ticket_params params.require(:ticket_type).permit(:price, :name, :max_quantity) end def exist_tickets TicketType.where(:event_id => params[:event_id]) end def exist_price?(new_ticket) exist_tickets.each do |ticket| return true if ticket.price == new_ticket.price end return false end def exist_max_quantity?(new_ticket) exist_tickets.each do |ticket| return true if ticket.max_quantity == new_ticket.max_quantity end return false end end
ActiveAdmin.register Purchaser do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if resource.something? # permitted # end show title: :name do panel "Items" do table_for purchaser.items do |t| t.column("Identifier") { |item| item.identifier } t.column("Description") { |item| item.description } t.column("Price") { |item| number_to_currency item.price } end end panel "Total" do attributes_table_for purchaser do row("Cash/Check") { number_to_currency purchaser.items.sum(:price) } row("Credit Card (Add 3%)") { number_to_currency(purchaser.items.sum(:price) * 1.03) } end end end end
class LoginController < ApplicationController skip_before_filter :require_login, :only => [:new, :create] layout "login" def new end def create user = User.authenticate(params) if user session[:current_user_id] = user.id redirect_to user_path(user) else flash[:alert] = "Incorrect username or password" redirect_to url_for(:action => "new") end end def logout session[:current_user_id] = nil redirect_to root_path end end
# frozen_string_literal: true # @private # An internal join model not to be used directly class ClaimClaimant < ApplicationRecord belongs_to :claim belongs_to :claimant default_scope { order(id: :asc) } end
require 'parser/current' require_relative './ruby_class' require_relative './node_wrapper' require_relative './const_definition_finder' class ClassDefinitionProcessor < Parser::AST::Processor CLASS_OR_MODULE = %i(class module) attr_accessor :klasses def initialize(*) super @klasses = [] @nesting = [] @current_scope = [RubyClass.global_scope] end def process(node) @nesting.push(node) super node = @nesting.pop @current_scope.pop if CLASS_OR_MODULE.include?(node&.type) end def on_class(node) declare_info(NodeWrapper.new(node, @nesting)) super end def on_module(node) declare_info(NodeWrapper.new(node, @nesting)) super end def on_const(node) scope = @current_scope.last wrapped_node = NodeWrapper.new(node, @nesting) unless %i[class const].include?(wrapped_node.parent.type) if wrapped_node.current_namespace_node if wrapped_node.parent.type == :send && wrapped_node.parent.to_a[1] == :include scope.includes << find_or_declare_class(wrapped_node.node_value, scope) end if wrapped_node.parent.type == :send && wrapped_node.parent.to_a[1] == :extend scope.extends << find_or_declare_class(wrapped_node.node_value, scope) end end end super end private def declare_info(wrapped_node) scope = @current_scope.last existed_class = find_existed_class(wrapped_node.current_namespace_name, scope) ruby_class = existed_class || RubyClass.new parent = find_or_declare_class(wrapped_node.this_class_parent_name, scope) ruby_class.set_by_ast_node(wrapped_node, scope, parent) scope.constants = (scope.constants << ruby_class).uniq parent.constants = (parent.constants << ruby_class).uniq if parent @current_scope.push(ruby_class) return if existed_class @klasses << ruby_class end def find_or_declare_class(name, scope) return unless name klass = ConstDefinitionFinder.new(name, scope).call return klass if klass RubyClass.build_external(name, RubyClass.global_scope).tap do |klass| RubyClass.global_scope.constants = (RubyClass.global_scope.constants << klass).uniq @klasses << klass end end def find_existed_class(name, scope) existed_class = scope.constants.find { |klass| klass.name == name } existed_class || RubyClass.global_scope.constants.find { |klass| klass.external && (klass.name == name) } end end
# -*- encoding : utf-8 -*- require 'singleton' module Magti # URL for sending SMS. SMS_SEND_URL = 'http://81.95.160.47/mt/oneway' # URL for tracking SMS status. SMS_TRACK_URL = 'http://81.95.160.47/bi/track.php' # Maximum size of individual SMS message. MAX_SIZE = 160 # Service configuration class. # # Access it, using <code>Magti.config</code>. class Config include Singleton # user name attr_accessor :username # password attr_accessor :password # client attr_accessor :client # service attr_accessor :service # Returns security options hash. def security_options { :username => self.username, :password => self.password, :client_id => self.client, :service_id => self.service } end end def self.config(params = {}) params.each do |k, v| Magti::Config.instance.send "#{k}=".to_sym, v end Magti::Config.instance end end
require 'mirrors/iseq/visitor' require 'mirrors/marker' module Mirrors module ISeq # examines opcodes and aggregates references to classes, methods, and # fields. # # @!attribute [r] markers # @return [Array<Marker>] after {#call}, the class/method/field # references found in the bytecode. class ReferencesVisitor < Visitor attr_reader :markers def initialize super @markers = [] @last = [] end # If an instruction represents an access to an ivar, constant, or method # invocation, record it as such in {#markers}. Invoked by {#call}. # # @param [Array<Object>] bytecode a single instruction # @return [nil] def visit(bytecode) case bytecode.first when :getinstancevariable @markers << field_marker(bytecode[1]) when :getconstant @markers << class_marker(bytecode.last) when :opt_send_without_block @markers << method_marker(bytecode[1][:mid]) when :invokesuper @markers << method_marker(:super) when :defineclass @markers.concat(markers_from_block(bytecode[2])) when :putiseq @markers.concat(markers_from_block(bytecode[1])) when :send @markers << method_marker(bytecode[1][:mid]) if (bytecode[1][:flag] & FLAG_ARGS_BLOCKARG) > 0 if @last[0] == :putobject && @last[1].is_a?(Symbol) @markers << method_marker(@last[1]) end else @markers.concat(markers_from_block(bytecode[3])) end end @last = bytecode nil end private FLAG_ARGS_BLOCKARG = 0x02 def markers_from_block(native_code) vis = self.class.new vis.call(native_code) vis.markers end def class_marker(name) Marker.new( type: Mirrors::Marker::TYPE_CLASS_REFERENCE, message: name, file: @absolute_path, line: @line ) end def field_marker(name) Marker.new( type: Mirrors::Marker::TYPE_FIELD_REFERENCE, message: name, file: @absolute_path, line: @line ) end def method_marker(name) Marker.new( type: Mirrors::Marker::TYPE_METHOD_REFERENCE, message: name, file: @absolute_path, line: @line ) end end end end
class CartItemsController < ApplicationController before_action :authenticate_customer! def index @cart_items = CartItem.where(customer_id: current_customer.id) end def create @cart_item = current_customer.cart_items.build(cart_item_params) @cart_items = current_customer.cart_items.all unless @cart_item.quantity.present? @product = Product.find(@cart_item.product_id) render "products/show" else #byebug @cart_items.each do |cart_item| if cart_item.product_id == @cart_item.product_id add_quantity = cart_item.quantity + @cart_item.quantity cart_item.update_attribute(:quantity, add_quantity) @cart_item.delete end end#each文のend @cart_item.save flash[:notice] = "カートに商品を追加しました" redirect_to :cart_items end end def update @cart_item = CartItem.find(params[:id]) if @cart_item.update(cart_item_params) flash[:notice] = "カートの中身をを更新しました" redirect_to cart_items_path else render :index end end def destroy @cart_items = CartItem.find(params[:id]) @cart_items.destroy redirect_to cart_items_path end def destroy_all @cart_items = CartItem.where(customer_id: current_customer.id) @cart_items.destroy_all redirect_to cart_items_path end private def cart_item_params params.require(:cart_item).permit(:product_id, :quantity) end end
# frozen_string_literal: true module Rokaki module FilterModel class BasicFilter def initialize(keys:, prefix:, infix:, like_semantics:, i_like_semantics:, db:) @keys = keys @prefix = prefix @infix = infix @like_semantics = like_semantics @i_like_semantics = i_like_semantics @db = db @filter_query = nil end attr_reader :keys, :prefix, :infix, :like_semantics, :i_like_semantics, :db, :filter_query attr_accessor :filter_method, :filter_template def call first_key = keys.shift filter = "#{prefix}#{first_key}" name = first_key keys.each do |key| filter += "#{infix}#{key}" name += "#{infix}#{key}" end @filter_method = "def #{prefix}filter_#{name};" \ "#{_chain_filter_type(name)} end;" # class_eval filter_method, __FILE__, __LINE__ - 2 @filter_template = "@model = #{prefix}filter_#{name} if #{filter};" end def _chain_filter_type(key) filter = "#{prefix}#{key}" query = '' if like_semantics && mode = like_semantics[key] query = build_like_query( type: 'LIKE', query: query, filter: filter, mode: mode, key: key ) elsif i_like_semantics && mode = i_like_semantics[key] query = build_like_query( type: 'ILIKE', query: query, filter: filter, mode: mode, key: key ) else query = "@model.where(#{key}: #{filter})" end @filter_query = query end def build_like_query(type:, query:, filter:, mode:, key:) if db == :postgres query = "@model.where(\"#{key} #{type} ANY (ARRAY[?])\", " query += "prepare_terms(#{filter}, :#{mode}))" else query = "@model.where(\"#{key} #{type} :query\", " query += "query: \"%\#{#{filter}}%\")" if mode == :circumfix query += "query: \"%\#{#{filter}}\")" if mode == :prefix query += "query: \"\#{#{filter}}%\")" if mode == :suffix end query end end end end
module GroupDocs class Signature::Envelope::Log < Api::Entity # @attr [String] id attr_accessor :id # @attr [String] date attr_accessor :date # @attr [String] userName attr_accessor :userName # @attr [String] action attr_accessor :action # @attr [String] remoteAddress attr_accessor :remoteAddress # Human-readable accessors alias_accessor :remote_address, :remoteAddress alias_accessor :user_name, :userName end # Signature::Envelope::Log end # GroupDocs
#!/usr/bin/env ruby require 'digest' IN = 'eDP-1' SLEEPSECS = 5 PIDFILE = File.join ENV['HOME'], '.monitor-hotplug.pid' DEBUG = false PRECMD = [] #PRECMD = ['xrandr --newmode "1920x1080" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync', 'xrandr --addmode eDP-1 "1920x1080"'] POSTCMD = ['i3 restart', 'nitrogen --restore'] IN_APPEND = ' --mode 1920x1080' EXT_APPEND = ' --auto --primary' DRICARD = 'card0' @dripath = File.join('/sys', %x(udevadm info -q path -n /dev/dri/#{DRICARD}).chomp) puts "Using sys path: #{@dripath}" def shutdown File.delete(PIDFILE) if File.exist? PIDFILE exit 0 end def startup exit! if File.exist? PIDFILE File.write PIDFILE, @pid Process.detach @pid unless DEBUG puts "Forked process PID #{@pid}" end def execute(cmd) DEBUG ? (puts cmd) : (%x(#{cmd})) end def edidchanged? @edid ||= [] curr_edid = [] puts "checking #{@dripath}/#{DRICARD}-*" if DEBUG Dir.glob("#{@dripath}/#{DRICARD}-*").each do |dir| puts "checking edid path #{dir}" if DEBUG edid_f = File.join(dir, 'edid') next unless File.exist?(edid_f) curr_edid << Digest::MD5.file(edid_f).to_s end puts "Stored EDIDs: #{@edid}\nCurrent EDIDs: #{curr_edid}" if DEBUG unless @edid == curr_edid.sort @edid = curr_edid.sort puts 'EDIDs changed' if DEBUG return true end puts 'EDIDs unchanged' if DEBUG false end PRECMD.each do |cmd| execute cmd sleep 0.5 end @pid = fork do Signal.trap('INT') do shutdown end Signal.trap('TERM') do shutdown end loop do puts 'Running loop' if DEBUG sleep SLEEPSECS next unless edidchanged? _displays = [] %x(xrandr).split("\n").each { |l| _displays << l.gsub(/ .*/, '') if l =~ / connected/} external = (_displays - [IN]).first if external # external monitor @external = external xrandr = "xrandr --output #{IN} --off --output #{@external}#{EXT_APPEND}" else xrandr = "xrandr --output #{@external||= 'UDEF'} --off --output #{IN} --primary#{IN_APPEND}" end execute xrandr sleep 3 POSTCMD.each do |cmd| execute cmd end end end startup
# == Schema Information # # Table name: book_identifiers # # id :integer not null, primary key # client_id :integer not null # book_id :integer not null # code :string(20) not null # created_at :datetime not null # updated_at :datetime not null # class BookIdentifier < ActiveRecord::Base belongs_to :client belongs_to :book validates_presence_of :client_id, :book_id, :code validates_length_of :code, maximum: 20 end
Rails.application.routes.draw do default_url_options :host => "example.com" root 'sessions#new' get '/html' => 'prep_courses#html' get '/javascript' => 'prep_courses#javascript' get '/git' => 'prep_courses#git' get '/ruby' => 'prep_courses#ruby' get '/intro'=> 'prep_courses#intro' get '/submit' => 'prep_courses#submit' get 'users/:id/posts' => 'users#posts', :as => :user_posts get "mailbox/inbox" => "mailbox#inbox", as: :mailbox_inbox get "mailbox/sent" => "mailbox#sent", as: :mailbox_sent get "mailbox/trash" => "mailbox#trash", as: :mailbox_trash post '/posts' => 'posts#create' get '/signup'=> 'users#new' post '/login' => 'sessions#create' get '/logout' => 'sessions#destroy' resources :conversations do member do post :reply post :trash post :untrash end end resources :posts do resources :comments, only: [:create] end resources :prep_courses, only: [:index] resources :users resources :likes, only: [:create, :destroy] end
class Tag < ActiveRecord::Base validates :name, presence: true, uniqueness: true has_many :recipe_tags, dependent: :destroy has_many :recipes, through: :recipe_tags end
require 'pry' class Race < ActiveRecord::Base has_many :drivers, through: :finishing_positions has_many :finishing_positions def determine_race_score(driver) # creates a race score for a driver skill = driver.skill_factor technology = driver.constructor.tech_factor rand * 10 * skill * technology # returns an integer > score end def get_scorecards(drivers) # maps each driver to his/her race score drivers.map { |driver| [determine_race_score(driver), driver] } # returns an array of arrays > [score, driver instance] end def sort_scorecards(drivers) # gets racescore for drivers and sorts them get_scorecards(drivers).sort { |a, b| b[0] <=> a[0] } # returns an sorted array of arrays > [score, driver instance] end def get_ranked_scorecards(drivers) sort_scorecards(drivers).each_with_index.map do |scorecard, index| [index + 1, scorecard[1]] end # returns an array of arrays > [position, driver instance] end def run_race(drivers) # get ranking, save FinishingPositions to Database get_ranked_scorecards(drivers).each do |rank| FinishingPosition.create(final_position: rank[0], driver_id: rank[1].id, race_id: id, game_id: game_id ) end end def drivers_finishingposition FinishingPosition.select do |fp| fp.race_id == id && fp.game_id == game_id end # returns an array of instances [,,,] end def show_ranking puts ' ' puts "Live from #{circuit}, we just got the final results:" puts ' ' puts ' Position | Driver | Team' puts '----------------------------------------------' drivers_finishingposition.each do |fp| puts "#{fp.final_position} | #{fp.driver.name} | #{Constructor.find_by(id: fp.driver.constructor_id).name}" end puts ' ' end end
class Foodstuff < ApplicationRecord has_many :best_foodstuffs has_many :seasons, through: :best_foodstuffs has_many :morimori_foodstuffs has_many :morimoris, through: :morimori_foodstuffs has_many :foodstuff_makes has_many :makes, through: :foodstuff_makes belongs_to :category end
# frozen_string_literal: true class ChangeStatusFieldForAttendance < ActiveRecord::Migration[5.1] def up add_column :attendances, :status_string, :string execute('UPDATE attendances SET status_string = status;') execute('UPDATE attendances SET status = null;') remove_column :attendances, :status add_column :attendances, :status, :integer Attendance.all.each { |attendance| attendance.update(status: Attendance.statuses[attendance.status_string]) if attendance.status_string.present? } remove_column :attendances, :status_string end def down add_column :attendances, :status_int, :integer execute('UPDATE attendances SET status_int = status;') execute('UPDATE attendances SET status = null;') change_column :attendances, :status, :string Attendance.all.each { |attendance| attendance.update(status: Attendance.statuses.key(attendance.status_int)) if attendance.status_int.present? } remove_column :attendances, :status_int end end
Rails.application.routes.draw do devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks', registrations: 'users/registrations' } # sets the index action for the books controller as the root path for a signed in user # sets up the log in page as root path for an unauthenticated user authenticated :user do root 'books#index', as: 'authenticated_root' end devise_scope :user do root 'devise/sessions#new' end #view borrowable books/borrow book get '/books/:id/borrow', to: 'books#show_available_to_borrow', as:'view_borrowable_book' post '/books/:id/borrow', to: 'books#borrow_book', as:'borrow_book' #view borrowed books/return book get '/books/:id/borrowed', to: 'books#show_borrowed', as:'borrowed_book' post '/books/:id/return', to: 'books#return_book', as: 'return_book' #nested this way for clarity, as new comments are instantiated from borrowed books only #comment belongs_to book and borrowed is "nested" under books/:id #so comment CRUD routes live with books#show -- books/:book_id/comments/:id resources :books, only: [:show_borrowed] do resources :comments, only: [:new, :create, :edit, :update, :destroy] end #powers comment index, which allows editing and deletion by linking to nested routes above resources :comments, only: [:index] resources :books, only: [:index, :show, :new, :create, :edit, :update, :destroy] resources :genres, only: [:show] resources :authors, only: [:show] end
module ExamRoom::Practice def self.table_name_prefix 'exam_room_practice_' end end
Then(/^I should be on the cfs files page for the (.*) with (.*) '([^']*)'$/) do |object_type, key, value| expect(current_path).to eq(specific_object_path(object_type, key, value, prefix: 'cfs_files')) end
Rails.application.routes.draw do root 'application#info' # user namespace namespace :v1 do post 'user_token' => 'user_token#create' resources :offers, only: [:index, :show, :create] end # admin namespace namespace Settings.routes.admin_namespace do Sidekiq::Web.use Rack::Auth::Basic do |username, password| username == Settings.sidekiq.username && password == Settings.sidekiq.password end mount Sidekiq::Web => '/sidekiq' end match '*path', to: 'application#routing_not_found', via: :all end
require 'singleton' class PhotoFrame class Config include Singleton attr_accessor :paths, :patterns, :secret, :shuffle attr_reader :root def initialize self.paths, self.patterns = [], [] self.shuffle = false end def root=(path) @root = path @root.send(:extend, Root) end module Root def join(*args) File.join(self, *args) end end end end
# encoding: utf-8 module Antelope module Ace class Scanner # Scans the second part of the file. The second part of the # file _only_ contains productions (or rules). Rules have a # label and a body; the label may be any lowercase alphabetical # identifier followed by a colon; the body consists of "parts", # an "or", a "prec", and/or a "block". The part may consist # of any alphabetical characters. An or is just a vertical bar # (`|`). A prec is a precedence declaraction, which is `%prec ` # followed by any alphabetical characters. A block is a `{`, # followed by code, followed by a terminating `}`. Rules _may_ # be terminated by a semicolon, but this is optional. module Second # Scans the second part of the file. This should be from just # before the first content boundry; if the scanner doesn't # find a content boundry, it will error. It will then check # for a rule. # # @raise [SyntaxError] if no content boundry was found, or if # the scanner encounters anything but a rule or whitespace. # @return [void] # @see #scan_second_rule # @see #scan_whitespace # @see #error! def scan_second_part scanner.scan(CONTENT_BOUNDRY) or error! tokens << [:second] until @scanner.check(CONTENT_BOUNDRY) scan_second_rule || scan_whitespace || scan_comment || error! end end # Scans a rule. A rule consists of a label (the nonterminal # the production is for), a body, and a block; and then, # an optional semicolon. # # @return [Boolean] if it matched # @see #scan_second_rule_label # @see #scan_second_rule_body # @see #error! def scan_second_rule if @scanner.check(/(#{IDENTIFIER})(\[#{IDENTIFIER}\])?:/) scan_second_rule_label or error! scan_second_rule_body true end end # Scans the label for a rule. It should contain only lower # case letters and a colon. # # @return [Boolean] if it matched. def scan_second_rule_label if @scanner.scan(/(#{IDENTIFIER})(?:\[(#{IDENTIFIER})\])?: ?/) tokens << [:label, @scanner[1], @scanner[2]] end end # The body can contain parts, ors, precs, or blocks (or # whitespaces). Scans all of them, and then attempts to # scan a semicolon. # # @return [void] # @see #scan_second_rule_part # @see #scan_second_rule_or # @see #scan_second_rule_prec # @see #scan_second_rule_block # @see #scan_whitespace def scan_second_rule_body body = true while body scan_second_rule_prec || scan_second_rule_part || scan_second_rule_or || scan_second_rule_block || scan_whitespace || scan_comment || (body = false) end @scanner.scan(/;/) end # Attempts to scan a "part". A part is any series of # alphabetical characters that are not followed by a # colon. # # @return [Boolean] if it matched. def scan_second_rule_part if @scanner.scan(/(%?#{IDENTIFIER})(?:\[(#{IDENTIFIER})\])?(?!\:|[A-Za-z._])/) tokens << [:part, @scanner[1], @scanner[2]] end end # Attempts to scan an "or". It's just a vertical bar. # # @return [Boolean] if it matched. def scan_second_rule_or if @scanner.scan(/\|/) tokens << [:or] end end # Attempts to scan a precedence definition. A precedence # definition is "%prec " followed by a terminal or nonterminal. # # @return [Boolean] if it matched. def scan_second_rule_prec if @scanner.scan(/%prec (#{IDENTIFIER})/) tokens << [:prec, @scanner[1]] end end # Attempts to scan a block. This correctly balances brackets; # however, if a bracket is opened/closed within a string, it # still counts that as a bracket that needs to be balanced. # So, having extensive code within a block is not a good idea. # # @return [Boolean] if it matched. def scan_second_rule_block if @scanner.scan(/\{/) tokens << [:block, _scan_block] end end private # Scans the block; it scans until it encounters enough closing # brackets to match the opening brackets. If it encounters # an opening brackets, it increments the bracket counter by # one; if it encounters a closing bracket, it decrements by # one. It will error if it reaches the end before the # brackets are fully closed. # # @return [String] the block's body. # @raise [SyntaxError] if it reaches the end before the final # bracket is closed. def _scan_block brack = 1 body = "{" scan_for = %r{ ( (?: " ( \\\\ | \\" | [^"] )* "? ) | (?: ' ( \\\\ | \\' | [^'] )* '? ) | (?: // .*? \n ) | (?: \# .*? \n ) | (?: /\* [\s\S]+? \*/ ) | (?: \} ) | (?: \{ ) ) }x until brack.zero? if part = @scanner.scan_until(scan_for) body << part if @scanner[1] == "}" brack -= 1 elsif @scanner[1] == "{" brack += 1 end else if @scanner.scan(/(.+)/m) @line += @scanner[1].count("\n") end error! end end body end end end end end
class Song < ActiveRecord::Base belongs_to :user has_many :votes validates :song_title, presence: true, length: { maximum: 140 } validates :author, presence: true, length: { maximum: 25 } validates :url, format: { with: URI.regexp, message: "%{value} is not valid" } end
class EventsController < ApplicationController before_action :find_event, only: [:show, :edit, :update, :destroy] def index @active_events = Event.where(status: "Active") @inactive_events = Event.where(status: "Inactive") @past_events = Event.where(status: "Past") @current_user = User.find(session[:user_id]) end def new @event = Event.new @current_user = current_user end def create Event.create(event_params) redirect_to events_path end def show @current_user = User.find(session[:user_id]) @creator = Event.find(params[:id]).creator @event = Event.find(params[:id]) @games = Event.find(params[:id]).games.where(status: "pending") @winners = @event.leaderboard if @event.current_game @current_players = @event.currently_playing if @event.current_game.is_player?(session[:user_id]) @current_game = @event.current_game end end end def edit @current_user = Event.find(params[:id]).creator if @current_user!= User.find(session[:user_id]) flash[:edit_error] = "You are not allowed to edit this event. Please ask the #{creator}" redirect_to events_path end end def update @event.update(event_params) redirect_to events_path end def destroy @event.destroy redirect_to events_path end def search if Event.find(params[:q]) redirect_to event_path(Event.find(params[:q])) else flash[:search] = "No event found." redirect_to events_path end end # def search_post # redirect_to search_events_path(params[:q]) # end private def find_event @event = Event.find(params[:id]) end def event_params params.require(:event).permit(:title, :status, :creator_id) end end
# encoding: UTF-8 module Decider module Clustering class Hierarchical < Base def tree unless @tree @tree = Tree.new corpus.documents.each do |doc| @tree.insert(doc.name, vector(doc)) end end @tree end def root_node tree.root end def invalidate_cache @tree = nil super end end end end
class Chapter include Mongoid::Document field :title attr_accessible :title belongs_to :book end