text
stringlengths
10
2.61M
require "faraday" require "json" module Wunderapi class Request attr_reader :conn API_URL = "https://a.wunderlist.com" def initialize(attributes = {}) @conn = conn @api = attributes[:api] end def conn @conn ||= Faraday::Connection.new(:url => API_URL) do |builder| builder.use Faraday::Request::UrlEncoded builder.use Faraday::Adapter::NetHttp end end def get(url, options = {}) response = conn.get do |req| req.url url if options options.each do |k, v| req.params[k] = v end end req.headers = { 'X-Access-Token' => @api.access_token, 'X-Client-ID' => @api.client_id } end JSON.parse(response.body) end def post(url, options = {}) response = conn.post do |req| req.url url req.body = options.to_json req.headers = { 'X-Access-Token' => @api.access_token, 'X-Client-ID' => @api.client_id, 'Content-Type' => 'application/json', 'Content-Encoding' => 'UTF-8' } end JSON.parse(response.body) end def put(url, options = {}) response = conn.put do |req| req.url url req.body = options.to_json req.headers = { 'X-Access-Token' => @api.access_token, 'X-Client-ID' => @api.client_id, 'Content-Type' => 'application/json', 'Content-Encoding' => 'UTF-8' } end JSON.parse(response.body) end def delete(url, options = {}) response = conn.delete do |req| req.url url req.params[:revision] = options[:revision] req.headers = { 'X-Access-Token' => @api.access_token, 'X-Client-ID' => @api.client_id, 'Content-Encoding' => 'UTF-8' } end response.status end end end
class AddMaidenToSubmissions < ActiveRecord::Migration[5.0] def change add_column :submissions, :maiden_name, :string end end
require 'rails_helper' describe Astronaut, type: :model do describe 'Validations' do it { should validate_presence_of :name } it { should validate_presence_of :age } it { should validate_presence_of :job } end describe 'Relationships' do it { should have_many :astronaut_missions} it { should have_many :missions} end describe "Class Methods" do it ".average_age" do neil = Astronaut.create!(name: "Neil Armstrong", age: 37, job: "Commander") buzz = Astronaut.create!(name: "Buzz Aldrin", age: 38, job: "Engineer") jeff = Astronaut.create!(name: "Jeff C.", age: 40, job: "Custodian") # average = (37 + 38 + 40)/3.0 expect(Astronaut.average_age.round(2)).to eq(38.33) end end end
# 南昌教育信息网的新闻抓取类 class NceduSpider < BaseSpider def init_charset @charset = "gbk" end def modify_url(url) new_url = URI.join(url, Time.now.year.to_s + 'nzyxw/') return new_url end def before_spider(url, doc) pages_doc = doc.css("form[name='pageForm']") # pages_doc.children.remove pages_doc.css('select').remove page_count_arr = pages_doc.text.scan(/\d+/) set_item_count(page_count_arr[0].to_i) set_pages_info(page_count_arr[2].to_i, page_count_arr[1].to_i) return true end #新闻列表css选择 def get_list_selector return "a[title='$article.name']" end def get_next_url(base_url, next_page_number) next_page_url = URI.join(base_url, "index#{next_page_number-1}.htm") return next_page_url end #获取本地域名的新闻的详细信息 def spider_localhost_detail(url, detail_item) doc = get_html_document(url) return true if doc.nil? title = detail_item.text info_doc = doc.css("td[bgcolor='fff6d3']") publish_at = DateTime.strptime(info_doc.text[/\[.+\]/], '[%Y-%m-%d]') author_content = info_doc.css('strong').text # author = '南昌教育信息网' if author.length == 0 author = get_author('南昌教育信息网', '南昌', author_content) content_doc = doc.css('.newss') # content_html = doc_to_html(content_doc, url) # content_text = content_doc.text.strip # #保存新闻数据 # return save_news(title, url, author, publish_at, content_text, content_html) return save_news(title, url, author, publish_at, content_doc) end end
require 'rails_helper' # this page isn't important at all, but add a quick smoke test in case I # break it RSpec.describe 'admin - card images page' do include_context 'logged in as admin' before do @products = create_list(:card_product, 2) visit images_admin_card_products_path end it 'lists the cards' do @products.each do |product| expect(page).to have_selector "#card_product_#{product.id}" end end end
class AbstractMailer < ApplicationMailer default from: 'prme.asiaforum@spjimr.org' def welcome_email(user, upload) @upload = upload @user = user @url = 'http://prmeasia.spjimr.org/users/sign_in' mail(to: 'prme.asiaforum@spjimr.org', subject: 'New Abstract Uploaded') end def upload_abstract(user) @user = user mail(to: @user.email, subject: 'New Abstract Uploaded') end def payment(payment) @payment = payment mail(to: @payment.email, subject: 'Payment Information (PRMEASIA)') end end
class User < ActiveRecord::Base # CMD Line sample # u = User.new(nickname:'Matt', email:'matt@gmail.com', password:'foobar', password_confirmation:'foobar') before_save { self.email = email.downcase } before_create :create_remember_token before_destroy :destroy_associated_date validates :email, presence: true, uniqueness: true validates :email, format: /@/ validates :nickname, presence: true has_secure_password validates :password, length: { minimum: 6 } def User.new_remember_token SecureRandom.urlsafe_base64 end def User.encrypt(token) Digest::SHA1.hexdigest(token.to_s) end def send_password_reset #This is shady, maybe need to make use of Accessible/Attributes. self.update_columns(:password_reset_token => create_password_reset_token, :password_reset_sent_at => Time.zone.now) if Rails.env.production? client = Postmark::ApiClient.new(POSTMARK_API_KEY) client.deliver(from: 'info@kluvit.com', to: self.email, subject: 'Kluvit: Password Reset', text_body: self.nickname + ', follow the link below to change password! Otherwise your password will remain unchanged. ' + Rails.application.routes.url_helpers.edit_password_reset_url(self.password_reset_token, Rails.application.config.domain_host) ) else puts "$$$$$$$$ Forgotten pswd URL: " + Rails.application.routes.url_helpers.edit_password_reset_url(self.password_reset_token, Rails.application.config.domain_host) end end def create_password_reset_token begin password_reset_token = User.encrypt(User.new_remember_token) end while User.exists?(:password_reset_token => password_reset_token) return password_reset_token end private def create_remember_token # Create the token. begin self.remember_token = User.encrypt(User.new_remember_token) end while User.exists?(:remember_token => self.remember_token) end def destroy_associated_date # For the User, this scheme will delete each LineItem, Delete all HouseHoldMemberships, # reassign each Household the user is head of (and delete if they are sole member), # then delete the entire User record. No trace of User is left. ## Pseudo SQL. # For successful deletion of a User # -Delete all Lineitems where (payer OR payee) = User.id # -Delete all HouseholdMembers where member = User.id is # -For each Household h where hhowner = User.id # -Nullify hhowner. Insert c.id from HouseHoldMember c where h.id = c.member and has greatest updated_at timestamp. If empty, delete h # -Delete User where id = User.id Lineitem.destroy_all(["payer = ? OR payee = ?", id, id]) Householdmembers.destroy_all(["member = ?", id]) households = Household.where(hhowner: id) households.each do |hh| #Determine User who will inherit the Household inheritor = Householdmembers.where("hhid = ?", hh.id).order(updated_at: :asc).limit(1).first # Equivelant to: select * from householdmembers where hhid = 1 order by updated_at asc limit 1; if inheritor.nil? #Nobody is left in the household, delete it hh.destroy else #Reassign this household to the inheritor Household.update(hh.id, hhowner: inheritor.member) end end end end # == Schema Information # # Table name: users # # id :integer not null, primary key # nickname :string(255) # email :string(255) # created_at :datetime # updated_at :datetime # password_digest :string(255) # remember_token :string(255) # password_reset_token :string(255) # password_reset_sent_at :datetime #
class HauntsController < ApplicationController get "/locations/:id/haunts" do #page to select which characters haunt the location @location = Location.find(params[:id]) @writer = Writer.find_by(id: session[:writer_id]) erb :'/haunts/new' end post "/locations/:id/haunts" do #creates the haunt Haunt.create(location_id: params[:id], character_id: params[:character_id], blurb: params[:blurb]) redirect to "/characters/#{params[:character_id]}" end delete "/haunts/:id" do #deletes the haunt @haunt = Haunt.find(params[:id]) @haunt.delete redirect to "/characters/#{@haunt.character.id}" end end
class Phase < ActiveRecord::Base include RankedModel belongs_to :program has_many :sections, :dependent => :destroy validates_presence_of :name ranks :row_order, :with_same => :program_id acts_as_url :name, :url_attribute => :slug def to_param slug end def next_phase program.phases.rank(:row_order).where(["row_order > ?", row_order]).first end def previous_phase program.phases.rank(:row_order).where(["row_order < ?", row_order]).last end end
#!/usr/bin/env ruby require 'nokogiri' xml_str = File.read(ARGV[0]) doc = Nokogiri::XML(xml_str) doc.remove_namespaces! # doc.xpath(ARGV[1]).each do |node| # puts node.content # end def sum(xs) return xs.inject(0) {|s, n | s + n} end # Sum all amounts to cents # select all "//Amt " elements, # convert to text, # remove decimal dot, # convert to integer, def sum_and_n_transactions(doc) xs = doc.xpath("//Amt").map { |s| s.text.sub('.', '').to_i } puts xs.inject(0) {|s, n | s + n} puts xs.length end # print "Ustrd" values def print_ustrd(doc) xs = doc.xpath("//Ustrd").map { |s| s.text } puts xs end # print "Ustrd" value from path specified below def print_end_to_end_ref(doc) xs = doc.xpath("//NtryDtls/TxDtls/RmtInf/Ustrd").map { |s| s.text } puts xs end def print_reject_codes(doc) xs = doc.xpath("//RtrInf/Rsn/Cd").map { |s| s.text } puts xs end def ntrydtls_without_txdtls(doc) #xs0 = doc.xpath("//NtryDtls").select { |e| e.TxDtls != nil } #xs0 = doc.xpath("//NtryDtls").select { |e| e.xpath("/TxDtls") == nil } xs0 = doc.xpath("//NtryDtls").select { |e| e.xpath("/NtryRef") == nil } puts xs0.length #{ |s| s.text } #puts xs end def ntry_amts(doc) xs = doc.xpath("//Ntry/Amt").map { |s| s.text } puts xs end def parent_of_3m(doc) xs = doc.xpath("//Ntry/Amt[text()=3000000.00]/../..").map { |s| s.text } puts xs end def txdts_with_amt(doc, amount) xs = doc.xpath("//Amt[text()=#{amount}]/../../..")#.map { |s| s.text } puts xs end def ntryrefs(doc) xs = doc.xpath("//NtryRef").map { |s| s.text } puts xs end def ing_to_klarna_refs(doc) xs = doc.xpath("//RmtInf/Ustrd").map { |s| s.text } puts xs end def ing_to_klarna_end_to_end_refs(doc) xs = doc.xpath("//Refs/EndToEndId").map { |s| s.text } puts xs end # sum_and_n_transactions(doc) # print_ustrd(doc) # print_end_to_end_ref(doc) #print_reject_codes(doc) # ntrydtls_without_txdtls(doc) # ntry_amts(doc) # parent_of_3m(doc) # amount = "77.43" # txdts_with_amt(doc, amount) # ntryrefs(doc) #ing_to_klarna_refs(doc) ing_to_klarna_end_to_end_refs(doc)
#Blackjack! ##Objective #Practice contional logic including nested conditionals. #Use methods to keep our code DRY. ##Instructions #We are going to build a command line blackjack game. A player gets dealt two cards which have values between 1-11. After they get dealt two cards you should show them the total score of their cards and ask them if they want to hit or stay. A player is allowed to "hit" up to two times. After each hit you should ask if they want to hit or stay and display the total value of their cards. If they don't want to hit, and they are not at 21 they lose. Your program should tell them they lose and exit. #Note: To take input from the person "playing" the game your program will have to use the Ruby method "gets". ##Challenge #After successfully completing the previous game (there should be a commit with a working version of this game), alter the game so that a player can "hit" as many times as they want. def blackjack promt end def promt puts "Welcome! Would you like to play a game of blackjack? Enter Yes or No" play = gets.chomp.downcase if play == "yes" game_plan elsif play =="no" puts "That's too bad. Come back when you feel like playing" else puts "Sorry but I don't understand your respones. Please type and enter Yes to play or No to quit" blackjack end end def game_plan wants_to_play = true hand = [] total = first_move(hand) hit_me(hand) end def first_move(hand) deal(hand) deal(hand) total(hand) end def deal(hand) card = rand(12) puts "You have been dealt a card with a value of #{card}" hand << card end def total(hand) total = 0 hand.each do |count| total += count end total end def sum(total) puts "The sum of the cards you have been dealt is #{total}" end def hit_me(hand) puts "Would you like to hit or stick?" yay_or_nah = gets.chomp.downcase if yay_or_nah == "stick" eval(hand) else deal(hand) total = total(hand) if total < 21 sum(total) hit_me(hand) else eval(hand) end end end def eval(hand) total = total(hand) sum(total) if total < 21 puts "Sorry! The sum of the cards you have been dealt, #{total}, is less than 21. You lost this round!" playing = false elsif total == 21 puts "Lucky You! You won so drinks' are on the house:)" playing = false elsif total > 21 puts "Oops! You are busted buster!" end end blackjack
require "spec_helper" describe EmailListingsController do describe "routing" do it "routes to #index" do get("/email_listings").should route_to("email_listings#index") end it "routes to #new" do get("/email_listings/new").should route_to("email_listings#new") end it "routes to #show" do get("/email_listings/1").should route_to("email_listings#show", :id => "1") end it "routes to #edit" do get("/email_listings/1/edit").should route_to("email_listings#edit", :id => "1") end it "routes to #create" do post("/email_listings").should route_to("email_listings#create") end it "routes to #update" do put("/email_listings/1").should route_to("email_listings#update", :id => "1") end it "routes to #destroy" do delete("/email_listings/1").should route_to("email_listings#destroy", :id => "1") end end end
class CreateLargeFiles < ActiveRecord::Migration[5.1] def change create_table :large_files do |t| t.attachment :data, null: false t.references :chunked_upload_task, index: true, null: false t.timestamps end add_foreign_key :large_files, :chunked_upload_tasks end end
require 'spec_helper' describe "products/new" do before(:each) do assign(:product, stub_model(Product, :name => "MyString", :active => false, :creator_id => 1 ).as_new_record) end it "renders new product form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", products_path, "post" do assert_select "input#product_name[name=?]", "product[name]" assert_select "input#product_active[name=?]", "product[active]" assert_select "input#product_creator_id[name=?]", "product[creator_id]" end end end
require 'spec_helper' describe Wildcat::Game do it { should validate_presence_of(:away_team_id) } it { should validate_presence_of(:home_team_id) } it { should validate_presence_of(:label) } it { should validate_presence_of(:season) } it { should validate_presence_of(:stadium) } end
require 'test_helper' class TreeGraphTest < Minitest::Test class TestNode include TreeGraph def label_for_tree_graph "#{@word.upcase} (#{@word})" end def children_for_tree_graph sub_nodes end def initialize word @word = word end def << child sub_nodes << child end def sub_nodes @sub_nodes ||= [] end end def setup %w{a b c d e f g h}.each do |w| instance_variable_set "@#{w}", TestNode.new(w) end @a << @b << @c << @e @c << @g << @d << @f @d << @h << "i" end def test_that_it_has_a_version_number refute_nil ::TreeGraph::VERSION end def test_tree_graph tree = <<EOS A (a) ├─B (b) ├─C (c) │ ├─G (g) │ ├─D (d) │ │ ├─H (h) │ │ └─i │ └─F (f) └─E (e) EOS assert_equal tree.chomp, @a.tree_graph end def test_tree_graph_bottom_up tree = <<EOS ┌─E (e) │ ┌─F (f) │ │ ┌─i │ │ ├─H (h) │ ├─D (d) │ ├─G (g) ├─C (c) ├─B (b) A (a) EOS assert_equal tree.chomp, @a.tree_graph_bottom_up end def test_tree_graph_bottom_up_in_same_order tree = <<EOS ┌─B (b) │ ┌─G (g) │ │ ┌─H (h) │ │ ├─i │ ├─D (d) │ ├─F (f) ├─C (c) ├─E (e) A (a) EOS assert_equal tree.chomp, @a.tree_graph_bottom_up_in_same_order end end
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. describe AppsController do # This should return the minimal set of attributes required to create a valid # App. As you add validations to App, be sure to # update the return value of this method accordingly. def valid_attributes { :name => 'test app name' } end let(:app) { FactoryGirl.create(:app) } let(:user) { FactoryGirl.create(:user) } describe "GET index" do let(:app2) { FactoryGirl.create(:app) } let(:viewer) { FactoryGirl.create(:viewer) } before(:each) do app.viewers.push viewer app2.viewers.push app.account.administrator end describe "user not signed in" do it "should redirect to user sign in path" do get :index response.should redirect_to(new_user_session_path) end end describe "user signed in" do before(:each) do sign_in(user) end it "assigns @viewer_apps" do get :index, {} assigns(:viewer_apps).should be_blank assigns(:admin_apps).should be_blank end end describe "viewer signed in" do before(:each) do sign_in(viewer) end it "assigns @viewer_apps" do get :index, {} assigns(:viewer_apps).should == [app] assigns(:admin_apps).should be_blank end end describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "assigns @viewer_apps and @admin_apps" do get :index, {} assigns(:viewer_apps).should == [app2] assigns(:admin_apps).should == [app] end end end describe "GET show" do describe "user not signed in" do it "should redirect to user sign in page" do get :show, {:id => app.to_param} response.should redirect_to(new_user_session_path) end end describe "user signed in" do before(:each) do sign_in(user) end it "should return nil app" do get :show, {:id => app.to_param} assigns(:app).should be_nil end end describe "viewer signed in" do let(:viewer) { FactoryGirl.create(:viewer) } before(:each) do app.viewers.push viewer sign_out(user) sign_in(viewer) end it "should update last viewed" do app.last_viewed_at_by_user(viewer).should be_nil get :show, {:id => app.to_param} app.last_viewed_at_by_user(viewer).should > 1.minute.ago end it "should return last viewed at" do get :show, {:id => app.to_param} assigns(:last_viewed_at).should be_nil get :show, {:id => app.to_param} assigns(:last_viewed_at).should > 10.seconds.ago end it "should return app as @app" do get :show, {:id => app.to_param} assigns(:app).should == app end end describe "admin signed in" do before(:each) do sign_out(user) sign_in(app.account.administrator) end it "should return app as @app" do get :show, {:id => app.to_param} assigns(:app).should == app end xit "should show have duration and date range including records in DB" do date_min = 31.days.ago - 15.minutes date_max = 10.seconds.ago session1 = FactoryGirl.create(:recorded_app_session, :app => app, :duration => 1, :created_at => 1.day.ago) session2 = FactoryGirl.create(:recorded_app_session, :app => app, :duration => 100.5, :created_at => date_min) session3 = FactoryGirl.create(:recorded_app_session, :app => app, :duration => 4.5, :created_at => date_max) session4 = FactoryGirl.create(:non_recording_app_session, :app => app, :duration => 150, :created_at => 1.year.ago) get :show, {:id => app.to_param} assigns(:recorded_sessions).should include session1 assigns(:recorded_sessions).should include session2 assigns(:recorded_sessions).should include session3 assigns(:recorded_sessions).should_not include session4 assigns(:default_date_min).should == 32 # 32 days ago assigns(:default_date_max).should == 0 assigns(:default_duration_min).should == 1 assigns(:default_duration_max).should == 101 end describe "viewer of an app" do let(:app2) { FactoryGirl.create(:app) } before(:each) { app2.viewers << app.account.administrator } it "should able to view the app" do get :show, {:id => app2.to_param} response.should be_success assigns(:app).should == app2 end end end end describe "GET new" do describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "assigns a new app as @app" do get :new, {} response.should be_ok new_app = assigns(:app) new_app.should be_a_new(App) new_app.account.administrator.should == app.account.administrator end end describe "non admin signed in" do before(:each) do sign_in(user) end it "should redirect to index page" do get :new response.should redirect_to(apps_url) end end describe "not signed in" do it "should redirect to user sign in path" do get :new response.should redirect_to(new_user_session_path) end end end describe "GET edit" do describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "should return app as @app" do get :edit, { :id => app.to_param } response.should be_ok assigns(:app).should == app end end describe "non admin signed in" do before(:each) do sign_in(user) end it "should redirect to index" do get :edit, { :id => app.to_param } response.should redirect_to(apps_path) end end describe "not signed in" do it "should redirect to user sign in path" do get :edit, { :id => app.to_param } response.should redirect_to(new_user_session_path) end end end describe "POST create" do describe "not signed in" do it "should redirect to user sign in path" do post :create, { :app => valid_attributes } response.should redirect_to(new_user_session_path) end end describe "non admin signed in" do before(:each) do sign_in(user) end it "should redirect to app listing" do post :create, { :app => valid_attributes } response.should redirect_to(apps_path) end end describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end describe "with valid params" do it "creates a new App" do expect { post :create, {:app => valid_attributes} }.to change(App, :count).by(1) end it "assigns a newly created app as @app" do post :create, {:app => valid_attributes} assigns(:app).should be_a(App) assigns(:app).should be_persisted assigns(:app).account.should == app.account end it "redirects to app view with setup session var" do post :create, {:app => valid_attributes} response.should redirect_to(app_path(assigns(:app).to_param)) session[:app_first].should be_true end it 'schedules some recordings' do post :create, {:app => valid_attributes} new_app = assigns(:app) new_app.scheduled_recordings.should > 0 end end describe "with invalid params" do it "assigns a newly created but unsaved app as @app" do # Trigger the behavior that occurs when invalid params are submitted App.any_instance.stub(:save).and_return(false) post :create, {:app => {}} assigns(:app).should be_a_new(App) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted App.any_instance.stub(:save).and_return(false) post :create, {:app => {}} response.should render_template("new") end end end end describe "PUT update" do describe "not signed in" do it "should redirect to user sign in page" do put :update, {:id => app.to_param, :app => valid_attributes} response.should redirect_to(new_user_session_path) end end describe "non admin signed in" do before(:each) do sign_in(user) end it "should redirect to index" do put :update, {:id => app.to_param, :app => valid_attributes} response.should redirect_to(apps_path) end end describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end describe "with valid params" do it "updates the requested app" do # Assuming there are no other apps in the database, this # specifies that the App created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. App.any_instance.should_receive(:update_attributes).with({'these' => 'params'}) put :update, {:id => app.to_param, :app => {'these' => 'params'}} end it "assigns the requested app as @app" do put :update, {:id => app.to_param, :app => valid_attributes} assigns(:app).should eq(app) assigns(:app).name.should == valid_attributes[:name] end it "redirects to app listing" do put :update, {:id => app.to_param, :app => valid_attributes} response.should redirect_to(apps_path) end end describe "with invalid params" do it "assigns the app as @app" do # Trigger the behavior that occurs when invalid params are submitted App.any_instance.stub(:save).and_return(false) put :update, {:id => app.to_param, :app => {}} assigns(:app).should eq(app) end it "re-renders the 'edit' template" do # Trigger the behavior that occurs when invalid params are submitted App.any_instance.stub(:save).and_return(false) put :update, {:id => app.to_param, :app => {}} response.should render_template("edit") end end end end describe "DELETE destroy" do describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "destroys the requested app" do expect { delete :destroy, {:id => app.to_param} }.to change(App, :count).by(-1) end it "redirects to the apps list" do delete :destroy, {:id => app.to_param} response.should redirect_to(apps_url) end end describe "view signed in" do let(:viewer) { FactoryGirl.create(:viewer) } before(:each) do app.viewers << viewer sign_in(viewer) end it "does not destroys the requested app" do expect { delete :destroy, {:id => app.to_param} }.to change(App, :count).by(0) end it "redirects to the apps list" do delete :destroy, {:id => app.to_param} response.should redirect_to(apps_url) end end end describe "PUT update_recording" do describe "admin signed in" do describe "owns the app" do before(:each) do sign_in(app.account.administrator) end it "should pause recording" do put 'update_recording', { :app_id => app.id, :state => 'pause', :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'success' app.reload.recording_paused?.should be_true end it "should resume recording" do put 'update_recording', { :app_id => app.id, :state => 'resume', :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'success' app.reload.recording_paused?.should be_false end it "should fail given invalid state" do put 'update_recording', { :app_id => app.id, :state => 'invalid', :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'fail' result['reason'].should == 'invalid state' app.reload.recording_paused?.should be_false end end describe "does not own app" do let(:app2) { FactoryGirl.create(:app) } let(:admin2) { app2.account.administrator } before(:each) do sign_in(admin2) end it "should fail" do put 'update_recording', { :app_id => app.id, :state => 'pause', :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'fail' result['reason'].should == 'record not found' app.recording_paused?.should be_false end end end describe "other user signed in" do before(:each) do sign_in(user) end it "should fail" do put 'update_recording', { :app_id => app.id, :state => 'pause', :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'fail' result['reason'].should == 'record not found' app.recording_paused?.should be_false end end end describe "GET setup" do before(:each) do sign_in(app.account.administrator) end it "should return success" do get 'setup', { :app_id => app.id } response.should be_success assigns(:app).should == app end end describe "GET schedule_recording_edit" do describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "should increment the scheduled recording" do get 'schedule_recording_edit', { :app_id => app } response.should be_success end end describe "anyone who can administer signed in" do it "should increment the scheduled recording" end describe "other account signed in" do before(:each) do sign_in(user) end it "should redirect to apps lisnt" do get 'schedule_recording_edit', { :app_id => app } response.should redirect_to(apps_path) end end end describe "PUT schedule_recording_update" do describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "should set the scheduled recording with given amount" do put 'schedule_recording_update', { :app_id => app, :schedule_recording => 3 } response.should redirect_to(app_schedule_recording_edit_path(:app_id => app)) flash[:notice].should == 'Successfully scheduled recordings' app.reload app.scheduled_recordings.should == 3 end it "should render edit page with invalid param" do orig = app.scheduled_recordings put 'schedule_recording_update', { :app_id => app } response.should be_success app.reload app.scheduled_recordings.should == orig # no change end it "should not allow negative scheduled recording" do orig = app.scheduled_recordings put 'schedule_recording_update', { :app_id => app, :schedule_recording => -1 } response.should be_success app.reload app.scheduled_recordings.should == orig # no change flash.now[:notice].should == "Failed scheduling -1 recordings" end end end describe "PUT 'upload_on_wifi_only'" do let(:app2) { FactoryGirl.create(:app) } describe "admin signed in" do before(:each) do sign_in(app.account.administrator) end it "should success" do put 'upload_on_wifi_only', { :app_id => app.id, :state => 1, :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'success' app.reload app.uploading_on_wifi_only?.should be_true put 'upload_on_wifi_only', { :app_id => app.id, :state => 0, :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'success' app.reload app.uploading_on_wifi_only?.should be_false end it "should fail with missing state" do put 'upload_on_wifi_only', { :app_id => app.id, :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'fail' result['reason'].should == 'param state is missing' end it "should fail on app with no ownership" do sign_in(app2.account.administrator) put 'upload_on_wifi_only', { :app_id => app.id, :state => 1, :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'fail' result['reason'].should == 'access denied' end end describe "non admin signed in" do before(:each) do sign_in(user) end it "should fail" do put 'upload_on_wifi_only', { :app_id => app.id, :state => 1, :format => :json } response.should be_success result = JSON.parse(response.body) result['result'].should == 'fail' result['reason'].should == 'access denied' end end end end
require "sea_battle/version" require "sea_battle/board" require "sea_battle/gui" class SeaBattle def initialize(first_board, second_board, last_attack_move = nil) @last_attack_move = last_attack_move.split(";") unless last_attack_move.nil? @first_board = first_board @second_board = second_board end def active_user return :first_player if @last_attack_move.nil? player, row, column = @last_attack_move if player.to_sym == :first_player if @second_board.is_in_ship?(row.to_i, column.to_i) return :first_player else return :second_player end else if @first_board.is_in_ship?(row.to_i, column.to_i) return :second_player else return :first_player end end end def is_activated? not first_status.eql?(:initialized) and not second_status.eql?(:initialized) end def is_sunken_ship?(row, column, player) if player == :first_player @second_board.is_sunken_ship?(row, column) else @first_board.is_sunken_ship?(row, column) end end def last_attack_move return if @last_attack_move.nil? @last_attack_move.join(";") end def move(player, type, row, column) return false unless winner_is.nil? return false unless [:first_player, :second_player].include?(player) return false unless [:choose, :attack, :mark].include?(type) case type when :attack return false unless active_user == player return false unless first_status.eql?(:activated) and second_status.eql?(:activated) if player == :first_player @second_board.attack(row, column) else @first_board.attack(row, column) end @last_attack_move = [player, row, column] else end true end def winner_is return :second_player if first_status.eql? :finished return :first_player if second_status.eql? :finished nil end private def first_status @first_board.status end def second_status @second_board.status end end
class Lit < Formula desc "the universal literate programming tool" url "https://github.com/literate-programming/lit/releases/download/v0.3.2/lit_0.3.2_darwin_amd64.tar.gz" version "0.3.2" sha256 "a58e99a998decb9e1d02dc54cf76169aabdcb2d181c3c45095824625870b25e4" def install bin.install "lit" end test do system "#{bin}/lit -v" end end
# Another useful method that works in a similar way to each_index # is each_with_index. # each_with_index gives us the ability to manipulate both the value # and the index by passing in two parameters to the block of code. # The first is the value and the second is the index. You can then use # them in the block. # teams = ["Liverpool","Man City","Arsenal","Chavs","Spurs", "Man United"] teams = %w(Liverpool Man-city Arsenal Chelsea Spurs Man-United) # teams.each_with_index { |value, index| puts "#{index + 1} - #{value}" } teams.each_with_index do |value, index| puts "#{index + 1} - #{value}" end
class RemoveAssignedToAndMaintenancePeriodFromEquipment < ActiveRecord::Migration def self.up remove_column :equipment, :assigned_to, :string remove_column :equipment, :maintenance_period, :integer end def self.down add_column :equipment, :assigned_to, :string add_column :equipment, :maintenance_period, :integer end end
class Rayadmin::AdminsController < Rayadmin::RayadminController def home if not logged_in? redirect_to rayadmin_login_path end end end
class CreateLineItems < ActiveRecord::Migration[5.0] def change create_table :line_items do |t| t.belongs_to :lineable, polymorphic: true, index: true, null: false t.belongs_to :order, foreign_key: true, index: true, null: false t.float :item_cost, null: false t.timestamps end end end
## ## This file is only needed for Compass/Sass integration. If you are not using ## Compass, you may safely ignore or delete this file. ## ## If you'd like to learn more about Sass and Compass, see the sass/README.txt ## file for more information. ## # Default to development if environment is not set. saved = environment if (environment.nil?) environment = :development else environment = saved end # Location of the theme's resources. css_dir = "css" sass_dir = "sass" images_dir = "images" generated_images_dir = images_dir + "/generated" javascripts_dir = "js" # Require any additional compass plugins installed on your system. require 'compass-normalize' require 'rgbapng' require 'toolkit' require 'susy' require 'breakpoint' require 'sassy-buttons' #require 'sass-globbing' ## ## You probably don't need to edit anything below this. ## # You can select your preferred output style here (:expanded, :nested, :compact # or :compressed). output_style = (environment == :production) ? :expanded : :nested # To enable relative paths to assets via compass helper functions. Since Drupal # themes can be installed in multiple locations, we don't need to worry about # the absolute path to the theme from the server omega. relative_assets = true # Conditionally enable line comments when in development mode. line_comments = (environment == :production) ? false : true # Output debugging info in development mode. sass_options = (environment == :production) ? {} : {:debug_info => true} # Add the 'sass' directory itself as an import path to ease imports. add_import_path 'sass' require 'fileutils' on_stylesheet_saved do |file| # Move the home-layout.css file to the correct place. if File.exists?(file) && File.basename(file) == "home-layout.css" puts "Moving: #{file}" FileUtils.mv(file, File.dirname(file) + "/../layouts/panels/home-layout/" + File.basename(file)) end # Run the kss-node stylesheet generator. if File.exists?(file) && File.basename(file) == "australian-apprenticeships.styles.css" puts "Running kss-node!" cmd = system("kss-node css styleguide --template styleguide/template --css css/australian-apprenticeships.styles.css") end end
require "sfn-parameters" module SfnParameters # Common helper methods module Utils # Lock the given content # # @param content [Hash] content to lock # @return [Hash] locked content def lock_content(content) content = content.to_smash content.merge!(:sfn_lock_enabled => true) safe = SfnParameters::Safe.build( config.fetch(:sfn_parameters, :safe, Smash.new) ) safe.lock(dump_json(content)) end # Unlock given content # # @param content [Hash] content to unlock # @return [Hash] unlocked content def unlock_content(content) content = content.to_smash if content[:sfn_parameters_lock] safe = SfnParameters::Safe.build( config.fetch(:sfn_parameters, :safe, Smash.new) ) load_json(safe.unlock(content)).to_smash.merge(:sfn_lock_enabled => true) else content end end end end
class ChangeDatatypeRoomTimeOfMessages < ActiveRecord::Migration[5.0] def change change_column :messages, :room_time, :string end end
#!/usr/bin/env ruby require "rubygems" require "json" require "net/http" require "uri" class Opsgenie def initialize(api_key) @api_key = api_key @url_prefix = 'https://api.opsgenie.com/v1/json/alert' end def self.fetch_json(uri, params, req_type) uri = URI(uri) https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true begin if req_type=='post' res = https.post(uri.path, params) else uri.query = URI.encode_www_form(params) if params res = Net::HTTP.get_response(uri) end if res.is_a?(Net::HTTPSuccess) return JSON.parse(res.body) else return false end rescue return false end end def send_alert message params = "{ \"apiKey\":\"#{@api_key}\", \"message\":\"#{message}\" }" response = Opsgenie.fetch_json(@url_prefix, params, 'post') return response==false ? 'Alert could not be generated.':'Alert generated.' end def test_alert puts "Testing alert service." params = "{ \"apiKey\":\"#{@api_key}\", \"message\":\"testalert\" }" response = Opsgenie.fetch_json(@url_prefix, params, 'post') return response==false ? 'Alert could not be generated.':'Alert generated.' end end
# This migration comes from blogine (originally 20180111144533) class CreateBlogineArticles < ActiveRecord::Migration[5.1] def change create_table :blogine_articles do |t| t.string :title t.date :release_date t.text :content t.integer :category_id t.string :tags t.string :slug t.timestamps end end end
require './canhelplib' module CanhelpPlugin include Canhelp def self.get_student_count( canvas_url=prompt(:canvas_url), account_id=prompt(:account_id), student_role_id = prompt(:student_role_id) ) token = get_token subaccount_ids = get_json_paginated( token, "#{canvas_url}/api/v1/accounts/#{account_id}/sub_accounts", "recursive=true" ).map{|s| s['id']} subaccount_ids << account_id puts "\t" puts "Grabbing enrollments from courses in the following accounts:" subaccount_ids.each do |subaccount| puts "- #{subaccount}" end all_student_enrollments = [] subaccount_ids.each do |subaccount_id| courses = get_json_paginated( token, "#{canvas_url}/api/v1/accounts/#{subaccount_id}/courses", "include[]=total_students&include[]=teachers&state[]=available&state[]=completed" ) courses.each do |course| if course['workflow_state'] != 'unpublished' course_ids = course['id'] enrollments = get_json_paginated( token, "#{canvas_url}/api/v1/courses/#{course_ids}/enrollments", "state[]=active&state[]=completed&type[]=StudentEnrollment" ) course_name = course['name'] course_state = course['workflow_state'] total_students = course['total_students'] teacher_display_name = course['teachers'] teacher_display_name.each do |teacher| teacher_name = teacher['display_name'] puts puts "Teacher's Name: #{teacher_name}" end puts puts "- Course Name: #{course_name}" puts puts "- State: #{course_state}" puts puts "- Total number of students: #{total_students}" puts enrollments.each do |enrollment| if enrollment['role_id'].to_s == "#{student_role_id}" all_student_enrollments << enrollment student_name = enrollment['user']['name'] student_sis = enrollment['user']['sis_user_id'] student_workflow_state = enrollment['enrollment_state'] puts "- Student's Name: #{student_name} - #{student_sis} - #{student_workflow_state}" end end end end end student_ids = all_student_enrollments.map { |enrollment| enrollment['user_id'] }.uniq all_student_info = student_ids.map do |id| student_enrollment = all_student_enrollments.find { |enrollment| enrollment['user_id'] == id } next if student_enrollment.nil? "#{student_enrollment['user']['name']} - #{student_enrollment['user_id']} | #{student_enrollment['sis_user_id']} | #{student_enrollment['created_at']} | #{student_enrollment['updated_at']}" end.sort_by(&:downcase) total_student_count = student_ids.count puts puts "Total number of active and completed StudentEnrollments: #{total_student_count}" puts puts "All Students' Names: " all_student_info.each do |name| puts "- #{name}" end end end
require_relative 'shell_helper' namespace :java do def java_bin "#{fetch(:java_home)}/bin" end desc "execute command under java/bin directory" task :bin,:command do |t,args| on roles(:all),in: :sequence do |host| execute "#{java_bin}/#{args[:command]}" end end desc "view vmargs of java process" task :vmargs,:process do |t,args| on roles(:all),in: :sequence do |host| execute! "#{java_bin}/jcmd #{args[:process]} VM.flags",raise_on_non_zero_exit:false end end desc "view gcutil of java process" task :gcutil,:process do |t,args| process_name = args[:process] on roles(:all),in: :sequence do |host| command = "str=$(#{java_bin}/jps|grep #{process_name}|tr ' ' '\\n'|head -n 1) && [ \"$str\" ] && #{java_bin}/jstat -gcutil $str" execute! command,raise_on_non_zero_exit:false end end end
module JquerySortableTreeHelper # Ilya Zykin, zykin-ilya@ya.ru, Russia [Ivanovo, Saint Petersburg] 2009-2014 # github.com/the-teacher TREE_RENDERERS = { tree: RenderTreeHelper, sortable: RenderSortableTreeHelper, expandable: RenderExpandableTreeHelper, nested_options: RenderNestedOptionsHelper, indented_options: RenderIndentedOptionsHelper, optgroup: RenderOptgroupHelper }.freeze ############################################### # Common Base Methods ############################################### def define_class_of_elements_of tree case when tree.is_a?(ActiveRecord::Relation) then tree.name.to_s.underscore.downcase when tree.empty? then nil else tree.first.class.to_s.underscore.downcase end end def build_tree_html context, render_module, options = {} render_module::Render.new(context, options).render_node end ############################################### # Shortcuts ############################################### def just_tree(tree, options = {}) build_server_tree(tree, { type: :tree }.merge!(options)) end def base_data { model: params[:controller].singularize, title: 'title', max_levels: 5, parent_id: params[:parent_id], rebuild_url: send("rebuild_#{params[:controller]}_url"), url: url_for(controller: params[:controller], action: :show, id: ':id', format: :json) } end def space(height) content_tag(:div, '&nbsp;'.html_safe, style: "height: #{height}px;") end def fake_node(options) options[:title] ||= 'title' OpenStruct.new(options[:title] => '', id: ':id', children: nil) end def fake_sortable_ol_tag(options) content_tag(:ol, build_tree_html(self, TREE_RENDERERS[:sortable], base_options.merge(options).merge({ node: fake_node(options) })), class: 'fake-node hidden', style: 'display: none;') end def real_sortable_ol_tag(tree, options) content_tag(:ol, build_server_tree(tree, { type: :sortable }.merge(options)), class: 'sortable_tree', data: base_data.merge(options.slice(:parent_id, :model, :rebuild_url, :title, :max_levels)) ) end def sortable_tree(tree, options = {}) space(20) + add_new_node_form(base_data.merge(options)) + fake_sortable_ol_tag(options) + real_sortable_ol_tag(tree, options) end def form_for_options(options) { html: { id: "new-#{options[:model]}-form" }, url: send("#{options[:model].pluralize}_path", format: :json), method: :post, remote: true } end def add_new_node_form(options) capture do form_for(options[:model].to_sym, form_for_options(options)) do |f| title_field = f.text_field options[:title].to_sym, required: true, class: 'form-control', placeholder: I18n.t('sortable_tree.title_of_new_node', default: "The #{options[:title]} of new #{options[:model]}"), maxlength: 255 concat content_tag(:div, title_field, class: 'form-group') concat f.hidden_field :parent_id, value: options[:parent_id] end end end def nested_options(tree, options = {}) build_server_tree(tree, { type: :nested_options }.merge(options)) end def indented_options(tree, options = {}) build_server_tree(tree, { type: :indented_options }.merge(options)) end def expandable_tree(tree, options = {}) build_server_tree(tree, { type: :expandable }.merge(options)) end def optgroup(tree, options = {}) build_server_tree(tree, { type: :optgroup }.merge(options)) end ############################################### # Server Side Render Tree Helper ############################################### def base_options { id: :id, title: :title, node: nil, type: :tree, root: false, level: 0, namespace: [], controller: params[:controller] } end def build_children(tree, opts) children = (opts[:boost][opts[:node].id.to_i] || []) children.reduce('') { |r, elem| r + build_server_tree(tree, opts.merge(node: elem, root: false, level: opts[:level].next)) } end def roots(tree) min_parent_id = tree.map(&:parent_id).compact.min tree.select { |e| e.parent_id == min_parent_id } end def merge_base_options(tree, options) opts = base_options.merge(options) opts[:namespace] = [*opts[:namespace]] opts[:render_module] ||= TREE_RENDERERS[opts[:type]] opts[:klass] ||= define_class_of_elements_of(tree) opts[:boost] ||= tree.group_by { |item| item.parent_id.to_i } opts end def build_server_tree(tree, options = {}) tree = [*tree] opts = merge_base_options(tree, options) if opts[:node] raw build_tree_html(self, opts[:render_module], opts.merge(children: build_children(tree, opts))) else raw (roots(tree) || []).reduce('') { |r, root| r + build_server_tree(tree, opts.merge(node: root, root: true, level: opts[:level].next)) } end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) names = ["Lissette", "Gustavo", "Pepa", "Nova", "Marcelo"] imgs = ["https://cdn.pixabay.com/photo/2015/02/25/17/56/cat-649164__340.jpg", "https://cdn.pixabay.com/photo/2015/08/30/10/58/cat-914110__340.jpg", "https://cdn.pixabay.com/photo/2015/11/07/11/34/kitten-1031261__340.jpg", "https://cdn.pixabay.com/photo/2017/05/05/22/28/kitten-2288404__340.jpg", "https://cdn.pixabay.com/photo/2016/11/22/19/02/cat-1850056__340.jpg"] 5.times do |i| User.create(user_name: names[i], user_image: imgs[i], email: "#{names[i].downcase}@example.com", password: "123456" ) end 100.times do content = Faker::Quote.yoda user_id = Random.rand(1..5) parent_tweet = (Tweet.all.count>0 && rand>0.5)? Tweet.all.order('random()').first.id : nil content_retweet = (parent_tweet != nil) ? Tweet.find(parent_tweet).content : nil Tweet.create(content: content, user_id: user_id, parent_tweet: parent_tweet, content_retweet: content_retweet ) end 5.times do |i| 100.times do |j| if ((j+1) % (i+1) == 0) Like.create(user_id: i+1, tweet_id: j+1) end end end
class CreateAnalysisRequestItems < ActiveRecord::Migration[5.2] def change create_table :analysis_request_items do |t| t.references :analysis_request, foreign_key: true t.references :analysis, foreign_key: true t.float :price t.timestamps end end end
# frozen_string_literal: true module Dry module Types # Primitives with {Kernel} coercion methods KERNEL_COERCIBLE = { string: String, integer: Integer, float: Float, decimal: BigDecimal, array: ::Array, hash: ::Hash }.freeze # Primitives with coercions through by convention `to_*` methods METHOD_COERCIBLE = { symbol: Symbol }.freeze # By convention methods to coerce {METHOD_COERCIBLE} primitives METHOD_COERCIBLE_METHODS = { symbol: :to_sym }.freeze # Primitives that are non-coercible NON_COERCIBLE = { nil: NilClass, class: Class, true: TrueClass, false: FalseClass, date: Date, date_time: DateTime, time: Time, range: Range }.freeze # All built-in primitives ALL_PRIMITIVES = [KERNEL_COERCIBLE, METHOD_COERCIBLE, NON_COERCIBLE].reduce(&:merge).freeze # All coercible types COERCIBLE = KERNEL_COERCIBLE.merge(METHOD_COERCIBLE).freeze # All built-in primitives except {NilClass} NON_NIL = ALL_PRIMITIVES.reject { |name, _| name == :nil }.freeze # Register generic types for {ALL_PRIMITIVES} ALL_PRIMITIVES.each do |name, primitive| type = Nominal[primitive].new(primitive) register("nominal.#{name}", type) end # Register strict types for {ALL_PRIMITIVES} ALL_PRIMITIVES.each do |name, primitive| type = self["nominal.#{name}"].constrained(type: primitive) register(name.to_s, type) register("strict.#{name}", type) end # Register {KERNEL_COERCIBLE} types KERNEL_COERCIBLE.each do |name, primitive| register("coercible.#{name}", self["nominal.#{name}"].constructor(Kernel.method(primitive.name))) end # Register {METHOD_COERCIBLE} types METHOD_COERCIBLE.each_key do |name| register( "coercible.#{name}", self["nominal.#{name}"].constructor(&METHOD_COERCIBLE_METHODS[name]) ) end # Register optional strict {NON_NIL} types NON_NIL.each_key do |name| type = self[name.to_s].optional register("optional.strict.#{name}", type) register("optional.#{name}", type) end # Register optional {COERCIBLE} types COERCIBLE.each_key do |name| register("optional.coercible.#{name}", self["coercible.#{name}"].optional) end # Register `:bool` since it's common and not a built-in Ruby type :( register("nominal.bool", self["nominal.true"] | self["nominal.false"]) bool = self["strict.true"] | self["strict.false"] register("strict.bool", bool) register("bool", bool) register("any", Any) register("nominal.any", Any) register("strict.any", Any) end end require "dry/types/coercions" require "dry/types/params" require "dry/types/json"
class Post < ApplicationRecord include Rails.application.routes.url_helpers paginates_per 10 mount_uploader :image, ImageUploader enum post_status: %i[draft post_later posted] belongs_to :user has_many :comments, dependent: :destroy validates :title, :content, presence: true after_save :enqueue_post_later_job, if: :post_later? after_save :enqueue_post_to_social_job, if: :allow_social_post? def author user.display_name end private def enqueue_post_later_job PostLaterJob.set(wait_until: posted_at).perform_later(id) end def allow_social_post? Rails.application.secrets.allow_social_post end def enqueue_post_to_social_job link_url = post_url(self, host: Rails.application.secrets.host_url) PostToSocialJob.perform_later(link_url) end end
require 'fileutils' require 'sprockets' module Gloat class Static def generate generate_index config.static_decks.each { |deck| generate_deck deck } end def generate_index FileUtils.mkdir_p(File.join(static_path, 'assets')) File.open(File.join(static_path, 'index.html'), 'w') do |file| data = { name: 'Available decks', decks: config.decks, static_decks_path: static_decks_path } markup = Nokogiri::HTML(Gloat::Page::StaticBasic.new('static_decks', data).render) markup.css('link').each do |x| next if !x.attribute('href') || x.attribute('href').value.match(/^http/) x.attribute('href').value = "." + x.attribute('href').value end markup.css('script').each do |x| next if !x.attribute('src') || x.attribute('src').value.match(/^http/) x.attribute('src').value = "." + x.attribute('src').value end file.write markup.to_s end %W{ basic.css }.each do |file| File.open(File.join(static_path, 'assets', file), 'w') do |f| f.write env[file].to_s end end end def generate_deck deck deck = Gloat::Page::StaticDeck.new(deck) deck_path = File.join(static_path, 'decks', deck.slug) FileUtils.mkdir_p(File.join(static_path, 'assets', 'themes', deck.theme)) FileUtils.mkdir_p(deck_path) File.open(File.join(deck_path, 'index.html'), 'w') do |file| markup = Nokogiri::HTML(deck.render) # CSS markup.css('link').each do |x| next if !x.attribute('href') || x.attribute('href').value.match(/^http/) x.attribute('href').value = "../.." + x.attribute('href').value end # JavaScript markup.css('script').each do |x| next if !x.attribute('src') || x.attribute('src').value.match(/^http/) x.attribute('src').value = "../.." + x.attribute('src').value end file.write markup.to_s end %W{ vendor.js application.js base.css vendor.css application.css local_application.css themes/#{deck.theme}/style.css themes/#{deck.theme}/background.png themes/#{deck.theme}/logo.png }.each do |file| File.open(File.join(static_path, 'assets', file), 'w') do |f| f.write env[file].to_s end end # Slide images FileUtils.cp_r images_path, File.join(static_path, 'images') if Dir.exist?(images_path) # Theme files theme_files = Dir[File.join(assets_path, 'themes', deck.theme, '*')].reject { |x| x.match(/\.(erb|haml|sass)$/) } FileUtils.cp_r theme_files, File.join(static_path, 'assets', 'themes', deck.theme) # Assets FileUtils.cp_r Dir[File.join(assets_path, 'images', '*')], File.join(static_path, 'assets') FileUtils.cp_r Dir[File.join(root_assets_path, 'images', '*')], File.join(static_path, 'assets') FileUtils.cp_r Dir[File.join(assets_path, 'fonts', '*')], File.join(static_path, 'assets') FileUtils.cp_r Dir[File.join(root_assets_path, 'fonts', '*')], File.join(static_path, 'assets') end private def config Config.instance end def root_path @root_path ||= File.expand_path(File.join('..', '..', '..'), __FILE__) end def current_path Dir.pwd end def assets_path @assets_path ||= File.join(current_path, 'assets') end def root_assets_path @root_assets_path ||= File.join(root_path, 'assets') end def static_path @static_path ||= File.join(current_path, 'static') end def static_decks_path @static_decks_path ||= File.join(static_path, 'decks') end def images_path @images_path ||= File.join(current_path, 'slides', 'images') end def env @env ||= begin env = Sprockets::Environment.new [ root_assets_path, assets_path ].each do |path| env.append_path File.join(path, 'stylesheets') env.append_path File.join(path, 'javascripts') env.append_path File.join(path, 'images') env.append_path File.join(path, 'themes') env.append_path File.join(path, 'fonts') env.append_path File.join(path) end env end end end end
require 'rails_helper' describe Recipe do it 'has to have a pizza' do any_ingredient = 1 recipe = Recipe.new( pizza: nil, ingredient: any_ingredient ) recipe.save errors = recipe.errors expect(errors.count).to eq(1) expect(errors.messages[:pizza]).to eq(["can't be blank"]) end it 'has to have a ingredient' do any_pizza = 1 recipe = Recipe.new( pizza: any_pizza, ingredient: nil ) recipe.save errors = recipe.errors expect(errors.count).to eq(1) expect(errors.messages[:ingredient]).to eq(["can't be blank"]) end it 'can return the ingredients for a pizza' do pizza = PreparedPizza.new(name: 'Any pizza') pizza.save ingredient = Ingredient.new(name: 'Any ingredient', price: 1.0) ingredient.save recipe = Recipe.new(pizza: pizza.id, ingredient: ingredient.id) recipe.save ingredients_list = [ingredient.id] ingredients = Recipe.ingredients_for(pizza.id) expect(ingredients).to eq(ingredients_list) end end
FactoryBot.define do factory :transaction_type do trait :invalid_description do description { nil } end trait :invalid_nature do nature { nil } end trait :invalid_signal do signal { nil } end trait :positive do signal { '+' } end trait :negative do signal { '-' } end description { 'MyString' } nature { 'MyString' } signal { '+' } end end
FactoryGirl.define do factory :trivia_option do sequence(:text) {|n| "Answer #{n}"} end end
FactoryBot.define do factory :candidacy do score { 92 } association(:vacancy) association(:candidate) end end
require 'rails_helper' RSpec.describe Api::V1::VulnerabilitiesController, type: :controller do let(:vuln) { create(:vulnerability) } describe '#index' do it 'can get vulnerabilities' do get :index, format: :json expect(response).to be_success end it 'can query by description' do get :index, format: :json, params: { q: 'test' } expect(response).to be_success end it 'can query by year' do get :index, format: :json, params: { year: 2014 } expect(response).to be_success end it 'can query by ids' do arr = [ vuln.id, 0, 12] get :index, format: :json, params: { ids: arr } expect(response).to be_success end it 'can sort by cve' do get :index, format: :json, params: { o: 'cve', d: 'asc' } expect(response).to be_success end it 'can ignore a sort by a non-supported column' do get :index, format: :json, params: { o: 'weasels', d: 'desc' } expect(response).to be_success end end describe '#show' do it 'will fail to get a non-existant vulnerability' do expect do get :show, format: :json, params: { id: 0 } end.to raise_error ActiveRecord::RecordNotFound end end end
class LocalTransactionController < ApplicationController include ActionView::Helpers::TextHelper include Cacheable include Navigable before_action -> { set_content_item(LocalTransactionPresenter) } before_action -> { response.headers["X-Frame-Options"] = "DENY" } INVALID_POSTCODE = "invalidPostcodeFormat".freeze NO_MAPIT_MATCH = "fullPostcodeNoMapitMatch".freeze NO_MATCHING_AUTHORITY = "noLaMatch".freeze BANNED_POSTCODES = %w[ENTERPOSTCODE].freeze def search if request.post? @location_error = location_error if @location_error @postcode = postcode elsif mapit_response.location_found? slug = if lgsl == 364 && country_name == "Northern Ireland" "electoral-office-for-northern-ireland" else local_authority_slug end redirect_to local_transaction_results_path(local_authority_slug: slug) end end end def results @postcode = postcode @interaction_details = interaction_details @local_authority = LocalAuthorityPresenter.new(@interaction_details["local_authority"]) @country_name = @local_authority.country_name @service = LocalTransactionService.new( @publication.title, lgsl, @country_name, @local_authority.url ) if @service.unavailable? render :unavailable_service else render :results end end private def local_authority_slug @local_authority_slug ||= LocalTransactionLocationIdentifier.find_slug(mapit_response.location.areas, content_item) end def country_name @country_name ||= LocalTransactionLocationIdentifier.find_country(mapit_response.location.areas, content_item) end def location_error return LocationError.new(INVALID_POSTCODE) if banned_postcode? || mapit_response.invalid_postcode? || mapit_response.blank_postcode? return LocationError.new(NO_MAPIT_MATCH) if mapit_response.location_not_found? return LocationError.new(NO_MATCHING_AUTHORITY) unless local_authority_slug end def banned_postcode? BANNED_POSTCODES.include? postcode end def mapit_response @mapit_response ||= location_from_mapit end def location_from_mapit if postcode.present? begin location = Frontend.mapit_api.location_for_postcode(postcode) rescue GdsApi::HTTPNotFound location = nil rescue GdsApi::HTTPClientError => e error = e end end MapitPostcodeResponse.new(postcode, location, error) end def postcode PostcodeSanitizer.sanitize(params[:postcode]) end def lgsl content_item["details"]["lgsl_code"] end def lgil content_item["details"]["lgil_code"] || content_item["details"]["lgil_override"] end def interaction_details council = params[:local_authority_slug] if council == "electoral-office-for-northern-ireland" { "local_authority" => { "name" => "Electoral Office for Northern Ireland", "homepage_url" => "http://www.eoni.org.uk" }, "local_interaction" => { "url" => "http://www.eoni.org.uk/Utility/Contact-Us" }, } else @_interaction ||= Frontend.local_links_manager_api.local_link(council, lgsl, lgil) end end end
class CreateDiscountCodesForAllStudents < ActiveRecord::Migration def change Student.all.map(&:reset_discount_code!) end end
require 'test_helper' describe Ingredient do it 'must clear Beer join records before destruction' do beer = Factory(:beer) ingredient = Factory(:ingredient) beer.ingredients << ingredient beer.reload and ingredient.reload ingredient.destroy beer.reload beer.id.wont_be_nil beer.ingredients.wont_include(ingredient) end end
# Construct a swift compiler command. module Lightspeed class SwiftCommand include FileUtils COMPILER_MODES = { compiled: 'swiftc', immediate: 'swift', } attr_reader :args, :mode, :config def initialize(args, mode: :compiled, config: Lightspeed.configuration) @args = args @mode = COMPILER_MODES.fetch(mode) { fail ArgumentError, "unsupported swift compiler mode '#{mode}'" } @config = config end def build if block_given? yield *format_cmd else format_cmd end end private def format_cmd cmd = ['xcrun', *sdk_opts, mode, *framework_opts, *args] if args.count == 1 && args.first.to_s.include?(" ") cmd = cmd.join(" ") else cmd end end def sdk_opts ['-sdk', config.sdk.to_s] end def framework_opts [ *map_if?(build_dir) { |dir| "-F#{dir}" } ] end def build_dir ensure_exists(config.build_products_dir) end # If the value is truthy, map with the provided block, else return nil. def map_if?(val, &block) if val yield val end end end end
class MathDojo # your code here attr_accessor :answer def initialize @answer = 0 end def add *group for number in group if number.is_a? Fixnum @answer += number else number.each_index {|i| @answer += number[i]} end end self end def subtract *group for number in group if number.is_a? Fixnum @answer -= number else number.each_index {|i| @answer -= number[i]} end end self end def result puts @answer end end # challenge1 = MathDojo.new.add(2).add(2, 5).result challenge1 = MathDojo.new.add(2).add(2, 5).subtract(3, 2).result # => 4 challenge2 = MathDojo.new.add(1).add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract([2,3], [1.1, 2.3]).result # => 23.15
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) User.destroy_all Song.destroy_all demo_user = User.create(username: "Demo_User", password: "password", email: "test@email.com", avatar_url: "https://s3-us-west-1.amazonaws.com/loudfog/avatar_1.jpeg") avatars = [ "https://s3-us-west-1.amazonaws.com/loudfog/avatar_1.jpeg", "https://s3-us-west-1.amazonaws.com/loudfog/avatar_3.jpeg", "https://s3-us-west-1.amazonaws.com/loudfog/avatar_4.jpeg", "https://s3-us-west-1.amazonaws.com/loudfog/avatar_5.jpeg" ] username = ["userBob", "meanCat", "AndresTheGreat", "hassium", "dolerite", "popinjay", "SeaTriscuit", "gus_music", "wyatt", "buster"] 10.times do |i| name = username[i] email = "test#{i}@loudfog.com" User.create(username: name, password: "password", email: email, avatar_url: avatars[i]) end songs = ["Light For The Road", "Think Of Power","Broken Chances", "Songs For Tomorrow", "When You're Smiling", "Midnight Inventions", "Never Let Me Go", "Walking Mind", "Stormy Money", "Sound Of The Evening", "Dust Of Tomorrow"] Song.create(user_id: 0, title: "Lost Things", image: File.new("app/assets/images/seed/13.jpg"), audio: File.new("app/assets/music/13.mp3")) Song.create(user_id: 0, title: "Darling, The Night Is Still Young", image: File.new("app/assets/images/seed/12.jpg"), audio: File.new("app/assets/music/12.mp3")) 11.times do |i| user_id = User.all.sample.id title = songs[i] image = File.new("app/assets/images/seed/#{i+1}.jpg") audio = File.new("app/assets/music/#{i+1}.mp3") Song.create(user_id: user_id, title: title, image: image, audio: audio) end Like.create(user_id: 1, song_id: 0) Like.create(user_id: 1, song_id: 3) Like.create(user_id: 1, song_id: 5) Like.create(user_id: 1, song_id: 6) Like.create(user_id: 1, song_id: 7) Like.create(user_id: 1, song_id: 9) comments = ["Great stuff", "Love the song", "Interesting production", "Would love to see more songs like this", "When was this released?", "Been listening to this non-stop!", "My partner loves this song", "I want more of this!", "Nice", "Oooh, lovin' this one!", "Awesome instrumentals", "Really great production here!", "Sick track!", "Strong ending", "I actually love this"] 15.times do |i| user_id = User.all.sample.id song_id = Song.all.sample.id comment = comments[i] Comment.create(user_id: user_id, song_id: song_id, body: comment) end
require 'spec_helper' describe 'Crypting' do describe 'Correct' do before do add_config(false, false) @raw_mail = Notifier.fufu('<destination@foobar.com>', '<demo@foobar.com>') add_config(false, true) @mail = Notifier.fufu('<destination@foobar.com>', '<demo@foobar.com>') end it 'Must generate crypted text' do @mail.body.decoded.should_not eql @raw_mail.body.decoded end it 'Must generate crypted text' do decrypted = @mail.proceed(configuration: Notifier.x509_configuration) decrypted.to_s.should eql @raw_mail.body.decoded end it 'must have valid state' do states = @mail.get_states states[:crypted].should eql true end end describe 'Incorrect' do it 'incorrect text' do add_config(false, true) mail = Notifier.fufu('<destination@foobar.com>', '<demo@foobar.com>') mail.body = mail.body.to_s.gsub(/[0-9]/, 'g') -> { mail.proceed(configuration: Notifier.x509_configuration) }.should raise_error DecodeError end end end
class ApplicationController < ActionController::Base def current_user respond_to do |format| format.html do # Delegate to Devise's #current_user super end format.json do @current_user ||= User.find_by(token: request.headers["Authorization"]) end end end def require_authentication return if current_user respond_to do |format| format.html do flash[:alert] = "You must be signed in to do that" redirect_to root_path end format.json do head :unauthorized end end end end
class Contact attr_accessor :first_name, :last_name, :email, :note attr_reader :id @@contacts = [] @@id = 0 # This method should initialize the contact's attributes def initialize(first_name, last_name, email, note = 'none') @first_name = first_name @last_name = last_name @email = email @note = note @id = @@id @@id += 1 # this way the next contact will get a different id end # This method should call the initializer, # store the newly created contact, and then return it def self.create(first_name, last_name, email, note) new_contact = Contact.new(first_name, last_name, email, note) @@contacts << new_contact return new_contact end # This method should return all of the existing contacts def self.all @@contacts end # This method should accept an id as an argument # and return the contact who has that id def self.find puts "Please enter contact ID:" query = gets.chomp.to_i @@contacts.each { |listing| return listing if listing.id == query } #inline arguments for .each method. Much more compact! Refer back when you inevitably mess up trying to do it later on. end # This method should allow you to specify # 1. which of the contact's attributes you want to update # 2. the new value for that attribute # and then make the appropriate change to the contact def update puts "Update Contact:" puts '[1] First Name' puts '[2] Last Name' puts '[3] Email' puts '[4] Note' puts 'Enter a number: ' update = gets.chomp.to_i if update == 1 puts "Please enter new value for First Name:" firstname_new = gets.chomp.to_s @first_name = firstname_new return @first_name puts "Changed First Name to #{@first_name}." end if update == 2 puts "Please enter new value for Last Name:" lastname_new = gets.chomp.to_s @last_name = lastname_new return @last_name puts "Changed Last Name to #{@last_name}." end if update == 3 puts "Please enter new value for Email:" email_new = gets.chomp.to_s @email = email_new return @email puts "Changed Email to #{@email}." end if update == 4 puts "Please enter new value for Note:" note_new = gets.chomp @note = note_new return @note puts "Changed Note to #{@note}." end end # This method should work similarly to the find method above # but it should allow you to search for a contact using attributes other than id # by specifying both the name of the attribute and the value # eg. searching for 'first_name', 'Betty' should return the first contact named Betty def self.find_by puts 'Locate contact by:' puts '[1] First Name' puts '[2] Last Name' puts '[3] Email' puts 'Enter a number: ' input = gets.chomp.to_i if input == 1 puts "Please enter contact's First Name:" search_first = gets.chomp.to_s @@contacts.each do |item| return item if item.first_name == search_first end end if input == 2 puts "Please enter contact's Last Name:" search_last = gets.chomp.to_s @@contacts.each do |item| return item if item.last_name == search_last end end if input == 3 puts "Please enter contact's Email:" search_email = gets.chomp.to_s @@contacts.each do |item| return item if item.email == search_email end end end # This method should delete all of the contacts def self.delete_all @@contacts = [] end def full_name "#{@first_name} #{@last_name}" end # This method should delete the contact # HINT: Check the Array class docs for built-in methods that might be useful here def delete @@contacts.delete(self) #I'm honestly just making an educated guess with this one. Or just a regular guess. end # Feel free to add other methods here, if you need them. #No. I refuse. end
class DateFields < ActiveRecord::BaseWithoutTable column :year, :string column :month, :string column :day, :string validates_format_of :year, :with => /^(19|20)\d\d$/ validates_format_of :month, :with => /^(1|2|3|4|5|6|7|8|9|10|11|12)$/ validates_format_of :day, :with => /\A((0|1|2)?[0-9]|3[01])\Z/ def blank? self.year.blank? && self.month.blank? && self.day.blank? end def to_date return nil unless valid? Date.new self.year.to_i, self.month.to_i, self.day.to_i end def self.from_date(date) if date DateFields.new :year => date.year, :month => date.month, :day => date.day else DateFields.new end end end
module Types class QueryType < Types::BaseObject field :user, [Types::UserType], null: true, description: 'A list of users' def user User.all end end end
# # Be sure to run `pod lib lint Crary.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'Crary' s.version = '0.6.2' s.summary = 'Croquis Library for iOS' s.homepage = 'https://github.com/croquiscom/Crary-iOS' s.license = 'MIT' s.author = { 'yamigo' => 'yamigo1021@gmail.com', 'sixmen' => 'sixmen@gmail.com' } s.source = { :git => "https://github.com/croquiscom/Crary-iOS.git", :tag => 'v0.6.2' } s.requires_arc = true s.platform = :ios, '8.0' s.ios.deployment_target = '8.0' s.resource_bundle = { 'Crary' => ['Pod/Assets/*.lproj'] } s.public_header_files = 'Pod/Classes/Crary.h', 'Pod/Classes/CraryDefine.h' s.source_files = 'Pod/Classes/Crary.{h,m}', 'Pod/Classes/Crary+Private.h', 'Pod/Classes/CraryDefine.h' s.subspec 'Util' do |ss| ss.source_files = 'Pod/Classes/Util/*.{h,m}', 'Pod/Classes/Util/*.swift' end s.subspec 'RestClient' do |ss| ss.private_header_files = 'Pod/Classes/RestClient/CraryRestClient+Private.h' ss.source_files = 'Pod/Classes/RestClient/*.{h,m}', 'Pod/Classes/RestClient/*.swift' ss.dependency 'Crary/Util' ss.dependency 'AFNetworking' ss.dependency 'DCKeyValueObjectMapping' ss.dependency 'ObjectMapper' ss.ios.library = 'z' end s.subspec 'Dialog' do |ss| ss.source_files = 'Pod/Classes/Dialog/*.{h,m}', 'Pod/Classes/Dialog/*.swift' end end
class PaymentTokensController < ApplicationController before_filter :authenticate_user_json def show result = authed_user.get_braintree_token if result[:status] == 'success' client_token = Braintree::ClientToken.generate( customer_id: result[:token] ) if client_token.present? render json: {status: 'success', token: client_token, status: :ok} else render json: {status: 'failed', error: 'Token is not present for this id', status: :not_found} end else render json: {status: 'failed', error: token.error} end end end
Metasploit::Model::Spec.shared_examples_for 'Reference' do # # Authority factories # authority_factory = "#{factory_namespace}_authority" # # Reference factoriess # obsolete_reference_factory = "obsolete_#{reference_factory}" url_reference_factory = "url_#{reference_factory}" context 'derivation' do subject(:reference) do FactoryGirl.build( reference_factory, :authority => authority, :designation => designation ) end context 'with authority' do let(:authority) do authority_with_abbreviation(abbreviation) end context 'with abbreviation' do context 'BID' do let(:abbreviation) do 'BID' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_bid_designation end it_should_behave_like 'derives', :url, :validates => false end context 'CVE' do let(:abbreviation) do 'CVE' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_cve_designation end it_should_behave_like 'derives', :url, :validates => false end context 'MSB' do let(:abbreviation) do 'MSB' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_msb_designation end it_should_behave_like 'derives', :url, :validates => false end context 'OSVDB' do let(:abbreviation) do 'OSVDB' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_osvdb_designation end it_should_behave_like 'derives', :url, :validates => false end context 'PMASA' do let(:abbreviation) do 'PMASA' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_pmasa_designation end it_should_behave_like 'derives', :url, :validates => false end context 'SECUNIA' do let(:abbreviation) do 'SECUNIA' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_secunia_designation end it_should_behave_like 'derives', :url, :validates => false end context 'US-CERT-VU' do let(:abbreviation) do 'US-CERT-VU' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_us_cert_vu_designation end it_should_behave_like 'derives', :url, :validates => false end context 'waraxe' do let(:abbreviation) do 'waraxe' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_waraxe_designation end it_should_behave_like 'derives', :url, :validates => false end context 'ZDI' do let(:abbreviation) do 'ZDI' end let(:designation) do FactoryGirl.generate :metasploit_model_reference_zdi_designation end it_should_behave_like 'derives', :url, validates: false end end end end context 'factories' do context reference_factory do subject(reference_factory) do FactoryGirl.build(reference_factory) end it { should be_valid } its(:authority) { should_not be_nil } its(:designation) { should_not be_nil } its(:url) { should_not be_nil } end context obsolete_reference_factory do subject(obsolete_reference_factory) do FactoryGirl.build(obsolete_reference_factory) end it { should be_valid } its(:authority) { should_not be_nil } its(:designation) { should_not be_nil } its(:url) { should be_nil } end context url_reference_factory do subject(url_reference_factory) do FactoryGirl.build(url_reference_factory) end it { should be_valid } its(:authority) { should be_nil } its(:designation) { should be_nil } its(:url) { should_not be_nil } end end context 'mass assignment security' do it { should allow_mass_assignment_of(:designation) } it { should allow_mass_assignment_of(:url) } end context 'search' do context 'attributes' do it_should_behave_like 'search_attribute', :designation, :type => :string it_should_behave_like 'search_attribute', :url, :type => :string end end context 'validations' do subject(:reference) do FactoryGirl.build( reference_factory, :authority => authority, :designation => designation, :url => url ) end context 'with authority' do let(:authority) do FactoryGirl.create(authority_factory) end context 'with designation' do let(:designation) do FactoryGirl.generate :metasploit_model_reference_designation end context 'with url' do let(:url) do FactoryGirl.generate :metasploit_model_reference_url end it { should be_valid } end context 'without url' do let(:url) do nil end it { should be_valid } end end context 'without designation' do let(:designation) do nil end context 'with url' do let(:url) do FactoryGirl.generate :metasploit_model_reference_url end it { should be_invalid } it 'should record error on designation' do reference.valid? reference.errors[:designation].should include("can't be blank") end it 'should not record error on url' do reference.valid? reference.errors[:url].should be_empty end end context 'without url' do let(:url) do nil end it { should be_invalid } it 'should record error on designation' do reference.valid? reference.errors[:designation].should include("can't be blank") end it 'should not record error on url' do reference.valid? reference.errors[:url].should be_empty end end end end context 'without authority' do let(:authority) do nil end context 'with designation' do let(:designation) do FactoryGirl.generate :metasploit_model_reference_designation end let(:url) do nil end it { should be_invalid } it 'should record error on designation' do reference.valid? reference.errors[:designation].should include('must be nil') end end context 'without designation' do let(:designation) do nil end context 'with url' do let(:url) do FactoryGirl.generate :metasploit_model_reference_url end it { should be_valid } end context 'without url' do let(:url) do nil end it { should be_invalid } it 'should record error on url' do reference.valid? reference.errors[:url].should include("can't be blank") end end end end end context '#derived_url' do subject(:derived_url) do reference.derived_url end let(:reference) do FactoryGirl.build( reference_factory, :authority => authority, :designation => designation ) end context 'with authority' do let(:authority) do FactoryGirl.create( authority_factory ) end context 'with blank designation' do let(:designation) do '' end it { should be_nil } end context 'without blank designation' do let(:designation) do '31337' end it 'should call Metasploit::Model::Authority#designation_url' do authority.should_receive(:designation_url).with(designation) derived_url end end end context 'without authority' do let(:authority) do nil end let(:designation) do nil end it { should be_nil } end end context '#authority?' do subject(:authority?) do reference.authority? end let(:reference) do FactoryGirl.build( reference_factory, :authority => authority ) end context 'with authority' do let(:authority) do FactoryGirl.create(authority_factory) end it { should be_true } end context 'without authority' do let(:authority) do nil end it { should be_false } end end end
class CreateContacts < ActiveRecord::Migration def change create_table :contacts do |t| t.string :email t.string :contact_info t.string :demographics t.string :social_profiles t.string :primary_photo t.timestamps null: false end end end
module UniqueSequence class Generator @@SUM = 15 @@RANGE = (1..9) def get_next(sequence = nil) sequence ? get_next_from_sequence(sequence) : [1] end def get_next_from_sequence(sequence) to_add = sequence[-1] == sequence[-2] ? sequence[-1] + 1 : sequence[-1] sum = sequence.inject(:+) if sequence == [9] sequence = nil elsif sum + to_add <= @@SUM sequence << to_add elsif sequence[-1] == 9 || sum == 15 sequence = sequence[0..-2] sequence[-1] += 1 else sequence[-1] += 1 end sequence end def get_all_valid sequences = [] sequence = get_next while sequence sequences << sequence if Checker.check(sequence) sequence = get_next(sequence) end sequences end end end
#!/usr/bin/env ruby require_relative './test_helper' require 'brewed' class String_Tests < MiniTest::Test def test_safe_strip!() assert_equal 'this is a test', ' this is a test '.safe_strip!, "safe_strip! actually performs strip!" assert_equal 'this is a test', ' this is a test'.safe_strip!, "safe_strip! with only leading actually performs strip!" assert_equal 'this is a test', 'this is a test '.safe_strip!, "safe_strip! with only trailing actually performs strip!" assert_equal 'this is a test', 'this is a test'.safe_strip!, "safe_strip! returns self rather than nil" assert_equal 'none', 'none'.safe_strip!, "safe_strip! returns self when there is no whitespace" end def test_safe_gsub!() assert_equal 'this_is_a_test', 'this is a test'.safe_gsub!(/\s+/, '_'), "safe_gsub! actually performs gsub!" assert_equal 'this_is_a_test', 'this_is_a_test'.safe_gsub!(/\s+/, '_'), "safe_gsub! returns self rather than nil" end end
# 读取文件内容的流程如下 # 1 打开文件。 # 2 读取文件的文本数据。 # 3 输出文件的文本数据。 # 4 关闭文件。 filename = ARGV[0] file = File.open(filename) # 1 text = file.read # 2 print text # 3 file.close # 4 # 第 1 行,将命令行参数 ARGV[0] 赋值给变量 filename。也就是说,filename 表示希望 读取的文件名 # 第 2 行,File.open(filename) 表示打开名为 filename 的文件,并返回读 取该文件所需的对象 # 读取该文件所需的对象”实际在第 3 行使用。在这里,read 方法读取文本数据,并将读取到的数据赋值给 text 变量 # 第 4 行的代码会输出 text 的文本数据 # 程序执行最后一段代码 的 close 方法。这样,就可以关闭之前打开的文件了。 # 如果只是读取文件内容,直接使用 read 方法会使程序更简单 filename = ARGV[0] text = File.read(filename) print text # 如果不使用变量,一行代码就可以搞定 print File.read(ARGV[0]) # 刚才的程序有如下的问题: # ● 一下子读取全部文件内容会很耗时 # ● 读取的文件内容会暂时保存在内存中,遇到大文件时,程序有可能因此而崩溃 # 如一个文件有 100 万行数据,我们只希望读取最初的几行。这种情况下,如果程序不管 三七二十一读取文件的全部内容,无论从时间还是从内存角度来讲,都是严重的浪费。 # 因此,我们只能放弃“读取文件全部内容”的做法 # 读取全部数据: file.read # 逐行读取数据: file.each_line # 将之前代码改为逐行读取并输出这样,只需要具备当前行数据大小的内存就足够了。 filename = ARGV[0] file = File.open(filename) file.each_line do |line| print line end file.close # each_line 方法很像第 2 章介绍的 each 方法。each 方法是用于逐个处理数组元素,顾名思义,each_line 方法就是对文件进行逐行处理。 # 因此,程序会逐行读取文件的内容,使用 print 方法输出该行的文件内容 line,直到所有行的内容输出完为止。
# == Schema Information # # Table name: locations # # id :integer not null, primary key # name :string(255) # description :string(255) # x :decimal(8, 1) # y :decimal(8, 1) # z :integer # width :integer # height :integer # section_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'spec_helper' describe Location do #attr_accessible :height, :name, :width, :x, :y, :z # the (before) line will instance the variable for every (describe methods) #before { @item = Item.new()} before do @section = FactoryGirl.create(:section) @location = FactoryGirl.build(:location,section_id:@section.id ) end #the (subject)line declare the variable that is use in all the test subject { @location } #theme info it { @location.should respond_to(:name) } it { @location.should respond_to(:description) } it { @location.should respond_to(:section_id) } it { @location.should respond_to(:height)} it { @location.should respond_to(:width)} it { @location.should respond_to(:x) } it { @location.should respond_to(:y) } it { @location.should respond_to(:z) } it { @location.should be_valid } ############### #test validation section id is present ############### describe " section_id ",tag_section_id:true do it "should be valid " do @location.section_id == @section.id end end ############### #test validation section id is not valid ############### describe "should not be valid item id ",tag_section_id:true do let(:location_not_section_id){FactoryGirl.build(:location,section_id:-1 )} it { location_not_section_id.should_not be_valid } end ############### #test validation - height ############### describe "when height" , tag_height: true do context "is nil " do before {@location.height = nil } it {should_not be_valid} end context " is not integer '1.1' " do before {@location.height = 1.1 } it {should_not be_valid} end context " is number and integer " do before {@location.height = 1 } it {should be_valid} end end ############### #test validation - width ############### describe "when width" , tag_width: true do context "is nil " do before {@location.width = nil } it {should_not be_valid} end context " is not integer '1.1' " do before {@location.width = 1.1 } it {should_not be_valid} end context " is number and integer " do before {@location.width = 1 } it {should be_valid} end end ############### #test validation - x ############### describe "when x" , tag_x: true do context "is nil " do before {@location.x = nil } it {should_not be_valid} end context " is not integer '1.1' " do before {@location.x = 1.1 } it {should be_valid} end context " is number and integer " do before {@location.x = 1 } it {should be_valid} end end ############### #test validation - y ############### describe "when y" , tag_y: true do context "is nil " do before {@location.y = nil } it {should_not be_valid} end context " is not integer '1.1' " do before {@location.y = 1.1 } it {should be_valid} end context " is number and integer " do before {@location.y = 1 } it {should be_valid} end end ############### #test validation - y ############### describe "when z" , tag_z: true do context "is nil " do before {@location.z = nil } it {should_not be_valid} end context " is not integer '1.1' " do before {@location.z = 1.1 } it {should_not be_valid} end context " is number and integer " do before {@location .z = 1 } it {should be_valid} end end ############### #test function - id_and_location_section ############### describe "when the function id_and_location_section" , tag_function: true do context "get id and location and section" do before do @name = "location_name" @location.name = @name @location.save! @id = @location.id @section_id = @location.section_id @section_name = @location.section.name end it "should print the id and location and section " do #puts @location.id_and_location_section #@item.id_and_item.should == @id.to_s+". "+@name @location.id_and_location_section.should == "Location: "+@id.to_s+". "+@name+" --Section: "+@section_id.to_s+". "+@section_name end end end end
class CoordinateCalculator attr_reader :x, :y, :direction def initialize(first_input, instructions) @x = first_input[:x] @y = first_input[:y] @direction = first_input[:direction] @instructions = instructions end def calculate_instructions split_instructions = @instructions.split('') split_instructions.each do |ins| if ins == 'L' l_move elsif ins == 'R' r_move else g_move end end end private def g_move if @direction == 'N' || @direction == 'S' @y = g_rules[format_direction(@direction)] else @x = g_rules[format_direction(@direction)] end end def r_move @direction = r_rules[format_direction(@direction)].to_s.upcase end def l_move @direction = l_rules[format_direction(@direction)].to_s.upcase end def g_rules {n: @y + 1, s: @y - 1, e: @x + 1, w: @x - 1} end def r_rules {n: :e, s: :w, e: :s, w: :n} end def l_rules {n: :w, s: :e, e: :n, w: :s} end def instruction_rules {G: g_move, R: r_move, L: l_move} end def format_direction(direction) direction.downcase.to_sym end end
RSpec.describe HerokuStatus do subject { HerokuStatus } describe "Version" do it "has a version number" do expect(HerokuStatus::VERSION).not_to be nil end end describe "#current_status" do describe "No issues exist" do before do current_status_response = { "status" => { "Production" => "green", "Development" => "green" }, "issues" => [] } @current_status_req = stub_request(:get, "https://status.heroku.com/api/v3/current-status"). to_return(status: 200, body: current_status_response.to_json, headers: {}) end it "should return all green statuses" do subject.current_status expect(@current_status_req).to have_been_requested end end end describe "#issues" do # TODO end describe "#issue" do describe "Valid issue exists" do before do issue_response = { "id": 6, "created_at": "2009-10-23T18:49:49.000Z", "updated_at": "2012-06-22T23:41:10.468Z", "title": "Limited app interruption", "resolved": true, "upcoming": false, "status_dev": "green", "status_prod": "green", "href": "https://status.heroku.com/api/v3/issues/6", "full_url": "https://status.heroku.com/incidents/6", "updates": [ { "id": 10, "created_at": "2009-10-23T20:20:46.000Z", "updated_at": "2012-06-22T23:41:05.896Z", "incident_id": 6, "update_type": "resolved", "contents": "The instances affected by the EC2 hardware failure were in our database cluster. These instances have been restored, and database migrated with no data loss. \n\nThe recovery took slightly longer than expected, taking all necessary precautions to prevent data loss.\n\nIndividual applications are coming back online now.\n", "title": nil, "status_dev": "green", "status_prod": "green" }, { "id": 9, "created_at": "2009-10-23T18:49:49.000Z", "updated_at": "2012-06-22T23:41:05.988Z", "incident_id": 6, "update_type": "issue", "contents": "An Amazon hardware failure is impacting 187 Heroku applications right now.\nOur cloud has identified the failure, and is automatically brining the applications up on new instances.\nWe expect full restoration of service in <15 minutes.", "title": nil, "status_dev": "green", "status_prod": "yellow" } ] } @issue_req = stub_request(:get, "https://status.heroku.com/api/v3/issues/6"). to_return(status: 200, body: issue_response.to_json, headers: {}) end it "should return the issue" do subject.issue(6) expect(@issue_req).to have_been_requested end end describe "Invalid issue" do before do issue_response = { status: "error", message: "An issue occured while fetching the issue.", error_code: 500, body: "More info..." } @issue_req = stub_request(:get, "https://status.heroku.com/api/v3/issues/0"). to_return(status: 500, body: issue_response.to_json, headers: {}) end it "should throw a 500" do subject.issue(0) expect(@issue_req).to have_been_requested end end end end
#!/usr/bin/ruby require 'euler_helper.rb' functions = [:triangle, :square, :penta, :hexa, :hepta,:octa] def hsel h, key r = h.clone r.delete key r end def triangle n n*(n+1)/2 end def square n n ** 2 end def penta n n*(3*n-1)/2 end def hexa n n*(2*n-1) end def hepta n n*(5*n-3)/2 end def octa n n*(3*n-2) end def filt arr, target upper_bound = (target.digits[2...4].join.to_i + 1) * 100 lower_bound = (target.digits[2...4].join.to_i) * 100 arr.select {|n| (n > lower_bound) && (n < upper_bound)} end def solve numbers, functions, results, init ret = nil results = results.clone fun = functions.shift return nil unless fun if init to_iter = filt(numbers[fun], init) else to_iter = numbers[fun] end raise 'Error!' if functions.empty? && results.size < 2 if functions.empty? numlast = to_iter.detect {|n| n.digits[2...4] == results.first.digits[0...2] } return (results + [numlast]) if numlast return nil else to_iter.each do |num| functions.each do |f| r = solve(hsel(numbers, fun), ([f] + (functions-[f])), results + [num], num) ret = r unless r.nil? end end end ret end values = functions.inject({}) {|acc, fun| acc[fun] = (1..150).map{|n| send(fun, n)}.select {|n| n >= 1000 && n <= 9999 };acc } puts values.values.map(&:size).inspect values.each {|k,v| } functions.each do |f| (functions-[f]).each { |f2| values[f] -= values[f2] } end benchmark do puts sum(solve(values, functions, [], nil)) end
require "base64" class Comment < ActiveRecord::Base attr_accessor :subscribers_ids belongs_to :commentable, polymorphic: true belongs_to :author, polymorphic: true has_many :attachments, as: :attachable, dependent: :destroy serialize :account_users_ids serialize :company_users_ids after_create :notify before_validation :complete_attachment_fields before_create :set_subscribers validates_presence_of :message, :author_type, :author_id, :commentable_id, :commentable_type def account commentable.account end def company return nil if commentable.company.nil? commentable.company end def account_subscribers return [] if account_users_ids.nil? User.find account_users_ids end def author_name return author.email if author.name.nil? author.name end def commentable_contact commentable.contact || nil end def company_subscribers return [] if company_users_ids.nil? Contact.find company_users_ids end def email_reply_to # lo que va despues del arroba host = "app.folio.cl" mailbox = "#{object_name}-#{commentable.id}-#{encoded_account_id}" "#{mailbox}@#{host}" end def has_attachments? attachments.any? end def object_name commentable.class.to_s.downcase end def account_id commentable.account_id end def account_emails commentable.account.users_emails_array end def default_subscribers [author, commentable_contact].compact end def encoded_account_id Base64.strict_encode64(account_id.to_s) end def last_comment commentable.last_comment end def last_commentable_subscribers return default_subscribers if last_comment.nil? last_comment.subscribers end def possible_subscribers company_contacts = company.contacts account_users = account.users account_users + company_contacts end def notification_email_subject object = commentable object_name = commentable.class.model_name.human.titleize # Translated "[Nuevo Comentario] #{object_name} ##{object.number} - #{object.subject} - #{object.company.name}" end def self.new_from_email(email) return false if email.nil? # Si no hay correo no hacemos nada comment_metadata = metadata_from_email_to_field(email) comment_author = comment_author_from_email(email, comment_metadata[:account_id]) comment_metadata.delete(:account_id) # El comment no tiene este campo # Si no hay author no hacemos nada, puede que no haya # porque no se encontró una cuenta valida return false unless comment_author # Tenemos que crear el comentario desde el objeto (Factura por ahora) object = comment_metadata[:commentable_type].constantize.find(comment_metadata[:commentable_id]) comment = object.comments.new comment_metadata.merge comment_author comment.message = email.body.html_safe comment.from_email = true if email.attachments.any? email.attachments.each do |attachment| comment.attachments.new(resource: attachment) end end comment end def subscribers list = Array.new list << account_subscribers list << company_subscribers unless private? list.flatten end def subscribers_emails subscribers.map {|s| s.email } end def self.new_from_system(hash={}) return false if hash.nil? comment = new(hash) comment.author_id = comment.commentable.account.owner_id comment.author_type = "User" comment end private def self.metadata_from_email_to_field(email) ary = email.to.first[:token].split(/-/) ary[0] = ary[0].titleize ary[2] = decode_account_id(ary[2]) keys = [:commentable_type, :commentable_id, :account_id] comment_metadata = Hash.new ary.each_with_index {|el,index| comment_metadata[keys[index]] = el } comment_metadata end def self.comment_author_from_email(email, account_id) account = Account.find(account_id) return false if account.nil? author = Hash.new() user = account.users.find_by(email: email.from[:email]) if user author[:author_id] = user.id author[:author_type] = user.class.to_s return author end contact = account.contacts.find_by(email: email.from[:email]) if contact author[:author_id] = contact.id author[:author_type] = contact.class.to_s return author end return false end def self.decode_account_id(b64_string) Base64.strict_decode64(b64_string).to_i end def notify return if subscribers_emails.empty? CommentMailer.delay.comment_notification(id) end def set_subscribers self.subscribers_ids = set_subscribers_from_email if from_email? return if subscribers_ids.nil? self.account_users_ids = subscribers_ids[:account] self.company_users_ids = subscribers_ids[:company] unless private? end def set_subscribers_from_email subscribers_ids = Hash.new subscribers_ids[:account] = last_comment.account_users_ids subscribers_ids[:company] = last_comment.company_users_ids subscribers_ids end def complete_attachment_fields return unless attachments.any? attachments.each do |att| att.author_id ||= author_id att.author_type ||= author_type att.account_id ||= account.id end end end
require 'test/unit' require 'yaml' module WLang class YAMLAssumptionTest < Test::Unit::TestCase def test_it_supports_quotes_as_expected text = "---\nauthor:\n \"Bernard Lambeau\"\n" x = YAML::load(text) assert_equal({'author' => "Bernard Lambeau"}, x) end end # class YAMLAssumptionTest end # module WLang
class Api::V1::EventsController < ApplicationController def index @events = Event.all render json: @events, status: 200 end def show find_event render json: @event, status: 200 end def destroy @event.destroy end private def event_params params.permit(:cause, :style, :location, :date, :time, :users) end def find_event @event = Event.find(params[:id]) end end
# encoding: UTF-8 require 'rosette/preprocessors' java_import 'com.ibm.icu.util.ULocale' java_import 'com.ibm.icu.text.BreakIterator' module Rosette module Preprocessors class BreakPreprocessor < Preprocessor autoload :Configurator, 'rosette/preprocessors/break-preprocessor/configurator' DEFAULT_LOCALE = :en def self.configure config = Configurator.new yield config if block_given? new(config) end def process_translation(translation) new_trans = process_string( translation.translation, translation.locale ) translation.class.from_h( translation.to_h.merge(translation: new_trans) ) end private def process_string(string, locale) segments = segment_text( string, locale || DEFAULT_LOCALE.to_s ) segments.join(delimiter) end def delimiter if configuration.has_delimiter? configuration.delimiter else '' end end def segment_text(text, locale) brkiter = get_brkiter_instance(locale) brkiter.setText(text) start = brkiter.first segments = [] until (stop = brkiter.next) == BreakIterator::DONE segments << text[start...stop] start = stop end segments end def get_brkiter_instance(locale) ulocale = ULocale.new(locale.to_s) case configuration.boundary_type when :word BreakIterator.getWordInstance(ulocale) when :line BreakIterator.getLineInstance(ulocale) when :sentence BreakIterator.getSentenceInstance(ulocale) end end def method_for(object) # determine if the object implements the translation interface is_trans = object.respond_to?(:translation) && object.respond_to?(:locale) && object.class.respond_to?(:from_h) && object.respond_to?(:to_h) if is_trans :process_translation end end end end end
require 'spec_helper' describe OutgoingMessageProcessor do let(:publisher) { double(:publisher) } let(:processor) { OutgoingMessageProcessor.new publisher: publisher } it 'publishes outgoing messages' do message = double(:message) message.should_receive(:to_s).and_return('<Email Message>') publisher.should_receive(:publish).with('<Email Message>') processor.send [message] end end
require_relative '../../lib/before_and_after' class ClassWithFalseInvariantWithInitialize attr_accessor :x invariant { pp "Invariant" ;x > 2 } def initialize self.x = 1 end end
# encoding: utf-8 require 'faraday' class PlOperatorDetector class WJakiejSieci def initialize @conn = Faraday.new(:url => 'http://www.wjakiejsieci.pl/') do |faraday| faraday.request :url_encoded faraday.adapter Faraday.default_adapter faraday.headers["User-Agent"] = CustomUserAgent.get_user_agent end end def process(number) prefix = number.size == 11 ? "+#{number[0..1]}" : "+48" pnumbr = number.size == 11 ? number[2..12] : number rsp = @conn.post '/', { prefix: prefix, phone: pnumbr } { number: number }.merge process_response(rsp.body) end private def process_response(response) rslt = { } match_opstr = response.match(/Operator: <strong>(.{2,20})<\/strong><\/p>/) if match_opstr && match_opstr[1] rslt[:operator] = match_opstr[1] else raise PlOperatorDetector::ProcessingError, "Could not process given number" end rslt end end end
class OldResultTaker def initialize(client, folder_name, project_folder) @results_dao = ResultsDao.new(client) @old_resulst_collector = OldResultsCollector.new @folder_name = folder_name @project_folder = project_folder end def get_old_res project_folder_path = Dir.home + @project_folder Dir.chdir(project_folder_path) Dir.foreach(@folder_name) do |file| matches = @old_resulst_collector.collect_results(@folder_name + file) if File.file?(@folder_name + file) save_in_db(matches) if !matches.nil? end end private def save_in_db(matches) matches.each do |match| @results_dao.insert_matches_in_db(match) end end end
action :install do g = gem_package new_resource.name do gem_binary Sensu::Helpers.gem_binary version new_resource.version source new_resource.source options new_resource.options end new_resource.updated_by_last_action(g.updated_by_last_action?) end action :upgrade do g = gem_package new_resource.name do gem_binary Sensu::Helpers.gem_binary version new_resource.version source new_resource.source options new_resource.options action :upgrade end new_resource.updated_by_last_action(g.updated_by_last_action?) end action :remove do g = gem_package new_resource.name do gem_binary Sensu::Helpers.gem_binary version new_resource.version action :remove end new_resource.updated_by_last_action(g.updated_by_last_action?) end
class Store::AdressesController < StoreController load_and_authorize_resource def geocode @adress.update_columns(lat: params[:adress][:lat], lng: params[:adress][:lng], google_address: true) respond_to do |format| format.json { render :json => @adress } end end private def adress_params params.require(:adress).permit(:lat,:lng) end end
FactoryBot.define do factory :transfer do amount_cents { Random.rand(1000..30000) } user company end end
require 'data_search/organization_search' require 'data_search/user_search' require 'data_search/ticket_search' require 'rspec/json_expectations' describe DataSearch::OrganizationSearch do describe 'search organization by _id' do subject(:organization_by_id) do DataSearch::OrganizationSearch.find_elements_include_association(:_id, id)[0] end context 'valid id value' do let(:id) { :'101' } it 'should get the organization' do expect(organization_by_id).to include_json( { _id: 101, url: 'http://initech.zendesk.com/api/v2/organizations/101.json', external_id: '9270ed79-35eb-4a38-a46f-35725197ea8d', name: 'Enthaze', domain_names: [ 'kage.com', 'ecratic.com', 'endipin.com', 'zentix.com' ], created_at: '2016-05-21T11:10:28 -10:00', details: 'MegaCorp', shared_tickets: false, tags: %w[ Fulton West Rodriguez Farley ] } ) end context 'associated users' do it 'should have users' do expect(organization_by_id[:users].count).to eq 4 end it 'each user should have all attrs' do expect(organization_by_id[:users][0]).to eq( { _id: 5, active: true, alias: 'Mr Ola', created_at: '2016-06-12T08:49:19 -10:00', email: 'olapittman@flotonic.com', external_id: '29c18801-fb42-433d-8674-f37d63e637df', last_login_at: '2013-07-03T06:59:27 -10:00', locale: 'zh-CN', name: 'Loraine Pittman', organization_id: 101, phone: '9805-292-618', role: 'admin', shared: false, signature: "Don't Worry Be Happy!", suspended: false, tags: %w[Frizzleburg Forestburg Sandston Delco], timezone: 'Monaco', url: 'http://initech.zendesk.com/api/v2/users/5.json', verified: false } ) end end context 'associated tickets' do it 'should have tickets' do expect(organization_by_id[:tickets].count).to eq 4 end it 'each ticket should have all attrs' do expect(organization_by_id[:tickets][0]).to eq( { _id: 'b07a8c20-2ee5-493b-9ebf-f6321b95966e', assignee_id: 17, created_at: '2016-03-21T11:18:13 -11:00', description: 'Laborum exercitation officia nulla in. Consequat et commodo fugiat velit magna sunt mollit.', # rubocop:disable Layout/LineLength due_at: '2016-08-04T12:30:08 -10:00', external_id: 'ca4452fc-b24d-4e06-a752-b15ee3fc42bb', has_incidents: true, organization_id: 101, priority: 'low', status: 'hold', subject: 'A Drama in Portugal', submitter_id: 50, tags: ['Ohio', 'Pennsylvania', 'American Samoa', 'Northern Mariana Islands'], type: 'question', url: 'http://initech.zendesk.com/api/v2/tickets/b07a8c20-2ee5-493b-9ebf-f6321b95966e.json', via: 'web' } ) end end end end end
class Brie attr_reader :quality, :days_remaining def initialize(quality, days_remaining) @quality = quality @days_remaining = days_remaining end def tick @days_remaining -= 1 return if @quality >= 50 @quality += 1 @quality += 1 if @days_remaining <= 0 && @quality < 50 end end
class Event < ApplicationRecord belongs_to :event_venue has_many :ticket_types validate :start_date_cannot_be_in_the_past , :no2eventsinthesamevenue def start_date_cannot_be_in_the_past if self.start_date < self.created_at errors.add(:start_date, "can't be in the past") end end def no2eventsinthesamevenue obs = Event.where("start_date== ? and event_venue_id== ?",self.start_date, self.event_venue_id) if obs[1]!= nil errors.add(:start_date, "cant be the same") end end end
Rails.application.routes.draw do devise_for :admins, :controllers => { :registrations => "registrations" } mount RailsAdmin::Engine => '/admin', as: 'rails_admin' root 'application#home' get 'portfolio' => 'projects#index', as: :portfolio resources :projects, only: [:show] get 'skills' => 'skills#index', as: :skills get 'contact' => 'contacts#index', as: :contact resources :messages, only: [:create] end
class AdminUsersController < ApplicationController before_action :authenticate_admin! def index @users = User.all end def show @user = User.find(params[:id]) @hobbies = @user.hobbies end end
class Address include Mongoid::Document belongs_to :user, index: true field :street_number, :type => String field :street_address, :type => String field :appt_number, :type => String field :city, :type => String field :postal_code, :type => String field :province, :type => String field :default, :type => Boolean index({ _id:1 }, { unique: true, name:"id_index" }) end
FactoryBot.define do factory :shortened_url do original_url 'http://github.com' end end
class Book < ActiveRecord::Base validates :title, presence: true, uniqueness: {scope: :user_id, message: "in use by another book in your collection"} belongs_to :user has_many :book_authors has_many :authors, through: :book_authors has_many :book_genres has_many :genres, through: :book_genres has_many :comments def self.borrowable(current_user) where("user_id != ? AND status = ?", current_user.id, "available").order(:title) end def self.returnable(current_user) where({borrower: current_user.id, status: "borrowed"}).order(:title) end def borrowed_by? self.status == "borrowed" ? User.find(self.borrower) : false end def available?(current_user) self.status == "available" && self.user_id != current_user.id && self.borrower.nil? end def return_book self.update(status: "available", borrower: nil) self.save end def borrow_book(current_user) self.update(status: "borrowed", borrower: current_user.id) self.save end def authors_attributes=(author_attributes) author_attributes.values.each do |author_details| if author_details[:name].strip != "" author = Author.find_or_create_by(name: author_details[:name].titleize) self.book_authors.build(author: author) end end end def genres_attributes=(genre_attributes) genre_attributes.values.each do |genre_details| if genre_details[:name].strip != "" genre = Genre.find_or_create_by(name: genre_details[:name].titleize) self.book_genres.build(genre: genre) end end end end
class Complement #KEYS ARE DNA and VALUES ARE RNA COMPLEMENTS = {'G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U' } def self.of_dna(rna) return_string = "" rna.split("").each do |l| if COMPLEMENTS[l] return_string += COMPLEMENTS[l] else raise ArgumentError.new("Only CGTA are allowed") end end return_string end def self.of_rna(dna) return_string = "" dna.split("").each do |l| if COMPLEMENTS.key(l) return_string += COMPLEMENTS.key(l) else raise ArgumentError.new("Only GCAU are allowed") end end return_string end end #puts Complement.of_dna('U')
$: << File.dirname( __FILE__) require 'test_runner' require 'rubygems' require 'bundler/setup' require 'parallel' require 'yaml' # Edit the browser yaml file to specify which os/browsers you want to use # You can use multiple files and specify which to use at runtime browser_file = "browsers.yml" @browsers = YAML.load_file(browser_file)[:browsers] desc "Run all features against all browsers in parallel" task :qunit_sauce do year, month, day, time = Time.now.strftime("%Y,%m,%d,%H%M%S").split(",") dir = "reports/#{year}/#{month}/#{day}" reportdir = "#{dir}/#{time}" FileUtils::mkdir_p(reportdir) Parallel.map(@browsers, :in_threads => @browsers.size) do |browser| begin puts "Running with: #{browser.inspect}" ENV['SELENIUM_BROWSER_OS'] = browser[:os] ENV['SELENIUM_BROWSER_NAME'] = browser[:name] ENV['SELENIUM_BROWSER_VERSION'] = browser[:version] ENV['SELENIUM_REPORT_FILENAME'] = "#{dir}/#{year}-#{month}-#{day}-#{browser[:os]}_#{browser[:name]}_#{browser[:version]}.html".gsub(/\s/, "_").gsub("..", ".") ENV['REPORT_DIR'] = "#{reportdir}" runner = TestRunner.new(browser[:os], browser[:name], browser[:version]) rescue RuntimeError => e puts "Error while running rake task" puts e end end finalreport = "" Dir.foreach("#{File.dirname( __FILE__)}/#{reportdir}") do |file| next if file == "." or file == ".." or file.include? ".svn" File.open("#{File.dirname( __FILE__)}/#{reportdir}/#{file}", "r") do |f| f.each {|line| finalreport += "#{line}\n" } end end puts "Results:\n" + finalreport unless finalreport == "" end task :default => [:qunit_sauce]
class ApplicationController < ActionController::Base protect_from_forgery with: :exception helper_method :logged_in? def logged_in? session[:login] end private def authenticate login = authenticate_or_request_with_http_basic do |username, password| username == "Berry" && password == "12345" end session[:login] = login end def do_logout session[:login] = nil end end
require 'test_helper' class ListTest < ActiveSupport::TestCase test "no debe guardar una Lista sin nombre" do lista = List.new assert_not lista.save,"Se guardo una Lista sin nombre" end test "No debe guardar si la URL ya existe" do lista_uno = List.new lista_uno.URL = 'prueba url' lista_uno.save lista_dos = List.new lista_dos.URL = 'prueba url' assert lista_dos.invalid? end test "Debe guardar una lista con datos de URL" do lista = List.new lista.URL = 'funca' assert lista.save ,"El ciente valido no se ha guardado " end end
require 'test_helper' class CategoriesControllerTest < ActionController::TestCase def setup @category = Category.create(name: "productivity") @user = User.create(firstname: "Brad", lastname: "Harris", email: "bharris@thinmanager.com", company: "ABC Company", street: "123 Main Street", city: "Springfield", state: "OH", zipcode: 12345, phone: "123-456-0987", password: "password", admin: true) @user2 = User.create(firstname: "Bill", lastname: "Smith", email: "bsmith@thinmanager.com", company: "TM Company", street: "123 Main Street", city: "Springfield", state: "OH", zipcode: 12345, phone: "123-456-0987", password: "password", admin: false) end test "should get categories index" do session[:user_id] = @user2.id #non admin logged in get :index assert_response :success end test "should get new" do session[:user_id] = @user.id #admin logged in get :new assert_response :success end test "should get show" do session[:user_id] = @user2.id #non admin logged in get(:show, {'id' => @category.id}) assert_response :success end test "should redirect creat when admin not logged in" do session[:user_id] = @user2.id #non admin logged in assert_no_difference 'Category.count' do post :create, category: { name: "productivity" } end assert_redirected_to categories_path end end
class LocationsController < BaseController before_filter :authenticate_user! # GET /locations/1 # GET /locations/1.json def show get_locations end private def get_locations country_code = params[:id] country = Country.where(country_code: country_code).first if country locations = [] country.location_groups.each do |location_group| locations.concat location_group.locations end return render json: locations else return not_found! end end end
class CreateCareers < ActiveRecord::Migration[5.2] def change create_table :careers,comment:Career.model_name.human do |t| t.references :engineer, foreign_key: true t.references :skill,foreing_key: true t.string :description, comment:Career.human_attribute_name("description") t.date :career_from, comment:Career.human_attribute_name("career_from") t.string :career_at, comment:Career.human_attribute_name("career_at") t.timestamps end end end
class Ticket < ApplicationRecord belongs_to :user, optional: true belongs_to :event before_save :set_total_price def self.startsbefore_endsafter(arrival, departure) where('starts_at < ? AND ends_at > ?', arrival, departure) end def self.starts_during(arrival, departure) where('starts_at > ? AND starts_at < ?', arrival, departure) end def self.ends_during(arrival, departure) where('ends_at > ? AND ends_at < ?', arrival, departure) end def self.during(arrival, departure) arrival = arrival.change(hour: 14, min: 00, sec: 00) departure = departure.change(hour: 11, min: 00, sec: 00) startsbefore_endsafter(arrival, departure) .or(starts_during(arrival, departure)) .or(ends_during(arrival, departure)) end def self.sametime_events(arrival, departure) during(arrival, departure).pluck(:event_id) end def self.non_sametime_events(arrival, departure) end def set_total_price self.price = event.price * amount end end
class Project < ActiveRecord::Base validates :name, presence: true validates :name, length: { maximum: 15 } has_many :tasks end
require_relative '../PolyTreeNode/lib/00_tree_node' require 'byebug' class KnightPathFinder GRID_SIZE = 8 DELTA = [[1,2], [2,1], [2,-1], [1,-2], [-1,-2], [-2,-1], [-2, 1], [-1, 2]] def self.in_bounds?(x, y) x.between?(0, GRID_SIZE - 1) && y.between?(0, GRID_SIZE - 1) end def self.valid_moves(pos) possible_moves = [] DELTA.each do |(delta_x, delta_y)| new_x = pos.first + delta_x new_y = pos.last + delta_y possible_moves << [new_x, new_y] end possible_moves.select do |(x, y)| self.in_bounds?(x, y) end end attr_accessor :position, :visited_positions, :root_node def initialize(pos) raise "Position is out of bounds" unless KnightPathFinder.in_bounds?(*pos) @position = pos @visited_positions = [pos] @root_node = build_move_tree end def find_path(end_pos) target_node = root_node.dfs(end_pos) trace_path_back(target_node) end private def trace_path_back(target_node) path = [target_node.value] until target_node.parent.nil? parent_node = target_node.parent path << parent_node.value target_node = parent_node end path.reverse end def build_move_tree self.root_node = PolyTreeNode.new(position) node_queue = [root_node] until node_queue.empty? current_node = node_queue.shift children_position_arr = new_move_positions(current_node.value) children_position_arr.each do |pos| child = PolyTreeNode.new(pos) child.parent = current_node node_queue << child end end root_node end def new_move_positions(pos) possible_moves = KnightPathFinder.valid_moves(pos) new_moves = possible_moves.reject {|move| visited_positions.include?(move)} self.visited_positions += new_moves new_moves end end
class TemplateMailer < ActionMailer::Base CONFIG = YAML.load_file("#{Rails.root}/config/nyccollegeline.yml")[Rails.env] LOGO = File.read(Rails.root.join('app/assets/images/emails/logo.png')) default from: CONFIG['mail_sender'] def template_mail(user_survey_template) @user_survey_template = user_survey_template @user = User.find(@user_survey_template.user_id) @survey_template = SurveyTemplate.find(@user_survey_template.survey_template_id) @sender = User.find(@survey_template.creator_id) attachments.inline['logo.png'] = File.read(Rails.root.join('app/assets/images/emails/logo.png')) mail( to: @user.email, subject: @survey_template.title, from: "NYC College Line <no-reply@nyccollegeline.org>", ) end def guest_user_template_mail(guest_user_survey_template) @guest_user_survey_template = guest_user_survey_template @guest_user = GuestUser.find(@guest_user_survey_template.guest_user_id) @survey_template = SurveyTemplate.find(@guest_user_survey_template.survey_template_id) @sender = User.find(@survey_template.creator_id) attachments.inline['logo.png'] = File.read(Rails.root.join('app/assets/images/emails/logo.png')) mail( to: @guest_user.email, subject: @survey_template.title, from: "NYC College Line <no-reply@nyccollegeline.org>", ) end end
# frozen_string_literal: true # rubocop:todo all module Mongo module CRUD class Requirement YAML_KEYS = %w(auth minServerVersion maxServerVersion topology topologies serverParameters serverless csfle).freeze def initialize(spec) spec = spec.dup # Legacy tests have the requirements mixed with other test fields spec.delete('data') spec.delete('tests') unless (unhandled_keys = spec.keys - YAML_KEYS).empty? raise "Unhandled requirement specification keys: #{unhandled_keys}" end @min_server_version = spec['minServerVersion'] @max_server_version = spec['maxServerVersion'] # topologies is for unified test format. # topology is for legacy tests. @topologies = if topologies = spec['topology'] || spec['topologies'] topologies.map do |topology| { 'replicaset' => :replica_set, 'single' => :single, 'sharded' => :sharded, 'sharded-replicaset' => :sharded, 'load-balanced' => :load_balanced, }[topology].tap do |v| unless v raise "Unknown topology #{topology}" end end end else nil end @server_parameters = spec['serverParameters'] @serverless = if serverless = spec['serverless'] case spec['serverless'] when 'require' then :require when 'forbid' then :forbid when 'allow' then :allow else raise "Unknown serverless requirement: #{serverless}" end else nil end @auth = spec['auth'] @csfle = !!spec['csfle'] if spec['csfle'] end attr_reader :min_server_version attr_reader :max_server_version attr_reader :topologies attr_reader :serverless def short_min_server_version if min_server_version min_server_version.split('.')[0..1].join('.') else nil end end def short_max_server_version if max_server_version max_server_version.split('.')[0..1].join('.') else nil end end def satisfied? cc = ClusterConfig.instance ok = true if min_server_version ok &&= Gem::Version.new(cc.fcv_ish) >= Gem::Version.new(min_server_version) end if max_server_version ok &&= Gem::Version.new(cc.server_version) <= Gem::Version.new(max_server_version) end if topologies ok &&= topologies.include?(cc.topology) end if @server_parameters @server_parameters.each do |k, required_v| actual_v = cc.server_parameters[k] if actual_v.nil? && !required_v.nil? ok = false elsif actual_v != required_v if Numeric === actual_v && Numeric === required_v if actual_v.to_f != required_v.to_f ok = false end else ok = false end end end end if @serverless if SpecConfig.instance.serverless? ok = ok && [:allow, :require].include?(serverless) else ok = ok && [:allow, :forbid].include?(serverless) end end if @auth == true ok &&= SpecConfig.instance.auth? elsif @auth == false ok &&= !SpecConfig.instance.auth? end if @csfle ok &&= !!(ENV['LIBMONGOCRYPT_PATH'] || ENV['FLE']) ok &&= Gem::Version.new(cc.fcv_ish) >= Gem::Version.new('4.2.0') end ok end def description versions = [min_server_version, max_server_version].compact if versions.any? versions = versions.join('-') else versions = nil end topologies = if self.topologies self.topologies.map(&:to_s).join(',') else nil end [versions, topologies].compact.join('/') end end end end
class HomeController < ApplicationController def index render component: 'Index', props: { name: 'Home' } end end
require "bridgetown" require 'uri' require 'net/http' require 'openssl' require 'dotenv/tasks' Bridgetown.load_tasks # Run rake without specifying any command to execute a deploy build by default. task default: :deploy # # Standard set of tasks, which you can customize if you wish: # desc "Build the Bridgetown site for deployment" task :deploy => [:clean, "frontend:build"] do Bridgetown::Commands::Build.start end desc "Build the site in a test environment" task :test do ENV["BRIDGETOWN_ENV"] = "test" Bridgetown::Commands::Build.start end desc "Runs the clean command" task :clean do Bridgetown::Commands::Clean.start end namespace :frontend do desc "Build the frontend with Webpack for deployment" task :build do sh "yarn run webpack-build" end desc "Watch the frontend with Webpack during development" task :dev do sh "yarn run webpack-dev --color" rescue Interrupt end end namespace :cache do desc "Purge Bunny.net CDN cache" task :purge => :dotenv do puts "Purging the CDN cache" if ENV['REVIEW'] != 'true' url = URI("https://api.bunny.net/pullzone/#{ENV['BUNNY_ZONE_ID']}/purgeCache") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Post.new(url) request["AccessKey"] = ENV['BUNNY_API_KEY'] response = http.request(request) if response.code != "204" raise "Unexpected response from CDN. Expected 204, got #{response.code}\n Response body: #{response.body}" end puts "Cache purged" else puts "Skipping. In review app." end end end task "assets:precompile" do Rake::Task[:deploy].invoke end # # Add your own Rake tasks here! You can use `environment` as a prerequisite # in order to write automations or other commands requiring a loaded site. # # task :my_task => :environment do # puts site.root_dir # automation do # say_status :rake, "I'm a Rake tast =) #{site.config.url}" # end # end
module Plasma module Interpreter class PlasmaCore def self.plasma(interp) { :import => RubyClosure.new('import', interp) do |plasma| interp.merge(plasma) end, :print => RubyClosure.new('print', interp) do |string| puts string.to_plasma end, :eval => RubyClosure.new('eval', interp) do |quote| if quote.is_a?(String) interp.interpret(quote) else interp.evaluate(quote) end end, :parse => RubyClosure.new('parse', interp) do |code| interp.parse(code) end } end end end end
class ScoreDecorator < Draper::Decorator delegate_all delegate :current_page, :total_pages, :limit_value decorates_association :rider def rider_name rider ? rider.name : ".." end end
require 'binary_struct' require 'uuidtools' require 'stringio' require 'memory_buffer' require 'fs/xfs/superblock' require 'rufus/lru' module XFS # //////////////////////////////////////////////////////////////////////////// AG_FREESPACE = BinaryStruct.new([ # Common allocation group header information 'I>', 'magic_num', # magic number of the filesystem 'I>', 'version_num', # header version 'I>', 'seq_no', # sequence # starting from 0 'I>', 'length', # size in blocks of a.g. # Freespace Information # 'I>2', 'root_blocks', # Root Blocks 'I>', 'spare0', # spare field 'I>2', 'btree_levels', # btree levels 'I>', 'spare1', # spare field 'I>', 'fl_first', # first freelist block's index 'I>', 'fl_last', # last freelist block's index 'I>', 'fl_count', # count of blocks in freelist 'I>', 'free_blocks', # total free blocks 'L>', 'longest', # longest free space 'L>', 'btree_blocks', # # of blocks held in alloc group free btrees 'a16', 'uuid', # Filesystem uuid # # Reserve some contiguous space for future logged fields before we add # the unlogged fields. This makes the range logging via flags and # structure offsets much simpler. # 'Q>16', 'spare64', # underlying disk sector size in bytes # # Unlogged fields, written during buffer writeback. # 'Q>', 'last_write_seq', # last write sequence 'I>', 'crc', # CRC of alloc group free space sector 'I>', 'spare2', # name for the filesystem ]) AG_INODEINFO = BinaryStruct.new([ # Common allocation group header information 'I>', 'magic_num', # magic number of the filesystem 'I>', 'version_num', # header version 'I>', 'seq_no', # sequence # starting from 0 'I>', 'length', # size in blocks of a.g. # # Inode information # Inodes are mapped by interpretting the inode number, so no # mapping data is needed here. # 'I>', 'count', # count of allocated inodes 'I>', 'root', # root of inode btree 'I>', 'level', # levels in inode btree 'I>', 'free_count', # number of free inodes 'I>', 'new_inode', # new inode just allocated 'I>', 'dir_inode', # last directory inode chunk # # Hash table of inodes which have been unlinked but are # still being referenced. # 'I>64', 'unlinked_hash', # the hash 'a16', 'uuid', # Filesystem uuid 'I>', 'crc', # CRC of alloc group inode info sector 'I>', 'pad32', # 'Q>', 'last_write_seq', # last write sequence 'I>', 'free_root', # root of the free inode btree 'I>', 'free_level', # levels in free inode btree ]) # # The third AG block contains the AG FreeList, an array # of block pointers to blocks owned by the allocation btree code. # AG_FREELIST = BinaryStruct.new([ 'I>', 'magic_num', # magic number of the filesystem 'I>', 'seq_no', # sequence # starting from 0 'a16', 'uuid', # Filesystem uuid 'Q>', 'last_write_seq', # last write sequence 'I>', 'crc', # CRC of alloc group inode info sector 'I>', 'bno', # actually XFS_AGFL_SIZE ]) AG_FL_STRUCT_SIZE = AG_FREELIST.size # //////////////////////////////////////////////////////////////////////////// # // Class. class AllocationGroup AG_FREESPACE_SIZE = 512 AG_INODEINFO_SIZE = 512 AG_FREELIST_SIZE = 512 XFS_AGF_MAGIC = 0x58414746 XFS_AGI_MAGIC = 0x58414749 XFS_AGFL_MAGIC = 0x5841464c # ///////////////////////////////////////////////////////////////////////// # // initialize attr_reader :stream, :agf, :agi, :agfl, :allocation_group_block def initialize(stream, _agno, sb) raise "XFS::AllocationGroup.initialize: Nil stream" if stream.nil? # # The stream should be pointing at the Allocation Group to be built on the disk. # @stream = stream @agf = AG_FREESPACE.decode(@stream.read(AG_FREESPACE_SIZE)) @stream.seek(AG_FREESPACE_SIZE, IO::SEEK_CUR) @agi = AG_INODEINFO.decode(@stream.read(AG_INODEINFO_SIZE)) @stream.seek(AG_INODEINFO_SIZE, IO::SEEK_CUR) @agfl = AG_FREELIST.decode(@stream.read(AG_FREELIST_SIZE)) @stream.seek(-(AG_FREESPACE_SIZE + AG_INODEINFO_SIZE + AG_FREELIST_SIZE)) @allocation_group_block = @stream.read(sb['block_size']) # Grab some quick facts & make sure there's nothing wrong. Tight qualification. if @agf['magic_num'] != XFS_AGF_MAGIC raise "XFS::AllocationGroup.initialize: Invalid AGF magic number=[#{@agf['magic_num']}]" elsif @agi['magic_num'] != XFS_AGI_MAGIC raise "XFS::AllocationGroup.initialize: Invalid AGI magic number=[#{@agi['magic_num']}]" elsif @agfl['magic_num'] != XFS_AGFL_MAGIC raise "XFS::AllocationGroup.initialize: Invalid AGFL magic number=[#{@agfl['magic_num']}]" end end # //////////////////////////////////////////////////////////////////////////// # // Class helpers & accessors. # Dump object. def dump out = "\#<#{self.class}:0x#{format('%08x', object_id)}>\n" out << "AGI Magic number : #{@agf['magic_num']}\n" out << "Version number : #{@agf['version_num']})\n" out << "Sequence Number : #{@agf['seq_no']}\n" out << "Length : #{@agf['length']}\n" out << "Root Blocks : #{@agf['root_blocks']}\n" out << "Btree Levels : #{@agf['btree_levels']}\n" out << "1st Freelist Blk Index : #{@agf['fl_first']}\n" out << "Last Freelist Blk Index : #{@agf['fl_last']}\n" out << "# Blocks in Freelist : #{@agf['fl_count']}\n" out << "# of Free Blocks : #{@agf['free_blocks']}\n" out << "Longest Free Space : #{@agf['longest']}\n" out << "# Blks in AG Free Btree : #{@agf['btree_blocks']}\n" out << "Filesystem UUID : #{@agf['uuid']}\n" out << "Allocated Inodes : #{@agi['count']}\n" out << "Root of Inode BTree : #{@agi['root']}\n" out << "Levels in Inode BTree : #{@agi['level']}\n" out << "Number of Free Inodes : #{@agi['free_count']}\n" out << "Newest Inode Allocated : #{@agi['new_inode']}\n" out << "Last Dir Inode Chunk : #{@agi['dir_inode']}\n" out << "Root of Free Ino Btree : #{@agi['free_root']}\n" out << "Levels in Free Ino Btree : #{@agi['free_level']}\n" out end end # class AllocationGroup end # module XFS
require 'rails_helper' RSpec.describe QuestionCategoriesController, :type => :controller do before do @user = FactoryGirl.create :user sign_in @user FactoryGirl.create :course FactoryGirl.create :lesson_category QuestionCategory.create(name: 'a', exam_id: 1) FactoryGirl.create :attending, role: 1 FactoryGirl.create :exam end describe "POST create" do context "valid question category" do it "creates question category" do expect do post :create, exam_id: 1, question_category: { name: "Nazwa" } end.to change(QuestionCategory, :count).by(1) expect(response).to redirect_to edit_course_exam_path(1, 1) end end context "invalid question category" do it "does not create question category" do expect do post :create, exam_id: 1, question_category: { name: "" } end.not_to change(QuestionCategory, :count) expect(response).to redirect_to edit_course_exam_path(1, 1) end end end describe 'DELETE destroy' do before do FactoryGirl.create :question_category end it "destroys question category" do expect do delete :destroy, exam_id: 1, id: 1 end.to change(QuestionCategory, :count).by(-1) expect(response).to redirect_to edit_course_exam_path(1, 1) end end describe "PATCH update" do before do FactoryGirl.create :question_category end context "valid params" do it "updates question category" do xhr :put, :update, exam_id: 1, id: 1, question_category: { name: "Takowe" }, format: :json expect(QuestionCategory.first.name).to eq "Takowe" expect(JSON.parse(response.body).deep_symbolize_keys) .to(eq({ :question_category => { name: "Takowe", id: 1 } })) end end context "invalid params" do it "renders json with error" do xhr :put, :update, exam_id: 1, id: 1, question_category: { name: "a" * 444 }, format: :json expect(response).to have_http_status 422 expect(JSON.parse response.body).not_to be_nil expect(JSON.parse(response.body)['errors'].first).to( include 'długie' ) end end end end