text
stringlengths
10
2.61M
class SearchController < ApplicationController def index query = params[:q] @movies = Movie.where('title LIKE :query OR description LIKE :query OR year_released LIKE :query', query: "%#{query}%") end end
module Goodreads class Error < StandardError; end class ConfigurationError < Error ; end class Unauthorized < Error ; end class NotFound < Error ; end end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'spec_helper' describe TwitterCldr::Tokenizers::TimespanTokenizer do describe "#tokens" do it "should return the correct list of tokens" do tokenizer = described_class.new(nil) tokenizer.tokenize("Hace {0} minutos").tap do |tokens| tokens[0].tap do |token| expect(token.value).to eq("Hace ") expect(token.type).to eq(:plaintext) end tokens[1].tap do |token| expect(token.value).to eq("{0}") expect(token.type).to eq(:pattern) end tokens[2].tap do |token| expect(token.value).to eq(" minutos") expect(token.type).to eq(:plaintext) end end end end end
module Api::V1 class BalanceController < ApplicationController before_action :authenticate_user def update balance = Balance.find_by(id: params[:id]) balance.balance = balance_params.to_i if balance.save render status: 200, json: {message: "Update Successful"} else render status: 400, json: {error: "Something went wrong"} end end private def balance_params params.require(:balance) end end end
class Expense < ActiveRecord::Base belongs_to :user has_many :categories_expenses, :dependent => :destroy has_many :categories, :through => :categories_expenses validates_presence_of :description, :amount validates_numericality_of :amount end
Rails.application.routes.draw do root to: 'pages#home' get 'about', to: 'pages#about' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :offers, only: [ :index, :show ] do resources :redemptions, only: [ :create ] end resources :restaurants, only: [ :index, :show ] do resources :check_ins, only: [ :create ] resources :reviews, only: :create resources :favorites, only: [ :create , :destroy ] end get "users/favorites", to: "users#favorites", as: "favorite" get "users/dashboard", to: "users#dashboard", as: "dashboard" get "privacy", to: "pages#privacy" # get "/restaurants/:restaurant_id/offers", to: "offers#show", as: "offers" devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' } end
# frozen_string_literal: true class FlagsController < ApplicationController before_action :bucket, only: %i[flags national signals] title!('Flags') def flags @show_birmingham = true render(:flags, layout: 'application') end def national @show_birmingham = false @generic_logo = @bucket.link('logos/ABC/png/long/tr/slogan/1000.png') render(:flags, layout: 'flags') end def tridents svg = USPSFlags::Generate.spec( fly: fly, unit: unit, scale: scale, scaled_border: params[:border].present? ) respond_to do |format| format.svg { render inline: svg } end end def intersections fly = clean_params[:fly].present? ? Rational(clean_params[:fly]) : 2048 svg = USPSFlags::Generate.intersection_spec( fly: fly, scale: scale, scaled_border: params[:border].present? ) respond_to do |format| format.svg { render inline: svg } end end def signals @letters = %w[ alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu ].map { |name| Signal.new(name, name[0], :letters) } @numerals = [ [:zero, 0], [:one, 1], [:two, 2], [:three, 3], [:four, 4], [:five, 5], [:six, 6], [:seven, 7], [:eight, 8], [:nine, 9] ].map { |name, short| Signal.new(name, short, :numbers) } @codes = %i[repeat_1 repeat_2 repeat_3 code].map { |name| Signal.new(name, nil, :codes) } render(:signals, layout: 'application') end Signal = Struct.new(:name, :short, :dir) private def clean_params params.permit(:flag_type, :format, :fly, :unit, :scale, :size, :border) end def bucket @bucket = BPS::S3.new(:static) end def fly clean_params[:fly].present? ? Rational(clean_params[:fly]) : 24 end def unit return ' ' if clean_params[:unit] == 'none' return 'in' if clean_params[:unit].blank? clean_params[:unit] end def scale return clean_params[:scale].to_i if int_scale? return clean_params[:scale].to_f if float_scale? end def int_scale? clean_params[:scale].present? && clean_params[:scale].to_i.positive? end def float_scale? clean_params[:scale].present? && clean_params[:scale].to_f.positive? end def cache_file(key); end end
# Copyright 2019 The inspec-gcp-cis-benchmark Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. title 'Ensure log metric filter and alerts exists for VPC Network Firewall rule changes' gcp_project_id = input('gcp_project_id') cis_version = input('cis_version') cis_url = input('cis_url') control_id = '2.7' control_abbrev = 'logging' control "cis-gcp-#{control_id}-#{control_abbrev}" do impact 'low' title "[#{control_abbrev.upcase}] Ensure log metric filter and alerts exists for VPC Network Firewall rule changes" desc 'It is recommended that a metric filter and alarm be established for VPC Network Firewall rule changes.' desc 'rationale', 'Monitoring for Create or Update firewall rule events gives insight network access changes and may reduce the time it takes to detect suspicious activity.' tag cis_scored: true tag cis_level: 1 tag cis_gcp: control_id.to_s tag cis_version: cis_version.to_s tag project: gcp_project_id.to_s tag nist: %w[AU-3 AU-12] ref 'CIS Benchmark', url: cis_url.to_s ref 'GCP Docs', url: 'https://cloud.google.com/logging/docs/logs-based-metrics/' ref 'GCP Docs', url: 'https://cloud.google.com/monitoring/custom-metrics/' ref 'GCP Docs', url: 'https://cloud.google.com/monitoring/alerts/' ref 'GCP Docs', url: 'https://cloud.google.com/logging/docs/reference/tools/gcloud-logging' ref 'GCP Docs', url: 'https://cloud.google.com/vpc/docs/firewalls' log_filter = 'resource.type=global AND jsonPayload.event_subtype="compute.firewalls.patch" OR jsonPayload.event_subtype="compute.firewalls.insert"' describe "[#{gcp_project_id}] VPC FW Rule changes filter" do subject { google_project_metrics(project: gcp_project_id).where(metric_filter: log_filter) } it { should exist } end google_project_metrics(project: gcp_project_id).where(metric_filter: log_filter).metric_types.each do |metrictype| describe.one do filter = "metric.type=\"#{metrictype}\" resource.type=\"global\"" google_project_alert_policies(project: gcp_project_id).where(policy_enabled_state: true).policy_names.each do |policy| condition = google_project_alert_policy_condition(policy: policy, filter: filter) describe "[#{gcp_project_id}] VPC FW Rule changes alert policy" do subject { condition } it { should exist } end end end end end
# frozen_string_literal: true module Zafira module Operations module User class RefreshToken include Concerns::Operationable def initialize(client) self.client = client end def call chain { refresh_token } chain { update_token } end private attr_accessor :client, :token def refresh_token token_response = Api::User::RefreshToken.new(client).refresh self.token = Models::ZafiraToken::Builder.new(token_response).construct return if token dam("AccessToken's refresh failed: #{token_response.inspect}") end def update_token client.environment.zafira_access_token = token.access_token client.environment.refresh_token = token.refresh_token end end end end end
desc "This task is called by the Heroku scheduler add-on" task :send_confirmation_reminders => :environment do if Date.today.wednesday? puts "Sending Emails" User.where(confirmed: false).each do |user| if EmailAddress.valid?(user.email) ConfirmationCodeMailer.confirmation_reminder_email(user).deliver user.update(reminders_sent: user.reminders_sent + 1) end end end end
class ApplicationMailer < ActionMailer::Base default from: "fab-oger@live.fr" layout 'mailer' end
class AddTimeToVacationRequests < ActiveRecord::Migration[5.2] def change add_column :vacation_requests, :starts_at, :time add_column :vacation_requests, :ends_at, :time end end
# -*- mode: ruby -*- # vi: set ft=ruby : # # Before running vagrant up: # - Ensure that necessary ssh keys are added to ssh cookbook as templates # - Ensure that the below values are correct for your project # Vagrant.configure('2') do |config| config.vm.box = 'ubuntu/xenial64' config.vm.network 'forwarded_port', guest: 80, host: 50000 config.vm.provision "chef_solo" do |chef| chef.version = '12.17.44' chef.cookbooks_path = '~/DevEnv/chef/cookbooks' chef.roles_path = '~/DevEnv/chef/roles' chef.add_role('gamedev') chef.json = { 'npm' => { 'libraries' => %w( typescript ) }, 'git' => { 'email' => 'johnsmith@example.com', 'name' => 'John Smith', 'user' => 'ubuntu' }, 'dev_env' => { 'environment_variables' => %w( EDITOR="vim" PATH=~/.npm-global/bin:$PATH ), 'repos' => { 'barebones-express-server' => 'git@github.com:SeanHolden/barebones-express-server.git' } } } end end
namespace :services do services = %w[] # SETME actions = %w[stop start restart] services.each do |service| namespace service do actions.each do |action| desc "#{action} #{service}" task action do run "sudo monit #{action} #{rails_env}_#{service}" end end end end namespace :all do actions.each do |action| desc "#{action} all services" task action do services.each do |service| command = "sudo monit #{action} #{rails_env}_#{service}" if fetch(:skip_monit_services, nil) puts "Skipping: #{command}" else run command end end end end end end
# # Author:: Matt Eldridge (<matt.eldridge@us.ibm.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # Shindo.tests("Fog::Compute[:softlayer] | KeyPair model", ["softlayer"]) do pending unless Fog.mocking? @sl_connection = Fog::Compute[:softlayer] @key_gen = Proc.new { string='ssh-rsa '; while string.length < 380 do; string << Fog::Mock.random_base64(1); end; string; } @kp1 = @sl_connection.key_pairs.create(:label => 'test-key-1', :key => @key_gen.call) tests("success") do tests("#label=") do returns('new-label') { @kp1.label = 'new-label' } end tests("#label") do returns('new-label') { @kp1.label} end tests("#key=") do @new_key_value = @key_gen.call returns(@new_key_value) { @kp1.key = @new_key_value } end tests("#key") do returns(@new_key_value) { @kp1.key } end tests("#create(:label => 'test-key-2', :key => #{@key_gen.call}") do data_matches_schema(Fog::Softlayer::Compute::KeyPair) { @sl_connection.key_pairs.create(:label => 'test-key-2', :key => @key_gen.call)} end tests("#destroy") do returns(true) { @sl_connection.key_pairs.first.destroy } end end tests ("failure") do # ToDo: Failure cases. end end
module Roglew module GL INT64_NV ||= 0x140E UNSIGNED_INT64_NV ||= 0x140F end end module GL_NV_vertex_attrib_integer_64bit module RenderHandle include Roglew::RenderHandleExtension functions [ [:glGetVertexAttribLi64vNV, [ :uint, :uint, :pointer ], :void], [:glGetVertexAttribLui64vNV, [ :uint, :uint, :pointer ], :void], [:glVertexAttribL1i64NV, [ :uint, :int64 ], :void], [:glVertexAttribL1i64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL1ui64NV, [ :uint, :uint64 ], :void], [:glVertexAttribL1ui64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL2i64NV, [ :uint, :int64, :int64 ], :void], [:glVertexAttribL2i64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL2ui64NV, [ :uint, :uint64, :uint64 ], :void], [:glVertexAttribL2ui64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL3i64NV, [ :uint, :int64, :int64, :int64 ], :void], [:glVertexAttribL3i64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL3ui64NV, [ :uint, :uint64, :uint64, :uint64 ], :void], [:glVertexAttribL3ui64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL4i64NV, [ :uint, :int64, :int64, :int64, :int64 ], :void], [:glVertexAttribL4i64vNV, [ :uint, :pointer ], :void], [:glVertexAttribL4ui64NV, [ :uint, :uint64, :uint64, :uint64, :uint64 ], :void], [:glVertexAttribL4ui64vNV, [ :uint, :pointer ], :void], [:glVertexAttribLFormatNV, [ :uint, :int, :uint, :int ], :void] ] end end
class CreateMembers < ActiveRecord::Migration def change create_table :members do |t| t.string :role, null: false t.string :name, null: false t.integer :family_id, null: false t.integer :points, default: 0 t.string :color, null: false t.string :img_url, null: false t.timestamps null: false end end end
require 'rails_helper' describe Invitation do let (:invite) { FactoryGirl.create(:invitation) } it "Allows an event to have more than one invitation" do second_invite = FactoryGirl.build(:invitation, event: invite.event) expect(second_invite).to be_valid end it "Limits a user to one invitation per event" do second_invite = FactoryGirl.build(:invitation, event: invite.event, user: invite.user) expect(second_invite).not_to be_valid end end
module MachO # @param value [Fixnum] the number being rounded # @param round [Fixnum] the number being rounded with # @return [Fixnum] the next number >= `value` such that `round` is its divisor # @see http://www.opensource.apple.com/source/cctools/cctools-870/libstuff/rnd.c def self.round(value, round) round -= 1 value += round value &= ~round value end # @param num [Fixnum] the number being checked # @return [Boolean] true if `num` is a valid Mach-O magic number, false otherwise def self.magic?(num) MH_MAGICS.has_key?(num) end # @param num [Fixnum] the number being checked # @return [Boolean] true if `num` is a valid Fat magic number, false otherwise def self.fat_magic?(num) num == FAT_MAGIC end # @param num [Fixnum] the number being checked # @return [Boolean] true if `num` is a valid 32-bit magic number, false otherwise def self.magic32?(num) num == MH_MAGIC || num == MH_CIGAM end # @param num [Fixnum] the number being checked # @return [Boolean] true if `num` is a valid 64-bit magic number, false otherwise def self.magic64?(num) num == MH_MAGIC_64 || num == MH_CIGAM_64 end # @param num [Fixnum] the number being checked # @return [Boolean] true if `num` is a valid little-endian magic number, false otherwise def self.little_magic?(num) num == MH_CIGAM || num == MH_CIGAM_64 end # @param num [Fixnum] the number being checked # @return [Boolean] true if `num` is a valid big-endian magic number, false otherwise def self.big_magic?(num) num == MH_CIGAM || num == MH_CIGAM_64 end end
# == Schema Information # # Table name: albums # # id :integer not null, primary key # title :string # description :text # user_id :integer # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_albums_on_user_id (user_id) # index_albums_on_user_id_and_created_at (user_id,created_at) # # Foreign Keys # # fk_rails_... (user_id => users.id) # require 'rails_helper' RSpec.describe Album, type: :model do subject { build(:album) } it "is valid with valid attributes" do expect(subject).to be_valid end include_examples "invalid without attributes", :title, :user include_examples "invalid attributes length", { param: :title, length: 50 }, { param: :description, length: 140 } include_examples "valid without attributes", :description describe 'album validity' do shared_examples 'check album validity' do |validity:, photo_count:| context "for album with #{photo_count} photos" do subject { build(:album_with_photos, photos_count: photo_count) } it "is #{validity}" do expect(subject.valid?).to eq(validity) end end end include_examples 'check album validity', validity: true, photo_count: 0 include_examples 'check album validity', validity: true, photo_count: 50 include_examples 'check album validity', validity: false, photo_count: 51 end describe "#tags=" do let(:call) { subject.tags = [] } it "calls index_document on elasticsearch" do expect(subject).to receive_message_chain(:__elasticsearch__, :index_document).and_return("test") expect(call).to eq([]) end end context 'elasticsearch index' do before(:each) { create(:album, title: 'unknow') } it 'be indexed' do described_class.__elasticsearch__.refresh_index! expect(described_class.__elasticsearch__.search('unknow').records.length).to eq(1) end end end
# Copyright 2013 Ride Connection # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'rest_client' require 'api_param_factory' require 'yaml' require 'json' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/inflector' class ApiClient # options: # api_base_url: e.g. 'http://www.clearinghouse.org/api' # api_version: e.g. 'v1' # api_key: from provider API credentials # secret_key: from provider API credentials # raw: true causes the queries to return hashes instead of ApiClient instances (for processing larger datasets) attr_accessor :options def initialize(options_hash = {}) @options = (options_hash || {}).with_indifferent_access @site = RestClient::Resource.new(@options.delete(:api_base_url)) version = @options.delete(:api_version) @version = version.is_a?(String) ? version : "v#{ version || 1 }" @api_key = @options.delete(:api_key) @private_key = @options.delete(:api_private_key) @base_resource_path = nil @data_attributes = {}.with_indifferent_access @nonce_sequence = 0 end # REST-style request methods # # unless raw:true option is used, returned objects are instances of this class and can be used to request # nested objects, e.g. results returned by get('trip_tickets/1').get('trip_ticket_comments') # # resources can be: # symbols: :trip_tickets # strings: "trip_tickets/1/trip_comments" # arrays: ['trip_tickets', 1, :trip_comments] # nested arrays: ['trip_tickets', 1, [:trip_comments, 2]] def get(resource, additional_params = {}) request(:get, resource, additional_params) end def post(resource, additional_params) request(:post, resource, additional_params) end def put(resource, additional_params) request(:put, resource, additional_params) end def delete(resource) request(:delete, resource) end # allow returned objects to return attributes like a Hash def [](key) @data_attributes[key] end def []=(key, value) @data_attributes[key] = value end def to_s @data_attributes.to_s end # if we want to use all hash methods on the class... #def method_missing(method, *args) # @data_attributes.send(method, *args) #end # access to result hash def data @data_attributes end protected def request(method, resource, additional_params = nil) resource = flatten([@base_resource_path, resource]) resource_name = singular_resource_name(resource) if method == :get params = { params: signed_params(additional_params) } else params = signed_params({ resource_name => additional_params }) end result = @site[versioned(resource)].send(method, params) process_result(resource, result) end def process_result(resource, result) result = JSON.parse(result) if options[:raw] result else # convert raw results into dups of the current object with result data stored if result.is_a?(Array) result.map {|r| self.dup.tap {|dup| dup.set_attributes(resource, false, r) }} else self.dup.tap {|dup| dup.set_attributes(resource, true, result) } end end end def set_attributes(resource_path, singular_resource, attributes) @base_resource_path = resource_path @base_resource_path << "/#{attributes['id']}" unless singular_resource || attributes['id'].nil? @data_attributes = attributes.with_indifferent_access end def versioned(resource) [@version, resource].compact.join('/') end def flatten(resource) if resource.is_a?(Array) flattened = resource.compact.map {|r| flatten(r) } flattened.join('/') else resource end end def singular_resource_name(resource_path) # returns type of resource being accessed from its path # e.g. given 'trip_tickets/1/trip_ticket_comments/2' it should return 'trip_ticket_comment' # if path ends with two consecutive alphabetical segments, the last is assumed to be a custom action, # e.g. "trip_tickets/1/trip_ticket_comments/most_recent" should still return 'trip_ticket_comment' match = resource_path.match(/\/?([A-Za-z_-]+)(\/[A-Za-z_-]+)?[^A-Za-z_-]*$/) match[1].singularize if match end def nonce # current time + incremented sequence number should be unique, although not useful for debugging unless logged @nonce_sequence += 1 "#{Time.now.to_i}:#{@nonce_sequence}" end def signed_params(additional_params = nil) ApiParamFactory.authenticatable_params(@api_key, @private_key, nonce, additional_params) end end
class Cart < ActiveRecord::Base belongs_to :billing_information has_many :bookings, dependent: :destroy belongs_to :search belongs_to :user validates :user_id, :search_id, presence: true validate :valid_state accepts_nested_attributes_for :bookings delegate :credit_card, to: :billing_information scope :submitted, lambda { where.not(state: :shopping) } scope :unsubmitted, lambda { where(state: :shopping) } scope :finished, lambda { where(state: :finished) } scope :payment_received, lambda { where(state: :payment_received) } has_paper_trail def self.states %w[ shopping cancelled authorizing_payment awaiting_order_confirmation awaiting_order_authorization processing_payment awaiting_payment_correction payment_received finished ] end def total subtotal + taxes end def paypal_total total * 100 end def subtotal bookings.map { |b| b.total }.reduce(:+) end def taxes 0 end def self.new_with_bookings(search, item = nil) Cart.new.tap do |c| unless search.blank? c.search = search search.room_searches.each do |rs| b = c.bookings.build(adults: rs.adults, item: item) end end end end def fill_bookings self.bookings.each { |b| b.build_line_items(self.search) } end def build_bookings(search) bookings.each do |booking| booking.fill_line_items(search) end end def order_number id.to_s.rjust(10 , '0') end def shop self.bookings.first.shop end def confirmed? bookings.all? { |b| b.confirmed } end def to_s "#{order_number} - #{shop}" end def shop_cut bookings.map { |b| b.shop_cut }.reduce(:+) end def self.finalize_current_bookings Cart.payment_received.each do |cart| CartProcessingWorker.perform_async(cart.id) if cart.current? end end def current? bookings.sort { |a,b| a.checkout <=> b.checkout }.first.checkout >= Date.today end # # Hardcoded return codes # :confirmed - Order confirmed # :canceled - Order canceled # false - Confirmation code does match # def receive_confirmation(confirmation) if confirmation.sanitized_message.match("^#{order_number}") confirm return :confirmed elsif confirmation.sanitized_message.match("^x#{order_number}") cancle return :canceled else return false end end def self.find_cart(order_number) Cart.all.reject { |c| c.confirmed? }.find { |c| c.order_number == order_number } end def responsibles shop.responsibles end def complete_checkout authorize_payment && submit_payment_authorization && pay && confirm_payment end ############################################################################################################## ### state machine ############################################################################################################## state_machine :state, :initial => :shopping do after_transition any => any, do: :set_timestamp # # States - 9 # # state :authorizing_payment do # validates :billing_information_id, :email, :phone, :payment_amount, :order_confirmation, :terms_accepted, # presence: true # end # state :payment_processed do # end state :shopping do end state :cancelled do end state :authorizing_payment do end state :awaiting_order_confirmation do end state :processing_payment do end state :awaiting_payment_correction do end state :payment_received do end state :finished do end # # Transitions/Events - 13 # event :authorize_payment do transition [:shopping] => [:authorizing_payment] end event :cancle_cart do transition [:shopping] => [:cancelled] end event :reject_payment_authorization do transition [:authorizing_payment] => [:shopping] end event :confirm_order do transition [:authorizing_payment] => [:awaiting_order_confirmation] end event :authorize_order do transition [:awaiting_order_confirmation] => [:awaiting_order_authorization] end event :reject_order_confirmation do transition [:awaiting_order_confirmation] => [:cancelled] end event :reject_order_authorization do transition [:awaiting_order_authorization] => [:cancelled] end event :process_payment do transition [:awaiting_order_authorization] => [:processing_payment] end event :request_payment_correction do transition [:processing_payment] => [:awaiting_payment_correction] end event :retry_process_payment do transition [:awaiting_payment_correction] => [:processing_payment] end event :receive_payment do transition [:processing_payment] => [:payment_received] end event :reject_payment_processing do transition [:awaiting_payment_correction] => [:cancelled] end event :finish_order do transition [:payment_received] => [:finished] end # before_transition :on => :authorize_payment, :do => :prepare_for_checkout # event :authorize_payment do # transition :shopping => :authorizing_payment # end # event :pay do # transition [:authorizing_payment] => :processing_payment # end # after_transition :on => :confirm_payment, :do => :finalize_submission # event :confirm_payment do # transition [:processing_payment] => :payment_received, :if => lambda { |cart| cart.send :bill } # end # before_transition :on => :cancle_payment, :do => :reset_cart # event :cancle_payment do # transition [:authorizing_payment] => :shopping # end # event :finish do # transition [:payment_received] => :finished # end # event :cancle do # transition all => :cancelled # end end ############################################################################################################## ### ############################################################################################################## private def bill response = ::SPREEDLY_ENVIRONMENT.capture_transaction(auth_transaction_token) update_attributes(capture_transaction_token: response.token) response.succeeded end def set_timestamp update_attributes("#{state}_at" => Time.zone.now) end def reset_cart update_attributes(search_id: nil) end def set_order_confirmation self[:order_confirmation] = SecureRandom.hex.upcase[0,5] + order_number end def finalize_submission send_confirmation clear_unused_carts end def clear_unused_carts user.carts.unsubmitted.destroy_all end def confirm bookings.each { |b| b.confirm } end def submit_payment_authorization response = ::SPREEDLY_ENVIRONMENT.authorize_on_gateway(::PAYMENT_GATEWAY_TOKEN, billing_information.saved_gateway_id, paypal_total) update_attributes(auth_transaction_token: response.token) response.succeeded end def send_cancelation #send phone notice send_email_cancelation end def send_email_cancelation ShopperMailer.cancelation(self).deliver end def send_confirmation #send_phone_confirmation send_email_confirmation end def send_phone_confirmation shop.phones.each do |p| Sm.send(p, confirmation_message, self) end end def send_email_confirmation BookingConfirmationWorker.perform_async(self.id) end def prepare_for_checkout set_order_confirmation set_payment_amount save end def set_payment_amount self.payment_amount = total end def confirmation_message "#{order_number} - #{bookings_summary}" end def bookings_summary "".tap do |s| bookings.each do |b| s += b.sms_summary end end end def valid_state errors[:state] << I18n.t('cart.form.errors.valid_state') unless Cart.states.include?(self.state) end end
class MigrateAdminAccounts < ActiveRecord::Migration def self.up admins = Account.find(:all, :conditions => 'admin = 1') admins.each{|acc| acc.authz.has_role 'admin'} end def self.down end end
require 'byebug' # merge_sort def merge_sort(arr) return arr if arr.length < 2 # DIVIDE: partition into left, right halves mid = arr.length / 2 left = arr.take(mid) right = arr.drop(mid) # CONQUER: sort partitions merge_sort(left) merge_sort(right) # COMBINE: combine sorted arrays merge(left, right) end def merge(left, right) merged = [] # takes smallest element from arrays, appends to merged until left.empty? || right.empty? merged << (left.first < right.first ? left.shift : right.shift) end # merges remaining elements merged + left + right end
require 'spec_helper' describe SupportedSourceHelloWorld do it 'has the right version' do expect(SupportedSourceHelloWorld::VERSION).to eq('1.1.0') end it 'says hello world' do expect(SupportedSourceHelloWorld.hello_world).to eq('Hello world! If you can read this, the project was included successfully.') end end
class Susanoo::PageContentsController < ApplicationController # # html にルビをふる # # see app/controllers/application_controller.rb # after_action :rubi_filter, only: %i(content) end
require 'rails_helper' RSpec.describe List, type: :model do subject { build(:list) } it { is_expected.to respond_to(:name) } it { is_expected.to respond_to(:position) } it { is_expected.to respond_to(:board_id) } it { is_expected.to be_valid } it { is_expected.to belong_to(:board) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:position) } it { is_expected.to validate_length_of(:name).is_at_most(100) } it do is_expected.to validate_numericality_of(:position).only_integer .is_greater_than_or_equal_to(0) end it { is_expected.to validate_uniqueness_of(:position).scoped_to(:board_id) } end
# frozen_string_literal: true module Api module V1 class UsersController < ApplicationController include LoginHelper include ErrorMessageHelper include ResponseStatus include ErrorKeys def create @user = User.new(user_params) if @user.save @user.send_activation_email render json: generate_response(SUCCESS, message: 'activation mail has been sent') else failed_to_create @user end end def show if user_token_from_get_params onetime_session = login?(user_token_from_get_params) if onetime_session && token_available?(user_token_from_get_params) @session_user = User.find_by(id: onetime_session.user_id) elsif !token_available?(user_token_from_get_params) return old_token_response end end selected_user = User.find_by(name: user_name) unless selected_user&.activated? message = 'the user is not found' key = 'name' return error_response(key: key, message: message, status: 404) end render json: generate_response(SUCCESS, user_info(selected_user)) end def update unless user_tokens[:onetime] message = 'property onetime of token is empty' key = ErrorKeys::TOKEN return error_response(key: key, message: message) end onetime_session = login?(user_tokens[:onetime]) unless onetime_session message = 'you are not logged in' key = 'login' return error_response(key: key, message: message) end return old_token_response unless token_available?(user_tokens[:onetime]) selected_user = User.find_by(name: user_name) unless selected_user message = 'invalid user name' key = 'name' return error_response(key: key, message: message) end session_user = onetime_session.user unless session_user.admin? || session_user == selected_user message = 'you are not admin' key = 'admin' return error_response(key: key, message: message) end if update_selected_user(selected_user) render json: generate_response(SUCCESS, message: 'user parameters are updated successfully') else failed_to_create selected_user end end def destroy if user_token_from_get_params.nil? message = 'property onetime of token is empty' key = ErrorKeys::TOKEN return error_response(key: key, message: message) end onetime_session = login?(user_token_from_get_params) unless onetime_session message = 'you are not logged in' key = 'login' return error_response(key: key, message: message) end unless token_available?(user_token_from_get_params) return old_token_response end session_user = onetime_session.user selected_user = User.find_by(name: user_name) unless selected_user message = 'invalid user name' key = 'name' return error_response(key: key, message: message) end unless session_user.admin? || session_user == selected_user message = 'you are not admin' key = 'admin' return error_response(key: key, message: message) end if selected_user.discard render json: generate_response(SUCCESS, message: 'user is deleted successfully') else failed_to_create selected_user end end private def user_info(selected_user) { name: selected_user.name, nickname: selected_user.nickname, explanation: selected_user.explanation, icon: selected_user.icon, is_admin: selected_user.admin?, is_mypage: @session_user == selected_user } end def update_selected_user(user) user.transaction do user.update!(name: user_params[:name]) if user_params[:name] if user_params[:nickname] user.update!(nickname: user_params[:nickname]) end if user_params[:explanation] user.update!(explanation: user_params[:explanation]) end if user_params[:image] && user_params[:image][:base64_encoded_image] user.update_icon(user_params[:image][:base64_encoded_image]) end return true end rescue ActiveRecord::RecordInvalid false end def user_name params.permit(:id)[:id] end def user_params return {} if params[:value].nil? params.require(:value).permit(:name, :nickname, :email, :password, :explanation, image: %i[name base64_encoded_image]) end def user_tokens return {} if params[:token].nil? params.require(:token).permit(:onetime, :master) end def user_token_from_get_params return nil if params[:token].nil? params.permit(:token)[:token] end def create_sessions ActiveRecord::Base.transaction do @master_session = @user.master_session.create! @onetime_session = @user.onetime_session.create! end end def generate_response(status, body) { status: status, body: body } end end end end
# your code goes here require "pry" def begins_with_r(arr) if arr.count{|e| e[0] == "r"} ==arr.length return true else return false end end def contain_a(arr) arr.collect do |e| if(e.include?("a")) e else nil end end.compact end def first_wa(arr) arr.each do |e| if(e.to_s.start_with?("wa")) return e end end end def remove_non_strings(arr) arr.collect do |e| if(e.instance_of? String) e else nil end end.compact end def count_elements(arr) frequency_array = arr.uniq frequency_array.each do |e| e[:count] = arr.count(e) end end def merge_data(keys, data) merged_data=[] keys.each do |e| data.each do |element| if(!!element[e[:first_name]]) merged_data << element[e[:first_name]] merged_data.last[:first_name] = e[:first_name] end end end merged_data end def find_cool(arr) arr.collect do |e| if(e[:temperature]=="cool") e else nil end end.compact end def organize_schools(school_hash) school_hash_reorganized = {} school_hash.each do |key, value| if(!school_hash_reorganized[value[:location]]) school_hash_reorganized[value[:location]]=[key] else school_hash_reorganized[value[:location]].push(key) end end school_hash_reorganized end
module RackReverseProxy # Rule understands which urls need to be proxied class Rule # FIXME: It needs to be hidden attr_reader :options def initialize(spec, url = nil, options = {}) @has_custom_url = url.nil? @url = url @options = options @spec = build_matcher(spec) end def proxy?(path, *args) matches(path, *args).any? end def get_uri(path, env, *args) Candidate.new( self, has_custom_url, path, env, matches(path, *args) ).build_uri end def to_s %("#{spec}" => "#{url}") end private attr_reader :spec, :url, :has_custom_url def matches(path, *args) Matches.new( spec, url, path, options[:accept_headers], has_custom_url, *args ) end def build_matcher(spec) return /^#{spec}/ if spec.is_a?(String) return spec if spec.respond_to?(:match) return spec if spec.respond_to?(:call) raise ArgumentError, "Invalid Rule for reverse_proxy" end # Candidate represents a request being matched class Candidate def initialize(rule, has_custom_url, path, env, matches) @rule = rule @env = env @path = path @has_custom_url = has_custom_url @matches = matches @url = evaluate(matches.custom_url) end def build_uri return nil unless url raw_uri end private attr_reader :rule, :url, :has_custom_url, :path, :env, :matches def raw_uri return substitute_matches if with_substitutions? return just_uri if has_custom_url uri_with_path end def just_uri URI.parse(url) end def uri_with_path URI.join(url, path) end def evaluate(url) return unless url return url.call(env) if lazy?(url) url.clone end def lazy?(url) url.respond_to?(:call) end def with_substitutions? url =~ /\$\d/ end def substitute_matches URI(matches.substitute(url)) end end # Matches represents collection of matched objects for Rule class Matches # rubocop:disable Metrics/ParameterLists # FIXME: eliminate :url, :accept_headers, :has_custom_url def initialize(spec, url, path, accept_headers, has_custom_url, headers, rackreq, *_) @spec = spec @url = url @path = path @has_custom_url = has_custom_url @rackreq = rackreq @headers = headers if accept_headers @spec_arity = spec.method(spec_match_method_name).arity end def any? found.any? end def custom_url return url unless has_custom_url found.map do |match| match.url(path) end.first end def substitute(url) found.each_with_index.inject(url) do |acc, (match, i)| acc.gsub("$#{i}", match) end end private attr_reader :spec, :url, :path, :headers, :rackreq, :spec_arity, :has_custom_url def found @_found ||= find_matches end def find_matches Array( spec.send(spec_match_method_name, *spec_params) ) end def spec_params @_spec_params ||= _spec_params end def _spec_params [ path, headers, rackreq ][0...spec_param_count] end def spec_param_count @_spec_param_count ||= _spec_param_count end def _spec_param_count return 1 if spec_arity == -1 spec_arity end def spec_match_method_name return :match if spec.respond_to?(:match) :call end end end end
class TeamSubmittionsController < ApplicationController before_filter :set_team before_filter :find_or_initialize_submittion before_filter :verify_team_access before_filter :set_tabs before_filter :verify_contest_running layout 'control' def index @problems = @contest.problems.find_all @compilers = Compiler.find_all @submittions = @team.submittions.find(:all, :order => 'submittions.id DESC') @runs = @team.runs.find(:all, :include => [:problem, :compiler], :order => 'runs.id DESC') # @stats = OpenStruct.new # @stats.done = Run.count(:all, :conditions => ['state = 4 or state = 3']) # @stats.testing = Run.count(:all, :conditions => ['state = 2']) # @stats.queued = Run.count(:all, :conditions => ['state = 1 or state = 0']) # @stats.postponed = Run.count(:all, :conditions => ['state = 10 or state = 11']) end def show access_denied unless current_user.allow?(:view_all_submittions) || current_user == @team @submittion.text = Server.get_submittion_text(@contest.short_name, @submittion.file_name || @submittion.runs.first.file_name) render :layout => false end def create team_id = @team.id compiler_id = params[:submittion][:compiler_id] problem_id = params[:submittion][:problem_id] text = params[:submittion][:text] text ||= params[:file].read Server.submit(team_id, problem_id, compiler_id, text) flash[:message] = "Решение отправлено на проверку." redirect_to team_submittions_url(@contest.id, @team.id) end private def find_or_initialize_submittion @submittion = if params[:id].blank? @team.submittions.build else @team.submittions.find(params[:id]) end end def verify_contest_running return if current_user.allow?(:submit_always) st = (@team && @team.state_override) || @contest.state unless st == 2 if st == 3 flash[:message] = "Олимпиада окончена" else flash[:message] = "Олимпиада еще не началась" end redirect_to team_participation_url(@contest, @team) return false end return true end end
require 'spec_helper' describe OpenAssets::Provider::BitcoinCoreProvider do describe 'implicitly defined method#getbalance' do context 'use new provider.getbalance' do it 'returns provider.getbalance' do provider = OpenAssets::Provider::BitcoinCoreProvider.new({}) expect(provider).to receive(:request).with(:getbalance) provider.getbalance end end end describe 'implicitly defined methods' do context 'implicitly defined' do it 'returns help results' do help_commands = load_help("0.16.0").split("\n").inject([]) do |commands, line| if !line.empty? && !line.start_with?('==') commands << line.split(' ').first.to_sym end commands end expect(OpenAssets::Provider::BitcoinCoreProvider.public_instance_methods).to include *help_commands end end end describe 'explicitly defined methods' do let(:rest_client_mock) do rest_client_mock = double('Rest Client') allow(RestClient::Request).to receive(:execute).and_return(rest_client_mock) rest_client_mock end # For node-level RPC let(:provider_node_level) do config = {schema: 'https', user: 'user', password: 'password', host: 'localhost', port: '8332', wallet: '', timeout: 60, open_timeout: 60} OpenAssets::Provider::BitcoinCoreProvider.new(config) end # For node-level RPC (backward compatible: missing 'wallet' in config) let(:provider_node_level_backward) do config = {schema: 'https', user: 'user', password: 'password', host: 'localhost', port: '8332', timeout: 60, open_timeout: 60} OpenAssets::Provider::BitcoinCoreProvider.new(config) end # For wallet-level RPC let(:provider_wallet_level) do config = {schema: 'https', user: 'user', password: 'password', host: 'localhost', port: '8332', wallet: 'wallet.dat', timeout: 60, open_timeout: 60} OpenAssets::Provider::BitcoinCoreProvider.new(config) end context '#import_address' do context 'use node-level import_address' do it 'returns node-level import_address' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"importaddress\",\"params\":[\"address\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level.import_address(:address) expect(provider_node_level).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"importaddress\",\"params\":[\"address\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level.import_address(:address) expect(provider_node_level).to receive(:request).with(:importaddress, :address) provider_node_level.import_address(:address) end end context 'use node-level import_address with backward compatibility' do it 'returns node-level import_address' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"importaddress\",\"params\":[\"address\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level_backward.import_address(:address) expect(provider_node_level_backward).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"importaddress\",\"params\":[\"address\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level_backward.import_address(:address) expect(provider_node_level_backward).to receive(:request).with(:importaddress, :address) provider_node_level_backward.import_address(:address) end end context 'use wallet-level import_address' do it 'returns wallet-level import_address' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332/wallet/wallet.dat", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"importaddress\",\"params\":[\"address\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_wallet_level.import_address(:address) expect(provider_wallet_level).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"importaddress\",\"params\":[\"address\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_wallet_level.import_address(:address) expect(provider_wallet_level).to receive(:request).with(:importaddress, :address) provider_wallet_level.import_address(:address) end end end context '#list_unspent' do context 'use node-level list_unspent' do it 'returns node-level list_unspent' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"listunspent\",\"params\":[1,9999999,[]],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level.list_unspent expect(provider_node_level).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"listunspent\",\"params\":[1,9999999,[]],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level.list_unspent expect(provider_node_level).to receive(:request).with(:listunspent, 1, 9999999, []) provider_node_level.list_unspent end end context 'use node-level list_unspent with backward compatibility' do it 'returns node-level list_unspent' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"listunspent\",\"params\":[1,9999999,[]],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level_backward.list_unspent expect(provider_node_level_backward).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"listunspent\",\"params\":[1,9999999,[]],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level_backward.list_unspent expect(provider_node_level_backward).to receive(:request).with(:listunspent, 1, 9999999, []) provider_node_level_backward.list_unspent end end context 'use wallet-level list_unspent' do it 'returns wallet-level list_unspent' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332/wallet/wallet.dat", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"listunspent\",\"params\":[1,9999999,[]],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_wallet_level.list_unspent expect(provider_wallet_level).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"listunspent\",\"params\":[1,9999999,[]],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_wallet_level.list_unspent expect(provider_wallet_level).to receive(:request).with(:listunspent, 1, 9999999, []) provider_wallet_level.list_unspent end end end context '#get_transaction' do context 'use node-level get_transaction' do it 'returns node-level get_transaction' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"getrawtransaction\",\"params\":[\"transaction_hash\",0],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level.get_transaction(:transaction_hash) expect(provider_node_level).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"getrawtransaction\",\"params\":[\"transaction_hash\",0],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level.get_transaction(:transaction_hash) expect(provider_node_level).to receive(:request).with(:getrawtransaction, :transaction_hash, 0) provider_node_level.get_transaction(:transaction_hash) end end context 'use node-level get_transaction with backward compatibility' do it 'returns node-level get_transaction' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"getrawtransaction\",\"params\":[\"transaction_hash\",0],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level_backward.get_transaction(:transaction_hash) expect(provider_node_level_backward).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"getrawtransaction\",\"params\":[\"transaction_hash\",0],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level_backward.get_transaction(:transaction_hash) expect(provider_node_level_backward).to receive(:request).with(:getrawtransaction, :transaction_hash, 0) provider_node_level_backward.get_transaction(:transaction_hash) end end context 'use wallet-level get_transaction' do it 'returns wallet-level get_transaction' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332/wallet/wallet.dat", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"getrawtransaction\",\"params\":[\"transaction_hash\",0],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_wallet_level.get_transaction(:transaction_hash) expect(provider_wallet_level).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"getrawtransaction\",\"params\":[\"transaction_hash\",0],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_wallet_level.get_transaction(:transaction_hash) expect(provider_wallet_level).to receive(:request).with(:getrawtransaction, :transaction_hash, 0) provider_wallet_level.get_transaction(:transaction_hash) end end end context '#sign_transaction' do context 'use node-level sign_transaction' do it 'returns node-level sign_transaction' do allow(rest_client_mock).to receive(:[]).and_return(true, '01000000000000000000') expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level.sign_transaction(:tx) expect(provider_node_level).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}).and_return(rest_client_mock) provider_node_level.sign_transaction(:tx) expect(provider_node_level).to receive(:request).with(:signrawtransaction, :tx).and_return(rest_client_mock) provider_node_level.sign_transaction(:tx) end end context 'use node-level sign_transaction with backward compatibility' do it 'returns node-level sign_transaction' do allow(rest_client_mock).to receive(:[]).and_return(true, '01000000000000000000') expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level_backward.sign_transaction(:tx) expect(provider_node_level_backward).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}).and_return(rest_client_mock) provider_node_level_backward.sign_transaction(:tx) expect(provider_node_level_backward).to receive(:request).with(:signrawtransaction, :tx).and_return(rest_client_mock) provider_node_level_backward.sign_transaction(:tx) end end context 'use wallet-level sign_transaction' do it 'returns wallet-level sign_transaction' do allow(rest_client_mock).to receive(:[]).and_return(true, '01000000000000000000') expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332/wallet/wallet.dat", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_wallet_level.sign_transaction(:tx) expect(provider_wallet_level).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}).and_return(rest_client_mock) provider_wallet_level.sign_transaction(:tx) expect(provider_wallet_level).to receive(:request).with(:signrawtransaction, :tx).and_return(rest_client_mock) provider_wallet_level.sign_transaction(:tx) end end context 'version 0.16.0' do it 'should call signrawtransaction' do allow(rest_client_mock).to receive(:[]).and_return(true, '01000000000000000000') expect(provider_wallet_level).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"signrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}).and_return(rest_client_mock) provider_wallet_level.sign_transaction(:tx) end end context 'version 0.18.0' do before { allow_any_instance_of(OpenAssets::Provider::BitcoinCoreProvider).to receive(:core_version).and_return("0.18.0") } it 'should call signrawtransactionwithwallet' do rest_client_mock = double('Rest Client 0.18.0') allow(RestClient::Request).to receive(:execute).and_return(rest_client_mock) provider = OpenAssets::Provider::BitcoinCoreProvider.new({schema: 'https', user: 'user', password: 'password', host: 'localhost', port: '8332', wallet: 'wallet.dat', timeout: 60, open_timeout: 60}) allow(rest_client_mock).to receive(:[]).and_return(true, '01000000000000000000') expect(provider).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"signrawtransactionwithwallet\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}).and_return(rest_client_mock) provider.sign_transaction(:tx) end end end context '#send_transaction' do context 'use node-level send_transaction' do it 'returns node-level send_transaction' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"sendrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level.send_transaction(:tx) expect(provider_node_level).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"sendrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level.send_transaction(:tx) expect(provider_node_level).to receive(:request).with(:sendrawtransaction, :tx) provider_node_level.send_transaction(:tx) end end context 'use node-level send_transaction with backward compatibility' do it 'returns node-level send_transaction' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"sendrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_node_level_backward.send_transaction(:tx) expect(provider_node_level_backward).to receive(:post).with("https://user:password@localhost:8332", 60, 60, "{\"method\":\"sendrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_node_level_backward.send_transaction(:tx) expect(provider_node_level_backward).to receive(:request).with(:sendrawtransaction, :tx) provider_node_level_backward.send_transaction(:tx) end end context 'use wallet-level send_transaction' do it 'returns wallet-level send_transaction' do expect(RestClient::Request).to receive(:execute).with(:method => :post, :url => "https://user:password@localhost:8332/wallet/wallet.dat", :timeout => 60, :open_timeout => 60, :payload => "{\"method\":\"sendrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", :headers => {:content_type=>:json}) provider_wallet_level.send_transaction(:tx) expect(provider_wallet_level).to receive(:post).with("https://user:password@localhost:8332/wallet/wallet.dat", 60, 60, "{\"method\":\"sendrawtransaction\",\"params\":[\"tx\"],\"id\":\"jsonrpc\"}", {:content_type=>:json}) provider_wallet_level.send_transaction(:tx) expect(provider_wallet_level).to receive(:request).with(:sendrawtransaction, :tx) provider_wallet_level.send_transaction(:tx) end end end end end
Rails.application.routes.draw do resources :posts devise_for :users root 'posts#index' get 'post/:id/likes', to: 'posts#likes', as: :likes end
json.goal do json.partial! 'api/v1/goals/show', goal: @goal end
require 'json' require 'csv' # data is from 2014 # http://kff.org/global-indicator/people-living-with-hivaids/# def separate_comma(number) number.to_s.chars.to_a.reverse.each_slice(3).map(&:join).join(",").reverse end csv_data = File.read('hiv_aids_data_by_country.csv') csv = CSV.parse(csv_data, :headers=> true) country_hiv_aids_data = {} csv.each_with_index do |row, i| if row["People Living with HIV/AIDS"] != "N/A" && row["Adults receiving ART"] != "N/A" && row["AIDS Deaths"] != "N/A" num_people = row["People Living with HIV/AIDS"].split(",").join().to_i receiving_treatment = row["Adults receiving ART"].split(",").join().to_i row["AIDS Deaths"][0] == "<" ? deaths = row["AIDS Deaths"][1..-1] : deaths = row["AIDS Deaths"] deaths = deaths.split(",").join().to_i country_hiv_aids_data[row["Location"]] = { "people_living_with_hiv_aids" => num_people, "people_receiving_ART" => receiving_treatment, "aids_deaths" => deaths } end end country_hiv_aids_data = country_hiv_aids_data.sort_by {|country, data| data["people_living_with_hiv_aids"]}.reverse country_hiv_aids_data = country_hiv_aids_data[0..49].to_h output = File.open('country_hiv_aids_data.py', 'w') output << JSON.generate(country_hiv_aids_data) output.close output = File.open('country_hiv_aids_data.html', 'w') output << "<!DOCTYPE html><html><head><body><h2>People living with HIV/AIDS around the world</h2><table><tr><th>Country</th><th>People Living with HIV/AIDS (2014)</th><th>People Receiving Antiretroviral Therapy (2014)</th><th>AIDS Deaths (2014)</th></tr>" country_hiv_aids_data.each do |country, data| people_living_with_hiv_aids = separate_comma(data["people_living_with_hiv_aids"]) people_receiving_ART = separate_comma(data["people_receiving_ART"]) aids_deaths = separate_comma(data["aids_deaths"]) output << "<tr><td>#{country}</td><td>#{people_living_with_hiv_aids}</td><td>#{people_receiving_ART}</td><td>#{aids_deaths}</td></tr>" end output << "</table></body></html>" output.close
require 'pi_piper' module SMSService # A LED handler class LEDHandler def initialize(pins) unless pins.respond_to? 'each' raise ArgumentError, 'pins must be an array' end @pins = {} pins.each do |p| pin = PiPiper::Pin.new(pin: p, direction: :out) @pins[p] = pin end @animations = {} end def pin(p) @pins[p] end # rubocop:disable Metrics/MethodLength def flash(time = 0.500) stop_animations @animations[:flash] = Thread.new do loop do @pins.each do |_i, p| p.on end sleep time @pins.each do |_i, p| p.off end end end end def ascending(time = 0.250) stop_animations @animations[:ascending] = Thread.new do loop do @pins.each do |_i, p| p.on sleep time end @pins.each do |_i, p| p.off sleep time end end end end def lightshow(time = 0.500) stop_animations @animations[:lightshow] = Thread.new do @pins.each do |_i, p| p.off end loop do @pins.each do |_i, p| p.on sleep time p.off end end end end def stop_animations @animations.each do |_k, v| v.exit end @pins.each do |_i, p| p.off end @animations = {} end end end
class CreateJointTableIngredientsPets < ActiveRecord::Migration def change create_table :ingredients_pets, :id => false do |t| t.references :ingredients t.references :pets end end end
# Self pairings are disallowed. require 'json' require 'fileutils' module GenData # A directory inside this directory will be created for this data. DATA_BASE_DIR = File.join('.', 'data') DEFAULT_SEED = 4 OPTIONS = [ { :id => 'people', :short => 'p', :long => 'people', :valueDesc => 'number of people', :desc => 'The number of people to create.', :domain => [1, 1000000], :default => 10 }, { :id => 'locations', :short => 'l', :long => 'locations', :valueDesc => 'number of locations', :desc => 'The number of locations to create.', :domain => [1, 1000000], :default => 3 }, { :id => 'friendshipHigh', :short => 'fh', :long => 'friendship-high', :valueDesc => 'probability', :desc => 'The probability that two people in the same location are friends', :domain => [0.0, 1.0], :default => 1.0 }, { :id => 'friendshipLow', :short => 'fl', :long => 'friendship-low', :valueDesc => 'probability', :desc => 'The probability that two people in different locations are friends', :domain => [0.0, 1.0], :default => 0.0 }, { :id => 'similarityMeanHigh', :short => 'smh', :long => 'similarity-mean-high', :valueDesc => 'value', :desc => 'The mean of the gaussian distribution to draw high probabilities from.', :domain => [0.0, 1.0], :default => 0.8 }, { :id => 'similarityVarianceHigh', :short => 'svh', :long => 'similarity-variance-high', :valueDesc => 'value', :desc => 'The variance of the gaussian distribution to draw high probabilities from.', :domain => [0.0, 1.0], :default => 0.1 }, { :id => 'similarityMeanLow', :short => 'slh', :long => 'similarity-mean-low', :valueDesc => 'value', :desc => 'The mean of the gaussian distribution to draw low probabilities from.', :domain => [0.0, 1.0], :default => 0.2 }, { :id => 'similarityVarianceLow', :short => 'svl', :long => 'similarity-variance-low', :valueDesc => 'value', :desc => 'The variance of the gaussian distribution to draw low probabilities from.', :domain => [0.0, 1.0], :default => 0.1 }, { :id => 'seed', :short => 's', :long => 'seed', :valueDesc => 'value', :desc => 'The random seed to use.', :domain => [-999999999, 999999999], :default => DEFAULT_SEED }, { :id => 'name', :short => 'n', :long => 'name', :valueDesc => 'value', :desc => 'The base name for this experiment.', :domain => nil, :default => 'base' }, ] def GenData.writeData(dataDir, locations, similarity, friendship, options) FileUtils.mkdir_p(dataDir) similarObsPath = File.join(dataDir, 'similar_obs.txt') locationObsPath = File.join(dataDir, 'location_obs.txt') friendsTargetPath = File.join(dataDir, 'friends_targets.txt') friendsTruthPath = File.join(dataDir, 'friends_truth.txt') optionsPath, = File.join(dataDir, 'options.json') File.open(locationObsPath, 'w'){|file| file.puts(locations.each_with_index().map{|loc, index| "#{index}\t#{loc}"}.join("\n")) } File.open(similarObsPath, 'w'){|file| file.puts(similarity.map{|entry| entry.join("\t")}.join("\n")) } File.open(friendsTruthPath, 'w'){|file| file.puts(friendship.map{|entry| entry.join("\t")}.join("\n")) } File.open(friendsTargetPath, 'w'){|file| # Make sure to add on the zero for the initial value. file.puts(friendship.map{|entry| (entry[0...2].push(0)).join("\t")}.join("\n")) } # Write out the options as well. File.open(optionsPath, 'w'){|file| file.puts(JSON.pretty_generate(options)) } end # Return the directory the data is in. def GenData.genData(options) dataDir = File.join(DATA_BASE_DIR, "#{options['name']}_#{'%04d' % options['people']}_#{'%04d' % options['locations']}") if (File.exists?(dataDir)) puts "Data directory (#{dataDir}) already exists, skipping generation." return dataDir end random = Random.new(options['seed']) numPeople = options['people'] locations = [] for i in 0...numPeople locations << random.rand(options['locations']) end friendship = [] for i in 0...numPeople for j in 0...numPeople if (i == j) next else friendshipChance = options['friendshipHigh'] if (locations[i] != locations[j]) friendshipChance = options['friendshipLow'] end if (random.rand(1.0) < friendshipChance) friends = 1 else friends = 0 end end friendship << [i, j, friends] end end similarity = [] for i in 0...numPeople for j in 0...numPeople if (i == j) next else mean = options['similarityMeanHigh'] variance = options['similarityVarianceHigh'] if (locations[i] != locations[j]) mean = options['similarityMeanLow'] variance = options['similarityVarianceLow'] end sim = GenData.gaussian(mean, variance, random) end sim = [1.0, [0, sim].max()].min() similarity << [i, j, sim] end end GenData.writeData(dataDir, locations, similarity, friendship, options) return dataDir end # Box-Muller: http://www.taygeta.com/random/gaussian.html def GenData.gaussian(mean, variance, rng) w = 2 while (w >= 1.0) x1 = 2.0 * rng.rand() - 1 x2 = 2.0 * rng.rand() - 1 w = x1 ** 2 + x2 ** 2 end w = Math.sqrt((-2.0 * Math.log(w)) / w) return x1 * w * Math.sqrt(variance) + mean end def GenData.loadArgs(args) if ((args.map{|arg| arg.gsub('-', '').downcase()} & ['help', 'h']).any?()) puts "USAGE: ruby #{$0} [OPTIONS]" puts "Options:" optionsStr = OPTIONS.map{|option| " -#{option[:short]}, --#{option[:long]} <#{option[:valueDesc]}> - Default: #{option[:default]}. Domain: #{option[:domain]}. #{option[:desc]}" }.join("\n") puts optionsStr exit(1) end optionValues = OPTIONS.map{|option| [option[:id], option[:default]]}.to_h() while (args.size() > 0) rawFlag = args.shift() flag = rawFlag.strip().sub(/^-+/, '') currentOption = nil OPTIONS.each{|option| if ([option[:short], option[:long]].include?(flag)) currentOption = option break end } if (currentOption == nil) puts "Unknown option: #{rawFlag}" exit(2) end if (args.size() == 0) puts "Expecting value to argument (#{rawFlag}), but found nothing." exit(3) end value = args.shift() if (currentOption[:default].is_a?(Integer)) value = value.to_i() elsif (currentOption[:default].is_a?(Float)) value = value.to_f() end if (currentOption.has_key?(:domain) && currentOption[:domain] != nil && (value < currentOption[:domain][0] || value > currentOption[:domain][1])) puts "Value for #{rawFlag} (#{value}) not in domain: #{currentOption[:domain]}." exit(4) end optionValues[currentOption[:id]] = value end return optionValues end def GenData.main(args) return GenData.genData(GenData.loadArgs(args)) end end if ($0 == __FILE__) GenData.main(ARGV) end
class Picture < ActiveRecord::Base belongs_to :gallery validates :gallery, :presence => true Paperclip.interpolates :gallery_id do |attachment, style| attachment.instance.gallery_id end has_attached_file :photo, :styles => {:normal => "600x400#", :thumbnail => "225x150#"}, :default_style => :normal, :url => "/assets/galleries/:gallery_id/:style/photo_:id.:extension", :path => ":rails_root/public/assets/galleries/:gallery_id/:style/photo_:id.:extension", # Amazon S3 storage # :storage => :s3, # :s3_credentials => "#{::Rails.root}/config/s3.yml", :default_url => "/assets/galleries/default_photos/:style.png" validates_attachment :photo, :content_type => { :content_type => ['image/jpeg','image/png', 'image/pjpeg' ]}, :size => { :less_than => 4000.kilobytes } attr_accessible :gallery_id, :pic_order, :photo end
# == Schema Information # # Table name: resources # # id :integer not null, primary key # book_id :integer # created_at :datetime not null # updated_at :datetime not null # user_id :integer # require 'spec_helper' describe Resource do let(:book) { create :book } let(:user) { create :user } let(:resource) { create :resource, :user => user, :book => book } it "passes validation with all valid informations" do expect(resource).to be_valid end context "fails validation" do it "with a blank book" do resource.book_id = '' expect(resource.save).to be_false end end context "instance methods" do it "book_name" do resource.book_name.should eq book.name end it "post_by" do resource.post_by.should eq user.name end it "download_link" do #resource.download_link.should eq attachment.attachment.url end it "pdf2html_link" do resource.stub(:download_link) { "http://caok1231.com/attachment/18/AngularJS_Cheat_Sheet.pdf" } resource.pdf2html_link.should eq "http://caok1231.com/attachment/18/AngularJS_Cheat_Sheet.html" end end end
class SpaceAge attr_reader :seconds def initialize(seconds) @seconds = seconds @hours_in_day = 24 @mins_in_hour = 60 @sec_in_min = 60 yearly_orbit_in_days end def seconds_to_days @seconds / @sec_in_min / @mins_in_hour / @hours_in_day end def yearly_orbit_in_days @EARTH = 365.25000000 @VENUS = 0.61519726 * @EARTH @MARS = 1.88081580 * @EARTH @JUPITER = 11.86261500 * @EARTH @SATURN = 29.44749800 * @EARTH @URANUS = 84.01684600 * @EARTH @NEPTUNE = 164.79132000 * @EARTH @MERCURY = 0.24084670 * @EARTH end def on_mercury seconds_to_days / @MERCURY end def on_earth seconds_to_days / @EARTH end def on_venus seconds_to_days / @VENUS end def on_mars seconds_to_days / @MARS end def on_jupiter seconds_to_days / @JUPITER end def on_saturn seconds_to_days / @SATURN end def on_uranus seconds_to_days / @URANUS end def on_neptune seconds_to_days / @NEPTUNE end end
class Region < ActiveRecord::Base has_and_belongs_to_many :seasons end
require 'test_helper' class DirectoriosControllerTest < ActionController::TestCase setup do @directorio = directorios(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:directorios) end test "should get new" do get :new assert_response :success end test "should create directorio" do assert_difference('Directorio.count') do post :create, directorio: { administracion: @directorio.administracion, asesoria: @directorio.asesoria, direccion: @directorio.direccion, litigio: @directorio.litigio, planificacion: @directorio.planificacion, procuradora: @directorio.procuradora, telefono1: @directorio.telefono1, telefono2: @directorio.telefono2, viceprocuradora: @directorio.viceprocuradora } end assert_redirected_to directorio_path(assigns(:directorio)) end test "should show directorio" do get :show, id: @directorio assert_response :success end test "should get edit" do get :edit, id: @directorio assert_response :success end test "should update directorio" do put :update, id: @directorio, directorio: { administracion: @directorio.administracion, asesoria: @directorio.asesoria, direccion: @directorio.direccion, litigio: @directorio.litigio, planificacion: @directorio.planificacion, procuradora: @directorio.procuradora, telefono1: @directorio.telefono1, telefono2: @directorio.telefono2, viceprocuradora: @directorio.viceprocuradora } assert_redirected_to directorio_path(assigns(:directorio)) end test "should destroy directorio" do assert_difference('Directorio.count', -1) do delete :destroy, id: @directorio end assert_redirected_to directorios_path end end
class AddSource < ActiveRecord::Migration def change add_column :extensions, :source, :string end end
require 'spec_helper' describe Swift::Pyrite::Transformer do subject { described_class.new({}) } describe '#unwind_type' do context "simple type" do let(:input_expression) do { :type_name=>"String" } end it "unwinds to 'String'" do str = subject.unwind_type(input_expression) expect(str).to(eq('String')) end end context "array literal type" do let(:input_expression) do { :type_name=>"String", :bracketed=>"[", } end it "unwinds to '[String]'" do str = subject.unwind_type(input_expression) expect(str).to(eq('[String]')) end end context "array literals and generics" do let(:input_expression) do { :type_name=>"Array", :bracketed=>"[", :generic=>{ :type_name=>"String" } } end it "unwinds to '[Array<String>]'" do str = subject.unwind_type(input_expression) expect(str).to(eq('[Array<String>]')) end end context "array literals and generics" do let(:input_expression) do { :type_name=>"Array", :generic=>{ :bracketed=>"[", :type_name=>"String" } } end it "unwinds to 'Array<[String]>'" do str = subject.unwind_type(input_expression) expect(str).to(eq('Array<[String]>')) end end context "single generic" do let(:input_expression) do { :type_name=>"Array", :generic=>{ :type_name=>"String" } } end it "unwinds to 'Array<String>'" do str = subject.unwind_type(input_expression) expect(str).to(eq('Array<String>')) end end context "double generic" do let(:input_expression) do { :type_name=>"Array", :generic=>{ :type_name=>"Array", :generic=>{ :type_name=>"Ruby" } } } end it "unwinds to 'Array<Array<Ruby>>'" do str = subject.unwind_type(input_expression) expect(str).to(eq('Array<Array<Ruby>>')) end end end end
require_relative './init' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end describe "ResetPasswordService" do def setup_logger log_instance_double = double('logger instance') allow(log_instance_double).to receive(:info) logger_double = double('logger') allow(logger_double).to receive(:log).and_return(log_instance_double) logger_double end before do IntegrationSpecHelper.InitializeMongo() end before(:each) do Helper.destroy_all ResetPasswordToken.destroy_all end it "can reset a password" do helper = build(:helper) helper.save old_password = helper.password_hash reset_password_token = ResetPasswordToken.new reset_password_token.user = helper reset_password_token.save! logger_double = setup_logger sut = ResetPasswordService.new logger_double new_password = 'password1' success, message = sut.reset_password reset_password_token.token, new_password expect(success).to eq(true) helper.reload auth_user = User.authenticate_using_email helper.email, new_password expect(auth_user).to_not eq(nil) end end
require 'rails_helper' RSpec.describe Api::CardsController, type: :controller do describe "GET #index" do it "returns the correct cards" do card_1 = create(:card) card_2 = create(:card) get :index cards_response = json_response ids = card_ids_from_response cards_response expect(ids).to match [card_1.id, card_2.id] expect(cards_response.length).to be 2 expect(response.status).to eq 200 end end describe "GET #show" do it "shows the correct card" do card = create(:card) get :show, params: { id: card.id } card_response = json_response expect(card_response[:front]).to eq card.front end end describe "POST #create" do RSpec.shared_examples_for "a failed card creation" do it "doesn't create the card" do card = attributes_for(:card) deck = create(:deck) expect { post :create, params: { card: card, deck_id: deck.id } }.to_not change(Card, :count) end it "returns a 403 status" do post :create, params: { card: attributes_for(:card) } expect(response.status).to eq 403 end end context "when signed in as an educator" do context "who owns the deck" do it "creates the card when the educator owns the deck" do educator = sign_in_educator course = create(:course, educator: educator) deck = create(:deck, course: course) card = attributes_for(:card, deck_id: deck.id) expect { post :create, params: { card: card } }.to change(Card, :count).by(1) end end it "doesn't create the card when the educator doesn't own the deck" do deck = create(:deck) card = attributes_for(:card, deck_id: deck.id) sign_in_educator expect { post :create, params: { card: card } }.to_not change(Card, :count) end end context "when not signed in" do it_behaves_like "a failed card creation" end context "when signed in as a student" do before do sign_in_student end it_behaves_like "a failed card creation" end end describe "PATCH #update" do context "for a successful update" do it "updates then renders the card" do educator = sign_in_educator card = create(:card, consecutive_correct_answers: 0) card.deck.course.update(educator: educator) front = "My updated front" patch :update, params: { id: card.id, card: { front: front } } card_response = json_response expect(card_response[:front]).to eq front expect(response.status).to eq 200 end end end def card_ids_from_response cards_response cards_response.map { |c| c[:id] } end end
require 'rails_helper' RSpec.describe PositionsController, type: :controller do describe "#index" do it "正常にレスポンスを返す" do get :index expect(response).to be_successful end end describe "#show" do before do @acount = FactoryBot.create(:account) @area = FactoryBot.create(:area) @category = FactoryBot.create(:category) @position = FactoryBot.create(:position, name:"テスト求人名", account:@acount , area:@area, category:@category) end it "正常に求人画面を表示する" do get :show, params: { id: @position.id } expect(response).to be_successful end end end
require 'pg' require 'bcrypt' class User attr_reader :id, :username, :password, :signed_in attr_writer :signed_in def initialize(id:, username:, password:) @id = id @username = username @password = password @signed_in = false end def self.all if ENV['RACK_ENV'] == 'test' connection = PG.connect(dbname: 'makersbnb_test') else connection = PG.connect(dbname: 'makersbnb') end result = connection.exec('SELECT * FROM users') result.map { |user| User.new( id: user['id'], username: user['username'], password: user['password'] )} end def self.create(username:, password:) if ENV['RACK_ENV'] == 'test' connection = PG.connect(dbname: 'makersbnb_test') else connection = PG.connect(dbname: 'makersbnb') end encrypted_password = BCrypt::Password.create(password) result = connection.exec("INSERT INTO users (username, password) VALUES('#{username}', '#{encrypted_password}') RETURNING id, username, password;") @user = User.new(id: result[0]['id'], username: result[0]['username'], password: result[0]['password']) end def self.find(number) if ENV['RACK_ENV'] == 'test' connection = PG.connect(dbname: 'makersbnb_test') else connection = PG.connect(dbname: 'makersbnb') end result = connection.exec("SELECT * FROM users WHERE id = #{number}") User.new(id: result[0]['id'], username: result[0]['username'], password: result[0]['password']) end def self.delete(id:) if ENV['RACK_ENV'] == 'test' connection = PG.connect(dbname: 'makersbnb_test') else connection = PG.connect(dbname: 'makersbnb') end result = connection.exec("DELETE FROM users WHERE id = #{id}") end def signed_in? @signed_in end def self.sign_in(username:, password:) user = User.authentication(username, password) if user.nil? user else user.signed_in = true user end # raise "Your password is incorrect" if User.authentication(username, password) # @signed_in = true end def sign_out @signed_in = false end def self.authentication(username, password) if ENV['RACK_ENV'] == 'test' connection = PG.connect(dbname: 'makersbnb_test') else connection = PG.connect(dbname: 'makersbnb') end result = connection.query("SELECT * FROM users WHERE username = '#{username}'") return unless result.any? return unless BCrypt::Password.new(result[0]['password']) == password User.new(id: result[0]['id'], username: result[0]['username'], password: result[0]['password']) end end
module Task class AttributeRevisionRecord < ActiveRecord::Base self.table_name = 'task_attribute_revisions' self.record_timestamps = false attr_accessible :attribute_name, :updated_value, :update_date, :next_update_date, :sequence_number, :computed serialize :updated_value scope :computed, where(:computed => true) belongs_to :task, :class_name => ::Task::Record, :foreign_key => :task_id, :inverse_of => :attribute_revisions def self.save_revisions(task_record, revisions) revisions.map{ |rev| save_revision(task_record, rev) }.compact end def self.save_revision(task_record, revision) scope = task_record.attribute_revisions record = if revision.persisted? scope.detect { |rec| rec.id == revision.id } else scope.build end record.map_from_revision(revision) record.save! if record.changed? revision.id = record.id end def self.load_revisions(task_record) task_record.attribute_revisions.map do |rec| attrs = { id: rec.id, updated_value: rec.updated_value, update_date: rec.update_date, sequence_number: rec.sequence_number, } if rec.next_update_date? attrs[:next_update_date] = rec.next_update_date end ::Task::Base.new_attribute_revision( rec.computed?, rec.attribute_name.to_sym, attrs ) end end def map_from_revision(rev) self.sequence_number = rev.sequence_number self.update_date = rev.update_date self.next_update_date = rev.has_next? ? rev.next_update_date : nil self.attribute_name = rev.attribute_name.to_s self.updated_value = rev.updated_value self.computed = rev.computed? self end end end
require 'rails_helper' RSpec.describe Album, type: :model do describe 'validations' do it 'has a valid factory' do expect(FactoryGirl.create(:album)).to be_valid end end describe 'associations' do it { should belong_to(:member) } it { should have_many(:images) } it { should have_many(:album_groups) } it { should have_many(:groups).through(:album_groups) } end end
class Subscription < ActiveRecord::Base # attr_accessible :title, :body validates :project_id, :presence => true, :numericality => { :only_integer => true } validates :luser_id, :presence => true, :numericality => { :only_integer => true } belongs_to :luser belongs_to :project end
class Installations < ActiveRecord::Migration class PrinterModel < ActiveRecord::Base attr_accessible :name end class InkSystem < ActiveRecord::Base attr_accessible :name end class ConsumptionProfile < ActiveRecord::Base attr_accessible :code, :name end class PrinterFunction < ActiveRecord::Base attr_accessible :name end def up create_table :clients do |t| t.string :code t.string :name t.timestamps end create_table :representatives do |t| t.string :first_name t.string :last_name t.timestamps end create_table :printer_models do |t| t.string :name t.timestamps end %w{4000 4800 4900 7600 7700 7800 7880 7890 7900 9600 9700 9800 9880 9890 9900 Other}.each do |name| printer_model = PrinterModel.new(name: name) printer_model.save! end create_table :ink_systems do |t| t.string :name t.timestamps end %w{BIS RMC CIS}.each do |name| ink_system = InkSystem.new(name: name) ink_system.save! end create_table :consumption_profiles do |t| t.string :code t.string :name t.timestamps end %w{A B C}.each do |code| consumption_profile = ConsumptionProfile.new(code: code, name: "Type #{code} consumption profile") consumption_profile.save! end create_table :printer_functions do |t| t.string :name t.timestamps end %w{Proof Repro Mix Film Other}.each do |name| printer_function = PrinterFunction.new(name: name) printer_function.save! end create_table :installations do |t| t.integer :client_id t.string :location t.integer :printer_model_id t.integer :ink_system_id t.date :installed_date t.integer :consumption_profile_id t.integer :representative_id t.integer :printer_function_id t.timestamps end end def down drop_table :clients drop_table :representatives drop_table :printer_models drop_table :ink_systems drop_table :consumption_profiles drop_table :printer_functions end end
require 'spec_helper' describe Relevant::Widget do describe "to_html" do it "renders the widgets template" do TestWidget.template "Hello <%= @options[:name] %>" TestWidget.template_format :erb widget = TestWidget.setup(:name => 'Mr. Roboto') widget.to_html.should == "Hello Mr. Roboto" end end describe "options" do it "tracks the types for form building" do TestWidget.available_options[:name].should == String end end describe 'template_format' do it "reads the format if given no options" do TestWidget.template_format.should == :erb end it "allows sets the format if you pass it" do TestWidget.template_format :haml TestWidget.template_format.should == :haml end end describe 'template' do it "reads the template if given no options" do TestWidget.template.should == "Hello <%= @options[:name] %>" end it "allows sets the template if you pass it" do TestWidget.template "Hello World" TestWidget.template.should == "Hello World" end end describe "label" do class Relevant::Something include Relevant::Widget end class Relevant::LongerNameWidget include Relevant::Widget end class Relevant::SpecialSnowflake include Relevant::Widget label "I'm a unique snowflake" end context "default case" do it "strips module namespaces and humanizes" do Relevant::Something.label.should == "Something" Relevant::LongerNameWidget.label.should == "Longer Name Widget" end end context "overridden label" do it "uses the overide" do Relevant::SpecialSnowflake.label.should == "I'm a unique snowflake" end end end describe "setup" do it "automagically converts whitespace options to nils" do TestWidget.setup(:name => " ").options[:name].should be_nil TestWidget.setup(:name => "").options[:name].should be_nil end end end
module LinkHelper def icon_link_to(type, body, url = nil, options = {}) link_to icon_tag(type, label: body, fixed: options.delete(:fixed), join: options.delete(:join)), url, options end end
class Link attr_accessor :key, :val, :next, :prev def initialize(key = nil, val = nil) @key = key @val = val @next = nil @prev = nil end end class LinkedList include Enumerable attr_reader :head, :tail def initialize @head = Link.new @tail = Link.new @head.next = @tail @tail.prev = @head end def first head.next end def last tail.prev end def [](idx) i = 0 my_each do |current_node| return current_node.val if i == idx i += 1 end nil end def get(key) current_node = first until current_node == tail return current_node.val if current_node.key == key current_node = current_node.next end nil end def insert(key, val) new_link = Link.new(key, val) new_link.next = tail new_link.prev = last last.next = new_link @tail.prev = new_link new_link end def remove(key) current_node = first until current_node == tail if current_node.key == key current_node.prev.next = current_node.next current_node.next.prev = current_node.prev end current_node = current_node.next end nil end def include?(key) current_node = first until current_node == tail return true if current_node.key == key current_node = current_node.next end false end def my_each current_node = first until current_node == tail yield current_node current_node = current_node.next end end end
require 'json' class WishesController < ApplicationController def show @wish = Wish.friendly.find(params[:id]) end def new @list = List.friendly.find(params[:list_id]) @wish = Wish.new authorize @wish end def create @wish = Wish.new @wish.assign_attributes(wish_params) @list = List.friendly.find(params[:list_id]) @wish.user = current_user @wish.list = @list authorize @wish if @wish.save flash[:notice] = "Wish was saved successfully." redirect_to @wish.list else flash.now[:alert] = "There was an error saving the wish. Please try again." render :new end end def edit @wish = Wish.friendly.find(params[:id]) authorize @wish end def update @list = List.friendly.find(params[:list_id]) @wish = Wish.friendly.find(params[:id]) @wish.assign_attributes(wish_params) authorize @wish if @wish.save flash[:notice] = "Wish was updated successfully." redirect_to @wish.list else flash.now[:alert] = "There was an error saving the wish. Please try again." render :edit end end def destroy @wish = Wish.friendly.find(params[:id]) authorize @wish if @wish.destroy flash[:notice] = "\"#{@wish.title}\" was deleted successfully." redirect_to @wish.list else flash.now[:alert] = "There was an error deleting the wish." render :show end end private def wish_params params.require(:wish).permit(:title, :body, :url, :price_cents, :currency, :rating, :list_id) end end
require 'test_helper' class ContentsControllerTest < ActionController::TestCase setup do @campaign = campaigns(:one) @content = contents(:one) end test "should get index" do get :index, params: { campaign_id: @campaign } assert_response :success end test "should get new" do get :new, params: { campaign_id: @campaign } assert_response :success end test "should create content" do assert_difference('Content.count') do post :create, params: { campaign_id: @campaign, content: @content.attributes } end assert_redirected_to campaign_content_path(@campaign, Content.last) end test "should show content" do get :show, params: { campaign_id: @campaign, id: @content } assert_response :success end test "should get edit" do get :edit, params: { campaign_id: @campaign, id: @content } assert_response :success end test "should update content" do put :update, params: { campaign_id: @campaign, id: @content, content: @content.attributes } assert_redirected_to campaign_content_path(@campaign, Content.last) end test "should destroy content" do assert_difference('Content.count', -1) do delete :destroy, params: { campaign_id: @campaign, id: @content } end assert_redirected_to campaign_contents_path(@campaign) end end
class GoodDog attr_accessor :name, :height, :weight def initialize(name) @name = name end def speak "#{@name} says arf!" end def self.what_am_i puts "I'm a GoodDog class!" end def to_s "this is dog" end end sparky = GoodDog.new("Sparky") #puts sparky.speak #puts sparky.name #sparky.name = "Spartacus" #puts sparky.name puts sparky #GoodDog.what_am_i
class CocktailHour < ActiveRecord::Base belongs_to :event has_and_belongs_to_many :instruments validates :start_time, presence: true, unless: :not_performing_at_cocktail? validates :end_time, presence: true, unless: :not_performing_at_cocktail? private def not_performing_at_cocktail? !performing end end
require 'spec_helper' CSV_EXAMPLES = YAML.load_file(Rails.root.join('spec/fixtures/usgs_service/sample_csv_fragments.yml')) describe USGSService do let(:service) { FactoryGirl.build :usgs_service } subject { service } context 'class-level interface' do subject { USGSService } describe '.latest' do it 'instantiates a new USGSService with the 7-day URL' do subject.should_receive(:new).with(USGSService::EQS7DAY) subject.latest end end describe '.new' do it 'returns new instance, given valid URI as parameter' do subject.new('uri://resource').should be_a(USGSService) end it 'raises an error given wrong number of params' do expect { subject.new() }.to raise_exception expect { subject.new('uri://resource', true) }.to raise_exception end it 'raises an error given bad URI' do expect { subject.new('bad uri') }.to raise_exception end end end describe '#data_url' do subject { USGSService.new 'uri://example' } it 'should be a URI parsed from the value given at initialization' do subject.data_url.should == URI.parse('uri://example') end end describe '#convert_row' do subject do data = CSV_EXAMPLES['sample_parsed_row_data'] || raise sample_row = CSV::Row.new(data.keys, data.values) service.convert_row(sample_row) end its([:source]) { should == 'ci' } its([:eqid]) { should == '12321' } its([:version]) { should == 1 } its([:date_time]) { should == DateTime.new(2013, 4, 19, 06, 47, 12) } its([:latitude]) { should == 39.8283 } its([:longitude]) { should == -122.8617 } its([:depth]) { should == 3.4 } its([:nst]) { should == 7 } its([:region]) { should == 'Northern California' } end describe '#all' do subject { service.all } it { should be_a_kind_of(Enumerable) } it { should have_exactly(3).items } end describe '#each' do it { subject.each.should be_an(Enumerator) } it 'should accept a block and pass to it the records' do values = [] subject.each { |r| values << r } values.should == subject.all end end describe '#csv' do subject { service.csv } it { should respond_to(:each) } it('should invoke #data') do service.should_receive(:csv) subject end describe 'each item' do subject { service.csv.first } it { should be_a CSV::Row } it 'should respond to [] with symbolized header names' do subject[:src].should == 'ci' end end end describe '#data' do it 'returns the body of the response from GET-ing #data_url' do subject.data.should == CSV_EXAMPLES['sample_set'] end end end
class Place < ActiveRecord::Base validates_presence_of :name validates_presence_of :phone validates_presence_of :address validates_presence_of :website validates_presence_of :user_id belongs_to :user geocoded_by :address after_validation :geocode end
class SearchSerializer include FastJsonapi::ObjectSerializer attributes :id, :query, :url has_many :cocktails end
def double_consonants(str) output = '' str.each_char do |char| output << char if char =~ /[a-z&&[^aeiou]]/i output << char end end output end puts double_consonants('String') == "SSttrrinngg" puts double_consonants("Hello-World!") == "HHellllo-WWorrlldd!" puts double_consonants("July 4th") == "JJullyy 4tthh" puts double_consonants('') == ""
namespace :db do desc "Erase and fill database" task :populate => :environment do [Location].each(&:delete_all) Dir.glob(Rails.root + 'app/IPlogs/*.log') do |file| puts file File.open(file, "r") do |f| f.each_line do |line| data = line.split(',') Location.create(address: data[0], attack_type: data[1]) end end end end end
module ProjectsHelper def add_responsibility_link(name) link_to_function name do |page| page.insert_html :bottom, :responsibilities, :partial => 'responsibility', :object => Responsibility.new end end def prefix(responsibility) "project[#{responsibility.new_record? ? 'new' : 'existing'}_responsibility_attributes][]" end end
class MonitoringsStudent < ApplicationRecord belongs_to :student, class_name: 'User', foreign_key: 'student_id', validate: true belongs_to :monitoring end
class Page < ApplicationRecord belongs_to :subject has_and_belongs_to_many :users scope :sample, -> {offset(rand(Page.count)).first} end
#!/usr/bin/env ruby # # Stats the TEM's firmware version, buffers, and keys, and dumps them to stdout. # # Author:: Victor Costan # Copyright:: Copyright (C) 2007 Massachusetts Institute of Technology # License:: MIT require 'rubygems' require 'tem_ruby' require 'pp' Tem.auto_conf print "Connected to TEM using #{$tem.transport.inspect}\n" begin fw_ver = $tem.fw_version print "TEM firmware version: #{fw_ver[:major]}.#{fw_ver[:minor]}\n" rescue Exception => e print "Could not read TEM firmware version. Is the TEM firmware installed?\n" print "#{e.class.name}: #{e}\n#{e.backtrace.join("\n")}\n" end begin b_stat = $tem.stat_buffers print "TEM memory stat:\n" pp b_stat rescue Exception => e print "Could not retrieve TEM memory stat. Is the TEM activated?\n" print "#{e.class.name}: #{e}\n#{e.backtrace.join("\n")}\n" end begin k_stat = $tem.stat_keys print "TEM crypto stat:\n" pp k_stat rescue Exception => e print "Could not retrieve TEM crypto stat. Is the TEM activated?\n" print "#{e.class.name}: #{e}\n#{e.backtrace.join("\n")}\n" end
class KittensController < ApplicationController def index @kittens = Kitten.all respond_to do |format| format.html format.json { render :json => @kittens } end end def show @kitten = Kitten.find(params[:id]) respond_to do |format| format.html format.json { render :json => @kitten } end end def new @kitten = Kitten.new end def create @kitten = Kitten.new(kitten_params) if @kitten.save flash[:success] = "You successfully added a kitten. D'aww." redirect_to kitten_path(@kitten.id) else flash[:error] = "You filled out your form improperly. Womp womp." render :new end end def edit @kitten = Kitten.find(params[:id]) end def update @kitten = Kitten.find(params[:id]) if @kitten.update(kitten_params) flash[:success] = "Kitten successfully updated." redirect_to kitten_path(@kitten.id) else flash.now[:error] = "You have failed to update the kitten." render :edit end end def destroy @kitten = Kitten.find(params[:id]) if @kitten.destroy flash[:success] = "Kitten deleted." redirect_to root_path else flash.now[:error] = "Kitten not deleted." render :show end end private def kitten_params params.require(:kitten).permit(:name, :age, :cuteness, :softeness) end end
# -*- coding: utf-8 -*- =begin Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: a. salário bruto. b. quanto pagou ao INSS. c. quanto pagou ao sindicato. d. o salário líquido. e. calcule os descontos e o salário líquido, conforme a tabela abaixo: + Salário Bruto : R$ - IR (11%) : R$ - INSS (8%) : R$ - Sindicato ( 5%) : R$ = Salário Liquido : R$ Obs.: Salário Bruto - Descontos = Salário Líquido. =end puts "=====================================================" print "Quanto voce ganha por hora?: " horaTrab = gets.chomp.to_i print "Digite o numero de horas trabalhadas (Mes):" horaTrabMes = gets.chomp.to_i salarioBruto = horaTrab * horaTrabMes impostoRenda = salarioBruto * 0.11.round(2) inss = salarioBruto * 0.08.round(2) sindicato = salarioBruto * 0.05.round(2) puts "Salario bruto: R$ #{salarioBruto}".to_s puts "Voce pagou ao imposto de renda: #{impostoRenda}".to_s puts "Voce pagou ao inss:#{inss}".to_s puts "Voce pagou ao sindicato: #{sindicato}".to_s puts "Salario liquido: R$ #{salarioBruto - impostoRenda - inss - sindicato}".to_s puts "====================================================="
class TermsController < ApplicationController def index return if params[:search].nil? headers['Last-Modified'] = Time.now.httpdate @tree = Tree.find_by_name(params[:search]) @term = Term.new render 'errors/no_such_tree' and return if @tree.nil? respond_to do |f| f.html f.json do render(json: Marshall::load(@tree.body)) end end end end
module AdobeConnect # Public: Current Gem version. VERSION = '1.0.8' end
#!/usr/bin/env ruby # Quick and simple script to transform user input # into ascii equivalent values. # Not including spaces. # ASCII character mapping def mapping(stringToSplit) arrSplit = stringToSplit.scan /\w/ return arrSplit.map { |n| n.ord } end if __FILE__ == $0 print "Enter the string that is to be converted to ascii: " userInput = gets.chomp splitBySpace = userInput.split(" ") responseType = splitBySpace.map {|splitStr| mapping(splitStr)} print responseType end
require 'test/unit' require_relative 'show' class ClassesTest < Test::Unit::TestCase def setup @show = Show.new end def test_1 @show.regex('price 12 dollari', /[aeiou]/) # il primo match @show.regex('price 12 dollari', /[\s]/) # questi li prende @show.regex('price 12$ dollaroni', /[$]/) #quelli speciali li posso inserire senza problemi end def test_2 value = 'see The PickAxe-page 123' @show.regex(value, /[A-F]/) # il primo match è la A di Axe @show.regex(value, /[A-Fa-f]/) # match: la prima e di see @show.regex(value, /[0-9]/) # match: 1 @show.regex(value, /[0-9][0-9]/) # match: 12 end def test_3 value = 'pRice 12 dollarz' @show.regex(value, /[A-Z]/) # R @show.regex(value, /[^A-Z]/) # p @show.regex(value, /[\w]/) # p (qualsiasi carattere, quindi prende il primo) @show.regex(value, /[^\w]/) # tutto quello che non è carattere, becca il primo spazio. value = 'price 12 dollarz' @show.regex(value, /[a-z][^a-z]/) # un carattere seguito da un non carattert: [e ] end def test_4 value = 'pRice 12 dollarz' @show.regex(value, /[0-9]/) # 1 @show.regex(value, /\d/) # 1 end def test_5 @show.regex('Über', /(?a)\w+/) @show.regex('Über', /(?d)\w+/) @show.regex('Über', /(?u)\w+/) @show.regex('Über', /(?a)\W+/) @show.regex('Über', /(?d)\W+/) @show.regex('Über', /(?u)\W+/) end def test_6 @show.regex('Price $12.', /[aeiou]/) @show.regex('Price $12.', /[[:digit:]]/) @show.regex('Price $12.', /[[:space:]]/) end def test_7 value = 'see [The PickAxe-page 123]' @show.regex(value, /[\[]/) @show.regex(value, /[\-]/) @show.regex(value, /[\d\-]/) # il primo dei due che incontra è il match del trattino. end def test_8 p 'now is the time'.gsub(/[[a-z]&&[^aeiou]]/, '*') # Sostituisco tutte le non vocali. end def test_9 value = 'δy / δx = 2πr' # occhio che in realtà il simbolo di derivata parziale è diverso. Qui c'è un delta... @show.regex(value, /\p{Alnum}/) @show.regex(value, /\p{Digit}/) @show.regex(value, /\p{Greek}/) end def test_10 value = 'It costs $12.' @show.regex(value, /c.s/) @show.regex(value, /./) @show.regex(value, /\./) end end
# This class is used to experiment with classes and functions in Ruby. class Bowling attr_reader :score def initialize @score = 0 end def hit(pin_count) @score += pin_count end end
class Customer < ApplicationRecord include Pinable include Reviewable include Tokenizable include Hashable # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :properties, dependent: :destroy has_many :jobs, through: :properties has_many :reviews, as: :owner has_many :reviews, as: :reviewee has_many :penalties has_many :notifications has_many :credit_cards has_many :payments has_many :invoices has_many :invoice_details mount_uploader :avatar, AvatarUploader after_create :send_welcome_email def full_name "#{first_name} #{last_name}" end def send_recover_password_email set_reset_password_pin! CustomerMailer.send_recover_password_app_email(self).deliver end def get_review(job) Review.where.not(id: job.reviews.where(owner: self).pluck(:id)) end private def send_welcome_email CustomerMailer.send_welcome_email(self).deliver end end
require 'rails_helper' RSpec.describe 'Registration', js: true do let!(:gym) { create(:gym) } before do visit new_user_registration_path end it 'successfully registers' do fill_in 'First Name', with: 'Test' fill_in 'Last Name', with: 'User' fill_in 'Email', with: 'test.user@email.com' fill_in 'Password', with: 'Te$tuseR1' select gym.name, from: 'Gym' check 'Not a robot' click_on 'Create User' expect(page).to have_content 'Please fill out remainder of information and get started working out. Click on image placeholder to complete all user information or click Start Workout to get started now.' end context 'fails to register user' do it 'is missing gym' do fill_in 'First Name', with: 'Test' fill_in 'Last Name', with: 'User' fill_in 'Email', with: 'test.user@email.com' fill_in 'Password', with: 'Te$tuseR1' check 'Not a robot' click_on 'Create User' expect(page).to have_content '* Gym must exist' end context 'email' do before do fill_in 'First Name', with: 'Test' fill_in 'Last Name', with: 'User' fill_in 'Password', with: 'Te$tuseR1' select gym.name, from: 'Gym' check 'Not a robot' end it 'is missing' do click_on 'Create User' expect(page).to have_content '* Email can\'t be blank' end it 'is not unique' do create(:user, gym: gym, email: 'test.user@email.com') fill_in 'Email', with: 'test.user@email.com' click_on 'Create User' expect(page).to have_content '* Email has already been taken' end end it 'is missing first name' do fill_in 'Last Name', with: 'User' fill_in 'Email', with: 'test.user@email.com' fill_in 'Password', with: 'Te$tuseR1' check 'Not a robot' click_on 'Create User' expect(page).to have_content '* First_name can\'t be blank' end it 'is missing last name' do fill_in 'First Name', with: 'Test' fill_in 'Email', with: 'test.user@email.com' fill_in 'Password', with: 'Te$tuseR1' check 'Not a robot' click_on 'Create User' expect(page).to have_content '* Last_name can\'t be blank' end it 'is missing password' do fill_in 'First Name', with: 'Test' fill_in 'Last Name', with: 'User' fill_in 'Email', with: 'test.user@email.com' check 'Not a robot' click_on 'Create User' expect(page).to have_content '* Password can\'t be blank' end it 'is a robot' do fill_in 'First Name', with: 'Test' fill_in 'Last Name', with: 'User' fill_in 'Email', with: 'test.user@email.com' fill_in 'Password', with: 'Te$tuseR1' click_on 'Create User' expect(page).to have_content 'User cannot be a robot' end end end
class ArticulosController < ApplicationController def index @articulos = Articulo.all end def show @articulo = Articulo.find(params[:id]) end def new end def create @articulo = Articulo.new(articulo_params) @articulo.save redirect_to @articulo end private def articulo_params params.require(:articulo).permit(:titular, :contenido) end end
#!/usr/bin/env ruby # (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> # Utility for finding filenames in a Plan R repo require 'plan-r/application/cli' require 'plan-r/repo' class App < PlanR::CliApplication def self.disable_plugins?; true; end def self.disable_jruby?; true; end def self.disable_vcs?; true; end def self.disable_db?; true; end def handle_options(args) @options.repo = nil @options.path = nil @options.patterns = [] opts = OptionParser.new do |opts| opts.banner = "Usage: #{File.basename $0} REPO DIR [GLOB] [...]" opts.separator "Find all filenames matching GLOB in Plan-R repo." opts.separator " * REPO is the path to a Plan-R repo dir." opts.separator " * DIR is a document path in the repo ('/')." opts.separator " * GLOB is a filename glob to match." opts.separator "" opts.separator "Options:" standard_cli_options(opts) end opts.parse!(args) @options.repo = args.shift @options.path = args.shift || '/' args.each do |arg| pat = arg.gsub('*','.*').gsub('?','.?') options.patterns << /#{pat}$/ end if ! @options.repo $stderr.puts "REPO argument required!" puts opts exit -1 end end def start repo = PlanR::Application::RepoManager.open(@options.repo) raise "Unable to open repo at '#{@options.repo}'" if ! repo PlanR::Application::DocumentManager.find(repo, @options.path) { |path| (@options.patterns.empty?) || \ (! @options.patterns.select { |pat| path =~ pat }.empty?) }.each { |path| display_item path } PlanR::Application::RepoManager.close(repo) end def display_item(path) # TODO: -l option? puts path end end if __FILE__ == $0 App.new(ARGV).exec end
class Comment include Mongoid::Document field :author, type: String field :comment, type: String # each comment is embeded in a post embedded_in :post end
class Type < ActiveRecord::Base validates :name, presence: true has_many :games, dependent: :destroy end
class SubscriptionsController < ApplicationController layout :orders_layout include UserInformation before_action :authenticate_user!, except: [:new, :create] before_action :check_admin, except: [:new, :create] before_action :verify_actions_for_filter, only: :filter before_action :load_subscription, only: [:show, :dispatch_box] before_action :load_plan, only: [:new, :create] before_action :validate_plan, only: [:new, :create] before_action :check_subscription_active, only: [:dispatch_box] before_action :check_same_shipping_address, only: :create before_action :create_or_update_user, only: :create before_action :check_not_already_dispatched, only: :dispatch_box def index @subscriptions = Subscription.order(created_at: :desc).page(params[:page]) end def filter @subscriptions = Subscription.send(params[:by]).order(created_at: :desc).page(params[:page]) render :index end def show end def destroy end def new end def create @subscription = @user.subscriptions.build(plan_id: @plan.id) if @subscription.save redirect_to root_path, notice: "Your subscription has been successfully created. You have chosen #{ @plan.type.humanize } plan." else flash[:alert] = 'Unable to create your subscription.' render({ action: :new }) end end def dispatch_box if @subscription.dispatch redirect_to(subscription_path(@subscription), notice: "Box is dispatched successfully at #{ @subscription.last_dispatch_date.to_s(:long) }. Expected payment: INR #{ @subscription.remaining_amount_to_be_collected }") else render({ action: :show }, alert: "Couldn't dispatch box. Error(s): #{ @subscription.error.full_messages.join('. ')}") end end protected def verify_actions_for_filter valid_filters = [:current_month_deliveries, :pending_payments, :pending_deliveries, :active, :cancelled_ones, :completed_ones] unless valid_filters.include?(params[:by].to_sym) redirect_to subscriptions_path, alert: 'Invalid Filter' end end def orders_layout admin_actions = ['index', 'show', 'filter'] (@user.admin? && admin_actions.include?(action_name.to_s)) ? 'admin' : 'user' end def load_subscription @subscription = Subscription.find_by(id: (params[:subscription_id] || params[:id])) unless @subscription.present? redirect_to({ action: :index }, alert: 'No such subscription found') end end def load_plan @plan = Plan.find_by(id: params[:plan_id].to_i) unless @plan redirect_to root_path, alert: 'No such plan exists' end end def validate_plan unless Plan.find_by(id: params[:plan_id].to_i).active? redirect_to root_path, alert: 'This plan is no longer active' end end def create_or_update_user unless @user.update(user_params) render({ action: :new }, alert: 'Please make sure your details are valid') end end def initialize_subscription @subscription = @user.build_subscription(active: true, plan_id: @plan.id) end def check_not_already_dispatched if @subscription.box_dispatched_for_current_month? redirect_to(subscription_path(@subscription), alert: 'Box already dispatched for this month') end end def check_subscription_active unless @subscription.active? redirect_to(subscription_path(@subscription), alert: "This subscription plan(#{ @subscription.id }) is not active") end end end
module Issues class UpdateComment prepend SimpleCommand attr_reader :current_user, :args, :id, :comment_id, :message def initialize(current_user, args) @id = args[:id] @comment_id = args[:comment_id] @message = args[:message] end def call return nil unless (valid_user? && valid_data?) issue = Issues::Issue.find(id) issue.comments.find(id: comment_id).update!(message: message) issue end def valid_user? true end def valid_data? true end end end
platform 'osx-13-arm64' do |plat| plat.inherit_from_default plat.output_dir File.join('apple', '13', 'puppet7', 'arm64') end
Before do @old_root_node_seed = Constants::ROOT_SERIALIZED_ADDRESS silence_warnings do Constants::ROOT_SERIALIZED_ADDRESS = MoneyTree::Master.new(seed_hex: '0123456789abcdef').to_serialized_address end end After do silence_warnings do Constants::ROOT_SERIALIZED_ADDRESS = @old_root_node_seed end end
require 'rails_helper' RSpec.describe Vote, type: :model do it { should validate_presence_of(:comic_id) } it { should validate_uniqueness_of(:comic_id) } end
module Cms::MealTypesHelper def set_selected(meal_type, i, key, time_type) time_slot_field_name = "#{get_slot_number_string(i).downcase}_slot" time_for_time_slot = meal_type.send(time_slot_field_name) if !time_for_time_slot.blank? time_for_time_slot_split = time_for_time_slot.split("-") return "selected" if time_type == 'to_time' and time_for_time_slot_split.last.strip == key return "selected" if time_type == 'from_time' and time_for_time_slot_split.first.strip == key end end def get_slot_number_string i {1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth", 6 => "Sixth"}[i] end end
namespace :xylophone do desc 'bootstrap the xylophone application from a new image' task :bootstrap do system('bundle install') system('bundle exec rake db:migrate') system('bundle exec rake db:seed') system('bundle exec rake db:migrate RAILS_ENV=test') system('bundle exec rake db:seed RAILS_ENV=test') system('bundle exec rspec spec/models') `bundle exec rspec spec/helpers` `bundle exec node_modules/karma/bin/karma start xy.conf.js --single-run` end desc 'start the app in production mode' task :start do system('RAILS_ENV=production bundle exec rake assets:clean') system('RAILS_ENV=production bundle exec rake assets:precompile') system('bundle exec rails server Puma -p 3000 -e production -d --binding 127.0.0.1') system('sidekiq -C config/sidekiq.yml -d -e production') end desc 'restart the app in production mode' task :restart do system('bundle exec rake xylophone:stop') system('bundle exec rake xylophone:start') end desc 'kill the app' task :stop do pid_file = 'tmp/pids/server.pid' pid = File.read(pid_file).to_i and File.delete(pid_file) Process.kill(9, pid) system('sidekiqctl stop tmp/pids/sidekiq.pid 60') end namespace :db do desc 'reset the database (clears all data)' task :reset do system('bundle exec rake db:drop') system('bundle exec rake db:create') system('bundle exec rake db:migrate') system('bundle exec rake db:seed') system('bundle exec rake db:drop RAILS_ENV=test') system('bundle exec rake db:create RAILS_ENV=test') system('bundle exec rake db:migrate RAILS_ENV=test') system('bundle exec rake db:seed RAILS_ENV=test') end end end
module SequelSpec module Matchers module Validation class ValidateSchemaTypesMatcher < ValidateMatcher def description desc = "validate schema types of #{@attribute.inspect}" desc << " with option(s) #{hash_to_nice_string @options}" unless @options.empty? desc end def validation_type :validates_schema_types end end def validate_schema_types(attribute) ValidateSchemaTypesMatcher.new(attribute) end alias :validate_schema_types_of :validate_schema_types end end end
class Person < ActiveRecord::Base using_access_control belongs_to :user has_friendly_id :name, :use_slug => true validates_presence_of :name, :job_title, :email, :phone, :mobile, :profile, :user validates_uniqueness_of :name, :email validates_format_of :email, :with => %r{\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z}i has_many :companies, :dependent => :destroy, :order => 'start_date DESC' has_many :skills, :dependent => :destroy, :order => :position has_many :schools, :dependent => :destroy, :order => 'date_from DESC' has_one :social_media, :dependent => :destroy validates_associated :companies, :skills, :schools, :social_media accepts_nested_attributes_for :social_media accepts_nested_attributes_for :companies, :allow_destroy => true, :reject_if => lambda { |a| a['name'].blank? and a['role'].blank? and a['business_type'].blank? and a['start_date(3i)'] == '1' and a['end_date(3i)'] == '1' } accepts_nested_attributes_for :skills, :allow_destroy => true, :reject_if => lambda { |a| a.values.all?(& :blank?) } accepts_nested_attributes_for :schools, :allow_destroy => true, :reject_if => lambda { |a| a['name'].blank? and a['course'].blank? and a['date_to(3i)'] == '1' and a['date_from(3i)'] == '1' } has_attached_file :photo, :styles => {:small => '100x100#'} validates_attachment_size :photo, :less_than => 10.megabytes, :unless => lambda { |m| m[:photo].nil? } validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png'], :unless => lambda { |m| m[:photo].nil? } named_scope :search, lambda { |query| { :conditions => ['(lower(people.name) LIKE :query OR lower(people.email) LIKE :query OR lower(people.job_title) LIKE :query)', {:query => "%#{query.downcase}%"}] } } named_scope :sorted_by, lambda { |option| case option.to_s when 'ascending_name' {:order => 'lower(people.name) ASC'} when 'descending_name' {:order => 'lower(people.name) DESC'} when 'ascending_email' {:order => 'lower(people.email) ASC'} when 'descending_email' {:order => 'lower(people.email) DESC'} when 'ascending_job_title' {:order => 'lower(people.job_title) ASC'} when 'descending_job_title' {:order => 'lower(people.job_title) DESC'} else raise ArgumentError, "Invalid sort option: #{option.inspect}" end } def self.filter(options) # chain together all the conditions raise(ArgumentError, "Expected Hash, got #{options.inspect}") unless options.is_a?(Hash) ar_proxy = Person options.each do |key, value| next unless self.filter_options.include?(key) # only consider the filter options next if value.blank? # ignore blank list options ar_proxy = ar_proxy.send(key, value) # compose this option end ar_proxy # return the ActiveRecord proxy object end def self.filter_options # add any named scopes that should be excluded from search options self.scopes.map { |s| s.first } - [:named_scope_that_is_not_a_filter_option] end def skills_by_category categories = Hash.new { |h, k| h[k] = [] } skills.each { |s| categories[s.category.name] << s } categories end def first_company companies.sort { |a, b| a.start_date <=> b.start_date }.first end def first_school schools.sort { |a, b| a.date_from <=> b.date_from }.first end end
require 'rails_helper' RSpec.describe User, type: :model do it { should have_many(:projects) } it { should have_many(:tasks).through(:projects) } end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe TextfilesController do def mock_textfile(stubs={}) @mock_textfile ||= mock_model(Textfile, stubs) @mock_textfile.stub!(:needs_fs_update=) @mock_textfile.stub!(:modified_at=) return @mock_textfile end describe "GET index" do it "assigns all textfiles as @textfiles" do Textfile.stub!(:find).with(:all).and_return([mock_textfile]) #get :index #assigns[:textfiles].should == [mock_textfile] end end describe "GET show" do it "assigns the requested textfile as @textfile" do Textfile.stub!(:find).with("37").and_return(mock_textfile) get :show, :id => "37" assigns[:textfile].should equal(mock_textfile) end end describe "GET new" do it "assigns a new textfile as @textfile" do Textfile.stub!(:new).and_return(mock_textfile) get :new assigns[:textfile].should equal(mock_textfile) end end describe "GET edit" do it "assigns the requested textfile as @textfile" do Textfile.stub!(:find).with("37").and_return(mock_textfile) get :edit, :id => "37" assigns[:textfile].should equal(mock_textfile) end end describe "POST create" do describe "with valid params" do it "assigns a newly created textfile as @textfile" do Textfile.stub!(:new).with({'these' => 'params'}).and_return(mock_textfile(:save => true)) post :create, :textfile => {:these => 'params'} assigns[:textfile].should equal(mock_textfile) end it "redirects to the created textfile" do Textfile.stub!(:new).and_return(mock_textfile(:save => true)) post :create, :textfile => {} response.should redirect_to(textfile_url(mock_textfile)) end end describe "with invalid params" do it "assigns a newly created but unsaved textfile as @textfile" do Textfile.stub!(:new).with({'these' => 'params'}).and_return(mock_textfile(:save => false)) post :create, :textfile => {:these => 'params'} assigns[:textfile].should equal(mock_textfile) end it "re-renders the 'new' template" do Textfile.stub!(:new).and_return(mock_textfile(:save => false)) post :create, :textfile => {} response.should render_template('new') end end end describe "PUT update" do describe "with valid params" do it "updates the requested textfile" do Textfile.should_receive(:find).with("37").and_return(mock_textfile) mock_textfile.should_receive(:update_attributes).with({'these' => 'params'}) put :update, :id => "37", :textfile => {:these => 'params'} end it "assigns the requested textfile as @textfile" do Textfile.stub!(:find).and_return(mock_textfile(:update_attributes => true)) put :update, :id => "1" assigns[:textfile].should equal(mock_textfile) end it "redirects to the textfile" do Textfile.stub!(:find).and_return(mock_textfile(:update_attributes => true)) put :update, :id => "1" response.should redirect_to(textfile_url(mock_textfile)) end end describe "with invalid params" do it "updates the requested textfile" do Textfile.should_receive(:find).with("37").and_return(mock_textfile) mock_textfile.should_receive(:update_attributes).with({'these' => 'params'}) put :update, :id => "37", :textfile => {:these => 'params'} end it "assigns the textfile as @textfile" do Textfile.stub!(:find).and_return(mock_textfile(:update_attributes => false)) put :update, :id => "1" assigns[:textfile].should equal(mock_textfile) end it "re-renders the 'edit' template" do Textfile.stub!(:find).and_return(mock_textfile(:update_attributes => false)) put :update, :id => "1" response.should render_template('edit') end end end describe "DELETE destroy" do it "destroys the requested textfile" do Textfile.should_receive(:find).with("37").and_return(mock_textfile) mock_textfile.should_receive(:destroy) delete :destroy, :id => "37" end it "redirects to the textfiles list" do Textfile.stub!(:find).and_return(mock_textfile(:destroy => true)) delete :destroy, :id => "1" response.should redirect_to(textfiles_url) end end end
# frozen_string_literal: true feature 'Authentication user', js: true do before(:all) do @file = './spec/test_data/credentials.yaml' @user = User.new @user.save_to_file(@file) end before(:each) do @home_page = HomePage.new @home_page.load end after(:all) { File.delete(@file) } scenario 'User can register' do expect(@home_page.header.text).to include 'Redmine@testautomate.me' @home_page.menu.sigh_up_link.click sign_up_user(@user) expect(@home_page.menu.logged_as.text).to include "Logged in as #{@user.user_name}" end scenario 'User can log in' do credentials = @user.read_from_file(@file) expect(@home_page.header.text).to include 'Redmine@testautomate.me' @home_page.menu.sigh_in_link.click sign_in_user(credentials[:user_name], credentials[:password]) expect(@home_page.menu.logged_as.text).to include "Logged in as #{credentials[:user_name]}" end end
require 'peep' require 'pg' require_relative '../helper_methods.rb' describe Peep do let(:con) { PG.connect test_database } let(:test_database) { { dbname: 'chitter_chatter_test' }} describe '.create' do it 'creates a new peep' do peep = Peep.create(message: "Henlo World") expect(peep).to be_a Peep expect(peep.message).to eq "Henlo World" end end end
class User < ActiveRecord::Base validates_uniqueness_of :email, presence: true has_secure_password has_and_belongs_to_many :gifs ############FAVES########## def favorite(url) unless self.gifs.include?(url) self.gifs << url end end def unfavorite(url) self.gifs.delete(Gif.where(url: url)) end end
class FontArchitypeRenner < Formula version "001.000" url "https://fontlot.com/wp-content/uploads/2017/08/archityperenner.zip" desc "Architype Renner" homepage "https://fontlot.com/4598/architype-renner/" def install (share/"fonts").install "ArchitypeRenner-Bold.otf" (share/"fonts").install "ArchitypeRenner-Demi.otf" (share/"fonts").install "ArchitypeRenner-Medium.otf" (share/"fonts").install "ArchitypeRenner-Regular.otf" end test do end end
# Code your prompts here! # Try starting out with puts'ing a string. puts "Hi, you've been invited to a party! What is your name?" guest_name = gets.chomp.capitalize puts "What is the party?" party_name = gets.chomp puts "When is it?" date = gets.chomp puts "What time is it?" time = gets.chomp puts "Who is the host?" host_name = gets.chomp puts "Dear #{guest_name.capitalize}, you are cordially invited to #{party_name} on #{date} at #{time}. Please RSVP soon. Sincerely, #{host_name}"
require 'rubygems' require 'neography' require 'sinatra/base' require 'uri' class Neovigator < Sinatra::Application set :haml, :format => :html5 set :app_file, __FILE__ configure :test do require 'net-http-spy' Net::HTTP.http_logger_options = {:verbose => true} end helpers do def link_to(url, text=url, opts={}) attributes = "" opts.each { |key,value| attributes << key.to_s << "=\"" << value << "\" "} "<a href=\"#{url}\" #{attributes}>#{text}</a>" end def neo @neo = Neography::Rest.new(ENV['NEO4J_URL'] || "http://localhost:7474") end end def neighbours {"order" => "depth first", "uniqueness" => "none", "return filter" => {"language" => "builtin", "name" => "all_but_start_node"}, "depth" => 1} end def node_id(node) case node when Hash node["self"].split('/').last when String node.split('/').last else node end end START="stephenfry" def node_for(id) id = START if !id return neo.get_node(id) if id =~ /\d+/ return (neo.get_node_auto_index("name",id)||[]).first || neo.get_node_auto_index("name",START).first end def get_properties(node) properties = "<ul>" node["data"].each_pair do |key, value| properties << "<li><b>#{key}:</b> #{value}</li>" end properties + "</ul>" end get '/resources/show' do content_type :json node = node_for(params[:id]) user = node["data"]["name"] connections = neo.traverse(node, "fullpath", neighbours) incoming = Hash.new{|h, k| h[k] = []} outgoing = Hash.new{|h, k| h[k] = []} nodes = Hash.new attributes = Array.new connections.each do |c| c["nodes"].each do |n| nodes[n["self"]] = n["data"] end end connections.each do |c| rel = c["relationships"][0] if rel["end"] == node["self"] incoming["Incoming:#{rel["type"]}"] << {:values => nodes[rel["start"]].merge({:id => node_id(rel["start"]) }) } else outgoing["Outgoing:#{rel["type"]}"] << {:values => nodes[rel["end"]].merge({:id => node_id(rel["end"]) }) } end end incoming.merge(outgoing).each_pair do |key, value| attributes << {:id => key.split(':').last, :name => key, :values => value.collect{|v| v[:values]} } end attributes = [{"name" => "No Relationships","name" => "No Relationships","values" => [{"id" => "#{user}","name" => "No Relationships "}]}] if attributes.empty? @node = {:details_html => "<h2>User: #{user}</h2>\n<p class='summary'>\n#{get_properties(node)}</p>\n", :data => {:attributes => attributes, :name => user, :id => node_id(node)} } @node.to_json end get '/' do @user = node_for(params["user"]||START)["data"]["name"] haml :index end end
require 'rails_helper' RSpec.describe UsersController, type: :controller do let(:stripe_helper) { StripeMock.create_test_helper } before { StripeMock.start } after { StripeMock.stop } it "updates the users payment method" do @request.env["devise.mapping"] = Devise.mappings[:user] plan = stripe_helper.create_plan(:id => 'idrivealot_monthly', :amount => 200) stripe_user = build(:user) stripe_user.stripe_card_token = stripe_helper.generate_card_token stripe_user.save_with_payment post :update_payment, id: stripe_user.id, user: {stripe_card_token: stripe_helper.generate_card_token} expect(response).to redirect_to mileage_records_path end end