text
stringlengths
10
2.61M
class RenameColumnInCompetitions < ActiveRecord::Migration def up rename_column :competitions, :team_stats_type, :team_stats_config end def down rename_column :competitions, :team_stats_config, :team_stats_type end end
#!/usr/bin/env ruby # :title: PlanR::Plugins::Interpreter::R =begin rdoc Interpreter plugin for R scripts and the R process. (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end require 'tg/plugin' require 'plan-r/document/script' require 'plan-r/application/interpreter' require 'plan-r/application/script_mgr' module PlanR module Plugins module Interpreter =begin rdoc Plugin for executing R scripts and launching R interpreters =end class R extend TG::Plugin name 'R Interpreter' author 'dev@thoughtgang.org' version '0.01' description 'Interpreter for R language' help 'NOT IMPLEMENTED' LANG_NAME = 'R' class Interpreter < Application::Interpreter def initialize cmd = `which R`.chomp + ' --vanilla --no-readline --slave' super cmd end def quit_command 'q()' end def cmd_done_marker "$PID$#{@pid}$" end def statement_with_marker(cmd) cmd + "; print(\"#{cmd_done_marker}\")" end end def application_startup(app) PlanR::Application::ScriptManager.register_language_interpreter( LANG_NAME, self) end def application_shutdown(app) (@instances || []).each { |r| r.term } end def launch_r @instances ||= [] r = Interpreter.new r.start @instances << r r end spec :interpreter, :launch_r, 70 =begin def eval_r(script, args) # FIXME: actually evaluate script using R # keep interpreter running? output = [] #IO.popen("R #{script.abs_path}") do |pipe| # args.contents.lines.each { |line| pipe.puts line } # pipe.each { |line| output << line } #end output.join("\n") end spec :evaluate, :eval_r, 50 # do |script, args| # TODO: check if script is an R script? =end end end end end
class UserPaymentsController < ApplicationController before_action :set_user_payment, only: %i[ show edit update destroy ] before_action :authenticate_user, only: [:create, :index] def index @user_payments = UserPayment.all @unpaid_payments = UserPayment.where(user:@current_user).where('status= ? OR status= ?', 'unpaid', 'cancelled') end def show end def new @user_payment = UserPayment.new end def edit end def create @user_payment = UserPayment.new(user_payment_params) @user_payment.user = @current_user respond_to do |format| if @user_payment.save format.html { redirect_to @user_payment, notice: "User payment was successfully created." } format.json { render :show, status: :created, location: @user_payment } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @user_payment.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @user_payment.update(user_payment_params) format.html { redirect_to @user_payment, notice: "User payment was successfully updated." } format.json { render :show, status: :ok, location: @user_payment } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @user_payment.errors, status: :unprocessable_entity } end end end def destroy @user_payment.destroy respond_to do |format| format.html { redirect_to user_payments_url, notice: "User payment was successfully destroyed." } format.json { head :no_content } end end private def set_user_payment @user_payment = UserPayment.find(params[:id]) end def authenticate_user @current_user = User.find_by(email: 'test01@gmail.com') end def user_payment_params params.require(:user_payment).permit(:user_id, :status, :issue_date, :payment_date) end end
class AddForeignKey < ActiveRecord::Migration def change add_reference :books, :staff, index: true add_foreign_key :books, :staff add_reference :books, :author, index: true add_foreign_key :books, :author add_reference :books, :manufacturer, index: true add_foreign_key :books, :manufacturer end end
# Homepage (Root path) require 'json' before do if session[:user_id] @user = User.find(session[:user_id]) else @user = User.new @user.cart = Cart.new @user.user_wish_list = UserWishList.new session[:user_id] = @user_id end # if loggedin? # @cart = User.find(session[:user_id]).cart # else # begin # @cart = Cart.find(session[:cart_id]) # rescue ActiveRecord::RecordNotFound # c = Cart.create # session[:cart_id] = c.id # end # end end helpers do def loggedin? session[:user_id] end end # Home page # TODO make a real home page with nice backgound picture, and sign up form, log in, to listings, BONUS play music get '/' do erb :index end # User log in. starts user session. post '/login' do user = User.find_by(username: params[:username]) if user && user.password == params[:password] session[:user_id] = user.id @username = user.username redirect '/pokedex#pokedex' else flash[:notice] = "Username or password you entered is not correct." redirect '/' end end get '/logout' do session[:user_id] = nil redirect '/' end get '/profile' do @user = User.find(session[:user_id]) if @user erb :'/users/profile' else redirect '/' end end get '/profile/wishlist' do erb :'users/wishlist' end get '/profile/tradelist' do erb :'users/tradelist' end post '/listings' do # flash[:keyword] = params[:keyword] redirect "/listings?keyword=#{params[:keyword]}" end get '/listings' do erb :'listings/index', locals: {keyword: params[:keyword], show_all: "false"} end get '/pokedex' do erb :'pokemons/pokedex' end get '/pokemon/add/:id' do # if loggedin? @species = Species.find(params[:id]) erb :'pokemons/add' # else # flash[:notice] = 'Please log in to add pokemon to your profile' # redirect '/pokedex' # end end # post '/pokemon/add/submit' do # @new_pokemon = Pokemon.new( # user: User.find(params[:user_id]), # species: Species.find(params[:species_id]), # name: params[:name], # cp: params[:cp], # quick_move: Move.find_by(name: params[:quick_move]), # charge_move: Move.find_by(name: params[:charge_move]) # ) # @new_pokemon.save # redirect '/pokedex' # end # # button from pokedex, to add to wishlist # post '/pokemon/wish_list' do # if loggedin? # pokemon = Pokemon.new # pokemon.user_wish_list = UserWishList.find_by(user_id: session[:user_id]) # pokemon.species = Species.find(params[:id]) # pokemon.save # else # flash[:notice] = 'Please log in to add pokemon to your wish list' # end # redirect '/pokedex' # end post '/listings/add_to_cart' do listings = @user.cart.listings if listings.select{|l|l.id.to_s == params[:listing_id]}.empty? @user.cart.listings << Listing.find(params[:listing_id]) redirect '/carts' else redirect '/listings' end end delete '/cart/listing' do @cart.listings.delete(Listing.find(params[:listing_id])) redirect :'/carts/show' end get '/carts' do @cart = @user.cart erb :'/carts/show' end # post '/checkout' do # binding.pry # listing = Listing.find(params[:listing_id]) # seller = listing.user # seller_pokemon = listing.pokemon # buyer = User.find(params[:buyer_id]) # price = listing.price # # buyer_pokemon = Pokemon.find(params[:buyer_pokemon_id]) # if buyer.wallet >= price # buyer.wallet -= price # buyer.save # seller.wallet += price # seller.save # seller_pokemon.user = buyer # seller_pokemon.save # # buyer_pokemon.user = seller # listing.status = 'completed' # listing.save # result = listing.attributes # result["message"]="Success" # json result # # redirect '/carts' # else #transaction failed # # do something # end # end
class UserSerializer < ActiveModel::Serializer attributes :id, :name,:last_name, :profile, :avatar, :profile, :location, :company, :position, :phone, :email, :authentication_token, :industries, :areas, :status def avatar if object.image.url == "/images/original/missing.png" object.avatar.present? ? object.avatar : nil else object.image end end end
class SaeQualification < UserQualification def sae_label_method "#{self.user.full_name} SAE Qualification" end RailsAdmin.config do |config| config.model SaeQualification do visible false object_label_method do :sae_label_method end edit do field :qualified_on field :expires_on do read_only true end field :maintenance_record, :enum do enum_method do :maintenance_enum end end field :user_licenses do visible do !bindings[:object].new_record? end associated_collection_scope do # bindings[:object] & bindings[:controller] are available, but not in scope's block! user = bindings[:object].user Proc.new { |scope| # scoping all Players currently, let's limit them to the team's league # Be sure to limit if there are a lot of Players and order them by position scope = scope.where(user_id: user.id) if user.present? scope = scope.limit(10) # 'order' does not work here } end end end end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # login :string(255) not null # email :string(255) not null # crypted_password :string(255) not null # password_salt :string(255) not null # persistence_token :string(255) not null # single_access_token :string(255) not null # perishable_token :string(255) not null # login_count :integer default(0), not null # failed_login_count :integer default(0), not null # last_request_at :datetime # current_login_at :datetime # last_login_at :datetime # current_login_ip :string(255) # last_login_ip :string(255) # cached_slug :string(255) # created_at :datetime # updated_at :datetime # # -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../spec_helper' describe User do before do @user = Factory(:quentin) end end
class Api::V1::User < ApplicationRecord has_secure_password has_many :followed_users, foreign_key: "follower_id", class_name: "Api::V1::Follow" has_many :followees, through: :followed_users has_many :following_users, foreign_key: "followee_id", class_name: "Api::V1::Follow" has_many :followers, through: :following_users has_many :events has_one :wishlist has_many :items, through: :wishlists has_one_attached :profile_picture accepts_nested_attributes_for :events end
module Airmodel class Query include Enumerable def initialize(querying_class) @querying_class = querying_class end def params @params ||= { where_clauses: {}, formulas: [], order: @querying_class.default_sort, offset: nil } end def where(args) params[:where_clauses].merge!(args) self end def by_formula(formula) params[:formulas].push formula self end def search(args={}) if args && args[:q] && args[:fields] searchfields = if args[:fields].is_a?(String) args[:fields].split(",").map{|f| f.strip } else args[:fields] end query = if args[:q].respond_to?(:downcase) args[:q].downcase else args[:q] end f = "OR(" + searchfields.map{|field| # convert strings to case-insensitive searches "FIND('#{query}', LOWER({#{field}}))" }.join(',') + ")" params[:formulas].push f end self end def limit(lim) params[:limit] = lim ? lim.to_i : nil self end def order(order_string) if order_string ordr = order_string.split(" ") column = ordr.first direction = ordr.length > 1 ? ordr.last.downcase : "asc" params[:order] = [column, direction] end self end def offset(airtable_offset_key) params[:offset] = airtable_offset_key self end # return saved airtable offset for this query def get_offset @offset end # add kicker methods def to_a puts "RUNNING EXPENSIVE API QUERY TO AIRTABLE (#{@querying_class.name})" # merge explicit formulas and abstracted where-clauses into one Airtable Formula formula = "AND(" + params[:where_clauses].map{|k,v| "{#{k}}='#{v}'" }.join(',') + params[:formulas].join(',') + ")" records = @querying_class.table.records( sort: params[:order], filterByFormula: formula, limit: params[:limit], offset: params[:offset] ) @offset = records.offset @querying_class.classify records end def all to_a end def each(&block) to_a.each(&block) end def map(&block) to_a.map(&block) end def inspect to_a.inspect end def last to_a.last end def find_by(filters) params[:limit] = 1 params[:where_clauses] = filters first end end end
require 'faker' FactoryGirl.define do factory :party_a do city { Faker::Address.city } company { Faker::Company.name } end factory :party_b do name { Faker::Name.name } uuid { Faker::Code.ean } phone { Faker::PhoneNumber.cell_phone } card_number { Faker::Business.credit_card_number } address { Faker::Address.street_address } bank { Faker::Business.credit_card_type } end factory :contract do trait :initial do contract_no do created_at = Time.now.to_s 'I-' + SecureRandom.hex(2) + created_at.slice(0, created_at.index('+')).gsub(/[^\d]/, '') end end trait :formal do contract_no do created_at = Time.now.to_s 'F-' + SecureRandom.hex(2).upcase + created_at.slice(0, created_at.index('+')).gsub(/[^\d]/, '') end end breed { Faker::App.name } cultivated_area { Faker::Number.decimal(2) } transplant_number { Faker::Number.number(4) } purchase { Faker::Number.number(4) } association :party_a, factory: :party_a, strategy: :create association :party_b, factory: :party_b, strategy: :create factory :initial_contract, traits: [:initial] factory :formal_contract, traits: [:formal] end end
feature 'user sign in' do scenario 'a user can sign in with email and password' do User.create(name: 'Bob', email: 'bob@gmail.com', password: 'password', password_confirmation: 'password') expect{ sign_in }.not_to change(User, :count) expect(page).to have_content "Welcome, Bob" end scenario 'a user cannot sign in with an incorrect password' do User.create(name: 'Bob', email: 'bob@gmail.com', password: 'password', password_confirmation: 'password') expect{ sign_in(password: "wrong") }.not_to change(User, :count) expect(page).not_to have_content "Welcome, Bob" expect(page).to have_content "Email or Password are incorrect" end end
require 'helper_frank' module Rdomino describe View do before do @db = Rdomino.local[:test].with_fixtures @people = @db.view 'People' @by_form = @db.view 'by Form' end it { @people.template.must_equal 'templi'} it "#pluck" do assert_equal %w(Frank Tobias),@people.pluck(:name).sort end it '#parent' do assert_equal @people.parent, @db #to_array assert_equal [['Tobias',30.0],['Frank',43.0]], @people.to_array #categories @by_form.categories.must_equal ['Group','Person',''] @by_form.categories(0,1).must_equal [ ['Group',1.0], ['Person',2.0], ['',3.0] ] #find_all all = @by_form.find_all 'Person' assert_instance_of DocumentCollection, all assert_equal 2, all.count #find tobias = @people.find 'Tobias' tobias.g(:name).must_equal 'Tobias' tobias.parent.must_equal @people assert_nil @people.find('Frankk') #find! proc {@people.find!('Frankk')}.must_raise EntryNotFoundError #finds documents with multiple keys @db.view('Form-Name').find('Person','Frank').g(:name).must_equal 'Frank' #accessor @db.people.name.must_equal 'People' #count @db.people.count.must_equal 2 #as @people.as(Db::Test::Person).find('Frank').age.must_equal 43 #to_s @people.documents_inspect.must_equal <<-HERE "Frank", 43.0 "Tobias", 30.0 HERE #find_category mc = @by_form.find_category('Person','Group') mc.count.must_equal 3 mc.map(&:form).must_equal %w(Person Person Group) #find_categories @by_form.find_categories(:== ,'Person').count.must_equal 2 @by_form.find_categories(:>= ,'A').count.must_equal 3 @by_form.find_categories(:< ,'A').count.must_equal 0 end it "#empty" do v = @db.system_log v.count.must_equal 0 assert_nil v.first end # -key # 5 Frank # 3 GSE # 6 Tobias it "#by_key" do proc{ # all @db.view("bykey").by_key("key"){|d| print d.g(:name) }}.must_output "FrankGSETobias" proc{ # limited @db.view("bykey").by_key("key", :limit=>10){|d| print d.g(:name) }.must_equal 8 }.must_output "FrankGSE" proc{ # docs @db.view("bykey").by_key("key", :docs=>1){|d| print d.g(:name) }.must_equal 1 }.must_output "Frank" # none @db.view("bykey").by_key("bla"){|d| flunk } end it "#selection=" do assert_equal 'SELECT Form="Person"', @people.selection @people.selection = 'SELECT @All' assert_equal 'SELECT @All', @people.selection @people.selection = 'SELECT Form="Person"' end it "#collection" do coll = @people.collection coll.must_be_instance_of DocumentCollection coll.count.must_equal 2 end end end
class FayePublishWorker include Sidekiq::Worker def perform(channel, message) FayeClient.publish(channel, message) end end
#!/usr/bin/env ruby # http://tammersaleh.com/posts/the-modern-vim-config-with-pathogen # Other plugins # * Git # git://github.com/tpope/vim-fugitive.git # git://github.com/tpope/vim-git.git # * File explorer / navigation # git://github.com/scrooloose/nerdtree.git # git://github.com/vim-scripts/project.tar.gz # * Comments # git://github.com/tsaleh/vim-tcomment.git # * Autocomplete # git://github.com/ervandew/supertab.git # * Python # git://github.com/fs111/pydoc.vim.git # * Ruby # git://github.com/tsaleh/vim-shoulda.git # git://github.com/tpope/vim-cucumber.git # * Markup # git://github.com/tpope/vim-haml.git # * Scala # https://github.com/bdd/vim-scala vim_org_scripts = [ ["anotherdark", "4449", "colors"], # http://www.vim.org/scripts/script.php?script_id=1308 ] # xmledit for other filetypes xmledit_filetypes = ["ant", "html", "jsp", "php", "sgml", "xhtml"] require 'fileutils' require 'open-uri' puts "Updating bundles" puts " Updating submodules" `git submodule update --init --recursive` bundles_dir = File.join(File.dirname(__FILE__), "bundle") FileUtils.cd(bundles_dir) vim_org_scripts.each do |name, script_id, script_type| if File.exist? name puts " Removing #{name}" FileUtils.rm_rf name end puts " Downloading #{name}" local_file = File.join(name, script_type, "#{name}.vim") FileUtils.mkdir_p(File.dirname(local_file)) File.open(local_file, "w") do |file| file << open("http://www.vim.org/scripts/download_script.php?src_id=#{script_id}").read end end puts " Xmledit for other filetypes" xmledit_filetypes.each do |filetype| target = File.expand_path("./xmledit/ftplugin/#{filetype}.vim") if not File.exist? target FileUtils.ln_s(File.expand_path("./xmledit/ftplugin/xml.vim"), target) end end # Build command-t FileUtils.cd("command-t") puts " Building command-t" `rake make`
module AdvancedFlash DELETED_CREDENTIAL_FLASH = '_deleted_credential' DELETED_CREDENTIAL_SESSION_ID = :deleted_credential_id DELETED_CALENDAR_FLASH = '_deleted_calendar' DELETED_CALENDAR_SESSION_ID = :deleted_calendar_id module ControllerSupport protected def add_deleted_credential_flash(deleted_credential) session[AdvancedFlash::DELETED_CREDENTIAL_SESSION_ID] = deleted_credential.id flash['deleted credential notice'] = AdvancedFlash::DELETED_CREDENTIAL_FLASH end def add_deleted_calendar_flash(deleted_calendar) session[AdvancedFlash::DELETED_CALENDAR_SESSION_ID] = deleted_calendar.id flash['deleted calendar notice'] = AdvancedFlash::DELETED_CALENDAR_FLASH end end module Helper def flash_to_html return '' if flash.empty? content_tag :ul, :id => 'flash', :class => 'span-20 last' do flash.map do |k,v| content_tag(:li, flash_content(v), :class => k) end.join(' ') end end def flash_to_json returning(flash.each { |k,v| flash[k] = flash_content(v) }.to_json) do flash.clear end end def flash_content(v) content_tag(:span, flash_text(v)) end def flash_text(v) case v when DELETED_CREDENTIAL_FLASH deleted_credential_id = session.delete(AdvancedFlash::DELETED_CREDENTIAL_SESSION_ID) c = Credential::Archive.find_by_user_and_id!(current_user, deleted_credential_id) form = inline_button_to(t('common.undo'), undestroy_user_credential_path(current_user, deleted_credential_id), :put, :class => 'ajax') t("credentials.deleted", :provider => c.provider, :undo_link => form) when DELETED_CALENDAR_FLASH deleted_calendar_id = session.delete(AdvancedFlash::DELETED_CALENDAR_SESSION_ID) c = Calendar::Archive.find_by_user_and_id!(current_user, deleted_calendar_id) form = inline_button_to(t('common.undo'), undestroy_user_calendar_path(current_user, deleted_calendar_id), :put, :class => 'ajax') t('calendars.deleted', :title => c.title, :undo_link => form) else v end end end end
class Quotation < ApplicationRecord belongs_to :currency INTERVALS = { 'day': {date_interval: 1.day, date_format: "%H", maxLabels: 6}, 'week': { date_interval: 7.day, date_format: "%b/%d", maxLabels: 7}, 'month': { date_interval: 1.month, date_format: "%b/%d", maxLabels: 15}, 'months': { date_interval: 3.month, date_format: "%b", maxLabels: 3}, 'year': { date_interval: 1.year, date_format: "%b/%y", maxLabels: 12} } def self.get_date_interval(interval) INTERVALS[interval.to_sym][:date_interval] end def self.json_serialize(rows, interval) puts "interval #{interval}" data = [] labels = [] interval_config = INTERVALS[interval.to_sym] rows.each do |obj| values = { bid_value: obj.bid_value.to_f, ask_value: obj.ask_value.to_f, date: obj.date.strftime("%Y-%m-%d %H:%M") } labels.push(obj.date.strftime(interval_config[:date_format])) data.push(values) end return {data: data, labels: labels, maxLabels: interval_config[:maxLabels]}.to_json end end
class AddSpaceIdToTables < ActiveRecord::Migration def change add_column :resources, :space_id, :integer add_column :tools, :space_id, :integer add_column :strata, :space_id, :integer end end
require_relative "vehicle" class Minivan < Vehicle def to_s "The minivan: #{model} - #{type} - #{number}" end def max_passengers 10 end end
FactoryGirl.define do factory :organization do sequence(:name) { |n| "Fake Organization #{n}" } # need this for fake data process_ssrs false transient do children_count 0 has_protocols false end after :create do |organization, evaluator| create_list(:pricing_setup, 3, organization: organization).each do |pricing_setup| pricing_setup.update_attributes(organization_id: organization.id) end evaluator.children_count.times do case(organization.type) when "Institution" if evaluator.has_protocols create(:organization_provider_with_protocols, parent_id: organization.id) else create(:organization_provider, parent_id: organization.id) end when "Provider" if evaluator.has_protocols create(:organization_program_with_protocols, parent_id: organization.id) else create(:organization_program, parent_id: organization.id) end when "Program" if evaluator.has_protocols create(:organization_core_with_protocols, parent_id: organization.id) else create(:organization_core, parent_id: organization.id) end end end end trait :institution do type "Institution" parent_id nil end trait :core do type "Core" end trait :program do type "Program" end trait :provider do type "Provider" end trait :with_protocols do after(:create) do |organization, evaluator| sub_service_request = create(:sub_service_request, organization: organization) create(:protocol, sub_service_request: sub_service_request) end end trait :with_services do after(:create) do |organization, evaluator| create_list(:service, 4, organization: organization) create_list(:service_with_one_time_fee, 4, organization: organization) end end trait :with_child_organizations do after(:create) do |organization, evaluator| 3.times do child = create(:organization_with_services, parent: organization) create_list(:organization_with_services, 3, parent: child) end end end # trait :with_3_child_orgs do # after(:create) do |organization, evaluator| # 3.times do # create(:organization_with_services, parent: organization) # end # end # end factory :organization_institution, traits: [:institution] factory :organization_provider, traits: [:provider] factory :organization_program, traits: [:program] factory :organization_core, traits: [:core] factory :organization_institution_with_protocols, traits: [:institution, :with_protocols] factory :organization_provider_with_protocols, traits: [:provider, :with_protocols] factory :organization_program_with_protocols, traits: [:program, :with_protocols] factory :organization_core_with_protocols, traits: [:core, :with_protocols] factory :organization_with_protocols, traits: [:core, :with_protocols] factory :provider_with_protocols, traits: [:provider, :with_protocols] factory :program_with_protocols, traits: [:program, :with_protocols] factory :core_with_protocols, traits: [:core, :with_protocols] factory :organization_with_services, traits: [:core, :with_services] factory :provider_with_child_organizations_and_protocols, traits: [:with_protocols, :provider, :with_child_organizations] factory :provider_with_child_organizations, traits: [:with_services, :provider, :with_child_organizations] factory :program_with_child_organizations, traits: [:with_services, :program, :with_child_organizations] factory :organization_with_child_organizations, traits: [:with_services, :core, :with_child_organizations] # factory :provider_with_3_child_orgs, traits: [:with_services, :provider, :with_3_child_orgs] # factory :program_with_3_child_orgs, traits: [:with_services, :program, :with_3_child_orgs] # factory :core_with_3_child_orgs, traits: [:with_services, :core, :with_3_child_orgs] end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :prepare_meta_tags, if: "request.get?" after_action :prepare_unobtrusive_flash after_action :store_location if Rails.env.production? or Rails.env.staging? rescue_from ActiveRecord::RecordNotFound, ActionController::UnknownFormat do |exception| render_404 end rescue_from CanCan::AccessDenied do |exception| begin self.response_body = nil redirect_to root_url, :alert => exception.message rescue AbstractController::DoubleRenderError => e end end rescue_from ActionController::InvalidCrossOriginRequest, ActionController::InvalidAuthenticityToken do |exception| begin self.response_body = nil redirect_to root_url, :alert => I18n.t('errors.messages.invalid_auth_token') rescue AbstractController::DoubleRenderError => e end end end def render_404 begin self.response_body = nil render file: "#{Rails.root}/public/404.html", layout: false, status: 404 rescue AbstractController::DoubleRenderError => e end end def errors_to_flash(model) flash[:notice] = model.errors.full_messages.join('<br>').html_safe end def prepare_meta_tags(options={}) set_meta_tags build_meta_options(options) end def build_meta_options(options) site_name = "국회톡톡" title = options[:title] || "내게 필요한 법, 국회톡톡으로 국회에 직접 제안하자!" image = options[:image] || view_context.image_url('seo.png') url = options[:url] || root_url description = options[:description] || "국회톡톡은 시민의 제안을 법으로 만듭니다. 지금 참여해서 시민의 제안을 국회로 연결해주세요!" { title: title, reverse: true, image: image, description: description, keywords: "시민, 정치, 국회, 입법, 법안, 20대국회, 온라인정치, 정치참여, 국회톡톡, 시민입법, 빠띠, 빠흐띠, 와글", canonical: url, twitter: { site_name: site_name, site: '@parti_xyz', card: 'summary', title: title, description: description, image: image }, og: { url: url, site_name: site_name, title: title, image: image, description: description, type: 'website' } } end def redirect_back_with_anchor(anchor:, fallback_location:, **args) if referer = request.headers["Referer"] redirect_to "#{referer}##{anchor}", **args else redirect_to fallback_location, **args end end private def store_location return unless request.get? return if params[:controller].blank? return if params[:controller].match("users/") return if params[:controller].match("devise/") return if params[:controller] == "users" and params[:action] == "join" return if request.xhr? store_location_for(:user, request.fullpath) end end
class StudentsProjectMembershipsController < ApplicationController before_action :set_students_project_membership, only: [:show, :edit, :update, :destroy] # GET /students_project_memberships # GET /students_project_memberships.json def index @students_project_memberships = StudentsProjectMembership.all end # GET /students_project_memberships/1 # GET /students_project_memberships/1.json def show end # GET /students_project_memberships/new def new @students_project_membership = StudentsProjectMembership.new end # GET /students_project_memberships/1/edit def edit end # POST /students_project_memberships # POST /students_project_memberships.json def create @students_project_membership = StudentsProjectMembership.new(students_project_membership_params) respond_to do |format| if @students_project_membership.save format.html { redirect_to @students_project_membership, notice: 'Students project membership was successfully created.' } format.json { render :show, status: :created, location: @students_project_membership } else format.html { render :new } format.json { render json: @students_project_membership.errors, status: :unprocessable_entity } end end end # PATCH/PUT /students_project_memberships/1 # PATCH/PUT /students_project_memberships/1.json def update respond_to do |format| if @students_project_membership.update(students_project_membership_params) format.html { redirect_to @students_project_membership, notice: 'Students project membership was successfully updated.' } format.json { render :show, status: :ok, location: @students_project_membership } else format.html { render :edit } format.json { render json: @students_project_membership.errors, status: :unprocessable_entity } end end end # DELETE /students_project_memberships/1 # DELETE /students_project_memberships/1.json def destroy @students_project_membership.destroy respond_to do |format| format.html { redirect_to students_project_memberships_url, notice: 'Students project membership was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_students_project_membership @students_project_membership = StudentsProjectMembership.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def students_project_membership_params params.require(:students_project_membership).permit(:student_id, :project_id) end end
class ChangeColNameFromImageToImageUrlAndAddPublicIdColumn < ActiveRecord::Migration def change rename_column :photos, :image, :image_url add_column :photos, :public_id, :string change_column :photos, :public_id, :string, null: false end end
module ModelExtensions public def get_assocs(type = :belongs_to) aggregate_objs = self.reflect_on_all_associations(type) aggregate_objs.select{|m| m.name != :users}.map{|m| m.klass} end def attrs excludes = %w(audits accepted_roles created_at updated_at users id) attrs = [] self.column_names.each do |column| next if excludes.include?(column) attrs << [column.sub(/_id$/,''),column] end return attrs end end
module Qiita # Qiita API アクセスクラス # 特定のタグがつけられた投稿を取得する。 # また、ブロックを受け取り、データ取得後に非同期で任意の処理を実行できるようにする。 # # @example # Qiita::Client.fetch_tagged_items('tag') { |items, error_message| # # 任意の処理 # } class Client # BASE_URL = 'https://qiita.com/api/v1' BASE_URL = 'http://qiita-server.herokuapp.com/api/items' PAGE_NUM = 1 PER_PAGE = 30 THRESHOLD = 30 def self.fetch_tagged_items(&block) items = [] message = nil PAGE_NUM.times do |i| page = (i+1).to_s BW::HTTP.get(BASE_URL) do |response| begin if response.ok? items << get_items(response) else message = get_error_message(response) end rescue => e p e items = [] message = 'Error' end block.call(items, message) end end end private def self.get_items(response) # 1件ずつQiita::Itemクラスのインスタンスにして格納 # per_page=100につき、だいたい直近20時間の間に何ストックされたか。 BW::JSON.parse(response.body.to_s).map.with_index(1) {|item, i| next if item['data']['stock_count'].to_i < THRESHOLD Qiita::Item.new(item['data']) } end def self.get_error_message(response) if response.body.nil? response.error_message else json = BW::JSON.parse(response.body.to_s) json['error'] end end end end
module Riopro module KillBill module Return class Itau < Riopro::KillBill::Return::Base # Verifies if parsed file is valid. Returns boolean def valid? valid = true @errors = [] unless self.transactions.size == self.trailer[:quantidade_detalhes] @errors << "Quantidade de transações diferente da quantidade total do Trailer do arquivo" end if self.transactions.size > 0 total = 0.0 self.transactions.each do |transaction| total += transaction[:valor_principal] end unless total == self.trailer[:valor_total_informado] @errors << "Valor total das transações diferente do existente no Trailer do arquivo" end end valid = false unless @errors.empty? valid end private # Parses the header line and returns a hash. def parse_header(string) { # identificação do registro header :tipo_registro => string[0..0].to_i, # identificação do arquivo retorno :codigo_retorno => string[1..1], # identificação por extenso do tipo de movimento :literal_retorno => string[2..8], # identificação do tipo de serviço :codigo_servico => string[9..10], # identificação por extenso do tipo de serviço :literal_servico => string[11..25], # agência mantenedora da conta :agencia => string[26..29], # complemento de registro :zeros => string[30..31], # número da conta corrente da empresa :conta => string[32..36], # dígito de auto-conferência ag/conta empresa :dac => string[37..37], # complemento do registro #:brancos1 => string[38..45], # nome por extenso da "empresa mãe" :nome_empresa => string[46..75], # número do banco na câmara de compensação :codigo_banco => string[76..78], # nome por extenso do banco cobrador :nome_banco => string[79..93].strip, # data de geração do arquivo :data_geracao => string[94..99], # unidade de densidade :densidade => string[100..104], # densidade de gravação do arquivo :unidade_densidade => string[105..107], # número sequencial do arquivo retorno :numero_sequencial_arquivo_retorno => string[108..112], # data de crédito dos lançamentos :data_credito => string[113..118], # complemento do registro #:brancos2 => string[119..393], # número sequencial do registro no arquivo :numero_sequencial => string[394..399] } end # Parses the trailer line and returns a hash. def parse_trailer(string) { # identificação do registro trailer :tipo_registro => string[0..0].to_i, # identificação de arquivo retorno :codigo_retorno => string[1..1], # identificação do tipo de serviço :codigo_servico => string[2..3], # identificação do banco na compensação :codigo_banco => string[4..6], # complemento de registro #:brancos1 => string[7..16], # quantidade de títulos em cobrança simples :quantidade_titulos_simples => string[17..24].to_i, # valor total dos títulos em cobrança simples :valor_total_simples => string[25..38].to_f/100, # referência do aviso bancário :aviso_bancario_simples => string[39..46], # complemento do registro #:brancos2 => string[47..56], # quantidade de títulos em cobrança/vinculada :quantidade_titulos_vinculada => string[57..64].to_i, # valor total dos títulos em cobrança/vinculada :valor_total_vinculada => string[65..78].to_f/100, # referência do aviso bancário :aviso_bancario_vinculada => string[79..86], # complemento do registro #:brancos3 => string[87..176], # quantidade de títulos em cobrança direta/escritural :quantidade_titulos_direta => string[177..184].to_i, # valor total dos títulos em cobrança direta/escritural :valor_total_direta => string[185..198].to_f / 100, # referência do aviso bancário :aviso_bancario_direta => string[199..206], # número sequencial do arquivo retorno :controle_arquivo => string[207..211], # quantidade de registros de transação :quantidade_detalhes => string[212..219].to_i, # valor dos títulos informados no arquivo :valor_total_informado => string[220..233].to_f/100, # complemento do registro #:brancos4 => string[234..393], # número sequencial do registro no arquivo :numero_sequencial => string[394..399].to_i } end # Parses a transaction line and returns a hash. def parse_transaction(string) { # identificação do registro transação :tipo_registro => string[0..0].to_i, # identificação do tipo de inscrição/empresa :codigo_inscricao => string[1..2], # número de inscrição da empresa (cpf/cnpj) :numero_inscricao => string[3..16], # agência mantenedora da conta :agencia => string[17..20], # complemento de registro :zeros => string[21..22], # número da conta corrente da empresa :conta => string[23..27], # dígito de auto-conferência ag/conta empresa :dac => string[28..28], # complemento de registro #:brancos1 => string[29..36], # identificação do título na empresa :uso_da_empresa => string[37..61], # identificação do título no banco :nosso_numero1 => string[62..69], # complemento de registro #:brancos2 => string[70..81], # número da carteira :carteira1 => string[82..84], # identificação do título no banco :nosso_numero2 => string[85..92], # dac do nosso número :dac_nosso_numero => string[93..93], # complemento de registro #:brancos3 => string[94..106], # código da carteira :carteira2 => string[107..107], # identificação da ocorrência :codigo_ocorrencia => string[108..109], # data de de ocorrência no banco :data_ocorrencia => convert_date(string[110..115]), # número do documento de cobrança (dupl, np etc) :numero_documento => string[116..125], # confirmação do número do título no banco :nosso_numero3 => string[126..133], # complemento de registro #:brancos4 => string[134..145], # data de vencimento do título :vencimento => convert_date(string[146..151]), # valor nominal do título :valor_titulo => string[152..164].to_f / 100, # número do banco na câmara de compensação :codigo_banco => string[165..167], # ag. cobradora, ag. de liquidação ou baixa :agencia_cobradora => string[168..171], # dac da agência cobradora :dac_agencia_cobradora => string[172..172], # espécie do título :especie => string[173..174], # valor da despesa de cobrança :tarifa_cobranca => string[175..187].to_f / 100, # complemento de registro #:brancos5 => string[188..213], # valor do iof a ser recolhido (notas seguro) :valor_iof => string[214..226].to_f / 100, # valor do abatimento concedido :valor_abatimento => string[227..239].to_f / 100, # valor do desconto concedido :descontos => string[240..252].to_f / 100, # valor lançado em conta corrente :valor_principal => string[253..265].to_f / 100, # valor de mora e multa pagos pelo sacado :juros_mora_multa => string[266..278].to_f / 100, # valor de outros créditos :outros_creditos => string[279..291].to_f / 100, # complemento de registro #:brancos6 => string[292..294], # data de crédito desta liquidação :data_credito => convert_date(string[295..300]), # código da instrução cancelada :instrucao_cancelada => string[301..304], # complemento de registro #:brancos7 => string[305..323], # nome do sacado :nome_sacado => string[324..353], # complemento de registro #:brancos8 => string[354..376], # registros rejeitados ou alegação do sacado :erros => string[377..384], # complemento de registro #:brancos9 => string[385..391], # meio pelo qual o título foi liquidado :codigo_liquidacao => string[392..393], # número sequencial do registro no arquivo :numero_sequencial => string[394..399].to_i } end end end end end
module ArRollout module Controller module Helpers def self.included(base) base.send :helper_method, :rollout? base.send :helper_method, :degrade_feature? end def rollout?(name) return false unless current_user ArRollout.active?(name, current_user) end def degrade_feature?(name) ArRollout.degrade_feature?(name) end end end end
require 'open-uri' require 'pry' require 'nokogiri' class Scraper def self.scrape_index_page(index_url) html = open(index_url) doc = Nokogiri::HTML(html) students = [] #create a new hash for each student #push each hash onto the array doc.css("div.student-card").each do |student| student = {:name => student.css("a div.card-text-container h4.student-name").text, :location => student.css("a div.card-text-container p.student-location").text, :profile_url => student.css("a").attribute("href").value} students << student end students end def self.scrape_profile_page(profile_url) html = open(profile_url) profile = Nokogiri::HTML(html) #iterate over the socials and return an array with the link for each social #create a new array with the socials, with the icon link => link student_profile = {} social_icons = [] social_links = [] profile.css(".social-icon-container a").each do | social| social_icon = social.css("img.social-icon").attribute("src").value social_icons << social_icon social_link = social.attribute("href").value social_links << social_link end #if the Twitter exists if social_icons.any? { |link| link.downcase.include?("twitter") } student_profile[:twitter] = social_links.select { |link| link.downcase.include?("twitter")}.join #create a Twitter key with the link as the value end if social_icons.any? { |link| link.downcase.include?("linkedin") } student_profile[:linkedin] = social_links.select { |link| link.downcase.include?("linkedin")}.join end if social_icons.any? { |link| link.downcase.include?("github") } student_profile[:github] = social_links.select { |link| link.downcase.include?("github")}.join end if social_icons.any? { |icon| icon.downcase.include?("rss") } index = social_icons.index { |icon| icon.include?("rss") } link = social_links[index] student_profile[:blog] = link end student_profile[:profile_quote] = profile.css(".profile-quote").text student_profile[:bio] = profile.css(".bio-content .description-holder p").text student_profile end end Scraper.scrape_profile_page("https://learn-co-curriculum.github.io/student-scraper-test-page/students/ryan-johnson.html")
class RolesSerializer include FastJsonapi::ObjectSerializer attributes :name attribute :id do |object| object.id.to_s end end
class AddPeopleInvitedToEvents < ActiveRecord::Migration def change add_column :events, :people_invited, :text end end
class ProjectsController < ApplicationController before_action :authenticate_user!, except: [:dashboard] before_action :set_project, only: [:show, :edit, :update, :destroy] load_and_authorize_resource :project, :except => [:edit_status, :update_status] def dashboard if current_user.present? && current_user.role?(:admin) @todos = Todo.select("todos.title, todos.status, users.name").joins(:user).where("true").group_by(&:status)#.group("todos.status,todos.title")#.references(:todos) @devs = User.where(role: 1).select(:name).order(:id) @todos_p = Todo.select("todos.title, todos.status, projects.name").joins(:project).where("true").group_by(&:status) @projects = Project.where("true").select(:name, :id).order(:id) project_id = params[:project].present? ? params[:project] : 1 @graph_data = Todo.includes(:project).where(project_id: project_id).select("status, project_id").group_by(&:status).collect{|k , v | [k, v.count]} elsif current_user.present? && current_user.role?(:developer) @todos = Todo.where(user_id: current_user.id) end end # GET /projects # GET /projects.json def index @projects = Project.all end # GET /projects/1 # GET /projects/1.json def show end # GET /projects/new def new @project = Project.new @project.todos.build end # GET /projects/1/edit def edit end # POST /projects # POST /projects.json def create @project = Project.new(project_params) respond_to do |format| if @project.save format.html { redirect_to @project, notice: 'Project was successfully created.' } format.json { render :show, status: :created, location: @project } else format.html { render :new } format.json { render json: @project.errors, status: :unprocessable_entity } end end end # PATCH/PUT /projects/1 # PATCH/PUT /projects/1.json def update respond_to do |format| if @project.update(project_params) format.html { redirect_to @project, notice: 'Project was successfully updated.' } format.json { render :show, status: :ok, location: @project } else format.html { render :edit } format.json { render json: @project.errors, status: :unprocessable_entity } end end end # DELETE /projects/1 # DELETE /projects/1.json def destroy @project.destroy respond_to do |format| format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' } format.json { head :no_content } end end def edit_status @todo = Todo.find(params[:id]) end def update_status @todo = Todo.find(params[:id]) respond_to do |format| if @todo.update_attributes(todo_params) format.html { redirect_to dashboard_projects_path, notice: 'Todo was successfully updated.' } format.json { render :dashboard, status: :ok, location: dashboard_projects_path } else format.html { render :edit_status } format.json { render json: @todo.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_project @project = Project.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def project_params params.require(:project).permit(:name, todos_attributes: [:id, :title, :user_id, :status,:_destroy]) end def todo_params params.require(:todo).permit(:status) end end
module MCollective module Util module IPTables class IPv4 def initialize configure end def configure @iptables_cmd = Config.instance.pluginconf.fetch("iptables.iptables", "/sbin/iptables") @logger_cmd = Config.instance.pluginconf.fetch("iptables.logger", "/usr/bin/logger") @chain = Config.instance.pluginconf.fetch("iptables.chain", "junk_filter") @target = Config.instance.pluginconf.fetch("iptables.target", "DROP") end def activate? cmd = File.executable?(@iptables_cmd) chain = cmd && (Shell.new("#{@iptables_cmd} -L #{@chain} -n").runcommand.exitstatus == 0) Log.warn("Could not find iptables command %s" % @iptables_cmd) unless cmd Log.warn("Could not find chain %s" % @chain) unless chain cmd && chain end def listblocked iptables_output = "" status = Shell.new("#{@iptables_cmd} -L #{@chain} -n 2>&1", :stdout => iptables_output, :chomp => true).runcommand unless status.exitstatus == 0 raise "iptables returned %d" % status.exitstatus end parse_iptables_list(iptables_output) end def blocked?(ip) listblocked.include?(ip) end # returns an array with members: # # - true or false indicating success # - a human readable string of status # - blocked?(ip) def block(ip) return([false, "#{ip} is already blocked", true]) if blocked?(ip) iptables_output = "" Shell.new("#{@iptables_cmd} -A #{@chain} -s #{ip} -j #{@target} 2>&1", :stdout => iptables_output, :chomp => true).runcommand Shell.new("#{@logger_cmd} -i -t mcollective 'Attempted to add #{ip} to iptables #{@chain} chain on #{Socket.gethostname}'").runcommand blocked = blocked?(ip) if blocked iptables_output = "#{ip} was blocked" if iptables_output == "" else return([false, "still unblocked, iptables output: '%s'" % iptables_output, true]) end [true, iptables_output, blocked] end # returns an array with members: # # - true or false indicating success # - a human readable string of status # - blocked?(ip) def unblock(ip) return([false, "#{ip} is already unblocked", false]) unless blocked?(ip) iptables_output = "" Shell.new("#{@iptables_cmd} -D #{@chain} -s #{ip} -j #{@target} 2>&1", :stdout => iptables_output, :chomp => true).runcommand Shell.new("#{@logger_cmd} -i -t mcollective 'Attempted to remove #{ip} from iptables #{@chain} chain on #{Socket.gethostname}'") blocked = blocked?(ip) if blocked raise "still blocked, iptables output: '%s'" % iptables_output else iptables_output = "#{ip} was unblocked" if iptables_output == "" end [true, iptables_output, blocked] end def parse_iptables_list(output) output.split("\n").grep(/^#{@target}/).map{|l| l.split(/\s+/)[3]} end end end end end
Transform /^table:cards,card$/ do |table| table.map_headers! {|header| header.downcase.to_sym } table.map_column!(:player) {|player| ordinal.to_i } table.map_column!(:card_rank) {|rank| rank.to_i } table.map_column!(:card_suit) {|suit| suit.downcase.to_sym } table end Given /^"([^"]*)" players$/ do |number_of_players| @players = (1..number_of_players.to_i).map {|i| Player.new } end When /^I create the default card deck$/ do @deck = CardDeck::Base.new end Given /^I create a trump deck$/ do @deck = CardDeck::TrumpCardDeck::Base.new end Given /^"([^"]*)" are trump$/ do |suit| suit = pluralize(suit).to_sym @deck.trump_suit = suit end Given /^the players receive the following cards:$/ do |table| # table is a Cucumber::Ast::Table table.hashes.each do |row| @players[row[:player].to_i].hand << Card.new(row[:card_rank].to_i, row[:card_suit]) end end When /^I create a euchre deck$/ do @deck = CardDeck::TrumpCardDeck::EuchreDeck.new end When /^I create a pinochle deck$/ do @deck = CardDeck::TrumpCardDeck::PinochleDeck.new end When /^I deal "([^"]*)" cards$/ do |number_of_cards| number_of_cards = number_of_cards.to_i @deck.deal number_of_cards, @players end When /^each player plays their card$/ do @deck.new_hand @players.each do |player| player.play_card player.hand.first, @deck end end Then /^each player should have "([^"]*)" cards$/ do |number_of_cards| @players.each do |player| player.hand.size.should == number_of_cards.to_i end end Then /^the deck should have "([^"]*)" cards remaining$/ do |number_of_cards| @deck.size.should == number_of_cards.to_i end Then /^I should have "([^"]*)" cards$/ do |number| @deck.size.should == number.to_i end Then /^the suits should be "([^"]*)"$/ do |valid_suits| @valid_suits = valid_suits.split(', ').map { |i| i.to_sym } hash = sort_deck @deck.cards deck_suits = hash.keys (@valid_suits - deck_suits).should be_empty (deck_suits - @valid_suits).should be_empty end Then /^the ranks should range from "([^"]*)" to "([^"]*)"$/ do |min, max| @valid_ordinals = (min..max).map { |i| i.to_i } hash = sort_deck @deck.cards hash.values.each do |suit_hash| suit_ordinals = suit_hash.keys (@valid_ordinals - suit_ordinals).should be_empty (suit_ordinals - @valid_ordinals).should be_empty end end Then /^no cards should match$/ do hash = {} @deck.cards.each do |card| if hash.has_key? card.suit hash[card.suit].should_not have_key card.ordinal else hash[card.suit] = {} end end end Then /^I should have "([^"]*)" of each card$/ do |number_of_cards| hash = sort_deck @deck.cards hash.each_value do |suit| suit.each_value do |ordinal| ordinal.should == number_of_cards.to_i end end end Then /^player "([^"]*)" should win the hand$/ do |player| winning_player = @deck.rank_hand winning_player.should == @players[player.to_i] end
RailsAdmin.config do |config| config.main_app_name { ['NixTest', 'Admin'] } ### Popular gems integration config.authorize_with do authenticate_or_request_with_http_basic('Authorization required') do |email, password| user = User.find_by_email(email) if email if user && user.valid_password?(password) && user.moderator? config.included_models = %w(Question Comment Tag) config.included_models << 'User' if user.admin? user else nil end end end config.model "User" do list do include_fields :id, :login, :email, :birth_date field :avatar, :paperclip field :role_id do label "Role" pretty_value do User::ROLES[value] end end field :questions do pretty_value do value.count end end field :comments do pretty_value do value.count end end include_fields :country, :city, :address, :created_at, :updated_at end show do fields :id, :login, :email field :avatar, :paperclip field :role_id do label "Role" pretty_value do User::ROLES[value] end end fields :birth_date, :country, :city, :address, :created_at, :updated_at exclude_fields :password_digest end create do include_fields :login, :email, :role_id field :avatar, :paperclip field :password include_fields :birth_date, :country, :city, :address end edit do include_fields :login, :email, :role_id field :avatar, :paperclip field :password include_fields :birth_date, :country, :city, :address, :created_at, :updated_at end end config.model "Question" do list do include_fields :id, :title, :content field :rating field :user do pretty_value do value.login end end field :comments do pretty_value do value.size end end field :tags include_fields :created_at, :updated_at end show do include_fields :id, :title, :content field :rating field :tags include_fields :user, :comments, :created_at, :updated_at end create do include_fields :title, :content field :user do required true end field :tags do required true end end edit do include_fields :content, :title field :user do required true end field :tags do required true end include_fields :created_at, :updated_at end end config.model "Comment" do list do include_fields :id, :content field :rating field :user do pretty_value do value.login end end field :question include_fields :created_at, :updated_at end show do include_fields :id, :content field :rating field :user field :question include_fields :user, :created_at, :updated_at end create do include_fields :content field :question do required true end field :user do required true end end edit do include_fields :content field :question do required true end field :user do required true end include_fields :created_at, :updated_at end end config.model "Tag" do list do include_fields :id, :name, :questions_count, :created_at, :updated_at end show do include_fields :id, :name, :questions_count field :questions include_fields :created_at, :updated_at end create do include_fields :name, :questions_count field :questions end edit do include_fields :name, :questions_count field :questions include_fields :created_at, :updated_at end end config.actions do dashboard # mandatory index # mandatory new show edit delete ## With an audit adapter, you can add: # history_index # history_show end end
# == Schema Information # # Table name: images # # id :integer not null, primary key # column :integer # row :integer # extra_height_in_lines :integer default(0) # image :string # caption_title :string # caption :string # source :string # position :integer # page_number :integer # story_number :integer # landscape :boolean # used_in_layout :boolean # working_article_id :integer # issue_id :integer # created_at :datetime not null # updated_at :datetime not null # extra_line :integer # x_grid :integer # y_in_lines :integer # height_in_lines :integer # draw_frame :boolean default(TRUE) # zoom_level :integer default(1) # zoom_direction :integer default(5) # move_level :integer # auto_size :integer # fit_type :string # image_kind :string # not_related :boolean # reporter_image_path :string # crop_x :integer # crop_y :integer # crop_w :integer # crop_h :integer # require 'test_helper' class ImageTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
module Qualtrics::API class Group < BaseModel attribute :id attribute :type attribute :organization_id attribute :division_id attribute :name attribute :all_users attribute :creation_date attribute :creator_id ## # Make the model serializeable by ActiveModelSerializer # # @return [OpenStruct] # def self.model_name OpenStruct.new(name: "Qualtrics::API::MailingList", klass: self, singular: "qualtrics_group", plural: "qualtrics_groups", element: "group", human: "group", collection: "qualtrics/groups", param_key: "qualtrics_groups", i18n_key: "qualtrics/groups", route_key: "qualtrics_groups", singular_route_key: "qualtrics_group") end end end
=begin Write a program that includes a method called multiply that takes two arguments and returns the product of the two numbers. multiply(2, 5) -> 10 =end def multiply(a,b) return a * b end puts multiply(2,5)
# frozen_string_literal: true FactoryGirl.define do factory :exam_section do title 'Test Exam' type 'Opción Múltiple' end end
class Admin < ApplicationRecord validates :user_name, presence: true validates :password, presence: true, length: {minimum: 8} has_secure_password end
#!/usr/bin/env ruby require 'tempfile' tmp_path = File.expand_path("../../", __FILE__) readme_path = File.expand_path("../../README.md", __FILE__) index_path = File.expand_path("../../docs/index.html", __FILE__) ribbon = %{ <a href="https://github.com/johnsusi/bluesky"> <img style="position: absolute; top: 0; left: 0; border: 0;" src="https://camo.githubusercontent.com/121cd7cbdc3e4855075ea8b558508b91ac463ac2/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f6c6566745f677265656e5f3030373230302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_left_green_007200.png"> </a> } lines = File.open(readme_path).read.split(/\r?\n/) lines.insert(2, ribbon) file = Tempfile.new(['README', '.md'], tmp_path) file.sync = true puts file.path file.write(lines.join("\n")) file.write("\n") file.rewind system("spec-md #{file.path} > #{index_path}") # file.close
class User < ActiveRecord::Base validates :email, uniqueness: true has_many :participations has_many :themes, through: :participations has_many :expenses end
class AddAttachmentToPhotos < ActiveRecord::Migration def change add_attachment :photos, :pic end end
module Fog module Compute class Brkt class Real def update_server(id, options={}) request( :expects => [202], :method => "POST", :path => "v2/api/config/instance/#{id}", :body => Fog::JSON.encode(options) ) end end class Mock def update_server(id, options={}) response = Excon::Response.new server_data = self.data[:servers][id] server_data.merge!(Fog::StringifyKeys.stringify(options)) response.body = server_data response end end end end end
require 'spec_helper' describe "Home Page" do describe "get root path" do it "works if user is admin" do admin_user_login visit root_path current_path.should == root_path end it "fails if user is not an admin" do user_login visit root_path current_path.should == new_user_session_path end end end
class ToDoItemsController < ApplicationController before_action :set_to_do_item, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token protect_from_forgery with: :null_session # GET /to_do_items # GET /to_do_items.json def index if params[:user] != nil @to_do_items = ToDoItem.where(user: params[:user]) render json: {data: @to_do_items} end @to_do_items = ToDoItem.all end def get_where_user @to_do_items = ToDoItem.where(user: params[:user]) render json: {data: @to_do_items} end # GET /to_do_items/1 # GET /to_do_items/1.json def show end # GET /to_do_items/new def new @to_do_item = ToDoItem.new end # GET /to_do_items/1/edit def edit end # POST /to_do_items # POST /to_do_items.json def create @to_do_item = ToDoItem.new(to_do_item_params) respond_to do |format| if @to_do_item.save format.html { redirect_to @to_do_item, notice: 'To do item was successfully created.' } format.json { render :show, status: :created, location: @to_do_item } else format.html { render :new } format.json { render json: @to_do_item.errors, status: :unprocessable_entity } end end end # PATCH/PUT /to_do_items/1 # PATCH/PUT /to_do_items/1.json def update respond_to do |format| if @to_do_item.update(to_do_item_params) format.html { redirect_to @to_do_item, notice: 'To do item was successfully updated.' } format.json { render :show, status: :ok, location: @to_do_item } else format.html { render :edit } format.json { render json: @to_do_item.errors, status: :unprocessable_entity } end end end # DELETE /to_do_items/1 # DELETE /to_do_items/1.json def destroy @to_do_item.destroy respond_to do |format| format.html { redirect_to to_do_items_url, notice: 'To do item was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_to_do_item @to_do_item = ToDoItem.find(params[:id]) end # Only allow a list of trusted parameters through. def to_do_item_params params.require(:to_do_item).permit(:user, :title, :description, :status) end end
class Account < ActiveRecord::Base validates :name, presence: true validates :number, presence: true, numericality: { greater_than: 0 } belongs_to :organization delegate :credits, :debits, to: :amounts has_many :amounts scope :asset_accounts, ->{ where(type: 'AssetAccount') } scope :liability_accounts, ->{ where(type: 'LiabilityAccount') } scope :equity_accounts, ->{ where(type: "EquityAccount" )} def self.types %w(AssetAccount LiabilityAccount EquityAccount) end end
class PhysiciansController < ApplicationController # Create # GET: /physicians/new get "/sign_up" do erb :"/physicians/new.html" end # POST: /physicians logging in post "/physicians" do if params[:name] == "" && params[:password] == "" redirect "/sign_up" else if Physician.find_by(name: params[:name]) redirect "/log_in" else phy_info = Physician.create(name: params[:name], password: params[:password]) session[:physician_id] = phy_info.id redirect "/physicians/#{@phy_info.id}" end end end # Read # GET: /physicians/5 get "/physicians/:id" do # This is the show page @patients = current_phys.patients erb :"/physicians/show.html" end # Update # GET: /physicians/5/edit get "/physicians/:id/edit" do if logged_in? if current_phys.id erb :"/physicians/edit.html" else redirect "/physicians/#{current_phys.id}" end else redirect '/' end end # PATCH: /physicians/5 patch "/physicians/:id/edit" do if logged_in? if current_phys.id current_phys.update(name: params[:name], username: params[:username], password: params[:password]) else redirect "physicians/#{current_phys.id}" end else redirect '/' end end # Destroy # DELETE: /physicians/5/delete delete "/physicians/:id/delete" do redirect "/physicians" end end
# == Schema Information # # Table name: conversations_profiles # # profile_id :integer not null # conversation_id :integer not null # id :integer not null, primary key # # Indexes # # index_conversations_profiles_on_conversation_id_and_profile_id (conversation_id,profile_id) # index_conversations_profiles_on_profile_id_and_conversation_id (profile_id,conversation_id) # class ConversationParticipant < ApplicationRecord self.table_name = "conversations_profiles" belongs_to :conversation belongs_to :profile end
require 'spec_helper' describe "file_uploads/index" do before(:each) do assign(:file_uploads, [ stub_model(FileUpload, :originalname => "Originalname", :filename => "Filename", :size => 1, :sha1_hash => "SHA1 hash", ), stub_model(FileUpload, :originalname => "Originalname", :filename => "Filename", :size => 1, :sha1_hash => "SHA1 hash", ) ]) end it "renders a list of file_uploads" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Originalname".to_s, :count => 2 assert_select "tr>td", :text => "Filename".to_s, :count => 2 assert_select "tr>td", :text => 1.to_s, :count => 2 assert_select "tr>td", :text => "SHA1 hash".to_s, :count => 2 end end
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details # Scrub sensitive parameters from your log # filter_parameter_logging :password before_filter :login_required before_filter :set_user_variable def login_required if session[:current_user_id] true else flash[:warning] = "Ole hyvä ja kirjaudu" flash.keep redirect_to root_url false end end def set_user_variable if session[:current_user_id] @logged_user_id = session[:current_user_id] #could be prettier @logged_username = User.find(@logged_user_id).username else @logged_user_id = nil @logged_username = nil end end end
require_relative 'temporal_operator' module ConceptQL module Operators # Trims the end_date of the LHS set of results by the RHS's earliest # start_date (per person) # If a the RHS contains a start_date that comes before the LHS's start_date # that LHS result is completely discarded. # # If there is no RHS result for an LHS result, the LHS result is passed # thru unaffected. # # If the RHS result's start_date is later than the LHS end_date, the LHS # result is passed thru unaffected. class TrimDateEnd < TemporalOperator register __FILE__ desc <<-EOF Trims the end_date of the left hand results (LHR) by the earliest start_date (per person) in the right hand results (RHR) If the RHR contain a start_date that comes before the start_date in the LHR that result in the LHR is completely discarded. If there is no result in the RHR for a result in the LHR, the result in the LHR is passed through unaffected. If the start_date of the result in the RHR is later than the end_date of the result in the LHR, the result in the LHR is passed through unaffected. EOF allows_one_upstream within_skip :before def query(db) grouped_right = db.from(right_stream(db)).select_group(:person_id).select_append(Sequel.as(Sequel.function(:min, :start_date), :start_date)) where_criteria = Sequel.expr { l__start_date <= r__start_date } where_criteria = where_criteria.|(r__start_date: nil) # If the RHS's min start date is less than the LHS start date, # the entire LHS date range is truncated, which implies the row itself # is ineligible to pass thru ds = db.from(left_stream(db)) .left_join(Sequel.as(grouped_right, :r), l__person_id: :r__person_id) .where(where_criteria) .select(*new_columns) .select_append(Sequel.as(Sequel.function(:least, :l__end_date, :r__start_date), :end_date)) ds = add_option_conditions(ds) ds.from_self end def within_column :l__end_date end private def new_columns (COLUMNS - [:end_date]).map { |col| "l__#{col}".to_sym } end end end end
class CreateHours < ActiveRecord::Migration def change create_table :hours do |t| t.integer :zone end end end
namespace :hp do HP_URL = 'http://www.haskell.org/platform/download/2013.2.0.0/haskell-platform-2013.2.0.0.tar.gz' HP_TAR = "/var/tmp/#{HP_URL.split('/').last}" HP_DIR = "/var/tmp/#{HP_URL.split('/').last.split('.tar').first}" desc "install hp from source" task :install => [:build] do sh "cd #{HP_DIR} && sudo make install" end task :build => [:pkgs, HP_DIR] do sh "cd #{HP_DIR} && make" end HP_PKGS = 'zlib1g-dev libgl1-mesa-dev libglc-dev freeglut3-dev libedit-dev libglw1-mesa libglw1-mesa-dev hscolour' task :pkgs do sh "sudo apt-get install -y #{HP_PKGS}" end directory HP_DIR => HP_TAR do |t| sh "cd /var/tmp && tar xf #{HP_TAR}" cmd = ['configure'] cmd << '--prefix=/opt/ghc' cmd << '--with-ghc=/opt/ghc/bin/ghc' cmd << '--with-ghc-pkg=/opt/ghc/bin/ghc-pkg' # hack: otherwise build fails (dunno why); but nevertheless QuickCheck is installed cmd << '--without-QuickCheck' sh "cd #{HP_DIR} && #{cmd.join(' ')}" end file HP_TAR do |t| sh "wget -c -O #{t.name} #{HP_URL}" end task :clean, [:step] do |t,arg| arg.with_defaults(step: 1) DIRS = [] DIRS << HP_TAR if arg.step.to_i == 1 DIRS << HP_DIR if arg.step.to_i >= 1 DIRS.each do |d| sh "rm -rf #{d}" end end end
require 'rails_helper' RSpec.describe BirthdayParty, type: :model do describe "build_unwithdrew_redpacks" do let!(:party) { FactoryGirl.create(:birthday_party) } let!(:virtual_present) { FactoryGirl.create(:virtual_present, value: 708, price: 2000) } let!(:bless) { FactoryGirl.create(:bless, virtual_present: virtual_present, birthday_party: party, paid: true) } it "为没有被分发到红包的余额创建红包,以单个红包最大金额为200进行切割" do expect { party.order.finish! party.send(:build_unwithdrew_redpacks) }.to change{ party.redpacks.count }.by(4) values = party.redpacks(true).map do |redpack| redpack.amount.to_f end expect(values).to eq([200, 200, 200, 108]) end it "更新withdrew的值" do party.order.finish! party.send(:build_unwithdrew_redpacks) expect(party.withdrew).to eq(708) end end # describe "send_unsent_redpacks" do # let!(:party) { FactoryGirl.create(:birthday_party) } # let!(:virtual_present) { FactoryGirl.create(:virtual_present, value: 708, price: 2000) } # let!(:bless) { FactoryGirl.create(:bless, virtual_present: virtual_present, birthday_party: party, paid: true) } # it "对那些没有发送成功的红包,进行发送操作" do # party.build_unwithdrew_redpacks # Redpack.any_instance.should_receive(:send_redpack) # party.order.finish! # party.send_unsent_redpacks # end # it "对那些已经发送成功的红包,不会进行发送操作" do # expect { # }.not_to receive() # party.order.finish! # party.send_unsent_redpacks # end # end end
shared_examples_for 'php-fpm' do |enabled_suite, disabled_suite| # Basic tests describe service(get_helper_data_value(enabled_suite, :fpm_service_name)) do it { should be_enabled } it { should be_running } end if os[:family] == 'ubuntu' && os[:release] == '14.04' # On Trusty we need to check a TCP/IP socket describe port(get_helper_data_value(enabled_suite, :fpm_port)) do it { should be_listening } end describe port(get_helper_data_value(disabled_suite, :fpm_port)) do it { should_not be_listening } end else describe file(get_helper_data_value(enabled_suite, :fpm_socket)) do it { should be_socket } end describe file(get_helper_data_value(disabled_suite, :fpm_socket)) do it { should_not be_socket } end end # Pool tests describe file(get_helper_data_value(enabled_suite, :default_pool)) do it { should be_file } end describe file(get_helper_data_value(disabled_suite, :default_pool)) do it { should_not be_file } end end
=begin - input: array of elements that can be sorted - output: same array with elements sorted - Data Structure: work directly with Array Algorithm: - if first element > second element then array[0], array[1] = array[1], array[0] - now second element compared to third => if array[1] > array[2] then swap =end def bubble_sort!(array) n = array.size loop do newn = 0 1.upto(n - 1) do |idx| if array[idx - 1] > array[idx] array[idx - 1], array[idx] = array[idx], array[idx - 1] newn = idx end end n = newn break if n == 0 end array end #array = [5, 3] #bubble_sort!(array) #array == [3, 5] p array = [6, 2, 7, 1, 4] bubble_sort!(array) p array #== [1, 2, 4, 6, 7] p array = %w(Sue Pete Alice Tyler Rachel Kim Bonnie) bubble_sort!(array) p array #== %w(Alice Bonnie Kim Pete Rachel Sue Tyler)
require_relative '../../refinements/string' using StringRefinements module BankStatements class HashCategoryProcessor def initialize(category_hash, default = nil) @category_hash = category_hash @default = default || ['Misc'] @hash_info = HashCategoryInfo.new(@category_hash, @default) end def match(description) categories = process_category_item(@category_hash, description) categories = categories.flatten.uniq return @default if categories.empty? categories end def keys @hash_info.keys end private def process_category_item(object, description) return process_hash(object, description) if (object.is_a?(Hash) && !(object.empty?)) return process_array(object, description) if object.is_a?(Array) return process_string(object, description) if object.is_a?(String) [] end def process_hash(object, description) match_items = [] object.each_pair do |key, value| matches = process_category_item(value, description) next if matches.empty? match_items << key << matches end match_items end def process_array(object, description) match_items = [] object.each do |item| matches = process_category_item(item, description) match_items << matches unless matches.empty? end match_items end def process_string(object, description) object.within?(description) ? object : '' end class HashCategoryInfo def initialize(category_hash, default) @category_hash = category_hash @default = default end def keys() categories = process_category_item(@category_hash) categories << @default categories.flatten.uniq end private def process_category_item(object) return process_hash(object) if (object.is_a?(Hash) && !(object.empty?)) return process_array(object) if object.is_a?(Array) return process_string(object) if object.is_a?(String) [] end def process_hash(object) categories = [] object.each_pair do |key, value| categories << key categories << process_category_item(value) end categories end def process_array(object) categories = [] object.each do |item| categories << process_category_item(item) end categories end def process_string(object) object end end private_constant :HashCategoryInfo end end # Sainsburys supermarkets SAINSBURYS S/MKTS, SAINSBURYS, SAINSBURY'S SMKT # Sainsburys petrol SAINSBURYS PETROL # Sainsburys (ATM) SAINSBURYS B # Tesco TESCO STORES, TESCO EXPRESS, TESCO UPT, TESCO SACAT, TESCO GARAGE, TESCO PETROL # Tesco mobile TESCO MOBILE # Wildlife HIOW WILDLIFE TRUS # L&G medical LEGAL AND GEN MI C/L # Post Office POST OFFICE # Halfords HALFORDS # Morrisons MORRISONS, W M MORRISON
require 'test_helper' require 'place_service' class PlaceServiceTest < ActiveSupport::TestCase test "the truth" do assert true end id1 = "ohGSnJtMIC5nPfYRi_HTAg" id2 = "GXvPAor1ifNfpF0U5PTG0w" openingHourJSON = { "Days" => [ "monday", "tuesday", "wednesday" ], "Hours" => [ "0 - 12", "13 - 24" ] } placeJSON = { "Name" => "Test Name", "Location" => "Test Location", "OpeningHours" => [ openingHourJSON, openingHourJSON, openingHourJSON ] } test "Successfull Queries" do place1 = PlaceService.query(id1) place2 = PlaceService.query(id2) assert_not_nil(place1) assert_not_nil(place2) end test "Notfound Queries" do id ="1234" place = PlaceService.query(id) assert_nil(place) end end
class AssignmentTypesController < ApplicationController before_action :set_assignment_type, only: [:show, :edit, :update, :destroy] # GET /assignment_types # GET /assignment_types.json def index @assignment_types = AssignmentType.all.order("name") end # GET /assignment_types/1 # GET /assignment_types/1.json def show end # GET /assignment_types/new def new @assignment_type = assignmentType.new end # GET /assignment_types/1/edit def edit end # POST /assignment_types # POST /assignment_types.json def create @assignment_type = assignmentType.new(assignment_type_params) respond_to do |format| if @assignment_type.save format.html { redirect_to @assignment_type, notice: 'assignment type was successfully created.' } format.json { render :show, status: :created, location: @assignment_type } else format.html { render :new } format.json { render json: @assignment_type.errors, status: :unprocessable_entity } end end end # PATCH/PUT /assignment_types/1 # PATCH/PUT /assignment_types/1.json def update respond_to do |format| if @assignment_type.update(assignment_type_params) format.html { redirect_to @assignment_type, notice: 'assignment type was successfully updated.' } format.json { render :show, status: :ok, location: @assignment_type } else format.html { render :edit } format.json { render json: @assignment_type.errors, status: :unprocessable_entity } end end end # DELETE /assignment_types/1 # DELETE /assignment_types/1.json def destroy @assignment_type.destroy respond_to do |format| format.html { redirect_to assignment_types_url, notice: 'assignment type was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_assignment_type @assignment_type = assignmentType.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def assignment_type_params params.require(:assignment_type).permit(:name, :description) end end
class Image < ApplicationRecord belongs_to :project mount_uploader :image_url, PhotoUploader end
object @user attributes :id child :runs do attributes :distance attributes :run_time attributes :notes attributes :id attributes :user_id node(:run_date) { |run| pretty_date(run.run_date)} node(:pace) { |run| pretty_pace(run.per_mile_pace)} node(:run_id) { |run| run.id} end
RSpec.describe Faye::Server do let(:user) { create(:user) } let(:circle) { create(:circle) } describe '#make_response' do it do message = { 'ext' => 'ext' } expect(subject).to receive(:make_response_without_ext).with(message).and_return({ 'successful' => true }) expect(subject.make_response(message)).to eq({ 'successful' => true, 'ext' => 'ext' }) end end describe '#process' do it do user1 = create(:user) circle.users << user << user1 stub_const('FayeServer::VERSIONS', %w(v1 v2)) original_messages = [ { 'channel' => '/messages', 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'User', 'recipient_id' => user.encrypted_id } } }, { 'channel' => '/messages', 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'User', 'recipient_id' => user.encrypted_id } } }, { 'channel' => '/messages', 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => '/messages', 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => '/subscribe', 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } } ] processed_messages = [ { 'channel' => "/v1/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'User', 'recipient_id' => user.encrypted_id } } }, { 'channel' => "/v2/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'User', 'recipient_id' => user.encrypted_id } } }, { 'channel' => "/v1/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'User', 'recipient_id' => user.encrypted_id } } }, { 'channel' => "/v2/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'User', 'recipient_id' => user.encrypted_id } } }, { 'channel' => "/v1/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v2/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v1/users/#{user1.encrypted_id}/messages", 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v2/users/#{user1.encrypted_id}/messages", 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v1/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v2/users/#{user.encrypted_id}/messages", 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v1/users/#{user1.encrypted_id}/messages", 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => "/v2/users/#{user1.encrypted_id}/messages", 'data' => { 'message_type' => 'instant_state', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } }, { 'channel' => '/subscribe', 'data' => { 'message_type' => 'message', 'message' => { 'recipient_type' => 'Circle', 'recipient_id' => circle.encrypted_id } } } ] expect(subject).to receive(:process_without_dispatch).with(processed_messages, nil) subject.process(original_messages, nil) end end end
class MakersController < ApplicationController before_action :require_admin before_action :set_maker, only: [:edit, :update, :show] def index @sort = [params[:sort]] @makers = Maker.paginate(page: params[:page], per_page: 25).order(@sort) end def new @maker = Maker.new end def show end def edit end def update if @maker.update(maker_params) flash[:success] = "Hardware Company was successfully updated" redirect_to makers_path else render 'edit' end end def create @maker = Maker.new(maker_params) if @maker.save flash[:success] = "Hardware company has been created and saved" redirect_to makers_path else render 'new' end end def destroy @maker = Maker.find(params[:id]) @maker.destroy flash[:danger] = "Hardware Company has been deleted" redirect_to makers_path end private def maker_params params.require(:maker).permit(:name, :logo_path, :url, :description) end def set_maker @maker = Maker.find(params[:id]) end def require_admin if (logged_in? and (!current_user.admin? && !current_user.hw_admin?)) || !logged_in? flash[:danger] = "Only admin users can perform that action" redirect_to root_path end end end
class LikesController < ApplicationController def create user = current_user post = Post.find(params[:post_id]) likes = Like.where(:user_id => user, :post_id => post) response = "failure" if likes.size == 0 Like.create(:user => user, :post => post) response = "success" end respond_to do|format| format.json {render :json => {:likes => post.likes.size}} end end def destroy user = current_user post = Post.find(params[:post_id]) like = Like.where(:user_id => user, :post_id => post) like.each do |l| l.destroy end respond_to do|format| format.json {render :json => {:likes => post.likes.size}} end end end
module Mpki::MpkiClient require "#{Rails.root}/lib/Mpki/userManagementServiceDriver.rb" class MpkiClient def initialize(uri_path) @driver = UserManagementOperations.new("https://pki-ws.symauth.com/" + uri_path) @driver.loadproperty("#{Rails.root}/config/mpki.properties") end def create_user(username) userAttribute = NameValueType.new("common_name", username) request_id = "abcd1234" # requestId version = "1.0" # version user_info = UserInformationType.new(username, nil, nil, nil, nil, nil, userAttribute) req = CreateOrUpdateUserRequestMessageType.new(request_id, user_info, version) create_user_result_to_hash(@driver.createOrUpdateUser(req)) end def create_passcode(username, oid) request_id = "abcd1234" # requestId version = "1.0" # version passcode_info = PasscodeInformationType.new(nil, nil, nil, nil, nil, username, oid) req = CreateOrUpdatePasscodeRequestMessageType.new(request_id, passcode_info, version) create_passcode_result_to_hash(@driver.createOrUpdatePasscode(req)) end private def create_user_result_to_hash(ret) ret_hash = { 'clientTransactionID' => ret::clientTransactionID, 'serverTransactionID' => ret::serverTransactionID, 'seatId' => ret::userCreationStatus[0]::seatId, 'statusCode' => ret::userCreationStatus[0]::statusCode, 'version' => ret::version } return ret_hash end def create_passcode_result_to_hash(ret) ret_hash = { 'clientTransactionID' => ret::clientTransactionID, 'serverTransactionID' => ret::serverTransactionID, 'passcode' => ret::passcodeCreationStatus[0]::passcodeInformation::passcode, 'numberOfBadAttempts' => ret::passcodeCreationStatus[0]::passcodeInformation::numberOfBadAttempts, 'passcodeStatus' => ret::passcodeCreationStatus[0]::passcodeInformation::passcodeStatus, 'expiryDateTime' => ret::passcodeCreationStatus[0]::passcodeInformation::expiryDateTime.new_offset(Rational(+9,24)), 'creationDateTime' => ret::passcodeCreationStatus[0]::passcodeInformation::creationDateTime.new_offset(Rational(+9,24)), 'seatId' => ret::passcodeCreationStatus[0]::passcodeInformation::seatId, 'certificateProfileOid' => ret::passcodeCreationStatus[0]::passcodeInformation::certificateProfileOid, 'statusCode' => ret::passcodeCreationStatus[0]::statusCode, 'version' => ret::version } return ret_hash end end end
require 'spec_helper' describe Like do let(:micropost) { FactoryGirl.create(:micropost) } before do @like = micropost.likes.build(micropost_id: micropost.id) @like.user_id = micropost.user.id end subject { @like } it { should respond_to(:micropost_id) } it { should be_valid } describe "when user does not exist" do before { @like.user_id = nil } it { should_not be_valid } end describe "when micropost does not exist" do before { @like.micropost_id = nil } it { should_not be_valid } end end
parsed_directories = JSON.parse(IO.read("config/directories.json")) def keys_to_sym data if data.is_a? Hash new_hash = {} data.each do |k, v| new_hash[k.to_sym] = keys_to_sym v end new_hash elsif data.is_a? Array data.map{|el| keys_to_sym el} else data end end DIRECTORIES = keys_to_sym parsed_directories FUNCTIONS = DIRECTORIES[:functions] REQUEST_OPERATORS = DIRECTORIES[:request_operators] RESOURCE_TYPES = DIRECTORIES[:resource_types] TOOL_TYPES = DIRECTORIES[:tool_types]
# If we build an array like this: flintstones = ["Fred", "Wilma"] flintstones << ["Barney", "Betty"] flintstones << ["BamBam", "Pebbles"] # We will end up with this "nested" array: # ["Fred", "Wilma", ["Barney", "Betty"], ["BamBam", "Pebbles"]] # Make this into an un-nested array. p flintstones.flatten! # Maybe they didn't want this to originally happen. # We could individually push the items. flintstones = ["Fred", "Wilma"] flintstones << "Barney" flintstones << "Betty" flintstones << "BamBam" flintstones << "Pebbles" p flintstones # Or we could use the original format and instead of pushing arrays onto the array # we could add elements to it instead. flintstones = ["Fred", "Wilma"] flintstones += ["Barney", "Betty"] flintstones += ["BamBam", "Pebbles"] p flintstones # Or if we still want to use push we could use the push method and push the element individually again flintstones = ["Fred", "Wilma"] flintstones.push("Barney", "Betty", "BamBam", "Pebbles") p flintstones
# Sous-class Bdoc::Paragraphe class Bdoc class Paragraphe # ------------------------------------------------------------------- # Classe # ------------------------------------------------------------------- # => Extrait les paragraphes de +foo+ et retourne une liste d'instances # de Bdoc::Paragraphe # # @param foo SOIT : # - Le path ou le nom d'un fichier Bdoc (in Bdoc::folder_bdoc) # - Un code string au format Bdoc # - Une instance de document Bdoc # - Un identifiant (Fixnum) def self.extract_paragraphes foo # --- Le code Bdoc à utiliser --- code = case foo.class.to_s when "String" then # Code, nom de fichier bdoc ou path de fichier bdoc if File.exists? foo File.read foo elsif File.exists?(File.join(Bdoc::folder_bdoc, foo)) File.read File.join(Bdoc::folder_bdoc, foo) else foo end when "Bdoc" then return foo.paragraphes.as_array when "Fixnum" then Bdoc::new( foo ).texte end # --- Décomposition du code --- Bdoc::Paragraphes::extract_from_code code end # ------------------------------------------------------------------- # Instance # ------------------------------------------------------------------- @id = nil # Identifiant String. Utiliser méthode éponyme @index = nil # Index du paragraphe dans le document, if any # Cette valeur est calculée lors de l'extraction des # paragraphes, ou updatée par # Bdoc::Paragraphes::update_indexes lors d'ajouts. @bdoc = nil # Instance Bdoc du document contenant le paragraphe, # s'il est défini. Nil si le paragraphe n'appartient # pas à un Bdoc. # Utiliser la méthode éponyme pour le définir. @html = nil # Propriété qui sert localement à construire le code # HTML du paragraphe. @code = nil # Code du paragraphe, c'est-à-dire avec sa balise, # avec ses définitions et son texte @inner = nil # L'intérieur du code, c'est-à-dire tout sauf les # balises. @texte = nil # Contenu textuel du paragraphe (String), donc hors # balises, css ou définition de type. Utiliser la # méthode éponyme pour le récupérer @css = nil # Les classes CSS du paragraphe (Array de String) # Propriétés volatiles # -------------------- @is_titre = nil @data_titre = nil @id_html = nil # Types d'affichages # ------------------ @into_balises = nil # Si défini, c'est une liste de tags dans laquelle # il faut "enrouler" le paragraphe. Par exemple, # si l'entête du paragraphe contient ':pre', # alors le paragraphe est enroulé dans une # balise : <pre>...paragraphe...</pre> @as_liste = nil # Si défini, prend la valeur 'ul' ou 'ol' et # provoque l'affichage du paragraphe comme une # liste HTML. Des classes peuvent être définies # au-dessus ou en dessous de la marque 'ul/ol' @highlighted_code = nil # Si true, c'est un paragraphe de code # "hightlighté" @highlighted_language = nil # Le langage utilisé pour l'highlight du code @collapsable_starting = nil # Si true, le paragraphe doit inaugurer une # section masquable/masquée @collapsable_ending = nil # Si true, le paragraphe est le dernier d'une # section masquable/masquée @collapsable_opened = nil # Si true, la section masquable doit être # visible à l'affichage de la page # Instanciation # -------------- # # @param id Optionnel. L'identifiant (String) du paragraphe, en base # 24. # def initialize id = nil @id = id end # Remet les propriétés volatiles à nil pour forcer leur recalcul # def reset @is_titre, @data_titre, @id_html = nil, nil, nil end # Ré-initialise toutes les propriétés du paragraphe (avant analyse de son # inner) def reset_all @css = nil @into_balises = nil @as_liste = nil @highlighted_code = nil @highlighted_language = nil @collapsable_starting = nil @collapsable_ending = nil @collapsable_opened = nil end # => Return ou définit l'instance Bdoc du document contenant le # paragraphe. # # @param bdoc Instance Bdoc # # @note Le paragraphe peut ne pas appartenir à un document, donc @bdoc # n'est pas toujours défini. # def bdoc bdoc = nil @bdoc = bdoc unless bdoc.nil? @bdoc end # => Return ou définit l'index du paragraphe dans le bdocument # def index value = nil @index = value unless value.nil? @index end # => Return le code HTML du paragraphe, pour affichage # -------------------------------------------------- # # @note: il existe deux types de paragraphes : ceux contenant du texte # normal et ceux contenant du code (et seulement du code) et devant être # évalués # # @param opts Les options. # Hash de clés-valeurs définissant les options d'affichage # :edit Si true, c'est un code pour éditer le paragraphe qui # est renvoyé. false par défaut. # :things Si true, les « things » du paragraphe sont affichées # # def to_html opts = nil opts ||= {} (opts.has_key?(:edit) && opts[:edit]) ? to_edit : contenu_formated(opts) end # Actualise les données du paragraphe # # @param hvars Hash de clés-valeurs où `cle' est la propriété du para- # graphe et 'valeur' la valeur à lui donner. Traitement # spécial de la clé `texte' qui peut définir plusieurs # (nouveaux) paragraphes. # # @note Traitement spécial lorsque c'est un titre de niveau 1 du # tout premier paragraphe => ça change le titre du document. # Noter que le titre est forcément défini à la création de la page # Si ce premier paragraphe est transformé, sans être un titre, le # titre original reste en place. # @TODO: à l'avenir, il faudra un autre comportement : lorsque # le titre sera supprimé, on mettre un titre provisoire # "Sans titre" et un message sera envoyé à l'utilisateur, l'invitant # à le définir en définissant le premier paragraphe. # def update hvars old_texte = self.texte reset hvars.each do |prop, new_value| case prop.to_sym when :texte then texte_has_changed = old_texte != new_value update_inner( new_value ) @is_titre, @data_titre = nil, nil if texte_has_changed && index == 0 && titre? && data_titre[:level] == 1 new_title_for_page data_titre[:titre] end else instance_variable_set("@#{prop}", new_value) end end end # Les deux méthodes suivantes permettent de définir des textes variables # à utiliser dans la page. Elles sont maintenues par la classe, dans un # Hash. # @usage : cf. le document de référence Bdoc.md # # @param hvars Hash de paires clé-valeur où `clé' est la variable qui # pourra être récupérée avant `get' dans un texte (on # peu utiliser aussi « #{variable} » tout seul). # def set hvars Bdoc::consigne_variables hvars end # => Return la valeur consignées avec la clé +var+ soit dans les valeurs # consignées par `set' ci-dessus (dans Bdoc::variables_consigned) soit # dans les paramètres. # @return la valeur trouvée ou nil def get var res = Bdoc::get_variables_consigned( var ) return res unless res.nil? res = param( var.to_sym ) return res unless res.nil? param( var.to_s ) end # => Return le @texte formaté HTML # ----------------------------- # Ce texte contient les styles définis, met en forme le titre si c'en est # un (et l'enregistre dans la table des matières de la page) # Et ajoute les boutons d'édition, de Things ou de commentaires. # Il convertit aussi les marques de formatage spéciales (étoiles, crochets # avec [url], [route], etc.) # # @param options Les options de conversion. Cf. la class String # rallonge de la class Bdoc pour le détail. # def contenu_formated options = nil if titre? contenu_formated_as_titre else ( contenu_formated_by_type + boutons_edition ).as_div( :id => id_html, :class => ((@css || []) << "bdoc_p").join(' ') ) end.convert( options ) end # => Return le texte formaté suivant son type def contenu_formated_by_type if @type.nil? @html = if @as_liste != nil contenu_formated_as_liste else contenu_formated_as_texte end eval_variables_ruby balises_warping unless @into_balises.nil? else # quand @type est défini # @TODO: ce `@type' devient ambigu, il faudrait lui donner un autre nom @html = eval( texte ) end return @html end # => Enroule le code HTML du paragraphe dans les balises définies dans # l'entête. Par exemple, si @into_balises = ['pre'], alors le code est # enroulé dans "<pre>...paragraphe...</pre>" def balises_warping @into_balises.reverse.each do |balise| @html = BuilderHtml::wrap(balise, @html) end end # => Évalue les portions #{...} dans un texte simple (sauf pour les # paragraphe qui sont du code colorisé) # cf. le document de référence Bdoc.md pour l'utilisation détaillée. def eval_variables_ruby return if @html.index(/#\{/).nil? # pas de code ruby return @html if @highlighted_code # pas d'évaluation pour extraits de code @html = @html.gsub(/[^\\]#\{(.*?)\}/) do code = $1 res = nil # On essaie de voir d'abord si on a affaire à une variable consignée if code.index(" ").nil? res = get(code) end eval(code) if res.nil? res end end # => Return le texte formaté HTML comme une liste UL/OL def contenu_formated_as_liste items = texte.split("\n") index_item = items.count - 1 items = items.collect do |item| # Ajout du point final ? if index_item > 0 && !item.end_with?( ';' ) item += " ;" elsif index_item == 0 && !(item[-1..-1] =~ /[.?!…]/) item += "." end index_item -= 1 item.as_li end.join('') @as_liste == 'ul' ? items.as_ul : items.as_ol end REG_RETRAITS = %r{(–|-|•| |->|>) } LENGTH_PARAGRAPHE_CUT_UP = 72 # @TODO: Quand le texte contient le style explication_code, alors il faut # découper le texte (qui peut contenir des retours chariot simples) en # lignes de maximum 72 lettres de long. # + prendre en compte les retraits : si une phrase commence avec un retrait # ou un signe comme un signe "- ", alors il faut conserver ce retrait # pour les lignes qui le composent. # Il faut faire un algorithme qui fasse ça très proprement. # # @param texte Le texte à découper # @param length La longueur maximale de la ligne REG_HTML_TAG = /<[^>]+>/ def cut_up texte, length_max = LENGTH_PARAGRAPHE_CUT_UP lines = [] # Boucle sur chaque paragraphe texte.split("\n").each do |paragraphe| if paragraphe.length <= length_max lines << paragraphe else # # Traitement nécessaire # ---------------------- # Il faut prendre la longueur exacte nécessaire, en tenant compte # des balises de formatage (<b>, <i>, etc.) qui peuvent composer le # paragraphe. # @note 1 Ces balises ne doivent pas contenir d'espace, dans lequel # cas la balise serait découpée (mais ça ne doit pas poser # de problème, a priori, puisque l'HTML supporte très bien # ce genre de chose) # @note 2 Si le paragraphe commence par des espaces, ou un signe # reconnu comme "- ", "• ", "> " (voir la liste), alors # tout le paragraphe sera mis en retrait. # retrait_fois = 0 # Nombre retraits (à cause d'Unicode) retrait_length = 0 # Longueur du retrait retrait_mark = "" # Marque de début de paragraphe retrait_vide = "" # Espace de début de ligne pour les autres # lignes que la première # Calcul du retrait # ----------------- # C'est la première ligne, il faut voir si elle ne commence pas # par une marque de retrait. Cf. `liste_retraits' # La boucle est nécessaire dans le cas de doubles espaces multiples # Dans les autres cas ("- ", "• ", etc.) elle n'aura pas lieu. while paragraphe.index(/^#{REG_RETRAITS}/) != nil paragraphe = paragraphe.sub(/^#{REG_RETRAITS}/){ retrait_fois += 1 retrait_mark += $& "" } end retrait_length = retrait_fois * 2 real_length_max = length_max - retrait_length retrait_vide = " " * retrait_length retrait_other_lines = "\n#{retrait_vide}" length_retrait_other_lines = retrait_other_lines.length # Découpe # -------- # Principe : on se sert de la méthode `insert' pour insérer : # - la marque de fin de ligne # - le retrait # dans la chaine jusqu'à arriver au bout. # @note: on ne tient pas compte des balises HTML, car de toute # façon, le texte ne sera que rarement justifié, donc peut importe # ou alors on va essayer quand même de repérer first_index = 0 # Tous les extraits du paragraphe seront mis dans cette liste extraits = [] iloop = 0 while first_index < paragraphe.length iloop += 1 if iloop > 50 break end last_index = first_index + real_length_max + 1 section_prov = paragraphe[first_index..last_index] if last_index >= paragraphe.length extraits << section_prov.strip break end # Si la section contient des balises HTML, on ne doit pas les # compter dans la longueur d'extrait prise unless section_prov.index(REG_HTML_TAG).nil? last_index += 1 ajout = 0 section_prov.scan(REG_HTML_TAG){ |m| ajout += m.length } # On étudie l'extrait à ajouter bout_extrait = paragraphe[last_index..(last_index+ajout)] pointeur = last_index + ajout bout_total = "" + bout_extrait unless bout_extrait.index(REG_HTML_TAG).nil? ajout = 0 bout_extrait.scan(REG_HTML_TAG){ |m| ajout += m.length} bout_extrait = paragraphe[pointeur..(pointeur+ajout)] pointeur += ajout bout_total += bout_extrait end else bout_total = "" end # La section réellement prise en compte, en excluant les balises # HTML du comptage de la longueur (ci-dessus) # @note: pour l'instant, il reste une erreur, quand on rajoute # une partie qui elle-même contient des balises HTML # real_section = paragraphe[first_index..last_index] real_section = section_prov + bout_total # Fin de la section # L'index du dernier espace ou ">" index_eol = real_section.rindex(/[ ><]/) index_eol = real_section.length -2 if index_eol.nil? # On pourrait insérer le caractère, mais il risquerait de rester # des espaces en début de ligne. Donc on procède autrement : # on extrait la portion du paragraphe pour la travailler extrait = paragraphe[first_index..(first_index + index_eol)].strip extraits << extrait # On insert le retrait à l'endroit voulu # OBSOLÈTE: on ne touche plus au paragraphe # paragraphe.insert( first_index + index_eol, retrait ) # On définit le premier index suivant first_index += index_eol #+ length_retrait end lines << retrait_mark + extraits.join(retrait_other_lines) end end lines.join("\n") end # => Return le texte formaté HTML quand ce n'est pas un titre # def contenu_formated_as_texte html = "" texte_init = need_cut_up? ? cut_up(texte) : texte if @collapsable_starting id = "collapsed_" + (@icollapsed = @icollapsed.nil? ? 1 : @icollapsed + 1).to_s # Fermé ou ouvert ? style = @collapsed_opened ? "" : "display:none;" # @TODO: METTRE ICI LE LIEN POUR MASQUER/AFFICHER html += '<div id="' + id + '" class="collapsable" style="'+style+'">' end if @highlighted_code texte_init = '<pre><code data-language="' + @highlighted_language + '">' + texte_init + "</code></pre>" end html += texte_init # Les fermetures éventuelles html += '</div>' if @collapsable_ending return html end # => Return true si le paragraphe doit être découpé. # Le paragraphe est à découpé s'il contient la class css 'dissection' # et s'il est plus long que la longueur de paragraphe découpé def need_cut_up? return false if @css.nil? return false unless @css.include?('dissection') return @texte.length > LENGTH_PARAGRAPHE_CUT_UP end # => Return le contenu formaté HTML comme un titre si le paragraphe # définit un titre (entre signes '=') # # @note: Si on appelle cette méthode, c'est que le titre sera inséré # dans la page. Donc c'est cette méthode-ci qui se charge # d'incrémenter la Bdoc::Tdm de la page. # (en prévision du fait que peut-être une portion seulement de la # page pourrait être utilisé, par exemple pour constituer une # nouvelle page à l'aide d'autres fragments de page.) # # @note Le titre est enroulé dans un H1 (surtout pour la conformité avec # le portail). S'il s'avère qu'un autre titre doit "surplomber" ce # titre, alors utiliser plutôt un div de class spéciale, par ex. # "grand_titre_page" # def contenu_formated_as_titre dt = data_titre dt = dt.merge :id => id_html # Ajout du titre à la table des matières du Bdoc (s'il existe) bdoc.tdm.add( dt ) unless bdoc.nil? # CSS dt[:css] = "#{@css || ''} #{dt[:css] || ''} bdoc_p".strip # Retourner le code HTML (dt[:titre] + boutons_edition).as_h(dt[:level], :id =>id_html, :class => dt[:css]) end # => Return true si le paragraphe définit un titre def titre? @is_titre ||= begin if data_titre.nil? false else ! @data_titre[:level].nil? # @note: le level du titre est forcément défini si un titre # conforme a été trouvé. end end end # => Return ou définit les data pour un titre, si le paragraphe est # un titre def data_titre @data_titre ||= data_titre_if_titre end # => Return les données du titre, ou nil si le texte n'est pas un titre # # @return nil si mauvais titre ou Un Hash contenant : # :titre Le texte du titre à afficher # :level Le niveau (1-start) # :id L'identifiant à utiliser / nil # :css Array des class css / nil # def data_titre_if_titre return nil unless texte.start_with? '=' data = {:level => nil, :titre => nil, :id => nil, :css => nil } texte.sub(/^(=+) (.*?)(?:\|(.*?))?(?:\|(.*))?\1$/){ tout, level, titre, id, css = [$&, $1, $2, $3, $4] data[:level] = level.strip.length data[:titre] = titre.strip unless id.nil? id = id.strip data[:id] = id unless id.blank? end unless css.nil? css = css.strip data[:css] = css unless css.blank? end } data end # Définit ou retourne le nouveau titre pour la page, quand le paragraphe # est le premier et que c'est un titre de niveau 1 # # @note: Cette méthode NE s'assure PAS que le titre soit unique dans # le livre si on travaille avec un PISite. C'est aux méthodes de # PISite de le faire. # # @note: Cette méthode ne doit être appelée qu'après s'être assuré que : # self.index == 0 Tout premier paragraphe # self.titre? C'est un titre # self.data_titre[:level] == 1 C'est un titre de premier niveau # new ≠ old Le texte a changé # def new_title_for_page valeur = nil if valeur.nil? then @new_title_for_page else @new_title_for_page = valeur end end # => Return le code HTML des boutons d'édition pour le paragraphe # # Ces boutons permettent : # ADMINISTRATEUR # - d'éditer le paragraphe # - de déplacer le paragraphe # - de poser une question/faire une remarque # - de répondre à une question / une remarque # SIMPLE USER # - de poser une question/faire une remarque # - de lire les questions/remarques # def boutons_edition btns = "" btns += (btn_edit+btn_up+btn_down+btn_destroy) if U.admin? btns += btn_commenter btns += btn_questionner btns += btn_read_comments btns.as_div( :class => 'btns_edition') end # => Return le code HTML de tous les boutons d'édition def btn_edit build_btn_edition 'edit', "Éditer" end def btn_up build_btn_edition 'up', "Up" end def btn_down build_btn_edition 'down', "Down" end def data_for_thing # @note à propos de :pid ci-dessous. Normalement, il n'y a que pendant # les tests que bdoc peut ne pas être défini. { # :type, :titre, :action, :class à définir par la méthode appelante :ptype => 'bdoc', :pid => (bdoc.nil? ? nil : bdoc.id), :sptype => "paragraphe", :spid => self.id, } end def btn_questionner Question::link_to(data_for_thing.merge( :titre => U.admin? ? "Questionner" : "Question sur ce paragraphe", :action => 'new', :class => 'btn_question' ) ) end def btn_answer return "" unless U.admin? Question::link_to(data_for_thing.merge( :titre => "Répondre", :action => 'answer', :class => 'btn_question' ) ) end def btn_commenter # puts "\ndata_for_thing in btn_commenter: #{data_for_thing.inspect}" Comment::link_to(data_for_thing.merge( :titre => U.admin? ? "Commenter" : "Commenter ce paragraphe", :action => 'new', :class => 'btn_comment' ) ) end def btn_read_comments Comment::link_to(data_for_thing.merge( :type => 'comment', :titre => U.admin? ? "Lire coms" : "Lire les commentaires/questions", :action => 'show', :class => 'btn_comment' ) ) end # => Return le code pour le bouton Supprimer (le paragraphe) def btn_destroy name = "Supprimer" return "" unless U.admin? build_btn_edition 'destroy', name end def build_btn_edition action, btn_name "[#{btn_name}]".as_link( :href => route_to_action(action), :class => "btn_#{action}" ) end def route_to_action action bdoc_id = bdoc.nil? ? nil : bdoc.id.to_s route_to("paragraphe/#{id}/#{action}", :bdoc_id => bdoc_id, '#' => id_html ) end # => Return le code d'édition du paragraphe # --------------------------------------- # def to_edit # Textarea contenant le texte du paragraphe idtxta = "txta_#{id_html}" # html = texte.as_textarea( :id => idtxta, :name => idtxta ) html = inner.as_textarea( :id => idtxta, :name => idtxta ) html += bdoc.id.to_s.as_hidden( :name => "bdoc_id" ) unless bdoc.nil? # Boutons (sauver, supprimer, annuler) html += (submit_button + btn_destroy + cancel_button). as_div(:class => 'btns_edition') # Assemblage du formulaire data_form = {:id => "edit_#{id_html}", :action => route_to_action('update')} html.as_form( data_form ).as_div(:id => id_html) end # => Return le code HTML pour le bouton submit de nom +nom+ def submit_button name = "Enregistrer" name.as_submit end # => Return le code pour le bouton annuler def cancel_button name = "Annuler" href = route_to("#{PISite::folder}/#{bdoc.id}/show") name.as_link(:href => href, :class => 'btn_cancel') end # # => Retourne l'identifiant HTML def id_html @id_html ||= "bdoc_p-#{id}" end # => Return le code du paragraphe # ------------------------------------------- # # @note Le `code` est l'intégralité des informations du paragraphe, # au format String, donc entre les balises de délimitation. # @note Il ne faut pas le consigner dans une propriété, car ce code # peut être actualisé très souvent. # # @return le String du paragraphe au format bdoc. # def code assemble_code end alias :to_file :code # => Return le code assemblé pour enregistrement du paragraphe def assemble_code balise_in + "\n" + inner + "\n" + balise_out end # => Return ou définit l'inner du code # def inner valeur = nil valeur.nil? ? get_inner() : set_inner( valeur ) end # => Définit l'inner du code # ------------------------ # # Analyse +code+, qui est le contenu d'un paragraphe Bdoc, hors balises # # @note Contrairement à l'ancienne version des Bdoc (rubysites), c'est # seulement la première ligne qui peut définir le paragraphe, sauf # pour :collapsable et :/collapsable qui définissent simplement # une section « fermable » # Cette première ligne, si elle commence par un ":", définit # quelquechose : cf. le document de référence Bdoc.md # def set_inner code ary_code = code.split(/\r?\n/) ary_code = analyse_lines_twodots( ary_code ) if ary_code.first.start_with?( ':' ) @texte = ary_code.join("\n") end # Analyse de la ligne +line+ qui commence par ":" # Permet de définir de nombreuses choses pour le paragraphe courant # cf. ci-dessus la méthode set_inner # # @return Les lignes qui restent (Array) après avoir retiré les lignes # commençant par ":" # # WARNING: SI UN TRAITEMENT EST AJOUTÉ ICI, AVEC UNE NOUVELLE PROPRIÉTÉ, # IL FAUT ABSOLUMENT RÉ-INITIALISER CETTE PROPRIÉTÉ CI-DESSUS DANS LA # MÉTHODE `reset_all' # WARNING: NE PAS OUBLIER NON PLUS D'AJOUTER CETTE PROPRIÉTÉ À L'ASSEMBLAGE # DU PARAGRAPHE AVANT ENREGISTREMENT/ÉDITION (DANS `get_inner' ci-dessous). def analyse_lines_twodots lines # Dans tous les cas, il faut initialiser toutes les propriétés du # paragraphe, car c'est peut-être un update. Or, dans le cas d'un update # le paragraphe a été chargé, donc analysé, et il faut remettre tout à # zéro puisque l'« inner » peut tout redéfinir reset_all first_line = lines.delete_at 0 first_mots = first_line[1..-1].gsub(/ ( *)/,' ').split(/[ |=]/) if Bdoc::LANGAGES.include? first_mots.first # C'est un langage de programmation, on définit le type # Le reste (s'il y a d'autres mots) est ignoré pour le moment @type = first_mots.first else first_mot = first_mots.first.downcase case first_mot when 'pre' @into_balises ||= [] @into_balises += first_mots when "ul", "ol" @as_liste = first_mot when "code" # Section de code à highlighter. Le second mot doit # définir le langage @highlighted_code = true @highlighted_language = first_mots[1] # @TODO: Plus tard, chargement automatique du script rainbow et # de la feuille js pour le langage défini. when "collapsable" # Ouverture d'une section masquable @collapsable_starting = true @collapsable_opened = first_mots[1] == "true" when "/collapsable" # Fermeture d'une section masquable @collapsable_ending = true else # Alors ce sont une ou des classes css qu'on ajoute @css = (@css || []) + first_mots end end # On poursuit, si la ligne suivante commence aussi par ":" lines = analyse_lines_twodots( lines ) if lines.first.start_with?(':') return lines end def highlighted_code? @highlighted_code === true && ! @highlighted_language.to_s.blank? end # => Retourne l'inner du code # ------------------------ # # Recompose le code du paragraphe Bdoc d'après ses données. def get_inner inn = [] inn << ":collapsable" if @collapsable_starting inn << ":/collapsable" if @collapsable_ending inn << ":code=#{@highlighted_language}" if highlighted_code? inn << ":#{@into_balises.join(' ')}" unless @into_balises.nil? if simple_text? inn << ":#{@css.join(' ')}" unless @css.nil? inn << ":#{@as_liste}" unless @as_liste.nil? else # par exemple du code ruby, javascript, etc. inn << ":#{@type}" unless @type.nil? end inn << texte inn.join("\n") end # => Return ou définit le texte du paragraphe def texte txt = nil @texte = txt unless txt.nil? @texte ||= "" end def balise_in; @balise_in ||= "::#{id}::" end def balise_out; @balise_out ||= "::/#{id}::" end # => Return ou définit l'identifiant unique du paragraphe def id; @id ||= Time.now.to_i.to_s(24) end def timestamp; @timestamp ||= id.to_i(24) end def date; @date ||= Time.at timestamp end # --- Type du Bdoc --- def type; @type end def simple_text?; type == nil end def ruby?; type == 'ruby' end # => Ajoute la classe +classcss+ au paragraphe # def add_css classcss @css ||= [] @css << classcss unless @css.include? classcss end # => Actualise le texte du paragraphe # -------------------------------- # # Cette méthode est tout à fait spéciale dans le sens où elle est # capable de créer de nouveau paragraphe. Car si le texte fourni dans # +code+ contient plusieurs paragraphes, il faut les créer. Un texte de # paragraphe ne peut pas contenir deux retours-chariots à la suite, par # définition et par essence. def update_inner code code = code.strip.gsub(/\r/,'') ary_para = code.split("\n\n") # Dans tous les cas, le premier paragraphe trouvé redéfini ce paragraphe set_inner ary_para.delete_at(0) # Si la liste ne contient qu'un seul élément, c'est un update simple, # sans ajout de paragraphe return if ary_para.empty? # Des nouveaux paragraphes doivent être créés et ajoutés au document index_courant = self.index now = Time.now.to_i # Pour obtenir des ids en série uniques now += 1 while bdoc.paragraphes.by_id[now.to_s(24)] != nil ary_para.each do |inner_paragraphe| id_new = (now += 1).to_s(24) new_paragraphe = Bdoc::Paragraphe::new( id_new ) new_paragraphe.bdoc( bdoc ) new_paragraphe.set_inner inner_paragraphe bdoc.paragraphes.add new_paragraphe, (index_courant += 1) end end end # /class Bdoc::Paragraphe end # / class Bdoc
class VideoSerializer < ActiveModel::Serializer attributes :title, :type, :description, :youtube, :vimeo def href object.link end def type 'text/html' end def description object.video_description.empty? ? object.video_description : object.title end def youtube regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/ match = regExp.match(object.link) match && match[7].length == 11 ? match[7] : "" end def vimeo regExp = /(?:https?:\/\/)?(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/ match = regExp.match(object.link) match && match[3].length == 9 ? match[3] : "" end end
require "rdf" require "rdf/n3" class SocialNetworkRDFSerializer def initialize(social_network, include_visual_data = false) @social_network = social_network @include_visual_data = include_visual_data end def to_rdf base = options[:base_uri] RDF::Writer.for(:n3).buffer(options) do |writer| writer << RDF::Statement.new(@social_network.uri(base), prefix(:rdf, :type), sn(:socialNetwork)) writer << RDF::Statement.new(@social_network.uri(base), sn(:name), @social_network.name) writer << RDF::Statement.new(@social_network.uri(base), prefix(:dc, :description), @social_network.description) @social_network.nodes.each do |node| node_uri = node.uri(base) writer << RDF::Statement.new(node_uri, prefix(:rdf, :type), sn(node.kind.downcase)) writer << RDF::Statement.new(node_uri, sn(:name), node.name) writer << RDF::Statement.new(node_uri, sn(:kind), node.kind) if visual_data? writer << RDF::Statement.new(node_uri, sn(:positionX), node.x) writer << RDF::Statement.new(node_uri, sn(:positionY), node.y) end node.families.each do |family| writer << RDF::Statement.new(node_uri, sn(:belongsToFamily), family.uri(base)) end node.node_attributes.each do |attribute| attribute_uri = attribute.uri(base) writer << RDF::Statement.new(node_uri, sn(:hasAttribute), attribute_uri) writer << RDF::Statement.new(attribute_uri, prefix(:rdf, :type), sn(:attribute)) writer << RDF::Statement.new(attribute_uri, sn(:key), attribute.key) writer << RDF::Statement.new(attribute_uri, sn(:value), attribute.value) end end @social_network.roles.each do |role| role_uri = role.uri(base) writer << RDF::Statement.new(role_uri, prefix(:rdf, :type), sn(:role)) writer << RDF::Statement.new(role_uri, sn(:name), role.name) writer << RDF::Statement.new(role.actor.uri(base), sn(:participatesAs), role_uri) writer << RDF::Statement.new(role_uri, sn(:inRelation), role.relation.uri(base)) end @social_network.families.each do |family| family_uri = family.uri(base) writer << RDF::Statement.new(family_uri, prefix(:rdf, :type), sn(:family)) writer << RDF::Statement.new(family_uri, sn(:name), family.name) writer << RDF::Statement.new(family_uri, sn(:kind), family.kind) if visual_data? writer << RDF::Statement.new(family_uri, sn(:color), family.color) end end end end def visual_data? @include_visual_data end def sn(content) prefix(:sn, content) end def prefix(name, content) options[:prefixes][name.to_sym] + content.to_s end def options @options ||= { base_uri: RDF::URI("http://sn.dcc.uchile.cl/"), prefixes: { rdf: RDF.to_uri, rdfs: RDF::RDFS.to_uri, sn: RDF::URI("#{SocialNetwork.vocabulary}#"), dc: RDF::DC.to_uri, } } end end
class EditColumns < ActiveRecord::Migration def change remove_column :services, :socks_per_month add_column :services, :socks_per_month, :integer end end
class Banner < ActiveRecord::Base validates_presence_of :image, :category_id mount_uploader :image, ImageUploader belongs_to :category def as_json(opts = {}) { id: self.id, title: self.title || "", image_url: self.image_url, link: Setting.upload_url + "/banners/#{self.id}", } end def image_url if self.image self.image.url(:large) else "" end end end
require 'test_helper' class AppointmentTest < ActiveSupport::TestCase fixtures :pets, :users test "Validate date of visit is not in the past" do appointment = Appointment.create(date_of_visit: DateTime.now - 1.day, pet: pets(:tommy), customer: "Nancy", user: users(:doctor_robert), reason_for_visit: "Tommy not feeling good") assert !appointment.valid? assert_equal appointment.errors.full_messages.first, "Date of visit cannot be in the past" end end
describe Kafka::Protocol::Encoder do let(:io) { StringIO.new("") } describe '#write_varint' do context 'data = 0' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(0) expect(binaries_in_io(io)).to eq ["00000000"] end end context 'data is positive' do context 'data is stored in 1 group' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(10) expect(binaries_in_io(io)).to eq ["00010100"] end end context 'data exceeds max of 1 group' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(63) expect(binaries_in_io(io)).to eq ["01111110"] end end context 'data is stored in 2 groups' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(300) expect(binaries_in_io(io)).to eq ["11011000", "00000100"] end end context 'data is stored in 3 groups' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(215233) expect(binaries_in_io(io)).to eq ["10000010", "10100011", "00011010"] end end context 'data is max positive int 64' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(2**63 - 1) expect(binaries_in_io(io)).to eq [ "11111110", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "00000001" ] end end context 'data contains all trailing zero' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(2**62) expect(binaries_in_io(io)).to eq [ "10000000", "10000000", "10000000", "10000000", "10000000", "10000000", "10000000", "10000000", "10000000", "00000001" ] end end end context 'data is negative' do context 'data is stored in 1 group' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(-10) expect(binaries_in_io(io)).to eq ["00010011"] end end context 'data exceeds max of 1 group' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(-63) expect(binaries_in_io(io)).to eq ["01111101"] end end context 'data is stored in 2 groups' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(-300) expect(binaries_in_io(io)).to eq ["11010111", "00000100"] end end context 'data is stored in 3 groups' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(-215233) expect(binaries_in_io(io)).to eq ["10000001", "10100011", "00011010"] end end context 'data is min negative int 64' do it do encoder = Kafka::Protocol::Encoder.new(io) encoder.write_varint(-2**63) expect(binaries_in_io(io)).to eq [ "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "00000001" ] end end end end end def binaries_in_io(io) io.string.bytes.map { |byte| byte.to_s(2).rjust(8, '0') } end
require "test_helper" class EventTest < ActiveSupport::TestCase # Matchers should belong_to(:organization) should validate_presence_of(:organization_id) should allow_value(Date.current).for(:date) should allow_value(Date.tomorrow).for(:date) should allow_value(Date.yesterday).for(:date) should_not allow_value(2).for(:date) should_not allow_value(2.5).for(:date) should_not allow_value("bad").for(:date) should_not allow_value(nil).for(:date) # Context context "Given context" do setup do create_organizations create_events end should "identify a non-active organization as part of an invalid event" do inactive_org = FactoryBot.create(:organization, name: "ghost", short_name: "ghost", active: false) invalid_event = FactoryBot.build(:event, organization: inactive_org) deny invalid_event.valid? end should "identify a non-existent organization as part of an invalid event" do ghost_org = FactoryBot.build(:organization, name: "ghost", short_name: "ghost", active: true) invalid_event = FactoryBot.build(:event, organization: ghost_org) deny invalid_event.valid? end end end
require 'tmpdir' require 'fileutils' tmsupport_path = File.join(ENV['HOME'], 'Library', 'Application Support', 'TextMate') tmplugins_path = File.join(tmsupport_path, 'PlugIns') tmbundles_path = File.join(tmsupport_path, 'Bundles') plugin_repos = [ 'https://github.com/enormego/EGOTextMateFullScreen.git', 'https://github.com/fdintino/projectplus.git' ] bundles_repo = 'git@github.com:ggilder/tmsetup.git' desc "Install latest versions of TextMate plugins" task :plugins do |t| Dir.mktmpdir do |build_dir| puts "Installing TextMate Plugins..." puts "tmp dir #{build_dir}" plugin_repos.each do |repo| repo_dir = File.basename(repo, File.extname(repo)) puts "Building #{repo_dir}..." `cd #{build_dir} && git clone #{repo} && cd #{repo_dir} && xcodebuild` end products = Dir.glob(File.join(build_dir, '*', 'build', 'Release', '*.tmplugin')) products.each do |product| print "Installing #{File.basename(product)}... " destination = File.join(tmplugins_path, File.basename(product)) remove_entry_secure(destination, true) if File.exists?(destination) FileUtils.mv product, tmplugins_path puts "installed." end end end desc "Install or update TextMate bundles" task :bundles do |t| puts "Updating TextMate Bundles at #{tmbundles_path}..." git_branch = `cd "#{tmbundles_path}" && git symbolic-ref HEAD 2>/dev/null` if git_branch.empty? puts "No git repo in bundle path, setting up tracking..." `cd "#{tmbundles_path}" && git init && git remote add origin #{bundles_repo} && git fetch origin && git branch -t bundles origin/bundles && git checkout -f bundles && git submodule init && git submodule update` puts "Done setting up." else `cd "#{tmbundles_path}" && git pull && git submodule init && git submodule update` puts "Done updating." end # reload bundles `osascript -e 'tell app "TextMate" to reload bundles'` if `ps -x` =~ /TextMate\.app/ end desc "Install TextMate plugins and bundles" task :tmsetup => [:bundles, :plugins]
# frozen_string_literal: true module Hanamimastery module CLI module Commands class ToPRO < Dry::CLI::Command desc 'Renders HTML out of Markdown' argument :episode, type: :integer, required: :true, desc: "Episode's ID to render" option :save, aliases: ['-s'], type: :boolean, default: false, desc: 'Save to file?' include Deps[ repository: 'repositories.episodes', transformation: 'transformations.to_pro' ] def call(episode:, save:, **) content = repository.fetch(episode).content processed = transformation.call(content) save ? File.write("#{episode}-episode.html", processed) : puts(processed) end end end end end
class CreateComments < ActiveRecord::Migration[6.0] def change create_table :comments do |t| t.string :pseudo t.string :email t.string :content t.string :secret t.boolean :published, default: false t.integer :word_id t.timestamps end end end
require 'google/apis/script_v1' require 'googleauth' require 'googleauth/stores/file_token_store' require 'fileutils' require '/home/bhargav/Github/ruby_astm/adapter' class Google_Lab_Interface < Adapter OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze APPLICATION_NAME = 'Google Apps Script API Ruby Quickstart'.freeze CREDENTIALS_PATH = 'credentials.json'.freeze # The file token.yaml stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. TOKEN_PATH = 'token.yaml'.freeze SCOPE = 'https://www.googleapis.com/auth/script.projects'.freeze SCOPES = ["https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/script.projects","https://www.googleapis.com/auth/spreadsheets"] $service = nil SCRIPT_ID = "M7JDg7zmo0Xldo4RTWFGCsI2yotVzKYhk" ## # Ensure valid credentials, either by restoring from the saved credentials # files or intitiating an OAuth2 authorization. If authorization is required, # the user's default browser will be launched to approve the request. # # @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials def authorize client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH) token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH) authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store) user_id = 'default' credentials = authorizer.get_credentials(user_id) if credentials.nil? url = authorizer.get_authorization_url(base_url: OOB_URI) puts 'Open the following URL in the browser and enter the ' \ "resulting code after authorization:\n" + url code = gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI ) end credentials end def initialize puts "initializing lab interface." $service = Google::Apis::ScriptV1::ScriptService.new $service.client_options.application_name = APPLICATION_NAME $service.authorization = authorize end # method overriden from adapter. # data should be an array of objects. # see adapter for the recommended structure. def update_LIS(data) orders = JSON.generate(data) pp = { :input => orders } request = Google::Apis::ScriptV1::ExecutionRequest.new( function: 'update_report', parameters: pp ) ## here we have to have some kind of logging. ## should it be with redis / to a log file. ## logging is also sent to redis. ## at each iteration of the poller. begin puts "request is:" puts request.parameters.to_s puts $service.authorization.to_s resp = $service.run_script(SCRIPT_ID, request) if resp.error puts "there was an error." else puts "success" end rescue => e puts "error ----------" puts e.to_s end end end
class AdminMailer < ActionMailer::Base default from: "no-reply@acfb.org" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.admin_mailer.new_agency.subject # def new_agency(agency) @greeting = "Aloha!" @agency = agency mail to: "someone_to_update_later@acfb.org" end end
wordList = ["laboratory", "experiment", "Pans Labyrinth", "elaborate"] # using include method # def findLab(word) # if word.include?("lab") # puts word # else # nil # end # end # # using regex # def findLab(word) # if /lab/ =~ word # puts word # else # nil # end # end # using regex with case insensitive option 'i' def findLab(word) if /lab/i =~ word puts word else nil end end wordList.each { |word| findLab(word)}
require 'rails_helper' describe FantasyLeague do context "validations" do # Associations it { should have_many(:fantasy_teams) } # Validations it { should validate_presence_of(:year) } it { should validate_presence_of(:division) } end describe ".right_joins_fantasy_players" do it "returns all fantasy players with their owners in a league" do fantasy_league_a = create(:fantasy_league, year: 2016, division: "A") fantasy_league_b = create(:fantasy_league, year: 2016, division: "B") fantasy_team_a = create(:fantasy_team, name: "Axel", fantasy_league: fantasy_league_b) fantasy_team_b = create(:fantasy_team, name: "Brown", fantasy_league: fantasy_league_b) owned_player = create(:fantasy_player, name: "PlayerA") create(:roster_position, fantasy_player: owned_player, fantasy_team: fantasy_team_b) unowned_player = create(:fantasy_player, name: "PlayerB") result = FantasyLeague.right_joins_fantasy_players(fantasy_league_b.id) expect(result.map(&:fantasy_player_name)).to eq(%w(PlayerA PlayerB)) # Need to fix to include Axel not exact expect(result.map(&:fantasy_team_name)).to_not eq(%w(Axel)) end end describe ".fantasy_team_subquery_by_league(league)" do it "joins only fantasy teams in a league" do fantasy_league_a = create(:fantasy_league, year: 2016, division: "A") fantasy_league_b = create(:fantasy_league, year: 2016, division: "B") fantasy_team_a = create(:fantasy_team, fantasy_league: fantasy_league_a) fantasy_team_b = create(:fantasy_team, fantasy_league: fantasy_league_b) result = FantasyLeague. fantasy_team_subquery_by_league(fantasy_league_a.id) expect(result.map(&:division)).to eq(%w(A)) end end describe ".select_fantasy_league_columns" do it "selects all attribute columns" do fantasy_league_a = create(:fantasy_league, year: 2016, division: "A") result = FantasyLeague.select_fantasy_league_columns expect(result.map(&:division)).to eq(%w(A)) end end describe ".only_league(league)" do it "returns only one league by league id" do fantasy_league_a = create :fantasy_league, division: "A" fantasy_league_a_id = fantasy_league_a.id create(:fantasy_league, division: "B") result = FantasyLeague.only_league(fantasy_league_a_id) expect(result.map(&:division)).to eq(%w(A)) end end describe "#name" do it "returns the name of the fantasy league" do fantasy_league = create(:fantasy_league, year: 2016, division: "A") result = fantasy_league.name expect(result).to eq "2016 Division A" end end end
class User < ActiveRecord::Base has_and_belongs_to_many :smart_products has_and_belongs_to_many :detections has_many :mobile_devices, :dependent => :destroy validates_uniqueness_of :email_address end
class AddProjectFilesToResponses < ActiveRecord::Migration[5.2] def change add_column :responses, :project_files_id, :string add_column :responses, :project_files_filename, :string add_column :responses, :project_files_size, :string add_column :responses, :project_files_content_type, :string end end
# frozen_string_literal: true require 'test_helper' module Vedeu module Repositories class StoreTestClass include Vedeu::Repositories::Store attr_reader :model def initialize(model = nil, storage = {}) @model = model @storage = storage end private def in_memory {} end end describe Store do let(:described) { Vedeu::Repositories::Store } let(:included_described) { Vedeu::Repositories::StoreTestClass } let(:included_instance) { included_described.new(model, storage) } let(:model) {} let(:storage) {} describe '#all' do it { included_instance.must_respond_to(:all) } end describe '#clear' do it { included_instance.must_respond_to(:clear) } end describe '#each' do subject { included_instance.each } it { subject.must_be_instance_of(Enumerator) } end describe '#empty?' do subject { included_instance.empty? } context 'when empty' do it { subject.must_equal(true) } end context 'when not empty' do let(:storage) { [:item] } it { subject.must_equal(false) } end end describe '#exists?' do let(:_name) {} subject { included_instance.exists?(_name) } context 'when the store is empty' do let(:_name) { :vedeu_repositories_store } it { subject.must_equal(false) } end context 'with no name' do it { subject.must_equal(false) } end context 'with empty name' do let(:_name) { '' } it { subject.must_equal(false) } end context 'when the model does not exist' do let(:storage) { { 'samarium' => [:some_model_data] } } let(:_name) { 'terbium' } it { subject.must_equal(false) } end context 'when the model exists' do let(:storage) { { 'samarium' => [:some_model_data] } } let(:_name) { 'samarium' } it { subject.must_equal(true) } end end describe '#registered?' do it { included_instance.must_respond_to(:registered?) } end describe '#registered' do subject { included_instance.registered } it { subject.must_be_instance_of(Array) } context 'when the storage is a Hash' do let(:storage) { { 'rutherfordium' => { name: 'rutherfordium' } } } it 'returns a collection of the names of all the registered entities' do subject.must_equal(['rutherfordium']) end end context 'when the storage is an Array' do let(:storage) { ['rutherfordium'] } it 'returns the registered entities' do subject.must_equal(['rutherfordium']) end end context 'when the storage is a Set' do let(:storage) { Set['rutherfordium'] } it 'returns the registered entities' do subject.must_equal(['rutherfordium']) end end context 'when the storage is empty' do it 'returns an empty collection' do subject.must_equal([]) end end end describe '#size' do subject { included_instance.size } context 'when empty' do it { subject.must_equal(0) } end context 'when not empty' do let(:storage) { [:item] } it { subject.must_equal(1) } end end describe '#all' do it { included_instance.must_respond_to(:all) } end end # Store end # Repositories end # Vedeu
# # Copyright 2013, Seth Vargo <sethvargo@gmail.com> # Copyright 2013, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module CommunityZero # The endpoint for interacting with a single cookbook version. # # @author Seth Vargo <sethvargo@gmail.com> class CookbookVersionsVersionEndpoint < Endpoint def get(request) name, version = request.path[1], request.path[-1].gsub('_', '.') unless cookbook = store.find(name) return respond(404, { 'error_code' => 'NOT_FOUND', 'error_messages' => ['Resource not found'], } ) end version = store.latest_version(cookbook) if version == 'latest' cookbook = store.find(name, version) respond(response_hash_for(cookbook)) end private # The response hash for this cookbook. # # @param [CommunityZero::Cookbook] cookbook # the cookbook to generate a hash for def response_hash_for(cookbook) { 'cookbook' => url_for(cookbook), 'average_rating' => cookbook.average_rating, 'version' => cookbook.version, 'license' => cookbook.license, 'file' => "http://s3.amazonaws.com/#{cookbook.name}.tgz", 'tarball_file_size' => cookbook.name.split('').map(&:ord).inject(&:+) * 25, # don't even 'created_at' => cookbook.created_at, 'updated_at' => cookbook.upadated_at, } end end end
require 'uuid' require 'open3' require 'tempfile' module Hadupils::Extensions # Tools for managing shell commands/output performed by the runners module Runners module Shell def self.command(*command_list) opts = {} begin if RUBY_VERSION < '1.9' Open3.popen3(*command_list) do |i, o, e| @stdout = o.read @stderr = e.read end @status = $? $stdout.puts @stdout unless @stdout.nil? || @stdout.empty? || Shell.silence_stdout? $stderr.puts @stderr unless @stderr.nil? || @stderr.empty? @stdout = nil unless capture_stdout? @stderr = nil unless capture_stderr? else stdout_rd, stdout_wr = IO.pipe if capture_stdout? stderr_rd, stderr_wr = IO.pipe if capture_stderr? opts[:out] = stdout_wr if capture_stdout? opts[:err] = stderr_wr if capture_stderr? # NOTE: eval prevents Ruby 1.8.7 from throwing a syntax error on Ruby 1.9+ syntax pid = eval 'Process.spawn(*command_list, opts)' @status = :waiting unless pid.nil? Thread.new do Process.wait pid @status = $? end Thread.new do if capture_stdout? stdout_wr.close @stdout = stdout_rd.read stdout_rd.close $stdout.puts @stdout unless @stdout.nil? || @stdout.empty? || Shell.silence_stdout? end end Thread.new do if capture_stderr? stderr_wr.close @stderr = stderr_rd.read stderr_rd.close $stderr.puts @stderr unless @stderr.nil? || @stderr.empty? end end sleep 0.1 while @status == :waiting end [@stdout, @stderr, @status] rescue Errno::ENOENT => e $stderr.puts e [@stdout, @stderr, nil] end end def self.capture_stderr? @capture_stderr end def self.capture_stderr=(value) @capture_stderr = value end def self.capture_stdout? @capture_stdout || Shell.silence_stdout? end def self.capture_stdout=(value) @capture_stdout = value end def self.silence_stdout? @silence_stdout end def self.silence_stdout=(value) @silence_stdout = value end end end # Tools for managing tmp files in the hadoop dfs module Dfs module TmpFile def self.uuid @uuid ||= UUID.new end def self.tmp_ttl @tmp_ttl ||= (ENV['HADUPILS_TMP_TTL'] || '1209600').to_i end def self.tmp_path @tmp_path ||= (ENV['HADUPILS_TMP_PATH'] || '/tmp') end def self.tmpfile_path @tmpfile_path ||= ::File.join(tmp_path, "hadupils-tmp-#{uuid.generate(:compact)}") end def self.reset_tmpfile! @tmpdir_path = nil end end end # Tools for managing hadoop configuration files ("hadoop.xml"). module HadoopConf module HadoopOpt def hadoop_opts ['-conf', path] end end # Wraps an extant hadoop configuration file and provides # an interface compatible with the critical parts of the # Static sibling class so they may be used interchangeably # by runners when determining hadoop options. class Static attr_reader :path include HadoopOpt # Given a path, expands it ti def initialize(path) @path = ::File.expand_path(path) end def close end end end # Tools for managing hive initialization files ("hiverc"). module HiveRC module HiveOpt def hive_opts ['-i', path] end end # Wraps an extant hive initialization file, and providing # an interface compatible with the critical parts of the # Dynamic sibling class so they may be used interchangeably # by runners when determining hive options. class Static attr_reader :path include HiveOpt # Given a path, expands it ti def initialize(path) @path = ::File.expand_path(path) end def close end end # Manages dynamic hive initialization files, assembling a temporary file # and understanding how to write assets/lines into the initialization file for # use with hive's -i option. class Dynamic attr_reader :file include HiveOpt # This will allow us to change what handles the dynamic files. def self.file_handler=(handler) @file_handler = handler end # The class to use for creating the files; defaults to ::Tempfile def self.file_handler @file_handler || ::Tempfile end # Sets up a wrapped file, using the class' file_handler, def initialize @file = self.class.file_handler.new('hadupils-hiverc') end def path ::File.expand_path @file.path end def close @file.close end # Writes the items to the file, using #hiverc_command on each item that # responds to it (Hadupils::Assets::* instances) and #to_s on the rest. # Separates lines by newline, and provides a trailing newline. However, # the items are responsible for ensuring the proper terminating semicolon. # The writes are flushed to the underlying file immediately afterward. def write(items) lines = items.collect do |item| if item.respond_to? :hiverc_command item.hiverc_command else item.to_s end end @file.write(lines.join("\n") + "\n") @file.flush end end end class EvalProxy def initialize(scope) @scope = scope end def assets(&block) @scope.instance_eval do @assets_block = block end end def hadoop_conf(&block) @scope.instance_eval do @hadoop_conf_block = block end end def hiverc(&block) @scope.instance_eval do @hiverc_block = block end end end class Base attr_reader :assets, :path def initialize(directory, &block) if block_given? EvalProxy.new(self).instance_eval &block end @path = ::File.expand_path(directory) unless directory.nil? @assets = merge_assets(self.class.gather_assets(@path)) end def merge_assets(assets) return @assets_block.call(assets) if @assets_block assets end def hadoop_confs [] end def hivercs [] end def self.gather_assets(directory) if directory Hadupils::Assets.assets_in(directory) else [] end end end class Flat < Base def hivercs @hiverc ||= assemble_hiverc [@hiverc] end def default_hiverc_items @assets.dup end def assemble_hiverc assets = default_hiverc_items if @hiverc_block assets = @hiverc_block.call(assets.dup) end hiverc = Hadupils::Extensions::HiveRC::Dynamic.new hiverc.write(assets) hiverc end end class FlatArchivePath < Flat def archives_for_path_env @assets.find_all do |a| if a.kind_of? Hadupils::Assets::Archive begin Hadupils::Util.archive_has_directory?(a.path, 'bin') rescue false end else false end end end def default_hiverc_items items = super archs = archives_for_path_env if archs.length > 0 items << self.class.assemble_path_env(archs) end items end def self.assemble_path_env(archives) paths = archives.collect {|a| "$(pwd)/#{ a.name }/bin" } "SET mapred.child.env = PATH=#{ paths.join(':') }:$PATH;" end end class Static < Base def self.gather_assets(path) [] end def hadoop_conf_path ::File.join(path, 'hadoop.xml') if path end def hiverc_path ::File.join(path, 'hiverc') if path end def hadoop_conf? hadoop_conf_path ? ::File.file?(hadoop_conf_path) : false end def hiverc? hiverc_path ? ::File.file?(hiverc_path) : false end def hadoop_confs r = [] r << Hadupils::Extensions::HadoopConf::Static.new(hadoop_conf_path) if hadoop_conf? r end def hivercs r = [] r << Hadupils::Extensions::HiveRC::Static.new(hiverc_path) if hiverc? r end end end require 'hadupils/extensions/hive'
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # # Model object. # # class CommitDetailsCommit # @return [String] Commit message attr_accessor :message # @return [CommitDetailsCommitAuthor] attr_accessor :author # # Mapper for CommitDetailsCommit class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { required: false, serialized_name: 'CommitDetails_commit', type: { name: 'Composite', class_name: 'CommitDetailsCommit', model_properties: { message: { required: false, serialized_name: 'message', type: { name: 'String' } }, author: { required: false, serialized_name: 'author', type: { name: 'Composite', class_name: 'CommitDetailsCommitAuthor' } } } } } end end end end
# require 'Date' module Hotel COST_OF_ROOM = 200 class Reservation attr_reader :id, :check_in, :check_out, :rooms, :total_cost, :date_range, :discount_rate def initialize(id_num, number_of_rooms:1, check_in:, check_out:, discount_rate: 1, block_id:'') @id = id_num @block_id = block_id @check_in = Date.parse(check_in) @check_out = Date.parse(check_out) @date_range = (@check_in...@check_out) @rooms = [] @discount_rate = discount_rate #change this to standard error / rescue if @check_out != nil if @check_out <= @check_in raise ArgumentError, "Invalid date range" end end end def find_reservation(date) date = Date.parse(date) return self.date_range.include? date end def overlaps?(check_in, check_out) existing_check_in = self.check_in existing_check_out = self.check_out if existing_check_in <= check_out && existing_check_in >= check_in return true elsif check_in <= existing_check_out && existing_check_out <= check_out return true else return false end end def total_cost total_cost = self.date_range.count * self.rooms.length * COST_OF_ROOM * self.discount_rate return total_cost end end end
module RailsAdminSitemap def self.configuration @configuration ||= Configuration.new end def self.config @configuration ||= Configuration.new end def self.configure yield configuration end class Configuration attr_accessor :generator attr_accessor :config_file attr_accessor :output_file attr_accessor :dynamic_sitemaps_conf def initialize @generator = :sitemap_generator @config_file = Rails.root.join("config", "sitemap.rb") @output_file = Rails.root.join("public", "sitemap.xml") @dynamic_sitemaps_conf = { path: Rails.root.join("public"), folder: "sitemaps", index_file_name: "sitemap.xml" } end end end
class AddBirthdayToUsers < ActiveRecord::Migration def change add_column :users, :birthday, :date end end
class ApiHelper attr_reader :api_key def initialize() @api_key = 'jellyvision_audition' end def get_possible_results(type) good = [ 'It is certain', 'It is decidedly so', 'Without a doubt', 'Yes - definatley', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes'] bad = ["Don't count on it", "My reply is no", 'My sources say no', 'Outlook not so good', 'Very doubtful' ] neutral = ['Reply hazy - Try Again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again'] any = good + bad + neutral case type when 'any' any when 'good' good when 'bad' bad when 'neutral' neutral else false end end def get_result(type) results = get_possible_results(type) if results results.sample else false end end def validate_api_key(params) val = true begin unless params[:api_key] == api_key val = false end rescue val = false end val end end
class CreateAnnotations < ActiveRecord::Migration def change create_table :annotations do |t| t.string :guid, null: false t.string :checksum, null: false t.string :amazon_reference_id, default: nil t.string :book_reference_id, default: nil t.string :customer_reference_id, default: nil t.string :embedded_reference_id, default: nil t.integer :book_id, null: false t.integer :user_id, null: false t.text :raw_content, null: false t.boolean :is_note_only, default: false t.integer :location, default: 0 t.integer :start_location, default: 0 t.integer :end_location, default: 0 t.timestamps null: false end add_index :annotations, :guid, unique: true add_index :annotations, :book_id add_index :annotations, :user_id add_index :annotations, :amazon_reference_id, unique: true add_index :annotations, :book_reference_id add_index :annotations, :customer_reference_id add_index :annotations, :embedded_reference_id end end
require_relative '../spatial' module PdfExtract module Chunks # TODO Look for obj[:writing_mode] == :vertical or :horizontal Settings.declare :char_slop, { :default => 0.2, :module => self.name, :description => "Maximum allowed space between characters for them to be considered part of the same word. char_slop is multiplied by the width of each character to find its joining width." } Settings.declare :word_slop, { :default => 4.0, :module => self.name, :description => "Maximum allowed space between words for them to be considered part of the same line. word_slop is multiplied by width of the last character in a word to find its joining width." } Settings.declare :overlap_slop, { :default => 0.9, :module => self.name, :description => "A minimum permitted ratio of the overlapped height of words for them to join together into lines." } def self.include_in pdf pdf.spatials :chunks, :paged => true, :depends_on => [:characters] do |parser| rows = {} parser.before do rows = {} end parser.objects :characters do |chars| y = chars[:y] rows[y] = [] if rows[y].nil? idx = rows[y].index { |obj| chars[:x] <= obj[:x] } if idx.nil? rows[y] << chars.dup else rows[y].insert idx, chars.dup end end parser.after do char_slop = pdf.settings[:char_slop] word_slop = pdf.settings[:word_slop] overlap_slop = pdf.settings[:overlap_slop] text_chunks = [] rows.each_pair do |y, row| char_width = row.first[:width] while row.length > 1 left = row.first right = row[1] if (left[:x] + left[:width] + (char_width * char_slop)) >= right[:x] # join as adjacent chars row[0] = Spatial.merge left, right row.delete_at 1 char_width = right[:width] unless right[:content].strip =~ /[^A-Za-z0-9]/ elsif (left[:x] + left[:width] + (char_width * word_slop)) >= right[:x] # join with a ' ' in the middle. row[0] = Spatial.merge left, right, :separator => ' ' row.delete_at 1 char_width = right[:width] unless right[:content].strip =~ /[^A-Za-z0-9]/ else # leave 'em be. text_chunks << left row.delete_at 0 char_width = row.first[:width] end end text_chunks << row.first end # Merge chunks that have slightly different :y positions but which # mostly overlap in the y dimension. text_chunks.sort_by! { |obj| obj[:x] } merged_text_chunks = [] while text_chunks.count > 1 left = text_chunks.first right = text_chunks[1] overlap = [left[:height], right[:height]].min - (left[:y] - right[:y]).abs overlap = overlap / [left[:height], right[:height]].min if overlap >= overlap_slop # TODO follow char / word slop rules. # join text_chunks[0] = Spatial.merge left, right text_chunks.delete_at 1 else # no join merged_text_chunks << text_chunks.first text_chunks.delete_at 0 end end merged_text_chunks << text_chunks.first # Remove empty lines - they mess up region detection by # making them join together. merged_text_chunks.reject { |chunk| chunk[:content].strip == "" } end end end end end
module Webex # comment class Configuration %w( site_name webex_id password back_type back_url).each do |name| define_singleton_method(name) { ENV["WEBEX_#{name.upcase}"] } end def self.host_url "https://#{site_name}.webex.com/#{site_name}/" # "https://engsound.webex.com/engsound/" end end CONFIGURATION = Webex::Configuration end
# frozen_string_literal: true # this is comments class Carrig include Validation include TrainCarrige NUMBER_FORMAT = /^[0-9a-zа-я]{3}-?[0-9a-zа-я]{2}$/i.freeze NAME_FORMAT = /^[а-яa-z]+\D/i.freeze attr_reader :number, :amount attr_accessor_with_history :color, :repair_date strong_attr_accessor :production_year, Integer def initialize(number, amount) @number = number @amount = amount @amount_now = 0 @status = false name_manufacturer! validate! end def increase_amount(amount) if @amount_now + amount > @amount puts 'Недостаточно места в вагоне!!!' elsif amount <= @amount @amount_now += amount free_amount else puts "Вагон может вместить только #{@amount} !!!" end end def free_amount @amount - @amount_now end def show_amount_now @amount_now end def show_free_amount free_amount end def change_status(train) if train.carrig.include?(self) connect else disconnect end end def connect @status = true end def disconnect @status = false end def to_s "Тип вагона: #{self.class}, номер: #{number}, соединен ли с поездом: #{@status}, производитель #{name_manufacturer}" end protected :connect, :disconnect end
class Track < ActiveRecord::Base validates :name, :roll, :options, :octave, presence: true end
module WebiniusCms module ApplicationHelper def errors_for(model, attribute) if model.errors[attribute].present? content_tag :div, content_tag(:span, model.errors[attribute].first, class: 'control-label'), class: 'field_with_errors' end end def list_nested_pages(pages) pages.map do |page, sub_pages| render(page) + list_nested_pages(sub_pages) end.join.html_safe end def set_lang(receiver, method_name) text = receiver.send("#{I18n.locale}_#{method_name}") text.present? ? text : receiver.send("de_#{method_name}") end def nested_page_path(page, slug = nil, args = {}) url_params = args.present? ? "?#{args.to_query}" : '' path = "/#{I18n.locale}/" + page.send(:"#{I18n.locale}_slug") path << "/#{slug}" if slug path << url_params end end end
# Calc.rb exercise puts 1 + 2; # Integer addition, yields 3, writes 3 to screen puts ''; # 2.4 Simple Arithmetic # Floats puts 1.0 + 2.0; puts 2.0 * 3.0; puts 5.0 - 8.0; puts 9.0 / 2.0; puts ''; # Integers puts 1+2; puts 2*3; puts 5-8; puts 9/2; # Integer division always rounds down to the nearest whole number expressed as an integer puts ''; # Experiment with programs of your own puts 5 * (12-8) + -15; puts 98 + (59872 / (13*8)) * -51;