text
stringlengths
10
2.61M
describe HistoryList do describe '#events' do it "returns proposal creation as the first event" do proposal = create(:proposal) history = described_class.new(proposal) expect(history.events.first.event).to eq("create") end context "when the history contains client data events" do it "filters client data events out" do work_order = create(:ncr_work_order) work_order.update(function_code: "blah!") history = described_class.new(work_order.proposal) expect(history.events.collect(&:item_type)).to_not include("Ncr::WorkOrder") end end context "when the history contains step creation" do it "filters the step creation events out" do proposal = create(:proposal, :with_serial_approvers) history = described_class.new(proposal) expect(history.events.collect(&:item_type)).to_not include("Steps::Serial") expect(history.events.collect(&:item_type)).to_not include("Steps::Approval") end end end end
require 'yaml' require 'pry' def load_library(file_path) emoticons = YAML.load_file(file_path) results = {"get_emoticon" => {}, "get_meaning" => {}} emoticons.each do |meaning, array| english_emoticon = array[0] japanese_emoticon = array[1] results["get_meaning"][japanese_emoticon] = meaning results["get_emoticon"][english_emoticon] = japanese_emoticon end return results end def get_japanese_emoticon(file_path, emoticon) emoticons = load_library(file_path) if emoticons["get_emoticon"].has_key?(emoticon) return emoticons["get_emoticon"][emoticon] else return "Sorry, that emoticon was not found" end end def get_english_meaning(file_path, emoticon) emoticons = load_library(file_path) if emoticons["get_meaning"].has_key?(emoticon) return emoticons["get_meaning"][emoticon] else return "Sorry, that emoticon was not found" end end
Pod::Spec.new do |s| s.name = 'Keith' s.module_name = 'Keith' s.version = '0.2.12' s.license = { type: 'MIT', file: 'LICENSE' } s.summary = 'A media player for iOS written in Swift.' s.homepage = 'https://github.com/movile/Keith' s.authors = { 'Rafael Alencar' => 'rafael.alencar@movile.com' } s.source = { :git => 'https://github.com/movile/Keith.git', :tag => "v#{s.version}" } s.ios.deployment_target = '9.2' s.source_files = 'Keith/*.swift' end
module Xmpush class AndroidBuilder < Message # 设置通知类型 NOTIFY_TYPE_DEFAULT_ALL = -1 NOTIFY_TYPE_DEFAULT_SOUND = 1 # 使用默认提示音提示 NOTIFY_TYPE_DEFAULT_VIBRATE = 2 # 使用默认震动提示 NOTIFY_TYPE_DEFAULT_LIGHTS = 4 # 使用默认led灯光提示 NTF_CENTER_NTF = 0 # 通知栏消息 PASS_THROUGH_NTF = 1 # 透传消息 attr_accessor :pass_through, :notify_id, :sound_url def initialize(**message) super(message) extra = message.delete(:extra) if message[:extra] @pass_through = message[:pass_through] || NTF_CENTER_NTF @notify_id = message[:notify_id] || 0 @notify_type = message[:notify_type] || NOTIFY_TYPE_DEFAULT_ALL extra_message = {sound_url: ""} extra_message.merge!(extra) if extra @extra = extra_message end def build extra_message = extra(@extra) if @extra message = { payload: @payload, title: @title, notify_id: @notify_id, pass_through: @pass_through, notify_type: @notify_type, restricted_package_name: @restricted_package_name, description: @description } message.merge!(extra_message) return message end end end
class AddCostToService < ActiveRecord::Migration[5.1] def change add_column :services, :cost, :decimal end end
class ApplicationController < ActionController::Base protect_from_forgery def current_user @current_user ||= User.find_by_token(params[:token]) end end
require 'aws-sdk' module Aws::EC2 end class Aws::EC2::Handler def self.ec2_client @ec2_client ||= Aws::EC2::Client.new end def self.ec2_resource @ec2_resource ||= Aws::EC2::Resource.new end def self.instances(filters: {}) filter_params = filters.map do |key, values| { name: key.to_s, values: Array(values), } end ec2_resource.instances({ filters: filter_params, }) end def self.running_instances(tag_name: nil, tag_role: nil) filters = { 'instance-state-name' => 'running', } filters['tag:Name'] = tag_name if tag_name filters['tag:Role'] = tag_role if tag_role self.instances(filters: filters) end end
class Event < ApplicationRecord belongs_to :user has_many :event_followers, foreign_key: "event_id", dependent: :destroy has_many :followers, through: :event_followers, source: :follower has_many :posts validates_presence_of :title attr_accessor :num_follower end
# frozen_string_literal: true module AttendanceFormDataLoader private def load_form_data(year, month, group_id) @year = year @month = month first_date = Date.new(year, month, 1) last_date = Date.new(year, month, -1) @group = Group.includes(:group_schedules, :martial_art).find(group_id) weekdays = @group.group_schedules.map(&:weekday) @dates = (first_date..last_date).select { |d| weekdays.include? d.cwday } @instructors = @group.active_instructors(@dates) current_members = @group.members.active(first_date, last_date) .includes({ user: { attendances: { practice: :group_schedule }, groups: :group_schedules }, graduates: %i[graduation rank] }) attended_query = Member.references(:practices) .includes(user: { attendances: { practice: :group_schedule } }, graduates: %i[graduation rank]) .where(practices: { group_schedule_id: @group.group_schedules.map(&:id) }) .where('year > ? OR ( year = ? AND week >= ?)', first_date.cwyear, first_date.cwyear, first_date.cweek) .where('year < ? OR ( year = ? AND week <= ?)', last_date.cwyear, last_date.cwyear, last_date.cweek) attended_query = attended_query.where.not('members.id' => @instructors.map(&:id)) if @instructors.any? attended_members = attended_query.to_a @members = current_members | attended_members @instructors.sort_by! do |m| r = m.current_rank(@group.martial_art_id, last_date) [r ? -r.position : 99, m.first_name, m.last_name] end @members.sort_by! do |m| r = m.current_rank(@group.martial_art_id, first_date) [r ? -r.position : 99, m.first_name, m.last_name] end @instructors -= current_members @passive_members = (@members - attended_members).select { |m| m.passive_or_absent?(last_date, @group) } @members -= @passive_members @instructors -= @passive_members @birthdate_missing = @members.empty? || @members.find { |m| m.birthdate.nil? } end end
class AddColumnsForAttDocToLoans < ActiveRecord::Migration def change add_column :loans, :loan_doc, :string add_column :loans, :loan_doc_file_name, :string add_column :loans, :loan_doc_content_type, :string add_column :loans, :loan_doc_file_size, :integer add_column :loans, :loan_doc_update_at, :datetime add_column :loans, :refund_doc, :string add_column :loans, :refund_doc_file_name, :string add_column :loans, :refund_doc_content_type, :string add_column :loans, :refund_doc_file_size, :integer add_column :loans, :refund_doc_update_at, :datetime end end
class Sable::Client def initialize(options) @options = options end def apply(dry_run) expected = load_file(@options[:file]) Sable::Command::Apply.new( gcloud, gcloud.service_accounts, expected.service_accounts ).execute(dry_run) end def export(output) File.write(output, dsl.convert(gcloud.service_accounts)) end private def load_file(file) open(file) do |f| dsl.parse(f.read) end end def dsl @dsl ||= Sable::DSL.new(@options) end def gcloud @gcloud ||= Sable::GCloud.new(@options) end end
name 'fluentd' # fluentd v0.14.11 default_version 'v1.3.3' dependency 'ruby' dependency 'bundler' source git: 'https://github.com/fluent/fluentd.git' relative_path 'fluentd' build do env = with_standard_compiler_flags(with_embedded_path) bundle 'install --path vendor/bundle' rake 'build', env: env gem 'install --no-ri --no-rdoc pkg/fluentd-*.gem', env: env end
class MenusController < ApplicationController before_action :signed_in_administrator, only: [:new, :index, :edit, :update, :destory] def new @menu = Menu.new end def index @menus = Menu.where(lang: I18n.locale) end def create @menu = Menu.new(menu_params) @menu.save redirect_to menus_path end def show @menu = Menu.find(params[:id]) end def edit @menu = Menu.find(params[:id]) end def update @menu = Menu.find(params[:id]) if @menu.update_attributes(menu_params) redirect_to menus_path else render 'edit' end end def destroy Menu.find(params[:id]).destroy redirect_to :back end private def menu_params params.require(:menu).permit(:cuisine, :restaurant_id, :lang) end end
class BarDecorator < Draper::Decorator delegate_all def self.collection_decorator_class PaginatingDecorator end def username user.username end end
module Alf class Aggregator # # Defines a COUNT aggregation operator # class Count < Aggregator def least(); 0; end def happens(memo, tuple) memo + 1; end end # class Count # # Defines a SUM aggregation operator # class Sum < Aggregator def least(); 0; end def _happens(memo, val) memo + val; end end # class Sum # # Defines an AVG aggregation operator # class Avg < Aggregator def least(); [0.0, 0.0]; end def _happens(memo, val) [memo.first + val, memo.last + 1]; end def finalize(memo) memo.first / memo.last end end # class Sum # # Defines a variance aggregation operator # class Variance < Aggregator def least(); [0, 0.0, 0.0]; end def _happens(memo, x) count, mean, m2 = memo count += 1 delta = x - mean mean += (delta / count) m2 += delta*(x - mean) [count, mean, m2] end def finalize(memo) count, mean, m2 = memo m2 / count end end # class Variance # # Defines an standard deviation aggregation operator # class Stddev < Variance def finalize(memo) Math.sqrt(super(memo)) end end # class Stddev # # Defines a MIN aggregation operator # class Min < Aggregator def least(); nil; end def _happens(memo, val) memo.nil? ? val : (memo < val ? memo : val) end end # class Min # # Defines a MAX aggregation operator # class Max < Aggregator def least(); nil; end def _happens(memo, val) memo.nil? ? val : (memo > val ? memo : val) end end # class Max # # Defines a COLLECT aggregation operator # class Collect < Aggregator def least(); []; end def _happens(memo, val) memo << val end end # # Defines a CONCAT aggregation operator # class Concat < Aggregator def least(); ""; end def default_options {:before => "", :after => "", :between => ""} end def _happens(memo, val) memo << options[:between].to_s unless memo.empty? memo << val.to_s end def finalize(memo) options[:before].to_s + memo + options[:after].to_s end end end # class Aggregator end # module Alf
class RemoveLikesColumn < ActiveRecord::Migration[5.0] def up remove_column :posts, :likes end def down add_column :posts, :likes, :integer, :default => 0 end end
module API module Service def sign_in_service let(:account) { create(:account) } let(:service) { create(:service, :with_escalation_policy, account: account) } let(:token) { service.authentication_token } before do header 'Authorization', %[Token token="#{token}"] end end end module User def sign_in_user let(:account) { create(:account) } let(:user) { create(:user, account: account) } let(:token) { user.authentication_token } before do header 'Authorization', %[Token token="#{token}"] end end end end RSpec.configure do |config| config.extend API::Service, api: :true config.extend API::User, api: true end
class EditAuditReportContext < BaseContext attr_accessor :audit_report, :user def audit_report_as_json { audit_report: audit_report_json, fields: fields } end private def audit_report_json { id: audit_report.id, audit_report_summary: audit_report_summary_json, field_values: field_values_as_json, audit_report_name_field_value: { id: audit_report.id, name: 'Report name', value: audit_report.name, value_type: 'string', original_value: audit_report.audit.name, from_audit: true } } end def audit_report_summary_json audit_report_calculator = AuditReportCalculator.new(audit_report: audit_report) AuditReportSummarySerializer.new( audit_report: audit_report, audit_report_calculator: audit_report_calculator).as_json end def field_values_as_json fields = [ :id, :value, :field_api_name ] audit_report.field_values.pluck_to_hash(*fields).map do |row| field = Field.by_api_name!(row[:field_api_name]) # if row[:field_api_name] == 'location_for_temperatures' # field_options = location_for_temperature_options # else field_options = field.options # end { id: row[:id], name: field.name, value: row[:value], value_type: field.value_type, original_value: nil, from_audit: false, api_name: row[:field_api_name], options: field_options } end end def fields [ { title: 'Basic Audit Info', rows: [ [:report_name, :audit_date, :auditor_name, :auditor_email] ] }, { title: 'Client information', rows: [ [:contact_name, :contact_company, :contact_phone, :contact_email], [:contact_address, :contact_city, :contact_state], [:contact_zip] ] }, { title: 'Temperature data', rows: [ [ :location_for_temperatures, :heating_season_start_month, :heating_season_end_month, :heating_degree_days ], [ :average_indoor_temperature ] ] }, { title: 'Building characteristics', rows: [ [ :building_name, :building_address ], [ :building_city, :building_state, :building_zip ], [ :building_sqft, :num_apartments, :num_occupants, :num_bathrooms ], [ :num_stories, :num_bedrooms ] ] }, { title: 'Utility costs', rows: [ [ :electric_cost_per_kwh, :gas_cost_per_therm, :oil_cost_per_btu, :water_cost_per_gallon ] ] }, { title: 'Utility usage', rows: [ [ :electric_usage_in_kwh, :gas_usage_in_therms, :oil_usage_in_btu, :water_usage_in_gallons ], [ :heating_usage_in_therms, :cooling_usage_in_therms, :heating_fuel_baseload_in_therms ] ] }, { title: 'SIR-related', rows: [ [ :escalation_rate, :inflation_rate, :interest_rate ] ] } ] end def location_for_temperature_options field_options = TemperatureLocation.order(:location) .pluck_to_hash(:location, :state_code) [['', '']] + field_options.map do |row| ["#{row[:location]}, #{row[:state_code]}", "#{row[:location]}"] end end end
module SimpleSpark module Endpoints # Provides access to the /transmissions endpoint # See: https://developers.sparkpost.com/api/#/reference/transmissions class Transmissions attr_accessor :client def initialize(client) @client = client end # Sends an email message # @param values [Hash] the values to send with. This can be a complex object depending on the options chosen. # @param num_rcpt_errors [Integer] limit the number of recipient errors returned. Will default to all # @returns { results: { total_rejected_recipients: 0, total_accepted_recipients: 1, id: "11668787484950529" } } # @note See: https://developers.sparkpost.com/api/#/reference/transmissions/create # @note Example: # properties = { # options: { open_tracking: true, click_tracking: true }, # campaign_id: 'christmas_campaign', # return_path: 'bounces-christmas-campaign@sp.neekme.com', # metadata: {user_type: 'students'}, # substitution_data: { sender: 'Big Store Team' }, # recipients: [ # { address: { email: 'yourcustomer@theirdomain.com', name: 'Your Customer' }, # tags: ['greeting', 'sales'], # metadata: { place: 'Earth' }, substitution_data: { address: '123 Their Road' } } # ], # content: # { from: { name: 'Your Name', email: 'you@yourdomain.com' }, # subject: 'I am a test email', # reply_to: 'Sales <sales@yourdomain.com>', # headers: { 'X-Customer-CampaignID' => 'christmas_campaign' }, # text: 'Hi from {{sender}} ... this is a test, and here is your address {{address}}', # html: '<p>Hi from {{sender}}</p<p>This is a test</p>' # } # } def create(values, num_rcpt_errors = nil) query_params = num_rcpt_errors.nil? ? {} : { num_rcpt_errors: num_rcpt_errors } @client.call(method: :post, path: 'transmissions', body_values: values, query_values: query_params) end # Sends an email message # @param campaign_id [String] limit results to this Campaign ID # @param template_id [String] limit results to this Template ID # @returns [ { "content": { "template_id": "winter_sale" }, "id": "11713562166689858", # "campaign_id": "thanksgiving", "description": "", "state": "submitted" } ] # @note See: https://developers.sparkpost.com/api/#/reference/transmissions/list def list(campaign_id = nil, template_id = nil) query_params = {} query_params[:campaign_id] = campaign_id if campaign_id query_params[:template_id] = template_id if template_id @client.call(method: :get, path: 'transmissions', query_values: query_params) end # Deletes all transmissions for a given campaign # @param campaign_id [String] specifies the campaign to delete transmissions for # @returns empty string # @note Endpoint returns empty response body with 204 status code def delete_campaign(campaign_id) @client.call(method: :delete, path: 'transmissions', query_values: { campaign_id: campaign_id }) end # send_message to be reserved as a 'quick' helper method to avoid using hash for Create # alias_method :send_message, :create end end end
require 'spec_helper' require_relative '../../lib/paths' using StringExtension module Jabverwock using StringExtension RSpec.describe 'jw basic test' do subject(:inp) { INPUT.new } it "TagManager, path confirm " do tm = TagManager.new tm.name = "first" expect(tm.openString).to eq "<first>" expect(tm.closeString).to eq "</first>" end it "TagManager, name is void " do tm = TagManager.new tm.name = "" expect{tm.openString}.to raise_error StandardError end it "name and id add" do tm = TagManager.new() tm.name = "p" tm.tagAttribute.add_id ("test") expect(tm.openString).to eq "<p id=\"test\">" end it "tagAttr, id add, chain method" do tm = TagManager.new() tm.name = "p" tm.tagAttr("id","test").tagAttr("cls","test") expect(tm.openString).to eq "<p id=\"test\" class=\"test\">" end it "tagAttr, id add" do tm = TagManager.new() tm.name = "p" tm.tagAttr("id","test") expect(tm.openString).to eq "<p id=\"test\">" end it "id add, symbol use" do tm = TagManager.new() tm.name = "p" tm.tagAttr(:id,"test") expect(tm.openString).to eq "<p id=\"test\">" end it "id and name add" do tm = TagManager.new() tm.tagAttr(:id,"test") tm.name = "sample" expect(tm.openString).to eq "<sample id=\"test\">" end it "class add" do tm = TagManager.new() tm.name = "p" tm.tagAttr(:cls,"test") expect(tm.openString).to eq "<p class=\"test\">" end it "class, id , name add" do tm = TagManager.new() tm.tagAttr(:cls,"test").tagAttr(:id, "test") tm.name = "sample" expect(tm.openString).to eq "<sample class=\"test\" id=\"test\">" expect(tm.tagAttribute.cls).to eq "test" end it "not br tag " do tm = TagManager.new tm.name = "b" expect(tm.openString).to eq "<b>" expect(tm.closeString).to eq "</b>" end it "tag attribute lang add" do tm = TagManager.new tm.name = "a" tm.tagAttr(:lang, "jp") expect(tm.openString).to eq "<a lang=\"jp\">" end it "tag attribute lang call" do tm = TagManager.new tm.name = "a" tm.tagAttr(:lang, "jp") expect(tm.tagAttribute.lang).to eq "jp" end it "openString replace" do tm = TagManager.new tm.tempOpenString = "aaa" tm.openStringReplace("a","b") expect(tm.tempOpenString).to eq"bbb" end it "closeString replace" do tm = TagManager.new tm.tempCloseString = "aaa" tm.closeStringReplace("a","b") expect(tm.tempCloseString).to eq "bbb" end end RSpec.describe 'comment' do subject(:tm) { TagManager.new } it 'COMMENT class, tag' do tm.name = 'comment' expect(tm.isComment).to be true end it 'JWComment class' do jwc = COMMENT.new expect(jwc.tagManager.isComment).to be true end end end
module Celluloid OWNER_IVAR = :@celluloid_owner # reference to owning actor # Wrap the given subject with an Cell class Cell class ExitHandler def initialize(behavior, subject, method_name) @behavior = behavior @subject = subject @method_name = method_name end def call(event) @behavior.task(:exit_handler, @method_name) do @subject.send(@method_name, event.actor, event.reason) end end end def initialize(subject, options, actor_options) @actor = Actor.new(self, actor_options) @subject = subject @receiver_block_executions = options[:receiver_block_executions] @exclusive_methods = options[:exclusive_methods] @finalizer = options[:finalizer] @subject.instance_variable_set(OWNER_IVAR, @actor) if exit_handler_name = options[:exit_handler_name] @actor.exit_handler = ExitHandler.new(self, @subject, exit_handler_name) end @actor.handle(Call) do |message| invoke(message) end @actor.handle(BlockCall) do |message| task(:invoke_block) { message.dispatch } end @actor.handle(BlockResponse, Response) do |message| message.dispatch end @actor.start @proxy = (options[:proxy_class] || CellProxy).new(@actor.proxy, @actor.mailbox, @subject.class.to_s) end attr_reader :proxy, :subject def invoke(call) meth = call.method if meth == :__send__ meth = call.arguments.first end if @receiver_block_executions && meth if @receiver_block_executions.include?(meth.to_sym) call.execute_block_on_receiver end end task(:call, meth, :dangerous_suspend => meth == :initialize) { call.dispatch(@subject) } end def task(task_type, method_name = nil, meta = nil, &block) meta ||= {} meta.merge!(:method_name => method_name) @actor.task(task_type, meta) do if @exclusive_methods && method_name && @exclusive_methods.include?(method_name.to_sym) Celluloid.exclusive { yield } else yield end end end # Run the user-defined finalizer, if one is set def shutdown return unless @finalizer && @subject.respond_to?(@finalizer, true) task(:finalizer, @finalizer, :dangerous_suspend => true) do begin @subject.__send__(@finalizer) rescue => ex Logger.crash("#{@subject.class} finalizer crashed!", ex) end end end end end
class CreateBowlingGame < ActiveRecord::Migration[5.0] def change create_table :bowling_games do |t| t.text :game_data t.timestamps end end end
require_relative "../bank.rb" describe Bank do describe ".new" do it "should assign a name to the new bank" do bank_name = "Commonweatlth" bank = Bank.new(bank_name) expect(bank.name).to eq bank_name end it "should have no accounts" do bank = Bank.new("FOO") expect(bank.accounts.length).to eq 0 end end describe "#create_account" do let(:bank) { Bank.new("Foo") } it "creates an account with the given account name" do bank.create_account("Sam Smith", 200) expect(bank.accounts["Sam Smith"]).to_not eq nil end it "initializes the account balance to the specified amount" do bank.create_account("Sam Smith", 200) expect(bank.accounts["Sam Smith"]).to eq 200 end it "returns false when account name is already taken" do bank.create_account("Sam Smith", 200) expect(bank.create_account("Sam Smith", 200)).to eq false end it "cannot initialize a negative account balance" do expect(bank.create_account("Sam Smith", -200)).to eq false end it "it returns the account balance on successful creation" do expect(bank.create_account("Sam Smith", 200)).to eq 200 end end describe "#withdraw" do let(:bank) {Bank.new("Foo")} before :each do bank.create_account("Foo Bar", 1000) end it "should deduct the amount from the given balance" do bank.withdraw("Foo Bar", 500) expect(bank.accounts["Foo Bar"]).to eq 500 end it "should return false if not enough funds" do expect(bank.withdraw("Foo Bar", 2000)).to eq false end it "should return false if account doesn't exist" do expect(bank.withdraw("Sam Smith", 2000)).to eq false end it "should return false if deducting negative amount" do expect(bank.withdraw("Foo Bar", -1)).to eq false end it "should return the new balance" do expect(bank.withdraw("Foo Bar", 600)).to eq 400 end end end
class Timestamp attr_reader :time def initialize(timestamp) @time = Time.at(timestamp).utc end def to_second @time.to_i end def to_minute @time.change(sec: 0).to_i end def to_hour @time.beginning_of_hour.to_i end def to_day @time.beginning_of_day.to_i end def to_week @time.beginning_of_week end def to_month @time.beginning_of_month.to_i end def to_year @time.beginning_of_year.to_i end def to_formatted_second @time.strftime("%Y-%m-%dT%H:%M:%S") end def to_formatted_minute @time.strftime("%Y-%m-%dT%H:%M") end def to_formatted_hour @time.strftime("%Y-%m-%dT%H") end def to_formatted_day @time.strftime("%Y-%m-%d") end def to_formatted_month @time.strftime("%Y-%m") end def to_formatted_year @time.strftime("%Y") end end
require 'rails_helper' RSpec.describe 'Admin settings saving' do before do sign_in_to_admin_area end it 'saves integer setting' do allow(Setting).to receive(:integer_settings) { %i[test_setting] } post admin_settings_path, settings: { test_setting: '1' } expect(Setting.test_setting).to eq(1) end it 'saves float setting' do allow(Setting).to receive(:float_settings) { %i[test_setting] } post admin_settings_path, settings: { test_setting: '1.2' } expect(Setting.test_setting).to eq(1.2) end it 'saves boolean setting' do allow(Setting).to receive(:boolean_settings) { %i[test_setting] } post admin_settings_path, settings: { test_setting: 'true' } expect(Setting.test_setting).to be true end it 'saves string setting' do post admin_settings_path, settings: { test_setting: 'test' } expect(Setting.test_setting).to eq('test') end it 'redirects to :index' do post admin_settings_path, settings: { test: 'test' } expect(response).to redirect_to admin_settings_path end end
Spree::Order.class_eval do # Redefine the checkout flow to place the `payment` step before the `address` # step, since the user is required to enter their billing address on # Authorize.net's hosted form. checkout_flow do go_to_state :payment, if: ->(order) { order.payment_required? } go_to_state :address go_to_state :delivery go_to_state :confirm, if: ->(order) { order.confirmation_required? } go_to_state :complete end state_machine.after_transition from: :delivery, do: :update_payment_total_with_shipping private def update_payment_total_with_shipping payment = payments.valid.first return unless payment && payment.amount != total payment.update!(amount: total) end # Overridden to grab the default billing/shipping addresses from the payment # method entered previously. def assign_default_addresses! if payments.any? clone_billing_from_payments clone_shipping_from_payments if checkout_steps.include?("delivery") elsif user clone_billing clone_shipping if checkout_steps.include?("delivery") end end def clone_billing_from_payments return if bill_address_id address = address_from_payments self.bill_address = address.try(:clone) if address.try(:valid?) end def clone_shipping_from_payments return if ship_address_id address = address_from_payments self.ship_address = address.try(:clone) if address.try(:valid?) end def address_from_payments payment = payments.find { |p| p.source.present? && p.source.address_id.present? } Spree::Address.find(payment.source.address_id) if payment && payment.source.address_id end end
# to_roman_numeral.rb class Integer def to_roman roman_numbers = { 1000=>'M', 900=>'CM', 500=>'D', 400=>'CD', 100 => "C", 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" } integer = self result = [] while integer != 0 roman_numbers.each_pair do |normal_number, roman_number| if (integer - normal_number) >= 0 result << roman_number integer -= normal_number end end end return result.join end end (1..15).each { |i| puts i.to_roman }
class Game < ActiveRecord::Base has_and_belongs_to_many :players validate :check_number_of_players private def check_number_of_players if self.players.length != 2 errors.add(:number_of_players, "must be 2") end end end
# -*- coding: utf-8 -*- class User < ActiveRecord::Base has_many :cities validates_presence_of :name validates_uniqueness_of :name def disable_other_capital(capital_city) self.cities.where(:capital => true).each {|city| next if capital_city == city city.update_attributes(:capital => false) } end # 对方城市 def target_cities City.where('user_id != ?', self.id) end end
require 'fileutils' require_relative "item" require_relative "list" require 'colorize' class Todo # attr_accessor :lines, :list def initialize (filename = "todo.data") @filename = filename @list = List.new("Today") end # Show all items def show_all puts "here is our mission today:".colorize(:blue) @list.display end # The current list def list @list end # Show the number of items #first way def number_item @list.how_many_item? end #second way #def number_item # Item.count #end # Show all done items def show_done @list.display_done end # Show all undone items def show_undone @list.display_undone end # Add an item def add(task) item = Item.new(task) @list.add(item) show_all end # Loading... file def load_data @lines = File.read(@filename).split("\n") @lines.each do |line| # "- [ ] Learn Numbers" item = Item.new_from_line(line) @list.add(item) end end # Item completed def mark_item(index) mark_index = index loop do break if mark_index <= number_item show_all puts "Enter the right item number to mark as done:".colorize(:red) grandma_index = gets.chomp.split grandma_index[0] mark_index = grandma_index[0].to_i end puts "You've marked index #{mark_index} as done".colorize(:blue) @list.complete_at!(mark_index - 1) show_all puts "Great bro, the task is complete!".colorize(:blue) end #remove an item def remove_item(index) re_index = index loop do break if re_index <= number_item show_all puts "Enter the right item number to remove:".colorize(:red) grandma_index = gets.chomp.split grandma_index[0] re_index = grandma_index[0].to_i end puts "the item has been removed".colorize(:blue) @list.remove_at!(re_index - 1) show_all puts "the task is remove!" end # Have fun with prompt def start_prompt puts "your commands your rules:".colorize(:blue) grandma_index = gets.chomp.split case grandma_index[0] when "exit", "e", "quit" puts "---------------Goodbye!----------------".colorize(:blue) "exit" when "showall","list","sa", "all" show_all when "add","a", "+" add(grandma_index[1..-1].join(" ")) when "showdone", "sd", "done" show_done when "showundone", "su", "undone" show_undone when "mark", "m" mark_item(grandma_index[1].to_i) when "num" puts "number items: #{number_item}".colorize(:green) when "r", "remove" remove_item((grandma_index[1].to_i)) else display_instructions end end def display_instructions puts "----------------------------------------------------".colorize(:blue) puts "Here are the commands you can try:".colorize(:red) puts "- showall".colorize(:red) + ", ".colorize(:blue) + "all".colorize(:red) + ", ".colorize(:blue) + "sa".colorize(:red) + " or".colorize(:blue) + " list".colorize(:red) + " : show all items".colorize(:blue) puts "- done".colorize(:red) + ",".colorize(:blue) + " showdone".colorize(:red) + " or".colorize(:blue) + " sd".colorize(:red) + " : show done items".colorize(:blue) puts "- undone".colorize(:red) + ",".colorize(:blue) + " showundone".colorize(:red) + " or".colorize(:blue) + " su".colorize(:red) + " : show done items".colorize(:blue) puts "- add".colorize(:red) + " item".colorize(:green) + ",".colorize(:blue) + " a".colorize(:red) + " item".colorize(:green) + " or".colorize(:blue) + " +".colorize(:red) + " item".colorize(:green) + " : add a new task".colorize(:blue) puts "- remove".colorize(:red) + " index ".colorize(:green) + "or ".colorize(:blue) + "r ".colorize(:red) + "index".colorize(:green) + " : remove a task".colorize(:blue) puts "- mark".colorize(:red) + " index".colorize(:green) + " or".colorize(:blue) + " m".colorize(:red) + " index".colorize(:green) + " : mark a task as done".colorize(:blue) puts "- num".colorize(:red) + " : give number of items".colorize(:blue) puts "- exit".colorize(:red) + ",".colorize(:blue) + "quit".colorize(:red) + " or".colorize(:blue) + " e".colorize(:red) + " : Quit the application".colorize(:blue) end end @todo = Todo.new @todo.list @todo.load_data puts "-----------welcome to todo App-----------".rjust(50).colorize(:blue) case ARGV[0] when "showall", "list", "sa", "all" @todo.show_all when "add","a", "+" @todo.add(ARGV[1..-1].join(" ")) when "showdone", "sd", "done" @todo.show_done when "showundone", "su", "undone" @todo.show_undone when "num" Puts "number items: #{@todo.number_item}" else ARGV.clear @todo.display_instructions loop do break if @todo.start_prompt == "exit" end end
class Dsp < ActiveRecord::Base has_many :dsp_users has_many :users, through: :dsp_users validates :name, uniqueness: true end
# encoding: UTF-8 module AMQP def self.start_web_dispatcher(amqp_settings={}) @settings = settings.merge(amqp_settings) case Qusion::ServerSpy.server_type when :passenger RAILS_DEFAULT_LOGGER.info "=> Qusion running AMQP for Passenger" PhusionPassenger.on_event(:starting_worker_process) do |forked| if forked EM.kill_reactor Thread.current[:mq], @conn = nil, nil end Thread.new { self.start } die_gracefully_on_signal end when :standard Thread.new { self.start } die_gracefully_on_signal when :evented die_gracefully_on_signal when :none puts "=> Qusion configured AMQP settings (vhost = #{@settings[:vhost]})" else raise ArgumentError, "AMQP#start_web_dispatcher requires an argument of [:standard|:evented|:passenger|:none]" end end def self.die_gracefully_on_signal Signal.trap("INT") { AMQP.stop { EM.stop } } Signal.trap("TERM") { AMQP.stop { EM.stop } } end end
# -*- encoding: utf-8 -*- # stub: community_engine 3.0.0 ruby lib Gem::Specification.new do |s| s.name = "community_engine" s.version = "3.0.0" s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Bruno Bornsztein"] s.date = "2014-12-03" s.description = "CommunityEngine is a free, open-source social network platform for Ruby on Rails applications. Drop it into your new or existing application, and you\u{2019}ll instantly have all the features of a basic community site." s.email = "admin@curbly.com" s.extra_rdoc_files = ["LICENSE", "README.markdown"] s.files = ["LICENSE", "README.markdown"] s.homepage = "http://www.communityengine.org" s.licenses = ["MIT", "see each plugin"] s.rubygems_version = "2.4.8" s.summary = "CommunityEngine for Rails 4" s.installed_by_version = "2.4.8" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<actionpack-action_caching>, [">= 0"]) s.add_runtime_dependency(%q<actionpack-page_caching>, [">= 0"]) s.add_runtime_dependency(%q<acts_as_commentable>, ["~> 4.0.2"]) s.add_runtime_dependency(%q<acts_as_list>, [">= 0.3.0"]) s.add_runtime_dependency(%q<acts-as-taggable-on>, ["~> 2.4.1"]) s.add_runtime_dependency(%q<authlogic>, [">= 3.3.0"]) s.add_runtime_dependency(%q<aws-sdk>, [">= 0"]) s.add_runtime_dependency(%q<bcrypt>, [">= 0"]) s.add_runtime_dependency(%q<cocaine>, ["~> 0.5.1"]) s.add_runtime_dependency(%q<configatron>, ["~> 4.2.0"]) s.add_runtime_dependency(%q<dynamic_form>, [">= 0"]) s.add_runtime_dependency(%q<friendly_id>, ["~> 5.0.0.beta1"]) s.add_runtime_dependency(%q<haml>, [">= 0"]) s.add_runtime_dependency(%q<hpricot>, [">= 0"]) s.add_runtime_dependency(%q<htmlentities>, [">= 0"]) s.add_runtime_dependency(%q<kaminari>, [">= 0"]) s.add_runtime_dependency(%q<koala>, ["~> 1.6.0"]) s.add_runtime_dependency(%q<omniauth>, ["~> 1.1.4"]) s.add_runtime_dependency(%q<rails_autolink>, [">= 0"]) s.add_runtime_dependency(%q<paperclip>, ["~> 3.5.1"]) s.add_runtime_dependency(%q<power_enum>, ["~> 2.0.1"]) s.add_runtime_dependency(%q<rack>, [">= 1.5.2"]) s.add_runtime_dependency(%q<rails>, ["~> 4.0.0"]) s.add_runtime_dependency(%q<rails-observers>, [">= 0"]) s.add_runtime_dependency(%q<rakismet>, [">= 0"]) s.add_runtime_dependency(%q<ransack>, ["~> 1.0.0"]) s.add_runtime_dependency(%q<recaptcha>, [">= 0"]) s.add_runtime_dependency(%q<ri_cal>, [">= 0"]) s.add_runtime_dependency(%q<sanitize>, [">= 2.0.6"]) s.add_runtime_dependency(%q<bootstrap-sass>, ["~> 3.2.0"]) s.add_runtime_dependency(%q<bootstrap_form>, [">= 0"]) s.add_runtime_dependency(%q<font-awesome-rails>, [">= 0"]) s.add_runtime_dependency(%q<jquery-rails>, [">= 0"]) s.add_runtime_dependency(%q<jquery-ui-rails>, ["~> 5.0.0"]) s.add_runtime_dependency(%q<sass-rails>, ["~> 4.0.0"]) s.add_runtime_dependency(%q<sprockets>, ["~> 2.10.0"]) s.add_runtime_dependency(%q<tinymce-rails>, ["~> 4.0.2"]) else s.add_dependency(%q<actionpack-action_caching>, [">= 0"]) s.add_dependency(%q<actionpack-page_caching>, [">= 0"]) s.add_dependency(%q<acts_as_commentable>, ["~> 4.0.2"]) s.add_dependency(%q<acts_as_list>, [">= 0.3.0"]) s.add_dependency(%q<acts-as-taggable-on>, ["~> 2.4.1"]) s.add_dependency(%q<authlogic>, [">= 3.3.0"]) s.add_dependency(%q<aws-sdk>, [">= 0"]) s.add_dependency(%q<bcrypt>, [">= 0"]) s.add_dependency(%q<cocaine>, ["~> 0.5.1"]) s.add_dependency(%q<configatron>, ["~> 4.2.0"]) s.add_dependency(%q<dynamic_form>, [">= 0"]) s.add_dependency(%q<friendly_id>, ["~> 5.0.0.beta1"]) s.add_dependency(%q<haml>, [">= 0"]) s.add_dependency(%q<hpricot>, [">= 0"]) s.add_dependency(%q<htmlentities>, [">= 0"]) s.add_dependency(%q<kaminari>, [">= 0"]) s.add_dependency(%q<koala>, ["~> 1.6.0"]) s.add_dependency(%q<omniauth>, ["~> 1.1.4"]) s.add_dependency(%q<rails_autolink>, [">= 0"]) s.add_dependency(%q<paperclip>, ["~> 3.5.1"]) s.add_dependency(%q<power_enum>, ["~> 2.0.1"]) s.add_dependency(%q<rack>, [">= 1.5.2"]) s.add_dependency(%q<rails>, ["~> 4.0.0"]) s.add_dependency(%q<rails-observers>, [">= 0"]) s.add_dependency(%q<rakismet>, [">= 0"]) s.add_dependency(%q<ransack>, ["~> 1.0.0"]) s.add_dependency(%q<recaptcha>, [">= 0"]) s.add_dependency(%q<ri_cal>, [">= 0"]) s.add_dependency(%q<sanitize>, [">= 2.0.6"]) s.add_dependency(%q<bootstrap-sass>, ["~> 3.2.0"]) s.add_dependency(%q<bootstrap_form>, [">= 0"]) s.add_dependency(%q<font-awesome-rails>, [">= 0"]) s.add_dependency(%q<jquery-rails>, [">= 0"]) s.add_dependency(%q<jquery-ui-rails>, ["~> 5.0.0"]) s.add_dependency(%q<sass-rails>, ["~> 4.0.0"]) s.add_dependency(%q<sprockets>, ["~> 2.10.0"]) s.add_dependency(%q<tinymce-rails>, ["~> 4.0.2"]) end else s.add_dependency(%q<actionpack-action_caching>, [">= 0"]) s.add_dependency(%q<actionpack-page_caching>, [">= 0"]) s.add_dependency(%q<acts_as_commentable>, ["~> 4.0.2"]) s.add_dependency(%q<acts_as_list>, [">= 0.3.0"]) s.add_dependency(%q<acts-as-taggable-on>, ["~> 2.4.1"]) s.add_dependency(%q<authlogic>, [">= 3.3.0"]) s.add_dependency(%q<aws-sdk>, [">= 0"]) s.add_dependency(%q<bcrypt>, [">= 0"]) s.add_dependency(%q<cocaine>, ["~> 0.5.1"]) s.add_dependency(%q<configatron>, ["~> 4.2.0"]) s.add_dependency(%q<dynamic_form>, [">= 0"]) s.add_dependency(%q<friendly_id>, ["~> 5.0.0.beta1"]) s.add_dependency(%q<haml>, [">= 0"]) s.add_dependency(%q<hpricot>, [">= 0"]) s.add_dependency(%q<htmlentities>, [">= 0"]) s.add_dependency(%q<kaminari>, [">= 0"]) s.add_dependency(%q<koala>, ["~> 1.6.0"]) s.add_dependency(%q<omniauth>, ["~> 1.1.4"]) s.add_dependency(%q<rails_autolink>, [">= 0"]) s.add_dependency(%q<paperclip>, ["~> 3.5.1"]) s.add_dependency(%q<power_enum>, ["~> 2.0.1"]) s.add_dependency(%q<rack>, [">= 1.5.2"]) s.add_dependency(%q<rails>, ["~> 4.0.0"]) s.add_dependency(%q<rails-observers>, [">= 0"]) s.add_dependency(%q<rakismet>, [">= 0"]) s.add_dependency(%q<ransack>, ["~> 1.0.0"]) s.add_dependency(%q<recaptcha>, [">= 0"]) s.add_dependency(%q<ri_cal>, [">= 0"]) s.add_dependency(%q<sanitize>, [">= 2.0.6"]) s.add_dependency(%q<bootstrap-sass>, ["~> 3.2.0"]) s.add_dependency(%q<bootstrap_form>, [">= 0"]) s.add_dependency(%q<font-awesome-rails>, [">= 0"]) s.add_dependency(%q<jquery-rails>, [">= 0"]) s.add_dependency(%q<jquery-ui-rails>, ["~> 5.0.0"]) s.add_dependency(%q<sass-rails>, ["~> 4.0.0"]) s.add_dependency(%q<sprockets>, ["~> 2.10.0"]) s.add_dependency(%q<tinymce-rails>, ["~> 4.0.2"]) end end
require "test_helper" describe GamesController do let(:game) { games :one } it "gets index" do get games_url value(response).must_be :success? end it "gets new" do get new_game_url value(response).must_be :success? end it "creates game" do expect { post games_url, params: { game: { attendee: game.attendee, creator: game.creator, date: game.date, location: game.location, sport: game.sport } } }.must_change "Game.count" must_redirect_to game_path(Game.last) end it "shows game" do get game_url(game) value(response).must_be :success? end it "gets edit" do get edit_game_url(game) value(response).must_be :success? end it "updates game" do patch game_url(game), params: { game: { attendee: game.attendee, creator: game.creator, date: game.date, location: game.location, sport: game.sport } } must_redirect_to game_path(game) end it "destroys game" do expect { delete game_url(game) }.must_change "Game.count", -1 must_redirect_to games_path end end
#!/usr/bin/env ruby require 'tiny_segmenter' # Ignore particles ignore = ["の", "に", "て", "は", "た", "が", "を", "で", "も", "と", "だ", "な", "か", "や"] # Read arguments content = "" for arg in ARGV content = content + File.read(arg) end # Parse the input ts = TinySegmenter.new words = ts.segment(content, ignore_punctuation: true) # Make an empty hash frequency = Hash.new(0) # Get the words and their frequencies words.each { |word| frequency[word] += 1 } # Sort by the frequencies frequency = frequency.sort_by {|key, value| value}.reverse.to_h # Output to file frequency.each do |key,value| if !ignore.include? key str = key + ", " + value.to_s File.open("freq.txt", 'a'){|file| file.puts str} end end
class CreateSusuTransactions < ActiveRecord::Migration[6.1] def change create_table :susu_transactions do |t| t.decimal :net_amount, null: false t.decimal :fees, null: false t.integer :round, null: false t.integer :trans_type, null: false t.integer :payment_type, null: false t.integer :status, null: false t.text :description t.references :susu, null: false, foreign_key: true t.references :user, null: false, foreign_key: true t.timestamps end end end
require "./Coor3D.rb" class AgentList < Array def delete(obj) if obj.is_a? Human Human.decrement elsif obj.is_a? Zombie Zombie.decrement end super end end # All zombies, humans, wild animals, etc. are derived from an Agent. class Agent attr_reader :energy, :health MAX_HEALTH = 100 MAX_ENERGY = 100 MOVE_COST = 1 def initialize @energy = MAX_ENERGY @health = MAX_HEALTH end # Returns nil if agent's energy has been expended. # Otherwise, return the coordinate to move to. def moveFrom(coor) if coor.is_a? Coor3D to = coor.dup to.randomChange(speedFactor) end # XXX Energy depletion as it is here results in all agents dying by # XXX iteration 100 and moving slowly enough that no human succumbs to # XXX zombification. Addition of food may solve this problem. #@energy -= MOVE_COST # If we've expended all energy, this agent need to die. if @energy <= 0 nil else to end end def to_s "E: #@energy; H: #@health" end # Generate a factor in the range 0...10 based on current stats. def speedFactor Integer((@energy + @health) / (MAX_HEALTH + MAX_ENERGY)) * 10 end end class Zombie < Agent @@count = 0 def Zombie.decrement @@count -= 1 end def initialize super @@count += 1 # Zombies, by nature, have no health and cannot gain health. This also # serves to cripple their movement speed. # ----- # NOTE Value of 0 relies on speedFactor being additive not multiplicative, # NOTE otherwise the zombie will never go anywhere. @health = 0 @health.freeze end def Zombie.report puts "There are #@@count zombies in the world." end end class Human < Agent # % chance, after all other factors considered, human will become zombie # during an encounter. ZOMBIFICATION_CHANCE = 0.3 @@count = 0 def Human.decrement @@count -= 1 end def initialize super @@count += 1 end # Fighting should be a function of energy, health, number of enemies # (zombies) number of allies (other humans at the same location), and # some dumb luck. If all of these factors combine to be less than some # predetermined value, then the human dies and becomes a zombie. # # Actual mechanics of that combination are up for debate. For now, just # deal with Lady Luck. # # Evaluates to false if Human lost fight, true otherwise. def fight(zombies, humans=1) if rand < ZOMBIFICATION_CHANCE false else true end end def Human.report puts "There are #@@count humans in the world." end end
require("minitest/autorun") require("minitest/rg") require_relative("../dice") class TestDice < MiniTest::Test def setup @dice = Dice.new(6) end def test_how_many_sides assert_equal(6, @dice.sides) end def test_random_roll range = 1..6 assert_equal(true, range.include?(@dice.random_roll())) end end
class AddUpdateCounterToLogTimes < ActiveRecord::Migration def change add_column :log_times, :update_counter, :integer, default: 0 end end
class VideoGame < ApplicationRecord belongs_to :user scope :for_user_and_followed, ->(user) { user_ids = [user.id] + user.following.pluck(:id) where(user_id: user_ids) } end
require('pg') require('minitest/autorun') require('minitest/emoji') require_relative('../db/SqlRunner.rb') require_relative('../models/burger_eatery.rb') require_relative('../models/burger.rb') class TestBurger < Minitest::Test def setup # Table will be dropped and then remade from scratch for every test SqlRunner.reset_table burger_eatery_name1 = 'Big Gulp' burger_eatery_name2 = 'Munch & Crunch' @burger_eatery1 = BurgerEatery.new('name' => burger_eatery_name1) @burger_eatery2 = BurgerEatery.new('name' => burger_eatery_name2) @burger_eatery1.save @burger_eatery2.save burger1_name = 'Chewtastic' burger2_name = 'Greasetrough' @burger1 = Burger.new('name' => burger1_name, 'burger_eatery_id' => @burger_eatery2.id) @burger2 = Burger.new('name' => burger2_name, 'burger_eatery_id' => @burger_eatery2.id) end def test_database_access assert(true) # Table can be accessed without error end def test_table sql = 'SELECT * FROM burgers' results = SqlRunner.run(sql) assert_equal(PG::Result, results.class) # The table returns results assert_nil(results.first) # Table is empty end def test_table_columns sql = "SELECT column_name FROM information_schema.columns WHERE table_name='burgers'" results = SqlRunner.run(sql) assert_equal( [{ 'column_name' => 'id' }, { 'column_name' => 'name' }, { 'column_name' => 'burger_eatery_id' }], results.to_a ) # Table has expected column names end def test_class_initialize_and_readers # Class instance initialised with name assert_equal('Chewtastic', @burger1.name) # Class does not assign a value to id by default assert_nil(@burger2.id) end ## Tests are still set up for burger_eateries def test_class_create # Before being saved, id should be accessible but nil assert_nil(@burger1.id) # Before being saved, id should be accessible but nil assert_nil(@burger2.id) @burger1.save @burger2.save # When saved, object instance is updated with new id assert_equal(1, @burger1.id) # When saved, BIGSERIAL incraments ids as expected assert_equal(2, @burger2.id) sql = 'SELECT * FROM burgers' results = SqlRunner.run(sql) # First entry has the name of Big Gulp assert_equal('Chewtastic', results.first['name']) # Second entry has an id of 2 assert_equal(2, results[1]['id'].to_i) # Should return nil assert_nil(@burger_eatery1.save) end def test_class_read # Table is empty assert_equal(0, Burger.all.size) # Table is empty arry assert_equal([], Burger.all) @burger1.save # Table has one entry assert_equal(1, Burger.all.size) # First entry is the first entry is a tautology assert_equal(@burger1.id, Burger.all.first.id) assert_equal(@burger1.name, Burger.all.first.name) @burger2.save # Table has two entries assert_equal(@burger2.id, Burger.all[1].id) assert_equal(@burger2.name, Burger.all[1].name) # Table has two entries assert_equal(2, Burger.all.size) # First entry has an id of 1 assert_equal(1, Burger.all.first.id) # Last entry has a name of Munch & Crunch assert_equal('Greasetrough', Burger.all.last.name) end def test_class_update @burger1.save # Name is Chewtastic before update assert_equal('Chewtastic', Burger.all.first.name) @burger1.name = 'Mashum' @burger1.update assert_equal('Mashum', Burger.all.first.name) assert_nil(@burger1.update) end def test_class_delete @burger1.save @burger2.save # There should be 2 entries assert_equal(2, Burger.all.size) Burger.delete(2) # There should be 1 entry after deleting assert_equal(1, Burger.all.size) # Delete should return nothing assert_nil(BurgerEatery.delete(1)) end end
class Vehicle @wheels = 0 @@wheels = 0 @@count = 0 def self.wheels @wheels end def self._wheels @@wheels end def self.count @@count end def initialize @@count += 1 end def description; end def self.register(vin) end end class Car < Vehicle @wheels = 4 @@wheels = 4 def initialize(colour = 'white') @colour = colour end attr_reader :colour def color @colour end def self.register(vin) super end end Motorbike = Class.new(Vehicle) do @wheels = 2 @@wheels = 2 def self.register(vin) super end end # class Motorbike < Vehicle # @wheels = 2 # @@wheels = 2 # # def self.register(vin) # super # end # end puts Vehicle.wheels puts Car.wheels puts Motorbike.wheels puts Vehicle._wheels puts Car._wheels puts Motorbike._wheels Car.new; Car.new; Car.new; Motorbike.new puts Vehicle.count
# # app.rb # twitter_warp # # Created by Nate Todd on 2009-07-24. # require 'rubygems' require 'sinatra' require 'init' # Set up Patron instances (https?) # Probably can just persist this before do @public_session = Patron::Session.new @public_session.timeout = 15 @public_session.base_url = "http://twitter.com/" @public_session.username = "foo" @public_session.password = "bar" end # JSON-API GET get '/*.json' do # Currently do nothing with json "json hit" end # XML-API GET get '/*.xml' do uri = params["splat"].to_s + ".xml" response = @public_session.get(uri) parse_response(response.body) end # Non-API GET - just return the response get '/*' do response = @public_session.get(params["splat"]) response.body end # Non-API POST # This code sortof works for already-authenticated posts, but login is broken # Not sure how to handle that ATM. Maybe persist the twitter session in the app somehow? post '/*' do post_data = request.env["rack.request.form_vars"] response = @public_session.post(params["splat"], post_data) redirect '/' end private # Parse the response to do whatever you want def parse_response(response) response end
class AddAvatarToDatosUsuario < ActiveRecord::Migration def change add_attachment :datos_usuario, :avatar end end
class ParticipatesController < ApplicationController before_action :authenticate_user def create event = Event.find(params[:event_id]) participate = current_user.participates.new(event_id: event.id) participate.save @event = Event.find(params[:event_id]) @participate = current_user.participates.find_by(event_id: params[:event_id]) end def destroy participate = current_user.participates.find_by(event_id: params[:event_id]) participate.destroy @event = Event.find(params[:event_id]) @participate = current_user.participates.find_by(event_id: params[:event_id]) end private #ライブ情報 def event_params params.require(:event) .permit( :id, :datetime, :title, :description, :tel, :email, :image, event_links_attributes: [ :id, :event_id, :url], event_change_histories_attributes: [ :id, :event_id, :user_id, :user_ip], event_performers_attributes: [ :id, :event_id, :performer], event_categories_attributes: [ :id, :event_id, :category] ) end #ユーザー情報 def user_params params.require(:user).permit(:id, :name, :profile_image, :uid, :email, :password) end end
=begin question 1. Method Definitions: What is an explicit return? You can generally leave out the return method in most Ruby functions. A Ruby function will automatically return the last thing evaluated, unless an explicit return comes before it. The explicit return is using the reserved key word return for returning a value. return gives you the ability to reuse values in other functions, while puts will merely print it to the screen. =end =begin question 2. Arrays: How can you add two arrays together? Concatenation is to append one thing to another. For example, concatenating the arrays [1,2,3] and [4,5,6] will give you [1,2,3,4,5,6]. This can be done in a few ways in Ruby.To do this using the concat method well do. To do this another way we can use "+" just like we would on strings and this will make a copy of the original array. array_one = [1,2,3] array_two = [4,5,6] array_concatenated = array_one.concat(array_two) output : array_concatenated = [1,2,3,4,5,6] //altering original array_concatenated = array_one + array_two output : array_concatenated = [1,2,3,4,5,6] //copy =end =begin question 3. Arrays: How to get the number of items in an array? to get the amount of items/elements in an array we can use the .length method array_one = [1,2,3] num = array_one.length output : num = 3 =end =begin question 4. Arrays: If you have nested arrays what method will turn it into a single, unnested array?? To turn a nested array into a single string you can use the .flatten method array_one = [ [1,[2],3] ] array_two = array_one.flatten output : [1, 2, 3]; =end
class Comment < ActiveRecord::Base belongs_to :item belongs_to :author, class_name: 'User' validates :body, presence: true, length: { minimum: 10 } end
class AddCityAndStateAndCountryAndCountryCodeAndCoordinatesAndAreaToUser < ActiveRecord::Migration[5.0] def change add_column :users, :city, :string add_column :users, :state, :string add_column :users, :country, :string add_column :users, :country_code, :string add_column :users, :coordinates, :string add_column :users, :area, :string end end
# frozen_string_literal: true require 'services/application_service' module Services module Purchases class FindOrCreateActivePurchase < ApplicationService include Import['repos.purchase_repo'] def call purchase = purchase_repo.active return purchase if purchase purchase_repo.create(state: 'active') end end end end
namespace :dev do task fake_restaurant: :environment do Restaurant.destroy_all 500.times do |i| Restaurant.create!(name: FFaker::Name.first_name, opening_hours: FFaker::Time.datetime, tel: FFaker::PhoneNumber.short_phone_number, address: FFaker::Address.street_address, description: FFaker::Lorem.paragraph, category: Category.all.sample, image: File.open(Rails.root.join("public/seed_img/#{rand(1..20)}.jpg")) ) end puts "have created fake restaurants" puts "now you have #{Restaurant.count} restaurants data" end task fake_user: :environment do 20.times do |i| user_name = FFaker::Name.first_name User.create!( name: user_name, email: "#{user_name}@example.com", password: "12345678", avatar: File.open(File.join(Rails.root, "public/picseed_img/#{rand(0..19)}.jpg")) ) end puts "have created fake users" puts "now you have #{User.count} users data" end task fake_comment: :environment do Restaurant.all.each do |restaurant| 3.times do |i| restaurant.comments.create!( content: FFaker::Lorem.sentence, user: User.all.sample ) end end puts "have created fake comments" puts "now you have #{Comment.count} comment data" end task fake_favorite: :environment do 500.times do Favorite.create!( user_id: User.all.ids.sample, restaurant_id: Restaurant.all.ids.sample ) end puts "have created fake favorites" puts "now you have #{Favorite.count} favorites' data" end task fake_followship: :environment do Followship.destroy_all User.all.each do |user| #where.not的用法,排除...,這裡確保不會自己加自己好友 @users = User.where.not(id: user.id).shuffle 5.times do user.followships.create!( following: @users.pop ) end end puts "have created fake followship" puts "now you have #{Followship.count} followships' data" end end
def TextField { type: "textfield", name: "address to field", value: "1antani", placeholder: "Enter BTC address", style: STYLES[:textfield].merge( # secure: true # for password fields ) } end
class Location < ActiveRecord::Base belongs_to :user #attr_accessible :address, :latitude, :longitude geocoded_by :address after_validation :geocode def self.search(query) where("blood like ?", "%#{query}%") end end
require "spec_helper" describe Lita::Handlers::BlockTeam, lita_handler: true, additional_lita_handlers: Lita::Handlers::CreateTeam do describe "block team" do it "blocks a team" do send_command "create testing team" send_command "block testing team" expect(replies.last).to eq("testing team blocked") end context "team already exists" do it "does not block any team" do send_command "block testing team" expect(replies.last).to eq("testing team does not exist") end end end describe "unblock team" do it "unblocks a team" do send_command "create testing team" send_command "block testing team" send_command "unblock testing team" expect(replies.last).to eq("testing team unblocked") end end end
class AddColumnsImagePathAndDescriptionToSellers < ActiveRecord::Migration def change add_column :sellers, :image_path, :text add_column :sellers, :description, :text end end
module Fog module Compute class ProfitBricks class Real # Create a new user under a particular contract. # # ==== Parameters # * options<~Hash>: # * firstname<~String> - Required, The name of the group. # * lastname<~String> - Required, The group will be allowed to create virtual data centers. # * email<~String> - Required, The group will be allowed to create snapshots. # * password<~String> - Required, The group will be allowed to reserve IP addresses. # * administrator<~Boolean> - The group will be allowed to access the activity log. # * forceSecAuth<~Boolean> - The group will be allowed to access the activity log. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~String> - The resource's unique identifier. # * type<~String> - The type of the created resource. # * href<~String> - URL to the object's representation (absolute path). # * metadata<~Hash> - Hash containing metadata for the user. # * etag<~String> - ETag of the user. # * creationDate<~String> - A time and date stamp indicating when the user was created. # * lastLogin<~String> - A time and date stamp indicating when the user last logged in. # * properties<~Hash> - Hash containing the user's properties. # * firstname<~String> - The first name of the user. # * lastname<~String> - The last name of the user. # * email<~String> - The e-mail address of the user. # * administrator<~Boolean> - Indicates if the user has administrative rights. # * forceSecAuth<~Boolean> - Indicates if secure (two-factor) authentication was enabled for the user. # * secAuthActive<~Boolean> - Indicates if secure (two-factor) authentication is enabled for the user. # # {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v4/#create-a-user] def create_user(options = {}) user = { :properties => options } request( :expects => [202], :method => 'POST', :path => "/um/users", :body => Fog::JSON.encode(user) ) end end class Mock def create_user(options = {}) response = Excon::Response.new response.status = 202 user_id = Fog::UUID.uuid user = { 'id' => user_id, 'type' => 'user', 'href' => "https=>//api.profitbricks.com/rest/v4/um/users/#{user_id}", 'metadata' => { 'etag' => '26a6259cc0c1dae299a5687455dff0ce', 'creationDate' => '2017-05-22T08:15:55Z', 'lastLogin' => '', }, 'properties' => { 'firstname' => options[:firstname], 'lastname' => options[:lastname], 'email' => options[:email], 'password' => options[:password], 'administrator' => options[:administrator], 'forceSecAuth' => options[:force_sec_auth] } } data[:users]['items'] << user response.body = user response end end end end end
class Question < ActiveRecord::Base has_many :user_ques has_many :users, through: :user_ques end
require 'spec_helper' describe 'datadog_checks::default' do subject { ChefSpec::Runner.new.converge(described_recipe) } let(:datadog_checks_run) { ChefSpec::Runner.new.converge(described_recipe) } it 'creates template for http checks' do expect(datadog_checks_run).to create_template('/etc/dd-agent/conf.d/http_check.yaml') .with_variables( {:instances=>[{"name"=>"app_name", "url"=>"app_url"}, {"name"=>"app_name_with_password", "url"=>"app_url", "username"=>"username", "password"=>"password"}]} ) end it 'creates template for process checks' do expect(datadog_checks_run).to create_template('/etc/dd-agent/conf.d/process.yaml') .with_variables( { :instances=>["process"] }) end it "ensures datadog directories exist" do expect(datadog_checks_run).to create_directory("/etc/dd-agent") expect(datadog_checks_run).to create_directory("/etc/dd-agent/conf.d") end end
shared_examples_for 'API Authenticable' do |method, url, params| let(:access_token) { create(:access_token) } context 'unauthorized' do it 'returns 401 status if no access token' do xhr method, url, format: :json expect(response).to have_http_status(401) end it 'returns 401 status if access token is incorrect' do xhr method, url, format: :json, access_token: '1234' expect(response).to have_http_status(401) end end context 'authorized' do before(:each) do params||={} xhr method, url, {format: :json, access_token: access_token.token}.merge(params) end it 'returns response' do expect(response).to be_success end end end
# frozen_string_literal: true class Season < ApplicationRecord include OperatorAccessor has_paper_trail belongs_to :anime has_many :melodies, dependent: :destroy has_many :advertisements, dependent: :destroy has_many :tagged_seasons, dependent: :destroy validates :phase, presence: true, uniqueness: { scope: :anime_id }, numericality: { only_integer: true, greater_than_or_equal_to: 1, allow_nil: true } validates :previous_name, :behind_name, length: { maximum: Settings.season.name.maximum_length } def self.airing(date) where('seasons.start_on <= ?', date) .where('seasons.end_on >= ? or seasons.end_on is null', date) end def anime_advertisements Advertisement.where(id: anime.advertisements.pluck(:id).sample) end end
class SageoneApiSigner # Class to generate the signature base for generating the actual signature. # The string value (#to_s) of this class will be used as the `key` value in `OpenSSL::HMAC.digest(digest, key, data)` class SignatureBase include SageoneApiSigner::PercentEncoder attr_reader :request_method, :uri, :body_params, :nonce def initialize(request_method, uri, body_params, nonce) @request_method = request_method @uri = uri @body_params = body_params @nonce = nonce end # Returns the signature base, that will be used for generating the actual signature def to_s @signature_base_string ||= [ request_method, percent_encode(base_url), percent_encode(parameter_string), percent_encode(nonce) ].join('&') end private def parameter_string @parameter_string ||= ( Hash[url_params.merge(body_params).sort].to_query.gsub('+', '%20') ) end # Return the base URL without query string and fragment def base_url @base_url ||= [ uri.scheme, '://', uri.host, uri_port_string, uri.path ].join end def url_params @url_params ||= Hash[URI::decode_www_form(uri.query || '')] end def uri_port_string uri.port == uri.default_port ? "" : ":#{uri.port}" end end end
class SessionsController < ApplicationController def create #login user = User.find_by(:email => params[:user][:email]) if user && user.authenticate(params[:user][:password]) created_jwt = encode_token(id: user.id) cookies.signed[:jwt] = {value: created_jwt, httponly: true} render json: user else render json: { error: "error logging in" }, status: 404 end end def destroy cookies.delete(:jwt) render json: { message: "Successfully logged out" } end def currentUser if logged_in? render json: serializer_user(current_user) else render json: {error: "user not logged in."} end end end
class Review < ActiveRecord::Base validates :author, :presence => true validates :text, :presence => true belongs_to :movie end
#encoding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jekyll-gh-pages/version' Gem::Specification.new do |gem| gem.name = "jekyll-gh-pages" gem.version = JekyllGhPages::VERSION gem.authors = ["Ryo Chikazawa"] gem.email = ["chikathreesix@gmail.com"] gem.summary = %q{Deploy Jekyll sites to Github Pages easily} gem.description = %q{Inspired by middleman-gh-pages, Jekyll Github Pages helps deploying Jekyll site to github gh-pages branch. However Github Pages basically supports Jekyll, they have a lot of restrictions. So you might want to use github pages just as a host for static pages. This gem provides rake tasks that automate the process of deploying a Jekyll site to Github Pages.} gem.homepage = "https://github.com/chikathreesix/jekyll-gh-pages" gem.license = 'MIT' gem.files = `git ls-files -z`.split("\x0") gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency 'rake', '> 0.9.3' gem.add_development_dependency "bundler", "~> 1.6" gem.add_development_dependency "rspec" end
# frozen_string_literal: true coverage_config = proc do add_filter "/test/" end if ENV["CI"] # No doing coverage badge at the moment.. Coveralls stopped working right after switching to # Github actions, and its doc is too bad for me to figure it out. A few hours lost is more # than I wanted to put into this. else require "deep_cover" end require_relative "support/load_test_env" require "minitest/autorun" require_relative "support/custom_asserts" class MyMinitestSpec < Minitest::Spec include TestHelpers # Annoying stuff for tests to run in transactions include ActiveRecord::TestFixtures if ActiveRecord.gem_version >= Gem::Version.new("5.0") self.use_transactional_tests = true def run_in_transaction? self.use_transactional_tests end else self.use_transactional_fixtures = true def run_in_transaction? self.use_transactional_fixtures end end if %w(1 true).include?(ENV["SQL_WITH_FAILURES"]) before do @prev_logger = ActiveRecord::Base.logger @my_logged_string_io = StringIO.new @my_logger = Logger.new(@my_logged_string_io) @my_logger.formatter = proc do |severity, datetime, progname, msg| "#{msg}\n" end ActiveRecord::Base.logger = @my_logger end after do |test_case| ActiveRecord::Base.logger = @prev_logger next if test_case.passed? || test_case.skipped? @my_logged_string_io.rewind logged_lines = @my_logged_string_io.readlines # Ignore lines that are about the savepoints. Need to remove color codes first. logged_lines.reject! { |line| line.gsub(/\e\[[0-9;]*m/, "")[/\)\s*(?:RELEASE )?SAVEPOINT/i] } logged_string = logged_lines.join if logged_string.present? exc = test_case.failure orig_message = exc.message exc.define_singleton_method(:message) do "#{orig_message}\n#{logged_string}" end end end end end # Use my custom test case for the specs Minitest::Spec.register_spec_type(//, MyMinitestSpec)
class Score < ApplicationRecord validates :player_name, :score, presence: true belongs_to :word end
require 'open-uri' require 'json' class GamesController < ApplicationController def new @letters = [] 10.times { @letters << [*"A".."Z"].sample } @letters end def score # raise @attempt = params[:attempt] @letters = params[:letters] @start_time = DateTime.parse(params[:time]) @end_time = Time.now run_game(@attempt, @letters, @start_time, @end_time) if session[:total].nil? session[:total] = @score else session[:total] += @score end end def in_the_grid?(attempt, letters) attempt.upcase.split('').all? do |letter| attempt.upcase.count(letter) <= letters.count(letter) end end def english?(attempt) url = "https://wagon-dictionary.herokuapp.com/#{attempt.downcase}" answer_serialized = open(url).read answer = JSON.parse(answer_serialized) answer["found"] end def run_game(attempt, letters, start_time, end_time) if !english?(attempt) @message = "Not an english word" elsif !in_the_grid?(attempt, letters) @message = "The given word is not included in the given letters" else return compute_score(attempt, letters, start_time, end_time) end end def compute_score(attempt, letters, start_time, end_time) @time = (end_time - start_time) length = 1 / (letters.length - attempt.length).to_f @score = ((1 /@time) * length * 10000).to_i @message = "Well done" end end
json.array!(@song_artists) do |song_artist| json.extract! song_artist, :id, :song_id, :artist_id, :role_slug json.url song_artist_url(song_artist, format: :json) end
class TreeNode attr_reader :children, :parent, :value def initialize(value) @value = value @parent = nil @children = [] end def parent=(new_parent) previous_parent = self.parent previous_parent.children.delete(self) if previous_parent new_parent.children << self if new_parent @parent = new_parent end def add_child(child) child.parent = self end def remove_child(child) raise "Child not present" if !children.include?(child) child.parent = nil end def dfs(target_value) return self if value == target_value children.each do |child| result = child.dfs(target_value) return result if result end nil end def my_bfs(target) current_level = [self] until current_level.empty? found = current_level.select { |node| node.value == target } if !found.empty? # always truthy return found[0] else current_level = current_level.map { |node| node.children }.flatten end end end def bfs(target) queue = Queue.new queue.enqueue(self) until queue.length == 0 node = queue.dequeue return node if node.value == target node.children.each { |child| queue.enqueue(child) } end end def trace_path path = [self] current_node = self while current_node.parent path.unshift(current_node.parent) current_node = current_node.parent end path.map(&:value) end end class Queue attr_accessor :store def initialize @store = [] end def dequeue self.store.shift end def enqueue(el) self.store.push(el) end def length self.store.length end end
# frozen_string_literal: true require "concurrent/map" module Dry module Types class Constructor < Nominal # Function is used internally by Constructor types # # @api private class Function # Wrapper for unsafe coercion functions # # @api private class Safe < Function def call(input, &block) @fn.(input, &block) rescue ::NoMethodError, ::TypeError, ::ArgumentError => e CoercionError.handle(e, &block) end end # Coercion via a method call on a known object # # @api private class MethodCall < Function @cache = ::Concurrent::Map.new # Choose or build the base class # # @return [Function] def self.call_class(method, public, safe) @cache.fetch_or_store([method, public, safe]) do if public ::Class.new(PublicCall) do include PublicCall.call_interface(method, safe) define_method(:__to_s__) do "#<PublicCall for :#{method}>" end end elsif safe PrivateCall else PrivateSafeCall end end end # Coercion with a publicly accessible method call # # @api private class PublicCall < MethodCall @interfaces = ::Concurrent::Map.new # Choose or build the interface # # @return [::Module] def self.call_interface(method, safe) @interfaces.fetch_or_store([method, safe]) do ::Module.new do if safe module_eval(<<~RUBY, __FILE__, __LINE__ + 1) def call(input, &block) # def call(input, &block) @target.#{method}(input, &block) # @target.coerve(input, &block) end # end RUBY else module_eval(<<~RUBY, __FILE__, __LINE__ + 1) def call(input, &block) # def call(input, &block) @target.#{method}(input) # @target.coerce(input) rescue ::NoMethodError, ::TypeError, ::ArgumentError => error # rescue ::NoMethodError, ::TypeError, ::ArgumentError => error CoercionError.handle(error, &block) # CoercionError.handle(error, &block) end # end RUBY end end end end end # Coercion via a private method call # # @api private class PrivateCall < MethodCall def call(input, &block) @target.send(@name, input, &block) end end # Coercion via an unsafe private method call # # @api private class PrivateSafeCall < PrivateCall def call(input, &block) @target.send(@name, input) rescue ::NoMethodError, ::TypeError, ::ArgumentError => e CoercionError.handle(e, &block) end end # @api private # # @return [MethodCall] def self.[](fn, safe) public = fn.receiver.respond_to?(fn.name) MethodCall.call_class(fn.name, public, safe).new(fn) end attr_reader :target, :name def initialize(fn) super @target = fn.receiver @name = fn.name end def to_ast [:method, target, name] end end class Wrapper < Function # @return [Object] def call(input, type, &block) @fn.(input, type, &block) rescue ::NoMethodError, ::TypeError, ::ArgumentError => e CoercionError.handle(e, &block) end alias_method :[], :call def arity 2 end end # Choose or build specialized invokation code for a callable # # @param [#call] fn # @return [Function] def self.[](fn) raise ::ArgumentError, "Missing constructor block" if fn.nil? if fn.is_a?(Function) fn elsif fn.respond_to?(:arity) && fn.arity.equal?(2) Wrapper.new(fn) elsif fn.is_a?(::Method) MethodCall[fn, yields_block?(fn)] elsif yields_block?(fn) new(fn) else Safe.new(fn) end end # @return [Boolean] def self.yields_block?(fn) *, (last_arg,) = if fn.respond_to?(:parameters) fn.parameters else fn.method(:call).parameters end last_arg.equal?(:block) end include ::Dry::Equalizer(:fn, immutable: true) attr_reader :fn def initialize(fn) @fn = fn end # @return [Object] def call(input, &block) @fn.(input, &block) end alias_method :[], :call # @return [Integer] def arity 1 end def wrapper? arity.equal?(2) end # @return [Array] def to_ast if fn.is_a?(::Proc) [:id, FnContainer.register(fn)] else [:callable, fn] end end # @return [Function] def >>(other) f = Function[other] Function[-> x, &b { f.(self.(x, &b), &b) }] end # @return [Function] def <<(other) f = Function[other] Function[-> x, &b { self.(f.(x, &b), &b) }] end end end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def authenticate_user! unless user_signed_in? flash[:notice] = "Please sign in" redirect_to new_session_path end end helper_method :authenticate_user! def user_signed_in? current_user.present? end helper_method :user_signed_in? def current_user @current_user ||= User.find_by_id(session[:user_id]) end helper_method :current_user end
class Movie < ActiveRecord::Base validates_presence_of :title, length: { minimum: 1, maximum: 50 } validates_presence_of :format, length: { minimum: 1, maximum: 499 } validates :length, presence: true, numericality: true validates :release_year, presence: true, numericality: true, inclusion: { in: 1800..2100 } validates :rating, presence: true, numericality: true end
class App::MentorsController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :show] semantic_breadcrumb 'Mentors', :mentors_path # mentors_path GET /mentors def index @mentors = Mentor.where.not(recruited_at: nil, authorized_at: nil) end # mentor_path GET /mentors/:id def show @mentor = Mentor.find(params[:id]) if @mentor.recruited_at? && @mentor.authorized_at? semantic_breadcrumb "#{@mentor.user.name} 선생님" else redirect_to mentors_path end end end
# frozen_string_literal: true require 'progress_counter' namespace :sphinx do desc "Enqueue indexation of tables" task enqueue: :environment do |_task, args| klasses_index = args.to_a indices = ThinkingSphinx::RakeInterface.new.rt.send(:indices) indices.select! { |ind| klasses_index.include?(ind.model.name) } if klasses_index.any? indices.each do |index| scope = index.scope total = scope.count if total.zero? puts "Skipping indexation of #{index.model} because no record to index." next end puts "Enqueueing indexation of #{index.model}" progress = ProgressCounter.new(total) # As we enqueue, we only need the :id scope.select(:id).find_in_batches(batch_size: 1000) do |batch| batch.each do |record| SphinxIndexationWorker.perform_later(record) end progress.call(increment: batch.size) end puts end end end
FactoryGirl.define do sequence :name do |n| "name_#{n}" end sequence :email do |n| "#{n}@gmail.com" end factory :user do name { FactoryGirl.generate :name } email { FactoryGirl.generate :email } password '123456' password_confirmation '123456' end #factory :session do #user { FactoryGirl.generate :email } #user_id { FactoryGirl.generate : } #end #factory :session do #user { FactoryGirl.generate :email } #association :user, :factory => :user #end factory :project do name { FactoryGirl.generate :name } end factory :ticket do name { FactoryGirl.generate :name } description 'Test' association :user, :factory => :user association :project, :factory => :project status 'New' end factory :comment do title 'No subject' body 'abc' association :user, :factory => :user association :ticket, :factory => :ticket end end
class AddLikesCountToUserImages < ActiveRecord::Migration def change add_column :user_images, :likes_count, :integer, default: 0 end end
class AddLocationToTrainings < ActiveRecord::Migration def change add_column :trainings, :location, :string end end
Devise.setup do |config| config.authentication_keys = [:login] config.case_insensitive_keys = [:login] end
require 'aepic' require 'responders' module Aepic module Concerns module Responder extend ActiveSupport::Concern include Responders::HttpCacheResponder private def do_http_cache? get? && (@http_cache != false) && persisted? && resource_item.respond_to?(:updated_at) end # @return [Boolean] def do_http_cache! resource_item = resource_item.object if resource_item.is_a?(Draper::Decorator) last_modified = resource_item.try(:updated_at) || Time.at(0) etag = resource_collection resource_collection.each do |resource| resource = resource.object if resource.is_a?(Draper::Decorator) last_modified = resource.updated_at if resource.updated_at > last_modified end if resource_collection.length > 1 !controller.stale?(etag: etag, last_modified: last_modified) end # @return [Array] array of resources def resource_collection @resource_collection ||= resource.is_a?(Array) ? resource : resources end # @return [Object] just one resource def resource_item @resource_item ||= resource.is_a?(Array) ? resource.last : resource end end end end
class SnapshotsController < ApplicationController def index redirect_to :action => :show end def show # snapshot if params[:id] @snapshot = Snapshot.find(params[:id]) elsif params[:match_id] @snapshot = Match.find(params[:match_id]).last_snapshot elsif params[:player_id] @snapshot = Player.find(params[:player_id]).snapshots.last else @snapshot = Snapshot.last end #snapshots if Snapshot.count == 0 render :text => "<div style='padding:15px'>No Snapshots fetched yet.</div>", :layout => "application" return end if params[:d] @date = DateTime.civil(params[:y].to_i, params[:m].to_i, params[:d].to_i, 0, 0, 0) else @date = @snapshot.created_at end @match = Match.find(params[:match_id]) if params[:match_id] @player = Player.find(params[:player_id]) if params[:player_id] @snapshots = Snapshot.find_in_day(@date, :match => @match, :player => @player) @snapshots_by_hour = Snapshot.by_hour(@snapshots) @has_next_day = Snapshot.last.created_at > @date.tomorrow.beginning_of_day @has_previous_day = Snapshot.first.created_at < @date.yesterday.end_of_day end def reset Snapshot.delete_all Player.delete_all Map.delete_all redirect_to snapshots_path end end
class OrganizationLogo < ActiveRecord::Base belongs_to :organization has_attachment :storage => :file_system, :size => (1..256.kilobytes), :path_prefix => 'public/images/organizations' validates_as_attachment end
class AddIsLimitedToSharePrizes < ActiveRecord::Migration def change add_column :share_prizes, :is_limited, :integer,:default => 0 end end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) Gem::Specification.new do |s| s.name = %q{acts_as_optimistic_lock} s.version = "0.0.7" s.authors = ["Mitsuhiro Shibuya"] s.description = %q{Optimistic Locking for Rails ActiveRecord models.} s.email = %q{mit.shibuya@gmail.com} s.extra_rdoc_files = [ "README" ] s.files = Dir.glob("{config,lib}/**/*") + %w(MIT-LICENSE README) s.homepage = %q{https://github.com/greenbell/acts_as_optimistic_lock} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{Optimistic Locking for Rails ActiveRecord models} s.add_runtime_dependency 'activerecord', [">= 3.0", "< 5"] s.add_runtime_dependency 'activesupport', [">= 3.0", "< 5"] s.add_development_dependency 'rails' s.add_development_dependency 'rspec', "~> 3.0" s.add_development_dependency 'factory_girl_rails', "~> 4.0" s.add_development_dependency 'database_cleaner' end
# these routes will help cut down the nav repetition in our steps # page 109 PageObject::PageFactory.routes = { # this is one route. you can have many # providing args to a page: [HomePage, :select_puppy, 'Brook'], :default => [ [HomePage, :select_puppy], [DetailsPage, :add_to_cart], [ShoppingCartPage, :proceed_to_checkout], [CheckoutPage, :checkout] ] }
require_relative 'errors/constraint_error' class ContractValidator def validate(input_hash, contract) result = contract.call(input_hash) return result.to_h if result.success? raise ConstraintError.new(result.errors.to_h, *contract.validated_classes) end def errors(input_hash, contract) contract.call(input_hash).errors.to_h end end
require_relative 'logger_decorator' module EDRTest module Logger class NetworkActivityDecorator < LoggerDecorator def initialize(logger) @logger = logger end def build_log(destination_info, source_info, bytes_sent, tx_protocol, pid) { destination_address: destination_info[:addr], destination_port: destination_info[:port], source_address: source_info[:addr], source_port: source_info[:port], amt_data_sent: bytes_sent, transfor_protocol: tx_protocol }.merge!(@logger.build_log(pid)) end end end end
class Hiragana < ApplicationRecord MAX_CHAR_NUM = 8 HIRAGANA = [*"ぁ".."ん"] - ["ぁ", "ぃ", "ぅ", "ぇ", "ぉ", "ゎ", "ゑ", "ゐ", "を"] def self.view(animal) #名前を一文字ずつ分割して配列としてname_arrayに代入 name_array = animal[:name].chars.uniq # 重複を防ぐためにHIRAGANAからname_arrayを除く unique_hiragana_ary = HIRAGANA - name_array # 正解の文字とランダムな文字をlistsに代入 random_char_num = MAX_CHAR_NUM - name_array.length lists = name_array + unique_hiragana_ary.sample(random_char_num) # Hiraganaモデルから画像urlのリンクを取得 hiragana_list = Hiragana.where(name: lists) # shuffleでランダムに並び替え hiragana_list.shuffle end end
require_relative "code" class Mastermind def initialize(n) @secret_code = Code.random(n) end def print_matches(guess_code) puts @secret_code.num_exact_matches(guess_code) puts @secret_code.num_near_matches(guess_code) end def ask_user_for_guess puts 'Enter a code' guess = Code.from_string(gets.chomp) print_matches(guess) return @secret_code == guess end end # Done in 15m44s
class CreateMains < ActiveRecord::Migration def change create_table :mains do |t| t.integer :player_id t.integer :character_id t.timestamps null: false end add_index :mains, :player_id, unique: true add_index :mains, :character_id, unique: true end end
task :default => :get_up task :get_up do puts 'Getting up...' end task :teeth => :get_up do puts 'Cleaning teeth...' end task :exercises => :get_up do puts 'Shake your body!!!' end task :breakfast => [:teeth, :exercises] do puts 'Heaving breakfast...' end task :get_to_work => [:breakfast, :get_in_the_car] do puts 'On my way' end task :get_in_the_car do puts 'I\'m in and ready to go' end desc 'task to clean teeth' task :clean_teeth => :get_up do puts 'Cleaning teeth...' end # $ rake get_to_work # Getting up... # Cleaning teeth... # Shake your body!!! # Heaving breakfast... # I'm in and ready to go # On my way namespace :home do task :get_to_work => [:breakfast, :get_in_the_car] do puts 'On my way' end task :get_in_the_car do puts 'I\'m in and ready to go' end end namespace :work do task :get_to_meeting do puts 'Boring...' end end task :with_args, [:first_arg, :second_arg] do |t, args| puts args.first_arg puts args.second_arg puts t end # to call namespaces: # rake home:get_up namespace :main do task :run_all do sh 'cucumber -t @reg -f junit -o reports/ -f html -o reports/reports.html' end task :registration do sh 'cucumber -t @reg' end task :reg_as_dep => [:regestration] do sh 'cucumber -t @s1' end end task :test do sh 'ruby tasks/test1_main_data_classes/test1_main_data_classes.rb' end task :rspec_test1 do # sh 'cd tasks/test11_rspec' sh 'rspec spec/lib/rspec_task2/rspec_testredmine.rb --format documentation --tag aaa' # sh 'rspec spec/lib/rspec_task2/rspec_testredmine.rb --format documentation --tag ~aaa' # sh 'rspec spec/lib/rspec_task2/rspec_testredmine.rb ---format documentation --out report.txt --tag aaa' end #cucumber --format junit --out reports/ # firewall-cmd --zone=public --add-port=8080/tcp --permanent # firewall-cmd --zone=public --add-service=http --permanent # firewall-cmd --reload # firewall-cmd --list-all
require 'rspec' require 'rules/base' module Rules describe Base do describe 'processing' do let(:criteria) { { minimum_daily_hours: 0.0, maximum_daily_hours: 0.0, minimum_weekly_hours: 0.0, maximum_weekly_hours: 0.0, saturdays_overtime: true, sundays_overtime: true, holidays_overtime: true, decimal_place: 2, billable_hour: 0.25, closest_minute: 8.0, region: "ca_on", scheduled_shift: OpenStruct.new(started_at: DateTime.parse("2018-01-01 6:00am"), ended_at: DateTime.parse("2018-01-01 4:30pm")) } } let(:base) { Base.new(OpenStruct.new(attributes_for(:activity)), criteria) } subject { base.process_activity } it "should calculate billable, regular and total to be the same as total hours" do expect(subject.id).to eq(1) expect(subject.regular).to eq(1.0) expect(subject.overtime).to eq(0.0) expect(subject.total).to eq(1.0) end it "should store the criteria of the activity" do expect(base.decimal_place).to eq(2) end end end end
class Entry < ActiveRecord::Base belongs_to :user has_many :comments, dependent: :destroy default_scope -> { order(created_at: :desc) } validates :user_id, presence: true validates :title, presence: true, length: { maximum: 140 } validates :content, presence: true, length: { maximum: 140 } def feed_comment user_id = "SELECT user_id FROM comments WHERE entry_id = :entry_id" Comment.where("user_id IN (#{user_id}) ") end end
class User < ApplicationRecord has_secure_password has_many :roles, dependent: :destroy has_many :commit_adjustments, dependent: :destroy has_many :orders, dependent: :destroy has_many :items, through: :orders validates :email, uniqueness: { case_sensitive: false } end
class CreateUsers < ActiveRecord::Migration[5.0] def change create_table :users do |t| t.string :name t.string :email t.string :password_digest t.string :resume t.string :sq1 t.string :sq2 t.string :sq3 t.string :sq4 t.string :sq5 t.timestamps end end end
class UsersController < ApplicationController before_action :ensure_correct_user, only: %i[destroy] def new @user = User.new end def create @user = User.new(user_params) @user.save end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.update(user_params) redirect_to user_path(@user.id) end def show if current_user @user = current_user # 自分の投稿を表示する @events = Event.default.where(user_id: @user.id) # ユーザーがフォローしている芸人一覧を取得 @geinins = Geinin.default.where(followings: { user_id: @user.id } ) else redirect_to lp_url end end def ensure_correct_user if current_user.id != params[:id].to_i flash[:notice] = I18n.t('errors.messages.no_authorization') redirect_to user_path(@user.id) end end private def user_params params.require(:user).permit(:id, :name, :profile_image, :uid, :email, :password) end end
class CadastroPlataforma < SitePrism::Page #@dados = Dados.new element :campo_Nome, '#Nome' element :campo_email, '#input9' element :campo_telefone, '#telefone' element :campo_cpf, '#cpf' element :campo_senha, '#Password' element :campo_repita_Senha, '#ConfirmPassword' element :botao_cadastro, 'input[value="Cadastrar"]' def preencherCampos(campos) #cademail = @dados.lerDadosEmail campo_Nome.set campos [:Nome] campo_email.set campos [:Email] campo_telefone.set campos [:Telefone] campo_cpf.set campos [:CPF] campo_senha.set campos [:Senha] campo_repita_Senha.set campos [:Repita_Senha] @email = campos [:Email] @senha = campos [:Senha] end def cadastrar botao_cadastro.click dados = Dados.new dados.gravandoDadosEmail(@email) dados.gravandoDadosSenha(@senha) end end
FactoryGirl.define do factory :educational_qualification do institution "MyString" certificate "MyString" enrolled_at "2017-03-28 22:46:42" completed_at "2017-03-28 22:46:42" employee nil end end
# Go ahead and try the following methods: # .include?(value) => true or false a = [ "a", "b", "c" ] a.include?("b") #=> true a.include?("z") #=> false # .last => returns the last object in range a = [ "w", "x", "y", "z" ] a.last #=> "z" a.last(2) #=> ["y", "z"] # .max => returns the maximum value in range a = [ "w", "x", "y", "z" ] a.last #=> "z" a.last(2) #=> ["y", "z"] # .min => returns the minimum value in range a = %w(albatross dog horse) a.min #=> "albatross" a.min { |a, b| a.length <=> b.length } #=> "dog"
############### #joels solution ############### class Binary def initialize(str) @binary_string = str end def to_i exponent = 0 result = 0 @binary_string.split('').reverse.each do |bit| result += (2 ** exponent) if bit == '1' exponent += 1 end result end end b1 = Binary.new('1001') puts b1.to_i b2 = Binary.new('0b110110110110101') puts b2.to_i # irb(main):001:0> 0b1011001 # => 89 # irb(main):002:0> 0b1101 # => 13 # irb(main):003:0> 0b110110110110101 # => 28085 ############ #my solution ############ binary = 110110110110101 # split to array components = binary.to_s.split(//) # throw and error if not a binary number raise "not a binary string" unless components.all? { |value| value == '0' || value == '1' } # iterate through the rest of the digits sum = 0 components.each do |value| sum = (( sum * 2 ) + value.to_i) end puts sum
module Cacheable extend ActiveSupport::Concern included do def cached_metadata(pid: nil, provider_id: nil) Rails.cache.fetch("metadata/#{pid}") do case provider_id when "datacite" then Bolognese::Datacite.new(id: pid) when "crossref" then Bolognese::Crossref.new(id: pid) end end end end module ClassMethods def cached_event_count Rails.cache.fetch("event_count", expires_in: 1.hour) do Event.count end end def cached_event_state_count(state) Rails.cache.fetch("event_state_count/#{state}", expires_in: 1.hour) do Event.where(aasm_state: state).count end end def cached_event_source_token_count(source_token) Rails.cache.fetch("event_source_token_count/#{source_token}", expires_in: 1.hour) do Event.where(source_token: source_token).count end end def cached_event_source_token_state_count(source_token, state) Rails.cache.fetch("event_source_token_statecount/#{source_token}-#{state}", expires_in: 1.hour) do Event.where(source_token: source_token).where(aasm_state: state).count end end end end
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require 'spec_helper' require 'time' module AWS shared_examples_for "an authorize v4 request" do let(:request) { described_class.new } let(:credentials) { AWS::Core::CredentialProviders::StaticProvider.new({ :access_key_id => 'akid', :secret_access_key => 'secret', }) } let(:now) { Time.parse('2012-01-01') } before(:each) do Time.stub(:now).and_return(now) request.host = 'hostname' request.region = 'region-name' request.stub(:body).and_return('body') request.stub(:service).and_return('service-name') end context '#add_authorization!' do it 'sets the content type form-urlencoded by default' do request.headers['content-type'].should eq(nil) request.add_authorization!(credentials) request.headers['content-type'].should eq('application/x-www-form-urlencoded') end it 'populates the host header' do request.headers['host'].should eq(nil) request.add_authorization!(credentials) request.headers['host'].should eq('hostname') end it 'populates the date header' do request.headers['x-amz-date'].should eq(nil) request.add_authorization!(credentials) request.headers['x-amz-date'].should eq(now.utc.strftime("%Y%m%dT%H%M%SZ")) end it 'omits the security token header when session token not provided' do credentials.session_token.should eq(nil) request.add_authorization!(credentials) request.headers['x-amz-security-token'].should eq(nil) end it 'populates the security token header when session token is provided' do credentials.stub(:session_token).and_return('SESSION') request.add_authorization!(credentials) request.headers['x-amz-security-token'].should eq('SESSION') end it 'popualtes the authorization header' do request.headers['authorization'].should eq(nil) request.add_authorization!(credentials) request.headers['authorization'].should eq("AWS4-HMAC-SHA256 Credential=akid/20120101/region-name/service-name/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=58ba42aa064264dc8b8d056d1e1a174679d2fcfa545bb860145b23ee20342346") end it 'includes the session token in the signature when present' do credentials.stub(:session_token).and_return('SESSION') request.add_authorization!(credentials) request.headers['authorization'].should eq("AWS4-HMAC-SHA256 Credential=akid/20120101/region-name/service-name/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-security-token, Signature=c6345f040b0b32469729beb2f57fb706b133e65ef32f8bc2a18aee77c51c8991") end end end end