text
stringlengths
10
2.61M
#モデルに書いたメソッドはコントローラーで使用可能 #いわゆるインスタンスメソッド class User < ApplicationRecord #saveを実行する前にemailを小文字に破壊的に変換、selfが付いているので自分自身の変数ということ before_save { self.email.downcase! } #nameカラムのバリデーション validates :name, presence: true, length: { maximum: 50 } #emailのバリデーション、formatでemailの型を検証、uniquenessで被りがないか検証 validates :email, presence: true, length: { maximum: 255 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }, uniqueness: { case_sensitive: false } #パスワード設定の際に必要 has_secure_password #Userから見た際に複数のMicropostを持つので一対多 has_many :microposts #ユーザーによるmicropostのお気に入り機能追加の為に追記 #中間テーブルとの関係 #dependent: :destroyを設定することで記事を消した時に中間テーブルも消す has_many :favorites, dependent: :destroy #Useの投稿した記事との関連付けの際にmicropostsメソッド使用、重複を避ける為にfavorite_micropostsメソッドを指定 #新発見、テーブルの関連付けの際にメソッドとして定義される has_many :likes, through: :favorites, source: :micropost, dependent: :destroy #フォロー関係のテーブル設定 #前提としてrelationshipsの中間テーブルを持っている、左から中間 has_many :relationships #followingsは勝手に命名、上記のhas_many :relationshipsを通じて自身のフォローしているuser_idを取得、左から右 has_many :followings, through: :relationships, source: :follow #reverses_of_relationshipは勝手に命名、relationshipsクラスを通じて自分が右側になった時、自身がfollow_idになると指定、逆の時のみ指定必須、右から中間 has_many :reverses_of_relationships, class_name: "Relationship", foreign_key: "follow_id" #followersは勝手に命名、上記のhas_many :reverses_of_relationshipsを通じて自分をフォローしているuser_idを取得、右から左 has_many :followers, through: :reverses_of_relationships, source: :user #ここから下はインスタンスメソッド、Usersコントラーラーの処理を手伝う def follow(other_user) #selfにはこのメソッドを実行したインスタンス(変数)が入ってる(レシーバー自身)、user1.follow(user2)の場合だとuser1が入ってる unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end def unfollow(other_user) relationship = self.relationships.find_by(follow_id: other_user.id) relationship.destroy if relationship end def following?(other_user) #自分がフォローしているユーザーの中にotherユーザーが含まれていればtrue self.followings.include?(other_user) end def feed_microposts #following_idsはhas_many :followingsによって自動で生成されるメソッド、UserがフォローしているUserのidを配列で取得、Micropost.where(user_id: フォローユーザ + 自分自身) となる Micropost を全て取得しています #もし、自分のuser_idが3で、自分がフォローしているユーザーのidが5,6の時、 #Micropost.where(user_id: 3,5,6)⇨⇨uer_idが3,5.6の投稿したメッセージを探すということになる Micropost.where(user_id: self.following_ids + [self.id]) end #current_userがお気に入り登録した記事表示用 def like_microposts #following_idsはhas_many :followingsによって自動で生成されるメソッド、UserがフォローしているUserのidを配列で取得、Micropost.where(user_id: フォローユーザ + 自分自身) となる Micropost を全て取得しています #もし、自分のuser_idが3で、自分がフォローしているユーザーのidが5,6の時、 #Micropost.where(user_id: 3,5,6)⇨⇨uer_idが3,5.6の投稿したメッセージを探すということになる #whereのところにwhere(micropost_id: self.like_ids)と書くのは間違い #Micropostのidではなく、Micropostのmicropost_idというあるはずのないカラムを探してしまうから Micropost.where(id: self.like_ids) end #other_userとother_user、micropostがあってるか不明 #お気に入り機能の設定 def favorite(micropost) #find_or_create_byメソッドはカラム名の指定とそれに対する引数のみが必要、find_or_create_by(カラム名: カラムの値) #findはidのみ、find_byはid以外を指定可能 #なぜidなのにfindではないかというと、Favoriteテーブルから見たidは中間テーブルのidであり、micropost_idとは異なる為 #イメージではUserテーブルを通じて、中間テーブルの中のmicropost_idを探すイメージ self.favorites.find_or_create_by(micropost_id: micropost.id) end def unfavorite(micropost) #favoriteインスタンスの中身は自分のお気に入りした記事のid favorite = self.favorites.find_by(micropost_id: micropost.id) #もしお気に入りしていたら(favoriteがnilでなければ)中間テーブルから削除 favorite.destroy if favorite end def favorite?(micropost) #favorite_micropostsメソッドはhas_manyのテーブルの関連付けの際に指定 self.likes.include?(micropost) end end
class PayrollEntriesController < ApplicationController before_filter :payroll_entry_owner layout 'application-admin' def show @payroll_entry = PayrollEntry.find(params[:id]) @payroll = @payroll_entry.payroll @entries_by_date = @payroll_entry.group_by_date_and_calculate_totals end def destroy @payroll_entry = current_user.payroll_entries.find(params[:id]) @payroll_entry.destroy redirect_to @payroll_entry.payroll, :notice => "Entry for #{@payroll_entry.full_name} has been removed" end def update @payroll_entry = current_user.payroll_entries.find(params[:id]) respond_to do |format| if @payroll_entry.update_attributes(params[:payroll_entry]) format.json { respond_with_bip(@payroll_entry) } else format.json { respond_with_bip(@payroll_entry) } end end end def payroll_entry_owner if current_user.blank? || (params[:id].present? && current_user != PayrollEntry.find_by_id(params[:id]).user) redirect_to user_root_path, notice: "Please sign into the account which owns this payroll entry record to edit it" end end end
class Notifications < ActionMailer::Base default :from => "from@example.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.notifications.membership.subject # def membership(owner, items) @items = items mail :to => owner, :subject => 'Membership Notification' end end
json.array!(@member_event_categories) do |member_event_category| json.extract! member_event_category, :id, :mec_sName, :mec_sDescripton json.url member_event_category_url(member_event_category, format: :json) end
fastlane_version "2.69.2" default_platform :android platform :android do before_all do end desc "Build Debug" lane :build do gradle( task: "assembleDebug" ) end desc "Build Release" lane :build_release do gradle( task: "assembleRelease" ) end desc "Bump version number" lane :bump_version do android_set_version_code version = android_get_version_name parts = version.split(/[.]/) major = parts[0].to_i minor = parts[1].to_i patch = parts[2].to_i android_set_version_name( version_name: "#{major}.#{minor}.#{patch + 1}" ) end desc "Tag current version and push to GitHub" lane :tag_version do version = android_get_version_name build = android_get_version_code sh "git checkout master" git_pull git_commit( path: "./app/build.gradle", message: "Version #{version} (build #{build}) [release android] [skip ci]" ) add_git_tag( tag: "v#{version}-#{build}-android" ) push_to_git_remote( remote_branch: "master", tags: true, force: true ) end after_all do |lane| end error do |lane, exception| end end
require 'rails_helper' RSpec.describe "Edits", type: :request do let(:user) { FactoryGirl.create(:user) } let(:other_user) { FactoryGirl.create(:user) } def log_in_as(user, remember_me: '1') post login_path, params: { session: { email: user.email, password: user.password, remember_me: remember_me } } end describe "GET /edit" do it "doesnt update user with bad params" do log_in_as(user) get edit_user_path(user) expect(response).to render_template(:edit) patch user_path(user), params: { user: { name: "", email: "foo@invalid", password: "foo", password_confirmation: "bar" } } expect(response).to render_template(:edit) end it "updates user info successfully" do log_in_as(user) get edit_user_path(user) expect(response).to render_template(:edit) new_name = "John Doe" new_email = "johnd@example.com" patch user_path(user), params: { user: { name: new_name, email: new_email, password: "", password_confirmation: "" } } expect(flash[:success]).to be expect(response).to redirect_to user_path user.reload expect(user.name).to eq new_name expect(user.email).to eq new_email end it "redirects home if a user isnt logged in" do get edit_user_path(other_user) expect(flash[:danger]).to be expect(response).to redirect_to login_path end it "should redirect update when not logged in" do patch user_path(other_user), params: { user: { name: other_user.name, email: other_user.email } } expect(flash[:danger]).to be expect(response).to redirect_to login_path end it "should redirect home if a user tries to access another user's edit page" do log_in_as(other_user) get edit_user_path(user) expect(flash[:danger]).to_not be expect(response).to redirect_to root_path end it "should redirect home if a user tries to update another user's info" do log_in_as(other_user) patch user_path(user), params: { user: { name: other_user.name, email: other_user.email } } expect(flash[:danger]).to_not be expect(response).to redirect_to root_path end it "successful goes to edit with friendly forwarding" do get edit_user_path(user) log_in_as(user) expect(response).to redirect_to edit_user_url(user) name = "Foo Bar" email = "foo@bar.com" patch user_path(user), params: { user: { name: name, email: email, password: "", password_confirmation: "" } } #expect(flash[:danger]).to_not be expect(response).to redirect_to user_path user.reload expect(name).to eq user.name expect(email).to eq user.email end it "only friendly forwards once" do get edit_user_path(user) log_in_as(user) expect(response).to redirect_to edit_user_url(user) expect(session[:forwarding_url]).to_not be end end describe "updating values" do it "Doesnt allow admin attribute to be edited via the web" do log_in_as(user) expect(other_user.admin?).to be false patch user_path(other_user), params: { user: { password: "foobar", password_confirmation: "foobar", admin: true } } expect(other_user.admin?).to be false end end end
ActiveAdmin.register Transaction do permit_params :id, :kind, :original_balance, :amount, :amount_positive, :final_balance, :confirmation, :itemable_type, :itemable_id, :itemable, :concernable, :concernable_type, :concernable_id, :reason, :restaurant_id belongs_to :user, optional: true controller do def scoped_collection if params[:id] && params[:type] loggable_type = params[:type] loggable_id = params[:id] type = loggable_type.constantize parent = type.find(loggable_id) transactions = parent.transactions.get_unarchived else Transaction.get_unarchived end end def create #move user_id if came through transaction params if params[:transaction][:user_id] params[:user_id] = params[:transaction][:user_id] end #concernable id is restaurant id. #Active admin couldn't make nested routes for both users and restaurants #check that admin came to this page through a user or restaurant first if params[:user_id] || params[:transaction][:concernable_id] #get concernable variables for redirect if params[:user_id].present? id = params[:user_id] type = "User" else id = params[:transaction][:concernable_id] type = "Restaurant" end #check to see if admin has entered amount yet or not and if not #ask admin to enter amount if params[:transaction][:amount] if params[:transaction][:kind] == "Adjustment" #create transaction if Transaction.create_adjustable_transaction(params, current_admin_user.id) flash[:notice] = "Transaction Added" redirect_to admin_transactions_path(id: id, type: type) else flash[:danger] = "Transaction Could not be added. " + "Please make sure reason is filled out so we know you're not " + "just sending yourself money :)" redirect_to :back end # use "who is paying" presence to check if it is a #restaurant balance payment elsif params[:transaction][:who_is_paying] transaction_params = Transaction.setup_balance_payment_params params if Transaction.create_balance_payment_transaction(transaction_params) flash[:notice] = "Transaction Added" redirect_to admin_transactions_path(id: id, type: "Restaurant") else flash[:danger] = "Transaction Could not be added. There was an error" redirect_to :back end else flash[:danger] = "Please choose a proper transaction category" redirect_to :back end else flash[:notice] = "Please enter transaction information" redirect_to new_admin_transaction_path(id: id, kind: params[:transaction][:kind], type: type) end else flash[:danger] = "Transaction Could not be added. Please make a " + "transaction through a user or restaurant first" redirect_to :back end end def destroy #do nothing for now end def update #do nothing for now end end index do selectable_column id_column column :kind column :confirmation column :original_balance column :amount column :amount_positive column :final_balance column :reason column :admin_id column :created_at column :updated_at actions end filter :kind filter :confirmation filter :original_balance filter :amount filter :amount_positive filter :final_balance filter :reason filter :admin_id filter :created_at filter :updated_at form do |f| f.inputs "New transaction" do #1st step make admin choose transaction_kind #if transaction kind is chosen then move to step 2 (entering amounts and reasons or who is paying) #kind is either adjustment or "restaurant balance payment" #type is User or Restaurant if params[:kind] == "Adjustment" f.input :amount, required: true f.input :reason, required: true if params[:type] == "Restaurant" f.input :concernable_id, input_html: { value: params[:id], hidden: true }, label: false else f.input :user_id, input_html: { value: params[:id], hidden: true }, label: false end f.input :concernable_type, input_html: { value: params[:type], hidden: true }, label: false f.input :kind, as: :string, input_html: { value: params[:kind], hidden: true }, label: false elsif params[:kind] == "Restaurant Balance Payment" f.input :amount, required: true f.input :who_is_paying, label: "Who is paying?", :as => :select, :collection => ['happy dining', 'restaurant'] f.input :concernable_id, input_html: { value: params[:id], hidden: true }, label: false f.input :concernable_type, input_html: { value: "Restaurant", hidden: true }, label: false f.input :kind, input_html: { value: params[:kind], hidden: true }, label: false else f.input :kind, label: "Please choose type of transaction you would like to create", :as => :select, :collection => ['Adjustment', 'Restaurant Balance Payment'] f.input :concernable_id, input_html: { value: params[:id], hidden: true }, label: false end end f.actions end end
class Search < SitePrism::Page set_url "/" # Submit Form Elements element :title_field, :id, "title" element :body_field, :id, "content" element :keywords_field, :id, "keywords" element :minimum_impact_field, :id, "minImpactFactor" element :maximum_impact_field, :id, "maxImpactFactor" element :primary_subject_field, "select#primary-subject" element :secondary_subjects_field, "select#secondary-subjects" element :find_journals_button, :id, "suggest" # Journal Suggestion Results Table ## Table element :results_table, :css, "#suggestions #search-results .table" element :name_table_header, :css, "#suggestions #search-results table.table-striped>thead>tr>th:nth-child(1)" element :impact_factor_table_header, :css, "#suggestions #search-results table.table-striped>thead>tr>th:nth-child(2)" element :access_type_table_header, :css, "#suggestions #search-results table.table-striped>thead>tr>th:nth-child(3)" elements :results_table_rows, :css, "#suggestions #search-results table.table-striped>tbody>tr" elements :mega_journals_table_rows, :css, "#suggestions #mega-journals-results table.table-striped>tbody>tr" elements :journal_names_in_results, :css, "#suggestions #search-results .result-row>td>a" elements :journal_impact_factor_in_results, :css, "#suggestions #search-results .result-row>td:nth-child(2)" ## Show More Copy Message Template Buttons element :show_more_button, :id, "show-more" element :copy_to_clipboard_button, :id, "copy-button" ## Message Template element :message_template_button, :id, "message-template-button" element :close_message_template_button, :id, "close-msg-template-button" element :message_template_modal_header, :css, "div.modal-header" element :message_template_text, :id, "message-text" ## Select Check Boxes Journals elements :select_checkboxes_table, :css, "#suggestions #search-results [name='selectedJournals']" # Header Section section :header, HeaderSection, ".nav.navbar-nav" # Selected Journals elements :suggestions_check_boxes, :css, "#suggestions #search-results [name='selectedJournals']" end
class ContactEntry < ActiveRecord::Base validates :name, :email, :message, :presence => true end
class CreateFavorite < ActiveRecord::Migration def change create_table :favorites do |t| t.belongs_to :tweet t.belongs_to :user, index: true t.timestamps null: false, index: true end end def down drop_table :favorites end end
Rails.application.routes.draw do get "/", to: "home#index", as: "home" post "/webhooks", to: "webhooks#index", as: "webhooks" match "/404", to: "errors#not_found", via: :all match "/500", to: "errors#internal_server_error", via: :all match "/422", to: "errors#unprocessable_entity", via: :all get "/signup", to: "auth#signup", as: "signup" post "/signup", to: "auth#create_user", as: "create_user" get "/login", to: "auth#login", as: "login" post "/login", to: "auth#authenticate", as: "authenticate" get "/logout", to: "auth#logout", as: "logout" get "/forgot_password", to: "auth#forgot_password", as: "forgot_password" post "/forgot_password", to: "auth#request_password_link", as: "request_password_link" get "/reset_password/:token", to: "auth#new_password", as: "new_password" post "/reset_password", to: "auth#reset_password", as: "reset_password" get "/activate_email/:token", to: "auth#activate_email", as: "activate_email" get "/settings", to: "settings#index", as: "settings" put "/settings", to: "settings#update", as: "update_settings" get "/setup", to: "setup#index", as: "setup" post "/setup/first_step", to: "setup#first_step", as: "setup_first_step" post "/setup/second_step", to: "setup#second_step", as: "setup_second_step" get "/setup/second_step/callback", to: "setup#second_step_callback", as: "setup_second_step_callback" post "/setup/third_step", to: "setup#third_step", as: "setup_third_step" post "/setup/fourth_step", to: "setup#fourth_step", as: "setup_fourth_step" post "/setup/fifth_step", to: "setup#fifth_step", as: "setup_fifth_step" post "/setup/sixth_step", to: "setup#sixth_step", as: "setup_sixth_step" get "/phone_number", to: "phone_number#index", as: "phone_number" put "/phone_number/pin_code", to: "phone_number#update_pin_code", as: "update_pin_code" get "/billing", to: "billing#index", as: "billing" get "/billing/invoice/:id", to: "billing#invoice", as: "billing_invoice" put "/billing/payment_method", to: "billing#update_payment_method", as: "update_payment_method" delete "/billing/cancel", to: "billing#cancel_subscription", as: "cancel_subscription" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
module BTWATTCH2 class Payload CMD_HEADER = [ 0xAA ] RTC_TIMER = [ 0x01 ] MONITORING = [ 0x08 ] TURN_OFF = [ 0xA7, 0x00 ] TURN_ON = [ 0xA7, 0x01 ] BLINK_LED = [ 0x3E, 0x01, 0x02, 0x02, 0x0F ] class << self def rtc(time) payload = [ RTC_TIMER, time.sec, time.min, time.hour, time.day, time.mon - 1, time.year - 1900, time.wday ].flatten generate(payload) end def monitoring generate(MONITORING) end def on generate(TURN_ON) end def off generate(TURN_OFF) end def blink_led generate(BLINK_LED) end def generate(payload) [ CMD_HEADER, size(payload), payload, CRC8.crc8(payload) ].flatten.pack("C*") end def size(payload) [payload.size].pack("n*").unpack("C*") end end end end
require "gepub" require "sinatra" class Hivemind < Sinatra::Base get "/epubs" do @epubs = EPub.all erb :"epubs/index" end get "/epubs/upload" do erb :"epubs/upload" end post "/epubs/upload" do tf = params[:epub][:tempfile] book = nil File.open(tf) do |f| book = GEPUB::Book.parse(f) end title = book&.title&.content || "Unknown title" creator = book&.creator&.content || "Unknown creator" publisher = book&.publisher&.content || "Unknown publisher" epub = EPub.create( title: title, creator: creator, publisher: publisher, uploader: current_user, epub: File.read(tf), ) Event.record(:uploaded_epub, user_id: current_user.id, epub_id: epub.id) if epub.cover? epub.cover_blob = epub.cover.content epub.cover_media_type = epub.cover.media_type epub.save end redirect "/epubs/#{epub.id}" end get "/epubs/random" do redirect "/epubs/#{EPub.select(&:id).map(&:id).shuffle.first}" end get "/epubs/:epub_id" do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? c_ids = @epub.collections.map(&:id) @collections = Collection.all @potential_collections = @collections.reject { |c| c_ids.include? c.id } erb :"epubs/show" end get "/epubs/:epub_id/cover" do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? raise Sinatra::NotFound if @epub.cover_blob.nil? || @epub.cover_blob.empty? cache_control :public, :max_age => 86400 content_type @epub.cover_media_type @epub.cover_blob end post "/epubs/:epub_id/status" do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? status = params[:status]&.gsub("-", "_")&.to_sym raise Sinatra::BadRequest if status.nil? case status when :wants_to_read current_user.wants_to_read_epub!(@epub) when :is_reading current_user.is_reading_epub!(@epub) when :has_read current_user.has_read_epub!(@epub) when :clear current_user.clear_epub_status!(@epub) end redirect "/epubs/#{@epub.id}" end post "/epubs/:epub_id/bookmark" do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? href = params[:href] raise Sinatra::BadRequest if href.nil? current_user.bookmark_epub!(epub_id=@epub.id, href=href) redirect @epub.href_path(href) + "?read#read-start" end get "/epubs/:epub_id/read" do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? redirect "/epubs/#{@epub.id}/href/#{@epub.first_readable.href}?read#read-start" end get %r(/epubs/(?<epub_id>\d+)/href/(?<href>.*)) do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? @item = @epub.parsed.item_by_href(params[:href]) if params.key? :read @href = params[:href] @show_bookmark_button = current_user.bookmark_for_epub(@epub) != @href erb :"epubs/read" else content_type @item.media_type @item.content end end post "/epubs/:epub_id/collections" do @epub = EPub.find(id: params[:epub_id]) raise Sinatra::NotFound if @epub.nil? @collection = Collection.find(id: params[:collection_id]) raise Sinatra::NotFound if @collection.nil? @collection.add_epub(@epub) redirect "/epubs/#{@epub.id}" end end class EPub < Sequel::Model def parsed @parsed ||= GEPUB::Book.parse StringIO.new(self.epub.to_s) end def href_path(href) "/epubs/#{id}/href/#{href}" end def chapters parsed.items.values.select { _1.media_type =~ /html/ } end def images parsed.items.values.select { _1.media_type =~ /jpeg/i || _1.media_type =~ /png/i } end def prev_href(item) chapters.take_while { _1.id != item }.last&.href end def next_href(item) chapters.drop_while { _1.id != item }.drop(1).first&.href end def cover images.select { |i| i.id =~ /cover/i }.first end def cover? !cover.nil? end def cover_href return nil if cover_blob.nil? || cover_blob.empty? "/epubs/#{id}/cover" end def table_of_contents chapters.select { |c| c.id =~ /contents/i }.first || chapters.select { |c| c.id =~ /toc/i }.first || chapters.select { |c| c.id =~ /table/i }.first || chapters.select { |c| c.id =~ /content/i }.first end def table_of_contents? !table_of_contents.nil? end def first_readable chapters.find { |v| v.id =~ /cover/i } || chapters.find { |v| v.id =~ /toc/i } || chapters.find { |v| v.id =~ /contents/i } || chapters.find { |v| v.id =~ /preface/i } || chapters.find { |v| v.id =~ /foreword/i } || chapters.find { |v| v.id =~ /chapter/i } || chapters.find { |v| v.id =~ /content/i } || chapters.first end end
class Waiter attr_accessor :name, :yrs_experience @@all = [] def initialize(name, yrs_experience) @name = name @yrs_experience = yrs_experience @@all << self end def self.all @@all end # create a meal def new_meal(customer, total, tip=0) Meal.new(self, customer, total, tip) end # we need a way for our customer and waiter instances to # get information about each other. # we can get info about customer through the meals they've created # a waiter might want to know who their regular customers are # and what meals those customers usually order # a method so a waiter can find a customer def meals Meal.all.select do |meal| meal.waiter == self #checking for waiter now end end # a way for a waiter to find all the meals they created def best_tipper best_tipped_meal = meals.max do |meal_a, meal_b| meal_a.tip <=> meal_b.tip end best_tipped_meal.customer end end # a customer can have many meals. # different instances of the meal # relationship with the customer is through your waiter.
Rails.application.routes.draw do root to: 'posts#index' post 'posts', to: 'posts#create' # メモのidを取得。queryパラメーターを使用した場合、/posts/?id=1とリクエストを送ると、 # params[:id]にてパラメーターを取得できる。今回はpathパラメーターで、一意の情報であるidを取得する get 'posts/:id', to: 'posts#checked' end
require "formula" class Dcraw < Formula homepage "http://www.cybercom.net/~dcoffin/dcraw/" url "http://www.cybercom.net/~dcoffin/dcraw/archive/dcraw-9.22.tar.gz" sha1 "f786f12d6cbf2a5571881bcf7f9945365459d433" bottle do cellar :any sha1 "a41d9e98e7c9470a488702da477b9413b9576716" => :mavericks sha1 "f4df4c978a8ddb2d6f96ed0627958ab8e326492a" => :mountain_lion sha1 "92e4cb2415cde153113b02addb1036fac1cc8dd0" => :lion end depends_on "jpeg" depends_on "jasper" depends_on "little-cms2" def install ENV.append_to_cflags "-I#{HOMEBREW_PREFIX}/include -L#{HOMEBREW_PREFIX}/lib" system "#{ENV.cc} -o dcraw #{ENV.cflags} dcraw.c -lm -ljpeg -llcms2 -ljasper" bin.install "dcraw" man1.install "dcraw.1" end end
class Api::V1::EntriesController < ApplicationController def index @entries = Entry.all render json: @entries end end
class City < ActiveRecord::Base has_many :neighborhoods has_many :listings, :through => :neighborhoods has_many :reservations, through: :listings include Place::InstanceMethods extend Place::ClassMethods # def city_openings(datestring1, datestring2) # date1 = City.to_date_time(datestring1) # date2 = City.to_date_time(datestring2) # self.listings.select {|listing| listing.is_open(date1, date2)} # end # def res_to_listings # unless self.listings.count==0 # self.reservations.count.to_f/self.listings.count # else # 0 # end # end # def self.highest_ratio_res_to_listings # City.all.max {|city1, city2| city1.res_to_listings <=> city2.res_to_listings } # end # def self.most_res # City.all.max { |city1, city2| city1.reservations.count <=> city2.reservations.count} # end # def self.to_date_time(datestring) # da = datestring.split('-') # DateTime.new(da[0].to_i, da[1].to_i, da[2].to_i) # end end
# Requires ruby 1.9.3 # A Trie is, as the pronunciation suggestions, a tree ( More accurately a root # system ). Each node contains a single letter, with branches to all possible # subletters in a word set. # Words that share prefixes will follow the same path until they differ, at # which point they branch into their respective paths. # This is faster for approximate matching as you remove re-checking in similar # words, significantly increasing operation speed, especially with larger # dictionaries # class Trie # Make sure the entire word is lowercase as distance calc # sees cases as different letters and we don't want that # CUNsperrICY -> cunsperricy # Remove duplicate consonnants if they are preceeded by duplicate vowels # peepple -> peeple # Replace duplicate+ consonants with singular if they are not right # After the first character in the word # apple -> apple # cunsperricy -> cunspericy # Replace triplicate+ vowels with duplicates # sheeeeep -> sheep # def self.normalize(word) word.downcase .gsub(/([aeiou])\1{1,}([^aeiou])\2{1,}/i,'\1\1\2') .gsub(/(?!^).([^aeiou])\1{1,}/i,'\1') .gsub(/([aeiou])\1{2,}/i,'\1\1') end attr_accessor :word attr_reader :children attr_reader :max_length def initialize(dict = nil) @word = nil @children = {} @max_length = 0 # pass a dict yet still can update attrs before build step yield self if block_given? self.build(dict) if dict end def insert word @max_length = word.length if word.length > @max_length node = self word.each_char do |letter| # register letter if it's not already present node.children[letter] ||= Trie.new # visit letter node = node.children[letter] end # register the word at the leaf node node.word = word end def build(dict) raise "Cannot build invalid dictionary: #{dict}" unless File.exists?(dict) IO.foreach(dict) { |word| self.insert(word.strip.downcase) } self end def suggest(word, max_cost = nil) word = self.class.normalize(word) max_cost ||= word.length # Made fast by keeping state between steps, so work is never done twice # state = {} 1.upto(max_cost).each { |i| suggestion = search(word, i, state) return suggestion if suggestion } 'NO SUGGESTION' end def search(word, cost = nil, outside_state = nil) word = self.class.normalize(word) cost ||= word.length state = outside_state || {} # Build the first row for Levenshtein distance calculation current_row = (0..word.size).to_a # results format: # { # "suggestion" => distance_calc, # "suggestion" => distance_calc # } results = {} # Recursively search each branch of the Trie self.children.each_key do |key| search_recursive(self.children[key], key, word, current_row, results, cost, state) end if (!results.empty?) matching_start = false results.each_key do |result| # Cheaper computationally to do this than calculate edit distance # with floating point math in the first place # # If the initial characters match, it's a better score # initial character typos were not part of the possible mistakes if (result[0] == word[0]) results[result] -= 0.4 matching_start = true # probably just substitution, a good chance this is worth more if (result.length == word.length) results[result] -= 0.1 end end end # Sort the results so the "best" result is at the top, then choose it if # the starting letter is the same as the entered word # Best = lowest return (matching_start) ? results.sort_by{|k,v| v}[0][0] : false else # Better luck next time return false end end def search_recursive(tnode, letter, word, previous_row, results, cost, state) # Check if state-data exists from the previous step if state[cost-1] and state[cost-1][tnode.object_id] # if its not empty then we've done this already, just restore the last # step's calculations then we just pass them off to the next recursion # like we would if we'd calculated them ourselves current_row = state[cost-1][tnode.object_id] # TODO: consider fetch else # If no state data exists, we're a fresh run! # Get busy with those calculations! current_row = [previous_row[0] + 1] # Build one row for the letter, with a column for each letter in the # target word, plus one for the empty string at column 0 (1..word.size).each do |column| insertCost = current_row[column - 1] + 1 deleteCost = previous_row[column] + 1 replaceCost = previous_row[column - 1] if word[column - 1] != letter replaceCost += 1 # vowels should be less valuable to replace, so if we're replacing a # consonant, increase the cost if letter =~ /[^aeiou]/ replaceCost += 1 end end current_row << [insertCost, deleteCost, replaceCost].min end # Set the state for this step on this trie, in case we have to run # another step state[cost] ||= {} state[cost][tnode.object_id] = current_row end # If the last entry in the row indicates the optimal cost is # not greater than the maximum cost, and there is a word in this # trie node, then add it to the results. if current_row.last <= cost and tnode.word != nil results[tnode.word] = current_row.last end # If any entries in the row are less than the maximum cost, then # recursively search each branch of the Trie. if current_row.min <= cost tnode.children.each_key do |letter| search_recursive(tnode.children[letter], letter, word, current_row, results, cost, state) end end end end
class UserSessionsController < ApplicationController layout 'login' def new end def create if login(params[:email], params[:password]) @user = User.find_by_email(params[:email]) redirect_back_or_to(user_path(@user)) else flash.now.alert = "Login failed." render action: :new end end def destroy logout redirect_to(root_path) end end
class CreateAdminReviews < ActiveRecord::Migration def change create_table :reviews do |t| t.references :student, index: true t.string :avatar t.integer :rating t.references :bootcamp, index: true t.text :body t.text :url t.timestamps end end end
require 'test_helper' class CategoryTest < ActiveSupport::TestCase # This method is always run before all the successive tests run def setup @category = Category.new(name: "sports") end test "category should be valid" do # Basically the following statement tests that can we create a new instance of Category and is it valid? assert @category.valid? end test "name should be present" do @category.name = " " assert_not @category.valid? end test "name should be unique" do @category.save category2 = Category.new(name: 'sports') assert_not category2.valid? end test "name should not be too long" do @category.name = "r" * 26 assert_not @category.valid? end test "name should not be too short" do @category.name = "rr" assert_not @category.valid? end end
class AddLiteracyRatePercentageAbove15ToYears < ActiveRecord::Migration def change add_column :years, :literacy_rate_percentage_above_15, :decimal end end
class CreateCheckins < ActiveRecord::Migration def change create_table :checkins do |t| t.boolean :sober t.integer :mood t.text :remarks t.boolean :need_support t.references :user, index: true, foreign_key: true t.timestamps null: false end end end
# # Seeds Client # # Clients consist of reference number, entities (only 1 in examples) # and an address # # Client Entity Address # id human_ref id title initials Name id flat_no house # 1 1 1 Mr K S Ranjitsinhji 1 96 Old Trafford # 2 2 2 Mr B Simpson 2 54 Old Trafford # 3 3 3 Mr V Richards 3 84 Old Trafford one = Client.new(id: 1, human_ref: 1) one.entities.build(entitieable_id: 1, entitieable_type: 'Client', title: 'Mr', initials: 'K S', name: 'Ranjitsinhji') one.build_address(addressable_id: 1, addressable_type: 'Client', flat_no: '96', house_name: 'Old Trafford', road_no: '154', road: 'Talbot Road', district: 'Stretford', town: 'Manchester', county: 'Greater Manchester', postcode: 'M16 0PX') two = Client.new(id: 2, human_ref: 2) two.entities.build(entitieable_id: 2, entitieable_type: 'Client', title: 'Mr', initials: 'B', name: 'Simpson') two.build_address(addressable_id: 2, addressable_type: 'Client', flat_no: '64', house_name: 'Old Trafford', road_no: '311', road: 'Brian Statham Way', district: 'Stretford', town: 'Manchester', county: 'Greater Manchester', postcode: 'M16 0PX') three = Client.new(id: 3, human_ref: 3) three.entities.build(entitieable_id: 3, entitieable_type: 'Client', title: 'Mr', initials: 'V', name: 'Richards') three.build_address(addressable_id: 3, addressable_type: 'Client', flat_no: '84', house_name: 'Old Trafford', road_no: '189', road: 'Great Stone Road', district: 'Stretford', town: 'Manchester', county: 'Greater Manchester', postcode: 'M16 0PX') Client.transaction do one.save! two.save! three.save! end
require_relative '../test_helper' #require_relative '../app/models/deposition' class DepositionTest < ActiveSupport::TestCase # test "the truth" do # assert true # end # # CAS REFUS D'EMBARQUEMENT test "Should return true when Refus d'embarquement" do reason = "Refus d'embarquement" dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) depo = Deposition.create(reason: reason, dep_city: dep_city, arr_city: arr_city, departure: departure, arrival: arrival) indemn = depo.indemn? assert_equal(true, indemn) end # # CAS ANNULATION SANS REACHEMINEMENT # # 1. sans avoir ete alerte test "should return true when there is no alert date and the reason is cancelation." do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Jamais" depo = Deposition.create(reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(true, indemn) end # 2. alerte entre 7 et 14 jours a l'avance test "should return true when the alert date is less than 14 days before the flight and the reason is cancelation." do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Entre 7 et 14 jours avant le vol" depo = Deposition.create(reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(true, indemn) end # 3. alerte plus de 14 jours a l'avance test "should return false when the alert date is more than 14 days before the flight and the reason is cancelation." do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Plus de 14 jours avant le vol" depo = Deposition.create(reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(false, indemn) end # CAS ANNULATION AVEC REACHEMINEMENT # 1. prevenu entre 7 et 14 jours a l'avance et reacheminement avec depart 2h max plus tot et arrivee 4h max plus tard test "1 should return false when the alert date is more than 7 days before the flight, the real departure is less than 2 hours before the flight, the arrival is less than 4 hours after the arrival and the reason is cancelation." do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Entre 7 et 14 jours avant le vol" forward = true forward_dep = DateTime.new(2020, 8, 20, 7, 0, 0) pp (departure - forward_dep) * 24 < 2 forward_arr = DateTime.new(2020, 8, 20, 11, 0, 0) depo = Deposition.create(forward: forward, forward_dep: forward_dep, forward_arr: forward_arr, reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) # pp (departure - forward_dep) * 24 <= 2 && (forward_arr - arrival) * 24 <= 4 indemn = depo.indemn? assert_equal(false, indemn) end # 2. prevenu entre 7 et 14 jours a l'avance et reacheminement avec depart 3h plus tot test "2 should return true when the alert date is more than 7 days before the flight, the real departure is more than 2 hours before the flight or the arrival is more than 4 hours after the arrival and the reason is cancelation." do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Entre 7 et 14 jours avant le vol" forward = true forward_dep = DateTime.new(2020, 8, 20, 5, 0, 0) forward_arr = DateTime.new(2020, 8, 20, 11, 0, 0) depo = Deposition.create(forward: forward, forward_dep: forward_dep, forward_arr: forward_arr, reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(true, indemn) end # 3. prevenu moins de 7 jours a l'avance et reacheminement avec depart 1h max plus tot et arrivee 2h max plus tard test '3 should return false when the alert date is less than 7 days before the flight, the real departure is less than 1 hour before the flight && the arrival is less than 2 hours after the arrival and the reason is cancelation.' do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Moins de 7 jours avant le vol" forward = true forward_dep = DateTime.new(2020, 8, 20, 8, 0, 0) forward_arr = DateTime.new(2020, 8, 20, 11, 0, 0) depo = Deposition.create(forward: forward, forward_dep: forward_dep, forward_arr: forward_arr, reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(false, indemn) end # # 4. prevenu moins de 7 jours a l'avance et reacheminement avec depart 2h max plus tot test 'should return true when the alert date is less than 7 days before the flight, the real departure is more than 1 hour before the flight or the arrival is more than 2 hours after the arrival and the reason is cancelation.' do reason = 'Annulation' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Moins de 7 jours avant le vol" forward = true forward_dep = DateTime.new(2020, 8, 20, 6, 0, 0) forward_arr = DateTime.new(2020, 8, 20, 11, 0, 0) depo = Deposition.create(forward: forward, forward_dep: forward_dep, forward_arr: forward_arr, reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(true, indemn) end # CAS ANNULATION CRISE SANITAIRE test "2 should return false when there is a problem because of covid" do reason = 'Annulation' excuse = "Crise sanitaire" dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) alert_date = "Entre 7 et 14 jours avant le vol" forward = true forward_dep = DateTime.new(2020, 8, 20, 5, 0, 0) forward_arr = DateTime.new(2020, 8, 20, 11, 0, 0) depo = Deposition.create(excuse: excuse, forward: forward, forward_dep: forward_dep, forward_arr: forward_arr, reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, alert_date: alert_date) indemn = depo.indemn? assert_equal(false, indemn) end # CAS RETARD SANS REACHEMINEMENT # 1. retard de moins de 3h a l'arrivee test 'should return false when the reason is late and the delay is less than 3 hours after the arrival.' do reason = 'Retard' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) delay = "Moins de 3h" depo = Deposition.create(reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, delay: delay) indemn = depo.indemn? assert_equal(false, indemn) end # 2. retard de plus de 3h a l'arrivee test 'should return true when the reason is late and the delay is more than 3 hours after the arrival.' do reason = 'Retard' dep_city = "Paris" arr_city = "Berlin" departure = DateTime.new(2020, 8, 20, 8, 0, 0) arrival = DateTime.new(2020, 8, 20, 10, 0, 0) delay = "3h ou plus" depo = Deposition.create(reason: reason, departure: departure, arrival: arrival, dep_city: dep_city, arr_city: arr_city, delay: delay) indemn = depo.indemn? assert_equal(true, indemn) end end
# Copyright:: # License:: # Description:: # Usage:: class Storage < ActiveRecord::Base belongs_to :user belongs_to :deployment belongs_to :cloud belongs_to :storage_type has_many :data_chunks include ModelMixins::PatternMixin include ModelMixins::DataLinkMixin validates :user_id, :cloud_id, :storage_type_id, :deployment_id, :name, :presence => true validates :storage_size_monthly_baseline, :read_request_monthly_baseline, :write_request_monthly_baseline, :numericality => { :greater_than_or_equal_to => 0 } validates :quantity_monthly_baseline, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0 } attr_accessible :name, :description, :storage_size_monthly_baseline, :read_request_monthly_baseline, :write_request_monthly_baseline, :quantity_monthly_baseline after_initialize :set_defaults def deep_clone(options={}) Storage.transaction do new_storage = self.dup(:include => [:pattern_maps], :use_dictionary => true) new_storage.name = options[:name] || "Copy of #{new_storage.name}" new_storage.save!(:validate => false) new_storage end end def display_class "Storage" end private def set_defaults if new_record? self.storage_size_monthly_baseline ||= 0 self.read_request_monthly_baseline ||= 0 self.write_request_monthly_baseline ||= 0 self.quantity_monthly_baseline ||= 1 end end end
class NodeWrapper CLASS_NODES = %i(module class) attr_reader :node, :nesting def initialize(node, nesting) @node = node @nesting = nesting end def parent nesting.last(2).first end def global_scope? nesting.size <= 2 end def current_namespace_node(deep_level = 1) nesting.reverse.select { |x| x.type == :class || x.type == :module }.first(deep_level).last end def current_namespace_name this_class_name(current_namespace_node) end # will work only if node is class def this_class_name(this_node = node) klass_konst, _, _ = *this_node source_for(klass_konst) end def this_class_parent_name (node.type == :class && node.to_a[1]) ? source_for(node.to_a[1]) : nil end def node_value node.loc.expression.source.sub(/\A::/, '') end def class_definition? %i[class module const].include?(parent.type) end private def source_for(node) node.loc.expression.source end end
class Mark < ActiveRecord::Base belongs_to :user belongs_to :educational_program has_many :groups, through: :user has_one :profile, through: :user validates :user_id, :educational_program_id, :subject, :value, presence: true validates :value, numericality: { integer_only: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5 } private def self.import(file) spreadsheet = open_spreadsheet(file) header = spreadsheet.row(1) students = load_users(['students', 'graduates']) common_columns = 6 (2..spreadsheet.last_row).to_a.in_groups_of(100, false) do |group| ActiveRecord::Base.transaction do group.each do |i| row = Hash[[header, spreadsheet.row(i)].transpose] if row.select{|k, v| v != nil}.length > common_columns unless row['Имя пользователя'] logins = student_login(row) student = nil logins.each do |login| student ||= students.find_by_login(login) end else login = row['Имя пользователя'] student = students.find_by_login(login) end if student educational_program_id = row['Направление (специальность)'] common_columns.times do row.shift end row.select{|k, v| v != nil}.each do |subject, value| mark = student.marks.find_by_subject(subject) || student.marks.new mark.educational_program_id = educational_program_id mark.subject = subject mark.value = value mark.save end end end end end end end def self.load_users(group) User.includes(:profile).joins(:groups).where(groups: {name: group}).select(:id, :login) end def self.student_login(row) educational_program = EducationalProgram.find(row['Направление (специальность)']) if educational_program case educational_program.name when 'Лечебное дело' ["inter#{row['Зачетная книга']}", "lech#{row['Зачетная книга']}", "l#{row['Зачетная книга']}"] when 'Педиатрия' ["ped#{row['Зачетная книга']}", "p#{row['Зачетная книга']}"] when 'Стоматология' ["stomat#{row['Зачетная книга']}", "s#{row['Зачетная книга']}"] else [] end end end def self.open_spreadsheet(file) case File.extname(file.original_filename) when ".ods" then Roo::Openoffice.new(file.path) when ".csv" then Roo::CSV.new(file.path) when ".xls" then Roo::Excel.new(file.path) when ".xlsx" then Roo::Excelx.new(file.path) else raise "Unknown file type: #{file.original_filename}" end end end
class MyCar attr_accessor :color attr_reader :year def initialize(year, color, model) @year = year @color = color @model = model @speed = 0 @ignition = "off" end def change_speed(spd) if @ignition == "on" if spd > @speed puts "Your car sped up from #{@speed} to #{spd} mph." elsif spd < @speed puts "Your car slowed down from #{@speed} to #{spd} mph." else puts "Your car is already traveling #{@speed} mph." end @speed = spd else puts "Turn on the car first." end end def start_car() if @ignition == "off" @ignition = "on" puts "You started your car." else puts "Your car is already running." end end def shut_off() if @speed > 0 puts "You should probably stop first." elsif @speed == 0 && @ignition == 'on' @ignition = 'off' puts "You shut off your car." else puts "Your car is already off." end end def info puts "Your #{year} #{color} #{@model} is traveling #{@speed} mph." end def spray_paint(new_color) old_color = self.color self.color = new_color puts "Your #{old_color} #{@model} was spray painted #{color}." end end ft_car = MyCar.new("2007", "White", "Rav4") ft_car.shut_off ft_car.start_car ft_car.change_speed(35) ft_car.change_speed(50) ft_car.change_speed(25) ft_car.change_speed(25) ft_car.info ft_car.shut_off ft_car.change_speed(0) ft_car.shut_off puts ft_car.color puts ft_car.year ft_car.spray_paint("Black") ft_car.start_car ft_car.change_speed(65) ft_car.info ft_car.change_speed(0) ft_car.shut_off ft_car.info
class ContactMailer < ActionMailer::Base default from: "bassanly.exe@gmail.com" def contact_form(sender, recipient, message) @user = sender @message = message if @message.size > 4000 @message = @message[0..4000] + " \n #{I18n.t('message_truncated')}" end mail(to: recipient.email, subject: "#{I18n.t('contact_request')}: #{@user.username}") end end
# Requiring this file causes Test::Unit failures to be printed in a format which # disables the failing tests by monkey-patching the failing test method to a nop # # Note that this will only detect deterministic test failures. Sporadic # non-deterministic test failures will have to be tracked separately require 'test/unit/ui/console/testrunner' require 'stringio' def test_method_name(fault) match = / (test.*) # method name \( (.+) # testcase class name (in parenthesis) \) /x.match(fault.test_name) if match and match.size == 3 method_name, class_name = match[1], match[2] if !(class_name =~ /^[\w:]+$/) and defined? ActiveSupport::Testing::Declarative # class_name might be a descriptive string specified with ActiveSupport::Testing::Declarative.describe ObjectSpace.each_object(Class) do |klass| if klass.respond_to? :name if klass.name == class_name class_name = klass.to_s break end end end end [method_name, class_name] else warn "Could not parse test name : #{fault.test_name}" [fault.test_name, "Could not parse test name"] end end # Some tests have both a failure and an error def ensure_single_fault_per_method_name(faults) method_names = [] faults.reject! do |f| method_name = test_method_name(f)[0] if method_names.include? method_name true else method_names << method_name false end end end class TagGenerator class << self attr :test_file, true # Name of the file with UnitTestSetup and disabled tags attr :initial_tag_generation, true end def self.write_tags(new_tags) existing_content = nil File.open(TagGenerator.test_file) do |file| existing_content = file.read end method_name = TagGenerator.initial_tag_generation ? "disable_tests" : "disable_unstable_tests" pos = /(def #{method_name}(\(\))?)\n/ =~ existing_content exit "Please add a placeholder for #{method_name}()" if not pos pos = pos + $1.size File.open(TagGenerator.test_file, "w+") do |file| file.write existing_content[0..pos] file.write new_tags.string file.write existing_content[pos..-1] puts "Added #{new_tags.size} tags to #{TagGenerator.test_file}" end rescue puts puts "Could not write tags..." puts new_tags.string end def self.finished(faults, elapsed_time) return if faults.size == 0 if TagGenerator.test_file new_tags = StringIO.new("", "a+") TagGenerator.output_tags faults, new_tags TagGenerator.write_tags new_tags else TagGenerator.output_tags faults, $stdout end end def self.output_tags(faults, output) output.puts() faults_by_testcase_class = {} faults.each_with_index do |fault, index| testcase_class = test_method_name(fault)[1] faults_by_testcase_class[testcase_class] = [] if not faults_by_testcase_class.has_key? testcase_class faults_by_testcase_class[testcase_class] << fault end faults_by_testcase_class.each_key do |testcase_class| testcase_faults = faults_by_testcase_class[testcase_class] ensure_single_fault_per_method_name testcase_faults output.puts " disable #{testcase_class}, " testcase_faults.each do |fault| method_name = test_method_name(fault)[0] commented_message = fault.message[0..400] if fault.respond_to? :exception backtrace = fault.exception.backtrace[0..2].join("\n") # Sometimes backtrace is an Array of size 1, where the first and only # element is the string for the full backtrace backtrace = backtrace[0..1000] commented_message += "\n" + backtrace end commented_message = commented_message.gsub(/^(.*)$/, ' # \1') output.puts commented_message if fault == testcase_faults.last comma_separator = "" else comma_separator = "," end if method_name =~ /^[[:alnum:]_]+[?!]?$/ method_name = ":" + method_name.to_s else method_name = "#{method_name.dump}" end output.puts " #{method_name}#{comma_separator}" end output.puts() end end end class Test::Unit::UI::Console::TestRunner def finished(elapsed_time) TagGenerator.finished(@faults, elapsed_time) nl output(@result, result_color) end end if $0 == __FILE__ # Dummy examples for testing if RUBY_VERSION == "1.8.7" or RUBY_VERSION =~ /1.9/ require 'rubygems' gem 'test-unit', "= 2.0.5" gem 'activesupport', "= 3.0.pre" require 'active_support' require 'active_support/test_case' class TestCaseWithDescription < ActiveSupport::TestCase describe "Hello there @%$" def test_1() assert(false) end end end class ExampleTest < Test::Unit::TestCase def teardown() if @teardown_error @teardown_error = false raise "error during teardown" end end def raise_exception() raise "hi\nthere\n\nyou" end def test_1!() assert(false) end def test_2?() raise_exception end def test_3() assert(true) end def test_4() @teardown_error = true; assert(false) end define_method("test_\"'?:-@2") { assert(false) } end end
# frozen_string_literal: true require_relative 'core/cli_options' module CMSScanner module Controller # Core Controller class Core < Base def setup_cache return unless NS::ParsedCli.cache_dir storage_path = File.join(NS::ParsedCli.cache_dir, Digest::MD5.hexdigest(target.url)) Typhoeus::Config.cache = Cache::Typhoeus.new(storage_path) Typhoeus::Config.cache.clean if NS::ParsedCli.clear_cache end def before_scan maybe_output_banner_help_and_version setup_cache check_target_availability end def maybe_output_banner_help_and_version output('banner') if NS::ParsedCli.banner output('help', help: option_parser.simple_help, simple: true) if NS::ParsedCli.help output('help', help: option_parser.full_help, simple: false) if NS::ParsedCli.hh output('version') if NS::ParsedCli.version exit(NS::ExitCode::OK) if NS::ParsedCli.help || NS::ParsedCli.hh || NS::ParsedCli.version end # Checks that the target is accessible, raises related errors otherwise # # @return [ Void ] def check_target_availability res = NS::Browser.get(target.url) case res.code when 0 raise Error::TargetDown, res when 401 raise Error::HTTPAuthRequired when 403 raise Error::AccessForbidden, NS::ParsedCli.random_user_agent unless NS::ParsedCli.force when 407 raise Error::ProxyAuthRequired end # Checks for redirects # An out of scope redirect will raise an Error::HTTPRedirect effective_url = target.homepage_res.effective_url return if target.in_scope?(effective_url) raise Error::HTTPRedirect, effective_url unless NS::ParsedCli.ignore_main_redirect target.homepage_res = res end def run @start_time = Time.now @start_memory = NS.start_memory output('started', url: target.url, ip: target.ip, effective_url: target.homepage_url) end def after_scan @stop_time = Time.now @elapsed = @stop_time - @start_time @used_memory = GetProcessMem.new.bytes - @start_memory output('finished', cached_requests: NS.cached_requests, requests_done: NS.total_requests, data_sent: NS.total_data_sent, data_received: NS.total_data_received) end end end end
# frozen_string_literal: true module CopyToClipboardHelper def copy_to_clipboard_button string_to_copy, label = nil tag.span label || string_to_copy, data: { copy_to_clipboard: string_to_copy }, class: "btn-tiny btn-nodanger btn-copy-to-clipboard" end end
module JRuby::Lint class Collector attr_accessor :checkers, :findings, :project, :contents, :file def initialize(project = nil, file = nil) @checkers = Checker.loaded_checkers.map(&:new) @checkers.each {|c| c.collector = self } @findings = [] @project, @file = project, file || '<inline-script>' end class CheckersVisitor < AST::Visitor attr_reader :checkers def initialize(ast, checkers) super(ast) @checkers = checkers end def visit(method, node) after_hooks = [] checkers.each do |ch| begin if ch.respond_to?(method) res = ch.send(method, node) after_hooks << res if res.respond_to?(:call) end rescue => e ch.collector.findings << Finding.new("Exception while traversing: #{e.message}", [:internal, :debug], node.position) end end super ensure begin after_hooks.each {|h| h.call } rescue end end end def run begin CheckersVisitor.new(ast, checkers).traverse rescue SyntaxError => e file, line, message = e.message.split(/:\s*/, 3) findings << Finding.new(message, [:syntax, :error], file, line) end end def ast @ast ||= JRuby.parse(contents, file, true) end def contents @contents || File.read(@file) end def self.inherited(base) self.all << base end def self.all @collectors ||= [] end end module Collectors end end require 'jruby/lint/collectors/ruby' require 'jruby/lint/collectors/bundler' require 'jruby/lint/collectors/rake' require 'jruby/lint/collectors/gemspec'
require 'google/api_client' class YoutubeVideoFetcher DEVELOPER_KEY = ENV['YOUTUBE_API_KEY'] YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' def self.get_service client = Google::APIClient.new( :key => DEVELOPER_KEY, :authorization => nil, :application_name => $PROGRAM_NAME, :application_version => '1.0.0' ) youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION) return client, youtube end def self.search_youtube(band_name, results, duration) client, youtube = get_service begin videos = [] # Call the search.list method to retrieve results matching the specified # query term. search_response = client.execute!( :api_method => youtube.search.list, :parameters => { :part => 'snippet', :q => band_name, :maxResults => results, :type => 'video', :videoDuration => duration } ) search_response.data.items.each do |search_result| videos.push(search_result.id.videoId) end return videos rescue Google::APIClient::TransmissionError => e puts e.result.body end end def self.fetch(band_name) videos = [] videos.push(search_youtube(band_name, 4, 'short')).flatten! videos.push(search_youtube(band_name, 6, 'medium')).flatten! return videos end end
class FormatHistoric < FormatVintage def format_pretty_name "Historic" end def in_format?(card) card.printings.each do |printing| next if @time and printing.release_date > @time # These are currently no excluded sets return true if printing.arena? end false end end
class WidgetsController < ApplicationController before_action :set_widget, only: [:show, :edit, :update, :destroy] # GET /widgets # GET /widgets.json def index @widgets = Widget.all_descendants end # GET /widgets/1 # GET /widgets/1.json def show end # GET /widgets/new def new @widget = Widget.new(widget_params) end # GET /widgets/1/edit def edit end # POST /widgets # POST /widgets.json def create @widget = Widget.new(widget_params) @widget.user_id = current_user.id @widget.save respond_to do |format| if @widget.save format.html { redirect_to dashboard_path, notice: 'Widget was successfully created.' } format.json { render :show, status: :created, location: @widget } format.js { render :layout => false } else format.html { redirect_to widgets_path} format.json { render json: @widget.errors, status: :unprocessable_entity } format.js { render :layout => false } end end end # PATCH/PUT /widgets/1 # PATCH/PUT /widgets/1.json def update respond_to do |format| if widget_params.has_key? 'query_id' @widget.query = Query.find(widget_params['query_id']) variables = params['widget']['variables'] unless variables.nil? variables = params['widget']['variables'].deep_symbolize_keys end display_variables = params['widget']['display_variables'] unless display_variables.nil? display_variables = params['widget']['display_variables'].deep_symbolize_keys display_variables[:providers] = formatted_providers(display_variables[:providers]) display_variables[:kpis] = display_variables[:kpis] end @widget.variables = variables @widget.display_variables = display_variables @widget.save end if @widget.update(widget_params.except('query_id', 'user', 'variables', 'display_variables')) email = params['widget']['user'] if not email.empty? user = User.find_by(email: email) copy = @widget.dup copy.user = user copy.save end format.html { render nothing: true, notice: 'Widget was successfully updated.' } format.json { render :show, status: :ok, location: @widget } else format.html { render :edit } format.json { render json: @widget.errors, status: :unprocessable_entity } end end end # DELETE /widgets/1 # DELETE /widgets/1.json def destroy @widget.destroy respond_to do |format| format.html { redirect_to dashboard_path , notice: 'Widget was successfully destroyed.' } format.json { head :no_content } end end def get_new_variables query_id = params[:id] if Query.find(query_id).complete_queries.empty? variables_array = Query.find(query_id).variables variables = variables_array.map { |var| [var,nil] }.to_h else variables = Query.find(query_id).complete_queries.order(last_executed: :desc).first.get_required_variables end respond_to do |format| format.html { render partial: 'widgets/variables', locals: {new_variables: variables} } format.json { render json: variables } end end private def formatted_providers(providers) if providers.tr(" \n\t", "") == "*" Provider.all_providers(@widget.brand) else providers.chomp(", ") end end # Use callbacks to share common setup or constraints between actions. def set_widget @widget = Widget.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def widget_params params.require(:widget).permit(:name, :row, :column, :width, :height, :type, :query_id, {variables: [:start_time, :end_time, :providers, :brand_id]}, {display_variables: [kpis: []]}) end end
require_relative "./tax_rate" class Orderline class OrderlineArgumentError < StandardError; end attr_reader :line, :tax def initialize(line = []) raise OrderlineArgumentError if line.size < 3 @line = line @tax = TaxRate.new(product_name, price).apply end def quantity line[0].to_i end def product_name line[1] end def price line[2].to_f.round(2) * quantity end def total_price (tax + price).round(2) end end
class Transaction attr_reader :date, :balance_change, :new_balance def initialize(date, balance_change, initial_balance) @date = date @balance_change = balance_change @new_balance = initial_balance + balance_change end end
class Post < ApplicationRecord belongs_to :user belongs_to :location belongs_to :day has_many :post_comments end
class Dialog STATES = %w(start new finish address point_name point_description point_location point_type point_options) attr_reader :id attr_accessor :state attr_reader :answers def initialize chat_id, json @id = chat_id @state = json.nil? ? STATES[0] : json.state @answers = json.nil? ? {} : json.answers end def add_answer state, answer @answers[state.to_sym] = answer end def clear @state = 'address' @answers = {} end def next_state @state = STATES[STATES.index(@state)+1] end def to_json { id: @id, state: @state, answers: @answers }.to_json end end
module DataMapper module Associations module OneToOne #:nodoc: class Relationship < Associations::Relationship %w[ public protected private ].map do |visibility| superclass.send("#{visibility}_instance_methods", false).each do |method| undef_method method unless method.to_s == 'initialize' end end # Loads (if necessary) and returns association target # for given source # # @api semipublic def get(source, other_query = nil) assert_kind_of 'source', source, source_model return unless loaded?(source) || source_key.get(source).all? relationship.get(source, other_query).first end # Sets and returns association target # for given source # # @api semipublic def set(source, target) assert_kind_of 'source', source, source_model assert_kind_of 'target', target, target_model, Hash, NilClass relationship.set(source, [ target ].compact).first end # TODO: document # @api public def kind_of?(klass) super || relationship.kind_of?(klass) end # TODO: document # @api public def instance_of?(klass) super || relationship.instance_of?(klass) end # TODO: document # @api public def respond_to?(method, include_private = false) super || relationship.respond_to?(method, include_private) end private attr_reader :relationship # Initializes the relationship. Always assumes target model class is # a camel cased association name. # # @api semipublic def initialize(name, target_model, source_model, options = {}) klass = options.key?(:through) ? ManyToMany::Relationship : OneToMany::Relationship target_model ||= Extlib::Inflection.camelize(name).freeze @relationship = klass.new(name, target_model, source_model, options) end # TODO: document # @api private def method_missing(method, *args, &block) relationship.send(method, *args, &block) end end # class Relationship end # module HasOne end # module Associations end # module DataMapper
require 'util/miq-xml' class ScanProfilesBase def self.get_class(type, from) k = from.instance_variable_get("@scan_#{type}_class") return k unless k.nil? k = "#{from.name.underscore.split('_')[0..-2].join('_').camelize}#{type.camelize}" require "metadata/ScanProfile/#{k}" from.instance_variable_set("@scan_#{type}_class", Object.const_get(k)) end def self.scan_item_class; get_class('item', self); end def self.scan_profile_class; get_class('profile', self); end def self.scan_profiles_class; self; end include Enumerable attr_accessor :profiles def initialize(dataHash, options = {}) @params = dataHash @options = options @xml_class = @options[:xml_class] || XmlHash::Document @profiles = @params.nil? ? [] : @params.collect { |p| self.class.scan_profile_class.new(p, @options) } end def each profiles.each { |p| yield p } end def each_scan_definition(type = nil, &blk) profiles.each { |p| p.each_scan_definition(type, &blk) } end def each_scan_item(type = nil, &blk) profiles.each { |p| p.each_scan_item(type, &blk) } end def parse_data(obj, data, &blk) each_scan_item { |si| si.parse_data(obj, data, &blk) } end def to_xml xml = @xml_class.createDoc("<scan_profiles/>") each { |p| xml.root << p.to_xml } xml end def to_hash {:scan_profiles => collect(&:to_hash)} end def to_yaml YAML.dump(to_hash) end end
module HomeHelper def fetch_featured_manufacturers @featured_manufacturers = Manufacturer.featured.logo_present.order(:name).limit(60).to_a end def fetch_featured_boats limit = 12 country = Country.find_by(iso: session[:country]) @featured_boats = Boat.featured.active.country_or_all(country).order('RAND()').limit(limit) .includes(:manufacturer, :currency, :primary_image, :model, :vat_rate, :country, user: [:comment_request]).to_a limit -= @featured_boats.size if limit > 0 other_boats = Boat.featured.active.limit(limit).order('RAND()') .includes(:manufacturer, :currency, :primary_image, :model, :vat_rate, :country, user: [:comment_request]) if session[:country] == 'US' other_boats = other_boats.where.not(country: country) else euro_country_ids = Country.european_country_ids.select { |x| x != country&.id } other_boats = other_boats.where(country_id: euro_country_ids) end @featured_boats.concat(other_boats.to_a) end @featured_boats, @featured_boats_slider = @featured_boats.partition.with_index { |_boat, i| i < 6 } end def fetch_newest_boats @newest_boats = Boat.active.order('id DESC').limit(15).includes(:currency, :manufacturer, :model, :country) end def fetch_recent_viewed_boats boat_ids = nil if current_user boat_ids = current_user.user_activities.where(kind: 'boat_view') .order('id DESC').group(:boat_id).limit(3).pluck(:boat_id) if boat_ids.empty? && cookies[:recently_viewed_boat_ids] boat_ids = Boat.where(id: cookies.delete(:recently_viewed_boat_ids).split(',')).limit(3).pluck(:id) boat_ids.each { |boat_id| UserActivity.create_boat_visit(boat_id: boat_id, user: current_user) } end elsif cookies[:recently_viewed_boat_ids] boat_ids = cookies[:recently_viewed_boat_ids].split(',') end if boat_ids&.any? @recent_boats = Boat.active.where(id: boat_ids) .includes(:currency, :manufacturer, :model, :country, :primary_image).to_a end end end
require 'rest-client' class CandidateBidRequestStub def self.callback(candidate_id) api = RestClient::Resource.new "http://local:3000/api" attrs = { candidate: { bid: bid } } raw_json = api["candidates/#{candidate_id}"].put attrs.to_json, accept: "application/json", content_type: "application/json" end def self.bid 100.0 end end
require 'rails_helper' RSpec.describe CandidaturesController, type: :controller do let(:volunteer) { create(:volunteer) } let(:gig) { create(:gig) } let(:valid_attributes) { { gig_id: gig.id, volunteer_id: volunteer.id, introduction_letter: 'Im here to help the dogs', accepted: false } } let(:invalid_attributes) { { gig_id: nil, volunteer_id: nil, introduction_letter: "" } } let(:valid_session) { {} } describe "GET #index" do it "returns a success response" do candidature = Candidature.create! valid_attributes get :index, params: {gig_id: gig.id}, session: valid_session expect(response).to be_success end end describe "GET #show" do it "returns a success response" do candidature = Candidature.create! valid_attributes get :show, params: {gig_id: gig.id, id: candidature.to_param}, session: valid_session expect(response).to be_success end end describe "GET #new" do it "returns a success response" do get :new, params: {gig_id: gig.id}, session: valid_session expect(response).to be_success end end describe "GET #edit" do it "returns a success response" do candidature = Candidature.create! valid_attributes get :edit, params: {gig_id: gig.id, id: candidature.to_param}, session: valid_session expect(response).to be_success end end describe "POST #create" do context "with valid params" do it "creates a new Candidature" do expect { post :create, params: {gig_id: gig.id, candidature: valid_attributes}, session: valid_session }.to change(Candidature, :count).by(1) end it "redirects to the created candidature" do post :create, params: {gig_id: gig.id, candidature: valid_attributes}, session: valid_session expect(response).to redirect_to(Candidature.last) end end context "with invalid params" do it "returns a success response (i.e. to display the 'new' template)" do post :create, params: {gig_id: gig.id, candidature: invalid_attributes}, session: valid_session expect(response).to be_success end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { { introduction_letter: "Im also wanna help the cats" } } it "updates the requested candidature" do candidature = Candidature.create! valid_attributes put :update, params: {gig_id: gig.id, id: candidature.to_param, candidature: new_attributes}, session: valid_session candidature.reload expect(candidature.introduction_letter).to eq(new_attributes[:introduction_letter]) end it "redirects to the candidature" do candidature = Candidature.create! valid_attributes put :update, params: {gig_id: gig.id, id: candidature.to_param, candidature: valid_attributes}, session: valid_session expect(response).to redirect_to(candidature) end end context "with invalid params" do it "returns a success response (i.e. to display the 'edit' template)" do candidature = Candidature.create! valid_attributes put :update, params: {gig_id: gig.id, id: candidature.to_param, candidature: invalid_attributes}, session: valid_session expect(response).to be_success end end end describe "DELETE #destroy" do it "destroys the requested candidature" do candidature = Candidature.create! valid_attributes expect { delete :destroy, params: {gig_id: gig.id, id: candidature.to_param}, session: valid_session }.to change(Candidature, :count).by(-1) end it "redirects to the candidatures list" do candidature = Candidature.create! valid_attributes delete :destroy, params: {gig_id: gig.id, id: candidature.to_param}, session: valid_session expect(response).to redirect_to(candidatures_url) end end end
# Configure Rails Environment ENV['RAILS_ENV'] = 'test' require 'rubygems' require 'bundler' Bundler.setup(:default, :test) # Require simplecov before loading ..dummy/config/environment.rb because it will cause metasploit_data_models/lib to # be loaded, which would result in Coverage not recording hits for any of the files. require 'simplecov' require 'coveralls' SimpleCov.formatter = Coveralls::SimpleCov::Formatter require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'rspec/rails' require 'rspec/autorun' # full backtrace in logs so its easier to trace errors Rails.backtrace_cleaner.remove_silencers! spec_pathname = Metasploit::Model::Engine.root.join('spec') Dir[spec_pathname.join('support', '**', '*.rb')].each do |f| require f end RSpec.configure do |config| config.before(:suite) do # this must be explicitly set here because it should always be spec/tmp for w/e project is using # Metasploit::Model::Spec to handle file system clean up. Metasploit::Model::Spec.temporary_pathname = spec_pathname.join('tmp') # Clean up any left over files from a previously aborted suite Metasploit::Model::Spec.remove_temporary_pathname # catch missing translations I18n.exception_handler = Metasploit::Model::Spec::I18nExceptionHandler.new end config.after(:each) do Metasploit::Model::Spec.remove_temporary_pathname end config.mock_with :rspec config.order = :random end
class Step400Proc < ActiveRecord::Migration def up connection.execute(%q{ CREATE OR REPLACE FUNCTION public.proc_step_400(process_representative integer, experience_period_lower_date date, experience_period_upper_date date, current_payroll_period_lower_date date, current_payroll_period_upper_date date ) RETURNS void AS $BODY$ DECLARE run_date timestamp := LOCALTIMESTAMP; BEGIN -- STEP 4 -- Manual Class 4 Year Rollups -- Create table that adds up 4 year payroll for each unique policy number and manual class combination, -- Calculates expected losses for each manual class by joining bwc_codes_base_rates_exp_loss_rates table -- Adds industry_group to manual class by joining bwc_codes_ncci_manual_classes INSERT INTO final_manual_class_four_year_payroll_and_exp_losses ( representative_number, policy_number, manual_number, manual_class_type, data_source, created_at, updated_at ) ( SELECT a.representative_number, a.policy_number, b.manual_number, b.manual_class_type, 'bwc' as data_source, run_date as created_at, run_date as updated_at FROM public.final_employer_demographics_informations a Inner Join public.process_payroll_all_transactions_breakdown_by_manual_classes b ON a.policy_number = b.policy_number WHERE b.reporting_period_start_date >= experience_period_lower_date and a.representative_number = process_representative GROUP BY a.representative_number, a.policy_number, b.manual_number, b.manual_class_type ); -- Broke manual_class payroll calculations into two tables. -- One to calculate payroll and manual_reclass payroll when a.reporting_period_start_date > edi.policy_creation_date because a payroll is only counted in your experience when you have a policy_created. -- One to calculate the payroll of transferred payroll from another policy. This does not require a policy to be created. UPDATE public.final_manual_class_four_year_payroll_and_exp_losses a SET (manual_class_expected_loss_rate, manual_class_base_rate, manual_class_industry_group, updated_at) = (t2.manual_class_expected_loss_rate, t2.manual_class_base_rate, t2.manual_class_industry_group, t2.updated_at) FROM ( SELECT a.representative_number, a.policy_number, a.manual_number, a.manual_class_type, b.expected_loss_rate as manual_class_expected_loss_rate, b.base_rate as manual_class_base_rate, c.industry_group as "manual_class_industry_group", run_date as updated_at FROM public.final_manual_class_four_year_payroll_and_exp_losses a LEFT JOIN public.bwc_codes_base_rates_exp_loss_rates b ON a.manual_number = b.class_code LEFT JOIN public.bwc_codes_ncci_manual_classes c ON a.manual_number = c.ncci_manual_classification Left Join public.final_employer_demographics_informations edi ON a.policy_number = edi.policy_number ) t2 WHERE a.policy_number = t2.policy_number and a.manual_number = t2.manual_number and a.manual_class_type = t2.manual_class_type and a.representative_number = t2.representative_number and (a.representative_number is not null) and a.representative_number = process_representative; -- 7/5/2016 __ CREATED NEW PEO TABLE called process_policy_experience_period_peo. -- This will calculate which policies were involved with a state fund or self insurred peo. -- It finds the most recent date of the effective_date for si peo or sf peo and documents it -- Then it finds the most recent termintation date for si peo or sf peo and documents it. -- If a policy is involved with a peo within the experience period, you will eventually reject that policy from getting quoted for group rating. -- Insert all policy_numbers and manual_numbers that are associated with a PEO LEASE INSERT INTO public.process_policy_experience_period_peos ( representative_number, policy_type, policy_number, data_source, created_at, updated_at ) ( SELECT DISTINCT representative_number, predecessor_policy_type as policy_type, predecessor_policy_number as policy_number, 'bwc' as data_source, run_date as created_at, run_date as updated_at FROM public.process_policy_combine_partial_to_full_leases where representative_number = process_representative ); -- Self Insured PEO LEASE INTO UPDATE public.process_policy_experience_period_peos mce SET (manual_class_si_peo_lease_effective_date, updated_at) = (t2.manual_class_si_peo_lease_effective_date, t2.updated_at) FROM (SELECT pcl.representative_number, pcl.predecessor_policy_number as policy_number, max(pcl.transfer_effective_date) as manual_class_si_peo_lease_effective_date, run_date as updated_at FROM public.process_policy_combine_partial_to_full_leases pcl -- Self Insured PEO WHERE pcl.successor_policy_type = 'private_self_insured' and pcl.successor_policy_number in (SELECT peo.policy_number FROM bwc_codes_peo_lists peo) and pcl.representative_number = process_representative GROUP BY pcl.representative_number, pcl.predecessor_policy_number ) t2 WHERE mce.policy_number = t2.policy_number and mce.representative_number = t2.representative_number and (mce.representative_number is not null); -- -- -- Self Insured PEO LEASE OUT -- UPDATE public.process_policy_experience_period_peos mce SET (manual_class_si_peo_lease_termination_date, updated_at) = (t2.manual_class_si_peo_lease_termination_date, t2.updated_at) FROM ( SELECT pct.representative_number, pct.successor_policy_number as policy_number, max(pct.transfer_effective_date) as manual_class_si_peo_lease_termination_date, run_date as updated_at FROM public.process_policy_combination_lease_terminations pct WHERE pct.predecessor_policy_number in (SELECT peo.policy_number FROM bwc_codes_peo_lists peo) and pct.predecessor_policy_type = 'private_self_insured' and pct.representative_number = process_representative GROUP BY pct.representative_number, pct.successor_policy_number ) t2 WHERE mce.policy_number = t2.policy_number and mce.representative_number = t2.representative_number and (mce.representative_number is not null); -- -- -- State Fund PEO LEASE INTO -- UPDATE public.process_policy_experience_period_peos mce SET (manual_class_sf_peo_lease_effective_date, updated_at) = (t2.manual_class_sf_peo_lease_effective_date, t2.updated_at) FROM (SELECT pcl.representative_number, pcl.predecessor_policy_number as policy_number, max(pcl.transfer_effective_date) as manual_class_sf_peo_lease_effective_date, run_date as updated_at FROM public.process_policy_combine_partial_to_full_leases pcl -- Self Insured PEO WHERE pcl.successor_policy_type != 'private_self_insured' and pcl.successor_policy_number in (SELECT peo.policy_number FROM bwc_codes_peo_lists peo) and pcl.representative_number = process_representative GROUP BY pcl.representative_number, pcl.predecessor_policy_number ) t2 WHERE mce.policy_number = t2.policy_number and mce.representative_number = t2.representative_number and (mce.representative_number is not null); -- -- -- Self Insured PEO LEASE OUT -- UPDATE public.process_policy_experience_period_peos mce SET (manual_class_sf_peo_lease_termination_date, updated_at) = (t2.manual_class_sf_peo_lease_termination_date, t2.updated_at) FROM ( SELECT pct.representative_number, pct.successor_policy_number as policy_number, max(pct.transfer_effective_date) as manual_class_sf_peo_lease_termination_date, run_date as updated_at FROM public.process_policy_combination_lease_terminations pct WHERE pct.predecessor_policy_number in (SELECT peo.policy_number FROM bwc_codes_peo_lists peo) and pct.predecessor_policy_type != 'private_self_insured'and pct.representative_number = process_representative GROUP BY pct.representative_number, pct.successor_policy_number ) t2 WHERE mce.policy_number = t2.policy_number and mce.representative_number = t2.representative_number and (mce.representative_number is not null); DELETE FROM process_policy_experience_period_peos WHERE id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (partition BY representative_number, policy_type, policy_number, manual_class_sf_peo_lease_effective_date, manual_class_sf_peo_lease_termination_date, manual_class_si_peo_lease_effective_date, manual_class_si_peo_lease_termination_date) AS rnum FROM process_policy_experience_period_peos) t WHERE t.rnum > 1); end; $BODY$ LANGUAGE plpgsql; }) end def down connection.execute(%q{ DROP FUNCTION public.proc_step_400(integer, date, date, date, date); }) end end
class Primer def initialize(target) @target = target end def prime count = 1 position = 1 until count == @target position += 2 if is_prime?(position) count += 1 end end position end def is_prime?(number) (2..Math.sqrt(number)).each do |divisor| break if number == 2 return false if number % divisor == 0 || number < 2 end true end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end Rails.application.routes.draw do concern :api_base do resources :leaders resources :states do resources :leaders do collection do get 'us_senate' get 'us_house' get 'state_senate' get 'state_house' end end end end namespace :v1 do concerns :api_base end end
require 'rails_helper' describe Card do let(:cardset) { create(:cardset) } let(:card) { cardset.cards.build(question: "Question", answer: "Answer") } subject { card } it { should respond_to(:question) } it { should respond_to(:answer) } it { should respond_to(:cardset_id) } it { should respond_to(:cardset) } describe "without cardset_id" do before { card.cardset_id = nil } it { should_not be_valid } end describe "without question" do before { card.question = " " } it { should_not be_valid } end describe "without answer" do before { card.answer = " " } it { should_not be_valid } end describe "card methods" do before do @user_1 = cardset.create_author!(name: 'name', email: 'user_1@examle.com', password: 'password', password_confirmation: 'password') @user_2 = create(:user, email: 'user_2@example.com') @cards = (1..3).to_a.map do |num| cardset.cards.create!(question: "question #{num}", answer: "answer #{num}") end @level_1 = @cards.first.levels.create!(user: @user_1, status: 1, sort_order: 0) @level_2 = @cards.second.levels.create!(user: @user_1, status: 0, sort_order: 1) end it ".level_for_user(user_1) should return the level of the card" do expect(@cards.first.level_for_user(@user_1)).to eq(@level_1) end it ".with_levels_for(user_1) should return cards with levels" do expect(cardset.cards.with_levels_for(@user_1.id).count).to eq(3) end it ".with_levels_for(user_2) should also return the same cards" do expect(cardset.cards.with_levels_for(@user_2.id).count).to eq(3) end it ".with_levels_for(user_1).with_status(1) should return one card" do expect(cardset.cards.with_levels_for(@user_1.id).with_status(1).count).to eq(1) end it ".with_levels_for(user_2).with_status(1) should return no card" do expect(cardset.cards.with_levels_for(@user_2.id).with_status(1).count).to eq(0) end it ".with_levels_for(user_2).with_status(0) should return three cards" do expect(cardset.cards.with_levels_for(@user_2.id).with_status(0).count).to eq(3) end it ".with_levels_for(user_1) should return the correct order" do ordered_ids = cardset.cards.with_levels_for(@user_1.id).map(&:id) expect(ordered_ids).to eq([@cards[2].id, @cards[1].id, @cards[0].id]) end it ".with_levels_for(user_2) should return the correct order" do ordered_ids = cardset.cards.with_levels_for(@user_2.id).map(&:id) expect(ordered_ids).to eq([@cards[0].id, @cards[1].id, @cards[2].id]) end it ".with_levels_for(user_1).group_by_level should return correct groups" do ordered_hash = cardset.cards.with_levels_for(@user_1.id).group_by_level(@user_1) expect(ordered_hash).to eq({ 0 => [@cards[2], @cards[1]], 1 => [@cards[0]] }) end it ".with_levels_for(user_2).group_by_level should return correct groups" do cards = cardset.cards.with_levels_for(@user_2.id) expect(cards.group_by_level(@user_2)).to eq({ 0 => [@cards[0], @cards[1], @cards[2]] }) end it "when 2 users learn a cardset both should be saved in levels" do @cards.first.levels.create!(user: @user_2, status: 1, sort_order: 2) @cards.second.levels.create!(user: @user_2, status: 0, sort_order: 0) @cards.third.levels.create!(user: @user_2, status: 1, sort_order: 1) cards = cardset.cards.with_levels_for(@user_2.id) expect(cards.group_by_level(@user_2)).to eq({ 0 => [@cards[1]], 1 => [@cards[2], @cards[0]] }) end end describe "destroy" do before do @card_2 = cardset.cards.create(id: 1, question: "Q1", answer: "A1") @card_2.levels.create(card_id: 1, user_id: 1, status: 1) @card_2.destroy end it "should destroy the card itself" do expect(Card.find_by_id(@card_2.id)).to be_nil end it "should destroy all associated levels, too" do expect(Level.find_by_card_id(@card_2.id)).to be_nil end end describe ".with_status(status)" do before do @card_2 = cardset.cards.create(id: 2, question: "Q1", answer: "A1") @card_2.levels.create(card_id: 2, user_id: 1, status: 2) @card_3 = cardset.cards.create(id: 3, question: "Q1", answer: "A1") @card_3.levels.create(card_id: 3, user_id: 1, status: 2) end it "should return all cards with the requested status" do expect(cardset.cards.with_status(2)).to include(@card_2, @card_3) end it "should not return cards with another status" do expect(cardset.cards.with_status(3)).not_to include(@card_2, @card_3) end end end
#! /bin/env ruby require 'getoptlong' infiles=Hash.new para_list=nil inter=Hash.new pairs=Hash.new out_prefix=nil infiles['nega']="/home/sswang/project/dimer/data/DRYGIN/negative_interactions.list" infiles['posi']="/home/sswang/project/dimer/data/DRYGIN/positive_interactions.list" #################################################### def read_interaction_file(file) hash=Hash.new fh=File.open(file, 'r') while(line=fh.gets) do line.chomp! lines=line.split("\t") gene1,gene2 = lines[0].split("|") gene1=$1 if gene1=~/(.+)_/ gene2=$1 if gene2=~/(.+)_/ [gene1, gene2].each do |i| hash[i]=Hash.new if hash[gene1].nil? end hash[gene1][gene2]=1 end return(hash) end def get_pairs(file) hash=Hash.new fh=File.open(file, 'r') while(line=fh.gets) do line.chomp! hash[line]=1 end return hash end #################################################### opts=GetoptLong.new( ['--nega',GetoptLong::REQUIRED_ARGUMENT], ['--posi',GetoptLong::REQUIRED_ARGUMENT], ['--para_list',GetoptLong::REQUIRED_ARGUMENT], ['--out_prefix',GetoptLong::REQUIRED_ARGUMENT], ) opts.each do |opt,value| case opt when '--nega' infiles['nega']=value when '--posi' infiles['posi']=value when '--para_list' para_list=value when '--out_prefix' out_prefix=value end end #################################################### pairs = get_pairs(para_list) infiles.each_pair do |type, file| inter[type]=Hash.new inter[type]=read_interaction_file file end inter.each_key do |type| $stdout.reopen(out_prefix+'_'+type, 'w') if out_prefix pairs.each_key do |key| genes=Array.new genes=key.split("\t") if (! inter[type][genes[0]].nil?) and (! inter[type][genes[1]].nil?) then overlap_array = inter[type][genes[0]].keys & inter[type][genes[1]].keys overlap = overlap_array.size shared_proportion=2*overlap.to_f/(inter[type][genes[0]].keys.size+inter[type][genes[1]].keys.size) #print overlap, "\t", inter[type][genes[0]].keys.size+inter[type][genes[1]].keys.size next if shared_proportion == 0 puts shared_proportion end end end
class Movie < Media validates_presence_of :imdb_id validates_uniqueness_of :imdb_id def year release_date && release_date.split('-').first end def self.search(title, year = nil) self.where('title LIKE ?', title).first end def self.search_imdb(title, year = nil) result = ImdbService.search(title, year).first result && ImdbService.fetch(result[:imdb_id]) end def self.create_from_imdb(result) record = self.where(imdb_id: result.imdb_id).first_or_initialize if record.new_record? record.title = result.title record.image = result.poster_url record.rating = result.rating record.description = result.plot record.runtime = result.runtime record.release_date = result.release_date record.save! end record end def self.create_from_video_file(vf) record = self.search(vf.title, vf.year) unless record result = self.search_imdb(vf.title, vf.year) record = result && self.create_from_imdb(result) end if record record.video_files << vf end record end def self.populate VideoFile.unmatched.matchable.movies.each do |vf| if self.create_from_video_file(vf) puts "Matched: #{vf}" else puts "No match for: #{vf}" end end end end
json.array!(@petclubs) do |petclub| json.extract! petclub, :id, :name, :description json.url petclub_url(petclub, format: :json) end
Rails.application.routes.draw do resources :users, only: [:new,:create,:show] resources :rewards, only: [:index, :show] get '/login', to: "sessions#new" post '/login', to: "sessions#create" delete '/logout', to: 'sessions#destroy' resources :rewards_users, only: [:new, :create] namespace :admin do resources :rewards resources :users end end
class CreatePriceTables < ActiveRecord::Migration def change create_table :price_tables do |t| t.string :name t.integer :days t.integer :day1 t.integer :day2 t.integer :day3 t.integer :night t.integer :dinner end end end
# -*- coding: utf-8 -*- module Mushikago module Tombo # キャプチャリクエスト class CaptureRequest < Mushikago::Http::PostRequest def path; '/1/tombo/capture' end request_parameter :url request_parameter :image_format request_parameter :image_quality do |v| v.to_i.to_s end request_parameter :thumbnail do |v| (v ? 1 : 0).to_s end request_parameter :tags do |v| [v].flatten.compact.join(',') end request_parameter :user_agent request_parameter :delay_time do |v| v.to_i.to_s end request_parameter :display_width do |v| v.to_i.to_s end # @param [String] url キャプチャ対象のURL # @param [Hash] options リクエストのオプション # @option options [String] :image_format('jpg') 画像のフォーマット(jpg,png) # @option options [Integer] :image_quality(80) 画像の品質(0-100) # @option options [Boolean] :thumbnail(0) サムネイル取得フラグ(false:取得しない,true:取得する) # @option options [String,Array] :tags タグ # @option options [String] :user_agent ユーザエージェント # @option options [Integer] :delay_time キャプチャまでの待ち時間 # @option options [Integer] :display_width 仮想ブラウザの幅 def initialize url, options={} super(options) self.url = url self.image_format = options[:image_format] if options.has_key?(:image_format) self.image_quality = options[:image_quality] if options.has_key?(:image_quality) self.thumbnail = options[:thumbnail] if options.has_key?(:thumbnail) self.tags = options[:tags] if options.has_key?(:tags) self.user_agent = options[:user_agent] if options.has_key?(:user_agent) self.delay_time = options[:delay_time] if options.has_key?(:delay_time) self.display_width = options[:display_width] if options.has_key?(:display_width) @headers['Content-type'] = 'application/x-www-form-urlencoded; charset=utf-8' end end end end
Given /^(?:that\s)?Product Moderation is (enabled|disabled)$/ do |state| App.product_moderation[:enabled] = (state == 'true') end Given /^I have (?:a\s)?product (.*) created (\d+) days ago$/ do |product_name, days_ago| @product = Factory :product, :title => product_name.gsub(/^"|"$/, ''), :created_at => (Time.now - days_ago.to_i.day) , :stat => Factory(:product_stat) end Given /^a top level category of "([^\"]*)"$/ do |category_name| new_category = Factory :category, :name => category_name new_category.broader_thans << Category.find_by_name("__root__") end Given /^I have a product "([^\"]*)" in category "([^\"]*)"$/ do |product_name, category_name| @product = Factory :product, :title => product_name, :stat => Factory(:product_stat) category = Category.find_by_name(category_name) @product.category = category @product.save end Given /^that the product moderation queue is(\snot)? configured for ([^\"]*) mappings$/ do |is_not, source| App.product_moderation[:mapped_columns] = is_not.nil? ? [source] : nil end Then /^I should(\snot)? see a column heading for ([^\"]*)$/ do |should_not, text| (response.body =~ %r[<th>#{text}</th>]m) == !should_not.blank? end Then /^I should(\snot)? see the text "([^\"]*)"$/ do |should_not, text| (response.body =~ /#{text}/m).nil? == !should_not.blank? end Then /^I should be redirected to (.+?)$/ do |path| assert request.headers['HTTP_REFERER'] != nil assert request.headers['HTTP_REFERER'] != request.request_uri Then "I should be on #{path}" end When /^(?:|I )fill in "([^\"]*)" with the literal expression "(.*)"$/ do |field, value| fill_in(field, :with => value) end When /^I flag the product as being primary$/ do # Just ensure that we're actually doing this over XHR to better emulate # how the actual application would work. xhr "post", "/admin/products/update/#{@product.id}", {:product => {:primary_for_merge => true}} end Then /^the product should be flagged as primary/ do @product.reload assert @product.primary_for_merge == true end
module TextToNoise class LogReader attr_reader :io def initialize( io, mapper ) @io, @mapper = io, mapper end def call() while line = io.gets @mapper.dispatch line TextToNoise.throttle! end end end end
require 'rails_helper' RSpec.describe Player, type: :model do it { expect(subject).to have_db_column(:full_name) } it { expect(subject).to have_many(:sports) } end
class CreateCampaigns < ActiveRecord::Migration def change create_table :campaigns do |t| t.string :campaign_id, :limit => 8 t.string :campaign_name, :limit => 40 t.string :campaign_description t.column :active, "ENUM('Y','N')" t.datetime :campaign_changedate t.datetime :campaign_logindate t.string :user_group, :limit => 20 t.timestamps end end end
class AdminController < ApplicationController # Error Codes SUCCESS = 1 FIRST_NOT_VALID = 101 LAST_NOT_VALID = 102 EMAIL_NOT_VALID = 103 PASS_NOT_VALID = 104 PASS_NOT_MATCH = 109 DOB_NOT_VALID = 105 ADDRESS_NOT_VALID = 110 CITY_NOT_VALID = 111 ZIP_NOT_VALID = 106 CONTACT_ONE_NOT_VALID = 112 CONTACT_ONE_PRIMARY_NOT_VALID = 113 CONTACT_ONE_SECONDARY_NOT_VALID = 113 CONTACT_TWO_NOT_VALID = 114 CONTACT_TWO_PRIMARY_NOT_VALID = 115 CONTACT_TWO_SECONDARY_NOT_VALID = 116 GENDER_NOT_VALID = 120 SKILL_NOT_VALID = 118 EXTRA_NOT_VALID = 119 USER_EXISTS = 107 BAD_CREDENTIALS = 108 NOT_ADMIN = 121 DEFAULT = 999 def amIAdmin respond_to do |format| if not cookies.has_key?(:remember_token) format.json { render json: { errCode: NOT_ADMIN } } else user = User.find_by_remember_token(cookies[:remember_token]) if user if not user.type == "Admin" format.json { render json: { errCode: NOT_ADMIN } } end else format.json { render json: { errCode: NOT_ADMIN } } end end end end def init Admin.create(first: "first", last: "last", email: "admin@admin.org", password: "password", password_confirmation: "password", dob: "11/22/1234", zip: "12345", address: "123 a st.", city: "admin town", contact_one: "mom", contact_one_primary: "(111) 222-3333", contact_one_secondary: "(111) 222-3333", contact_two: "dad", contact_two_primary: "(111) 222-3333", contact_two_secondary: "(111) 222-3333", skill: "advanced", gender: "other", access_code: 0, extra: "", zip: "12345") redirect_to "/" return end def addInstructor respond_to do |format| if cookies.has_key?(:remember_token) user = User.find_by_remember_token(cookies[:remember_token]) else format.json { render json: { errCode: NOT_ADMIN } } end if user.type == "Admin" user = Instructor.new(first: params[:first], last: params[:last], dob: params[:dob], address: params[:residence][:address], city: params[:residence][:city], zip: params[:residence][:zip], contact_one: params[:contacts][:first][:name], contact_one_primary: params[:contacts][:first][:primary], contact_one_secondary: params[:contacts][:first][:secondary], contact_two: "nobody", contact_two_primary: "(000) 000-0000", contact_two_secondary: "(000) 000-0000", email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation], gender: "other", skill: "advanced", extra: "", access_code: 0) if user.save format.json { render json: { errCode: SUCCESS } } else if user.errors.messages[:first] format.json { render json: { errCode: FIRST_NOT_VALID } } elsif user.errors.messages[:last] format.json { render json: { errCode: LAST_NOT_VALID } } elsif user.errors.messages[:email] if not user.errors.messages[:email].grep(/taken/).empty? format.json { render json: { errCode: USER_EXISTS } } elsif not user.errors.messages[:email].grep(/invalid/).empty? format.json { render json: { errCode: EMAIL_NOT_VALID } } end elsif user.errors.messages[:password] if not user.errors.messages[:password].grep(/(blank)|(short)/).empty? format.json { render json: { errCode: PASS_NOT_VALID } } elsif not user.errors.messages[:password].grep(/match/).empty? format.json { render json: { errCode: PASS_NOT_MATCH } } else format.json { render json: { errCode: "Error in password" } } end elsif user.errors.messages[:dob] format.json { render json: { errCode: DOB_NOT_VALID } } elsif user.errors.messages[:address] format.json { render json: { errCode: ADDRESS_NOT_VALID } } elsif user.errors.messages[:city] format.json { render json: { errCode: CITY_NOT_VALID } } elsif user.errors.messages[:zip] format.json { render json: { errCode: ZIP_NOT_VALID } } elsif user.errors.messages[:contact_one] format.json { render json: { errCode: CONTACT_ONE_NOT_VALID } } elsif user.errors.messages[:contact_one_primary] format.json { render json: { errCode: CONTACT_ONE_PRIMARY_NOT_VALID } } elsif user.errors.messages[:contact_one_secondary] format.json { render json: { errCode: CONTACT_ONE_SECONDARY_NOT_VALID } } else format.json { render json: { errCode: DEFAULT } } end end else format.json { render json: { errCode: NOT_ADMIN } } end end end def delete respond_to do |format| if cookies.has_key?(:remember_token) user = User.find_by_remember_token(cookies[:remember_token]) else format.json { render json: { errCode: NOT_ADMIN } } end if user.type == "Admin" user_to_delete = User.find_by_id(params[:id]) if user_to_delete format.json { render json: { errCode: SUCCESS } } user_to_delete.delete else format.json { render json: { errCode: BAD_CREDENTIALS } } end else format.json { render json: { errCode: NOT_ADMIN } } end end end def exportUsers if cookies.has_key?(:remember_token) user = User.find_by_remember_token(cookies[:remember_token]) if user.type == "Admin" users = User.order(:type) database = users.to_csv send_data database, filename: "user_database", type: "text/csv" end end end def exportSections if cookies.has_key?(:remember_token) user = User.find_by_remember_token(cookies[:remember_token]) if user.type == "Admin" sections = Section.order(:start_date) database = sections.to_csv send_data database, filename: "section_database", type: "text/csv" end end end def allUsers respond_to do |format| if cookies.has_key?(:remember_token) format.json { render json: { errCode: SUCCESS, users: User.all } } else format.json { render json: { errCode: NOT_ADMIN } } end end end end
class Admissions::ResourceSuggestionsController < Admissions::AdmissionsController before_filter :set_resource_suggestion, only: [:edit, :update, :confirm_destroy, :destroy] load_resource find_by: :permalink authorize_resource def index respond_to do |format| format.html { order = params[:order] @type_id = params[:type_id] dir = (params[:dir].blank? || params[:dir] == "asc") ? "asc" : "desc" @resource_suggestions = ResourceSuggestion.paginate(page: params[:page], per_page: @per_page) unless @type_id.blank? @resource_suggestions = @resource_suggestions.where(type_id: @type_id) end unless order.blank? @resource_suggestions = @resource_suggestions.order("#{order} #{dir}") else @resource_suggestions = @resource_suggestions.ordered end } format.csv { send_data ResourceSuggestion.to_csv(request.host_with_port), type: 'text/csv; charset=iso-8859-1; header=present', disposition: "attachment; filename=resource_suggestions-#{DateTime.now}.csv" } end end def edit end def update if @resource_suggestion.update_attributes(params[:resource_suggestion]) redirect_to admin_resource_suggestions_path, notice: resource_suggestion_flash(@resource_suggestion).html_safe else render :edit end end def confirm_destroy end def destroy @resource_suggestion.destroy redirect_to admin_resource_suggestions_path, notice: "Successfully destroyed #{@resource_suggestion.title}." end private def set_resource_suggestion @resource_suggestion = ResourceSuggestion.find_by_id!(params[:id]) end def resource_suggestion_flash(resource_suggestion) render_to_string partial: "flash", locals: { resource_suggestion: resource_suggestion } end end
class CreateActivites < ActiveRecord::Migration def change create_table :activites do |t| t.string :titre t.text :description t.string :typeactivite t.string :prix t.string :adresse t.date :datedebut t.date :datefin t.timestamps end end end
# -*- mode: ruby -*- # vi: set ft=ruby : BOX_NAME = "debian-wheezy-64" BOX_URI = "http://basebox.libera.cc/debian-wheezy-64.box" VBOX_VERSION = "4.3.8" VAGRANTFILE_API_VERSION = "2" DOMAIN = "cluster.local" HOSTS = [ { :host => "node1-debian", :ip => "192.168.42.11"}, { :host => "node2-debian", :ip => "192.168.42.12"}, { :host => "node3-debian", :ip => "192.168.42.13"} ] LAST_HOSTNAME=HOSTS[-1][:host] Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.landrush.enable config.landrush.tld = DOMAIN HOSTS.each do | h | config.vm.define h[:host] do |machine| machine.vm.box = BOX_NAME machine.vm.box_url = BOX_URI machine.vm.hostname = "%s.%s" % [h[:host], config.landrush.tld] machine.vm.network :private_network, ip: h[:ip] machine.vm.provider "virtualbox" do |vb| vb.name = machine.vm.hostname vb.memory = 2048 vb.cpus = 1 vb.customize ['modifyvm', :id, '--ioapic', 'on', '--cpuexecutioncap', '50'] end if h[:host] == LAST_HOSTNAME machine.vm.provision :ansible do |ansible| ansible.playbook = "site.yml" ansible.sudo = true ansible.inventory_path = "./devel/inventory" ansible.limit = 'all' end end end end end
class CashRegister attr_accessor :total , :discount, :items, :last_transaction def initialize(discount = 0) @items = [] @total = 0 @discount = discount end def total return @total end def add_item(item,price,num = 1) value = price * num @total += value num.times do @items << item end @last_transaction = price * num end def apply_discount if @discount > 0 @discount = @discount/100.to_f @total = @total - (@total * @discount) "After the discount, the total comes to $#{@total.to_i}." else "There is no discount to apply." end end def void_last_transaction @total = @total - @last_transaction end end
json.jobs do |json| json.array!(@jobs) do |job| # Main Elements json.id job.id json.company job.company json.position job.position json.location job.location json.salary job.salary json.status job.status # Secondary Elements json.contact job.contact json.email job.email json.template job.template json.notes job.notes end end
FactoryGirl.define do factory :resume_table_medium do row { Faker::Number.between(1, 10) } sequence(:sequence) artist_medium nil resume_table nil end end
class PagesController < ApplicationController def index @page = Page.find_by(slug: params[:page]) end end
class AddToTables < ActiveRecord::Migration def change add_column :messages, :receiver, :text add_column :comments, :commentable_name, :text end end
require 'rubygems' require 'net/http' require 'nokogiri' require 'schema' require 'user' require 'twitt' require 'user_follower' require 'follower' require 'timeout' class Spider attr_accessor :base_url, :visited, :queue, :root_username, :limit def initialize(root_username,limit) @base_url = "http://www.twitter.com" @visited = [] @queue = [Follower.new(nil,root_username)] @root_username = root_username @limit = limit end def self.visit(url) response = visit_without_redirecting(url) response_body = response.body doc = Nokogiri::HTML(response_body) if response.code.to_s =~ /301|302/ redirect_url = doc.xpath('//a').first.get_attribute('href') response_body = visit_without_redirecting(redirect_url).body end response_body end def self.visit_without_redirecting(url) Net::HTTP.get_response(URI.parse(url)) end def scan_twitter(level=1) sleep(3) return if queue.empty? or (limit > 0 and level > limit) follower = queue.shift p username = follower.follower_nick url = "#{base_url}/#{username}" doc = Spider.get_doc(url) name = doc.xpath('//span[@class="fn"]').text location = doc.xpath('//span[@class="adr"]').text if user = User.find(:nick => username) user.update(:name => name, :location => location) else user = User.create(:nick => username, :name => name, :location => location) end if visited_user = User.find(:nick => follower.user_nick) and not UserFollower.find(:user_id => visited_user.id, :follower_id => user.id) UserFollower.create(:user_id => visited_user.id, :follower_id => user.id) end visited << username get_twitts(user,doc) @queue += get_followers(username,doc) scan_twitter(level+1) end def self.get_doc(url) body = nil while (body == nil) begin body = Spider.visit(url) rescue Timeout::Error puts "Connection reset. Waiting..." sleep(5*60) rescue Errno::ECONNRESET puts "Connection reset. Waiting..." sleep(2*60) rescue puts "Unknown exception. Waiting..." sleep(5*60) end end Nokogiri::HTML(body) end def get_twitts(user,doc) doc.xpath('//li[regex(.,"class","status")]', RegexpComparator.new).each do |li| id,body,date,parent_id,parent_url,parent_username = get_twitt(li) parent_result = false if parent_id parent_result = get_parent_twitt(parent_username,Spider.get_doc(parent_url)) end unless parent_result parent_id = nil end if Twitt.find(:id => id) == nil Twitt.create(:id => id, :parent_id => parent_id, :date => date, :body => body, :user_id => user.id) end end end def get_parent_twitt(username,doc) result = false doc.xpath('//div[regex(.,"id","status")]', RegexpComparator.new).each do |div| id,body,date,parent_id,parent_url,parent_username = get_twitt(div) parent_result = false if parent_id parent_result = get_parent_twitt(parent_username,Spider.get_doc(parent_url)) end unless user = User.find(:nick => username) user = User.create(:nick => username, :name => nil, :location => nil) end unless parent_result parent_id = nil end if Twitt.find(:id => id) == nil Twitt.create(:id => id, :parent_id => parent_id, :date => date, :body => body, :user_id => user.id) end result = true end result end def get_twitt(div) id = div.get_attribute("id").match(/\d+/).to_s body = div.children.xpath('./span[@class="entry-content"]').text meta = div.children.xpath('./span[@class="meta entry-meta"]') date = DateTime.parse(meta.children.xpath('./span[@class="published timestamp"]').first.get_attribute("data").match(/'.*'/).to_s.delete("'")) parent_id = nil parent_url = nil parent_username = nil meta.xpath('./a').each do |a| parent_url = a.get_attribute("href") splitted = parent_url.split("/") parent_id = splitted.last if a.text.to_s =~ /reply/ parent_username = splitted[-3] end [id,body,date,parent_id,parent_url,parent_username] end def get_followers(username,doc) followers = [] doc.xpath('//a[@rel="contact"]').each do |user| follower_nick = user.get_attribute('href')[1..-1] followers << Follower.new(username,follower_nick) end followers.each do |follower| followers.delete(follower) if visited.include?(follower) or queue.include?(follower) end followers end end class RegexpComparator def regex node_set, attribute, pattern node_set.find_all { |node| node[attribute] =~ /#{pattern}/ } end end #Spider.new("Dziamka",-1).scan_twitter()
class SyncAttributesOfContactInfos < ActiveRecord::Migration[5.0] def change add_column :contact_infos, :web, :string add_column :contact_infos, :facebook, :string end end
# -*- coding: utf-8 -*- require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings gem.name = "monkeyshines" gem.authors = ["Philip (flip) Kromer"] gem.email = "flip@infochimps.org" gem.homepage = "http://github.com/mrflip/monkeyshines" gem.summary = %Q{A simple scraper for directed scrapes of APIs, feed or structured HTML.} gem.description = %Q{A simple scraper for directed scrapes of APIs, feed or structured HTML. Plays nicely with wuclan and wukong.} gem.executables = FileList['bin/*.rb'].pathmap('%f') gem.files = FileList["\w*", "**/*.textile", "examples/*", "{app,bin,docpages,examples,lib,spec,utils}/**/*"].reject{|file| file.to_s =~ %r{.*private.*} } gem.add_dependency 'addressable' gem.add_dependency 'uuid' gem.add_dependency 'wukong' end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec begin require 'reek/rake_task' Reek::RakeTask.new do |t| t.fail_on_error = true t.verbose = false t.source_files = ['lib/**/*.rb', 'examples/**/*.rb', 'utils/**/*.rb'] end rescue LoadError task :reek do abort "Reek is not available. In order to run reek, you must: sudo gem install reek" end end begin require 'roodi' require 'roodi_task' RoodiTask.new do |t| t.verbose = false end rescue LoadError task :roodi do abort "Roodi is not available. In order to run roodi, you must: sudo gem install roodi" end end begin require 'yard' YARD::Rake::YardocTask.new do |yard| end rescue LoadError task :yardoc do abort "YARD is not available. In order to run yardoc, you must: sudo gem install yard" end end require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| require 'rdoc' if File.exist?('VERSION') version = File.read('VERSION') else version = "" end rdoc.options += [ '-SHN', '-f', 'darkfish', # use darkfish rdoc styler ] rdoc.rdoc_dir = 'rdoc' rdoc.title = "monkeyshines #{version}" # File.open(File.dirname(__FILE__)+'/.document').each{|line| rdoc.rdoc_files.include(line.chomp) } end begin require 'cucumber/rake/task' Cucumber::Rake::Task.new(:features) rescue LoadError task :features do abort "Cucumber is not available. In order to run features, you must: sudo gem install cucumber" end end
class AddRedirectUrlToKuhsaftPages < ActiveRecord::Migration def change I18n.available_locales.each do |locale| add_column :kuhsaft_pages, "redirect_url_#{locale.to_s.underscore}", :text end end end
require 'spec_helper' require 'aws/templates/utils' describe Aws::Templates::Help::Rdoc::Parametrized::Constraints::DependsOnValue do let(:parametrized) do Module.new do include Aws::Templates::Utils::Parametrized parameter :field parameter :depends_on_value_requires_field, constraint: depends_on_value(a: requires(:field)) end end let(:help) { Aws::Templates::Help::Rdoc.show(parametrized) } it 'prints documentation' do expect(help).to match( /depends_on_value_requires_field.*depends.*when[^\n]+a.*requires.*field/m ) end end
class Product < ActiveRecord::Base validates :name, :description, :price, presence: true validates :name, length: { maximum: 50 } validates :description, length: { maximum: 150 } end
module Awesome module Definitions module Filters def self.included(base) base.extend ClassMethods base.cattr_accessor :search_filters base.cattr_accessor :verbose_filters end module ClassMethods def search_filters_enabled self.search_filter_keys(false) end def get_class_for_filter(filter) self.get_class(self.search_filters[:search_filters_to_classes][filter]) end def search_filter_keys(symring = true) self.search_filters[:search_filters_to_filter_modifiers].map {|k,v| symring ? k : self.unmake_symring(k)} end def search_filter_modifiers(symring = true) # Needs to be flattened because the values are arrays self.search_filters[:search_filters_to_filter_modifiers].map {|k,v| symring ? v : self.unmake_symring(v)}.flatten end # filter param is an array of filters def valid_filter_modifiers(anytext, filter) # Weed out invalid filter requests puts "checking valid_filter_modifiers: #{anytext}, filter: #{filter.inspect}" if self.verbose_filters # We do not make_symring for two reasons: # 1. people will use whatever kind of filter value they need, and ruby can compare it. # 2. the filter param is an array # #filter = self.make_symring(filter) # Weed out invalid filter requests allowed = (self.search_filter_keys & filter) return false if !filter.empty? && allowed.empty? valid_filter_mods = self.get_filter_modifiers(anytext, allowed) valid_search_filters = valid_filter_mods.map do |fmod| puts "filter mod #{fmod.inspect} => #{self.search_filters[:filter_modifiers_to_search_filters][fmod]}" if self.verbose_filters self.search_filters[:filter_modifiers_to_search_filters][fmod] end.compact puts "valid_filter_modifiers: #{valid_search_filters.inspect}" if self.verbose_filters return valid_search_filters end def get_filter_modifiers(anytext, filter = nil) mods = anytext.scan(self.search_filter_modifiers_regex(false)).flatten.compact #If no filter mods are in the search string then the filter requested is valid so we pretend it was requested as a modifier mods = !filter.blank? && mods.empty? ? [self.make_symring(filter)] : mods #mods = (self.search_filter_modifiers & mods) | filter puts "get_filter_modifiers #{mods.reject {|x| x == ''}.inspect}" if self.verbose_filters mods.reject {|x| x == ''} end def get_search_filter_from_modifier(mod) self.search_filters[:filter_modifiers_to_search_filters][mod] end def search_filter_modifiers_regex(whitespace = false) self.modifier_regex_from_array(self.search_filter_modifiers, whitespace) end end # end of ClassMethods #INSTANCE METHODS end end end
class Api::V1::UsersController < ApplicationController before_action :authorized, only: [:update] def create user = User.new(user_params) if user.save token = encode_token(user_id: user.id) render json: {user: UserSerializer.new(user), jwt: token }, include: "*.*.*", status: :created else render json: {errors: user.errors.full_messages}, status: :not_acceptable end end def update @user.assign_attributes(user_params) if @user.save render json: @user, include: "*.*.*", status: :created else render json: {errors: @user.errors.full_messages} end end def show render json: User.find(params[:id]), include: "*.*.*" end private def user_params params.permit(:email, :password, :name) end end
class UsersFilter def initialize(type, id = nil) @type = type @id = id end def ids send @type, @id end private def all(*_) User.without_state(:closed).map(&:id) end def from_cluster(id) User.without_state(:closed).map do |u| if u.all_projects.any? { |p| p.requests.where(cluster_id: id).with_state(:active).any? } u.id end end.compact end def from_project(id) Project.find(id).accounts.with_access_state(:allowed).map do |account| account.user_id end.uniq end def from_organization(id) Organization.find(id).memberships.with_state(:active).map(&:user_id).uniq end def from_organization_kind(id) OrganizationKind.find(id).organizations.with_state(:active).map do |organization| organization.memberships.with_state(:active).map(&:user_id) end.flatten.uniq end def with_projects(*_) User.without_state(:closed).map do |u| if u.all_projects.with_state(:active).any? u.id end end.compact end def with_accounts(*_) User.without_state(:closed).map do |u| if u.accounts.with_access_state(:allowed).any? { |a| a.project.requests.with_state(:active).any? } u.id end end.compact end def with_refused_accounts(*_) User.without_state(:closed).each do |u| if u.all_projects.with_state(:active).any? { |p| p.requests.with_state(:blocked).any? } u.id end end.compact end def from_session(id) session = Session.find(id) User.without_state(:closed).map do |u| has_fault_with_session = proc do |s| u.faults.where(kind: "survey", reference_id: u.user_surveys.where(survey_id: session.survey_ids).pluck(:id)).with_state(:actual).any? || u.faults.with_state(:actual).where(kind: "report", reference_id: u.reports.where(session_id: session.id)).any? end if u.faults.with_state(:actual).any? && has_fault_with_session.call u.id end end.compact end def unsuccessful_of_current_session(*_) if session = Session.current User.without_state(:closed).map do |u| has_unsubmitted_surveys = proc { u.user_surveys.where(survey_id: session.survey_ids).without_state(:submitted).any? } has_unassessed_reports = proc { Report.where(session_id: session.id, project_id: u.owned_project_ids).without_state(:assessed).any? } has_failed_reports = proc { Report.where(session_id: session.id, project_id: u.owned_project_ids).with_state(:assessed).where("illustration_points < 3 or summary_points < 3 or statement_points < 3").any? } if has_unsubmitted_surveys.call || has_unassessed_reports.call || has_failed_reports.call u.id end end.compact end end end
# $LICENSE # Copyright 2013-2014 Spotify AB. All rights reserved. # # The contents of this file are 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_relative '../logging' module FFWD::Statistics # Example SMAP #(mapping header) #Size: 4 kB #Rss: 0 kB #Pss: 0 kB #Shared_Clean: 0 kB #Shared_Dirty: 0 kB #Private_Clean: 0 kB #Private_Dirty: 0 kB #Referenced: 0 kB #Anonymous: 0 kB #AnonHugePages: 0 kB #Swap: 0 kB #KernelPageSize: 4 kB #MMUPageSize: 4 kB #Locked: 0 kB #VmFlags: rd ex class SMAP attr_reader :size attr_reader :rss attr_reader :pss attr_reader :shared_clean attr_reader :shared_dirty attr_reader :private_clean attr_reader :private_dirty attr_reader :referenced attr_reader :anonymous attr_reader :anon_huge_pages attr_reader :swap attr_reader :kernel_page_size attr_reader :mmu_page_size attr_reader :locked attr_reader :vmflags KEY_MAPPING = { "Size" => :size, "Rss" => :rss, "Pss" => :pss, "Shared_Clean" => :shared_clean, "Shared_Dirty" => :shared_dirty, "Private_Clean" => :private_clean, "Private_Dirty" => :private_dirty, "Referenced" => :referenced, "Anonymous" => :anonymous, "AnonHugePages" => :anon_huge_pages, "Swap" => :swap, "KernelPageSize" => :kernel_page_size, "MMUPageSize" => :mmu_page_size, "Locked" => :locked, "VmFlags" => :vm_flags, } TYPE_MAP = { "VmFlags" => lambda{|s| s} } DEFAULT_TYPE = lambda{|s| s[0, s.size - 3].to_i * 1024} def initialize values values.each do |key, value| unless target = KEY_MAPPING[key] raise "unexpected key: #{key}" end instance_variable_set "@#{target}", value end end end class SystemStatistics include FFWD::Logging PID_SMAPS_FILE = '/proc/self/smaps' PID_STAT_FILE = '/proc/self/stat' STAT_FILE = '/proc/stat' MEMINFO_FILE = '/proc/meminfo' def initialize opts={} @cpu_prev = nil end def collect channel cpu = cpu_use memory = memory_use cpu.each do |key, value| yield "cpu-#{key}", "%", value end memory.each do |key, value| yield "memory-#{key}", "B", value end channel << {:memory => memory} end def check if not File.file? PID_SMAPS_FILE log.error "File does not exist: #{PID_SMAPS_FILE} (is this a linux system?)" return false end if not File.file? PID_STAT_FILE log.error "File does not exist: #{PID_STAT_FILE} (is this a linux system?)" return false end if not File.file? STAT_FILE log.error "File does not exist: #{STAT_FILE} (is this a linux system?)" return false end if not File.file? MEMINFO_FILE log.error "File does not exist: #{MEMINFO_FILE} (is this a linux system?)" return false end return true end def memory_use result = {:resident => 0, :total => read_total_memory} read_smaps do |smap| result[:resident] += smap.rss end result end def cpu_use stat = read_pid_stat current = { :system => stat[:stime], :user => stat[:utime], :total => read_stat_total } prev = @cpu_prev if @cpu_prev.nil? @cpu_prev = prev = current else @cpu_prev = current end total = current[:total] - prev[:total] system = current[:system] - prev[:system] user = current[:user] - prev[:user] if total == 0 return {:user => 0, :system => 0} end {:user => (user / total).round(3), :system => (system / total).round(3)} end private def read_pid_stat File.open(PID_STAT_FILE) do |f| stat = f.readline.split(' ').map(&:strip) return {:utime => stat[13].to_i, :stime => stat[14].to_i} end end def read_stat_total File.open(STAT_FILE) do |f| f.each do |line| next unless line.start_with? "cpu " stat = line.split(' ').map(&:strip).map(&:to_i) return stat.reduce(&:+) end end end def read_total_memory File.open(MEMINFO_FILE) do |f| f.each do |line| next unless line.start_with? "MemTotal:" total = line.split(' ').map(&:strip) return total[1].to_i * 1000 end end end def read_smaps File.open(PID_SMAPS_FILE) do |f| smap = {} loop do break if f.eof? unless smap.empty? yield SMAP.new(smap) smap = {} end loop do break if f.eof? line = f.readline.strip case line when /^[0-9a-f]+-[0-9a-f]+ / break else key, value = line.split(':', 2) next unless SMAP::KEY_MAPPING[key] smap[key] = (SMAP::TYPE_MAP[key] || SMAP::DEFAULT_TYPE).call(value.strip) end end end end end def smaps_read_entry f result = {} loop do break if f.eof? line = f.readline.strip case line when /^[0-9a-f]+-[0-9a-f]+ / break else result[key] = (SMAP::TYPE_MAP[key] || SMAP::DEFAULT_TYPE).call(value.strip) end end result end end end
module OHOLFamilyTrees module CurselogCache class Servers include Enumerable def initialize(cache = "cache/publicLifeLogData/") @cache = cache end attr_reader :cache def each(&block) iter = Dir.foreach(cache) .select {|dir| dir.match("curseLog_")} .map {|dir| Logs.new(dir, cache) } if block_given? iter.each(&block) end end end class Logs include Enumerable def initialize(dir, cache = "cache/publicLifeLogData/") @dir = dir @cache = cache end attr_reader :dir attr_reader :cache def server dir.match(/curseLog_(.*)/)[1] end def each Dir.foreach(File.join(cache, dir)) do |path| dateparts = path.match(/(\d{4})_(\d{2})\w+_(\d{2})/) next unless dateparts cache_path = File.join(dir, path) yield Logfile.new(cache_path, cache) end end end class Logfile def initialize(path, cache = "cache/publicLifeLogData/") @path = path @cache = cache end attr_reader :path attr_reader :cache def file_path File.join(cache, path) end def approx_log_time dateparts = path.match(/(\d{4})_(\d{2})\w+_(\d{2})/) return date unless dateparts Time.gm(dateparts[1], dateparts[2], dateparts[3]) end def within(time_range = (Time.at(0)..Time.now)) time_range.cover?(approx_log_time) end def date File.mtime(file_path) end def server path.match(/curseLog_(.*)\//)[1] end def open File.open(file_path, "r", :external_encoding => 'ASCII-8BIT') end end end end
require 'interrotron' describe "running" do def run(s,vars={},max_ops=nil) Interrotron.run(s,vars,max_ops) end it "should exec identity correctly" do run("(identity 2)").should == 2 end describe "and" do it "should return true if all truthy" do run("(and 1 true 'ohai')").should be_true end it "should return false if not all truthy" do run("(and 1 true false)").should be_false end end describe "or" do it "should return true if all truthy" do run("(or 1 true 'ohai')").should be_true end it "should return true if some truthy" do run("(or 1 true false)").should be_true end it "should return false if all falsey" do run("(or nil false)").should be_false end end describe "evaluating a single tokens outside on sexpr" do it "simple values should return themselves" do run("28").should == 28 end it "vars should dereference" do run("true").should == true end end describe "nested expressions" do it "should execute a simple nested expr correctly" do run("(+ (* 2 2) (% 5 4))").should == 5 end it "should execute complex nested exprs correctly" do run("(if false (+ 4 -3) (- 10 (+ 2 (+ 1 1))))").should == 6 end end describe "custom vars" do it "should define custom vars" do run("my_var", "my_var" => 123).should == 123 end it "should properly execute proc custom vars" do run("(my_proc 4)", "my_proc" => proc {|a| a*2 }).should == 8 end end describe "times" do it "should parse and compare them properly" do run('(> #t{2010-09-04} start_date)', start_date: DateTime.parse('2012-12-12').to_time) end it "should understand days, minutes, seconds, and hours, as integers" do run("(+ (days 1) (minutes 1) (hours 1) (seconds 1))").should == 90061 end it "should add the time using from-now" do n = Time.now Time.should_receive(:now).twice().and_return(n) run("(from-now (minutes 1))").to_i.should == (Time.now + 60).to_i end it "should compare times using convenience multipliers correctly" do run('(> (now) (ago (hours 12)))').should be_true end end describe "cond" do it "should work for a simple case where there is a match" do run("(cond (> 1 2) (* 2 2) (< 5 10) 'ohai')").should == 'ohai' end it "should return nil when no matches available" do run("(cond (> 1 2) (* 2 2) false 'ohai')").should == nil end it "should support true as a fallthrough clause" do run("(cond (> 1 2) (* 2 2) false 'ohai' true 'backup')").should == 'backup' end end describe "intermediate compilation" do it "should support compiled scripts" do # Setup an interrotron obj with some default vals tron = Interrotron.new(:is_valid => proc {|a| a.reverse == 'oof'}) compiled = tron.compile("(is_valid my_param)") compiled.call(:my_param => 'foo').should == true compiled.call(:my_param => 'bar').should == false end end describe "higher order functions" do it "should support calculating a fn at the head" do run('((or * +) 5 5)').should == 25 end end describe "array" do it "should return a ruby array" do run("(array 1 2 3)").should == [1, 2, 3] end it "should detect max vals correctly" do run("(max (array 82 10 100 99.5))").should == 100 end it "should detect min vals correctly" do run("(min (array 82 10 100 99.5))").should == 10 end it "should let you get the head" do run("(first (array 1 2 3))").should == 1 end it "should let you get the tail" do run("(last (array 1 2 3))").should == 3 end it "should let you get the length" do run("(length (array 1 2 3 'bob'))").should == 4 end describe "checking membership" do it "should work in the false case" do run("(member? 5 (array 10 20 30))").should be_false end it "should work in the true case" do run("(member? 5 (array 10 5 30))").should be_true end end end describe "functions" do it "should have access to vars they've bound" do pending run("((fn (n) (* n 2)) 5)").should == 10 end end describe "readme examples" do it "should execute the simple custom var one" do Interrotron.run('(> 51 custom_var)', 'custom_var' => 10).should == true end end describe "op counter" do it "should not stop scripts under or at the threshold" do run("(str (+ 1 2) (+ 3 4) (+ 5 7))", {}, 5) end it "should terminate with the proper exception if over the threshold" do proc { run("(str (+ 1 2) (+ 3 4) (+ 5 7))", {}, 3) }.should raise_exception(Interrotron::OpsThresholdError) end end describe "multiple forms at the root" do it "should return the second form" do run("(+ 1 1) (+ 2 2)").should == 4 end it "should raise an exception if a number is in a fn pos" do proc { run("(1)") }.should raise_exception(Interrotron::InterroArgumentError) end end describe "empty input" do it "should return nil" do run("").should be_nil end end describe "apply macro" do it "should spat an array into another function" do run("(apply + (array 1 2 3))").should == 6 end end describe "conversions" do it "should convert ints" do res = run("(int '2')") res.should == 2 res.should be_a(Fixnum) end it "should convert floats" do res = run("(float '2.5')") res.should == 2.5 res.should be_a(Float) end it "should parse dates and times" do run("(time '2012-05-01')").should == DateTime.parse("2012-05-01").to_time end end end
class Forum < ApplicationRecord before_create :generate_permalink searchkick belongs_to :user has_many :comments, dependent: :destroy private def generate_permalink pattern=self.subject.parameterize duplicates = Forum.where('permalink like ?', "%#{pattern}%") if duplicates.present? self.permalink = "#{pattern}-#{duplicates.count+1}" else self.permalink = pattern end end end
# frozen_string_literal: true module ManageStations attr_accessor :station def create_station print 'Введите название станции: ' station = Station.new(gets.chomp) stations << station puts "Станция '#{station.name}' создана!" rescue StandardError => e puts "#{e.message}\n" end def take_a_train loop do show_accessible_stations print stations.empty? ? "Нет станций. Введите '999', чтобы выйти: " : 'Введите индекс: ' station = gets.chomp.to_i break if station == 999 show_accessible_trains print 'Введите индекс поезда: ' train = gets.chomp.to_i stations[station].trains.push(trains[train]) puts 'Поезд прибыл на станцию.' break end end def departure_train loop do result = show_selected_stations result.each_with_index { |station, index| puts "- cтанция #{station.name}, индекс - #{index}." } print result.empty? ? "Нет станций. Введите '999', чтобы выйти: " : 'Введите индекс: ' station = gets.chomp.to_i break if station == 999 result[station].trains.each_with_index do |train, index| puts "- поезд №#{train.number}, индекс: #{index}." end print 'Введите индекс поезда: ' train = gets.chomp.to_i result[station].trains.delete(result[station].trains[train]) puts 'Поезд убыл со станции.' break end end def show_all_trains show_accessible_stations print 'Выберите станцию: ' choise = gets.chomp.to_i block = ->(train) { puts "Поезд № #{train.number}, #{train.type}, вагонов: #{train.wagons.size}." } stations[choise].add_stations_to_block(block) end def show_type_trains result = show_selected_stations result.each do |station| puts "На станции #{station.name} находятся:" cargo = 0 passenger = 0 station.trains.each { |train| train.type == :cargo ? cargo += 1 : passenger += 1 } puts "Грузовых поездов: #{cargo}, пассажирских поездов: #{passenger}.\n\n" end end end
class Dish < ApplicationRecord has_many :combo_items, dependent: :restrict_with_exception end
module ItemPedia module_function CATEGORIES = { :all => "Tutti", :potion => "Oggetti", :ingredient => "Ingredienti", :other => "Altro", #:weapon = "Armi", #:armor = "Armature", } #NON RIMUOVERE LA PARENTESI V_DROP = "Drop" V_STEAL = "Da rubare" #-------------------------------------------------------------------------- # * Restituisce le categorie dei nemici # @return [Array<Item_Category>] #-------------------------------------------------------------------------- def categories categories = [] CATEGORIES.each do |item| categories.push(Item_Category.new(item[0], item[1])) end categories end end #============================================================================== # ** EnemyDrop #============================================================================== class EnemyDrop attr_accessor :enemy attr_accessor :probability #-------------------------------------------------------------------------- # * inizializzazione # @param [RPG::Enemy] enemy # @param [Object] probability #-------------------------------------------------------------------------- def initialize(enemy, probability) @enemy = enemy @probability = probability end end #============================================================================== # ** RPG::Item #============================================================================== class RPG::Item #-------------------------------------------------------------------------- # * determina se l'oggetto è listabile nella itempedia #-------------------------------------------------------------------------- def in_list? @in_list ||= initialize_in_list end #-------------------------------------------------------------------------- # * determina se l'oggetto è un ingrediente #-------------------------------------------------------------------------- def ingredient? @ingredient ||= initialize_ingredient end #-------------------------------------------------------------------------- # * determina a quale categoria appartiene # @return [Symbol] #-------------------------------------------------------------------------- def wiki_category return :potion if menu_ok? return :ingredient if ingredient? :other end #-------------------------------------------------------------------------- # * inizializza l'informazione della lista #-------------------------------------------------------------------------- def initialize_in_list self.note.split(/[\n\r]+/).each do |line| return false if line =~ /<nascondi>/i end true end #-------------------------------------------------------------------------- # * inzizializza l'informazione dell'ingrediente #-------------------------------------------------------------------------- def initialize_ingredient self.note.split(/[\n\r]+/).each do |line| return true if line =~ /<ingrediente>/i end false end end #============================================================================== # ** RPG::Weapon #============================================================================== class RPG::Weapon #-------------------------------------------------------------------------- # * restituisce la categoria #-------------------------------------------------------------------------- def category; :weapon; end end #============================================================================== # ** RPG::Armor #============================================================================== class RPG::Armor #-------------------------------------------------------------------------- # * restituisce la categoria #-------------------------------------------------------------------------- def category; :armor; end end #============================================================================== # ** Game_Party #============================================================================== class Game_Party alias wiki_i_gain_item gain_item unless $@ # restituisce l'array degli ID degli oggetti scoperti # @return [Array] def discovered_items @discovered_items ||= initial_discovered_items end # genera l'array iniziale degli ID degli oggetti scoperti def initial_discovered_items @discovered_items = @items.keys end # aggiunge un oggetto scoperto all'array (se assente) def item_discovered(item_id) @discovered_items |= [item_id] end # determina se un determinato oggetto è scoperto def item_discovered?(item_id) discovered_items.include?(item_id) end # alias del metodo gain_item def gain_item(item, n = 1, include_equip = false) wiki_i_gain_item(item, n, include_equip) if item != nil item_discovered(item.id) if item.is_a?(RPG::Item) end end end #============================================================================== # ** Scene_Itempedia #------------------------------------------------------------------------------ # la schermata dell'oggettario #============================================================================== class Scene_Itempedia < Scene_MenuBase #-------------------------------------------------------------------------- # * inizio #-------------------------------------------------------------------------- def start super create_viewport create_windows end #-------------------------------------------------------------------------- # * crea il viewport #-------------------------------------------------------------------------- def create_viewport @viewport = Viewport.new(0, 0, Graphics.width, Graphics.height) end #-------------------------------------------------------------------------- # * crea le finestre #-------------------------------------------------------------------------- def create_windows create_items_window create_category_window create_drop_window end #-------------------------------------------------------------------------- # * crea la finestra degli oggetti #-------------------------------------------------------------------------- def create_items_window @items_window = Window_Item_WikiList.new(0, 0, 200, Graphics.height) @items_window.viewport = @viewport end #-------------------------------------------------------------------------- # * crea la finestra delle categorie #-------------------------------------------------------------------------- def create_category_window @category_window = Window_ItemCategoryW.new(0, 0) @category_window.set_list(@items_window) @items_window.set_category_window(@category_window) @items_window.set_list(@category_window.item.symbol) end #-------------------------------------------------------------------------- # * Aggiornamento #-------------------------------------------------------------------------- def update super @viewport.update end #-------------------------------------------------------------------------- # * crea la finestra dei drop #-------------------------------------------------------------------------- def create_drop_window x = @items_window.width y = @items_window.y w = Graphics.width - x h = Graphics.height @drop_window = Window_DropInfo.new(x, y, w, h) @items_window.set_info_window(@drop_window) @category_window.z = 9999 @drop_window.viewport = @viewport end #-------------------------------------------------------------------------- # * Chiusura #-------------------------------------------------------------------------- def terminate super @viewport.dispose end end #============================================================================== # ** Window_Item_WikiList #------------------------------------------------------------------------------ # Mostra l'elenco dei nemici visti #============================================================================== class Window_Item_WikiList < Window_List # refresh def refresh get_items create_contents draw_items end #-------------------------------------------------------------------------- # * Ottiene gli oggetti #-------------------------------------------------------------------------- def get_data @data = [] # @param [RPG::Item] item $data_items.each do |item| next if item.nil? next if item.name.size == 0 next unless $game_party.item_discovered?(item.id) next if item.key_item next unless item.in_list? next if no_item_drops(item) if @category == :all @data.push(item) else @data.push(item) if item.wiki_category == @category end end @data.sort! { |a, b| a.name <=> b.name } end #-------------------------------------------------------------------------- # * Restituisce true se non ci sono nemici che droppano l'oggetto # item: oggetto # noinspection RubyResolve # @param [RPG::Item] item #-------------------------------------------------------------------------- def no_item_drops(item) $game_party.defeated_enemies.select { |enemy| enemy.has_item?(item) }.empty? end #-------------------------------------------------------------------------- # * Disegna l'oggetto # index: indice dell'oggetto #-------------------------------------------------------------------------- def draw_item(index) rect = item_rect(index) item = @data[index] draw_icon(item.icon_index, rect.x, rect.y) draw_text(rect.x + 24, rect.y, rect.width - 24, rect.height, item.name) end end #enemy_list #============================================================================== # ** Window_ItemCategoryW #------------------------------------------------------------------------------ # Mostra la categoria degli oggetti #============================================================================== class Window_ItemCategoryW < Window_Category include ItemPedia #-------------------------------------------------------------------------- # * Metodo astratto per i dati #-------------------------------------------------------------------------- def default_data; categories; end end #============================================================================== # ** Window_DropInfo #------------------------------------------------------------------------------ # Mostra la categoria degli oggetti #============================================================================== class Window_DropInfo < Window_DataInfo #-------------------------------------------------------------------------- # * inizializzazione # @param [Integer] x # @param [Integer] y # @param [Integer] w # @param [Integer] h # noinspection RubyResolve #-------------------------------------------------------------------------- def initialize(x, y, w, h) @enemies = $game_party.known_enemies super(x, y, w, h) @pages = [:drops, :steals] end #-------------------------------------------------------------------------- # * Disegna il contenuto delle informazioni a seconda della pagina #-------------------------------------------------------------------------- def draw_content case selected_page when :drops; draw_drops(0, contents.width) when :steals; draw_steals(0, contents.width) else #nothing end end #-------------------------------------------------------------------------- # * Ottiene il nome della pagina #-------------------------------------------------------------------------- def page_name(symbol) case symbol when :drops; return ItemPedia::V_DROP when :steals; return ItemPedia::V_STEAL else #nothing end end #-------------------------------------------------------------------------- # * disegna i drop #-------------------------------------------------------------------------- def draw_drops(x, width) droplist = get_drop_list y = line_height return if droplist.size == 0 (0..droplist.size - 1).each do |i| draw_drop(x, y + (line_height * i), width, droplist[i]) break if i >= max_lines end end #-------------------------------------------------------------------------- # * disegna dove può essere rubato #-------------------------------------------------------------------------- def draw_steals(x, width) steallist = get_steal_list y = line_height return if steallist.size == 0 (0..steallist.size - 1).each do |i| draw_drop(x, y + (line_height * i), width, steallist[i]) break if i >= max_lines end end # disegna il drop # @param [Integer] x # @param [Integer] y # @param [Integer] width # @param [EnemyDrop] drop def draw_drop(x, y, width, drop) change_color normal_color draw_bg_rect(x, y, width, line_height) draw_enemy(x, y, width, drop.enemy) draw_text(x, y, width, line_height, sprintf('%10.2f%%', drop.probability), 2) end # disegna il nemico # @param [Integer] x # @param [Integer] y # @param [Integer] width # @param [RPG::Enemy] enemy def draw_enemy(x, y, width, enemy) draw_text(x, y, width, line_height, enemy.name) end # ottiene la lista dei nemici che possono droppare l'oggetto # @return [Array<EnemyDrop>] def get_drop_list drops = [] @enemies.each { |enemy| drops.push(item_drop(enemy)) if enemy.drops_item?(item) } drops.sort { |b, a| a.probability <=> b.probability } end # restituisce la lista dei nemici a cui puoi rubare l'oggetto # @return [Array<EnemyDrop>] def get_steal_list steals = [] @enemies.each { |enemy| steals.push(item_steal(enemy)) if enemy.can_steal_item?(item) } steals.sort { |b, a| a.probability <=> b.probability } end # restituisce il drop nemico # @param [RPG::Enemy] enemy # @return [EnemyDrop] def item_drop(enemy) item_array = enemy.drop_items.select { |drop| drop.item == item } prob = item_array.inject(0) { |v, d| v + d.drop_percentage } EnemyDrop.new(enemy, prob) end # restituisce l'enemyDrop del comando ruba # @param [RPG::Enemy] enemy # @return [EnemyDrop] def item_steal(enemy) item_array = enemy.steals.select { |steal| steal.item == item } prob = item_array.inject(0) { |v, d| v + d.probability } EnemyDrop.new(enemy, prob) end # restituisce l'oggetto selezionato # @return [RPG::Item] def item; @item; end end
class Question < ActiveRecord::Base validates_presence_of :body has_many :answers has_many :users, through: :answers end
require 'rails/generators' require 'rails/generators/migration' require 'rails/generators/active_record' module Kuhsaft module Translations class Add < Rails::Generators::Base include Rails::Generators::Migration source_root(File.join(Kuhsaft::Engine.root, '/lib/templates/kuhsaft/translations')) argument :locale, type: :string def self.next_migration_number(dirname) ActiveRecord::Generators::Base.next_migration_number(dirname) end def translated_columns Kuhsaft::Page.column_names.select { |attr| attr.end_with? "_#{I18n.default_locale}" } end def formatted_locale locale.underscore end def create_locale_migration_file migration_template('add_translation.erb', Rails.root.join('db', 'migrate', "add_#{formatted_locale}_translation.rb")) end private def get_attribute(attribute_name = '') attribute_name.gsub("_#{I18n.default_locale}", "_#{formatted_locale}") end def get_type(key = '') Kuhsaft::Page.columns_hash[key].type end end end end
class FplTeams::UpdateWaiverPickOrderForm < ApplicationInteraction object :current_user, class: User object :fpl_team_list, class: FplTeamList object :fpl_team, class: FplTeam object :waiver_pick, class: WaiverPick object :round, default: -> { fpl_team_list.round } array :waiver_picks, default: -> { fpl_team_list.waiver_picks } integer :new_pick_number validate :authorised_user validate :pending_waiver_pick validate :fpl_team_list_waiver_pick validate :round_is_current validate :not_first_round validate :waiver_pick_update_occurring_in_valid_period validate :valid_pick_number validate :change_in_pick_number run_in_transaction! def execute if waiver_pick.pick_number > new_pick_number waiver_picks.where( 'pick_number >= :new_pick_number AND pick_number <= :old_pick_number', new_pick_number: new_pick_number, old_pick_number: waiver_pick.pick_number ).each do |pick| pick.update!(pick_number: pick.pick_number + 1) end waiver_pick.update!(pick_number: new_pick_number) elsif waiver_pick.pick_number < new_pick_number waiver_picks.where( 'pick_number <= :new_pick_number AND pick_number >= :old_pick_number', new_pick_number: new_pick_number, old_pick_number: waiver_pick.pick_number ).each do |pick| pick.update!(pick_number: pick.pick_number - 1) end waiver_pick.update!(pick_number: new_pick_number) end end private def authorised_user return if fpl_team.user == current_user errors.add(:base, 'You are not authorised to make changes to this team.') end def fpl_team_list_waiver_pick return if fpl_team_list.waiver_picks.include?(waiver_pick) errors.add(:base, 'This waiver pick does not belong to your team.') end def round_is_current return if round.id == Round.current_round.id errors.add(:base, "You can only make changes to your squad's line up for the upcoming round.") end def waiver_pick_update_occurring_in_valid_period if Time.now > round.deadline_time - 1.days errors.add(:base, 'The deadline time for updating waiver picks this round has passed.') end end def pending_waiver_pick return if waiver_pick.pending? errors.add(:base, 'You can only edit pending waiver picks.') end def valid_pick_number return if waiver_picks.map { |pick| pick.pick_number }.include?(new_pick_number) errors.add(:base, 'Pick number is invalid.') end def change_in_pick_number return if waiver_pick.pick_number != new_pick_number errors.add(:base, 'No change in pick number.') end def not_first_round return if round.id != Round.first.id errors.add(:base, 'There are no waiver picks during the first round.') end end
class Request < ApplicationRecord belongs_to :customer belongs_to :service has_many :proposal, dependent: :delete_all validates :article, presence: true validates :description, presence: true #validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } #validates :description, presence: true end
# frozen_string_literal: true class TransactionHistory def initialize @transaction_logs = [] end def add_transaction(transaction) @transaction_logs.push(transaction) @transaction_logs = @transaction_logs.sort_by { |trnsaction| trnsaction[:date] } end attr_reader :transaction_logs end
class User include MongoMapper::Document attr_reader :password key :account_id, ObjectId, :required => true key :username, String, :required => true, :unique => true key :email, String, :required => true, :unique => true key :password_digest, String, :required => true key :session_token, String, :required => true key :admin, String timestamps! attr_accessible :account_id, :username, :password, :email, :admin, :forms validates_length_of :password, :minimum => 6, :allow_nil => true before_validation :ensure_session_token belongs_to :account def self.find_by_credentials(username, password) user = User.find_by_username(username) (user && user.is_password?(password)) ? user : nil end def password=(pass) @password = pass self.password_digest = BCrypt::Password.create(pass) end def is_password?(pass) BCrypt::Password.new(self.password_digest).is_password?(pass) end def self.generate_session_token SecureRandom::urlsafe_base64(16) end def reset_session_token! self.session_token = self.class.generate_session_token self.save! end def user_type if account.is_creator?(id) return "Account creator" elsif admin return "Admin" end return "User" end private def ensure_session_token self.session_token ||= self.class.generate_session_token end end
class UsersController < ApplicationController before_action :authenticate_user! def index @users = User.all.page(params[:page]).per(10) end def destroy @user = User.find(params[:id]) if current_user.admin? @user.destroy redirect_to users_path, notice: 'ユーザーを削除しました' elsif @user == current_user @user.destroy redirect_to root_path, notice: '自分のアカウントを削除しました' else flash[:danger] = '他人のアカウントは削除できません' redirect_to root_path end end end
class WelcomeController<ApplicationController def index if current_user && current_user.provider == "twitter" @recent_timeline = current_user.timeline end end end
class Topic < ActiveRecord::Base belongs_to :user has_many :topic_posts has_many :posts, :through => :topic_posts, :dependent => :destroy end
require 'test_helper' class MatchImporterTest < ActiveSupport::TestCase test 'imports placement matches' do account = create(:account) importer = MatchImporter.new(account: account, season: 1) path = file_fixture('valid-placement-import.csv') assert_difference 'account.matches.placements.count', 6 do importer.import(path) assert_empty importer.errors end matches = account.matches.placements.ordered_by_time assert_equal :win, matches[0].result assert_equal :win, matches[1].result assert_equal :loss, matches[2].result assert_equal :draw, matches[3].result assert_equal :loss, matches[4].result assert_equal :win, matches[5].result end test 'imports placement and regular matches from same file' do account = create(:account) importer = MatchImporter.new(account: account, season: 1) path = file_fixture('valid-placement-and-regular-import.csv') assert_difference 'account.matches.placements.count', 10 do assert_difference 'account.matches.non_placements.count' do importer.import(path) assert_empty importer.errors end end matches = account.matches.ordered_by_time assert matches[0..9].all? { |match| match.placement? }, 'first 10 matches should be placements' assert_equal :win, matches[0].result assert_equal matches[0], matches[1].prior_match assert_equal :win, matches[1].result assert_equal matches[1], matches[2].prior_match assert_equal :loss, matches[2].result assert_equal matches[2], matches[3].prior_match assert_equal :draw, matches[3].result assert_equal matches[3], matches[4].prior_match assert_equal :loss, matches[4].result assert_equal matches[4], matches[5].prior_match assert_equal :win, matches[5].result assert_equal matches[5], matches[6].prior_match assert_equal :win, matches[6].result assert_equal matches[6], matches[7].prior_match assert_equal :loss, matches[7].result assert_equal matches[7], matches[8].prior_match assert_equal :win, matches[8].result assert_equal matches[8], matches[9].prior_match final_placement_match = matches[9] refute_nil final_placement_match, 'should have logged a final placement match' assert_equal :loss, final_placement_match.result assert_equal 3115, final_placement_match.rank regular_match = matches[10] refute_nil regular_match, 'should have created a regular match' assert_equal matches[9], matches[10].prior_match assert_equal :win, regular_match.result assert_equal 3135, regular_match.rank assert_equal 'good teamwork', regular_match.comment end end
class Edge include Comparable attr_accessor :node1, :node2, :weight def initialize(node1, node2, weight) @node1 = node1 @node2 = node2 @weight = weight end def hash_key return @node1.node_data.to_s + "->" + @node2.node_data.to_s end def <=>(other) @weight <=> other.weight end end
class CreateReservations < ActiveRecord::Migration[5.0] def change create_table :reservations do |t| t.string :title t.datetime :begin_at t.datetime :ends_at t.references :meeting_room, foreign_key: true t.timestamps end end end
module Yawast module Scanner module Plugins module SSL class SSL def self.print_precert(cert) scts = cert.extensions.find {|e| e.oid == 'ct_precert_scts'} unless scts.nil? Yawast::Utilities.puts_info "\t\tSCTs:" scts.value.split("\n").each { |line| puts "\t\t\t#{line}" } end end def self.print_cert_hash(cert) hash = Digest::SHA1.hexdigest(cert.to_der) Yawast::Utilities.puts_info "\t\tHash: #{hash}" puts "\t\t\thttps://censys.io/certificates?q=#{hash}" puts "\t\t\thttps://crt.sh/?q=#{hash}" end def self.check_hsts(head) found = '' head.each do |k, v| if k.downcase.include? 'strict-transport-security' found = "#{k}: #{v}" end end if found == '' Yawast::Utilities.puts_warn 'HSTS: Not Enabled' else Yawast::Utilities.puts_info "HSTS: Enabled (#{found})" end end def self.check_hsts_preload(uri) begin info = Yawast::Shared::Http.get_json URI("https://hstspreload.com/api/v1/status/#{uri.host}") chrome = info['chrome'] != nil firefox = info['firefox'] != nil tor = info['tor'] != nil Yawast::Utilities.puts_info "HSTS Preload: Chrome - #{chrome}; Firefox - #{firefox}; Tor - #{tor}" rescue => e Yawast::Utilities.puts_error "Error getting HSTS preload information: #{e.message}" end end def self.set_openssl_options #change certain defaults, to make things work better #we prefer RSA, to avoid issues with small DH keys OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:ciphers] = 'RSA:ALL:COMPLEMENTOFALL' OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:verify_mode] = OpenSSL::SSL::VERIFY_NONE OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] = OpenSSL::SSL::OP_ALL end def self.check_for_ssl_redirect(uri) #check to see if the site redirects to SSL by default if uri.scheme != 'https' head = Yawast::Shared::Http.head(uri) if head['Location'] != nil begin location = URI.parse(head['Location']) if location.scheme == 'https' #we run this through extract_uri as it performs a few checks we need return Yawast::Shared::Uri.extract_uri location.to_s end rescue #we don't care if this fails end end end return nil end def self.ssl_connection_info(uri) begin # we only care if this is https if uri.scheme == 'https' # setup the connection socket = TCPSocket.new(uri.host, uri.port) ctx = OpenSSL::SSL::SSLContext.new ctx.ciphers = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:ciphers] ssl = OpenSSL::SSL::SSLSocket.new(socket, ctx) ssl.hostname = uri.host ssl.connect # this provides a bunch of useful info, that's already formatted # instead of building this manually, we'll let OpenSSL do the work puts ssl.session.to_text puts end rescue => e Yawast::Utilities.puts_error "SSL Information: Error Getting Details: #{e.message}" end end end end end end end