text
stringlengths
10
2.61M
Write a method that returns the number of Friday the 13ths in the year given by an argument. You may assume that the year is greater than 1752 (when the United Kingdom adopted the modern Gregorian Calendar) and that it will remain in use for the foreseeable future. Examples: friday_13th(2015) == 3 friday_13th(1986) == 1 friday_13th(2019) == 2 Question: Write a method that returns the number of Friday the 13ths in the year with a given year. Input vs Output: Input: integer Output: integer Explicit vs Implicit Rules: Explicit: 1) Friday the 13th means it's a friday on the 13th calendar day of the month Implicit: N/A Data structures: 1) date formatting Algorithm: friday_13th method 1) create a new date using Date.new(year,1,13) #year month day and set to 'thirteenth' 2) initialize variable 'result' with integer value 0 3) invoke times method on integer 12 4) within do..end block, result += 1 if thirteenth is a friday using friday? method 5) skip a month using next_month 6) return 'result' require 'date' def friday_13th(year) result = 0 thirteenth = Date.new(year, 1, 13) 12.times do result += 1 if thirteenth.friday? thirteenth = thirteenth.next_month end result end # point is to create the 13th on the first month of the given year using Date function # once we have the date, we need to do two things: determine if that date is a friday, and skip to the next month for the following iteration # create a counter that counts how many friday the 13ths are in that given year # return the counter on last line of code
require 'logger' module Cosell def initialize *args initialize_cosell! super end # # # ANNOUNCEMENTS QUEUE # # # Place all announcments in a queue, and make announcements in a background thread. # # Arguments: # :logger => a logger. Where to log exceptions and warnings. # This argument is mandatory -- it is too hard to debug exceptions in announcement # handler code without a logger. If you _really_ want your code to fail silently, # you will have to create a logger on /dev/null. # :sleep_time => how long to sleep (in seconds) after making a batch of announchements # optional arg, default: 0.01 # :announcements_per_cycle => how many announcements to make before sleeping for sleep_time # optional arg, default: 25 # # WARNING: If you do not pass in a logger, announcement code will fail silently (the queue # is in a background thread). # # Note: at the moment, this method may only be called once, and cannot be undone. There is # no way to interrupt the thread. def queue_announcements!(opts = {}) self.initialize_cosell_if_needed # The logger in mandatory if opts[:logger] self.queue_logger = opts[:logger] else raise "Cosell error: You have to provide a logger, otherwise failures in announcement handler code are to hard to debug" end # kill off the last queue first if self.announcements_thread kill_queue! sleep 0.01 queue_announcements! opts end self.should_queue_announcements = true @__announcements_queue ||= Queue.new how_many_per_cycle = opts[:announcements_per_cycle] || 25 cycle_duration = opts[:sleep_time] || 0.01 count = 0 self.announcements_thread = Thread.new do loop do if queue_killed? self.kill_announcement_queue = false self.announcements_thread = nil log "Announcement queue killed with #{self.announcements_queue.size} announcements still queued", :info break else begin self.announce_now! self.announcements_queue.pop count += 1 if (count%how_many_per_cycle).eql?(0) log "Announcement queue finished batch of #{how_many_per_cycle}, sleeping for #{cycle_duration} sec", :debug count = 0 sleep cycle_duration end rescue Exception => x log "Exception: #{x}, trace: \n\t#{x.backtrace.join("\n\t")}", :error end end end end end # # # SUBSCRIBE/MAKE ANNOUNCEMENTS # # # Pass in an anouncement class (or array of announcement classes), along with a block defining the # action to be taken when an announcment of one of the specified classes is announced by this announcer. # (see Cossell::Announcer for full explanation) def subscribe *announce_classes, &block self.initialize_cosell_if_needed Array(announce_classes).each do |announce_class| raise "Can only subscribe to classes. Not a class: #{announce_class}" unless announce_class.is_a?(Class) self.subscriptions[announce_class] ||= [] self.subscriptions[announce_class] << lambda(&block) end end alias_method :when_announcing, :subscribe # Stop announcing for a given announcement class (or array of classes) def unsubscribe *announce_classes Array(announce_classes).each do |announce_class| self.subscriptions.delete announce_class end end # If queue_announcements? true, puts announcement in a Queue. # Otherwise, calls announce_now! # Queued announcements are announced in a background thread in batches # (see the #initialize method doc for details). def announce announcement if self.queue_announcements? self.announcements_queue << announcement else self.announce_now! announcement end end # # First, an announcement is made by calling 'as_announcement' on an_announcement_or_announcement_factory, # and subscribers to the announcement's class are then notified # # subscribers to this announcer will be filtered to those that match to the announcement's class, # and those subscriptions will be 'fired'. Subscribers should use the 'subscribe' method (also # called 'when_announcing') to configure actions to take when a given announcement is made. # # Typically, an announcement is passed in for an_announcement_factory, in # which case as_announcement does nothing but return the announcement. But any class can override # as_announcement to adapt into an anouncement as they see fit. # # (see Cossell::Announcer for full explanation) # def announce_now! an_announcement_or_announcement_factory announcement = an_announcement_or_announcement_factory.as_announcement self.subscriptions.each do |subscription_type, subscriptions_for_type | if announcement.is_a?(subscription_type) subscriptions_for_type.each{|subscription| subscription.call(announcement) } end end return announcement end # # # DEBUG # # # # Log a message every time this announcer makes an announcement # # Options: # :on => Which class of announcements to spy on. Default is Object (ie. all announcements) # :logger => The log to log to. Default is a logger on STDOUT # :level => The log level to log with. Default is :info # :preface_with => A message to prepend to all log messages. Default is "Announcement Spy: " def spy!(opts = {}) on = opts[:on] || Object logger = opts[:logger] || Logger.new(STDOUT) level = opts[:level] || :info preface = opts[:preface_with] || "Announcement Spy: " self.subscribe(on){|ann| logger.send(level, "#{preface} #{ann.as_announcement_trace}")} end # lazy initialization of cosell. # Optional -- calling this will get rid of any subsequent warnings about uninitialized ivs # In most cases not necessary, and should never have an effect except to get rid of some warnings. def initialize_cosell_if_needed self.initialize_cosell! if @__subscriptions.nil? end # Will blow away any queue, and reset all state. # Should not be necessary to call this, but left public for testing. def initialize_cosell! # Using pseudo-scoped var names. # Unfortunately cant lazily init these w/out ruby warnings going berzerk in verbose mode, # So explicitly declaring them here. @__queue_announcements ||= false @__announcements_queue ||= nil @__kill_announcement_queue ||= false @__announcements_thread ||= nil @__subscriptions ||= {} @__queue_logger ||= {} end # Kill the announcments queue. # This is called automatically if you call queue_announcements!, before starting the next # announcments thread, so it's optional. A way of stopping announcments. def kill_queue! @__kill_announcement_queue = true end # return whether annoucements are queued or sent out immediately when the #announce method is called. def queue_announcements? return @__queue_announcements.eql?(true) end def subscriptions= x; @__subscriptions = x; end def subscriptions; @__subscriptions ||= []; end protected #:stopdoc: def log(msg, level = :info) self.queue_logger.send(level, msg) if self.queue_logger end # return whether the queue was killed by kill_queue! def queue_killed? @__kill_announcement_queue.eql?(true) end def queue_logger; @__queue_logger; end def queue_logger= x; @__queue_logger = x; end def announcements_queue; @__announcements_queue; end def announcements_queue= x; @__announcements_queue = x; end def announcements_thread; @__announcements_thread; end def announcements_thread= x; @__announcements_thread = x; end def kill_announcement_queue= x; @__kill_announcement_queue = x; end def should_queue_announcements= x; @__queue_announcements = x; end #:startdoc: public end
json.array!(@apps) do |app| json.extract! app, :id, :name, :description, :host_group, :metadata, :repo, :hooks, :created_at, :updated_at json.url app_url(app, format: :json) end
component "component2" do |pkg, settings, platform| pkg.ref "1.2.3" pkg.url "git://git.example.com/my-app/component2.git" pkg.mirror "https://git.example.com/my-app/component2.git" pkg.mirror "git@git.example.com:my-app/component2.git" pkg.build_requires "component1" pkg.install do ["#{settings[:bindir]}/component1 install --configdir=#{settings[:sysconfdir]} --mandir=#{settings[:mandir]}"] end end
require "spec_helper" class DummyPatternMatchable include Patme::PatternMatching def foo(arg1='test') ["foo('test')", arg1] end def foo(arg1=1) ["foo(1)", arg1] end def foo(arg1={a: 1}) ['foo({a: 1})', arg1] end def foo(arg1=true) ['foo(true)', arg1] end def foo 'foo()' end def foo(any) ["foo(any)", any] end def bar(arg1='bar', arg2='test') ["bar('bar', 'test')", [arg1, arg2]] end def bar(arg1='first', _arg2='opt') ["bar('first', optional)", [arg1, _arg2]] end def bar(any, arg2="test") ["bar(any, 'test')", [any, arg2]] end def bar(any, _arg2="opt") ["bar(any, optional)", [any, _arg2]] end def baz(arg1='test') ["baz('test')", arg1] end # don't work yet # def foo(bar: "test") # "foo(bar: 'test')" # end end RSpec.describe DummyPatternMatchable do subject{ described_class.new } it "correctly runs foo('test')" do expect( subject.foo('test') ).to eq ["foo('test')", 'test'] end it "correctly runs foo(1)" do expect( subject.foo(1) ).to eq ["foo(1)", 1] end it "correctly runs foo({a: 1})" do expect( subject.foo({a: 1}) ).to eq ["foo({a: 1})", {a: 1}] end it "correctly runs foo(true)" do expect( subject.foo(true) ).to eq ["foo(true)", true] end it "correctly runs foo(any)" do expect( subject.foo(:any) ).to eq ["foo(any)", :any] expect( subject.foo('any') ).to eq ["foo(any)", 'any'] end it "correctly runs foo()" do expect( subject.foo ).to eq "foo()" end it "correctly runs bar('bar', 'test')" do expect( subject.bar('bar', 'test') ).to eq ["bar('bar', 'test')", ['bar', 'test']] end it "correctly runs bar('first', optional)" do expect( subject.bar('first') ).to eq ["bar('first', optional)", ['first', 'opt']] expect( subject.bar('first', 'test') ).to eq ["bar('first', optional)", ['first', 'test']] end it "correctly runs bar(any, 'test')" do expect( subject.bar(:any, 'test') ).to eq ["bar(any, 'test')", [:any, 'test']] expect( subject.bar('any', 'test') ).to eq ["bar(any, 'test')", ['any', 'test']] end it "correctly runs bar(any, optional)" do expect( subject.bar(:any) ).to eq ["bar(any, optional)", [:any, 'opt']] expect( subject.bar('any') ).to eq ["bar(any, optional)", ['any', 'opt']] expect( subject.bar(:any, 'some') ).to eq ["bar(any, optional)", [:any, 'some']] expect( subject.bar('any', 'some') ).to eq ["bar(any, optional)", ['any', 'some']] end it "correctly runs baz('test')" do expect( subject.baz('test') ).to eq ["baz('test')", 'test'] end it "raises NoMethodError when baz is ran with unknown arguments" do expect{ subject.baz(1) }.to raise_error(NoMethodError) end end
require_relative '../../test_helper' describe Vuf::Batch do subject { Vuf::Batch.new(50) do |objQ| objQ.size.must_equal(50) unless objQ.empty? end } it "must respond to push" do subject.must_respond_to(:push) 1000.times do |i| subject.push(i) end end it "must respond to flush" do subject.must_respond_to(:flush) 1000.times do |i| subject.push(i) end subject.flush end end
class EasyUserAllocationObserver < ActiveRecord::Observer observe :issue, :time_entry def after_update(entity) allocate_entity(entity) end def after_create(entity) allocate_entity(entity) end def allocate_entity(entity) issue = entity if entity.is_a?(Issue) issue = entity.issue if entity.is_a?(TimeEntry) if issue && !issue.project.easy_is_easy_template? custom_allocations = issue.easy_user_allocations.where(:custom => true).all.reduce({}) {|h, alloc| h[alloc.date] = alloc.hours; h} EasyUserAllocation.allocate_issue!(issue, nil, custom_allocations) end end end
class BrokerTradeGood < ActiveRecord::Base belongs_to :broker belongs_to :trade_good end
require 'cards' require 'player' module Game def self.setup @turn = 0 end def self.turn(application, card, slot) raise unless %w{left right}.include? application @turn += 1 @proponent.send(application, card, slot) end def self.proponent @proponent ||= Player.new('0') end def self.opponent @opponent ||= Player.new('1') end def self.prompt puts "turn #{@turn / 2 + 1} of #{proponent.name}" app, slot, card = nil app = prompt_app if app == 'left' card = prompt_card slot = prompt_slot else slot = prompt_slot card = prompt_card end return app, card, slot end def self.prompt_app app = nil loop do print "apply 1/2? " app = gets.gsub(/[^0-9]*/, '').to_i if [1, 2].include?(app) app = %w{left right}[app - 1] break else puts "wrong (1/2)" end end app end def self.prompt_slot slot = nil loop do print "slot? " slot = gets.gsub(/[^0-9]*/, '').to_i if slot >= 0 && slot <= 255 break else puts "wrong (0..255)" end end slot end def self.prompt_card card = nil loop do print "card? " card = gets.gsub(/[^a-z]*/, '').upcase if Cards.playable?(card) card = Cards.const_get(card) break else puts "wrong (#{Cards.playable.join ' '})" end end card end def self.status puts puts "----------- players status ------------" puts " % 17s | % 17s " % [proponent.name, opponent.name] pros = [] proponent.slots.each_with_index do |v, i| pros << [v, i] if v != Slot.new end opps = [] opponent.slots.each_with_index do |v, i| opps << [v, i] if v != Slot.new end if pros.size > opps.size opps << nil until opps.size == pros.size else pros << nil until opps.size == pros.size end pros.size.times do |i| print_slot(pros[i]) print " | " print_slot(opps[i]) puts end puts puts end def self.print_slot(slot) if slot slot, index = *slot print "% 3i:% 14s" % [index, slot.to_s] else print " " * 18 end end def self.end? @turn >= 200_000 end def self.switch @proponent, @opponent = @opponent, @proponent end end
require 'dotenv/load' # Load DSL and set up stages require "capistrano/setup" # Include default deployment tasks require "capistrano/deploy" # Load the SCM plugin appropriate to your project: require "capistrano/scm/git" install_plugin Capistrano::SCM::Git SSHKit::Backend::Netssh.configure do |ssh| ssh.connection_timeout = 30 ssh.ssh_options = { forward_agent: true, auth_methods: %w(publickey password) } end if ENV['MATTERMOST_URI'] require 'net/http' require 'net/https' require 'capistrano/deploy_hooks' require 'capistrano/deploy_hooks/messengers/mattermost' set :deploy_hooks, { messenger: Capistrano::DeployHooks::Messengers::Mattermost, webhook_uri: ENV['MATTERMOST_URI'], channels: ENV['MATTERMOST_CHANNEL'], icon_url: ENV['MATTERMOST_ICON'], } end if ENV['BASTION'] require 'net/ssh/proxy/command' bastion_host = ENV['BASTION_HOST'] bastion_user = ENV['BASTION_USER'] bastion_port = ENV['BASTION_PORT'] ssh_command = "ssh -p #{bastion_port} #{bastion_user}@#{bastion_host} -W %h:%p" set :ssh_options, proxy: Net::SSH::Proxy::Command.new(ssh_command) end # Load custom tasks from `lib/capistrano/tasks` if you have any defined Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
class Triangle # write code here def initialize(lenght_1, lenght_2,length_3) @length_3 = length_3 @lenght_2 = lenght_2 @lenght_1 = lenght_1 end def kind () if (@lenght_1 + @lenght_2 <= @length_3)||(@length_3 + @lenght_2 <= @lenght_1)||(@lenght_1 + @length_3 <= @lenght_2) raise TriangleError elsif (@lenght_2 <= 0) ||(@lenght_1 <= 0) || (@length_3 <= 0) raise TriangleError else if (@lenght_1== @lenght_2) && (@lenght_2==@length_3) :equilateral elsif (@length_3 == @lenght_2)||(@lenght_2 == @lenght_1)||(@lenght_1==@length_3) :isosceles elsif (@length_3 !=@lenght_2)&&(@lenght_2 !=@lenght_1)&&(@lenght_1!=@length_3) :scalene end end end end class TriangleError < StandardError end
Twitter utiliza la versión uno de OAuth. OAuth es difícil y en particular la versión uno por lo que te ayudaremos en el proceso. http://oauth.net/core/1.0a/ Diagrama de como funciona OAuth https://codealab.files.wordpress.com/2015/06/oauth.png Diagrama de como funciona OAuth http://www.locomotion.mx/challenges/104/?course=1&week=9&day=3 Twitter OAuth Documentation https://dev.twitter.com/oauth OAuth Explained http://www.railstips.org/blog/archives/2009/03/29/oauth-explained-and-what-it-is-good-for/ https://github.com/tsamb/twitter_oauth/blob/master/config/environment.rb
class Course < ApplicationRecord has_many :course_users has_many :users, through: :course_users has_many :teams has_many :prototypes has_many :posts #Esta asosiacion es solo si la asosiacion es directa. En este caso es indirecta pues cuenta con un modelo intermedio #Por tal razon se utiliza has_many :course_users y has_many :users, through: :course_users #has_and_belongs_to_many :course_users #new attr_accessor :studentsAmount, :ceo, :ceo_id, :is_member, :logo_file, :access_requested # Agregar cualquier otro al metodo as_json de abajo # Sobreescribir la funcion as_json def as_json options=nil options ||= {} options[:methods] = ((options[:methods] || []) + [:studentsAmount, :ceo, :ceo_id, :is_member, :logo_file, :access_requested]) super options end end
class CreateImmunizations < ActiveRecord::Migration def self.up create_table :immunizations do |t| t.integer :doctor_visit_id t.integer :note_id t.timestamps end end def self.down drop_table :immunizations end end
# == Schema Information # Schema version: 20100705154452 # # Table name: ratings # # id :integer not null, primary key # value :float # entity_id :integer # user_id :integer # opinion_id :integer # created_at :datetime # updated_at :datetime # class Rating < ActiveRecord::Base belongs_to :user belongs_to :entity belongs_to :opinion validates_presence_of :value def self.get_value(user, entity, op) r = self.find_by_user_id_and_entity_id_and_opinion_id user, entity, op r ? r.value : nil end def self.entity_count(entity) Rating.count :select => "DISTINCT user_id", :conditions => "entity_id = #{entity.id}" end def self.user_count(user) Rating.count :select => "DISTINCT entity_id", :conditions => "user_id = #{user.id}" end end
class ApplicationController < ActionController::Base helper_method :current_admin before_action :login_required, only: [:new, :edit, :update, :destroy] private def current_admin @current_admin ||= Admin.find_by(id: session[:admin_id]) if session[:admin_id] end def login_required redirect_to login_path unless current_admin end end
#declares variable cars and assigns the integer 100 to it cars = 100 #declares variable and assigns a float number space_in_car = 4.0 #declares variable and assigns number drivers = 30 #declares variable and assigns number passengers = 90 #declares variable and assigns one variable minus another variable cars_not_driven = cars - drivers #declares a variable and sets it equal to a previous variable cars_driven = drivers #declares a variable and sets it equal to one variable times another carpool_capacity = cars_driven * space_in_car #declares a variable and sets it equal to one variable divided by another average_passengers_per_car = passengers / cars_driven # all of these are strings with variables interpolated puts "There are #{cars} cars available." puts "There are only #{drivers} drivers available." puts "There will be #{cars_not_driven} empty cars today." puts "We can transport #{carpool_capacity} people today." puts "We have #{passengers} to carpool today." puts "We need to put about #{average_passengers_per_car} in each car." # study drill question: explain "undefined local variable or method #'carpool_capacity' for main:Object (NameError) #This error means that the author likely forgot to declare the #variable and attempted to interpolate a non-existant variable #next step to fixing this would be to go to line 14 to see what's up #Study drill Q: #The code will work with the float or an integer. The float is #technically more accurate but since we don't quarter humans any more #it is probably not needed
require "spec_helper" module CSS describe Rule do let(:rule) { Rule.new('#id', 'background-color:#333;color:#FFF;z-index:99') } it "should return a property by name" do rule.color.should == '#FFF' end it "should return a property reference with a symbol" do rule[:color].should == '#FFF' end it "should allow referencing a property as a method call" do rule.color.should == '#FFF' end it "should allow referencing a hyphenated property by camel-case method name" do rule.backgroundColor.should == '#333' end it "should allow referencing a hyphenated property by underscored method name" do rule.background_color.should == '#333' end it "should merge properties" do rule.background << Property.create('background-image', 'url(image.png)') rule.background.image.should == 'url(image.png)' end it "should respond to #to_s" do rule.to_s.should == "background:#333;color:#FFF;z-index:99" end it "should respond to #to_style" do rule.to_style.should == "#id{background:#333;color:#FFF;z-index:99}" end it "should reveal that it has a background property" do rule.should have_property(:background) end it "should reveal that it has a background-color property" do rule.should have_property(:background_color) end it "should not have a background-image property" do rule.should_not have_property(:background_image) end it "should not have a font property" do rule.should_not have_property(:font) end it "should not have a border-color property" do rule.should_not have_property(:border_color) end it "should reveal that is has one of font or background properties" do rule.should have_one_property(:font, :background) end it "should be able to retrieve a long-hand rule via []" do rule['background-color'].should == '#333' end it "should be able to retrieve a property with a hyphen" do rule['z-index'].should == '99' end it "should be able to set a property value with []=" do rule['z-index'] = '100' rule['z-index'].should == '100' end it "should be able to set a property by method call" do rule.z_index = '100' rule.z_index.should == '100' end it "should be able to set a short-hand property" do rule['background'] = 'url(image2.png)' rule.background.image.should == 'url(image2.png)' end it "should be able to set a short-hand property via method call" do rule.background = 'url(image2.png)' rule.background.image.should == 'url(image2.png)' end it "should be able to set a long-hand property" do rule['background-image'] = 'url(image2.png)' rule.background.image.should be_a(Property) rule.background.image.should == 'url(image2.png)' end it "should be able to set a long-hand property via method call" do rule.background.image = 'url(image2.png)' rule.background.image.should be_a(Property) rule.background.image.should == 'url(image2.png)' end end end
require 'spec_helper' module EZAPIClient RSpec.describe PasswordTokenizable do let(:klass) do Class.new(BaseRequest) do attribute :reference_no, String include PasswordTokenizable end end let(:tokenizable) do klass.new( prv_path: "/prv_path", eks_path: "/eks_path", username: "username", password: "password", reference_no: "reference_no", ) end it "adds #password_token to the object" do expect(GenPasswordToken).to receive(:call).with( prv_path: "/prv_path", eks_path: "/eks_path", username: "username", password: "password", reference_no: "reference_no", ).and_return("password_token") expect(tokenizable.password_token).to eq "password_token" end end end
# == Schema Information # # Table name: answers # # id :integer not null, primary key # name :string(255) # correct :boolean default("f") # question_id :integer # created_at :datetime # updated_at :datetime # require 'rails_helper' RSpec.describe Answer, :type => :model do describe 'validation' do it { is_expected.to validate_presence_of :name } it { is_expected.to validate_presence_of :question } describe '#only_one_correct_if_single' do before do FactoryGirl.create :course FactoryGirl.create :lesson_category FactoryGirl.create :exam FactoryGirl.create :question_category FactoryGirl.create :question end context "there are no correct answers" do before do FactoryGirl.create :answer end it "is valid" do answer = FactoryGirl.build :answer, name: "Nie", correct: true expect(answer).to be_valid end end context "there is a correct answer" do before do FactoryGirl.create :answer, correct: true end it "is invalid" do answer = FactoryGirl.build :answer, name: "Nie", correct: true expect(answer).to be_invalid end end context "updating" do before do FactoryGirl.create :answer, correct: true end it "is valid" do expect(Answer.first.update_attributes({ name: "Takowo" })) .to eq true end end end end end
# frozen_string_literal: true class CompanySerializer < ActiveModel::Serializer attributes :name has_many :users has_many :invitations def users object.users.by_name.active end end
# frozen_string_literal: true module TeacherSetsEsHelper # Make teacherset object from elastic search document def teacher_sets_from_elastic_search_doc(es_doc) arr = [] if es_doc[:hits].present? es_doc[:hits].each do |ts| next if ts["_source"]['mappings'].present? teacher_set = TeacherSet.new teacher_set.title = ts["_source"]['title'] teacher_set.description = ts["_source"]['description'] teacher_set.contents = ts["_source"]['contents'] teacher_set.grade_begin = ts["_source"]['grade_begin'] teacher_set.grade_end = ts["_source"]['grade_end'] teacher_set.language = ts["_source"]['language'] teacher_set.id = ts["_source"]['id'] teacher_set.details_url = ts["_source"]['details_url'] teacher_set.availability = ts["_source"]['availability'] teacher_set.total_copies = ts["_source"]['total_copies'] teacher_set.call_number = ts["_source"]['call_number'] teacher_set.language = ts["_source"]['language'] teacher_set.physical_description = ts["_source"]['physical_description'] teacher_set.primary_language = ts["_source"]['primary_language'] teacher_set.created_at = ts["_source"]['created_at'] teacher_set.updated_at = ts["_source"]['updated_at'] teacher_set.available_copies = ts["_source"]['available_copies'] teacher_set.bnumber = ts["_source"]['bnumber'] teacher_set.set_type = ts["_source"]['set_type'] arr << teacher_set end end arr end end
class HelpersController < ApplicationController def method_missing(method) render :template => "/helpers/#{method}", :layout => false end end
# module DebuggerOverTCP # class Server # class ClientRegistry # def register(client) # semaphore.synchronize do # store[client.id] = client # end # end # def unregister(client) # semaphore.synchronize do # store.delete(client.id) # end # end # def broadcast(event) # semaphore.synchronize do # store.each do |client_id, client| # next if event.origin_client_id == client_id # client.send_message(event.message) # end # end # end # private # def store # @store ||= {} # end # def semaphore # @semaphore ||= Mutex.new # end # end # end # end
class CreateInstallationsUsers < ActiveRecord::Migration def change create_table :installations_users, id: false do |t| t.integer :installation_id t.integer :user_id end end end
class Order < ApplicationRecord belongs_to :user has_many :item_in_orders has_many :items, through: :item_in_orders has_one :payment [:user_id, :address_id, :delivery_courier].each do |field| validates field, presence: true end end
module ApiResponseCache module Actions class ResponseCache def initialize(cache_path, expires_in) @cache_path = cache_path @expires_in = expires_in || 1.hour end def present? cached_response.present? end def body cached_response['body'] end def status cached_response['status'] end def headers cached_response['headers'] end def cached_response @cached_response ||= Rails.cache.read(@cache_path) end def write_cache(response) cache_object = { body: response.body, status: response.status, headers: response.headers }.as_json Rails.cache.write(@cache_path, cache_object, expires_in: @expires_in) end end end end
class LaughTracksApp < Sinatra::Base get '/' do redirect '/comedians' end get '/comedians' do @comedians = params[:age] ? Comedian.find_by_age(params[:age]) : Comedian.all @comedians = @comedians.order(params[:sort].to_sym) if params[:sort] @average_age, @average_length = get_averages_for(@comedians) @uniq_hometowns = Comedian.uniq_hometowns(@comedians) erb :index end get '/comedians/new' do erb :new end get '/comedians/:id' do @comedian = Comedian.where('id = ?', params[:id])[0] erb :show, :layout => :show_layout end post '/comedians' do Comedian.create( name: params[:comedian][:name], age: params[:comedian][:age], city: params[:comedian][:hometown] ) redirect '/comedians' end def get_averages_for(comedians) return Comedian.average_age(@comedians), Special.average_length(specials_for(@comedians)) end def specials_for(comedians) Special.where("comedian_id IN (?)", @comedians.pluck(:id)) end end
module Gaman module Clip # Internal: Parses a FIBS You Kibitz CLIP message. This CLIP message # confirms that FIBS has processed your request to send a kibitz. Message # is in the format: # # message # # message: kibitz sent by the user. class YouKibitz def initialize(text) @message = text end def update(state) state.message_sent(:kibitz, @message) end end end end
class AddColumnArtistIdToSongs < ActiveRecord::Migration[5.0] #My code def change add_column :songs, :artist_id, :integer end #Solution Code # def change # change_table :songs do |t| # t.integer :artist_id # end # end end
class ChangeNonTrueValuesToFalseInOrganization < ActiveRecord::Migration def change Organization.where(active: nil).update_all(active: false) end end
class Node include Comparable attr_accessor :data, :lefty, :righty def initialize(data, lefty=nil, righty=nil) @data = data @lefty = lefty @righty = righty end def <=> other @data <=> other.data end end
desc 'Run phantom against Jasmine for all specs, once' task :phantom do `which phantomjs` raise "Could not find phantomjs on your path" unless $?.success? port = ENV['JASMINE_PORT'] || 8888 exec "phantomjs #{File.dirname(__FILE__)}/../../spec/run-phantom-jasmine.js #{port} #{ENV['filter']}" end
module Aucklandia module Routes ROUTE_ENDPOINT = '/gtfs/routes' def get_routes url = build_url(BASE_URL, ROUTE_ENDPOINT) response = get(url) JSON.parse(response)['response'] end def get_routes_by_short_name(short_name) url = build_url(BASE_URL, ROUTE_ENDPOINT, '/routeShortName/', short_name) response = get(url) JSON.parse(response)['response'] end def get_route_by_id(route_id) url = build_url(BASE_URL, ROUTE_ENDPOINT, '/routeId/', route_id) response = get(url) JSON.parse(response)['response'].first end end end
module Admin class CategoriesController < AdminBaseController before_action :load_category, except: %i(index create) before_action :check_destroy, only: :destroy def index @category = Category.new @categories = Category.lastest end def show @dish = @category.dishes.build @dishes = @category.dishes.lastest end def edit; end def create @category = Category.new category_params if @category.save flash[:success] = t ".message_success" else flash[:danger] = t ".message_danger" end redirect_back fallback_location: admin_categories_url end def update if @category.update_attributes category_params flash[:success] = t ".updated" else flash[:danger] = t ".not_update" end redirect_back fallback_location: admin_categories_url end def destroy if @category.destroy flash[:success] = t ".updated" else flash[:danger] = t ".not_update" end redirect_back fallback_location: admin_categories_url end private def category_params params.require(:category).permit :name, dishes_attributes: [:id, :name, :price, :description, :image, :_destroy] end def load_category @category = Category.find_by id: params[:id] return if @category flash[:danger] = t ".not_found" redirect_to admin_categories_url end def check_destroy return if @category.dishes.count == 0 flash[:danger] = t ".not_delete" redirect_to admin_categories_url end end end
require 'jekyll' require 'liquid' module Jekyll module Tags # include module class HamlInclude < IncludeTag def read_file(file, context) return super file, context unless matches_a_haml_template file file_content = read_file_with_context file, context template = split_frontmatter_and_template file_content compile_haml_to_html template end private def matches_a_haml_template(file) Jekyll::Haml::Parser.matches File.extname file end def read_file_with_context(file, context) File.read file, **file_read_opts(context) end def split_frontmatter_and_template(file_content) return $POSTMATCH if file_content =~ Document::YAML_FRONT_MATTER_REGEXP file_content end def compile_haml_to_html(template) Jekyll::Haml::Parser.compile template end end end end Liquid::Template.register_tag 'include', Jekyll::Tags::HamlInclude
class Enemy attr_accessor :location def initialize(hp,level, attack, defence,agility, gold, inventory,active_weapon,name,location,id) @hp = hp @level = level @attack = attack @defence = defence @agility = agility @gold = gold @active_weapon = active_weapon @inventory = inventory @name = name @location = location @id = id adjust_stats end def location @location end def level @level end def exp_drop @exp_drop = (15 * @level ** 1.1).floor end def hp @hp end def active_weapon @active_weapon end def alive? @hp > 0 end def attack @attack end def agility @agility end def name @name end def id @id end def defence @defence end def gold @gold end def inventory @inventory end def swing(player) @d20 = rand(1..20) if @d20 == 20 puts "#{@name} rolled #{@d20}. Its attack was CRITICAL!" player.take_damage(@attack*3) elsif @d20 == 1 # critical miss puts "#{@name} rolled #{@d20}." puts "Ooh...bad miss. #{@name} trips and falls." self.take_damage(1) elsif @d20 + @agility > player.defence + 12 puts "#{@name} rolled #{@d20} and hit." sprinkle_damage_range = [] sprinkle_damage_range = (0..@attack).to_a sprinkle_damage = sprinkle_damage_range.sample player.take_damage(@attack+sprinkle_damage) else puts "#{@name} rolled #{@d20} and missed." end end def take_damage(damage) @hp -= damage puts "#{@name} took #{damage} damage, and is on #{@hp} HP." end def adjust_stats @hp += 1 * (@level ** 1.18).floor @attack+= 1 * (@level ** 1.1).floor @defence+= 1 * (@level ** 1.1).floor @agility+= 1 * (@level ** 1.08).floor end def status puts "-------------------------------------" puts " ### STATUS ### " puts "-------------------------------------" puts "HP: #{@hp}" puts "LEVEL: #{@level}" puts "ATTACK: #{@attack}" puts "DEFENCE: #{@defence}" puts "AGILITY: #{@agility}" puts "POSITION: #{@location}" puts "--" #puts "EXP: #{@exp} / #{20 * ((@level+1) ** 2.3).floor}" if @active_weapon.nil? == false puts "ACTIVE WEAPON: #{@active_weapon.name}" puts " MODIFIED ATTACK: #{@attack + @active_weapon.attack} (#{@attack} + #{@active_weapon.attack})" else puts "No weapon equipped" end if @active_armor.nil? == false puts "ACTIVE ARMOR: #{@active_armor.name}" puts " MODIFIED DEFENCE: #{@defence + @active_armor.defence} (#{@defence} + #{@active_armor.defence})" else puts "No armor equipped" end #puts "MODIFIED AGILITY: #{@agility + @active_armor.agility + @active_weapon.agility} (#{@agility} + #{@active_weapon.agility} + #{@active_armor.agility})" puts "-------------------------------------" end end
class AddTotalToShopquikTodoList < ActiveRecord::Migration def change add_column :shopquik_todo_lists, :total_expenses, :integer, :limit => 8 end end
require_dependency "db_admin/api/base_controller" module DbAdmin class Api::DatabasesController < Api::BaseController include ActionController::MimeResponds def index databases = db_connection.databases respond_to do |format| format.json { render json: databases } format.xml { render xml: databases } end end end end
require 'rails_helper' #This has rspec file to verify the controller methods #First Spec: Checks if by clicking the FindSimilarMovies if it routes to view "Similar Movies With the director" #Second Spec: If no similar directors the route should render the default view if there are no Similar Movies or No Director describe MoviesController, :type => :request do context "When provided with movie with no director" do it " Should route back to the default \movies page" do movies_list = [{id: 1,title: "Titanic",director: ""},{id: 2,title: "Avatar",director: "James Cameroon"},{id: 3,title: "Avengers", director: "Joe Russo"}] movies_list.each do |movie| Movie.create(movie) end movie_id = Movie.find_by(title: "Titanic").id.to_s get ("/movies/"+movie_id+"/same_director") expect(response).to redirect_to('/movies') end end context "When provided with similar movies" do it "Should route to similar_movie webpage with similar movies" do movies_list = [{id: 1,title: "Titanic",director: "James Cameroon"},{id: 2,title: "Avatar",director: "James Cameroon"},{id: 3,title: "Avengers", director: "Joe Russo"}] movies_list.each do |movie| Movie.create(movie) end movie_id = Movie.find_by(title: "Titanic").id.to_s get ("/movies/"+movie_id+"/same_director") expect(response).to render_template("same_director") end end context "When Starting from homepage" do it " Should route properly based on the API calls " do movies_list = [{id: 1,title: "Titanic",director: "James Cameroon", release_date: "2004-12-12"}] movies_list.each do |movie| Movie.create(movie) end put "/movies/1", "movie": {"title": "movie_2"} expect(response).to redirect_to("/movies/1") get "/movies/1/edit" expect(response).to render_template("edit") get "/movies" expect(response).to render_template("index"); get ("/movies/"+"1"+"/same_director") expect(response).to render_template("same_director") get ("/movies/1/edit") expect(response).to render_template("edit") delete ("/movies/1") expect(response).to redirect_to("/movies") end end end
module SesBlacklistRails class Notification < ApplicationRecord # :nodoc: self.table_name = :ses_notifications enum notification_type: { bounce: 0, complaint: 1, delivery: 2, other: 9 } class << self def validate_bounce @validate_bounce ||= ->(email) { self.bounce.where(email: email).any? } end def validate_complaint @validate_complaint ||= ->(email) { self.complaint.where(email: email).any? } end end end end
class CreateCourses < ActiveRecord::Migration[5.1] def change create_table :courses do |t| t.string :name, comment: '课程名称' t.text :description, comment: '课程描述' t.integer :member_count, comment: '建议上课人数' t.integer :created_by, comment: '添加人' t.integer :is_enable, default: 1, comment: '是否启用' t.datetime :delete_at, comment: '删除时间' t.timestamps end end end
Rails.application.routes.draw do resources :days do get 'archived', on: :collection end resources :entries do put 'archive', on: :member put 'unarchive', on: :member end devise_for :users resources :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "entries#index" end
class ProjectsController < ApplicationController before_action :set_project, only: [:edit, :update, :destroy, :add, :del] # GET /projects def index @projects = Project.all end # GET /projects/1 def show @project = Project.find(params[:id]) @comments = @project.comments @comment = Comment.new end # GET /projects/new def new @project = Project.new end # GET /projects/1/edit def edit end # POST /projects def create @project = current_user.my_projects.build(project_params) respond_to do |format| if @project.save format.html { redirect_to projects_url, notice: 'Project was successfully created.' } else format.html { render :new } end end end # PATCH/PUT /projects/1 def update respond_to do |format| if @project.update(project_params) format.html { redirect_to projects_url, notice: 'Project was successfully updated.' } else format.html { render :edit } end end end # DELETE /projects/1 def destroy @project.destroy respond_to do |format| format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' } end end def add user = User.find_by_id(params[:id_k][:id]) @project.users << user redirect_to @project, notice: "User #{user.name} was successfully added." end def del user = User.find(params[:id_u]) @project.users.delete(user) redirect_to @project, notice: "User #{user.name} was deleted." end private # Use callbacks to share common setup or constraints between actions. def set_project @project = current_user.my_projects.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def project_params params.require(:project).permit(:title, :text, :city, :user_id) end end
class TrabatsController < ApplicationController before_action :set_trabat, only: [:show, :edit, :update, :destroy] # GET /trabats # GET /trabats.json def index @trabats = Trabat.all end # GET /trabats/1 # GET /trabats/1.json def show end # GET /trabats/new def new @trabat = Trabat.new end # GET /trabats/1/edit def edit end # POST /trabats # POST /trabats.json def create @trabat = Trabat.new(trabat_params) respond_to do |format| if @trabat.save format.html { redirect_to @trabat, notice: 'Trabat was successfully created.' } format.json { render :show, status: :created, location: @trabat } else format.html { render :new } format.json { render json: @trabat.errors, status: :unprocessable_entity } end end end # PATCH/PUT /trabats/1 # PATCH/PUT /trabats/1.json def update respond_to do |format| if @trabat.update(trabat_params) format.html { redirect_to @trabat, notice: 'Trabat was successfully updated.' } format.json { render :show, status: :ok, location: @trabat } else format.html { render :edit } format.json { render json: @trabat.errors, status: :unprocessable_entity } end end end # DELETE /trabats/1 # DELETE /trabats/1.json def destroy @trabat.destroy respond_to do |format| format.html { redirect_to trabats_url, notice: 'Trabat was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_trabat @trabat = Trabat.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def trabat_params params.require(:trabat).permit(:nombre, :descripcion) end end
class Api::GamesController < ApplicationController before_action :get_user before_action :get_game before_action :get_game_session before_action :verify_user_token before_action :get_wallet, only: [:deal] def create @game ||= Game.create!(user: @user, game_session: @session) if @game.shuffle_time @game_session = GameSession.create(user: @user) @game.update_attributes(game_session_id: @game_session.id) end if @game render status: 200, json: [@game] else render status: 500 end end def deal @game.deal @game.bet = params[:betAmount].to_i if params[:betAmount] @game.dealt @wallet.update_attributes(balance: (@wallet.balance -= @game.bet)) render status: 200, json: [@game] end def hit if @game.hit render status: 200, json: [@game] else render status: 500, json: errors end end def stand if @game.stand render status: 200, json: [@game] else render status: 500, json: errors end end def dealer @game.dealers_turn render status: 200, json: [@game] end private def verify_user_token @user == current_user end def get_user @user = User.find_by_authentication_token(request.authorization.split(' ')[1]) end def get_game @game = @user.unfinished_games.take end def get_game_session @session = @user.game_sessions.last || GameSession.create!(user_id: @user.id) end def get_wallet if @user @wallet = @user.wallets.take end end end
module Student class Model < Redson::Form::Model validates_presence_of 'name' end end
class CalendarsController < ApplicationController def index if params[:date] date = params[:date] @calendar = Calendar.find_by(date: date) @day = Day.where(calendars_id: @calendar.id) unless @calendar.nil? unless @day.nil? @teachers = Teacher.where(id: @day.map(&:teachers_id)) @subjects = Subject.where(id: @day.map(&:subjects_id)) end end end def show @calendar = Calendar.find_by(id: params[:id]) @teachers = Teacher.all @subjects = Subject.all end def new end def edit @calendar = Calendar.find_by(id: params[:id]) @day = Day.where(calendars_id: @calendar.id) @teachers = Teacher.all @subjects = Subject.all end def create @calendar = Calendar.new(calendars_params) if @calendar.save redirect_to @calendar else end end def update end def destroy Day.where(calendars_id: params[:id]).destroy_all Calendar.find_by(id: params[:id]).destroy redirect_to calendars_path end def ajax_for_index date = params[:date] ||= Date.today.to_s @calendar = Calendar.find_by(date: date, time_table_id: nil) @calendar = Calendar.find_by( date: date, time_table_id: Timetable.find_by(name: params[:timetable]).id ) unless params[:timetable].nil? || params[:timetable] == '' @day = Day.where(calendars_id: @calendar.id) unless @calendar.nil? unless @day.nil? @teachers = Teacher.where(id: @day.map(&:teachers_id)) @subjects = Subject.where(id: @day.map(&:subjects_id)) end respond_to do |format| format.html {redirect_to calendars_path} format.json {render :index, status: :created, location: calendars_path} format.js end params[:timetable] = nil params[:date] = nil end def ajax_for_day @calendar = Calendar.find_by(id: params[:id]) @day = Day.where(calendars_id: @calendar.id) @teachers = Teacher.all @subjects = Subject.all end private def calendars_params params.require(:calendar).permit(:date) end end
When /^I GET "([^\"]*)"$/ do |uri| @result = record_exception { Recliner.get(uri) } end When /^I GET "([^\"]*)" with:$/ do |uri, params| params = eval_hash_keys(params.rows_hash) @result = record_exception { Recliner.get(uri, params) } end When /^I PUT to "([^\"]*)"$/ do |uri| @result = record_exception { Recliner.put(uri, {}) } end When /^I PUT to "([^\"]*)" with the revision$/ do |uri| @result = record_exception { Recliner.put(uri, { '_rev' => @revision }) } end When /^I POST to "([^\"]*)"$/ do |uri| @result = record_exception { Recliner.post(uri, {}) } end When /^I POST to "([^\"]*)" with:$/ do |uri, payload| @result = record_exception { Recliner.post(uri, eval(payload)) } end When /^I DELETE "([^\"]*)" with the revision$/ do |uri| @result = record_exception { Recliner.delete("#{uri}?rev=#{@revision}") } end When /^I DELETE "([^\"]*)"$/ do |uri| @result = record_exception { Recliner.delete(uri) } end Then /^the result should have key "([^\"]*)"$/ do |key| @exception.should be_nil @result.should have_key(key) end Then /^the result should have "([^\"]*)" => "([^\"]*)"$/ do |key, value| @exception.should be_nil @result[key].to_s.should == value end Then /^the result should have "([^\"]*)" matching "([^\"]*)"$/ do |key, regexp| @exception.should be_nil @result[key].should match(regexp) end Then /^a "([^\"]*)" exception should be raised$/ do |exception_class| @exception.should_not be_nil @exception.class.to_s.should == exception_class end Then /^no exception should be raised$/ do @exception.should be_nil end
#!/usr/bin/env ruby module Day11 class HaltException < Exception end class Point attr_accessor :x, :y def initialize(x, y) @x, @y = x, y end def -(other) Point.new(@x - other.x, @y - other.y) end def +(other) Point.new(@x + other.x, @y + other.y) end def ==(other) @x == other.x && @y == other.y end alias eql? == def hash [@x, @y].hash end def to_s "(#{@x}, #{@y})" end end # the parameter to be interpreted as a position - if the parameter is 50, its value is the value stored at address 50 in memory POSITION_MODE = 0 # in immediate mode, a parameter is interpreted as a value - if the parameter is 50, its value is simply 50 IMMEDIATE_MODE = 1 # the parameter is interpreted as a position. Like position mode, parameters in relative mode can be read from or written to. RELATIVE_MODE = 2 def self.write_address_mode(mode, parameter, relative_base) if mode == POSITION_MODE return parameter elsif mode == IMMEDIATE_MODE raise "Destination parameter in immediate mode" elsif mode == RELATIVE_MODE return parameter + relative_base else raise "Unknown addressing mode" end end def self.read_address_mode(memory, mode, parameter, relative_base) if mode == POSITION_MODE return memory[parameter] elsif mode == IMMEDIATE_MODE return parameter elsif mode == RELATIVE_MODE return memory[parameter + relative_base] else raise "Unknown addressing mode" end end def self.int_code(memory, pc = 0, relative_base = 0, input) while pc < memory.size instruction = memory[pc] opcode = instruction % 100 modes = instruction.digits.drop(2) # if the 10th thousandth digit is missing # make it 0 while modes.size < 3 modes << 0 end # Opcode 1 adds together numbers read from two positions and stores the result in a third position. if opcode == 1 # Parameters that an instruction writes to will never be in immediate mode. memory[write_address_mode(modes[2], memory[pc + 3], relative_base)] = read_address_mode(memory, modes[0], memory[pc + 1], relative_base) + read_address_mode(memory, modes[1], memory[pc + 2], relative_base) pc += 4 next end # Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. if opcode == 2 # Parameters that an instruction writes to will never be in immediate mode. memory[write_address_mode(modes[2], memory[pc + 3], relative_base)] = read_address_mode(memory, modes[0], memory[pc + 1], relative_base) * read_address_mode(memory, modes[1], memory[pc + 2], relative_base) pc += 4 next end # Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. # For example, the instruction 3,50 would take an input value and store it at address 50. if opcode == 3 memory[write_address_mode(modes[0], memory[pc + 1], relative_base)] = input pc += 2 next end # Opcode 4 outputs the value of its only parameter. # For example, the instruction 4,50 would output the value at address 50. if opcode == 4 output = read_address_mode(memory, modes[0], memory[pc + 1], relative_base) pc += 2 return pc, relative_base, output #next end # Opcode 5 is jump-if-true: if the first parameter is non-zero, # it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing. if opcode == 5 if read_address_mode(memory, modes[0], memory[pc + 1], relative_base) != 0 pc = read_address_mode(memory, modes[1], memory[pc + 2], relative_base) else pc += 3 end next end # Opcode 6 is jump-if-false: if the first parameter is zero, it sets the instruction pointer # to the value from the second parameter. Otherwise, it does nothing. if opcode == 6 if read_address_mode(memory, modes[0], memory[pc + 1], relative_base) == 0 pc = read_address_mode(memory, modes[1], memory[pc + 2], relative_base) else pc += 3 end next end # Opcode 7 is less than: if the first parameter is less than the second parameter, # it stores 1 in the position given by the third parameter. Otherwise, it stores 0. if opcode == 7 if read_address_mode(memory, modes[0], memory[pc + 1], relative_base) < read_address_mode(memory, modes[1], memory[pc + 2], relative_base) memory[write_address_mode(modes[2], memory[pc + 3], relative_base)] = 1 else memory[write_address_mode(modes[2], memory[pc + 3], relative_base)] = 0 end pc += 4 next end # Opcode 8 is equals: if the first parameter is equal to the second parameter, # it stores 1 in the position given by the third parameter. Otherwise, it stores 0. if opcode == 8 if read_address_mode(memory, modes[0], memory[pc + 1], relative_base) == read_address_mode(memory, modes[1], memory[pc + 2], relative_base) memory[write_address_mode(modes[2], memory[pc + 3], relative_base)] = 1 else memory[write_address_mode(modes[2], memory[pc + 3], relative_base)] = 0 end pc += 4 next end # Opcode 9 adjusts the relative base by the value of its only parameter. # The relative base increases (or decreases, if the value is negative) by the value of the parameter. if opcode == 9 relative_base += read_address_mode(memory, modes[0], memory[pc + 1], relative_base) pc += 2 next end if opcode == 99 raise Day11::HaltException end raise "Unknown opcode: #{opcode}" end raise "should have seen opcode 99" end BLACK = 0 WHITE = 1 UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # a 0 means it should turn left 90 degress def self.turn_counter_clockwise(direction) if direction == UP return LEFT elsif direction == DOWN return RIGHT elsif direction == LEFT return DOWN elsif direction ==RIGHT return UP end end # a 1 means it should turn right 90 degress def self.turn_clockwise(direction) if direction == UP return RIGHT elsif direction == DOWN return LEFT elsif direction == LEFT return UP elsif direction ==RIGHT return DOWN else raise "Unknown direction: #{direction}" end end def self.padright!(a, n, x) a.fill(x, a.length...n) end # provide 0 if the robot is over a black panel or 1 if the robot is over a white panel. # Then, the program will output two values: # # First, it will output a value indicating the color to paint # the panel the robot is over: 0 means to paint the panel black, and 1 means to paint the panel white. # # Second, it will output a value indicating the direction the robot should turn: # 0 means it should turn left 90 degrees, and 1 means it should turn right 90 degrees. # # After the robot turns, it should always move forward exactly one panel. The robot starts facing up. # # The robot will continue running for a while like this and halt when it is finished drawing. # Do not restart the Intcode computer inside the robot during this process. # module Part1 # starting values point = Point.new(0, 0) direction = UP panels = Hash.new pc = 0 relative_base = 0 instructions = File.read("11.txt").split(",").map(&:strip).map(&:to_i) Day11.padright!(instructions, 10_000, 0) begin while true do input = panels.fetch(point, BLACK) pc, relative_base, color = Day11.int_code(instructions, pc, relative_base, input) pc, relative_base, turn = Day11.int_code(instructions, pc, relative_base, nil) if turn == 0 direction = Day11.turn_counter_clockwise(direction) elsif turn ==1 direction = Day11.turn_clockwise(direction) else raise "Unknown turn: #{turn}" end # draw the color panels[point] = color # advance the robot if direction == UP point += Point.new(0, 1) elsif direction == RIGHT point += Point.new(1, 0) elsif direction == DOWN point += Point.new(0,-1) elsif direction == LEFT point += Point.new(-1, 0) else raise "Unknown direction: #{direction}" end end rescue HaltException => e # do nothing end puts panels.keys.size end module Part2 # starting values point = Point.new(0, 0) direction = UP panels = Hash.new pc = 0 relative_base = 0 instructions = File.read("11.txt").split(",").map(&:strip).map(&:to_i) Day11.padright!(instructions, 10_000, 0) first = true begin while true do input = panels[point] if input == nil input = WHITE if first input = BLACK unless first first = false end pc, relative_base, color = Day11.int_code(instructions, pc, relative_base, input) pc, relative_base, turn = Day11.int_code(instructions, pc, relative_base, nil) if turn == 0 direction = Day11.turn_counter_clockwise(direction) elsif turn ==1 direction = Day11.turn_clockwise(direction) else raise "Unknown turn: #{turn}" end # draw the color panels[point] = color # advance the robot if direction == UP point += Point.new(0, 1) elsif direction == RIGHT point += Point.new(1, 0) elsif direction == DOWN point += Point.new(0,-1) elsif direction == LEFT point += Point.new(-1, 0) else raise "Unknown direction: #{direction}" end end rescue HaltException => e # do nothing end puts panels.keys.size max_x = panels.keys.map(&:x).max min_x = panels.keys.map(&:x).min max_y = panels.keys.map(&:y).max min_y = panels.keys.map(&:y).min max_y.downto(min_y).each do |y| (min_x..max_x).each do |x| value = panels[Point.new(x, y)] value = ' ' if value.nil? || value == 0 value = "#" if value == 1 print "#{value} " end puts end end end
# frozen_string_literal: true RSpec.describe TimeTo do let(:two_days) { 86_400 * 2 } let(:start_time) { subject - two_days } it 'has a version number' do expect(TimeTo::VERSION).not_to be nil end context 'Time' do subject { Time.new } it { is_expected.to respond_to :to } it 'returns a list of times' do expect(start_time.to(subject).count).to eq 3 end end context 'TimeWithZone', if: defined?(ActiveSupport::TimeWithZone) do before { Time.zone = 'America/New_York' } subject { Time.zone.now } it { is_expected.to respond_to :to } it 'returns a list of times' do expect(start_time.to(subject).count).to eq 3 end end end
class AddCountryToImages < ActiveRecord::Migration def change add_column :images, :country, :string end end
# Copyright © 2011-2019 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require 'rails_helper' RSpec.describe Dashboard::AssociatedUsersController do describe 'POST create' do let!(:identity) { build_stubbed(:identity) } let!(:other_user) { build_stubbed(:identity) } let!(:protocol) { findable_stub(Protocol) { build_stubbed(:protocol) } } context "User not authorized to edit Protocol" do before(:each) do authorize(identity, protocol, can_edit: false) log_in_dashboard_identity(obj: identity) post :create, params: { protocol_id: protocol.id }, xhr: true end it "should use ProtocolAuthorizer to authorize user" do expect(ProtocolAuthorizer).to have_received(:new). with(protocol, identity) end it { is_expected.to render_template "dashboard/shared/_authorization_error" } it { is_expected.to respond_with :ok } end context "User authorized to edit Protocol and params[:project_role] describes valid ProjectRole" do before(:each) do authorize(identity, protocol, can_edit: true) log_in_dashboard_identity(obj: identity) @new_project_roles_attrs = { identity_id: other_user.id.to_s } associated_user_creator = instance_double(AssociatedUserCreator, successful?: true) allow(AssociatedUserCreator).to receive(:new). and_return(associated_user_creator) post :create, params: { protocol_id: protocol.id, project_role: @new_project_roles_attrs }, xhr: true end it "should use AssociatedUserCreator to create ProjectRole" do expect(AssociatedUserCreator).to have_received(:new). with controller_params(@new_project_roles_attrs), identity end it "should not set @errors" do expect(assigns(:errors)).to be_nil end it { is_expected.to render_template "dashboard/associated_users/create" } it { is_expected.to respond_with :ok } end context "User authorized to edit Protocol and params[:project_role] describes an invalid ProjectRole" do before(:each) do authorize(identity, protocol, can_edit: true) log_in_dashboard_identity(obj: identity) @new_project_roles_attrs = { identity_id: other_user.id.to_s } new_project_role = build_stubbed(:project_role) allow(new_project_role).to receive(:errors).and_return("my errors") associated_user_creator = instance_double(AssociatedUserCreator, successful?: false, protocol_role: new_project_role) allow(AssociatedUserCreator).to receive(:new). and_return(associated_user_creator) post :create, params: { protocol_id: protocol.id, project_role: @new_project_roles_attrs }, xhr: true end it "should use AssociatedUserCreator to (attempt) to create ProjectRole" do expect(AssociatedUserCreator).to have_received(:new). with controller_params(@new_project_roles_attrs), identity end it "should set @errors from built ProjectRole's errors" do expect(assigns(:errors)).to eq("my errors") end it { is_expected.to render_template "dashboard/associated_users/create" } it { is_expected.to respond_with :ok } end context "admin user adds themself to a protocol" do before(:each) do authorize(identity, protocol, can_edit: true) log_in_dashboard_identity(obj: identity) @new_project_roles_attrs = {identity_id: identity.id} project_role = instance_double(ProjectRole, can_edit?: true, can_view?: true) associated_user_creator = instance_double(AssociatedUserCreator, successful?: true) allow(associated_user_creator).to receive(:protocol_role). and_return(project_role) allow(AssociatedUserCreator).to receive(:new). and_return(associated_user_creator) post :create, params: { protocol_id: protocol.id, project_role: @new_project_roles_attrs }, xhr: true end it 'should set @permission_to_edit' do expect(assigns(:permission_to_edit)).to eq(true) end it { is_expected.to render_template "dashboard/associated_users/create" } it { is_expected.to respond_with :ok } end end end
require 'spec_helper' describe TweetimageController do describe "GET index" do context "given a twitter handle" do before do get :index, :twitter_handle => 'bob' end it "redirects to show action" do response.should redirect_to(:action => :show, :twitter_handle => 'bob') end end end end
describe Pantograph::PluginInfo do describe 'object equality' do it "detects equal PluginInfo objects" do object_a = Pantograph::PluginInfo.new('name', 'Me', 'me@you.com', 'summary', 'details') object_b = Pantograph::PluginInfo.new('name', 'Me', 'me@you.com', 'summary', 'details') expect(object_a).to eq(object_b) end it "detects differing PluginInfo objects" do object_a = Pantograph::PluginInfo.new('name', 'Me', 'me@you.com', 'summary', 'details') object_b = Pantograph::PluginInfo.new('name2', 'Me2', 'me2@you.com', 'summary2', 'details') expect(object_a).not_to(eq(object_b)) end end describe '#gem_name' do it "is equal to the plugin name prepended with ''" do expect(Pantograph::PluginInfo.new('name', 'Me', 'me@you.com', 'summary', 'details').gem_name).to eq("#{Pantograph::PluginManager::PANTOGRAPH_PLUGIN_PREFIX}name") end end describe '#require_path' do it "is equal to the gem name with dashes becoming slashes" do expect(Pantograph::PluginInfo.new('name', 'Me', 'me@you.com', 'summary', 'details').require_path).to eq("pantograph/plugin/name") end end end
require 'active_support/concern' require 'pg_search' module Kuhsaft module Searchable extend ActiveSupport::Concern DICTIONARIES = { en: 'english', de: 'german' } def update_fulltext self.fulltext = collect_fulltext end included do unless included_modules.include?(BrickList) raise 'Kuhsaft::Searchable needs Kuhsaft::BrickList to be included' end translate :fulltext if included_modules.include?(Translatable) before_validation :update_fulltext if ActiveRecord::Base.connection.instance_values['config'][:adapter] == 'postgresql' include ::PgSearch cb = lambda do |query| { against: { locale_attr(:title) => 'A', locale_attr(:page_title) => 'A', locale_attr(:keywords) => 'B', locale_attr(:description) => 'C', locale_attr(:fulltext) => 'C' }, query: query, using: { tsearch: { dictionary: DICTIONARIES[I18n.locale] || 'simple' } } } end pg_search_scope :search_without_excerpt, cb scope :search, lambda { |query| ts_headline = sanitize_sql_array([ "ts_headline(%s, plainto_tsquery('%s')) AS excerpt", locale_attr(:fulltext), query ]) search_without_excerpt(query).select(ts_headline) } else # TODO: Tests run in this branch because dummy app uses mysql. Change it! # define empty fallback excerpt attribute attr_reader :excerpt scope :search, lambda { |query| if query.is_a? Hash where("#{query.first[0]} LIKE ?", "%#{query.first[1]}%") else stmt = '' stmt += "#{locale_attr(:keywords)} LIKE ? OR " stmt += "#{locale_attr(:title)} LIKE ? OR " stmt += "#{locale_attr(:page_title)} LIKE ? OR " stmt += "#{locale_attr(:description)} LIKE ? OR " stmt += "#{locale_attr(:fulltext)} LIKE ?" where(stmt, *(["%#{query}%"] * 5)) end } end end end end
require 'rails_helper' describe 'teams/recruit' do let(:team) { create(:team) } let!(:users) { create_list(:user, 4) } it 'shows all users' do pending "Doesn't work due to _search using 'fullpath'" assign(:team, team) assign(:users, User.paginate(page: 1)) render users.each do |user| expect(rendered).to include(user.name) end end end
require "check_responds_to/version" require "set" require "parser/current" require "socket" module CheckRespondsTo class Checker def initialize(config) @config = config @processor = ASTProcessor.new(config) end def check_interfaces(code) ast = Parser::CurrentRuby.parse(code) @processor.process(ast) @processor.result end end class Result attr_reader :errors def initialize(errors) @errors = errors end end class ASTProcessor include AST::Processor::Mixin def initialize(config) @config = config @errors = [] end def result Result.new(@errors) end def handler_missing(node) process_all(node.children.select { |maybe_node| maybe_node.is_a? AST::Node }) end def on_send(node) receiver, method_name, *args = node.children if recognize_variable?(receiver) if !method_exists?(receiver, method_name) @errors << [:no_method, node, receiver, method_name] elsif arity_mismatch?(receiver, method_name, args) @errors << [:arity_mismatch, node, receiver, method_name, args] end end end def recognize_variable?(receiver_node) return false unless receiver_node.is_a?(AST::Node) var_name = variable_name_from_receiver_node(receiver_node) var_name && @config.can_map_variable?(var_name) end def method_exists?(receiver_node, method_name) return false unless receiver_node.is_a?(AST::Node) var_name = variable_name_from_receiver_node(receiver_node) @config.variable_responds_to?(var_name, method_name) end def arity_mismatch?(receiver_node, method_name, args_nodes) return false unless receiver_node.is_a?(AST::Node) var_name = variable_name_from_receiver_node(receiver_node) !@config.variable_method_supports_arity?(var_name, method_name, args_nodes.size) end def variable_name_from_receiver_node(receiver_node) case receiver_node.type when :ivar receiver_node.children[0].to_s[1..-1] when :lvar receiver_node.children[0].to_s when :str, :send, :const # TODO: @jbodah 2019-02-21: string literal nil else raise "Unexpected receiver type: #{receiver_node.inspect}" end end end class Config def initialize(hash) @variable_to_class = hash.fetch(:variable_to_class) @method_map = hash.fetch(:method_map) end def can_map_variable?(var_name) @variable_to_class.key?(var_name) end def variable_responds_to?(var_name, method_name) klass = @variable_to_class[var_name] return false if klass.nil? klass_spec = @method_map[klass] return false if klass_spec.nil? klass_spec.include?(method_name.to_s) end def variable_method_supports_arity?(var_name, method_name, num_received) klass = @variable_to_class[var_name] return false if klass.nil? klass_spec = @method_map[klass] return false if klass_spec.nil? method_spec = klass_spec[method_name.to_s] return false if method_spec.nil? actual_arity = method_spec[:arity] Arity.supports?(arity: actual_arity, received: num_received) end end module Arity def self.supports?(arity: , received: ) return true if arity == -1 if arity < -1 received >= -1 * (arity + 1) else received == arity end end end class ServerBackedConfig def initialize(host, port) @host = host @port = port end def can_map_variable?(var_name) resp = ask(__method__, var_name) resp == ["YES"] end def variable_responds_to?(var_name, method_name) resp = ask(__method__, var_name, method_name) resp == ["YES"] end def variable_method_supports_arity?(var_name, method_name, num_received) resp = ask(__method__, var_name, method_name, num_received) resp == ["YES"] end private def ask(*args) connect do |socket| req = args.join("\t") puts "> " + req.inspect socket.sendmsg(args.join("\t")) puts "waiting for resp" resp = socket.recvmsg[0].split("\t") puts "< " + resp.inspect resp end end def connect socket = TCPSocket.new(@host, @port) yield socket ensure socket.close end end class Server CUSTOM_MAP = { "user" => "SemUser" } def initialize(port) @server = TCPServer.new(port) end def start puts "starting server" loop do puts "waiting for client" client = @server.accept puts "waiting for req" req = client.recvmsg[0].split("\t") puts "> " + req.inspect resp = handle_req(req) puts "< " + resp.inspect client.sendmsg(resp.join("\t")) client.close end end private def can_map_variable?(var_name) klass = klass_for(var_name) ["YES"] rescue NameError ["NO"] end def variable_responds_to?(var_name, method_name) klass = klass_for(var_name) klass.method_defined?(method_name) ? ["YES"] : ["NO"] rescue NameError ["NO"] end def variable_method_supports_arity?(var_name, method_name, num_received) klass = klass_for(var_name) arity = klass.instance_method(method_name).arity Arity.supports?(arity: arity, received: num_received.to_i) ? ["YES"] : ["NO"] rescue NameError ["NO"] end # NOTE: @jbodah 2019-02-21: we are assuming a Rails server here def klass_for(var_name) # 0. use hardcoded entry if it exists return CUSTOM_MAP[var_name].constantize if CUSTOM_MAP.key?(var_name) # 1. try to constantize begin return var_name.camelcase.constantize rescue NameError end models = Dir['app/models/*.rb'].map(&File.method(:basename)).map { |name| name.sub(/\.rb$/, '') } # 2. try to perform substring match candidates = models.select { |model| model.include? var_name } return candidates[0].constantize if candidates.size == 1 # 3. try to use acronym models_by_acronym = models.group_by { |model| model.split('_').map(&:first).join } if models_by_acronym[var_name] && models_by_acronym[var_name].size == 1 return models_by_acronym[var_name].constantize end raise NameError end def handle_req(req) name, *args = req send(name, *args) end end end
module Meiosis class Wallet < CKB::Wallet def initialize(api, privkey) super(api, privkey) end def get_pubkey pubkey end def get_pubkey_bin pubkey_bin end def lock=(data) @lock = data end def lock_binary CKB::Utils.bin_to_hex(CKB::Blake2b.digest(CKB::Blake2b.digest(get_pubkey_bin))) end def send_tx(tx) send_transaction_bin(tx) end def install_system_script_cell(mruby_cell_filename) data = CKB::Utils.bin_to_prefix_hex(File.read(mruby_cell_filename)) cell_hash = CKB::Utils.bin_to_prefix_hex(CKB::Blake2b.digest(data)) output = { capacity: 0, data: data, lock: lock } output[:capacity] = Meiosis::Utils.calculate_cell_min_capacity(output) p output[:capacity] i = Meiosis::Transaction.gather_inputs(output[:capacity], 0) input_capacities = i.capacities outputs = [output.merge(capacity: output[:capacity])] if input_capacities > output[:capacity] outputs << { capacity: (input_capacities - output[:capacity]), data: "0x", lock: lock } end tx = { version: 0, deps: [], inputs: i.inputs, outputs: outputs, witnesses: [] } hash = api.send_transaction(tx) { out_point: { hash: hash, index: 0 }, cell_hash: cell_hash } end end end
FactoryBot.define do factory :question do sequence(:title) { |n| "QuestionTitle#{n}" } sequence(:body) { |n| "QuestionBody#{n}" } user end factory :question_with_answers, parent: :question do transient do answers_count { 1 } answers_author { create(:user) } end after(:create) do |question, evaluator| create_list(:answer, evaluator.answers_count, question: question, user: evaluator.answers_author) end end factory :question_with_file, parent: :question do after(:build) do |question| question.files.attach( io: File.open(Rails.root.join('spec', 'fixtures', 'files', 'image1.jpg')), filename: 'image1.jpg', content_type: 'image/jpg' ) end end trait :invalid_question do title { nil } body { nil } end end
# In the easy exercises, we worked on a problem where we had to count the # number of uppercase and lowercase characters, as well as characters that were # neither of those two. Now we want to go one step further. # Write a method that takes a string, and then returns a hash that contains 3 # entries: one represents the percentage of characters in the string that are # lowercase letters, one the percentage of characters that are uppercase # letters, and one the percentage of characters that are neither. # You may assume that the string will always contain at least one character. require 'pry' def letter_percentages(str) new_hash = { lowercase: 0, uppercase: 0, neither: 0 } upper = 0.0 lower = 0.0 neither = 0.0 total = 0 str.split('').each do |char| if char == char.upcase && char.match(/[A-Z]/) upper += 1 total += 1 elsif char = char.downcase && char.match(/[a-z]/) lower += 1 total += 1 else neither += 1 total += 1 end end # binding.pry new_hash[:uppercase] = (upper / total) * 100 new_hash[:lowercase] = (lower / total) * 100 new_hash[:neither] = (neither / total) * 100 p new_hash end p letter_percentages('abCdef 123') == { lowercase: 50, uppercase: 10, neither: 40 } p letter_percentages('AbCd +Ef') == { lowercase: 37.5, uppercase: 37.5, neither: 25 } p letter_percentages('123') == { lowercase: 0, uppercase: 0, neither: 100 }
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/events', to: 'events#index' get '/events/:id', to: 'events#show', as: "event" get '/users/:id', to: 'users#show', as: "user" get '/users/:user_id/events', to: 'user_events#index' post '/users/:user_id/events', to: 'user_events#create' post '/login', to: 'sessions#create' post '/session_user', to: 'sessions#show' delete '/remove_saved_event', to: 'user_events#destroy' end
class AddBalanceToCustomer < ActiveRecord::Migration def up add_column :customers, :balance, :decimal, :precision => 10, :scale => 2, :default => 0.00 add_column :customers, :revenue, :decimal, :precision => 10, :scale => 2, :default => 0.00 Customer.reset_column_information Appointment.reset_column_information Customer.find_each do |customer| customer.appointments.actual.joins(:status).where("statuses.use_for_invoice = ?", true).where("appointments.start_time < ?", Time.zone.now.end_of_day).each do |appointment| if appointment.price.present? if !appointment.paid? customer.balance += appointment.price end customer.revenue += appointment.price end end customer.save! end end def down remove_column :customers, :balance remove_column :customers, :revenue end end
# Video example of .each # letters = ["a", "b", "c", "d", "e"] # new_letters = [] # puts "Original data:" # p letters # p new_letters # # iterate through the array with .each # letters.each do |letter| # new_letters << letter.next # end # puts "After .each call:" # p letters # p new_letters # ##################### # numbers = {1 => 'one', 2 => 'two', 3 => 'three'} # # iterate through the hash with .each # numbers.each do |digit, word| # puts "#{digit} is spelled out as #{word}" # end # Video example of .map # letters = ["a", "b", "c", "d", "e"] # puts "Original data:" # p letters # # iterate through the array with .map # letters.map! do |letter| # puts letter # letter.next # end # puts "After .map call:" # p letters # p modified_letters ################# Doing 5.3 again on my own # def greeting # # or set variables up here: # # name1 = "Steve" # # name2 = "Rose" # puts "hello there!" # yield("Steve", "Rose") # end # greeting { |name1, name2| puts "Great to see you #{name1} and #{name2}!" } # RELEASE 0: EXPLORE BLOCKS # def coffee # puts "I love coffee! This runs before the block." # yield("latte") # puts "This runs after the block." # end # coffee { |drink| puts "My favorite drink is a #{drink}"} # RELEASE 1: each, map, and map! drinks = ["coffee", "beer", "tea"] drinks_menu = { coffee: "$3", beer: "$6", tea: "$2", wine: "$8" } # .each p drinks p drinks_menu drinks.each do |drink_name| puts "#{drink_name} is delicious!" end drinks_menu.each do |drink_name, price| puts "#{drink_name} costs #{price}." end p drinks p drinks_menu # .map! drinks.map! do |drink_name| drink_name.capitalize end p drinks p drinks_menu # RELEASE 2: Use the Documentation # 1. beverages = ['Beer', 'wine', 'coffee', 'Water', 'Juice'] beverages_hash = { beer: '7', wine: '6', coffee: '2', water: '1', juice: '2' } beverages.delete_if {|drink| drink != drink.capitalize} p beverages beverages_hash.delete_if {|drink,money| money.to_i > 3} p beverages_hash #2. beverages = ['Beer', 'wine', 'coffee', 'Water', 'Juice'] beverages_hash = { beer: '7', wine: '6', coffee: '2', water: '1', juice: '2' } beverages.keep_if {|drink| drink == drink.capitalize} p beverages beverages_hash.keep_if {|drink, money| money.to_i < 3} p beverages_hash #3 beverages = ['Beer', 'wine', 'coffee', 'Water', 'Juice'] beverages_hash = { beer: '7', wine: '6', coffee: '2', water: '1', juice: '2' } new_beverages = beverages.select {|drink| drink == drink.capitalize} p new_beverages new_beverages_hash = beverages_hash.select {|drink, money| money.to_i < 3} p new_beverages_hash #4 beverages = ['Beer', 'wine', 'coffee', 'Water', 'Juice'] beverages_hash = { beer: '7', wine: '6', coffee: '2', water: '1', juice: '2' } new_beverages = beverages.drop_while {|drink| drink == drink.capitalize} p new_beverages # didn't find a similar method for hashes
class AddSupportingDocumentationTable < ActiveRecord::Migration def up remove_column :documentations, :parent_id create_table :supporting_documentations do |t| t.integer :parent_id t.integer :child_id end add_index :supporting_documentations, :child_id add_index :supporting_documentations, :parent_id add_foreign_key(:supporting_documentations, :documentations, :column => 'parent_id') add_foreign_key(:supporting_documentations, :documentations, :column => 'child_id') end def down drop_table :supporting_documentations add_column :documentations, :parent_id, :integer end end
# -*- coding: utf-8 -*- require 'mui/cairo_sub_parts_message_base' class Gdk::ReplyViewer < Gdk::SubPartsMessageBase EDGE_ABSENT_SIZE = 2 EDGE_PRESENT_SIZE = 8 register attr_reader :messages def on_click(e, message) case e.button when 1 case UserConfig[:reply_clicked_action] when :open Plugin.call(:open, message) when :smartthread Plugin.call(:open_smartthread, [message]) end end end def initialize(*args) super @edge = show_edge? ? EDGE_PRESENT_SIZE : EDGE_ABSENT_SIZE if helper.message.has_receive_message? helper.message.replyto_source_d(true).next{ |reply| @messages = [reply].freeze render_messages }.terminate('リプライ描画中にエラーが発生しました') end end def edge if show_edge? unless @edge == EDGE_PRESENT_SIZE @edge = EDGE_PRESENT_SIZE helper.reset_height end else unless @edge == EDGE_ABSENT_SIZE @edge = EDGE_ABSENT_SIZE helper.reset_height end end helper.scale(@edge) end def badge(_message) Skin[:reply].pixbuf(width: badge_radius*2, height: badge_radius*2) end def background_color(message) color = Plugin.filtering(:subparts_replyviewer_background_color, message, nil).last if color.is_a? Array and 3 == color.size color.map{ |c| c.to_f / 65536 } else [1.0]*3 end end def main_text_color(message) UserConfig[:reply_text_color].map{ |c| c.to_f / 65536 } end def main_text_font(message) helper.font_description(UserConfig[:reply_text_font]) end def header_left_content(*args) if show_header? super end end def header_right_content(*args) if show_header? super end end def icon_size if show_icon? if UserConfig[:reply_icon_size] Gdk::Rectangle.new(0, 0, helper.scale(UserConfig[:reply_icon_size]), helper.scale(UserConfig[:reply_icon_size])) else super end end end def text_max_line_count(message) UserConfig[:reply_text_max_line_count] || super end def render_outline(message, context, base_y) return unless show_edge? case UserConfig[:reply_edge] when :floating render_outline_floating(message, context, base_y) when :solid render_outline_solid(message, context, base_y) when :flat render_outline_flat(message, context, base_y) end end def render_badge(message, context) return unless show_edge? case UserConfig[:reply_edge] when :floating render_badge_floating(message, context) when :solid render_badge_solid(message, context) when :flat render_badge_flat(message, context) end end def show_header? (UserConfig[:reply_present_policy] || []).include?(:header) end def show_icon? (UserConfig[:reply_present_policy] || []).include?(:icon) end def show_edge? (UserConfig[:reply_present_policy] || []).include?(:edge) end end
# frozen_string_literal: true class CreateUsers < ActiveRecord::Migration[5.2] def create_name_fields(table) table.string :last_name, null: false, default: '' table.string :middle_name, null: false, default: '' table.string :first_name, null: false, default: '' end def create_credential_fields(table) table.string :email, null: false, default: '' table.string :phone table.integer :role, null: false end def create_password_fields(table) table.string :reset_password_token table.datetime :reset_password_time table.string :password_digest table.string :token end def create_social_fields(table) table.string :facebook_id table.string :google_id end def create_flag_fields(table) table.boolean :mailling_subscribed, null: false, default: false end def change create_table :users do |table| create_name_fields(table) create_credential_fields(table) create_password_fields(table) create_social_fields(table) create_flag_fields(table) table.boolean :is_active, null: false, default: true table.timestamps end add_index :users, :token, unique: true end end
require "rails_guides/helpers" module RailsGuides module HelpersJa include Helpers def finished_documents(documents) # Enable this line when not like to display WIP documents #documents.reject { |document| document['work_in_progress'] } documents.map{|doc| doc['url'].insert(0, '/') unless doc['url'].start_with?('/') } documents end def docs_for_sitemap(position) case position when "L" documents_by_section.to(4) when "C" documents_by_section.from(5).take(2) when "R" documents_by_section.from(7) else raise "Unknown position: #{position}" end end end end
class AddPublicToPainting < ActiveRecord::Migration def change add_column :paintings, :public, :boolean end end
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = "fewo-base" spec.version = "0.0.1" spec.authors = ["Lukas Himsel"] spec.email = ["lukas@himsel.me"] spec.summary = "A starter pack for AMP-based (amp.dev) Jekyll sites" spec.homepage = "https://github.com/lukas-h/fewo-base" spec.license = "Copyright (c) 2021 Lukas Himsel" spec.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^((?!Gemfile|_test_config|.gitignore|fewo-base|run_test.sh|test).*)}i) end spec.add_runtime_dependency "jekyll", "~> 4.1" spec.add_runtime_dependency "jekyll-data", "~> 1.1" spec.add_development_dependency "bundler" end
Rails.application.routes.draw do #Employee Routes get 'employees', to: 'employees#index' get 'employees/new', to: 'employees#new',as: :new_employee post 'employees', to: 'employees#create',as: :create_employee get 'employees/edit/:id', to: 'employees#edit',as: :edit_employee patch 'employees/:id', to: 'employees#update',as: :update_employee delete 'employees/:id', to: 'employees#destroy',as: :delete_employee get 'employees/emp', to: 'employees#emp',as: :employee # get 'employees/:id', to: 'employees#show',as: :employee #Project Routes get 'projects', to: 'projects#index' get 'projects/new', to: 'projects#new',as: :new_project post 'projects', to: 'projects#create',as: :create_project get 'projects/:id/edit', to: 'projects#edit',as: :edit_project patch 'projects/:id', to: 'projects#update',as: :update_project delete 'projects/:id', to: 'projects#destroy',as: :delete_project get 'projects/proj', to: 'projects#proj',as: :project # get 'projects/:id', to: 'projects#show',as: :project #Employeeprojects Routes get 'employeeprojects', to: 'employeeprojects#index' # get 'employeeprojects', to: 'employeeprojects#show',as: :employeeproject end
class CreateOrder < ActiveRecord::Migration def change create_table(:orders) do |t| t.integer :student_id, null: false t.timestamps end add_index :orders, :student_id end end
require "rails_helper" describe UsersSubjectsController do let(:trainee) {FactoryGirl.create :user} let(:users_subject) {FactoryGirl.create :users_subject} before do allow(request.env["warden"]).to receive(:authenticate!).and_return( trainee) allow(UsersSubject).to receive(:new).and_return users_subject end describe "POST create" do let(:user_subject_attributes) {FactoryGirl.attributes_for(:users_subject)} before do allow(users_subject).to receive(:save).and_return true post :create, users_subject: user_subject_attributes end it {expect(assigns :users_subject).to be users_subject} context "with valid attributes create UsersSubject" do let!(:course_subject_id) {users_subject.courses_subject_id} it {expect(response).to redirect_to edit_courses_subject_path( course_subject_id)} end context "with invalid attributes redirect to courses_subjects" do before do allow(users_subject).to receive(:save).and_return false post :create, users_subject: user_subject_attributes end it {expect(response).to render_template "courses_subjects/edit"} end end end
class PacientesController < ApplicationController def index name = params[:name] # Busca pacientes cujos nomes contenham a "string" pesquisada # O resultado será ordenado pelos nomes dos pacientes de forma alfabética # Cada página exibirá 20 resultados @pacientes = if name.nil? Paciente.order(:nome).page(params[:page]).per(20) else Paciente .search_by_name(name) #.includes([:anamneses, :avaliacoes, :tratamentos]) .order(:nome) .page(params[:page]) .per(20) end end def show @paciente = Paciente.find(params[:id]) end def new @paciente = Paciente.new end def edit id = params[:id] @paciente = Paciente.find(id) end def create @paciente = Paciente.new(paciente_params) if @paciente.save redirect_to(@paciente) else redirect_back(:fallback_location => root_path) end end def update @paciente = Paciente.find(params[:id]) @paciente.update(paciente_params) if @paciente.save redirect_to(@paciente) else redirect_back(:fallback_location => root_path) end end private def paciente_params params.require(:paciente).permit(:nome, :rg, :cpf, :nascimento, :sexo, :endereco, :telefone, :email, :acompanhante) end end
class RemoveTaskStatuses < ActiveRecord::Migration def change drop_table :task_statuses end end
class PurchaseEntry < Plutus::Entry has_one :purchase validates_presence_of :purchase # Override Plutus::Entry#amounts_cancel? due to a strange issue with BigDecimal # resulting in the following: # # (0..5).collect{ |i| (BigDecimal.new(i) + 0.30 + 0.69).to_f } # # => [0.9899999999999999, 1.99, 2.9899999999999998, 3.9899999999999998, 4.99, 5.99] # # WAT # # Therefore, we round the balances for the check, since we assume everything # is in cents. The original numbers do still get stored as is. private def amounts_cancel? super if credit_amounts.balance.round(5) != debit_amounts.balance.round(5) end end
#coding: utf-8 class Dashboard::MailBoxesController < Dashboard::ApplicationController inherit_resources defaults route_prefix: "dashboard" actions :all, except: :show respond_to :html #delete begin/rescue and move to lib/mail_box_uploader.rb def upload @mail_box = MailBox.where(id: params[:id]).first key, message = :notice, "Скачивание началось, это может занять некоторое время" begin if @mail_box && params[:password] @job_id = Uploader::MailBoxUploader.perform_async(params[:password], params[:id]) @mail_box.to_process!(nil, @job_id) p "inspect mailbox #{@mail_box.inspect}" end rescue => ex Rails.logger.info "Caught exception: #{ex.message}" key = :alert message = case ex when Net::POPAuthenticationError "Неверный логин или пароль." when SocketError "Неверный адрес pop3-сервера." else "Неизвестная ошибка." end end redirect_to dashboard_path, key => message end def check_upload_status data = SidekiqStatus::Container.load(params[:job_id]) render :json => { :status => data.status } end def change_job_status mail_box = MailBox.find_by(current_job_id: params[:job_id]) key, message = :alert, "Произошла ошибка при загрузке писем с ящика #{mail_box.login}@#{mail_box.domain}" if mail_box MailBox.finish_update_status.include?(params[:job_status]) ? mail_box.send("to_#{params[:job_status]}!") : mail_box.to_failed! if params[:job_status] == "complete" key, message = :notice, "Письма с ящика #{mail_box.login}@#{mail_box.domain} скачены." end else p "Error, job doesn't exist" end redirect_to dashboard_path, key => message end protected def begin_of_association_chain current_user end def collection @mail_boxes ||= end_of_association_chain.paginate(page: params[:page], per_page: WillPaginate.per_page) end def permitted_params params.permit(:mail_box => [:login, :pop3_server, :domain]) end end
class MailQueue include Enumerable attr_reader :resource private :resource def initialize args @resource = args[:resource] end def name resource.name.rpartition('/').last end def each &block decoded_messages.each &block end def clear resource.remove_messages end private def decoded_messages resource.map(&:decode) end end
class AddKidsToRelationship < ActiveRecord::Migration def change add_reference :relationships, :kid, index: true end end
class AddAPIId < ActiveRecord::Migration[6.1] def change add_column :stores, :api_key, :integer end end
class RecExpensesController < ApplicationController before_action :set_rec_expense, only: [:show, :edit, :update, :destroy] # GET /rec_expenses # GET /rec_expenses.json def index @rec_expenses = RecExpense.all end # GET /rec_expenses/1 # GET /rec_expenses/1.json def show end # GET /rec_expenses/new def new @rec_expense = RecExpense.new end # GET /rec_expenses/1/edit def edit end # POST /rec_expenses # POST /rec_expenses.json def create @rec_expense = RecExpense.new(rec_expense_params) respond_to do |format| if @rec_expense.save format.html { redirect_to @rec_expense, notice: 'Rec expense was successfully created.' } format.json { render :show, status: :created, location: @rec_expense } else format.html { render :new } format.json { render json: @rec_expense.errors, status: :unprocessable_entity } end end end # PATCH/PUT /rec_expenses/1 # PATCH/PUT /rec_expenses/1.json def update respond_to do |format| if @rec_expense.update(rec_expense_params) format.html { redirect_to @rec_expense, notice: 'Rec expense was successfully updated.' } format.json { render :show, status: :ok, location: @rec_expense } else format.html { render :edit } format.json { render json: @rec_expense.errors, status: :unprocessable_entity } end end end # DELETE /rec_expenses/1 # DELETE /rec_expenses/1.json def destroy @rec_expense.destroy respond_to do |format| format.html { redirect_to rec_expenses_url, notice: 'Rec expense was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_rec_expense @rec_expense = RecExpense.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def rec_expense_params params.require(:rec_expense).permit(:name, :frequency, :expense_id) end end
module MiqLinux class Utils def self.parse_ls_l_fulltime(lines) ret = [] return ret if lines.nil? || lines.empty? lines.each do |line| line = line.chomp parts = line.split(' ') next unless parts.length >= 9 perms, ftype = permissions_to_octal(parts[0]) ret << { :ftype => ftype, :permissions => perms, :hard_links => perms[1], :owner => parts[2], :group => parts[3], :size => parts[4], :mtime => Time.parse(parts[5..7].join(' ')).utc, :name => parts[8..-1].join(' '), } end ret end def self.permissions_to_octal(perms) if perms.length == 9 ftype = nil elsif perms.length == 10 ftype = perms[0, 1] perms = perms[1..-1] elsif perms.length == 11 # TODO: when se-linux is present, the format is like this '-rw-rw-r--.', . means an SELinux ACL. (+ means a # general ACL.). I need to figure out where to store this fact, ignoring it for now ftype = perms[0, 1] perms = perms[1..-2] else raise "Invalid perms length" end unless ftype.nil? ftype = case ftype when 'd' then 'dir' when 'l' then 'link' else 'file' end end octal = [0, 0, 0, 0] perms.split(//).each_with_index do |c, i| # puts [c, i, i % 3, 2 - (i % 3), 2 ** (2 - (i % 3)), i / 3, 2 - (i / 3), 2 ** (2 - (i / 3))].inspect octal[i / 3 + 1] += 2**(2 - (i % 3)) unless %w(- S T).include?(c) # puts octal.inspect octal[0] += 2**(2 - (i / 3)) if %w(s t S T).include?(c) # puts octal.inspect end octal = octal.join return octal, ftype end def self.octal_to_permissions(octal, ftype = nil) perms = "" unless ftype.nil? ftype = ftype[0, 1] ftype = '-' if ftype == 'f' perms << ftype end octal = octal.to_i(8) if octal.kind_of?(String) perms << (octal & 00400 != 0 ? 'r' : '-') perms << (octal & 00200 != 0 ? 'w' : '-') perms << (octal & 04000 != 0 ? (octal & 00100 != 0 ? 's' : 'S') : octal & 00100 != 0 ? 'x' : '-') perms << (octal & 00040 != 0 ? 'r' : '-') perms << (octal & 00020 != 0 ? 'w' : '-') perms << (octal & 02000 != 0 ? (octal & 00010 != 0 ? 's' : 'S') : octal & 00010 != 0 ? 'x' : '-') perms << (octal & 00004 != 0 ? 'r' : '-') perms << (octal & 00002 != 0 ? 'w' : '-') perms << (octal & 01000 != 0 ? (octal & 00001 != 0 ? 't' : 'T') : octal & 00001 != 0 ? 'x' : '-') perms end def self.parse_chkconfig_list(lines) ret = [] return ret if lines.nil? || lines.empty? lines.each_line do |line| line = line.chomp parts = line.split(' ') next unless parts.length >= 8 enable_level = [] disable_level = [] parts[1..-1].each do |part| level, state = part.split(':') case state when 'on' then enable_level << level when 'off' then disable_level << level end end nh = {:name => parts[0]} nh[:enable_run_level] = enable_level.empty? ? nil : enable_level.sort nh[:disable_run_level] = disable_level.empty? ? nil : disable_level.sort ret << nh end ret end def self.parse_systemctl_list(lines) return [] if lines.blank? lines.each_line.map do |line| line = line.chomp parts = line.split(' ') next if (/^.*?\.service$/ =~ parts[0]).nil? name, = parts[0].split('.') # TODO(lsmola) investigate adding systemd targets, which are used instead of runlevels. Drawback, it's not # returned by any command, so we would have to parse the dir structure of /etc/systemd/system/ # There is already MiqLinux::Systemd.new(@systemFs) called from class MIQExtract, we should leverage that {:name => name, :systemd_load => parts[1], :systemd_active => parts[2], :systemd_sub => parts[3], :typename => 'linux_systemd', :description => parts[4..-1].join(" "), :enable_run_level => nil, :disable_run_level => nil, :running => parts[3] == 'running'} end.compact end def self.parse_docker_ps_list(lines) return [] if lines.blank? lines.each_line.map do |line| line = line.chomp parts = line.split(/^(\S+)\s/) name, = parts[1] {:name => name, :systemd_load => 'container', :systemd_active => parts[2]&.strip&.start_with?('Up') ? 'active' : 'failed', :systemd_sub => parts[2]&.strip&.start_with?('Up') ? 'running' : 'failed', :typename => 'docker_container', :description => parts[1] + ' ' + parts[2].strip, :enable_run_level => nil, :disable_run_level => nil, :running => parts[2]&.strip&.start_with?('Up')} end.compact end def self.collect_interface(interfaces, interface) mac_addr = interface[:mac_address] return if mac_addr.blank? existing_interface = interfaces[mac_addr] if existing_interface.blank? interfaces[mac_addr] = interface else interface[:name] += "," + existing_interface[:name] existing_interface.merge!(interface) end end def self.parse_network_interface_list(lines) return [] if lines.blank? interfaces = {} interface = {} lines.each_line do |line| if /^\d+\:\s([\w-]+)\:.*?mtu\s(\d+).*?$/ =~ line collect_interface(interfaces, interface) unless interface.blank? interface = {:name => $1} elsif /^.*?link.*?((\w\w\:)+\w\w).*?$/ =~ line interface[:mac_address] = $1 elsif /^.*?inet\s((\d+\.)+\d+).*?$/ =~ line interface[:fixed_ip] = $1 elsif /^.*?inet6\s((\w*\:+)+\w+).*?$/ =~ line interface[:fixed_ipv6] = $1 end end collect_interface(interfaces, interface) interfaces.values end def self.parse_openstack_status(lines) lines = lines.to_s.split("\n").reject { |t| t.include?("=") }.group_by { |t| t.gsub(/openstack\-([a-z]+).*/i, '\1') } lines.map do |title, services| services = services.map { |service_line| service_line.split(/[:\(\)]/).map(&:strip) } # split service line by :, ( and ) and strip white space from results services = services.map do |service| { 'name' => service.first, 'active' => service[1] == 'active', 'enabled' => service[2] !~ /disabled/ } end { 'name' => title.capitalize, 'services' => services } end end def self.parse_openstack_container_status(lines) containers = lines.to_s.split("\n").group_by do |t| if t.include?('_') t.split("_")[0] elsif t.start_with?('openstack') t.split("-")[1] elsif t.include?('-') t.split("-")[0] else t.split(" ")[0] end end containers.map do |title, services| services = services.map { |service_line| service_line.split(/^(\S+)\s/) } # split service line by first space and strip white space from results services = services.map do |service| { 'name' => service[1], 'active' => service[2].strip.start_with?('Up'), 'enabled' => true } end { 'name' => title.capitalize, 'services' => services } end end def self.merge_openstack_services(systemctl_services, containerized_services) # Merge outputs 2 arrays with systemctl and containerized services, example: # systemctl_services = [{"name"=>"Swift", "services"=> [{"name"=>"openstack-swift-proxy", "active"=>true, "enabled"=>true}] # containerized_services = [{"name"=>"Swift", "services"=> [{"name"=>"swift_container_auditor", "active"=>true, "enabled"=>true}] # result is [{"name"=>"Swift", "services"=> [{"name"=>"openstack-swift-proxy", "active"=>true, "enabled"=>true}, # {"name"=>"swift_container_auditor", "active"=>true, "enabled"=>true}] all_services = systemctl_services + containerized_services service_names = all_services.map { |service| service['name'] }.uniq service_names.each do |name| merged_service = { "name" => name, "services" => [] } common_services = all_services.select { |service| service['name'] == name } common_services.each do |common_service| merged_service["services"].concat(common_service["services"]) all_services.delete(common_service) end all_services << merged_service end all_services end end end
require "test_helper" class ExpenseTest < ActiveSupport::TestCase def setup @expense= Expense.new(user_guid: "USR-12345678-1234-1234-1234-1234567890ab", name: "Expense Test", amount: 500, date: Time.now ) end test "should be valid" do assert @expense.valid? end test "should have valid user guid" do @expense.user_guid = " " assert_not @expense.valid? end test "valid description should be valid" do @expense.description = "a" * 100 assert @expense.valid? end test "invalid description should be invalid" do @expense.description = "a" * 101 assert_not @expense.valid? end test "invalid guids should be invalid" do invalid_guids = %w[USR-1234-12345678-1234-1234567890ab-1234 USR-12345678-1234-1234-1234-1234567890a USR;12345678,1234.1234-1234!1234567890ab] invalid_guids.each do |invalid_guid| @expense.user_guid = invalid_guid assert_not @expense.valid?, "#{invalid_guid.inspect} should be invalid" end end end
class RemoveReviewFromMeals < ActiveRecord::Migration def up remove_column :meals, :review_id end def down add_column :meals, :review_id, :integer end end
class Dojo < ActiveRecord::Base validates :branch, :street, :city, presence: true, length: { in: 3..30 } validates :state, presence: true, length: { is: 2 } has_many :students end
# encoding: utf-8 control "V-52359" do title "The DBMS must support the requirement to automatically audit account modification." desc "Once an attacker establishes initial access to a system, they often attempt to create a persistent method of reestablishing access. One way to accomplish this is for the attacker to simply modify an existing account. Auditing of account modification is one method and best practice for mitigating this risk. A comprehensive application account management process ensures an audit trail automatically documents the modification of application user accounts and, as required, notifies administrators, application owners, and/or appropriate individuals. Applications must provide this capability directly, leveraging complementary technology providing this capability or a combination thereof. Automated account auditing processes greatly reduces the risk that accounts will be surreptitiously modified and provides logging that can be used for forensic purposes. Note that user authentication and account management should be done via an enterprise-wide mechanism whenever possible. Examples of enterprise-level authentication/access mechanisms include, but are not limited to, Active Directory and LDAP. However, notwithstanding how accounts are managed, Oracle auditing must always be configured to capture account modification.true" impact 0.5 tag "check": " Check Oracle settings (and also OS settings, and/or enterprise-level authentication/access mechanisms settings) to determine if account creation is being audited. If account creation is not being audited by Oracle, this is a finding. To see if Oracle is configured to capture audit data, enter the following SQLPlus command: SHOW PARAMETER AUDIT_TRAIL or the following SQL query: SELECT * FROM SYS.V$PARAMETER WHERE NAME = 'audit_trail'; If Oracle returns the value 'NONE', this is a finding. " tag "fix": " Configure Oracle to audit account creation activities. Use this query to ensure auditable events are captured: ALTER SYSTEM SET AUDIT_TRAIL=<audit trail type> SCOPE=SPFILE; Audit trail type can be 'OS', 'DB', 'DB,EXTENDED', 'XML' or 'XML,EXTENDED'. After executing this statement, it may be necessary to shut down and restart the Oracle database. For more information on the configuration of auditing, please refer to 'Auditing Database Activity' in the Oracle Database 2 Day + Security Guide: http://docs.oracle.com/cd/E11882_01/server.112/e10575/tdpsg_auditing.htm and 'Verifying Security Access with Auditing' in the Oracle Database Security Guide: http://docs.oracle.com/cd/E11882_01/network.112/e36292/auditing.htm#DBSEG006 and '27 DBMS_AUDIT_MGMT' in the Oracle Database PL/SQL Packages and Types Reference: http://docs.oracle.com/cd/E11882_01/appdev.112/e40758/d_audit_mgmt.htm " # Write Check Logic Here end
require 'test/unit' require 'lib/rake_dotnet.rb' class SvnTest < Test::Unit::TestCase def test_initialize_with_no_opts svn = Svn.new assert_equal "\"#{TOOLS_DIR}/svn/bin/svn.exe\"", svn.exe end def test_initialize_with_path svn = Svn.new :svn => 'foo/bar/svn.exe' assert_equal "\"foo/bar/svn.exe\"", svn.exe end end
# ACQUIRING BEHAVIOR THROUGH INHERITANCE # Inheritance can be complicated, but at the end of the day it's about # automatic message delegation. If the original receiving object does # not know how to respond to that message, it is automatically sent to # the superclass. # Starting with what is necessary for a road bike class Bicycle attr_reader :size, :tape_color def initialize(args) @size = args[:size] @tape_color = args[:tape_color] end # every bike has the same default for tire and chain size def spares { chain: "10-speed", tire_size: "23", tape_color: tape_color } end # Many other methods... end bike = Bicycle.new(size: 'M', tape_color: 'red') bike.size # => 'M' bike.spares # -> {:tire_size => "23", # :chain => "10-speed", # :tape_color => "red"} # The example below is an example with BAD code. The scenario is now # the company from above wants to have mountain bikes and road bikes. # The code below is called an Antipattern -- a common pattern that # appears to be beneficial but is actually detrimental and for which, # there is a well-known alternative. class Bicycle attr_reader :style, :size, :tape_color, :front_shock, :rear_shock def initialize(args) @style = args[:style] @size = args[:size] @tape_color = args[:tape_color] @front_shock = args[:front_shock] @rear_shock = args[:rear_shock] end # checking "style" starts down a slippery slope def spares if style == :road { chain: "10-speed", tire_size: "23", # millimeters tape_color: tape_color } else { chain: "10-speed", tire_size: "2.1", # inches rear_shock: rear_shock } end end end bike = Bicycle.new( style: :mountain, size: 'S', front_shock: 'Manitou', rear_shock: 'Fox') bike.spares # -> {:tire_size => "2.1", # :chain => "10-speed", # :rear_shock => 'Fox'} # Similar to how duck-typing should be used when there were if statements # on classes and that was an indicator to use duck typing, the above # example has an if statement on an attribute of self. This is an # indicator to use inheritance. # A subclass should be everything its super is plus more. Thus, a class # of MountainBike should build on top of Bicycle. However, Bicycle should # not reference anything for RoadBike. # For inheritance to work, two things must be true. # 1. There must be a generalization-specialization relationship. # 2. You must use correct coding techniques. # Now, Bicycle is an abstract class (abstract: being disassociated from # any instance). Here's an outline of change process: class Bicycle # This class is now empty. # All code has been moved to RoadBike. end class RoadBike < Bicycle # Subclass of Bicycle. # Has all the code previously in Bicycle. end class MountainBike < Bicycle # Subclass of Bicycle. # Has no code in it. end # When creating an abstract in this process, it's easier to promote # behavior up to a super than move it down to a sub. This is why all code # that was in Bicycle was put into RoadBike, then brought back up. Failure # to separate the concrete from the abstract is what causes most confusion # when implementing inheritance. # Next step in the process is to bring behavior up to Bicycle and utilize # the abstract class. Starting with size since it's the simplest. class Bicycle attr_reader :size def initialize(args={}) @size = args[:size] end end class RoadBike < Bicycle attr_reader :tape_color def initialize(args) @tape_color = args[:tape_color] super(args) # RoadBike must now send 'super' end end # Because the super is explicitly called, the initialize message is now # shared. road_bike = RoadBike.new( size: 'M', tape_color: 'red' ) road_bike.size # -> ""M"" mountain_bike = MountainBike.new( size: 'S', front_shock: 'Manitou', rear_shock: 'Fox') mountain_bike.size # -> 'S' # Spares on the other hand is a convoluted mix of what is shared, what # is default, and what is specific to subs. We now need to make rules # that consider: # 1. Bicycles have a chain and a tire size. # 2. All bicycles share the same default for chain. # 3. Subclasses provide their own default for tire size. # 4. Concrete instances of subclasses are permitted to ignore defaults and supply instance-specific values. # The below example of using defaults is called the Template Mathod pattern. class Bicycle attr_reader :size, :chain, :tire_size def initialize(args={}) @size = args[:size] @chain = args[:chain] || default_chain @tire_size = args[:tire_size] || default_tire_size end def default_chain # <-- Common default '10-speed' end end class RoadBike < Bicycle # ... def default_tire_size # <-- Subclass default '23' end end class MountainBike < Bicycle # ... def default_tire_size # <-- Subclass default '2.1' end end road_bike = RoadBike.new(size: 'M', tape_color: 'red') road_bike.tire_size # => '23' road_bike.chain # => '10-speed' mountain_bike = MountainBike.new(size: 'S', front_shock: 'Manitou', rear_shock: 'Fox') mountain_bike.tire_size # => '2.1' mountain_bike.chain # => '10-speed' # However now if there's a new sub created, such as RecumbentBike, # the implementer will have to know that the super requires default_tire_size. # Not having it will produce an unclear error message. To fix this, add: class Bicycle # ... def default_tire_size raise NotImplementedError, "This #{self.class} cannont respond to: " end end # This will produce: bent = RecumbentBike.new # NotImplementedError: # This RecumbentBike cannot respond to: # 'default_tire_size' # Remember to always document Template Method requirements! # Now we have to move spares from RoadBike up to Bicycle. There are two # ways to do this. One is easier, but more coupled. The other more # sophisticated but more robust. # Current: class RoadBike < Bicycle # ... def spares { chain: '10-speed', tire_size: '23', tape_color: 'red' } end end class MountainBike < Bicycle # ... def spares super.merge({rear_shock: rear_shock}) end end # Changing RoadBike to mimic MountainBike and changing Bicycle to: class Bicycle def spares { tire_size: tire_size, chain: chain } end end # Gives an overall code that is easier, but coupled. This code is: class Bicycle attr_reader :size, :chain, :tire_size def initialize(args={}) @size = args[:size] @chain = args[:chain] || default_chain @tire_size = args[:tire_size] || default_tire_size end def spares { chain: chain, tire_size: tire_size } end def default_chain '10-speed' end def default_tire_size raise NotImplementedError end end class RoadBike < Bicycle attr_reader :tape_color def initialize(args) @tape_color = args[:tape_color] super(args) end def spares super.merge({ tape_color: tape_color }) end def default_tire_size '23' end end class MountainBike < Bicycle attr_reader :front_shock, :rear_shock def initialize(args) @front_shock = args[:front_shock] @rear_shock = args[:rear_shock] super(args) end def spares super.merge({ rear_shock: rear_shock }) end def default_tire_size '2.1' end end # The issue here is that if a new person is tasked to create a subclass # on Bicycle and they forget to put super in either the initialize or the # spares method, a very-hard-to-troubleshoot error will occur. To fix this # you can implement hooks. Note: The code below removes the initialize # method and the spares method in the subs. class Bicycle def initialize(args={}) @size = args[:size] @chain = args[:chain] || default_chain @tire_size = args[:tire_size] || default_tire_size post_initialize(args) end def post_initialize(args) nil end def spares { chain: chain, tire_size: tire_size }.merge(local_spares) end def local_spares {} end end class RoadBike < Bicycle def post_initialize(args) # RoadBike optionally overrides @tape_color = args[:tape_color] # the post_initialize in the super end def local_spares { tape_color: tape_color } end end class MountainBike < Bicycle def post_initialize(args) # MountainBike optionally overrides @front_shock = args[:front_shock] # the post_initialize in the super @rear_shock = args[:rear_shock] end def local_spares { rear_shock: rear_shock } end end # Now the subs aren't responsible for initializing. They responsible for # specific info that is required for initializing, but not when it occurs. # Final code: class Bicycle attr_reader :size, :chain, :tire_size def initialize(args={}) @size = args[:size] @chain = args[:chain] || default_chain @tire_size = args[:tire_size] || default_tire_size post_initialize(args) end def spares { tire_size: tire_size, chain: chain}.merge(local_spares) end def default_tire_size raise NotImplementedError end # subclasses may override def post_initialize(args) nil end def local_spares {} end def default_chain '10-speed' end end class RoadBike < Bicycle attr_reader :tape_color def post_initialize(args) @tape_color = args[:tape_color] end def local_spares {tape_color: tape_color} end def default_tire_size '23' end end class MountainBike < Bicycle attr_reader :front_shock, :rear_shock def post_initialize(args) @front_shock = args[:front_shock] @rear_shock = args[:rear_shock] end def local_spares {rear_shock: rear_shock} end def default_tire_size '2.1' end end # With this, a new subclass just has to implement the template methods. class RecumbentBike < Bicycle attr_reader :flag def post_initialize(args) @flag = args[:flag] end def local_spares { flag: flag } end def default_chain '9-speed' end def default_tire_size '28' end end bent = RecumbentBike.new(flag: 'tall and orange') bent.spares # -> {:tire_size => "28", # :chain => "10-speed", # :flag => "tall and orange"} # Note: It's best to wait until you have three concrete examples before # making a super/sub relationship. This way you can clearly know what is # concrete and what is abstract.
class AddFieldsToUser < ActiveRecord::Migration def change add_column :users, :name, :string add_column :users, :employee_id, :string add_column :users, :jive_id, :integer add_column :users, :mentor, :boolean, default: false end end
class RemoveNamesAndVenuesFromShows < ActiveRecord::Migration[5.1] def change remove_column :shows, :venue_city remove_column :shows, :venue_st remove_column :shows, :venue_country remove_column :shows, :promoter_name remove_column :shows, :promoter_phone remove_column :shows, :promoter_email remove_column :shows, :production_name remove_column :shows, :production_phone remove_column :shows, :production_email end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :current_user def current_user @login_user ||= User.find_by(id: session[:user_id]) if session[:user_id] end def require_login unless current_user flash[:status] = :failure flash[:result_text] = "You need to be logged in to do that" redirect_back fallback_location: root_path end end def render_404 render file: "/public/404.html", status: 404 # raise ActionController::RoutingError.new('Not Found') end end
class AddBodyToEssay < ActiveRecord::Migration def change add_column :essays, :body_id, :integer add_index :essays, :body_id end end
require 'spec_helper' describe PagesController do render_views describe "GET 'home'" do before(:each) do @client = YtDataApi::YtDataApiClient.new(ENV['YT_USER'], ENV['YT_USER_PSWD'], ENV['YT_DEV_AUTH_KEY']) response_one, @youtube_id_one = @client.create_playlist("test_playlist_one") response_two, @youtube_id_two = @client.create_playlist("test_playlist_two") response_three, @youtube_id_three = @client.create_playlist("test_playlist_three") Playlist.create!(:name => "test_playlist_one", :youtube_id => @youtube_id_one) Playlist.create!(:name => "test_playlist_two", :youtube_id => @youtube_id_two) Playlist.create!(:name => "test_playlist_three", :youtube_id => @youtube_id_three) get :home @home_playlist = assigns(:playlist) @home_playlists = assigns(:playlists) @switch_playlist = Playlist.find_by_name("test_playlist_three") end after(:each) do @client.delete_playlist(@youtube_id_one) @client.delete_playlist(@youtube_id_two) @client.delete_playlist(@youtube_id_three) end it "should be successful" do response.should be_success end it "should get the first playlist by default" do @home_playlist.id.should be Playlist.first.id end it "should have links for all playlists except the one that is displayed" do @home_playlists.each do |playlist| playlist.should_not be assigns(:playlist) end end it "should show a new playlist when it is selected" do get :home, :playlist_id => @switch_playlist.id assigns(:playlist).id.should be @switch_playlist.id end it "should update links when a new playlist is selected" do get :home, :playlist_id => @switch_playlist.id assigns(:playlists).each do |playlist| playlist.should_not be assigns(:playlist) end end it "should have the right title" do assigns(:title).should be @home_playlist.name end it "should have a link to the about page" do response.should have_selector("a", :href => "/about", :content => "alimi") end it "should have a link to the home page" do response.should have_selector("a", :href => "/", :content => "stormyflower") end end describe "GET 'about'" do before(:each) do get :about end it "should be successful" do response.should be_success end it "should have the right title" do assigns(:title).should == "about" end it "should have content" do response.should have_selector("section") end it "should have a link to the about page" do response.should have_selector("a", :href => "/about", :content => "alimi") end it "should have a link to the home page" do response.should have_selector("a", :href => "/", :content => "stormyflower") end end end
class BrochureSubsectionsController < ApplicationController layout "staff" before_filter :confirm_logged_in def index @brochure_subsections = BrochureSubsection.order("brochure_subsections.brochure_section_id, brochure_subsections.name ASC") end def show end def new @brochure_subsection = BrochureSubsection.new end def create @brochure_subsection = BrochureSubsection.new(params[:brochure_subsection]) if @brochure_subsection.save flash[:notice] = "Brochure Subsection \"#{@brochure_subsection.name}\" Created." redirect_to(:action => 'index') else flash[:notice] = "Brochure Subsection creation failed" render('new') end end def edit @brochure_subsection = BrochureSubsection.find(params[:id]) end def update @brochure_subsection = BrochureSubsection.find(params[:id]) if @brochure_subsection.update_attributes(params[:brochure_subsection]) flash[:notice] = "Brochure Subsection \"#{@brochure_subsection.name}\" updated." redirect_to(:action => 'index') else flash[:notice] = "Brochure Subsection update failed" render('edit') end end end
module Slack module Aria class Aika < Undine class << self def name '藍華・S・グランチェスタ' end def icon 'https://raw.githubusercontent.com/takesato/slack-aria/master/image/aika120x120.jpg' end end Company.client.on :message do |data| if(data['type'] == 'message' && data['text'] =~ /奇跡|ミラクル/) Aika.speak(data['channel'], "<@#{data['user']}> 恥しいセリフ禁止ー!!") end end end end end
class Cms::File < ActiveRecord::Base ComfortableMexicanSofa.establish_connection(self) set_table_name :cms_files cms_is_categorized # -- AR Extensions -------------------------------------------------------- has_attached_file :file, ComfortableMexicanSofa.config.upload_file_options # -- Relationships -------------------------------------------------------- belongs_to :site # -- Validations ---------------------------------------------------------- validates :site_id, :presence => true validates_attachment_presence :file validates_uniqueness_of :file_file_name, :scope => :site_id # -- Callbacks ------------------------------------------------------------ before_save :assign_label protected def assign_label self.label = self.label.blank?? self.file_file_name.gsub(/\.[^\.]*?$/, '').titleize : self.label end end
module Devise module TwoFactorAuthenticationHelper def two_factor_preference if UserOtpSender.new(current_user).otp_should_only_go_to_mobile? || both_options_at_sign_up return current_user.unconfirmed_mobile end second_factors = current_user.second_factors.pluck(:name) second_factors.map { |sf| current_user.send(sf.downcase) }.join(' and ') end def otp_drift_time_in_minutes Devise.allowed_otp_drift_seconds / 60 end def both_options_at_sign_up current_user.second_factors.size > 1 && current_user.second_factor_confirmed_at.nil? end end end
module ManageIQ::Providers::Amazon::CloudManager::Provision::Configuration def associate_floating_ip(ip_address) # TODO(lsmola) this should be moved to FloatingIp model destination.with_provider_object do |instance| if ip_address.cloud_network_only? instance.client.associate_address(:instance_id => instance.instance_id, :allocation_id => ip_address.ems_ref) else instance.client.associate_address(:instance_id => instance.instance_id, :public_ip => ip_address.address) end end end def userdata_payload raw_script = super return unless raw_script Base64.encode64(raw_script) end end
class CreateAuthors < ActiveRecord::Migration def change create_table :authors do |t| t.string :name t.string :status t.string :pic_url t.string :last_pub_date t.string :default_type #文章默认类型 t.timestamps end add_index :authors, :name, unique: true add_index :authors, :id end end
class BoardUser < ApplicationRecord validates :board_id, :user_id, presence:true belongs_to :board, foreign_key: :board_id, class_name: :Board belongs_to :user, foreign_key: :user_id, class_name: :User end