text
stringlengths
10
2.61M
# Scrapes Greyhound Site for trip cost. # Watir depends on Selenium Webdriver # Date must be in 'yyyy-mm-dd' format. # Example: # depart_date = '2016-06-01' # depart_from = {city: 'Vancouver', state: 'BC'} # return_date = '2016-06-02' # return_from = {city: 'Los Angeles', state: 'CA'} # trip_type = "Round Trip" # ghound = GreyhoundScraper.new(depart_date, depart_from, return_date, return_from, trip_type) # puts ghound.run # For Chrome: chromedriver has been placed in /usr/local/bin/, will be auto detected by Selenium # Todo - research headless scraping using PhantomJS class GreyhoundScraper FORM_URL = 'https://mobile.greyhound.ca/tix1.html' attr_reader :depart_date attr_reader :depart_from attr_reader :return_date attr_reader :return_from attr_reader :trip_type def initialize(depart_date, depart_from, return_date, return_from, trip_type, browser_type) if browser_type.downcase == "chrome" @browser = Watir::Browser.new:chrome # @browser = Watir::Browser.start "www.google.com", :chrome #alt elsif browser_type.downcase == "firefox" Selenium::WebDriver::Firefox::Binary.path='/Applications/Firefox.app/Contents/MacOS/firefox' @browser = Watir::Browser.new:firefox else # assume phantomjs @browser = Watir::Browser.new:phantomjs, :args => ['--ignore-ssl-errors=true'] end @depart_date = depart_date @depart_from = depart_from @return_date = return_date @return_from = return_from @trip_type = trip_type @browser_type = browser_type end def validate_depart_date if @depart_date > (Date.today + 322) 'Departure date must not exeed ' + (Date.today + 322).to_s + '.' elsif @depart_date < Date.today 'Departure date must be today (' + Date.today.to_s + ') or later.' else true end end def validate_return_date if @return_date > (Date.today + 322) 'Return date must not exeed ' + (Date.today + 322).to_s + '.' elsif @return_date <= @depart_date 'Return date must be be later than departure date(' + @depart_date.to_s + ')' else true end end # Todo - return success/fail msg def sure_load_link(mytimeout) browser_loaded = 0 while (browser_loaded == 0) begin browser_loaded = 1 Timeout::timeout(mytimeout) do yield end rescue Timeout::Error => e puts "Page load timed out: #{e}" browser_loaded = 0 retry end end puts "Homepage Successfully loaded" end def try_action(msg, wait_time, tries) fails = 0 begin yield rescue fails += 1 puts "#{msg}: fail #{fails}" sleep wait_time fails < tries ? retry : (puts "#{msg}: gave up"; return "Error") end return "#{msg}: action success" end # Todo - Dry this, make it call try_action def try_click(msg) fails = 0 begin yield rescue fails += 1 puts " #{msg}: fail #{fails}" sleep 0.2 fails < 5 ? retry : (puts " #{msg}: gave up"; return "Error") end return " #{msg}: click success" end def open_browser # 5 seconds safe for Chrome, 7 seconds safe for phantomjs. Todo - conditional logic if @browser_type == "chrome" wait = 5 elsif @browser_type == "firefox" wait = 7 else wait = 7 end sure_load_link(wait) { @browser.goto(FORM_URL) } end def enter_trip_type if @trip_type == "One Way" return try_click("Select One Way") { @browser.span(text: 'One Way').when_present.click } else return try_click("Select Round Trip") { @browser.span(text: 'Round Trip').when_present.click } end sleep 0.3 end # placeholder must be "Leaving from..." or "Going to..." def enter_location(placeholder, location) puts try_click("Select #{placeholder}") { @browser.text_field(placeholder: placeholder).click } sleep 0.2 @browser.text_field(placeholder: placeholder).set(location[:city][0..3]) seg2 = location[:city][4..(location[:city].length - 1)] if seg2 sleep 0.2 @browser.text_field(placeholder: placeholder).append(seg2) end index = 0 begin @browser.li(class: "ui-li ui-li-static ui-btn-up-x", index: index).wait_until_present(1) rescue Watir::Wait::TimeoutError => e return "Error" # todo - make nicer end # put 'ui-li ui-li-static ui-btn-up-x' this in scrapper config file along with the url while (@browser.li(class: "ui-li ui-li-static ui-btn-up-x", index: index).exists?) dropdown_match = (location[:city] + ', ' + location[:state]).upcase if @browser.li(class: "ui-li ui-li-static ui-btn-up-x", index: index).text == dropdown_match puts try_click("Click dropdown #{dropdown_match}") { @browser.li(class: "ui-li ui-li-static ui-btn-up-x", index: index).click } puts "Found " + location[:city] + ', ' + location[:state] sleep 0.3 return true # happy path ends here end index += 1 end puts "Error: " + location[:city] + ', ' + location[:state] + " not found" return "Error" end def enter_origin enter_location("Leaving from...", @depart_from) end def enter_destination enter_location("Going to...", @return_from) end # input_id must be "depart" or "return" def enter_date(input_id, date) date_field = @browser.input(id: input_id) # try to inject into date field js_change_date = "return arguments[0].value = '#{date}'" # not sure how arguments works, todo figure it out @browser.execute_script(js_change_date, date_field) sleep 0.1 end def enter_depart_date enter_date("depart", @depart_date) end def enter_return_date enter_date("return", @return_date) end def submit_form(next_page) @browser.scroll.to :bottom if @browser_type != "phantomjs" puts try_click("Click 'View Schedules' to goto #{next_page}") { @browser.button.when_present.click } # Watir::Wait.until(6, "Couldn't load next page: " + next_page) { @browser.url.include? next_page } begin Watir::Wait.until(6) { @browser.url.include? next_page } rescue Watir::Wait::TimeoutError => e return "Error" # todo - make nicer end end def submit_page1 submit_form("tix2.html") end def submit_page2 puts try_click("Select the first schedule in p2") { @browser.label(index: 0).when_present.click } sleep 0.2 submit_form("tix3.html") end # check page status i - if @browser.url.include? "mobile.greyhound.ca/tix2.html" def errors? if @browser.url.include? "tix1.html" if @browser.span(class: "feedbackPanelERROR").exists? # if @browser.span(class: "feedbackPanelERROR").text.include? "No schedules" #todo - necessary? # return "No schedules found" # # elsif (todo - test for other error types) # end return "No schedules found" end elsif @browser.url.include? "tix2.html" if @browser.p(class: "ui-li-aside", index: 0).span.exists? == false return "Couldn't get tickets" end end end # helper for get_depart_data, get_return_data # 2 possibilities for type: depart, return def get_trip_data begin data = {} # for each departure/return entry, grab: start_time, end_time, travel_time, cost i = 0 try_action("Wait for #{@browser.url} to load", 0.2, 10) { @browser.label(index: i).exists? } == "Error" ? (return "Error") : (puts "#{@browser.url} finished loading") sleep 0.2 while (@browser.label(index: i).exists?) cost = @browser.label(index: i).p(class: "ui-li-aside").span.text cost[0] = '' if cost[0] = '$' # remove $ sign start_time = @browser.label(index: i).h4.span.text end_time = @browser.label(index: i).p(index: 1).span(index: 1).text travel_time = @browser.label(index: i).p(index: 1).span(index: 3).text data[i] = { cost: cost, start_time: start_time, end_time: end_time, travel_time: travel_time} i += 1 end puts "Found #{i} schedules" rescue Watir::Exception::UnknownObjectException => e puts "Page load error" return nil end data end def close_browser # sleep 1 # testing @browser.close end def run self.open_browser puts self.enter_trip_type form_error_handler(enter_origin, "Error - Couldn't find origin", "Found origin") form_error_handler(enter_destination, "Error - Couldn't find destination.", "Found destination") self.enter_depart_date # assume error free self.enter_return_date # assume error free form_error_handler(submit_page1, "Error - Couldn't submit form.", "Form submitted successfully") result = {} # should be error free after this point if get_trip_data result[:depart] = self.get_trip_data form_error_handler(submit_page2, "Error - Couldn't submit form.", "Form submitted successfully") result[:return] = self.get_trip_data else close_browser return "No schedules found" end self.close_browser result end # FOR CACHING def get_depart_data # return something regardless of page load begin try_action("Wait for #{@browser.url} to load", 0.2, 10) { @browser.label(index: 0).exists? } == "Error" ? (return "Error") : (puts "#{@browser.url} finished loading") sleep 0.2 cost = @browser.label(index: 0).p(class: "ui-li-aside").span.text cost[0] = '' if cost[0] = '$' travel_time = @browser.label(index: 0).p(index: 1).span(index: 3).text close_browser rescue Watir::Exception::UnknownObjectException => e puts "Error" end { cost: cost, travel_time: travel_time } end def form_error_handler(element, err_msg, success_msg) if element == "Error" puts err_msg return nil else puts success_msg end end def run_depart open_browser puts enter_trip_type # quit right away if either one results in an error if enter_origin == "Error" || enter_destination == "Error" return { cost: nil, travel_time: nil } else enter_origin enter_destination end enter_date("depart", @depart_date) enter_date("return", @return_date) form_error_handler(submit_page1, "Error - Couldn't submit form.", "Form submitted") get_depart_data end end
require 'formula' class Ipcalc < Formula homepage 'http://jodies.de/ipcalc' url 'http://jodies.de/ipcalc-archive/ipcalc-0.41.tar.gz' sha1 'b75b498f2fa5ecfa30707a51da63c6a5775829f3' def install bin.install "ipcalc" end end
require File.join(File.dirname(__FILE__), '..', 'spec_helper') require 'rspec/its' describe Biggs::Format do describe '.find' do context 'known country with format' do subject { Biggs::Format.find('cn') } it { is_expected.to be_kind_of(Biggs::Format) } its(:country_name) { should eql('China') } its(:iso_code) { should eql('cn') } its(:format_string) { should eql("{{recipient}}\n{{street}}\n{{postalcode}} {{city}} {{region}}\n{{country}}") } end context 'known country with unknown format' do subject { Biggs::Format.find('af') } it { is_expected.to be_kind_of(Biggs::Format) } its(:country_name) { should eql('Afghanistan') } its(:iso_code) { should eql('af') } its(:format_string) { should eql(nil) } end context 'unknown country' do subject { Biggs::Format.find('xx') } it { is_expected.to be_kind_of(Biggs::Format) } its(:country_name) { should eql(nil) } its(:iso_code) { should eql('xx') } its(:format_string) { should eql(nil) } end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'splaytreemap/version' Gem::Specification.new do |spec| spec.name = "splaytreemap" spec.version = Splaytreemap::VERSION spec.authors = ["Kirk Haines"] spec.email = ["wyhaines@gmail.com"] spec.summary = %q{An implementation of Splay Tree, with a size limitation feature, offering a Map style API. Very useful for caches.} spec.description = %q{A Splay Tree is a self adjusting binary search tree with the additional property that recently accessed elements are quick to access again. This makes it useful for caches because the most commonly accessed elements will be the fastest ones to access. This tree has an additional feature that allows it's maximum size to be restricted. When it exceeds it's maximum size, it will drop all of the nodes which are at the terminal ends of the tree structure, leaving many of the more commonly accessed nodes intact. This implementation is written in C++ with a Ruby wrapper.} spec.homepage = "http://github.com/wyhaines/splaytreemap" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.require_paths = ["lib"] spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.extensions = %w[ext/splaytreemap/extconf.rb] spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "minitest", "~> 5.0" spec.add_development_dependency "rake-compiler", "~> 0" end
module Haenawa module Commands class Wait < Command def validate if target.blank? @step.errors.add(:target, :missing) elsif '_blank' == target elsif !VALID_STRATEGIES.include?(strategy) || locator.blank? @step.errors.add(:target, :invalid) else begin interpolated_locator rescue I18n::MissingInterpolationArgument @step.errors.add(:target, :invalid_placeholder) end end if value.present? begin Float(value) rescue ArgumentError, TypeError @step.errors.add(:value, :invalid) end end end def render ensure_capture do if target.include?('_blank') || value.present? sec = (value.to_f / 1000).ceil "sleep #{sec}" else "#{find_target}" end end rescue Haenawa::Exceptions::Unsupported::TargetType render_unsupported_target end end end end
module SessionsHelper # 渡されたユーザでログインする def log_in(user) session[:user_id] = user.id end # 渡されたユーザがログインしていれば true を返す def current_user?(user) user == current_user end # 現在ログイン中のユーザを返す (いる場合) def current_user @current_user ||= User.find_by(id: session[:user_id]) end # ユーザがログインしていればtrue、その他ならfalseを返す def logged_in? !current_user.nil? end # 現在のユーザをログアウトする def log_out session.delete(:user_id) @current_user = nil end # 渡されたユーザが削除されていなければ true を返す def existence_user?(user) user.existence end def guest_user? current_user.guest end end
class AddPacksToCards < ActiveRecord::Migration def change add_belongs_to :cards, :pack end end
describe 'Sign in', type: :feature do before :each do @user = User.create(email: 'user@example.com', password: 'password', name: 'user') end after :each do @user.destroy end it 'sign in user' do visit '/users/sign_in' fill_in 'Email', with: 'user@example.com' fill_in 'Password', with: 'password' click_button 'Log in' expect(page).to have_content('Signed in successfully.') end it "doesn't sign in unregistered user" do visit '/users/sign_in' fill_in 'Email', with: 'wrong_user@example.com' fill_in 'Password', with: 'wrong_password' click_button 'Log in' expect(page).to have_content 'Invalid Email or password.' end end
require 'test_helper' class StatementsControllerTest < ActionDispatch::IntegrationTest def setup @admin = users(:admin) @user = users(:user) @statement = statements(:statement1) @name = 'Extracto junio 2018' @date = '01-06-2018' end ################# # # # FUNCTIONS # # # ################# def assert_permissions follow_redirect! assert_equal flash[:danger], 'Tu cuenta no tiene permisos para realizar esa acción. Por favor, contacta con el administrador para más información.' end ############# # # # TESTS # # # ############# ########## # ROUTES # ########## test 'Statements Controller 001 - should get index' do log_in_as(@user) get statements_path assert_response :success end test 'Statements Controller 002 - should get show' do log_in_as(@user) get statement_path(@statement) assert_template 'statements/show' assert_select 'h1', "#{@statement.name}" end test 'Statements Controller 003 - new as non-admin user should redirect to homepage with message' do log_in_as(@user) get new_statement_path assert_permissions end test 'Statements Controller 004 - edit as non-admin user should redirect to homepage with message' do log_in_as(@user) get edit_statement_path(@statement) assert_permissions end test 'Statements Controller 005 - bucket as non-admin user should redirect to homepage with message' do log_in_as(@user) get bucket_path assert_permissions end test 'Statements Controller 006 - should get new as admin' do log_in_as(@admin) get new_statement_path assert_response :success end test 'Statements Controller 007 - should get edit as admin' do log_in_as(@admin) get edit_statement_path(@statement) assert_response :success end # test 'Statements Controller 008 - should get bucket as admin' do # log_in_as(@admin) # get bucket_path # assert_response :success # end ########### # ACTIONS # ########### # All controller actions: index, new, create, show, edit, update, destroy, bucket # # permissions: index, show # # actions: create, update, destroy test 'Statements Controller 009 - create as non-admin user should redirect to homepage with message' do log_in_as(@user) get new_statement_path post statements_path, params: { statement: { name: @name, date: @date}} assert_permissions end # test 'Statements Controller 010 - import statement should work with correct data as admin' do # # end # # test 'Statements Controller 011 - import statement without day should put todays date as default' do # # end # # test 'Statements Controller 012 - import statement without attachment should not work' do # # end # # test 'Statements Controller 013 - import statement should not work if attached file is not csv' do # # end # # test 'Statements Controller 014 - import statement CSV should at least have the required columns in Movement model' do # # end # test 'Statements Controller 015 - create statement should work properly as admin user' do # log_in_as(@admin) # get new_statement_path # assert_difference 'Statement.count', 1 do # post statements_path, params: { statement: { name: @name, date: @date}} # end # follow_redirect! # assert_template 'statements/show' # assert_not flash.empty? # end # test 'Statements Controller 016 - update statement as non-admin should redirect to homepage with message' do # # end test 'Statements Controller 017 - update statement should work properly as admin user with correct data' do log_in_as(@admin) get edit_statement_path(@statement) patch statement_path(@statement), params: { statement: { name: 'Extracto julio 2018', date: '01-07-2018'}} assert_not flash.empty? assert_redirected_to @statement @statement.reload assert_equal 'Extracto julio 2018', @statement.name assert_equal '01-07-2018', @statement.date.strftime("%d-%m-%Y") end test 'Statements Controller 018 - update statement should not work as admin user with incorrect data' do log_in_as(@admin) get edit_statement_path(@statement) patch statement_path(@statement), params: { statement: { name: '', date: ''}} assert_select 'div.form-alert', 'El formulario contiene algunos errores.' end test 'Statements Controller 019 - delete as non-admin user should redirect to homepage with message' do log_in_as(@user) get statement_path(@statement) assert_no_difference 'Statement.count' do delete statement_path(@statement) end assert_permissions end test 'Statements Controller 020 - destroy statement should work properly as admin user' do log_in_as(@admin) get statement_path(@statement) assert_template 'statements/show' assert_difference 'Statement.count', -1 do delete statement_path(@statement) end assert_redirected_to statements_path end end
require 'minitest' require 'minitest/autorun' require 'delve/widgets/key_value' class KeyValueWidgetTest < Minitest::Test def setup @x = 1 @y = 1 @label = 'Name' @value = 'Hero' @widget = KeyValueWidget.new @x, @y, @label, @value @display = mock('object') end def test_initialising_without_x_position_raises_error assert_raises RuntimeError do KeyValueWidget.new nil, @y, @label, @value end end def test_initialising_without_y_position_raises_error assert_raises RuntimeError do KeyValueWidget.new @x, nil, @label, @value end end def test_initialising_without_label_raises_error assert_raises RuntimeError do KeyValueWidget.new @x, @y, nil, @value end end def test_initialising_without_value_raises_error assert_raises RuntimeError do KeyValueWidget.new @x, @y, @label, nil end end def test_render_fails_if_no_display_is_given assert_raises RuntimeError do @widget.draw nil end end def test_get_value assert_equal @value, @widget.value end def test_set_value @widget.value = 'Nameless' assert_equal 'Nameless', @widget.value end def test_render @display.expects(:draw).with(1, 1, 'N') @display.expects(:draw).with(2, 1, 'a') @display.expects(:draw).with(3, 1, 'm') @display.expects(:draw).with(4, 1, 'e') @display.expects(:draw).with(5, 1, ':') @display.expects(:draw).with(6, 1, ' ') @display.expects(:draw).with(7, 1, 'H') @display.expects(:draw).with(8, 1, 'e') @display.expects(:draw).with(9, 1, 'r') @display.expects(:draw).with(10, 1, 'o') @widget.draw(@display) end end
class Restaurant < ApplicationRecord has_many :map_object, through: :is_open end
class User < ActiveRecord::Base has_and_belongs_to_many :roles # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable after_save :expire_buyer_relations after_save :expire_managers_savings_items after_destroy :expire_buyer_relations # Setup accessible (or protected) attributes for your model attr_accessible :type, :email, :password, :password_confirmation, :remember_me, :firstname, :lastname #has_many :manages #belongs_to :manager, :through => :manages, :class_name => "User" #has_many :buyers, :through => :manages, :class_name => "User" def name # ugly but removes chance of error fn = firstname.present? ? firstname : " " ln = lastname.present? ? lastname : " " "#{fn.capitalize} #{ln[0].capitalize}." end def full_name fn = firstname.present? ? firstname : " " ln = lastname.present? ? lastname : " " "#{fn.capitalize} #{ln.capitalize}" end def self.get_buyer_relations_from_cache Rails.cache.fetch("buyer_relations") do hash = {} Buyer.all.each do |buyer| manager_name = buyer.manager ? buyer.manager.name : "None" hash[buyer.id] = { :buyer_name => buyer.name, :manager_id => buyer.manager_id, :manager_name => manager_name } end hash end end def expire_buyer_relations Rails.cache.delete("buyer_relations") end def expire_managers_savings_items if self.manager_id manager_id = self.manager_id Quarterly.select(:id).map(&:id).each do |quarterly_id| Rails.cache.delete("manager_savings_items/#{manager_id}/#{quarterly_id}") end end true end end
require 'rails_helper' describe StructureChangeCreator do def audit_payload(data) payload = { 'audit' => data } expect(payload).to match_response_schema('retrocalc/audit') payload end let!(:measure_selection) { create(:measure_selection) } let!(:measure) { measure_selection.measure } let!(:audit_report) do measure_selection.audit_report end let!(:structure_wegoaudit_id) { SecureRandom.uuid } let!(:genus_structure_type) do mock_model(StructureType) end let!(:structure_type) do mock_model(StructureType, genus_structure_type: genus_structure_type) end before do payload = audit_payload( 'name' => 'report', 'id' => 'uuid', 'date' => '2015-05-15', 'audit_type' => 'type', 'structures' => [], 'measures' => []) audit_report.update!(data: payload['audit']) end it 'creates a structure_change with field values' do creator = described_class.new( measure: measure, measure_selection: measure_selection, structure_type: structure_type, structure_wegoaudit_id: structure_wegoaudit_id ) allow(StructureCreator).to receive(:new) .with(structure_change: an_instance_of(StructureChange), measure: measure, proposed: anything) .and_return(instance_double(StructureCreator, create: nil)) allow(StructureType).to receive(:find_by!).with(api_name: 'led') .and_return(structure_type) structure_change = creator.create expect(StructureCreator).to have_received(:new) .with(measure: measure, structure_change: structure_change, proposed: false) expect(StructureCreator).to have_received(:new) .with(measure: measure, structure_change: structure_change, proposed: true) end end
class AddEmailFieldToDeployment < ActiveRecord::Migration def up add_column :deployments, :email, :text end def down add_column :deployments, :email end end
class RenameUserTaskLabelToLabelAttachedTask < ActiveRecord::Migration[5.2] def change rename_table :user_task_labels, :label_attached_tasks end end
class RenameMessageToTextMessages < ActiveRecord::Migration[5.2] def change rename_column :comments, :message, :text_comments end end
require 'rails_helper' RSpec.describe "eu_vous/edit", type: :view do before(:each) do @eu_vou = assign(:eu_vou, EuVou.create!( :euvou => false, :user => nil, :event => nil )) end it "renders the edit eu_vou form" do render assert_select "form[action=?][method=?]", eu_vou_path(@eu_vou), "post" do assert_select "input#eu_vou_euvou[name=?]", "eu_vou[euvou]" assert_select "input#eu_vou_user_id[name=?]", "eu_vou[user_id]" assert_select "input#eu_vou_event_id[name=?]", "eu_vou[event_id]" end end end
module Openra class IRCBot < Cinch::Bot module Plugins class PointOne include Cinch::Plugin match '.1' def execute(m) m.reply "Gotta go, my #{nouns.sample} #{verbs.sample}" end private def nouns @nouns ||= Openra::IRCBot.dict('point_one.nouns') end def verbs @verbs ||= Openra::IRCBot.dict('point_one.verbs') end end end end end
class GamesController < ApplicationController def index @games = current_user.games end def create @game = Game.create @game.user_id = current_user.id @game.save redirect_to @game end def show @game = Game.find(params[:id]) unless @game.user == current_user flash[:alert] = "Cannot play someone's game!! Can you??" redirect_to games_path end @game_board = @game.game_board end ### # Update game preferences def update @game = Game.find(params[:id]) @game.update_preferences(game_params) if @game.errors.empty? flash[:notice] = "Your game preferences have been successfully updated!" else flash[:alert] = @game.errors[:base].to_sentence end redirect_to @game end ### # Respond with game as only json def counters @game = Game.find(params[:id]) unless @game.user == current_user render json: nil, status: 422 else render json: @game, status: 200 end end # def notify_user # if UserMailer.notify_email(params[:email], params[:url]).deliver # render json: nil, status: 200 # else # render json: nil, status: 422 # end # end private def game_params params.require(:game).permit(:id, :grid_size, :difficulty) end end
# frozen_string_literal: true require 'singleton' require_relative './validation' module Departments module Analysis module Services ## # Consumes the {Workers::Analysis::CodeInjection::Sql::CyberReportProducer}. class SqlInjectionReport include Singleton # Queues a job for a production of a {CodeInjection::SqlInjectionReport}. # @param [Integer] ip {FriendlyResource} ip address. # @param [Hash] data Intelligence data. # @return [Void] def queue_a_report(ip, data) Services::Validation.instance.ip_address?(ip) Services::Validation.instance.sql_injection_intelligence_data?(data) Rails.logger.debug("#{self.class.name} - #{__method__} - #{ip}, #{data}.") if Rails.env.development? Workers::Analysis::CodeInjection::Sql::CyberReportProducer.perform_async( ip, Shared::AnalysisType::SQL_INJECTION_CYBER_REPORT, data, Rails.env.development? ) end end end end end
require 'dry-validation' module ValidationHelper # Бросать в случае ошибки валидации с помощью dry-validation class ValidationError < StandardError attr_reader :errors # @param [Hash] errors def initialize(errors) @errors = errors end end # Переопределенный метод call бросает исключение ValidationError class Contract < Dry::Validation::Contract # @param [Hash] input # @raise [ValidationError] if validation failed # @return nil def call!(input) res = call input if res.failure? info = res.errors.to_h info.each {|k, arr| info[k] = arr.map{ |err| "#{err}, provided: #{input[k]}"}} raise ValidationError.new(info) end end end end
# frozen_string_literal: true def prime?(num) return false if num < 2 (2...num).each do |i| return false if (num % i).zero? end true end
# -*- coding: utf-8 -*- require 'spec_helper' describe Glossary do describe "#generate" do context "one word" do it "adds a glossary to the database" do lambda do Glossary.generate('data/edict_one_word.txt') end.should change(Glossary,:count).by(1) end it "sets the glossary name" do Glossary.generate('data/edict_one_word.txt') Glossary.last.name.should eq "銀河" end it "the glossary should have a definition" do Glossary.generate('data/edict_one_word.txt') Glossary.last.definitions.should eq [Definition.last] end it "adds a definiton to the database" do lambda do Glossary.generate('data/edict_one_word.txt') end.should change(Definition,:count).by(1) end it "sets the reading name of the definion" do Glossary.generate('data/edict_one_word.txt') Definition.last.reading.should eq "ぎんが" end it "adds meanings to the database" do lambda do Glossary.generate('data/edict_one_word.txt') end.should change(Meaning,:count).by(2) end it "sets the meanigs content" do Glossary.generate('data/edict_one_word.txt') Meaning.all.map(&:content).join(', ').should eq "(n) Milky Way, galaxy/(P)" end it "the definition should have meanings" do Glossary.generate('data/edict_one_word.txt') Definition.last.meanings.should eq [Meaning.first,Meaning.last] end end context "word with no reading" do it "adds a glossary to the database" do lambda do Glossary.generate('data/edict_no_reading.txt') end.should change(Glossary,:count).by(1) end it "the glossary name is set" do Glossary.generate('data/edict_no_reading.txt') Glossary.last.name.should eq 'あ' end it "adds a definition to the database" do lambda do Glossary.generate('data/edict_no_reading.txt') end.should change(Definition,:count).by(1) end it "the definiton reading is not set" do Glossary.generate('data/edict_no_reading.txt') Definition.first.reading.should be_nil end end context "same word with two different readings" do it "adds one glossary to the database" do lambda do Glossary.generate('data/edict_two_words.txt') end.should change(Glossary,:count).by(1) end it "sets the glossary name" do Glossary.generate('data/edict_two_words.txt') Glossary.last.name.should eq "銀河" end it "the glossary should have two definitions" do Glossary.generate('data/edict_two_words.txt') Glossary.last.definitions.should eq Definition.all end it "adds definitions to the database" do lambda do Glossary.generate('data/edict_two_words.txt') end.should change(Definition,:count).by(2) end it "sets the definition reading" do Glossary.generate('data/edict_two_words.txt') Definition.all.map(&:reading).join('、').should eq "ぎんが、ぎんぎ" end it "adds meanings to the database" do lambda do Glossary.generate('data/edict_two_words.txt') end.should change(Meaning,:count).by(4) end it "sets the meanigs content" do Glossary.generate('data/edict_two_words.txt') Meaning.all.map(&:content).join(', ').should eq "(n) Milky Way, galaxy/(P), (n) Milky Way, galaxy/(P)" end it "the glossary should have meanings" do Glossary.generate('data/edict_two_words.txt') Definition.first.meanings.should eq Meaning.all[0..1] Definition.last.meanings.should eq Meaning.all[2..3] end end end #generate describe "#edict_name" do it "cuts out the name" do Glossary.edict_name("銀河 [ぎんが] /(n) (1) Milky Way/(2) galaxy/(P)/").should eq "銀河" end end #edict_name describe "#edict_reading" do it "cuts out the reading" do Glossary.edict_reading("銀河 [ぎんが] /(n) (1) Milky Way/(2) galaxy/(P)/").should eq "ぎんが" end end describe "#edict_meanings" do context "cuts out the meanings" do it "simple meaning" do Glossary.edict_meanings("銀河 [ぎんが] /(n) Milky Way/").should eq ["(n) Milky Way"] end it "verb" do Glossary.edict_meanings("銀河 [ぎんが] /(v5s) Milky Way/").should eq ["(v5s) Milky Way"] end it "two meanings" do Glossary.edict_meanings("銀河 [ぎんが] /(n) (1) Milky Way/yeah/(2) galaxy/(P)/").should eq ["(n) Milky Way/yeah","galaxy/(P)"] end it "two meanings where 2nd starts with non-number" do Glossary.edict_meanings("銀河 [ぎんが] /(n) (1) Milky Way/yeah/(n) (2) galaxy/(P)/").should eq ["(n) Milky Way/yeah","(n) galaxy/(P)"] end end end #edict_meanings context "#create_glossary" do it "no arguments creates an empty glossary" do lambda do lambda do lambda do create_glossary end.should change(Glossary,:count).by(1) Glossary.last.name.should eq "RSpec Name" end.should change(Definition,:count).by(0) end.should change(Meaning,:count).by(0) end it "one argument creates a glossary with name" do lambda do lambda do lambda do create_glossary("板垣") end.should change(Glossary,:count).by(1) Glossary.last.name.should eq "板垣" end.should change(Definition,:count).by(0) end.should change(Meaning,:count).by(0) end context "glossary with name and definition with reading" do it "second argument is a string" do lambda do lambda do lambda do create_glossary("板垣","いたがき") end.should change(Glossary,:count).by(1) end.should change(Definition,:count).by(1) end.should change(Meaning,:count).by(0) end it "second argument is an array" do lambda do lambda do lambda do create_glossary("板垣",["いたがき"]) end.should change(Glossary,:count).by(1) end.should change(Definition,:count).by(1) end.should change(Meaning,:count).by(0) end after(:each) do Glossary.last.name.should eq "板垣" Glossary.last.definitions.should eq [Definition.last] Definition.last.reading.should eq "いたがき" end end context "glossary with name, definition with reading and meaning with content" do it "three arguments" do lambda do lambda do lambda do create_glossary("板垣","いたがき","fruit shop") end.should change(Glossary,:count).by(1) end.should change(Definition,:count).by(1) end.should change(Meaning,:count).by(1) end it "second argument is an array" do lambda do lambda do lambda do create_glossary("板垣",["いたがき","fruit shop"]) end.should change(Glossary,:count).by(1) end.should change(Definition,:count).by(1) end.should change(Meaning,:count).by(1) end after(:each) do Glossary.last.name.should eq "板垣" Glossary.last.definitions.should eq [Definition.last] Definition.last.reading.should eq "いたがき" Definition.last.meanings.should eq [Meaning.last] Meaning.last.content.should eq "fruit shop" end end context "glossary with name, definition with reading and two meanings with content" do it "four arguments" do lambda do lambda do lambda do create_glossary("板垣","いたがき","fruit shop","meeting place") end.should change(Glossary,:count).by(1) end.should change(Definition,:count).by(1) end.should change(Meaning,:count).by(2) end it "second argument array" do lambda do lambda do lambda do create_glossary("板垣",["いたがき","fruit shop","meeting place"]) end.should change(Glossary,:count).by(1) end.should change(Definition,:count).by(1) end.should change(Meaning,:count).by(2) end after(:each) do Glossary.last.name.should eq "板垣" Glossary.last.definitions.should eq [Definition.last] Definition.last.reading.should eq "いたがき" Definition.last.meanings.should eq [Meaning.first,Meaning.last] Meaning.first.content.should eq "fruit shop" Meaning.last.content.should eq "meeting place" end end #four arguments... it "glossary with name and two readings" do lambda do lambda do lambda do create_glossary("板垣",["いたがき"],["ショップ"]) end.should change(Glossary,:count).by(1) Glossary.first.name.should eq "板垣" end.should change(Definition,:count).by(2) Glossary.first.definitions.should eq [Definition.first,Definition.last] Definition.first.reading.should eq "いたがき" Definition.last.reading.should eq "ショップ" end.should change(Meaning,:count).by(0) end it "four arguments creates a glossary with name, definition with reading and two meanings with content" do lambda do lambda do lambda do create_glossary("板垣","いたがき","fruit shop","meeting place") end.should change(Glossary,:count).by(1) Glossary.last.name.should eq "板垣" end.should change(Definition,:count).by(1) Glossary.last.definitions.should eq [Definition.last] Definition.last.reading.should eq "いたがき" end.should change(Meaning,:count).by(2) Definition.last.meanings.should eq [Meaning.first,Meaning.last] Meaning.first.content.should eq "fruit shop" Meaning.last.content.should eq "meeting place" end end end
require 'spec_helper' require 'capybara' feature "signing up" do it "has a sign up page" do visit new_user_url expect(page).to have_content("Sign Up") end feature "signs up a user" do before(:each) do sign_up end it "should have sign in input boxes" do visit new_user_url expect(page).to have_content("Username") expect(page).to have_content("Password") end it "should show error at empty password" do visit new_user_url fill_in "Username", :with => "testuser" click_on "Sign Up" expect(page).to have_content("Password is too short") end it "should show error at empty username" do visit new_user_url fill_in "Password", :with => "password" click_on "Sign Up" expect(page).to have_content("Username can't be blank") end it "should redirect to the user page" do expect(page).to have_content("testuser") end end end feature "logging in" do it "shows username on the homepage after login" do sign_up visit new_session_url fill_in "Username", :with => "testuser" fill_in "Password", :with => "password" click_button "Sign In" expect(page).to have_content("testuser") end end feature "logging out" do it "begins with logged out state" do visit root_url expect(page).to have_content("Sign In") expect(page).to have_content("Sign Up") end it "doesn't show username on homepage after logout" do sign_up visit new_session_url fill_in "Username", :with => "testuser" fill_in "Password", :with => "password" click_button "Sign In" click_button "Sign Out" expect(page).not_to have_content("testuser") end end
class Publisher < ActiveRecord::Base has_many :books validates_length_of :name, :in => 2..255 validates_uniqueness_of :name attr_accessible :name end
require 'open-uri' require 'rubygems' require 'digest/md5' class Admin::ArticleParse private @article @article_to_parse public def initialize(feed, article) @article = Article.new() @article.feed_id = feed.id @article_to_parse = article self end def parseTitle title = @article_to_parse.css("title").first title ? @article.title = title.text : @article.title = "" self end def parseImage image = @article_to_parse.css("original_image").first image ? @article.image = image.text : @article.image = "" self end def parseContent content = @article_to_parse.css("description").first content = content.text.gsub(/<br [\S\s]{0,}/, '') content ? @article.content = content : @article.content = "" self end def parseCreateTime create_time = @article_to_parse.css("published_at").first create_time.text ? @article.create_time = create_time.text.to_time : @article.create_time = "" self end def parseHash @article.hash_code = Digest::MD5.hexdigest(@article.content.to_s) self end def parseArticleUrl begin_url_pos = @article_to_parse.to_html.index("link>") + 5 end_url_pos = @article_to_parse.to_html.rindex("<guid") - begin_url_pos url_article = @article_to_parse.to_html[begin_url_pos,end_url_pos] if url_article @article.url = url_article else @article.url = "" end self end def parseArticle parseTitle().parseImage().parseContent().parseCreateTime().parseHash().parseArticleUrl() @article end end class Admin::NewscreadPlugin < Admin::ParserPlugin def getArticles(url) doc = Nokogiri::HTML(open(url)) articles = doc.xpath("//article") return articles end def load(feed) #url = "http://api.newscred.com/category/u-s/articles?access_key=c4bcc3f7c9bf9ec159f51da0a86ca658" @all_articles = [] @articles = getArticles(feed.url) article_num = 0 while @articles.count > article_num do @all_articles << Admin::ArticleParse.new(feed, @articles[article_num]).parseArticle() article_num +=1; end @all_articles end end Admin::NewscreadPlugin.createPlugin
class Flat < ApplicationRecord validates :name, :address, :price_per_night, :number_of_guests, presence: true validates :price_per_night, :number_of_guests, numericality: true end
module Balance::Cell class Index < Index.superclass # An .hpanel with a table of balances for a specific person. Has a link to # add a new balance for the person. # # If the person belongs to a couples account, the header will say "(Person # name)'s points". If it's a solo account, it will simply say "My points". # # This cell is rendered on balances#index, once for each person on the # account # # @!method self.call(person, opts = {}) # @param person [Person] class PersonPanel < Abroaders::Cell::Base include ::Cell::Builder include Escaped include Integrations::AwardWallet::Links builds do |person| AwardWallet if person.award_wallet? end property :first_name property :loyalty_accounts property :partner? property :type subclasses_use_parent_view! private def header_text "#{partner? ? "#{first_name}'s" : 'My'} points" end def link_to_add_new_balance link_to new_balance_path, class: 'btn btn-success btn-xs' do link_to_add_new_balance_text end end def link_to_add_new_balance_text '<i class="fa fa-plus"> </i> Add new' end def new_balance_modal '' end def rows if loyalty_accounts.any? cell( LoyaltyAccount::Cell::Table, loyalty_accounts, account: model, ) else 'No points balances' end end class AwardWallet < self property :id private def modal_id "new_balance_modal_person_#{id}" end def link_to_add_new_balance button_tag( class: 'btn btn-success btn-xs', 'data-toggle': 'modal', 'data-target': "##{modal_id}", ) do link_to_add_new_balance_text end end def new_balance_modal cell( Abroaders::Cell::ChoiceModal, [ { link: { href: new_balance_path, text: 'Add on Abroaders', }, text: t('balance.new_balance_modal.abroaders.text'), }, { link: { href: new_account_on_award_wallet_url, target: '_blank', text: 'Add on AwardWallet', }, text: t('balance.new_balance_modal.award_wallet.text'), }, ], id: modal_id, ) end end end end end
require 'rails_helper' RSpec.describe 'Vote', type: :model do it 'is not valid without an article_id' do vote = Vote.new(user_id: 1) expect(vote.save).to be(false) end it 'is not valid without an password' do vote = Vote.new(article_id: 1) expect(vote.save).to be(false) end it 'belongs to article association' do vote = Vote.reflect_on_association(:article) expect(vote.macro).to eq(:belongs_to) end it 'belongs to user association' do vote = Vote.reflect_on_association(:user) expect(vote.macro).to eq(:belongs_to) end end
module BasicObjectBehavior def private_features [ :initialize, :method_missing, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined ] end def protected_features [] end def public_features [ :"!", :"!=", :==, :__send__, :equal?, :instance_eval, :instance_exec ] end end module BasicObjectClassBehavior end
require 'spec_helper' describe HyperTraverser::HyperInterpreter do describe ".create" do it "creates an appropriate HyperState object out of the provided data" do raw_data = { "barney" => "stinson", "blarney" => "stone", "cool_stuff" => [ { "thing" => "beans" }, { "thing" => "windows 10" }, { "href" => "http://microsoft.com" } ], "get_more_cool_stuff" => { "href" => "http://google.com/search?q=cool+stuff" }, "doit" => { "action" => "http://duckduckgo.com", "method" => "PUT", "input" => { "search" => { "type" => "text", "required" => true, "value" => "" }, "result_limit" => { "type" => "integer", "required" => "false", "value" => 100 } } } } HyperTraverser::Hyper.expects(:take_action).with("http://microsoft.com", "GET").returns(described_class.create({ "bing" => "bang" })) HyperTraverser::Hyper.expects(:take_action).with("http://google.com/search?q=cool+stuff", "GET").returns(described_class.create({ "docs" => "drive" })) HyperTraverser::Hyper.expects(:take_action).with("http://duckduckgo.com", "PUT", { search: "goose", result_limit: 40}.to_json).returns(described_class.create({ "quack" => "quack" })) hyper_obj = described_class.create raw_data expect(hyper_obj.barney).to eq("stinson") expect(hyper_obj.blarney).to eq("stone") expect(hyper_obj.cool_stuff[0].thing).to eq("beans") cool_stuff = hyper_obj.cool_stuff expect(cool_stuff[1].thing).to eq("windows 10") expect(cool_stuff[2].bing).to eq("bang") expect(hyper_obj.get_more_cool_stuff.docs).to eq("drive") doit = hyper_obj.doit expect(doit.inputs.search).to eq("") expect(doit.inputs.result_limit).to eq(100) doit.inputs.search = "goose" doit.inputs response = doit.submit result_limit: 40 expect(response.quack).to eq("quack") end it "creates collections" do raw_data = { "barney" => "stinson", "collection" => [ { "href" => "www.ruby.com" }, { "href" => "www.javascript.com" }, ] } HyperTraverser::Hyper.expects(:take_action).with("www.ruby.com", "GET").returns(described_class.create({ "proc" => "block" })) HyperTraverser::Hyper.expects(:take_action).with("www.javascript.com", "GET").returns(described_class.create({ "good" => "parts" })) hyper_obj = described_class.create raw_data expect(hyper_obj.barney).to eq("stinson") expect(hyper_obj[0].proc).to eq("block") expect(hyper_obj[1].good).to eq("parts") end end end
require 'spec_helper' describe 'openldap::server::slapdconf' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end context 'with no parameters' do let :pre_condition do "class {'openldap::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('openldap::server::slapdconf') } it { is_expected.to contain_openldap__server__database('dc=my-domain,dc=com').with({:ensure => :absent,})} end # On rhel, openldap is linked against moz nss: # ssl_ca parameter should contain the path to the moz nss database # ssl_cert parameter should contain the name of the certificate stored into the moz nss database # ssl_key can be omitted/is not used context 'with ssl_cert and ssl_ca set but not ssl_key' do let :pre_condition do "class {'openldap::server': ssl_cert => 'my-domain.com', ssl_ca => '/etc/openldap/certs'}" end case facts[:osfamily] when 'Debian' it { expect { is_expected.to compile }.to raise_error(/You must specify a ssl_key/) } when 'RedHat' it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('openldap::server::slapdconf') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCertificateFile') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCACertificateFile') } it { is_expected.not_to contain_openldap__server___globalconf( 'TLSCertificateKeyFile') } end end context 'with ssl_cert, ssl_key and ssl_ca set' do let :pre_condition do "class {'openldap::server': ssl_cert => '/etc/openldap/certs/fqdn.tld.crt', ssl_key => '/etc/openldap/certs/fqdn.tld.key', ssl_ca => '/etc/openldap/certs/ca.crt'}" end case facts[:osfamily] when 'Debian' it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('openldap::server::slapdconf') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCertificateFile') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCACertificateFile') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCertificateKeyFile') } when 'RedHat' it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('openldap::server::slapdconf') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCertificateFile') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCACertificateFile') } it { is_expected.to contain_openldap__server__globalconf( 'TLSCertificateKeyFile') } end end end end end
class DropSessionsTable < ActiveRecord::Migration def self.up drop_table :sessions end def self.down raise ActiveRecord::IrreversibleMigration end end
class Reputable::BadgeAward < ActiveRecord::Base set_table_name :reputable_badge_awards belongs_to :badge, :class_name => "Reputable::Badge" end
class Calculator attr_reader :number, :operation, :number_2 def initialize(number, operation, number_2) @number = number @operation = operation @number_2 = number_2 end def calculate case operation when "addition" result = number + number_2 when "subtraction" result = number - number_2 when "multiplication" result = (number.to_f * number_2.to_f).to_f when "division" result = (number.to_f/number_2.to_f).to_f else result = "Could not be calcuated" end end #def number #attr_reader replaces this method # return "#{@number}" #end end
class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.references 'sub' t.references 'user' t.text 'title' t.text 'text' t.text 'link' t.boolean 'visible', :default => false t.integer :sub_comments, :default => 0 t.integer :votes_diff, :default => 0 t.float :hotness, :default => 0 t.timestamps end add_index('posts', 'sub_id') end end
require 'rspec' require './lib/Sudoku/puzzle' require './lib/Solver/solver' describe 'Sudoku solver feature' do it 'should be able to solve via Only Possibility' do m = Puzzle.new(9).set("5 0 0 0 8 0 0 6 0 \n9 7 2 0 0 1 0 0 0 \n8 6 0 0 3 0 5 0 0 \n4 9 0 8 1 0 0 2 6 \n6 0 0 0 0 0 0 0 8 \n3 2 0 0 6 5 0 9 7 \n0 0 9 0 4 0 0 7 5 \n0 0 0 5 0 0 6 8 1 \n0 5 0 0 2 0 0 0 3 \n") Solver.scan(m, :possibility) expect(m.to_s).to eq("5 0 0 0 8 0 0 6 0 \n9 7 2 0 5 1 0 0 4 \n8 6 0 0 3 0 5 1 0 \n4 9 0 8 1 0 3 2 6 \n6 1 0 0 0 0 4 5 8 \n3 2 8 4 6 5 1 9 7 \n0 0 9 0 4 0 2 7 5 \n0 0 0 5 0 0 6 8 1 \n0 5 0 0 2 0 9 4 3 \n") end it 'should be able to solve via Elimination' do m = Puzzle.new(9).set("5 0 0 0 8 0 0 6 0 \n9 7 2 0 0 1 0 0 0 \n8 6 0 0 3 0 5 0 0 \n4 9 0 8 1 0 0 2 6 \n6 0 0 0 0 0 0 0 8 \n3 2 0 0 6 5 0 9 7 \n0 0 9 0 4 0 0 7 5 \n0 0 0 5 0 0 6 8 1 \n0 5 0 0 2 0 0 0 3 \n") Solver.scan(m, :elimination) # still have certain flaws if it is run multiple times expect(m.to_s).to eq("5 0 0 0 8 0 0 6 0 \n9 7 2 6 5 1 0 0 0 \n8 6 0 0 3 0 5 0 0 \n4 9 0 8 1 0 0 2 6 \n6 0 0 0 0 0 0 0 8 \n3 2 8 0 6 5 0 9 7 \n0 0 9 0 4 0 2 7 5 \n0 0 0 5 0 0 6 8 1 \n0 5 0 0 2 0 9 0 3 \n") end end
require 'rails_helper' RSpec.describe Role, type: :model do before :each do @role = Role.new end describe '#new' do it 'nimmt Parameter fuer Rollen an' do @role.should be_an_instance_of Role end end end
#todos estos son métodos de instancia class Persona #con esto estamos creando sus respectivos getters y setters attr_accessor :nombre,:sexo,:edad #si no queremos que se pueda cambiar un atributo, como el dni por ejemplo #damos permisos de solo lectura attr_reader :dni #también tenemos de solo escritura #attr_writer #Genero una variable de clase! (con @@) @@numero_de_personas = 0 #Defino un método de clase para acceder al nº de personas (con self.loquesea) def self.getNumeroPersonas @@numero_de_personas end #Este es el constructor de clase def initialize (dni, nombre, sexo, edad) #injección de dependencias @dni = dni @nombre = nombre @sexo = sexo @edad = edad #al no inicializarlo, decicimos que este atributo no es imprescindible para la creación del objeto persona. No lo pasas por constructor @colorOjos = nil end #utilizando set y get es la manera clásica de hacerlo def setColorOjos colorOjos @colorOjos = colorOjos end def getColorOjos @colorOjos end #no se puede poner espacio entre el igual y el nombre porque estas definiendo el nombre de un método def colorOjos= colorOjos @colorOjos = colorOjos end #lkjdlsjk def colorOjos @colorOjos end def saludar puts "Hola a todos, soy una persona y me llamo #{@nombre}" end def to_s "#{@dni},#{@nombre},#{@edad},#{@sexo},#{@colorOjos}" end end
class ChangeTableInspectsMeterAnomaly < ActiveRecord::Migration def change change_column :inspects, :meter_anomaly, :text, :limit => 4294967295 end end
CarrierWave.configure do |config| config.fog_credentials = { :provider => 'AWS', # required :aws_access_key_id => ENV['AWS_ACCESS_KEY'], # required :aws_secret_access_key => ENV['AWS_SECRET_KEY'], :region => 'us-west-2' } config.cache_dir = "#{Rails.root}/tmp/uploads" config.fog_directory = 'manuable02' # required config.fog_public = false # optional, defaults to true #config.asset_host = "https://manuable02.s3-us-west-2.amazonaws.com/" config.fog_attributes = { 'Cache-Control' => 'max-age=315576000' } # optional, defaults to {} config.fog_authenticated_url_expiration = 1000 config.storage = :fog config.enable_processing = true end
# frozen_string_literal: true module Halcyoninae class ArgumentsParser def initialize(argv) @left, @right = argv.slice_after(DOUBLE_DASH).to_a end def run parse_arguments end private attr_reader :left, :right DASH = "-" DOUBLE_DASH = "--" # https://goo.gl/qTPnwx def parse_arguments [arguments, right].flatten.compact end def arguments left.reject { |arg| option?(arg) } end def option?(arg) arg.start_with?(DASH) || arg.start_with?(DOUBLE_DASH) end end end
require('capybara/rspec') require('./app') Capybara.app = Sinatra::Application set(:show_exceptions, false) describe('add a new word from index path', {:type => :feature}) do it ("allows a user to submit a new word and adds it to the list of words") do visit('/') fill_in('word_name', :with => 'Socialism') click_button('Submit') expect(page).to have_content('Socialism') end end describe('view the definition(s) of a word from index path', {:type => :feature}) do it ("allows a user to click on a word and view its definitions") do visit('/') fill_in('word_name', :with => 'Capitalism') click_button('Submit') expect(page).to have_content('Capitalism') click_link('Capitalism') expect(page).to have_content('Add a new definition to Capitalism') end end describe('add a definition to a word from the word path', {:type => :feature}) do it ("allows a user to submit a description, synonyms, antonyms, and example phrase/sentence and adds the complete definition to the list of definitions for the word.") do visit('/') fill_in('word_name', :with => 'Freedom') click_button('Submit') expect(page).to have_content('Freedom') click_link('Freedom') expect(page).to have_content('Add a new definition to Freedom') fill_in('description', :with => 'the state of being free from the control or power of another') fill_in('synonym', :with => ['emancipation', 'autonomy']) fill_in('antonym', :with => ['subjection', 'dependence']) fill_in('example', :with => 'She has the freedom to do as she likes') click_button('Submit') expect(page).to have_content('She has the freedom to do as she likes') end end describe('return home from word path', {:type => :feature}) do it ("allows a user to return to the main dictionary page after visiting a word's page") do visit('/') fill_in('word_name', :with => 'Joy') click_button('Submit') expect(page).to have_content('Joy') click_link('Joy') expect(page).to have_content('Add a new definition to Joy') fill_in('description', :with => 'a feeling of great happiness') fill_in('synonym', :with => ['delight', 'bliss']) fill_in('antonym', :with => ['sadness', 'misery']) fill_in('example', :with => 'Spring wildflowers are a joy to behold.') click_button('Submit') expect(page).to have_content('Spring wildflowers are a joy to behold.') click_link('Return to Dictionary') expect(page).to have_content('Your words') end end
require "nokogiri" require_relative "kanji" class Kanjidic end class Kanjidic::Parser < Nokogiri::XML::SAX::Document DEFAULT_FILENAME = "/usr/share/kanjidic2/kanjidic2.xml" def initialize(filename = DEFAULT_FILENAME) @kanji = [] @current_kanji = nil parser = Nokogiri::XML::SAX::Parser.new(self) do |config| config.strict config.nonet end parser.parse(File.open(filename)) end # @return [Array<RawKanji>] def all @kanji end private def start_element(name, attributes = []) if name == "character" @current_kanji = RawKanji.new end if @current_kanji @current_kanji.start_element(name, attributes) end end def characters(string) if @current_kanji @current_kanji.characters(string) end end def end_element(name) if @current_kanji @current_kanji.end_element(name) end if name == "character" @kanji << @current_kanji @current_kanji = nil end end end
class CreateContact def initialize(params) @params = params end def call return Result.failure("Invalid phone number") unless phone_number.valid? contact = initialize_contact if contact.update(params.merge(saved: true)) Result.success(contact: contact) else Result.failure(contact.errors) end end private attr_reader :params, :lookup_adapter def initialize_contact Contact.for_user(params[:user]).find_or_initialize_by(phone_number: phone_number.to_s) end def phone_number params[:phone_number] end end
class CreateNoticia < ActiveRecord::Migration[5.2] def change create_table :noticia do |t| t.string :titulo t.string :texto t.string :foto t.string :fotografo t.references :usuario, foreign_key: true t.timestamps end end end
class AddConfirmationToOrder < ActiveRecord::Migration def change add_column :orders, :confirmation, :string, limit: 32 add_index :orders, :confirmation, unique: true end end
require 'test_helper' class ApiControllerTest < ActionDispatch::IntegrationTest test "should get state of the app" do get api_state_url assert_response :success body = JSON.parse(response.body, symbolize_names: true) assert_equal body[:app_state], 'running' end test "card info should return 401 for unauthorized user" do get api_card_info_url assert_response 401 # (unauthorized) end test "card info should return information about a card" do params = {cln_or_id: 920310153687} auth_headers = {"Authorization" => "Basic #{Base64.encode64('oict:secret')}"} # I know I am calling the real endpoint... I should create a mock for it... :) get '/api/card_info', params: params, as: :json, headers: auth_headers assert_response :success body = JSON.parse(response.body, symbolize_names: true) assert_equal body[:state_description], 'Aktivní v držení klienta' assert_equal body[:validity_end], '12.08.2020' end test "card info should require correct parameter" do params = {wrong_param: 920310153687} auth_headers = {"Authorization" => "Basic #{Base64.encode64('oict:secret')}"} get '/api/card_info', params: params, as: :json, headers: auth_headers body = JSON.parse(response.body, symbolize_names: true) assert_equal body[:error_params], 'Please, check params.' end end
require File.expand_path('../../../helpers/compute/data_helper', __FILE__) module Fog module Compute class ProfitBricks class Nic < Fog::Models::ProfitBricks::Base include Fog::Helpers::ProfitBricks::DataHelper identity :id # properties attribute :name attribute :mac attribute :ips attribute :dhcp attribute :lan attribute :nat attribute :firewall_active, :aliases => 'firewallActive' # metadata attribute :created_date, :aliases => 'createdDate', :type => :time attribute :created_by, :aliases => 'createdBy' attribute :last_modified_date, :aliases => 'lastModifiedDate', :type => :time attribute :last_modified_by, :aliases => 'lastModifiedBy' attribute :request_id, :aliases => 'requestId' attribute :state # entities attribute :firewallrules attribute :firewall_rules attribute :datacenter_id attribute :server_id attr_accessor :options def save requires :datacenter_id, :server_id, :lan properties = {} properties[:name] = name if name properties[:ips] = ips if ips properties[:dhcp] = dhcp if dhcp properties[:lan] = lan if lan properties[:nat] = nat if nat properties[:firewallActive] = firewall_active if firewall_active entities = {} if firewall_rules properties[:firewallActive] = true entities[:firewallrules] = get_firewall_rules(firewall_rules) end data = service.create_nic(datacenter_id, server_id, properties, entities) merge_attributes(flatten(data.body)) end def update requires :datacenter_id, :server_id, :id properties = {} properties[:name] = name if name properties[:ips] = ips if ips properties[:dhcp] = dhcp if dhcp properties[:lan] = lan if lan properties[:nat] = nat if nat data = service.update_nic(datacenter_id, server_id, id, properties) merge_attributes(data.body) end def delete requires :datacenter_id, :server_id, :id service.delete_nic(datacenter_id, server_id, id) true end def reload requires :datacenter_id, :server_id, :id data = begin collection.get(datacenter_id, server_id, id) rescue Excon::Errors::SocketError nil end return unless data new_attributes = data.attributes merge_attributes(new_attributes) self end def get_firewall_rules(firewall_rules) items = [] firewall_rules.each do |firewall_rule| item = {} item[:name] = firewall_rule[:name] if firewall_rule.key?(:name) item[:protocol] = firewall_rule[:protocol] if firewall_rule.key?(:protocol) item[:sourceMac] = firewall_rule[:source_mac] if firewall_rule.key?(:source_mac) item[:sourceIp] = firewall_rule[:source_ip] if firewall_rule.key?(:source_ip) item[:targetIp] = firewall_rule[:target_ip] if firewall_rule.key?(:target_ip) item[:portRangeStart] = firewall_rule[:port_range_start] if firewall_rule.key?(:port_range_start) item[:portRangeEnd] = firewall_rule[:port_range_end] if firewall_rule.key?(:port_range_end) item[:icmpType] = firewall_rule[:icmp_type] if firewall_rule.key?(:icmp_type) item[:icmpCode] = firewall_rule[:icmp_code] if firewall_rule.key?(:icmp_code) items << { :properties => item } end { :items => items } end end end end end
RSpec.describe 'assorted sanity checks' do let(:resource_methods) { Yaks::Resource.public_instance_methods.sort } let(:collection_resource_methods) { Yaks::CollectionResource.public_instance_methods.sort } let(:null_resource_methods) { Yaks::NullResource.public_instance_methods.sort } specify 'all resource classes should have the exact same public API' do expect(resource_methods).to eql null_resource_methods expect(resource_methods).to eql collection_resource_methods end end
class MeetingDetail < ApplicationRecord belongs_to :meeting, optional: true #alae001 - need to remove optional statement to ensure rule is enforced. belongs_to :role, optional: true #alae001 - need to remove optional statement to ensure rule is enforced. belongs_to :user, optional: true #alae001 - need to remove optional statement to ensure rule is enforced. belongs_to :meeting_detail_status, optional: true #alae001 - need to remove optional statement to ensure rule is enforced. has_many :clubs, :through => :meetings scope :sorted, lambda { order("id DESC" , "sort_order ASC") } scope :newest_first, lambda { order("created_at DESC") } scope :sort_order, lambda { order("sort_order ASC") } scope :search, lambda {|query| where(["discription LIKE ?", "%#{query}%"]) } end
require 'test_helper' class TokenizerTest < Minitest::Test def test_tokenize_strings assert_equal [' '], tokenize(' ') assert_equal ['hello world'], tokenize('hello world') end def test_tokenize_variables assert_equal ['{{funk}}'], tokenize('{{funk}}') assert_equal [' ', '{{funk}}', ' '], tokenize(' {{funk}} ') assert_equal [' ', '{{funk}}', ' ', '{{so}}', ' ', '{{brother}}', ' '], tokenize(' {{funk}} {{so}} {{brother}} ') assert_equal [' ', '{{ funk }}', ' '], tokenize(' {{ funk }} ') end def test_tokenize_blocks assert_equal ['{%comment%}'], tokenize('{%comment%}') assert_equal [' ', '{%comment%}', ' '], tokenize(' {%comment%} ') assert_equal [' ', '{%comment%}', ' ', '{%endcomment%}', ' '], tokenize(' {%comment%} {%endcomment%} ') assert_equal [' ', '{% comment %}', ' ', '{% endcomment %}', ' '], tokenize(" {% comment %} {% endcomment %} ") end def test_calculate_line_numbers_per_token_with_profiling template = Liquid::Template.parse("", :profile => true) assert_equal [1], template.send(:tokenize, "{{funk}}").map(&:line_number) assert_equal [1, 1, 1], template.send(:tokenize, " {{funk}} ").map(&:line_number) assert_equal [1, 2, 2], template.send(:tokenize, "\n{{funk}}\n").map(&:line_number) assert_equal [1, 1, 3], template.send(:tokenize, " {{\n funk \n}} ").map(&:line_number) end private def tokenize(source) Liquid::Template.new.send(:tokenize, source) end end
require 'rails_helper' RSpec.describe "txns/new", type: :view do before(:each) do assign(:txn, Txn.new( :amount => "9.99", :bank_number => "MyString", :debit_account => 1, :credit_account => 1, :payment => false, :ledger => nil, :apt => nil )) end it "renders new txn form" do render assert_select "form[action=?][method=?]", txns_path, "post" do assert_select "input[name=?]", "txn[amount]" assert_select "input[name=?]", "txn[bank_number]" assert_select "input[name=?]", "txn[debit_account]" assert_select "input[name=?]", "txn[credit_account]" assert_select "input[name=?]", "txn[payment]" assert_select "input[name=?]", "txn[ledger_id]" assert_select "input[name=?]", "txn[apt_id]" end end end
require File.join(Dir.pwd, 'spec', 'spec_helper') describe 'UserSkillList' do before do simulate_connection_to_server end after do end it 'should pass if user skill list attribute is not specifed' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_skill_list, { :total_entries => 1, :total_pages => 1, :skills => [FactoryGirl.attributes_for(:user_skill)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) skill_list = TheCityAdmin::UserSkillList.new({:user_id => user_id}) skill = skill_list[0] skill.name.should == "Teaching-Curriculum" end it 'should pass if user skill list is empty' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_skill_list, { :total_entries => 1, :total_pages => 1, :skills => [] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) skill_list = TheCityAdmin::UserSkillList.new({:user_id => user_id}) skill_list.empty?.should be_true end it 'should return a valid list of user skills' do user_id = 123 page = 2 request_data = FactoryGirl.attributes_for(:user_skill_list, { :total_entries => 1, :total_pages => 1, :skills => [FactoryGirl.attributes_for(:user_skill)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) skill_list = TheCityAdmin::UserSkillList.new({:user_id => user_id, :page => page}) skill = skill_list[0] skill.name.should == "Teaching-Curriculum" end it 'should iterate using *each* method' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_skill_list, { :total_entries => 1, :total_pages => 1, :skills => [FactoryGirl.attributes_for(:user_skill)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) skill_list = TheCityAdmin::UserSkillList.new({:user_id => user_id}) skills = [] skill_list.each { |skill| skills << skill.name } skills.should == ["Teaching-Curriculum"] end it 'should iterate using *collect* method' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_skill_list, { :total_entries => 1, :total_pages => 1, :skills => [FactoryGirl.attributes_for(:user_skill)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) skill_list = TheCityAdmin::UserSkillList.new({:user_id => user_id}) skills = skill_list.collect { |skill| skill.name } skills.should == ["Teaching-Curriculum"] end end
require 'rails_helper' describe Review, type: :model do describe 'Validations' do it { should validate_presence_of(:title) } it { should validate_presence_of(:body) } it { should validate_presence_of(:rating) } it { should validate_presence_of(:user_id) } it { should validate_presence_of(:book_id) } end describe 'Relationship' do it { should belong_to(:book) } it { should belong_to(:user) } end describe 'Methods' do it 'can find all reviews belonging to a specific user' do author_1 = Author.create(name: 'George Orwell') book_1 = author_1.books.create(title: '1984', pages: 300, year: 1936) user_1 = User.create(username: "Isaac F.") review_1 = book_1.reviews.create( title: "Great book!", body: "I really liked this book! Must read!", rating: 5, user_id: user_1.id) review_2 = book_1.reviews.create( title: "Pretty good.", body: "I enjoyed this book but it has it's issues.", rating: 4, user_id: user_1.id) reviews = Review.find_reviews_by_user_id(user_1.id) expect(reviews.first.title).to eq('Pretty good.') expect(reviews.second.title).to eq('Great book!') end end end
module RequestsHelper def format_date(date,short=nil) return if date.nil? time = Date.parse(date.to_s) time.strftime("%-m/%-d") end def format_time(time) return if time.nil? time = Time.parse(time.to_s) time.strftime("%l:%M%p").sub!('M','').downcase end def format_availability(a) date = [] << if a.date || a.endDate if a.endDate.nil? ["on",format_date(a.date)] elsif a.date.nil? ["before", format_date(a.endDate)] else [format_date(a.date), "-", format_date(a.endDate)] end end time = [] << if a.startTime || a.endTime if a.startTime.nil? ["by", format_time(a.endTime)] elsif a.endTime.nil? ["after", format_time(a.startTime)] else [" from", format_time(a.startTime), "-", format_time(a.endTime)] end end joiner = "::" if date.count + time.count == 2 [date,time].flatten.join(" ").html_safe end end
class CreateBackgroundrbQueueTable < ActiveRecord::Migration def self.up create_table :bdrb_job_queues do |t| t.column :args, :text t.column :worker_name, :string t.column :worker_method, :string t.column :job_key, :string t.column :taken, :int t.column :finished, :int t.column :timeout, :int t.column :priority, :int t.column :submitted_at, :datetime t.column :started_at, :datetime t.column :finished_at, :datetime t.column :archived_at, :datetime t.column :tag, :string t.column :submitter_info, :string t.column :runner_info, :string t.column :worker_key, :string t.column :scheduled_at, :datetime end end def self.down drop_table :bdrb_job_queues end end
module GroupDocs class Document::View < Api::Entity # @attr [GroupDocs::Document] document attr_accessor :document # @attr [String] short_url attr_accessor :short_url # @attr [Time] viewed_on attr_accessor :viewed_on # # Converts timestamp which is return by API server to Time object. # # @return [Time] # def viewed_on Time.at(@viewed_on / 1000) end # # Converts passed hash to GroupDocs::Document object. # # @param [GroupDocs::Document, Hash] object # @return [GroupDocs::Document] # def document=(object) if object.is_a?(GroupDocs::Document) @document = object else object.merge!(:file => GroupDocs::Storage::File.new(object)) @document = GroupDocs::Document.new(object) end end end # Document::View end # GroupDocs
# In Order def in_order?(array) array.each_with_index do |el, idx| next if idx == 0 return false unless el >= array[idx - 1] end true end # ------------------------------------------------------------------------------ # Boolean to Binary def boolean_to_binary(array) binary = "" array.each do |boolean| if boolean binary << "1" else binary << "0" end end binary end # ------------------------------------------------------------------------------ # More Vowels def count_vowels(word) vowels = %w(a e i o u) idx = 0 count = 0 while idx < word.length count += 1 if vowels.include?(word[idx]) idx += 1 end count end def more_vowels(string1, string2) vowel_count_1 = count_vowels(string1) vowel_count_2 = count_vowels(string2) if vowel_count_1 > vowel_count_2 string1 elsif vowel_count_2 > vowel_count_1 string2 else "tie" end end # ------------------------------------------------------------------------------ # Fibonacci Sequence def fibs(n) sequence = [0, 1] return sequence[0, n] if n <= 2 until sequence.length == n sequence << sequence[-1] + sequence[-2] end sequence end
require 'test_helper' class CustomerBookingsControllerTest < ActionDispatch::IntegrationTest setup do @customer_booking = customer_bookings(:one) end test "should get index" do get customer_bookings_url, as: :json assert_response :success end test "should create customer_booking" do assert_difference('CustomerBooking.count') do post customer_bookings_url, params: { customer_booking: { booking_order_id: @customer_booking.booking_order_id, created_by: @customer_booking.created_by, customer_id: @customer_booking.customer_id, is_active: @customer_booking.is_active, updated_by: @customer_booking.updated_by } }, as: :json end assert_response 201 end test "should show customer_booking" do get customer_booking_url(@customer_booking), as: :json assert_response :success end test "should update customer_booking" do patch customer_booking_url(@customer_booking), params: { customer_booking: { booking_order_id: @customer_booking.booking_order_id, created_by: @customer_booking.created_by, customer_id: @customer_booking.customer_id, is_active: @customer_booking.is_active, updated_by: @customer_booking.updated_by } }, as: :json assert_response 200 end test "should destroy customer_booking" do assert_difference('CustomerBooking.count', -1) do delete customer_booking_url(@customer_booking), as: :json end assert_response 204 end end
# frozen_string_literal: true # The InstrumentParser is responsible for the <Instrmt> mapping. This tag is one of many tags inside # a FIXML message. To see a complete FIXML message there are many examples inside of spec/datafiles. # # Relevant FIXML Slice: # # <Instrmt PxQteCcy="USD" Exch="NYMEX" PutCall="0" UOM="MMBtu" Mult="10000" StrkPx="65.0" MatDt="2014-12-26" # MMY="201501" SecTyp="OPT" CFI="OPAXPS" Src="H" ID="ON" Sym="ONF5 P65000"/> # module CmeFixListener # <Instrmt> Mappings from abbreviations to full names (with types) class InstrumentParser extend ParsingMethods MAPPINGS = [ ["productSymbol", "Sym"], ["productCode", "ID"], ["productSourceCode", "Src"], ["cfiCode", "CFI"], ["securityType", "SecTyp"], ["indexName", "SubTyp"], ["contractPeriodCode", "MMY"], ["maturityDate", "MatDt"], ["nextCouponCode", "CpnPmt"], ["restructuringType", "RestrctTyp"], ["seniority", "Snrty"], ["strikePrice", "StrkPx", :to_f], ["priceMultiplier", "Mult", :to_f], ["unitOfMeasure", "UOM"], ["unitOfMeasureCurrency", "UOMCcy"], ["putCall", "PutCall", :to_i], ["couponRate", "CpnRt"], ["productExchange", "Exch"], ["nextCouponDate", "IntArcl"], ["priceQuoteCurrency", "PxQteCcy"] ].freeze end end
class CreateContactPages < ActiveRecord::Migration def change create_table :contact_pages do |t| t.text :address t.text :working_hours t.text :contacts t.string :map_coordinates t.timestamps end end end
class AddOnMainToGoods < ActiveRecord::Migration def change add_column :goods, :on_main, :boolean end end
# == Schema Information # # Table name: match_answers # # id :integer not null, primary key # answer_id :integer # match_id :integer # team_id :integer # created_at :datetime not null # updated_at :datetime not null # match_question_id :integer # is_correct :boolean default(FALSE), not null # # Indexes # # index_match_answers_on_answer_id (answer_id) # index_match_answers_on_match_id (match_id) # index_match_answers_on_match_question_id (match_question_id) # index_match_answers_on_match_question_id_and_team_id (match_question_id,team_id) UNIQUE # index_match_answers_on_team_id (team_id) # class MatchAnswer < ApplicationRecord validates :match_question, presence: true validates :match, presence: true validates :team, presence: true validates :match, uniqueness: { scope: [:team, :match_question] } validates :match_question, uniqueness: { scope: [:team] } belongs_to :answer belongs_to :match_question belongs_to :match belongs_to :team def self.of_team(team:) where(team: team) end end
# Euler problem 44 class Problem44 def main pentagnoal_numbers = generate_pentagnoal_numbers(10_000) pairs = prepare_pairs(pentagnoal_numbers) puts 'Start' pairs.each do |pair| if pentagnoal_numbers.include?(pair_sum(pair)) && pentagnoal_numbers.include?(pair_difference(pair)) puts "pair: #{pair}, D:#{value_of_D(pair)}" end # if pentagnoal_numbers.include?(pair_sum(pair)) # puts "pair: #{pair}, D:#{value_of_D(pair)}" # end end puts 'End' end def pentagonal_sequence(n) n * (3 * n - 1) / 2 end def generate_pentagnoal_numbers(n) pentagonal_numbers = [] for i in 1..n pentagonal_numbers.push(pentagonal_sequence(i)) end pentagonal_numbers end def prepare_pairs(numbers_list) numbers_list.combination(2).to_a end def pair_sum(pair) pair[0] + pair[1] end def pair_difference(pair) pair[0] - pair[1] end def value_of_d(pair) (pair[1] - pair[0]).abs end end p44 = Problem44.new puts p44.main
class AddToToRingGroupCalls < ActiveRecord::Migration[5.2] def change add_column :ring_group_calls, :to, :string, array: true, default: [], null: false end end
class Array def sorted? (self.length-1).times do |index| if self[index] > self[index+1] return false end end return true end end [4, 6, 23, 63, 7, 234, 75, 234, 7543] def bogosort(array) ary = array.dup while not ary.sorted? ary.shuffle! end return ary end def bubblesort(array) ary = array.dup n = ary.length-1 swapped = true while swapped do swapped = false (n).times do |i| if ary[i] > ary[i+1] ary[i], ary[i+1] = ary[i+1], ary[i] swapped = true end end n-=1 end return ary end def gnomesort(array) ary = array.dup (ary.length).times do |index| (index).times do |time| if ary[index-time] < ary[index-time-1] ary[index-time], ary[index-time-1] = ary[index-time-1], ary[index-time] else break end end end return ary end def selectionsort(array) ary = array.dup n = ary.length - 1 n.times do |i| index_min = i (i + 1).upto(n) do |j| index_min = j if ary[j] < ary[index_min] end ary[i], ary[index_min] = ary[index_min], ary[i] if index_min != i end return ary end def insertionsort(array) ary = array.dup 1.upto(ary.length-1) do |index| ins = index 1.upto(index) do |time| if ary[index-time] > ary[index] ins = index-time else break end end ary.insert(ins, ary.delete_at(index)) end return ary end def shellsort(array) ary = array.dup k = ary.length/2 while k > 0 (ary.length-k).times do |index| ((ary.length/k)-1).times do |time| if ary[index-time] > ary[(index+k)-time] && index-time >= 0 ary[index-time], ary[(index+k)-time] = ary[(index+k)-time], ary[index-time] else break end end end k = k/2 end return ary end def radixsortlsd(array) ary = array.dup k = 0 ary.each { |value| k = value.to_s.length if value.to_s.length > k } ary.each_with_index {|value, index| ary[index] = value.to_s.rjust(k, "0").chars.map(&:to_i)} k.times do |digit| bucket = {0 => [], 1 => [], 2=> [], 3 => [], 4 => [], 5 => [], 6 => [], 7 => [], 8 => [], 9 => []} ary.each_with_index do |value, index| bucket[(value.reverse[digit])] << value end ary = [] bucket.each do |key, value| value.each do |num| ary << num end end end ary.each_with_index { |value, index| ary[index] = value.inject{|n, d| n * 10 + d} } return ary end def quicksort(array) ary = array.dup return ary if ary.length <= 1 pivot = ary.delete_at(-1) lower, upper = [], [] ary.each do |value| lower << value if value <= pivot upper << value if value > pivot end return quicksort(lower) + [pivot] + quicksort(upper) end
def input_students puts "Please enter the names of the students." puts "To finish, just hit return twice." # crate an empty array students = [] # get the first name name = gets.chomp # while the name is not empty, repeat this code while !name.empty? do # add the student hash to the array students << {:name => name, :cohort => :February} puts "Now we have #{students.length} students" # get another name from the user name = gets.chomp end # return the array of students students end =begin students = [ {:name => "Mario Gintili", :cohort => :february, :cob => :uk}, {:name => "Mikhail Dubov", :cohort => :february, :cob => :uk}, {:name => "Karolis Noreika", :cohort => :february, :cob => :uk}, {:name => "Michael Sidon", :cohort => :february, :cob => :uk}, {:name => "Charles De Barros", :cohort => :february, :cob => :uk}, {:name => "Ruslan Vikhor", :cohort => :february, :cob => :uk}, {:name => "Toby Retallick", :cohort => :february, :cob => :uk}, {:name => "Mark Mekhaiel", :cohort => :february, :cob => :uk}, {:name => "Sarah Young", :cohort => :february, :cob => :uk}, {:name => "Hannah Wight", :cohort => :february, :cob => :uk}, {:name => "Khushkaran Singh", :cohort => :february, :cob => :uk}, {:name => "Rick Brunstedt", :cohort => :february, :cob => :uk}, {:name => "Manjit Singh", :cohort => :february, :cob => :uk}, {:name => "Alex Gaudiosi", :cohort => :february, :cob => :uk}, {:name => "Ross Hepburn", :cohort => :february, :cob => :uk}, {:name => "Natascia Marchese", :cohort => :february, :cob => :uk}, {:name => "Tiffanie Chia", :cohort => :february, :cob => :uk}, {:name => "Matthew Thomas", :cohort => :february, :cob => :uk}, {:name => "Freddy McGroarty", :cohort => :february, :cob => :uk}, {:name => "Tyler Rollins", :cohort => :february, :cob => :uk}, {:name => "Richard Curteis", :cohort => :february, :cob => :uk}, {:name => "Anna Yanova", :cohort => :february, :cob => :uk}, {:name => "Andrew Cumine", :cohort => :february, :cob => :uk} ] =end def print_header puts "The Students of my Cohort at Makers Academy" puts "-------------" end def print(students) students.each_with_index do |student, index| # .each_with_index adds numbers to the front each item in the rash # puts "#{index+1}: #{student[:name]} (#{student[:cohort]} cohort)" if student[:name].length < 12 puts "#{student[:name]} " else puts nil end end end def print_footer(names) puts "\n" puts "Overal, we have #{names.length} great students.\n\n" end # nothing happens until we call the methods students = input_students print_header print(students) print_footer(students)
class AddComunidadIdToProvincia < ActiveRecord::Migration[5.0] def change add_column :provincia, :comunidad_id, :integer end end
class CommitFetcher def self.fetch_and_save events = Github.new(basic_auth: TokenMaster.get_token).activity.events.public(per_page: 40).map{ |e| [e.id, e.created_at, e.actor.login] } events.each do |event| event_id = event[0] Commit.create(event_id: event_id, commit_time: event[1], author: event[2]) end end def self.delete_old # Leave a few (with offset) so available work doesn't fall to 0 Commit.where(id: Commit.where(resolving_location: false, resolved: false).offset(20).pluck(:id)).delete_all Commit.where(resolved: true, author_location: nil).delete_all end def self.resolve_locations commits = Commit.where(resolving_location: false, resolved: false).order("created_at desc").take(6) commits.each do |commit| commit.update(resolving_location: true) ResolveLocationJob.perform_later(commit.event_id) end end def self.cleanup Commit.delete_all end end
module UserImageHelper DEFAULT_IMAGE_URL = "guest_image.png" def user_image(user) image_or_default(user.avatar_url, DEFAULT_IMAGE_URL, "profile-image") end def user_thumbnail(user) image_or_default(user.avatar_url, DEFAULT_IMAGE_URL, "thumbnail-image") end private def image_or_default(url, default, class_string) image_tag (url.presence || default), class: class_string end end
require 'spec_helper' describe TweetBatch do subject(:batch) { TweetBatch.new } it "should have the correct constant list url" do TweetBatch::LIST_URL.should eq 'https://twitter.com/cspan/members-of-congress' end context "initialization" do before do @tweet_id = 123456789 @new_batch = TweetBatch.new(@tweet_id) end it "should allow for setting the last id" do @new_batch.last_id.should be @tweet_id end end end
class Libuv < Formula homepage "https://github.com/libuv/libuv" url "https://github.com/libuv/libuv/archive/v1.4.2.tar.gz" sha1 "85882c7e0b6ce77c30240a895c62d158e04b361e" head "https://github.com/libuv/libuv.git", :branch => "v1.x" bottle do cellar :any sha1 "b2698a14753dfe1adc790472ad88a271b9aaf435" => :yosemite sha1 "2aeb30d3fadf2ab172feeb4151a096104fb6267c" => :mavericks sha1 "6027a89608cdf0c5e99b088ef360b654e8f1ce20" => :mountain_lion end option "without-docs", "Don't build and install documentation" option :universal depends_on "pkg-config" => :build depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build depends_on :python => :build if MacOS.version <= :snow_leopard && build.with?("docs") resource "sphinx" do url "https://pypi.python.org/packages/source/S/Sphinx/Sphinx-1.2.3.tar.gz" sha1 "3a11f130c63b057532ca37fe49c8967d0cbae1d5" end resource "docutils" do url "https://pypi.python.org/packages/source/d/docutils/docutils-0.12.tar.gz" sha1 "002450621b33c5690060345b0aac25bc2426d675" end resource "pygments" do url "https://pypi.python.org/packages/source/P/Pygments/Pygments-2.0.2.tar.gz" sha1 "fe2c8178a039b6820a7a86b2132a2626df99c7f8" end resource "jinja2" do url "https://pypi.python.org/packages/source/J/Jinja2/Jinja2-2.7.3.tar.gz" sha1 "25ab3881f0c1adfcf79053b58de829c5ae65d3ac" end resource "markupsafe" do url "https://pypi.python.org/packages/source/M/MarkupSafe/MarkupSafe-0.23.tar.gz" sha1 "cd5c22acf6dd69046d6cb6a3920d84ea66bdf62a" end def install ENV.universal_binary if build.universal? if build.with? "docs" ENV.prepend_create_path "PYTHONPATH", buildpath+"sphinx/lib/python2.7/site-packages" resources.each do |r| r.stage do system "python", *Language::Python.setup_install_args(buildpath/"sphinx") end end ENV.prepend_path "PATH", (buildpath/"sphinx/bin") # This isn't yet handled by the make install process sadly. cd "docs" do system "make", "man" system "make", "singlehtml" man1.install "build/man/libuv.1" doc.install Dir["build/singlehtml/*"] end end system "./autogen.sh" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.c").write <<-EOS.undent #include <uv.h> int main() { uv_loop_t* loop = malloc(sizeof *loop); uv_loop_init(loop); uv_loop_close(loop); free(loop); return 0; } EOS system ENV.cc, "test.c", "-luv", "-o", "test" system "./test" end end
# Studies Controller class StudiesController < PlatformController require 'will_paginate/array' before_action :authenticate_researcher, only: [:new, :create] before_action :authenticate_admin, only: [:feature] def index @section = params[:section] @section ||= 'featured_studies' @section_title = page_titles[@section] @page = params[:page] @page ||= 1 if @section == 'featured_studies' @studies = Study.where(timeslots_finalised: true, paid: true) .order(featured: :desc) .paginate(page: @page, per_page: Study.per_page) elsif @section == 'tags' && params[:tag] @studies = Study.where('? = ANY (tags)', params[:tag]) .paginate(page: @page, per_page: Study.per_page) elsif @section == 'all_studies' @studies = Study.where(timeslots_finalised: true, paid: true) .sort_by { |study| current_user.eligible?(study) ? 0 : 1 } .paginate(page: @page, per_page: Study.per_page) end if @studies @final_page = @studies.total_pages == @page end @categories = Study.tags return if Study.section_is_valid? @section head(404) end def new @new_study = Study.new end def create @new_study = Study.new(new_study_attributes) @new_study.researcher = current_user @new_study.reward_per_participant = params[:study][:reward_per_participant] if @new_study.reward_per_participant == 0 @new_study.paid = true end if @new_study.save @new_study.add_requirements(params[:study][:requirements_studies]) redirect_to @new_study else # flash[:error] = @new_study.errors.first render :new end end def update @study = current_user.studies.find(params[:id]) if @study.update(edit_study_params) flash[:success] = 'Your PDF or link has been uploaded' redirect_to study_path(params[:id]) else flash[:error] = 'Please try uploading your PDF again' redirect_to study_path(params[:id]) end end def show @study = Study.find(params[:id]) @new_participation = Participation.new @current_user = current_user @new_rating = Rating.new if @study.researcher == current_user && !@study.timeslots_finalised return redirect_to new_study_timeslot_path(@study) end if @study.researcher == current_user @new_non_user_participant = NonUserParticipant.new @filterrific_participants = initialize_filterrific( @study.participations, params[:filterrific], persistencce_id: 'shared_key', default_filter_params: {}, available_filters: [:sorted_by, :search_query] ) || return @participants_to_accept = @filterrific_participants.find.page(params[:page]) # @filterrific_timeslots = initialize_filterrific( # @study.timeslots, # params[:filterrific], # persistencce_id: 'shared_key', # default_filter_params: {}, # available_filters: [:sorted_by_from] # ) || return # # @timeslots_view = @filterrific_timeslots.find.page(params[:page]) respond_to do |format| format.html format.js end end return unless current_user.is_a? Participant @participation = @study.participations.find_by_participant_id(current_user.id) if @participation && !@participation.timeslot && @participation.accepted.nil? redirect_to edit_participation_path(@participation) end prefilled_requirements = [] @study.requirements_studies.each do |requirement_study| current_user.participations.each do |participation| participation.participation_requirements.map { |pr| if pr.requirement == requirement_study.requirement prefilled_requirements << pr end } end end @reqs = {} Requirement.all.each do |requirement| r = prefilled_requirements.select { |pr| pr.requirement == requirement } req = r.sort_by(&:created_at).last @reqs[req.requirement_id] = req if req end end def search @filterrific = initialize_filterrific( Study, params[:filterrific], persistence_id: 'shared_key', available_filters: [:search_query] ) || return @studies_search_results = @filterrific.find.page(params[:page]) @query = params[:filterrific][:search_query] respond_to do |format| format.js format.html end end def stats @study = Study.find_by(id: params[:id]) return unless (current_user.is_a?(Researcher)) return if current_user.studies.where(id: params[:id]).empty? @study = current_user.studies.find(params[:id]) respond_to do |format| format.json { render json: @study.stats.to_json } end end def feature @study = Study.find(params[:id]) @study.update(featured: params[:featured]) redirect_to @study end protected def new_study_attributes params.require(:study).permit(:title, :background_photo, :aim, :number_of_participants, :location, :duration, :min_age, :max_age, gender: [], tags: []) end def edit_study_params params.require(:study).permit(:pdf_attachment, :study_web_link) end def page_titles { 'featured_studies' => 'Featured Studies', 'all_studies' => 'All Studies', 'tags' => 'Categories' } end end
class Movie attr_accessor :id, :name, :studio, :reviews def ==(other) return false unless other return false if other.id == -1 return false if @id == -1 @id == other.id end end class MovieMapping < Humble::DatabaseMapping def run(map) map.table :movies map.type Movie map.primary_key(:id, default: -1) map.column :name map.belongs_to :studio_id, Studio map.has_many :reviews, Review end end
class Artist def initialize(name) @name = name @albums = [] end def name @name end def assign(album) @albums << album end def album_names name_strings = [] @albums.each do |a| name_strings << a.name end name_strings.join(", ") end end
class Character < ActiveRecord::Base validates_presence_of :name, :game_id, :user_id belongs_to :user belongs_to :game belongs_to :player has_many :traits has_many :game_traits, through: :traits before_create :starting_points def starting_points self.available_points = self.game.starting_points end def spent spent = 0 self.traits.each do |trait| spent += trait.points_spent end spent end end
require "test_helper" require "search_scoring" class SearchScoringTest < ActiveSupport::TestCase test "#name prioritizes exact matches" do query = "donald" good_match = "Donald" bad_match = "Donald Vladimir" assert_operator SearchScore.name(good_match, query), :<, SearchScore.name(bad_match, query) end test "#name prioritizes first names" do query = "sassy" good_match = "Sassy Beaver" bad_match = "Beaver Be Sassy" assert_operator SearchScore.name(good_match, query), :<, SearchScore.name(bad_match, query) end test "#name prioritizes middle/last names" do query = "smith" good_match = "John Smith" bad_match = "Smithsonian" assert_operator SearchScore.name(good_match, query), :<, SearchScore.name(bad_match, query) end test "#name prioritizes partial matches" do query = "uix" good_match = "Don Quixote" bad_match = "Captain Kirk" assert_operator SearchScore.name(good_match, query), :<, SearchScore.name(bad_match, query) end test "#name ranks bad searches equally" do query = "potato" bad_match1 = "Alphonse Elric" bad_match2 = "Courage The Cowardly Dog" assert_equal SearchScore.name(bad_match1, query), SearchScore.name(bad_match2, query) end end
require_relative 'repository' module Peel module Modelable def initialize(**args) args.each do |attribute, value| if self.class.columns.include?(attribute) instance_variable_set("@#{attribute.to_s}", value) else raise ArgumentError, "Unknown keyword: #{attribute}" end end end def self.included(base) base.extend(ClassMethods) end module ClassMethods def peel_off(table) @name = table.to_s @repository = Repository.new create_accessors end def create_accessors columns.each do |column| define_method("#{column}") { instance_variable_get("@#{column}")} define_method("#{column}=") { |value| instance_variable_set("@#{column}", value)} end end def find(id) result = @repository.execute( "SELECT * FROM #{@name} WHERE id = ? LIMIT 1", id ) if result.empty? {} else result_hash = columns.zip(result.first).to_h new(result_hash) end end def columns @repository.execute("PRAGMA table_info(#{@name})") .map { |col| col[1].to_sym } end end end end
# Object that acts like a routeable ActiveRecord model class Leaf def initialize(attributes) @attributes = attributes end def to_param @attributes[:id] end def self.model_name self end def self.singular_route_key "leaf" end end
class AddTallnessToPlant < ActiveRecord::Migration[5.1] def change add_column :plants, :tallness, :integer end end
class RegistrationsController < Devise::RegistrationsController skip_before_filter :require_no_authentication, :only => [:new, :create, :setup_account] before_filter :go_to_dashboard_if_signed_in, :except => [:deactive_account, :reactive_account, :update, :new, :create, :setup_account, :create_cashier] before_filter :go_to_login_page_unless_signed_in, :only => [:deactive_account, :reactive_account] # GET /services def index @plans = BraintreeRails::Plan.all resource = build_resource({}) respond_with resource end # GET /service/:id def service begin app_service = AppService.find_or_create_by_name(params[:id]) session[:app_service_id] = app_service.id return redirect_to new_user_registration_url rescue return redirect_to index_user_registration_path end end # GET /register def new if session[:app_service_id].nil? return redirect_to index_user_registration_path end if params[:fromstep2] == 'true' || session[:new_user_id] self.resource = User.find(session[:new_user_id]) @fromstep2 = params[:fromstep2] else resource = build_resource({}) resource.app_service_id = session[:app_service_id] resource.restaurants.build.country = 'United States' resource.billing_country = 'United States' resource.billing_country_code = 'US' end return respond_with(resource) end def create_cashier resource = User.new resource.employer_id = params["user"]["employer_id"] resource.first_name = params["user"]["first_name"] resource.last_name = params["user"]["last_name"] resource.username = params["user"]["username"] resource.zip = params["user"]["zip"] resource.email = params["user"]["email"] resource.restaurant_type = "restaurant" resource.password = params["user"]["password"] resource.password_confirmation = params["user"]["password_confirmation"] resource.role = CASHIER_ROLE if resource.save flash[:notice] = 'You have created a new cashier!' else flash[:error] = resource.errors.full_messages end redirect_to :back end # POST / def create if session[:app_service_id].nil? return redirect_to index_user_registration_path end resource = build_resource if resource.agree == '1' if (params[:fromstep2] == "true" || session[:new_user_id]) resource = User.find(session[:new_user_id]) session[:temp_pwd] = params[:user][:password] if resource.update_attributes(params[:user]) redirect_to user_steps_path else render :new end else if resource.save session[:new_user_id] = resource.id session[:temp_pwd] = params[:user][:password] redirect_to user_steps_path else render :new end end else clean_security_fields resource set_flash_message :alert, :agree_message return render :new end end ## # resource.skip_zip_validation = params[:user][:skip_zip_validation].to_i # if resource.agree == '1' # if resource.restaurants.length == 0 # return render :new # else # if !session["move_location_id"].blank? # location = Location.find(session["move_location_id"]) # resource.password = params["user"]["password"] # resource.password_confirmation = params["user"]["password_confirmation"] # else # location = resource.restaurants[0] # resource.password = "123456" # end # # Hack default value to pass validation # resource.role = OWNER_ROLE # if resource.autofill == '1' # resource.billing_address = params[:user][:billing_address] = location.address # resource.billing_city = params[:user][:billing_city] = location.city # resource.billing_state = params[:user][:billing_state] = location.state # resource.billing_zip = params[:user][:billing_zip] = location.zip # resource.billing_country = params[:user][:billing_country] = location.country # resource.billing_country_code = params[:user][:billing_country_code] = params[:restaurant_country_code] # end # flash[:alert] = nil # # TODO: need validation and checking restaurant errors # if resource.valid? # begin # @plan = AppService.find_plan(session[:app_service_id]) # params[:user][:has_byte] = true if @plan.id == BYTE_PLANS[:byte] # rescue Exception => e # @plan = nil # end # begin # @setup_fee = BraintreeRails::AddOn.find(ADD_ON[:setup_fee]) # rescue Exception => e # @setup_fee = nil # end # session[:user_params] = params[:user].to_json # render 'confirmation' # else # clean_security_fields resource # return render :new # end # end # else # clean_security_fields resource # set_flash_message :alert, :agree_message # return render :new # end # end # PUT /resource # We need to use a copy of the resource because we don't want to change # the current user in place. def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email) resource_params[:email] = resource_params[:email_confirmation] = current_user.email resource_params[:username] = current_user.username resource_params[:skip_zip_validation] = 1 resource_params[:skip_username_validation] = 1 resource_params[:skip_first_name_validation] = 1 resource_params[:skip_last_name_validation] = 1 # Assign data to pass validation resource_params[:credit_card_type] = VISA resource_params[:credit_card_number] = '4111111111111111' resource_params[:credit_card_holder_name] = 'test' resource_params[:credit_card_expiration_date] = '12/12' resource_params[:credit_card_cvv] = '123' resource_params[:billing_address] = 'Address' resource_params[:billing_zip] = '12345' if resource.update_with_password(resource_params) if is_navigational_format? flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ? :update_needs_confirmation : :updated set_flash_message :notice, flash_key else set_flash_message :notice, 'Your password was changed successfully.' end if resource.sign_in_count == 1 # sign_out current_user sign_in resource_name, resource, :bypass => true respond_with resource, :location => restaurants_path else sign_out current_user respond_with resource, :location => after_sign_out_path_for(resource) end # sign_in resource_name, resource, :bypass => true # respond_with resource, :location => restaurants_path else clean_up_passwords resource respond_with resource end end # POST /register/setup def setup_account if session[:user_params].nil? return redirect_to root_path end user_params = ActiveSupport::JSON.decode(session[:user_params]) resource = build_resource({}) resource.username = user_params['username'] resource.first_name = user_params['first_name'] resource.last_name = user_params['last_name'] resource.phone = user_params['phone'] resource.email = resource.email_confirmation = user_params['email'] resource.password_bak = (!session["move_location_id"].blank? ? user_params["password"] : resource.generate_password(8)) resource.app_service_id = user_params['app_service_id'] resource.credit_card_type = user_params['credit_card_type'] resource.credit_card_number = user_params['credit_card_number'] resource.credit_card_holder_name = user_params['credit_card_holder_name'] resource.credit_card_expiration_date = user_params['credit_card_expiration_date'] resource.credit_card_cvv = user_params['credit_card_cvv'] resource.billing_address = user_params['billing_address'] resource.billing_country = user_params['billing_country'] resource.billing_country_code = user_params['billing_country_code'] resource.billing_state = user_params['billing_state'] resource.billing_city = user_params['billing_city'] resource.billing_zip = user_params['billing_zip'] resource.has_byte = user_params['has_byte'] resource.restaurants[0] = Location.new if !session["move_location_id"].blank? resource.password = user_params["password"] resource.password_confirmation = user_params["password_confirmation"] end resource.restaurants[0].name = user_params['restaurants_attributes']['0']['name'] resource.restaurants[0].chain_name = user_params['restaurants_attributes']['0']['chain_name'] resource.restaurants[0].address = user_params['restaurants_attributes']['0']['address'] resource.restaurants[0].country = user_params['restaurants_attributes']['0']['country'] resource.restaurants[0].state = user_params['restaurants_attributes']['0']['state'] resource.restaurants[0].city = user_params['restaurants_attributes']['0']['city'] resource.restaurants[0].zip = user_params['restaurants_attributes']['0']['zip'] resource.restaurants[0].primary_cuisine = user_params['restaurants_attributes']['0']['primary_cuisine'] resource.restaurants[0].secondary_cuisine = user_params['restaurants_attributes']['0']['secondary_cuisine'] resource.active_braintree = true resource.skip_zip_validation = 1 customer_info = { :first_name => resource.first_name, :last_name => resource.last_name, :email => resource.email, :phone => resource.phone } credit_card_info = { :number => resource.credit_card_number, :cardholder_name => resource.credit_card_holder_name, :cvv => resource.credit_card_cvv, :expiration_date => resource.credit_card_expiration_date, :billing_address => { :street_address => resource.billing_address, :locality => resource.billing_city, :country_code_alpha2 => resource.billing_country_code, :region => resource.billing_state, :postal_code => resource.billing_zip } } session[:user_params] = nil @braintree_errors = false @customer = BraintreeRails::Customer.new(customer_info) if @customer.save resource.customer_id = @customer.id @credit_card = @customer.credit_cards.build(credit_card_info) unless @credit_card.save @braintree_errors = true BraintreeRails::Customer.delete(@customer.id) clean_security_fields resource return render :new end else @braintree_errors = true clean_security_fields resource return render :new end session[:app_service_id] = nil resource.role = OWNER_ROLE if resource.save if resource.active_for_authentication? set_flash_message :notice, :setuped if is_navigational_format? # sign_up(resource_name, resource) return redirect_to new_user_session_path # respond_with resource, :location => restaurants_path else expire_session_data_after_sign_in! respond_to do |format| format.html format.js end end else set_flash_message :alert, :expired return redirect_to root_path end end # DELETE /deactive-account def deactive_account unless current_user.subscription_id.nil? result = Braintree::Subscription.cancel(current_user.subscription_id) if result current_user.update_attribute(:active_braintree, false) sign_out current_user end end end def reactive_account unless current_user.active_braintree plan = AppService.find_plan(current_user.app_service_id) customer = BraintreeRails::Customer.find(current_user.customer_id) credit_card = customer.credit_cards[0] subscription = plan.subscriptions.build( :payment_method_token => credit_card.token ) if subscription.save current_user.subscription_id = subscription.id current_user.active_braintree = true current_user.save(:validate, false) end end end private def go_to_dashboard_if_signed_in if user_signed_in? redirect_to restaurants_path end end def go_to_login_page_unless_signed_in unless user_signed_in? redirect_to new_user_session_path end end def clean_security_fields(resource) resource.credit_card_number = resource.credit_card_holder_name = resource.credit_card_expiration_date = resource.credit_card_cvv = nil clean_up_passwords resource end end
class AuthenticationController < ApplicationController skip_before_action :authenticate_request def login command = AuthenticateUser.call(params[:email], params[:password]) if command.successful? render( json: { success: true, code: 200, message: "Login successfully", data: { token: command.result } } ) else render(json: {success: false, code: 401, message: "Unauthorized", error: command.errors }, status: :unauthorized) end end end
require 'pry' class Pokemon attr_accessor :name, :id, :type, :db def initialize(id:, name:, type:, db:) @id = id @name = name @type = type @db = db end def self.save(pname, ptype, db) query = "INSERT INTO pokemon (name, type) VALUES ('#{pname}', '#{ptype}');" # binding.pry db.execute(query) end def self.find(num, db) query = "SELECT * FROM pokemon WHERE id = #{num};" pokemon_arr = db.execute(query).first Pokemon.new(id: pokemon_arr[0], name: pokemon_arr[1], type: pokemon_arr[2], db: db) end end
class CalculateAmortizationSchedule def initialize(loan_detail) @loan_detail = loan_detail @interest = ((@loan_detail.interest * 0.01 )/ 12) * @loan_detail.loan_amount @monthly_payment = calculate_monthly_payment(@loan_detail.loan_amount, @loan_detail.term) @principal_amount = @monthly_payment - @interest @start_balance = @loan_detail.loan_amount @end_balance = @start_balance - @principal_amount @amortization_schedule = [] end # Check the type of loan and call appropriate function def call if(@loan_detail.type_of_loan == "Regular loan") amortization_schedule_regular_loan else amortization_schedule_interest_only_duration end end # Calculate monthly payment def calculate_monthly_payment(loan_amount, term) annual_interest = (@loan_detail.interest * 0.01 )/ 12 (( loan_amount * annual_interest ) * (( annual_interest + 1 )**term)) / ((( annual_interest + 1 )**term ) - 1 ) end private # Calculate the schedule for interest only duration def amortization_schedule_interest_only_duration build_initial_amortization_schedule_interest_only_duration build_pending_amortization_schedule @amortization_schedule end # Calculate the schedule for regular loan def amortization_schedule_regular_loan date = next_date(@loan_detail.request_date) build_amortization_schedule(date, @start_balance, @end_balance, @interest, @principal_amount, @monthly_payment) build_pending_amortization_schedule @amortization_schedule end #add rows to amortization_schedule def build_amortization_schedule(date, start_balance, end_balance, interest, principal, monthly_payment) @amortization_schedule.push(date: date, start_balance: start_balance, end_balance: end_balance, interest: interest, principal: principal, monthly_payment: monthly_payment) end # Calculate the schedule for interest only duration first 3 months def build_initial_amortization_schedule_interest_only_duration 3.times do if @amortization_schedule.blank? date = next_date(@loan_detail.request_date) else date = next_date(@amortization_schedule.last[:date]) end build_amortization_schedule(date, @start_balance, @start_balance, @interest, 0, @interest) end end # Calculate the schedule for the rest of the term def build_pending_amortization_schedule if(@loan_detail.type_of_loan == "Regular loan") term_left = @loan_detail.term - 1 else term_left = @loan_detail.term - 3 @monthly_payment = calculate_monthly_payment(@amortization_schedule.last[:end_balance], @loan_detail.term - 3) end term_left.times do start_balance = @amortization_schedule.last[:end_balance] interest = start_balance * ((@loan_detail.interest * 0.01 )/ 12) principal = @monthly_payment - interest end_balance = start_balance - principal date = next_date(@amortization_schedule.last[:date]) build_amortization_schedule(date, start_balance, end_balance, interest, principal, @monthly_payment) end end # Get the first of the next month def next_date(date) date.next_month.at_beginning_of_month end end
class AddAntecedentesFieldsToCandidates < ActiveRecord::Migration[5.2] def change add_column :candidates, :dm2, :json add_column :candidates, :hta, :json add_column :candidates, :ecv, :json add_column :candidates, :iam, :json add_column :candidates, :irc, :json add_column :candidates, :evc, :json add_column :candidates, :cancer, :json add_column :candidates, :hipercolesterolemia, :json add_column :candidates, :ar, :boolean, default: false add_column :candidates, :lupus, :boolean, default: false add_column :candidates, :espondilitis, :boolean, default: false add_column :candidates, :miopatia, :boolean, default: false add_column :candidates, :other_illness, :boolean, default: false add_column :candidates, :str_illness_other, :string end end
module ActiveSesame::TransactionBuilder def self.object_to_triples(object) base_class = object.class.base_uri_location.gsub(/<|>/,"") + object.class.rdf_class full_transaction = self.build_triple(object.instance, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", base_class) object.class.simple_attributes.keys.inject(full_transaction) do |transaction,attribute| transaction += self.build_triple(object.instance, attribute, object.send(Support.uri_to_sym(attribute))) end end def self.build_triples(list_of_triples, trans_type='add') xml_for_transation = list_of_triples.inject("<transaction>") do |xml, triple| xml += "<#{trans_type}>" + type_cast(triple[:subject]) + type_cast(triple[:predicate]) + type_cast(triple[:object]) + "</#{trans_type}>" xml end xml_for_transation += "</transaction>" end def self.type_cast(uri_or_literal) if uri_or_literal =~ /http:\/\// "<uri>#{uri_or_literal}</uri>" else "<literal datatype=\"#{ActiveSesame::RDFConstants.class_to_literal[uri_or_literal.class]}\">#{uri_or_literal}</literal>" end end end
require '3scale/backend/validators/base' require '3scale/backend/validators/oauth_setting' require '3scale/backend/validators/key' require '3scale/backend/validators/oauth_key' require '3scale/backend/validators/limits' require '3scale/backend/validators/redirect_uri' require '3scale/backend/validators/referrer' require '3scale/backend/validators/state' module ThreeScale module Backend module Validators COMMON_VALIDATORS = [Validators::Referrer, Validators::State, Validators::Limits].freeze VALIDATORS = ([Validators::Key] + COMMON_VALIDATORS).freeze OAUTH_VALIDATORS = ([Validators::OauthSetting, Validators::OauthKey, Validators::RedirectURI] + COMMON_VALIDATORS).freeze end end end
RSpec.configuration.before(:suite) do # override zip_dir method to write zip file to tmp dir class Opendata::App class << self alias_method :zip_dir_orig, :zip_dir @@tmp_dir = Pathname(::Dir.mktmpdir) def zip_dir @@tmp_dir end end end end RSpec.configuration.after(:suite) do FileUtils.rm_rf(Opendata::App.zip_dir) end
require 'spec_helper_acceptance' describe 'ksplice class' do context 'default parameters' do # Using puppet_apply as a helper it 'should work idempotently with no errors' do pp = <<-EOS class { 'ksplice': } EOS # Run it twice and test for idempotency apply_manifest(pp, :catch_failures => true) apply_manifest(pp, :catch_changes => true) end describe "ksplice::repo" do case fact('operatingsystem') when 'CentOS', 'RedHat', 'Fedora' describe yumrepo('ksplice') do it { is_expected.to exist } it { is_expected.to be_enabled } end end end describe "ksplice::install" do describe package('uptrack') do it { is_expected.to be_installed } end end describe "ksplice::config" do describe file('/etc/uptrack/uptrack.conf') do it { is_expected.to exist } it { is_expected.to be_mode(640) } it { is_expected.to be_owned_by('root') } it { is_expected.to be_grouped_into('root') } it { is_expected.to contain('accesskey = INSERT_ACCESS_KEY') } it { is_expected.to contain('https_proxy = None') } it { is_expected.to contain('install_on_reboot = yes') } it { is_expected.to contain('upgrade_on_reboot = yes') } it { is_expected.to contain('autoinstall = yes') } end end describe "ksplice::cron" do # describe cron('ksplice') do # it { is_expected.to have_entry('PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin: uptrack-upgrade --cron' ).with_user('root')} # end describe file('/etc/cron.d/uptrack') do it { is_expected.to_not exist } end end if ! ENV['KSPLICE_LICENSE'].nil? context 'with a ksplice license' do # Using puppet_apply as a helper it 'should work idempotently with no errors' do pp = <<-EOS class { 'ksplice': config_accesskey=>#{ENV['KSPLICE_LICENSE']}} EOS # Run it twice and test for idempotency apply_manifest(pp, :catch_failures => true) apply_manifest(pp, :catch_changes => true) end it 'should upgrade the kernel' do shell('/usr/sbin/uptrack-upgrade -y --all') shell(%q{test "$(uname -a)" != "$(uptrack-uname -a)"}, :acceptable_exit_codes => 0) end end end end end
class Group < ApplicationRecord validates :name, presence: true has_many :members has_many :users, through: :members has_many :messages def memberlist str = "Member: " users.each do |user| str += "#{user.name} " end return str end end
class MoveAreaIdsToArea < ActiveRecord::Migration # Area has been removed so we have to define it here class Area < ActiveRecord::Base end class User < BaseUser belongs_to :area end def change # map some descriptions to what one-app has mapping = { 'South East Asia' => 'SouthEast Asia', 'Eastern Europe and Russia' => 'Eastern Europe/Russia', 'West Africa' => 'Nigeria and West Africa', 'North America' => 'North America and Oceania', 'North America - Canada' => 'North America and Oceania', 'North America - US' => 'North America and Oceania', 'North America - US Lake Hart' => 'North America and Oceania', 'PACT' => 'Persian, Armenian, Central Asian, and Turkic Worlds', 'Latin America and Caribbean' => 'Latin America', } User.joins(:area).each do |user| user.update_column(:area, mapping[user.area.name] || user.area.name) end end end
class Article < ActiveRecord::Base belongs_to :user has_many :comments validates :title, length: { minimum: 5, maximum: 20, too_short: "Please lengthen title", too_long: "Please shorten title" } validates :body, length: { minimum: 50, maximum: 5000, too_short: "Please write a little bit more (at least 50 characters)", too_long: "Please keep article below 5000 characters" } extend FriendlyId friendly_id :title, use: :slugged end
module MessageStore module Postgres class Settings < ::Settings def self.instance @instance ||= build end def self.data_source Defaults.data_source end def self.names [ :dbname, :host, :hostaddr, :port, :user, :password, :connect_timeout, :options, :sslmode, :krbsrvname, :gsslib, :service, :keepalives, :keepalives_idle, :keepalives_interval, :keepalives_count, :tcp_user_timeout ] end class Defaults def self.data_source ENV['MESSAGE_STORE_SETTINGS_PATH'] || 'settings/message_store_postgres.json' end end end end end
json.array!(@piece22s) do |piece22| json.extract! piece22, :id, :name, :user_id, :pnameform_id json.url piece22_url(piece22, format: :json) end
Pod::Spec.new do |s| s.name = "LogicService" s.version = "0.0.1" s.summary = "LogicService: logic service" s.description = <<-DESC 工具库:通过pod管理,控制耦合度 DESC s.homepage = "https://github.com/zhu410289616" # s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" s.license = "MIT" # s.license = { :type => "MIT", :file => "FILE_LICENSE" } s.author = { "zhu410289616" => "zhu410289616@163.com" } # s.platform = :ios s.platform = :osx, "10.11" s.source = { :git => "https://github.com/zhu410289616", :tag => s.version.to_s } s.default_subspec = "LogicDAO" s.subspec "LogicDAO" do |cs| cs.dependency "PLFoundation" cs.source_files = "DAO/*.{h,m}" cs.requires_arc = true end end
require "socket" require "logger" # This class represents the ProjectRazor configuration. It is stored persistently in # './conf/razor_server.conf' and editing by the user module ProjectRazor module Config class Server include(ProjectRazor::Utility) # (Symbol) representing the database plugin mode to use defaults to (:mongo) attr_accessor :image_svc_host attr_accessor :persist_mode attr_accessor :persist_host attr_accessor :persist_port attr_accessor :persist_timeout attr_accessor :admin_port attr_accessor :api_port attr_accessor :image_svc_port attr_accessor :mk_tce_mirror_port attr_accessor :mk_checkin_interval attr_accessor :mk_checkin_skew attr_accessor :mk_uri attr_accessor :mk_fact_excl_pattern attr_accessor :mk_register_path # : /project_razor/api/node/register attr_accessor :mk_checkin_path # checkin: /project_razor/api/node/checkin # mk_log_level should be 'Logger::FATAL', 'Logger::ERROR', 'Logger::WARN', # 'Logger::INFO', or 'Logger::DEBUG' (default is 'Logger::ERROR') attr_accessor :mk_log_level attr_accessor :mk_tce_mirror_uri attr_accessor :mk_tce_install_list_uri attr_accessor :mk_kmod_install_list_uri attr_accessor :image_svc_path attr_accessor :register_timeout attr_accessor :force_mk_uuid attr_accessor :default_ipmi_power_state attr_accessor :default_ipmi_username attr_accessor :default_ipmi_password attr_accessor :daemon_min_cycle_time attr_accessor :node_expire_timeout attr_accessor :rz_mk_boot_debug_level attr_reader :noun # init def initialize use_defaults @noun = "config" end # Set defaults def use_defaults @image_svc_host = get_an_ip @persist_mode = :mongo @persist_host = "127.0.0.1" @persist_port = 27017 @persist_timeout = 10 @admin_port = 8025 @api_port = 8026 @image_svc_port = 8027 @mk_tce_mirror_port = 2157 @mk_checkin_interval = 60 @mk_checkin_skew = 5 @mk_uri = "http://#{get_an_ip}:#{@api_port}" @mk_register_path = "/razor/api/node/register" @mk_checkin_path = "/razor/api/node/checkin" fact_excl_pattern_array = ["(^facter.*$)", "(^id$)", "(^kernel.*$)", "(^memoryfree$)", "(^operating.*$)", "(^osfamily$)", "(^path$)", "(^ps$)", "(^ruby.*$)", "(^selinux$)", "(^ssh.*$)", "(^swap.*$)", "(^timezone$)", "(^uniqueid$)", "(^uptime.*$)","(.*json_str$)"] @mk_fact_excl_pattern = fact_excl_pattern_array.join("|") @mk_log_level = "Logger::ERROR" @mk_tce_mirror_uri = "http://localhost:#{@mk_tce_mirror_port}/tinycorelinux" @mk_tce_install_list_uri = @mk_tce_mirror_uri + "/tce-install-list" @mk_kmod_install_list_uri = @mk_tce_mirror_uri + "/kmod-install-list" @image_svc_path = $img_svc_path @register_timeout = 120 @force_mk_uuid = "" @default_ipmi_power_state = 'off' @default_ipmi_username = 'ipmi_user' @default_ipmi_password = 'ipmi_password' @daemon_min_cycle_time = 30 # this is the default value for the amount of time (in seconds) that # is allowed to pass before a node is removed from the system. If the # node has not checked in for this long, it'll be removed @node_expire_timeout = 300 # used to set the Microkernel boot debug level; valid values are # either the empty string (the default), "debug", or "quiet" @rz_mk_boot_debug_level = "" end def get_client_config_hash config_hash = self.to_hash client_config_hash = {} config_hash.each_pair do |k,v| if k.start_with?("@mk_") client_config_hash[k.sub("@","")] = v end end client_config_hash end # uses the UDPSocket class to determine the list of IP addresses that are # valid for this server (used in the "get_an_ip" method, below, to pick an IP # address to use when constructing the Razor configuration file) def local_ip # Base on answer from http://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '4.2.2.1', 1 # as this is UDP, no connection will actually be made s.addr.select {|ip| ip =~ /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/}.uniq end ensure Socket.do_not_reverse_lookup = orig end # This method is used to guess at an appropriate value to use as an IP address # for the Razor server when constructing the Razor configuration file. It returns # a single IP address from the set of IP addresses that are detected by the "local_ip" # method (above). If no IP addresses are returned by the "local_ip" method, then # this method returns a default value of 127.0.0.1 (a localhost IP address) instead. def get_an_ip str_address = local_ip.first # if no address found, return a localhost IP address as a default value return '127.0.0.1' unless str_address # if we're using a version of Ruby other than v1.8.x, force encoding to be UTF-8 # (to avoid an issue with how these values are saved in the configuration # file as YAML that occurs after Ruby 1.8.x) return str_address.force_encoding("UTF-8") unless /^1\.8\.\d+/.match(RUBY_VERSION) # if we're using Ruby v1.8.x, just return the string str_address end end end end
require 'travis/github_sync/config' describe Travis::GithubSync::Config do before { ENV['ENV'] = 'test' } it 'has an env on instances' do expect(subject.env).to eql('test') end it 'has an env on the class' do expect(described_class.env).to eql('test') end end
require "rails_helper" describe "Merge Call API", :graphql do describe "mergeCall" do let(:query) do <<-GRAPHQL mutation($input: MergeCallInput!) { mergeCall(input: $input) { participants { sid } } } GRAPHQL end it "moves participants from one call into another" do stub_const("TwilioAdapter", spy(update_call: true)) user = create(:user) from_call = create(:incoming_call, :in_progress, user: user) participant = create(:participant, call: from_call) to_call = create(:incoming_call, :in_progress, :with_participant, user: user) result = execute query, as: user, variables: { input: { fromCallId: from_call.id, toCallId: to_call.id, }, } participants_result = result[:data][:mergeCall][:participants] expect(participants_result).to include(sid: participant.sid) expect(to_call.participants.count).to eq(2) expect(to_call.participants).to include( an_object_having_attributes(sid: participant.sid, call_id: to_call.id) ) end end end
FactoryGirl.define do factory :property do name Faker::Name.first_name address1 Faker::Address.street_address city Faker::Address.city zip Faker::Address.zip_code state Faker::Address.state after(:build){|p| p.property_type = FactoryGirl.create(:multi_family)} after(:build){|p| p.user = FactoryGirl.create(:user)} end end