text
stringlengths
10
2.61M
# frozen_string_literal: true describe Facts::Macosx::SystemProfiler::SerialNumber do describe '#call_the_resolver' do subject(:fact) { Facts::Macosx::SystemProfiler::SerialNumber.new } let(:value) { 'C02WW1LAG8WL' } let(:expected_resolved_fact) { double(Facter::ResolvedFact, name: 'system_profiler.serial_number', value: value) } before do expect(Facter::Resolvers::SystemProfiler).to receive(:resolve).with(:serial_number_system).and_return(value) expect(Facter::ResolvedFact).to receive(:new) .with('system_profiler.serial_number', value) .and_return(expected_resolved_fact) end it 'returns system_profiler.serial_number fact' do expect(fact.call_the_resolver).to eq(expected_resolved_fact) end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? # def current_user # @current_user ||= Player.find_by(id: session[:player_id]) if session[:player_id] # end # helper_method :current_user def current_game @current_game ||= Game.find(session[:game_id]) if session[:game_id] end helper_method :current_game protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :email, :password]) # devise_parameter_sanitizer.permit(:account_update, keys: [:username, :email, :password, :current_password]) end end
require "capybara" feature "Enter player names" do scenario "players fill out forms" do sign_in_and_play expect(page).to have_text("John vs Duncan") end end
class Office < ActiveRecord::Base has_and_belongs_to_many :addresses belongs_to :listing belongs_to :office def address self.addresses.first end end
class AddMentor < ActiveRecord::Migration def change add_column :users, :isMentor, :boolean, default: false end end
require 'rails_helper' RSpec.describe EmailProcessor, :type => :model do describe "parsing emails" do before do @test_params = { "stripped-text" => "no longer checking the authenticity token when receiving emails", "body-plain" => "no longer checking the authenticity token when receiving emails\r\n", "Date" => "Mon, 13 Oct 2014 14:38:29 -0500", "timestamp" => "1413229117", "Return-Path"=>"<test@test.com>", } @ep = EmailProcessor.new @daily = @ep.process_email(@test_params) @test_employee = FactoryGirl.create(:active_employee, email: "test@test.com") end it "should get the plain body text" do expect(@daily.content).to eql("no longer checking the authenticity token when receiving emails") end it "should get the sender of the email" do allow(Employee).to receive(:find_by_email).and_return(@test_employee) @daily = @ep.process_email(@test_params) expect(@daily.employee).to eql(@test_employee) end describe "parse email from return path" do it "should extract the email" do expect(@ep.parse_email("<test@test.com>")).to eql("test@test.com") end it "should correctly fetch the email from the params" do daily = @ep.process_email(@test_params) expect(daily.employee.email).not_to be_nil expect(daily.employee.email).to eql("test@test.com") end end it "should get the date recieved" do expect(@daily.date_recieved).to eql(DateTime.parse("Mon, 13 Oct 2014 14:38:29 -0500")) end it "should get the date" do expect(@daily.date).to eql(DateTime.parse("Mon, 13 Oct 2014 14:38:29 -0500")) end end end
class CreateLogs < ActiveRecord::Migration[5.1] def change create_table :logs do |t| t.integer :round t.integer :day t.text :content t.integer :status, default: 0 t.integer :motivation, default: 5 t.timestamps end end end
class AccountTransaction < ApplicationRecord belongs_to :origin, class_name: "Account", foreign_key: "origin_account_id" belongs_to :recipient, class_name: "Account", foreign_key: "recipient_account_id", optional: true enum transaction_type: [:withdraw, :deposit, :transfer] validates :amount, presence: true, numericality: true validates :transaction_type, presence: true, inclusion: { in: transaction_types.keys } end
class FootballPlayer < ActiveRecord::Base has_many :fantasy_team_players scope :random, -> { order('RANDOM()') } scope :goalkeepers, -> { where(position: "Goalkeeper") } scope :defenders, -> { where(position: "Defender") } scope :attackers, -> { where(position: "Attacker") } scope :not_in_league, -> (fantasy_league) { where.not(id: fantasy_league.football_player_ids ) } # TODO: change to use joins rather than nested ids end
class Catalogo < ActiveRecord::Base self.table_name = 'catalogos' self.primary_key = 'id' has_many :especies_catalogos, :class_name => 'EspecieCatalogo' #has_one :especie, :through => :especies_catalogos, :class_name => 'EspecieCatalogo', :foreign_key => 'catalogo_id' IUCN_QUITAR_EN_FICHA = []#['Riesgo bajo (LR): Dependiente de conservación (cd)', 'No evaluado (NE)', 'Datos insuficientes (DD)','Riesgo bajo (LR): Preocupación menor (lc)', 'Riesgo bajo (LR): Casi amenazado (nt)'] AMBIENTE_EQUIV_MARINO = ['Nerítico', 'Nerítico y oceánico', 'Oceánico'] NIVELES_PRIORITARIAS = %w(alto medio bajo) def nom_cites_iucn(cat_actual = false, ws = false) condicion = ws ? (nivel2 == 1 || nivel2 == 3) : (nivel2 > 0) if nivel1 == 4 && condicion && nivel3 > 0 return descripcion if cat_actual limites = Bases.limites(id) id_inferior = limites[:limite_inferior] id_superior = limites[:limite_superior] edo_conservacion = Catalogo.where(:nivel1 => nivel1, :nivel2 => nivel2, :nivel3 => 0).where(:id => id_inferior..id_superior).first #el nombre del edo. de conservacion edo_conservacion ? edo_conservacion.descripcion : nil else nil end end # Saco el nombre del ambiente ya que al unir los catalogos, los nombres aveces no coinciden def ambiente if nivel1 == 2 && nivel2 == 6 && nivel3 > 0 #se asegura que el valor pertenece al ambiente descripcion else nil end end # Saco el nivel de la especie prioritaria def prioritaria if nivel1 == 4 && nivel2 == 4 && nivel3 > 0 #se asegura que el valor pertenece a prioritaria del diario oficial (DOF) descripcion elsif nivel1 == 4 && nivel2 == 5 && nivel3 > 0 #se asegura que el valor pertenece a prioritaria de de la CONABIO nil end end def self.ambiente_todos ambiente = Catalogo.where(:nivel1 => 2, :nivel2 => 6).where('nivel3 > 0').map(&:descripcion).uniq ambiente.delete_if{|a| AMBIENTE_EQUIV_MARINO.include?(a)} end def self.nom_cites_iucn_todos nom = where(:nivel1 => 4, :nivel2=> 1).where('nivel3 > 0').map(&:descripcion).uniq nom = [nom[3],nom[1],nom[0],nom[2]]#Orden propuesto por cgalindo # Esta categoria de IUCN esta repetida y no tenia nada asociado iucn = where(:nivel1 => 4, :nivel2=> 2).where("nivel3 > 0 AND descripcion != 'Riesgo bajo (LR): Casi amenazada (nt)'").map(&:descripcion).uniq iucn = [iucn[7],iucn[6],iucn[9],iucn[8],iucn[4],iucn[3],iucn[2],iucn[1],iucn[0],iucn[5]]#IDEM, el iucn[5] se quita en el helper, consultar con dhernandez ASAP cites = where(:nivel1 => 4, :nivel2=> 3).where('nivel3 > 0').map(&:descripcion).uniq #Esta ya viene en orden (I,II,III) {:nom => nom, :iucn => iucn, :cites => cites} end end
module ApplicationHelper def flash_class(type) case type when "alert" "message--alert" when "notice" "message--success" else "message--warning" end end end # def active_navigation(path) # "navigation__item--active navigation__item__link--active" if params[:controller] == path # end
class DeleteRailwayStations < ActiveRecord::Migration[5.1] def change drop_table :railway_stations end end
# OpSpec is the specification of an Operation to be added to a Graph # (using Graph AddOperation). class Tensorflow::OpSpec attr_accessor :type, :name, :input, :attr, :inputlist # @!attribute type # Type of the operation (e.g., "Add", "MatMul"). # @!attribute name # Name by which the added operation will be referred to in the Graph. # If omitted, defaults to Type. # @!attribute input # Inputs to this operation, which in turn must be outputs # of other operations already added to the Graph. # # An operation may have multiple inputs with individual inputs being # either a single tensor produced by another operation or a list of # tensors produced by multiple operations. For example, the "Concat" # operation takes two inputs: (1) the dimension along which to # concatenate and (2) a list of tensors to concatenate. Thus, for # Concat, len(Input) must be 2, with the first element being an Output # and the second being an OutputList. # @!attribute attr # Map from attribute name to its value that will be attached to this # operation. # Other possible fields: Device, ColocateWith, ControlInputs. def initialize(name = nil, type = nil, attribute = nil, input = nil, inputlist = nil) self.name = name self.type = type self.attr = if attribute.nil? {} else attribute end self.input = if input.nil? [] else input end self.inputlist = if inputlist.nil? [] else inputlist end raise 'The operation specification is either input or inputlist but not both.' if !input.nil? && !inputlist.nil? end end
require_relative 'import_controller' require_relative 'client' module Budget module PcFinancial class ImportJob def initialize(client_number: nil, password: nil, controller: nil, logger: Budget::NullLogger) @controller = controller @controller ||= PcFinancial::ImportController.new( PcFinancial::Client.new(client_number, password, logger: logger) ) @logger = logger end # TODO: integrate matt's work better def call(accounts: nil, since: nil) txn_data = controller.fetch(accounts: accounts, since: since) logger.info 'ingesting transactions...' txn_data.each_pair do |account, txns| a = ImportableAccount.find_or_initialize_by(source_id: account) a.name = account a.save txns.each do |txn| t = ImportableTransaction.find_or_initialize_by(source_id: txn.id) t.date = txn.date t.description = txn.notes t.category = 'unknown' t.expense = txn.expense? t.cents = txn.amount.abs t.account = account t.account_id = a.source_id t.source_id = txn.id t.save end end end private attr_reader :controller, :logger end end end
# @param {String} moves # @return {Boolean} def judge_circle(moves) move_map = { "U" => [0, 1], "D" => [0, -1], "L" => [-1, 0], "R" => [1, 0] } origin = [0, 0] moves.each_char do |item| move_step = move_map[item] origin[0] += move_step[0] origin[1] += move_step[1] end return origin == [0, 0] end def judge_circle1(moves) return moves.count('U') == moves.count('D') && moves.count('L') == moves.count('R') end
require 'spec_helper' describe Survey do let(:survey) { build(:survey) } it "is valid" do survey.should be_valid end it {should accept_nested_attributes_for (:questions)} it {should have_many(:users).through(:completed_surveys)} end
class DailyDigestJob < ApplicationJob include Sidetiq::Schedulable queue_as :default recurrence { daily(1) } def perform User.find_each do |user| DailyMailer.digest(user).deliver_later end end end
class AttendancesController < ApplicationController # GET /attendances # GET /attendances.json def index @conference = Conference.find(params[:conference_id]) @attendees = @conference.attendances respond_to do |format| format.html # index.html.erb format.json { render json: @attendees } end end # GET /attendances/1 # GET /attendances/1.json def show @conference = Conference.find(params[:conference_id]) @attendance = Attendance.find(params[:id]) @abstracts = @attendance.abstracts @like = Like.where("attendance_id = ? AND user_id = ?", @attendance.id, current_user.id).first @like_count = Like.where("attendance_id = ? AND user_id = ?", @attendance.id, current_user.id).count if(@attendance.user_id) @user = User.find(@attendance.user_id) # @keys = Abstract.where(:user_id => @user.id, :keywords => true).first @bio = Abstract.where(:user_id => @user.id, :is_bio => true).first @conferences = @user.get_conferences end if(current_user) @user_attendance = Attendance.where(:conference_id => @conference.id, :user_id => current_user.id).first if @user_attendance.nil? flash[:notice] = "You have no right to view this attendee" return redirect_to conferences_path end @connection = Connection.where(:attendance1_id => @user_attendance.id, :attendance2_id => params[:id]).first end respond_to do |format| format.html # show.html.erb format.json { render json: { :attendee => @attendance, :abstracts => @abstracts } } end end # GET /attendances/new # GET /attendances/new.json def new @attendance = Attendance.new respond_to do |format| format.html # new.html.erb format.json { render json: @attendance } end end # GET /attendances/1/edit def edit @attendance = Attendance.find(params[:id]) end # POST /attendances # POST /attendances.json def create @attendance = Attendance.create(params[:attendance]) respond_to do |format| if @attendance.save format.html { redirect_to @attendance, notice: 'Attendance was successfully created.' } format.json { render json: @attendance, status: :created, location: @attendance } else format.html { render action: "new" } format.json { render json: @attendance.errors, status: :unprocessable_entity } end end end # PUT /attendances/1 # PUT /attendances/1.json def update @attendance = Attendance.find(params[:id]) respond_to do |format| if @attendance.update_attributes(params[:attendance]) format.html { redirect_to @attendance, notice: 'Attendance was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @attendance.errors, status: :unprocessable_entity } end end end # DELETE /attendances/1 # DELETE /attendances/1.json def destroy #TODO Jbender will fix this later to use destroy instead of delete @attendance = Attendance.find(params[:id]) @conference = Conference.find(@attendance.conference_id) # Delete connected connections @attendance.connections.delete_all @connections = Connection.find(:all, :conditions => "attendance2_id = #{@attendance.id}") @connections.each do |c| c.delete end @attendance.delete @attendees = @conference.attendances respond_to do |format| format.html { redirect_to @conference, notice: 'Attendance successfully deleted' } format.json { render json: @conference } end end end
class AddSaltToUsers < ActiveRecord::Migration[5.1] def up # def change # reversible do |dir| # dir.up add_column :users, :salt, :string rename_column :users, :password, :encrypted_password # end end def down remove_column :users, :salt rename_column :users, :encrypted_password, :password end end
class Activity < ActiveRecord::Base belongs_to :answer validates :name, presence: true, uniqueness: true end
module Refinery module Accommodations class Accommodation < Refinery::Core::BaseModel self.table_name = 'refinery_accommodations' acts_as_indexed :fields => [:name, :rating, :description] after_save :remove_span extend FriendlyId friendly_id :name, :use => [:slugged] attr_accessible :name, :bread, :cover_image_id, :rating, :description, :position, :activity_ids, :location_id, :latitude, :longitude, :address, :gallery_id, :sub_name, :location_ids, :amenity_ids, :low_rate, :mid_rate, :high_rate, :jan, :feb, :marc, :apr, :may, :jun, :jul, :aug, :sept, :oct, :nov, :dec, :slug, :browser_title, :meta_description, :exclusion, :inclusion, :side_body validates :name, :presence => true, :uniqueness => true # validates :low_rate, :presence => true # validates :high_rate, :presence => true # validates :mid_rate, :presence => true RATES = %w(Low Mid High Closed) belongs_to :cover_image, :class_name => '::Refinery::Image' belongs_to :gallery, :class_name => '::Refinery::Portfolio::Gallery' # belongs_to :location, :class_name => '::Refinery::Locations::Location' has_and_belongs_to_many :activities, :class_name => '::Refinery::Activities::Activity', :join_table => 'refinery_activities_accommodations' has_and_belongs_to_many :posts, :class_name => 'Refinery::Blog::Post', :join_table => 'refinery_accommodations_posts' has_and_belongs_to_many :locations, :class_name => '::Refinery::Locations::Location', :join_table => 'refinery_accommodations_locations' has_and_belongs_to_many :amenities, :class_name => '::Refinery::Amenities::Amenity', :join_table => 'refinery_accommodations_amenities' default_scope { order(:position) } def remove_span new_slug = self.slug.gsub("-span-","-").gsub("-span","") self.update_column(:slug, new_slug) accommodation = self links = '' if accommodation.locations.first.present? and accommodation.locations.first.parent.present? if accommodation.locations.first.parent.parent.present? links << accommodation.locations.first.parent.parent.slug.gsub('-',' ') + " " links << accommodation.locations.first.parent.slug.gsub('-',' ') + " " else links << accommodation.locations.first.parent.slug.gsub('-',' ') + " " end end if accommodation.locations.first.present? links << accommodation.locations.first.slug.gsub('-',' ') + " " end links << accommodation.slug.gsub('-',' ') self.update_column(:bread, links.to_s) end def is_valid? gallery.present? and gallery.items.present? end end end end
Gem::Specification.new {|s| s.name = 'fuse' s.version = '0.0.1' s.author = 'meh.' s.email = 'meh@paranoici.org' s.homepage = 'http://github.com/meh/ruby-fuse' s.platform = Gem::Platform::RUBY s.summary = 'Bindings and wrapper for FUSE' s.files = `git ls-files`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ['lib'] s.add_dependency 'ffi' s.add_dependency 'ffi-extra' }
class PracticeJob < Struct.new(:practice_id, :transition) #Include the faye sender module to send... include CustomFayeSender def perform practica = Practica.find(practice_id) if transition.eql? :open practica.dispositivos.each do |dispositivo| dispositivo.set_ready RemoteIRCGateway.instance.send_reset_token dispositivo, 'false' end practica.abrir elsif transition.eql? :close practica.cerrar mensaje_raw = FayeMessagesController.new.generate_close_pratica_output practica send_via_faye "#{FAYE_CHANNEL_PREFIX}#{practica.faye_channel}", mensaje_raw begin practica.dispositivos.each do |dispositivo| dispositivo.reset end RemoteIRCGateway.instance.reset_practica practica RemoteIRCGateway.instance.initialize_vlan_switch_vlans rescue => e puts "Exception in Practice Job for IRCGateway> #{e.message}" end end end end
Rails.application.routes.draw do get 'home/index' root to: 'home#index' get '/tweets', to: 'twitter#tweets' get '/word-cloud', to: 'twitter#word_cloud' get '/sentiment', to: 'twitter#sentiment' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require "google/apis/gmail_v1" require "googleauth" require "json" require_relative "env_token_store" class GoogleMail OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze APPLICATION_NAME = "GovWifi Smoke Tests".freeze SCOPE = [ Google::Apis::GmailV1::AUTH_GMAIL_SEND, Google::Apis::GmailV1::AUTH_GMAIL_MODIFY, ].freeze def initialize @service = Google::Apis::GmailV1::GmailService.new @service.client_options.application_name = APPLICATION_NAME @service.authorization = authorize end def read(query = "") messages = @service.list_user_messages("me", q: query).messages return if messages.nil? message = @service.get_user_message("me", messages[0].id) @service.modify_message("me", message.id, Google::Apis::GmailV1::ModifyMessageRequest.new(remove_label_ids: %w[UNREAD])) message end def send_email(to, from, subject, body) message = Google::Apis::GmailV1::Message.new message.raw = [ "From: #{from}", "To: #{to}", "Subject: #{subject}", "", body, ].join("\n") @service.send_user_message("me", message) end def account_email @service.get_user_profile("me").email_address end private def authorize client_id = Google::Auth::ClientId.from_hash JSON.parse(ENV["GOOGLE_API_CREDENTIALS"]) token_store = EnvTokenStore.new ENV authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store user_id = "default" credentials = authorizer.get_credentials user_id return credentials unless credentials.nil? url = authorizer.get_authorization_url base_url: OOB_URI puts "Open the following URL in the browser and enter the " \ "resulting code after authorization:\n" + url code = gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI, ) credentials end end
class PagesController < ApplicationController def welcome @header= "WELCOME page @header" render :welcome end def about @header = "About page @header" end def contest @header = "Contest page @header" flash[:notice] = "Sorry, contest is finished!" redirect_to welcome_url end def kitten @header = 'Kitten page @header' set_kitten_url end def kittens @header = "Kittens page @header" set_kitten_url end def set_kitten_url requested_size = params[:size] @kitten_url = "http://lorempixel.com/#{requested_size}/#{requested_size}/cats" end def secrets @header = "Secrets page @header" if params[:magic_word] == "guest" render :secrets else flash[:alert] = "Sorry not the magic word...." redirect_to '/welcome' end end end
class Poll < ApplicationRecord #----------- # Includes #----------- #----------- # Callbacks #----------- # Relationships #----------- has_many :poll_opinions, class_name: 'PollOpinion' has_many :poll_dates, class_name: 'PollDate' belongs_to :owner, class_name: 'User' has_many :answers, dependent: :destroy accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true # Validations #----------- validates :question, presence: true, length: { minimum: 5, maximum: 120 } validates :expiration_date, presence: true # Scope #----------- default_scope -> { order('expiration_date ASC') } scope :opinion_polls, -> { where(type: 'PollOpinion') } scope :date_polls, -> { where(type: 'PollDate') } scope :passed_ordered, -> { unscoped.order('expiration_date DESC') } scope :expired, -> { where('expiration_date < ?', Time.zone.now) } scope :active, -> { where('expiration_date >= ?', Time.zone.now) } # ------------------------ # -- PUBLIC --- # ------------------------ def self.expecting_my_vote(current_user) total = PollOpinion.active.count total -= PollOpinion.with_my_opinion_votes(current_user).count total += PollDate.active.count total - PollDate.with_my_date_votes(current_user).count end def votes_count Vote.where(poll_id: id).group(:user).count.keys.size end def poll_creation_mail PollMailer.poll_creation_mail(self).deliver_now end def comments_count poll_thread = Commontator::Thread.where(commontable_id: id).take return 0 if poll_thread.nil? poll_thread.comments.count end end
class BarPolicy attr_reader :current_user, :bar def initialize(current_user, bar) @current_user = current_user @bar = bar end def destroy? return false if @current_user == @bar.user end end
class CreateTodoItems < ActiveRecord::Migration def self.up create_table :todo_items do |t| t.integer :todo_list_id t.integer :basecamp_id t.datetime :due_at t.string :content t.string :creator_name t.integer :responsible_party_id t.boolean :completed t.string :responsible_party_name t.datetime :commented_at t.integer :creator_id t.timestamps end end def self.down drop_table :todo_items end end
class Bowler < ActiveRecord::Base has_many :entries has_and_belongs_to_many :brackets validates :name, presence: true end
class AddSentToCompanies < ActiveRecord::Migration def change add_column :employees, :sent, :boolean, default: false end end
class DivesitesController < ApplicationController # GET /divesites # GET /divesites.xml def index @divesites = Divesite.order('area_id asc', 'pointname asc').paginate(:page => params[:page], :per_page => 20) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @divesites } end end # GET /divesites/1 # GET /divesites/1.xml def show @divesite = Divesite.find(params[:id]) @pictures = @divesite.pictures.joins(:details).order('id desc') @details = Detail.joins(:pictures).where('pictures.id' => @pictures.map{|p| p.id}).uniq @pictures = @pictures.paginate(:page => params[:page], :per_page => 10) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @divesite } end end # GET /divesites/new # GET /divesites/new.xml def new @divesite = Divesite.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @divesite } end end # GET /divesites/1/edit def edit @divesite = Divesite.find(params[:id]) end # POST /divesites # POST /divesites.xml def create @divesite = Divesite.new(params[:divesite]) respond_to do |format| if @divesite.save format.html { redirect_to(@divesite, :notice => 'Divesite was successfully created.') } format.xml { render :xml => @divesite, :status => :created, :location => @divesite } else format.html { render :action => "new" } format.xml { render :xml => @divesite.errors, :status => :unprocessable_entity } end end end # PUT /divesites/1 # PUT /divesites/1.xml def update @divesite = Divesite.find(params[:id]) respond_to do |format| if @divesite.update_attributes(params[:divesite]) format.html { redirect_to(@divesite, :notice => 'Divesite was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @divesite.errors, :status => :unprocessable_entity } end end end # DELETE /divesites/1 # DELETE /divesites/1.xml def destroy @divesite = Divesite.find(params[:id]) @divesite.destroy respond_to do |format| format.html { redirect_to(divesites_url) } format.xml { head :ok } end end def generate_area_list @areas = Area.find.all end end
require "test_helper" class HomeControllerTest < ActionController::TestCase include Devise::Test::ControllerHelpers test "should get homepage when not signed in" do get :index assert_select "#home-sl1", true, "home should be rendered if not signed in" end test "should get dashboard when signed in" do sign_in users(:viktor) get :index assert_select "#greeting", true, "dashboard should be rendered if signed in" end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :validatable # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable validates :name, presence:true validates :email, presence:true, uniqueness:true has_many :notes has_many :likes has_many :like_notes, through: :likes, source: :note has_many :posts has_many :post_notes, through: :posts, source: :note has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower has_many :subscribed, class_name: "Relationship", foreign_key: "followed_id" has_many :comments has_many :comment_articles, through: :comments, source: :article has_many :opinions has_many :opinion_microposts, through: :opinions, source: :micropost # ユーザーをフォローする def follow(other_user) active_relationships.create(followed_id: other_user.id) end # ユーザーをアンフォローする def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end # 現在のユーザーがフォローしてたらtrueを返す def following?(other_user) following.include?(other_user) end def set_image(file) if !file.nil? file_name = file.original_filename File.open("public/user_images/#{file_name}", 'wb'){|f|f.write(file.read)} self.image = file_name end end def admin? admin end end
module Kuhsaft module Api class PagesController < ActionController::Base layout :false respond_to :json def index I18n.locale = params[:locale] @pages = Kuhsaft::Page.unscoped.published.content_page.translated.order(position: :asc) render json: @pages.as_json end end end end
require 'factories/profiles.rb' describe CreditCardFormatValidator do let(:subject) { CreditCardFormatValidator } let( :attribute ) { :credit_card } let (:object) { Profile.new } invalid_credit_card_numbers = %w[9556494038121161 41128109359983 n396092084242542 535299462783972 1396092084242542] valid_credit_card_numbers = %w[4556494038121161 4112810935509983 4556828677360012 5396092084242542 5180466231664941 5352994627083972] context 'Wrong credit card format' do context 'No message is sent on the options' do it 'it returns error message expecified on the validator' do n = subject.new( { attributes: attribute } ) invalid_credit_card_numbers.each do |invalid_credit_card_number| expect(n.validate_each(object, attribute, invalid_credit_card_number)).to include('enter a valid credit card number (Visa or Mastercard)') end end end context 'Message is sent on the options' do it 'it returns error message expecified on the options' do n = subject.new( { message: 'Test error message', attributes: :postal_code } ) invalid_credit_card_numbers.each do |invalid_credit_card_number| expect(n.validate_each(object, attribute, invalid_credit_card_number)).to include('Test error message') end end end end context 'Correct credit card format' do context 'No message is sent on the options' do it 'it does not return error message' do n = subject.new( { attributes: attribute } ) valid_credit_card_numbers.each do |valid_credit_card_number| expect(n.validate_each(object, attribute, valid_credit_card_number)).to equal(nil) end end end context 'Message is sent on the options' do it 'it does not return error message' do n = subject.new( { message: 'Test error message', attributes: attribute } ) valid_credit_card_numbers.each do |valid_credit_card_number| expect(n.validate_each(object, attribute, valid_credit_card_number)).to equal(nil) end end end end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Server do fails_on_jruby declare_topology_double let(:cluster) do double('cluster').tap do |cl| allow(cl).to receive(:topology).and_return(topology) allow(cl).to receive(:app_metadata).and_return(app_metadata) allow(cl).to receive(:options).and_return({}) end end let(:listeners) do Mongo::Event::Listeners.new end let(:monitoring) do Mongo::Monitoring.new(monitoring: false) end let(:address) do default_address end let(:pool) do server.pool end let(:server_options) do {} end let(:server) do register_server( described_class.new(address, cluster, monitoring, listeners, SpecConfig.instance.test_options.merge(monitoring_io: false).merge(server_options)) ) end let(:monitor_app_metadata) do Mongo::Server::Monitor::AppMetadata.new( server_api: SpecConfig.instance.ruby_options[:server_api], ) end shared_context 'with monitoring io' do let(:server_options) do {monitoring_io: true} end before do allow(cluster).to receive(:monitor_app_metadata).and_return(monitor_app_metadata) allow(cluster).to receive(:push_monitor_app_metadata).and_return(monitor_app_metadata) allow(cluster).to receive(:heartbeat_interval).and_return(1000) end end describe '#==' do context 'when the other is not a server' do let(:other) do false end it 'returns false' do expect(server).to_not eq(other) end end context 'when the other is a server' do context 'when the addresses match' do let(:other) do register_server( described_class.new(address, cluster, monitoring, listeners, SpecConfig.instance.test_options.merge(monitoring_io: false)) ) end it 'returns true' do expect(server).to eq(other) end end context 'when the addresses dont match' do let(:other_address) do Mongo::Address.new('127.0.0.1:27018') end let(:other) do register_server( described_class.new(other_address, cluster, monitoring, listeners, SpecConfig.instance.test_options.merge(monitoring_io: false)) ) end it 'returns false' do expect(server).to_not eq(other) end end end end describe '#disconnect!' do context 'with monitoring io' do include_context 'with monitoring io' it 'stops the monitor instance' do expect(server.instance_variable_get(:@monitor)).to receive(:stop!).and_call_original server.disconnect! end end context 'when server has a pool' do before do allow(server).to receive(:unknown?).and_return(false) allow(cluster).to receive(:run_sdam_flow) server.pool.ready end it 'pauses and clears the connection pool' do expect(server.pool_internal).to receive(:close).once.and_call_original RSpec::Mocks.with_temporary_scope do # you can't disconnect from a known server, since this pauses the # pool and we only want to pause the pools of unknown servers. server.unknown! allow(server).to receive(:unknown?).and_return(true) server.close end end end context 'when server reconnects' do before do allow(server).to receive(:unknown?).and_return(false) allow(cluster).to receive(:run_sdam_flow) server.pool.ready end it 'keeps the same pool' do pool = server.pool RSpec::Mocks.with_temporary_scope do # you can't disconnect from a known server, since this pauses the # pool and we only want to pause the pools of unknown servers. # server.unknown! allow(server).to receive(:unknown?).and_return(true) server.disconnect! end server.reconnect! allow(server).to receive(:unknown?).and_return(false) expect(server.pool).to eq(pool) end end end describe '#initialize' do include_context 'with monitoring io' before do allow(cluster).to receive(:run_sdam_flow) end it 'sets the address host' do expect(server.address.host).to eq(default_address.host) end it 'sets the address port' do expect(server.address.port).to eq(default_address.port) end it 'sets the options' do expect(server.options[:monitoring_io]).to be true end context 'with monitoring app metadata option' do require_no_required_api_version it 'creates monitor with monitoring app metadata' do server.monitor.scan! expect(server.monitor.connection.options[:app_metadata]).to be monitor_app_metadata end end context 'monitoring_io: false' do let(:server_options) do {monitoring_io: false} end it 'does not create monitoring thread' do expect(server.monitor.instance_variable_get('@thread')).to be nil end end context 'monitoring_io: true' do include_context 'with monitoring io' it 'creates monitoring thread' do expect(server.monitor.instance_variable_get('@thread')).to be_a(Thread) end end end describe '#scan!' do clean_slate include_context 'with monitoring io' before do # We are invoking scan! on the monitor manually, stop the background # thread to avoid it interfering with our assertions. server.monitor.stop! end it 'delegates scan to the monitor' do expect(server.monitor).to receive(:scan!) server.scan! end it 'invokes sdam flow eventually' do expect(cluster).to receive(:run_sdam_flow) server.scan! end end describe '#reconnect!' do include_context 'with monitoring io' before do expect(server.monitor).to receive(:restart!).and_call_original end it 'restarts the monitor and returns true' do expect(server.reconnect!).to be(true) end end describe 'retry_writes?' do before do allow(server).to receive(:features).and_return(features) end context 'when the server version is less than 3.6' do let(:features) do double('features', sessions_enabled?: false) end context 'when the server has a logical_session_timeout value' do before do allow(server).to receive(:logical_session_timeout).and_return(true) end it 'returns false' do expect(server.retry_writes?).to be(false) end end context 'when the server does not have a logical_session_timeout value' do before do allow(server).to receive(:logical_session_timeout).and_return(nil) end it 'returns false' do expect(server.retry_writes?).to be(false) end end end context 'when the server version is at least 3.6' do let(:features) do double('features', sessions_enabled?: true) end context 'when the server has a logical_session_timeout value' do before do allow(server).to receive(:logical_session_timeout).and_return(true) end context 'when the server is a standalone' do before do allow(server).to receive(:standalone?).and_return(true) end it 'returns false' do expect(server.retry_writes?).to be(false) end end context 'when the server is not a standalone' do before do allow(server).to receive(:standalone?).and_return(true) end it 'returns false' do expect(server.retry_writes?).to be(false) end end end context 'when the server does not have a logical_session_timeout value' do before do allow(server).to receive(:logical_session_timeout).and_return(nil) end it 'returns false' do expect(server.retry_writes?).to be(false) end end end end describe '#summary' do context 'server is primary' do let(:server) do make_server(:primary) end before do expect(server).to be_primary end it 'includes its status' do expect(server.summary).to match(/PRIMARY/) end it 'includes replica set name' do expect(server.summary).to match(/replica_set=mongodb_set/) end end context 'server is secondary' do let(:server) do make_server(:secondary) end before do expect(server).to be_secondary end it 'includes its status' do expect(server.summary).to match(/SECONDARY/) end it 'includes replica set name' do expect(server.summary).to match(/replica_set=mongodb_set/) end end context 'server is arbiter' do let(:server) do make_server(:arbiter) end before do expect(server).to be_arbiter end it 'includes its status' do expect(server.summary).to match(/ARBITER/) end it 'includes replica set name' do expect(server.summary).to match(/replica_set=mongodb_set/) end end context 'server is ghost' do let(:server) do make_server(:ghost) end before do expect(server).to be_ghost end it 'includes its status' do expect(server.summary).to match(/GHOST/) end it 'does not include replica set name' do expect(server.summary).not_to include('replica_set') end end context 'server is other' do let(:server) do make_server(:other) end before do expect(server).to be_other end it 'includes its status' do expect(server.summary).to match(/OTHER/) end it 'includes replica set name' do expect(server.summary).to match(/replica_set=mongodb_set/) end end context 'server is unknown' do let(:server_options) do {monitoring_io: false} end before do expect(server).to be_unknown end it 'includes unknown status' do expect(server.summary).to match(/UNKNOWN/) end it 'does not include replica set name' do expect(server.summary).not_to include('replica_set') end end context 'server is a mongos' do let(:server) do make_server(:mongos) end before do expect(server).to be_mongos end it 'specifies the server is a mongos' do expect(server.summary).to match(/MONGOS/) end end end describe '#log_warn' do it 'works' do expect do server.log_warn('test warning') end.not_to raise_error end end end
json.array!(@enroll_statuses) do |enroll_status| json.extract! enroll_status, :id, :es_sDescription json.url enroll_status_url(enroll_status, format: :json) end
require_relative '../spec/spec_helper' require_relative '../lib/recommendations' require 'date' require 'benchmark' include Benchmark describe "Recommendations with mongo datamodel" do before(:each) do @db = Mongo::Connection.new.db("recommender") #@preference_collection = @db['items'] #@preference_collection.insert(:user_id=>'A', :item_id=>'B', :preference=>5) #@preference_collection.insert(:user_id=>'A', :item_id=>'C', :preference=>3) #@preference_collection.insert(:user_id=>'B', :item_id=>'B', :preference=>5) #@preference_collection.insert(:user_id=>'B', :item_id=>'C', :preference=>3) #@preference_collection.insert(:user_id=>'B', :item_id=>'D', :preference=>2) end after(:each) do #@preference_collection.remove end it "should integrate all elements and recommend accordingly" do data_model = Recommendations::DataModel::MongoDataModel.new db: 'recommender', collection: 'items' #data_model.activate_cache similarity = Recommendations::Similarity::EuclideanDistanceSimilarity.new(data_model) neighborhood = Recommendations::Similarity::Neighborhood::NearestNUserNeighborhood.new(data_model, similarity, 5, 0.5, 100) rating_estimator = Recommendations::Recommender::Estimation::DefaultRatingEstimator.new(data_model, similarity) recommender = Recommendations::Recommender::GenericUserBasedRecommender.new(data_model, similarity, neighborhood, rating_estimator) recommender.activate_cache recommendations = nil bm(1) do |x| x.report("before_cache") {recommendations = recommender.recommend('9810', 5)} x.report("after_cached") {recommendations = recommender.recommend('9810', 5)} end recommendations.should include Recommendations::Model::RecommendedItem.new('95', 5.0) end end
# -*- encoding: utf-8 -*- # # Author:: Edmund Haselwanter (<office@iteh.at>) # Copyright:: Copyright (c) 2011 Edmund Haselwanter # License:: Apache License, Version 2.0 # # 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 File.join(File.dirname(__FILE__), "/spec_helper") require 'ap' describe ZabbixPusher::Pusher do context 'Initialization' do FakeWeb.register_uri(:post, "http://localhost:4568/jolokia", :response => fixture_file("cms_perm_response.txt")) it 'should accept a template file' do @m = ZabbixPusher::Pusher.new(File.join(File.dirname(__FILE__), 'fixtures/tomcat_template.xml'),:jmx => {:base_uri => "http://localhost:4568"}) @m.send.should == {"jmx[java.lang:name=CMS Perm Gen,type=MemoryPool;Usage;max]"=>67108864, "jmx[java.lang:name=CMS Perm Gen,type=MemoryPool;Usage;used]"=>18890360, "jmx[java.lang:name=CMS Perm Gen,type=MemoryPool;Usage;committed]"=>31518720} end end context 'process items' do before(:each) do end it "should get the title" do end end end
# frozen_string_literal: true module Queries class AllActionsQuery < ::Queries::BaseQuery description 'アクション一覧取得' type [::Types::Enums::ActionEnum], null: false def query = ::AllowedAction.all_actions end end
module Api module V1 class CheckNonDeliveredController < ApplicationController before_action :restrict_access def index EntriesCheck.deliver_entries() render json: {message: "undelivered entries processed"}, status: :ok end private def restrict_access header_api_key = request.headers['api-key'] @api_key = AppApiKey.where(api_key: header_api_key).first if header_api_key unless @api_key render json: { error: 'Unauthorized' }, status: :unauthorized end end end end end
class AddLocationIdToRefineryAccommodations < ActiveRecord::Migration def change add_column :refinery_accommodations, :location_id, :integer end end
Rails.application.routes.draw do use_doorkeeper namespace :api do namespace :v1 do resources :posts, only: %i(index create show update destroy) end end devise_for :users root to: 'home#index' resources :posts end
class AddSitesToProperties < ActiveRecord::Migration[6.1] def change add_column :properties, :sites, :string end end
class CreateMarketSuppliers < ActiveRecord::Migration[5.0] def change create_table :market_suppliers do |t| t.references :market, foreign_key: true, index: true, null: false t.references :user, foreign_key: true, index: true, null: false t.integer :role t.timestamps end end end
# Instead of using spec_helper, I'm using the twice as fast custom helper # for active record objects. require 'spec_active_record_helper' require 'hydramata/works/predicate_presentation_sequences/storage' module Hydramata module Works module PredicatePresentationSequences describe Storage do subject { described_class.new } it 'belongs to a work type' do expect(subject.predicate).to be_nil end it 'has many predicates' do expect(subject.predicate_set).to be_nil end it 'has a meaningful #to_s method' do # Alright not entirely meaningful expect(subject.to_s).to match(/>.*-/) end end end end end
class Group < ActiveRecord::Base has_and_belongs_to_many :users has_many :group_privileges, :dependent => :destroy validates :name, :presence => true def has_privilege?(privilege) !privileges.index(privilege).nil? end def all_users User.find_by_sql <<-SQL select users.* from users, groups_users where users.id = groups_users.user_id and groups_users.group_id = #{self.id} SQL end def privileges self.group_privileges.map { |gp| gp.privilege } end end
# frozen_string_literal: true # == Schema Information # # Table name: user_achievements # # id :bigint not null, primary key # created_at :datetime not null # updated_at :datetime not null # achievement_id :bigint not null # photopost_id :integer # user_id :bigint not null # # Indexes # # index_user_achievements_on_achievement_id (achievement_id) # index_user_achievements_on_photopost_id (photopost_id) # index_user_achievements_on_user_id (user_id) # index_user_achievements_on_user_id_and_achievement_id (user_id,achievement_id) # class UserAchievement < ApplicationRecord belongs_to :user belongs_to :achievement belongs_to :photopost end
class SearchForm < ApplicationRecord attribute :posted_at_from, :datetime attribute :posted_at_to, :datetime end
class AddDescriptionFieldToProcedures < ActiveRecord::Migration def up add_column :procedures, :description, :text, default: "" end def down remove_column :procedures, :description end end
module Hydramata module Works module ValueParser module_function def call(options = {}, &block) value = options.fetch(:value) if value.respond_to?(:raw_object) block.call(value: value, raw_object: value.raw_object) else parser = parser_for(options) parser.call(value, &block) end end def parser_for(options = {}) parser_finder = options.fetch(:parser_finder) { default_parser_finder } parser_finder.call(options) end def default_parser_finder ->(options) do require 'hydramata/works/value_parsers' ValueParsers.find(options) end end private_class_method :default_parser_finder end end end
class AddTotalStatsFlag < ActiveRecord::Migration[5.2] def up add_column(:batting_stats, :eligible_games, :integer, default: 0, null: false) add_column(:batting_stats, :is_total, :boolean, default: true, null: false) BattingStat.reset_column_information BattingStat.fix_total_flags execute "UPDATE batting_stats SET eligible_games = 162 WHERE season < 2018" add_column(:pitching_stats, :eligible_games, :integer, default: 0, null: false) add_column(:pitching_stats, :is_total, :boolean, default: true, null: false) PitchingStat.reset_column_information PitchingStat.fix_total_flags execute "UPDATE pitching_stats SET eligible_games = 162 WHERE season < 2018" end def down remove_column(:batting_stats, :eligible_games) remove_column(:pitching_stats, :eligible_games) remove_column(:batting_stats, :is_total) remove_column(:pitching_stats, :is_total) end end
Rails.application.routes.draw do resources :projects, only: [:show, :index] resources :posts, only: [:index] mount RailsAdmin::Engine => '/admin', as: 'rails_admin' devise_for :users, :skip => [:registrations] get 'welcome/index' root 'welcome#index' end
require "dotman/messages" module Dotman module Init def show_init_message puts Dotman::Messages::MSG_FIRST_RUN end end end
require File.expand_path(File.dirname(__FILE__) + "/../test_helper") class MessageTest < ActiveSupport::TestCase should "test all_of_hostgroup" should "test count_of_hostgroup" do Host.make(:host => "somehost").save Message.make(:host => "foobar", :message => "bla").save Message.make(:host => "foobarish", :message => "gdfgdfhh").save Message.make(:host => "foofoo", :message => "foobarish").save Message.make(:host => "somehost", :message => "gdfgfdd").save Message.make(:host => "somehost", :message => "wat").save Message.make(:host => "anotherhost", :message => "foobar").save Message.make(:host => "anotherfoohost", :message => "don't match me").save hostgroup = Hostgroup.find(3) assert_equal 5, Message.count_of_hostgroup(hostgroup) end should "find additional fields" do Message.make(:host => "local", :message => "hi!", :_foo => "bar").save message = Message.last assert message.has_additional_fields expected = [{:value => 'bar', :key => 'foo' }] assert_equal expected, message.additional_fields end end
class RemoveLocationFromPost < ActiveRecord::Migration[5.0] def change remove_column :posts, :address remove_column :posts, :city remove_column :posts, :state remove_column :posts, :country remove_column :posts, :longitude remove_column :posts, :latitude end end
# frozen_string_literal: true module MachineLearningWorkbench::NeuralNetwork # Feed Forward Neural Network class FeedForward < Base # Calculate the size of each row in a layer's weight matrix. # Includes inputs (or previous-layer activations) and bias. # @return [Array<Integer>] per-layer row sizes def layer_row_sizes @layer_row_sizes ||= struct.each_cons(2).collect {|prev, _curr| prev+1} end # Activates a layer of the network # @param i [Integer] the layer to activate, zero-indexed def activate_layer i act_fn.call(state[i].dot layers[i]) end end end
module Types class ProjectAttributes < Types::BaseInputObject description 'Attributes for creating or updating projects' argument :title, String, required: true argument :description, String, required: false argument :is_completed, Boolean, required: false end end
class ChangeDatatypeAffiliateAmazonLinkOfMaikingTools < ActiveRecord::Migration[5.2] def change change_column :making_tools, :affiliate_amazon_link, :text end end
# encoding: utf-8 class Topic < ActiveRecord::Base attr_reader :type ## # Relationships belongs_to :user belongs_to :speaker, class_name: 'User' belongs_to :event has_many :comments, as: :commentable, dependent: :destroy, inverse_of: :commentable ## # Validations validates :content, presence: true, length: { in: 50..1000 } validates :title, presence: true, length: { in: 2..100 } acts_as_votable #def avg_votes #cached_votes_up-cached_votes_down # upvotes.size-downvotes.size #end rails_admin do configure :comments, :has_many_association configure :user, :belongs_to_association configure :speaker, :belongs_to_association configure :comments_count, :integer list do field :title field :user field :speaker field :comments_count end edit do field :title field :content field :user field :speaker end end end
class Beer < ActiveRecord::Base include AverageRating extend TopRated attr_accessible :brewery_id, :name, :style_id validates_length_of :name, minimum: 1 validates_presence_of :style belongs_to :brewery belongs_to :style has_many :ratings, :dependent => :destroy has_many :raters, through: :ratings, source: :user def to_s "#{name} (#{brewery.name})" end end
json.array!(@transactions) do |transaction| json.extract! transaction, :id, :customer_id, :payment_mode, :actual_total_price, :tax, :vat, :date json.url transaction_url(transaction, format: :json) end
module MeRedis # todo warn in development when gzipped size iz bigger than strict # use prepend for classes module ZipValues module FutureUnzip def set_transformation(&block) return if @transformation_set @transformation_set = true @old_transformation = @transformation @transformation = -> (vl) { if @old_transformation @old_transformation.call(block.call(vl, self)) else block.call(vl, self) end } self end # patch futures we need only when we are returning values, usual setters returns OK COMMANDS = %i[incr incrby hincrby get hget getset mget hgetall].map{ |cmd| [cmd, true]}.to_h end module ZlibCompressor def self.compress(value); Zlib.deflate(value.to_s ) end def self.decompress(value) value ? Zlib.inflate(value) : value rescue Zlib::DataError, Zlib::BufError return value end end module EmptyCompressor def self.compress(value); value end def self.decompress(value); value end end def self.prepended(base) base::Future.prepend(FutureUnzip) base.extend(MeRedis::ClassMethods) base.me_config.default_compressor = ::MeRedis::ZipValues::ZlibCompressor end def pipelined(&block) super do |redis| block.call(redis) _patch_futures(@client) end end def multi(&block) super do |redis| block.call(redis) _patch_futures(@client) end end def _patch_futures(client) client.futures.each do |ftr| ftr.set_transformation do |vl| if vl && FutureUnzip::COMMANDS[ftr._command[0]] # we only dealing here with GET methods, so it could be hash getters or get/mget keys = ftr._command[0][0] == 'h' ? ftr._command[1, 1] : ftr._command[1..-1] if ftr._command[0] == :mget vl.each_with_index.map{ |v, i| zip?(keys[i]) ? self.class.get_compressor_for_key(keys[i]).decompress( v ) : v } elsif zip?(keys[0]) compressor = self.class.get_compressor_for_key(keys[0]) # on hash commands it could be an array vl.is_a?(Array) ? vl.map!{ |v| compressor.decompress(v) } : compressor.decompress(vl) else vl end else vl end end end end def zip_value(value, key ) zip?(key) ? self.class.get_compressor_for_key(key).compress( value ) : value end def unzip_value(value, key) return value if value.is_a?( FutureUnzip ) value.is_a?(String) && zip?(key) ? self.class.get_compressor_for_key(key).decompress( value ) : value end def zip?(key); self.class.zip?(key) end # Redis prepended methods def get( key ); unzip_value( super( key ), key) end def set( key, value ); super( key, zip_value(value, key) ) end def mget(*args); unzip_arr_or_future(super(*args), args ) end def mset(*args); super( *map_msets_arr(args) ) end def getset( key, value ); unzip_value( super( key, zip_value(value, key) ), key ) end def hget( key, h_key ); unzip_value( super( key, h_key ), key ) end def hset( key, h_key, value ); super( key, h_key, zip_value(value, key) ) end def hsetnx( key, h_key, value ); super( key, h_key, zip_value(value, key) ) end def hmset( key, *args ); super( key, map_hmsets_arr(key, *args) ) end def hmget( key, *args ); unzip_arr_or_future( super(key, *args), key ) end private def unzip_arr_or_future( arr, keys ) return arr if arr.is_a?(FutureUnzip) arr.tap { arr.each_with_index { |val, i| arr[i] = unzip_value(val,keys.is_a?(Array) ? keys[i] : keys)} } end def map_hmsets_arr( key, *args ) return args unless zip?(key) counter = 0 args.map!{ |kv| (counter +=1).odd? ? kv : zip_value(kv, key ) } end def map_msets_arr( args ) args.tap { (args.length/2).times{ |i| args[2*i+1] = zip_value(args[2*i+1], args[2*i] ) } } end end end
require 'factory_girl_rails' FactoryGirl.define do factory :user do sequence(:email) { |n| "user-#{n}@example.com" } password 'testtest' password_confirmation 'testtest' admin true end end
class OmniauthController < ApplicationController skip_before_action :authenticate_user! def callback user = User.from_omniauth(oauth_hash) .assign_credentials(oauth_hash('credentials')) sign_in(user, scope: :users) uri_query = '?success=true' # we'll ask user to complete fields that is not present but required incomplete_fields = ['first_name', 'last_name'].map do |field| user[field].present? ? nil : field end.compact if incomplete_fields.present? uri_query << "&incomplete=#{incomplete_fields.join('&incomplete=')}" end redirect_to login_users_url.concat(uri_query) end private def oauth_hash(field = nil) field ? request.env['omniauth.auth'][field] : request.env['omniauth.auth'] end end
# Displays 3x3 board def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end # Converts user input 1-9 to index 0-8 def input_to_index(user_input) input_as_int = user_input.to_i index = input_as_int - 1 end # Determines if the user input is valid for a move def valid_move?(board, index) if index >= 0 && index <= 8 if board[index] == " " || board[index] == "" || board[index] == nil return true else return false end else return false end end # Counts the number of turns def turn_count(board) turn_count = 0 board.each do |square| if square == "X" || square == "O" turn_count += 1 end end return turn_count end # Determines whether it's X or O player based on turn count def current_player(board) turn_count = turn_count(board).even? ? "X" : "O" end # Places an X or O on the board def move(board, index, value) board[index] = value end # Turn loop def turn(board) puts "Please enter 1-9:" user_input = gets.strip index = input_to_index(user_input) if valid_move?(board, index) == true value = current_player(board) move(board, index, value) display_board(board) else puts "invalid." turn(board) end end # Playing the Game def play(board) while !(over?(board)) turn(board) end if won?(board) winner = winner(board) puts "Congratulations #{winner}!" else puts "Cats Game!" end end # WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] # Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Winning Move? def won?(board) WIN_COMBINATIONS.each do |combination| #pull values from board corresponding to winning combination position_1 = board[combination[0]] position_2 = board[combination[1]] position_3 = board[combination[2]] #check for a winner if position_1 == "X" && position_2 == "X" && position_3 == "X" return combination end if position_1 == "O" && position_2 == "O" && position_3 == "O" return combination end end return false end def full?(board) full = !(board.any? { |position| position == " " || nil }) return full end def draw?(board) if !(won?(board)) return full?(board) end end def over?(board) over = full?(board) || won?(board) || draw?(board) return over end def winner(board) win_combo = won?(board) if win_combo == false return nil else return board[win_combo[0]] end end
# #1 class Matrix attr_reader :rows, :columns def initialize(matrix) @rows = matrix.each_line.map { |row| row.split.map(&:to_i) } @columns = rows.transpose end end # #2 # class Matrix # def initialize(matrix) # @matrix = matrix # end # def rows # @rows ||= @matrix.each_line.map { |row| row.split.map(&:to_i) } # end # def columns # @columns ||= rows.transpose # end # end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook] validates_presence_of :username validates_uniqueness_of :username has_many :friendships, dependent: :destroy has_many :inverse_friendships, class_name: "Friendship", foreign_key: "friend_id", dependent: :destroy has_attached_file :avatar, :storage => :s3, styles: { medium: "370x370>", thumb: "100x100>" }, default_url: "/images/:style/missing.png", :url =>':s3_domain_url', :path => '/:class/:attachment/:id_partition/:style/:filename' validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/ default_scope { order('id DESC') } def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.provider = auth.provider user.uid = auth.uid user.email = auth.info.email user.password = Devise.friendly_token[0,20] user.username = auth.info.name # assuming the user model has a name user.gender = auth.extra.raw_info.gender user.avatar = process_uri(auth.info.image + "?width=9999") # assuming the user model has an image user.bio = auth.extra.raw_info.bio user.location = auth.info.location user.date_of_birth = auth.extra.raw_info.birthday end end # Friendship Methods ####### def request_match(user2) self.friendships.create(friend: user2) end def accept_match(user2) self.friendships.where(friend: user2).first.update_attribute(:state, "ACTIVE") end def remove_match(user2) inverse_friendship = inverse_friendships.where(user_id: user2).first if inverse_friendship self.inverse_friendships.where(user_id: user2).first.destroy else self.friendships.where(friend_id: user2).first.destroy end end ######## # Find all matches def matches(current_user) friendships.where(state: "pending").map(&:friend) + current_user.friendships.where(state: "ACTIVE").map(&:friend) + current_user.inverse_friendships.where(state: "ACTIVE").map(&:user) end # Filter Methods ####### def self.gender(user) case user.interest when "Male" where('gender = ?', "male") when "Female" where('gender = ?', "female") else all end end def self.not_me(user) where.not(id: user.id) end ####### private def self.process_uri(uri) require 'open-uri' require 'open_uri_redirections' final_uri = open(uri, :allow_redirections => :safe) do |r| r.base_uri.to_s end final_uri end # def self.from_omniauth(auth, signed_in_resource=nil) # user = User.where(provider: auth['provider'], uid: auth['uid']).first # if user # return user # else # user = User.create( # email: auth['info']['email'], # provider: auth['provider'], # uid: auth['uid'], # username: auth['info']['name'], # gender: auth['extra']['raw_info']['gender'], # avatar: process_uri(auth['info']['image'] + "?width=9999"), # date_of_birth: auth['extra']['raw_info']['birthday'].present? ? Date.strptime( auth['extra']['raw_info']['birthday'], '%m/%d/%Y') : nil, # location: auth['info']['location'], # bio: auth['extra']['raw_info']['bio'] # ) # end # end # def self.new_with_session(params, session) # if session["devise.user_attributes"] # new(session["devise.user_attributes"], without_protection: true) do |user| # user.attributes = params # user.valid? # end # else # super # end # end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) u1 = User.create(first_name: "Raúl", last_name: "Doe", email: "raul@example.org", password: "hola.123", password_confirmation: "hola.123", role: "teacher") u2 = User.create(first_name: "Estéban", last_name: "Roe", email: "esteban@example.org", password: "hola.123", password_confirmation: "hola.123", role: "student") r1 = Resource.create(name: "Ruby slides", description: "Características y principales elementos del lenguaje Ruby", user: u1) r2 = Resource.create(name: "HTTP slides", description: "HTTP y su implicancia en las rutas de Rails", user: u1) t1 = Tag.create(name: "rails") t2 = Tag.create(name: "ruby") t3 = Tag.create(name: "http") t4 = Tag.create(name: "clases") ResourcesTag.create(user: u1, tag: t2, resource: r1) ResourcesTag.create(user: u1, tag: t4, resource: r1) ResourcesTag.create(user: u1, tag: t3, resource: r2) ResourcesTag.create(user: u1, tag: t4, resource: r2)
class GemeinschaftSetupsController < ApplicationController # We use the heater rake task to generate this file. # So it loads super fast even on slow machines. # caches_page :new, :gzip => :best_compression skip_before_filter :start_setup_if_new_installation load_and_authorize_resource :gemeinschaft_setup def new @user = @gemeinschaft_setup.build_user( :user_name => t('gemeinschaft_setups.initial_setup.admin_name'), :male => true, :email => 'admin@localhost', ) @sip_domain = @gemeinschaft_setup.build_sip_domain( :host => guess_local_host(), :realm => guess_local_host(), ) @gemeinschaft_setup.country = Country.find_by_name('Germany') @gemeinschaft_setup.language = Language.find_by_name('Deutsch') @gemeinschaft_setup.default_company_name = generate_a_new_name(Tenant.new) @gemeinschaft_setup.default_system_email = 'admin@localhost' @gemeinschaft_setup.trunk_access_code = '0' end def create if @gemeinschaft_setup.save super_tenant = Tenant.create( :name => GsParameter.get('SUPER_TENANT_NAME'), :country_id => @gemeinschaft_setup.country.id, :language_id => @gemeinschaft_setup.language_id, :description => t('gemeinschaft_setups.initial_setup.super_tenant_description'), ) # GsNode GsNode.create(:name => 'Homebase', :ip_address => @gemeinschaft_setup.sip_domain.host, :push_updates_to => false, :accepts_updates_from => false, :site => 'Homebase', :element_name => 'Homebase') # Admin user = @gemeinschaft_setup.user super_tenant.tenant_memberships.create(:user_id => user.id) user.update_attributes(:current_tenant_id => super_tenant.id) # Create the Super-Tenant's group: super_tenant_super_admin_group = super_tenant.user_groups.create(:name => t('gemeinschaft_setups.initial_setup.super_admin_group_name')) super_tenant_super_admin_group.user_group_memberships.create(:user_id => user.id) # Set CallRoute defaults CallRoute.factory_defaults_prerouting(@gemeinschaft_setup.country.country_code, @gemeinschaft_setup.country.trunk_prefix, @gemeinschaft_setup.country.international_call_prefix, @gemeinschaft_setup.trunk_access_code, @gemeinschaft_setup.default_area_code ) # Set a couple of URLs in the GsParameter table GsParameter.where(:name => 'phone_book_entry_image_url').first.update_attributes(:value => "http://#{@gemeinschaft_setup.sip_domain.host}/uploads/phone_book_entry/image") GsParameter.where(:name => 'ringtone_url').first.update_attributes(:value => "http://#{@gemeinschaft_setup.sip_domain.host}") GsParameter.where(:name => 'user_image_url').first.update_attributes(:value => "http://#{@gemeinschaft_setup.sip_domain.host}/uploads/user/image") # Set ringback_tone if @gemeinschaft_setup.country.country_code.to_s == '49' GsParameter.where(:entity => 'dialplan', :section => 'variables', :name => 'ringback').first.update_attributes(:value => '%(1000,4000,425.0)') end # Restart FreeSWITCH if Rails.env.production? require 'freeswitch_event' FreeswitchAPI.execute('fsctl', 'shutdown restart') end # Create the tenant tenant = Tenant.create({:name => @gemeinschaft_setup.default_company_name, :sip_domain_id => SipDomain.last.id, :country_id => @gemeinschaft_setup.country.id, :language_id => @gemeinschaft_setup.language_id, :from_field_voicemail_email => @gemeinschaft_setup.default_system_email, :from_field_pin_change_email => @gemeinschaft_setup.default_system_email, }) # Become a member of this tenant. # tenant.tenant_memberships.create(:user_id => user.id) # Groups # admin_group = tenant.user_groups.create(:name => t('gemeinschaft_setups.initial_setup.admin_group_name')) admin_group.users << user user_group = tenant.user_groups.create(:name => t('gemeinschaft_setups.initial_setup.user_group_name')) user_group.users << user user.update_attributes!(:current_tenant_id => tenant.id) # Auto-Login: session[:user_id] = user.id # Perimeter settings if !@gemeinschaft_setup.detect_attacks detect_attacks = GsParameter.where(:entity => 'events', :section => 'modules', :name => 'perimeter_defense').first if detect_attacks detect_attacks.update_attributes(:value => '0', :class_type => 'Integer') end end if !@gemeinschaft_setup.report_attacks GsParameter.create(:entity => 'perimeter', :section => 'general', :name => 'report_url', :value => '', :class_type => 'String', :description => '') report_url = GsParameter.where(:entity => 'perimeter', :section => 'general', :name => 'report_url').first if report_url report_url.update_attributes(:value => '', :class_type => 'String') end end # Redirect to the user redirect_to page_help_path, :notice => t('gemeinschaft_setups.initial_setup.successful_setup') else render :new end end end
class Actor attr_reader :name @@all = [] ###### Instance methods ###### def initialize(name) @name = name @@all << self end #Return the characters the actor has played def characters() Character.all().select() { | char | char.actor == self } end #Assign a character to the actor def play_character(character) character.actor = self end ###### Class methods ###### #Return an array of all actors def self.all() @@all end #Return the actor who has played the most characters def self.most_characters() self.all().max_by() { | actor | actor.characters().length() } end end
require_relative 'synchronized_mapper_wrapper' class SynchronizedExpandingMapperWrapper < SynchronizedMapperWrapper def push_value(value) if value.respond_to?(:each) value.each do |item| producing_queue << item end else super end end end
#============================================================================== # ** Game_Battler #------------------------------------------------------------------------------ # A battler class with methods for sprites and actions added. This class # is used as a super class of the Game_Actor class and Game_Enemy class. #============================================================================== class Game_Battler < Game_BattlerBase #------------------------------------------------------------- # *) overwrite method: refresh #------------------------------------------------------------- def refresh state_resist_set.each {|state_id| erase_state(state_id) } @hp = [[@hp, mhp].min, 0].max @mp = [[@mp, mmp].min, 0].max if @hp == 0 if self.state?(89) # auto revive state id remove_state(89) remove_state(death_state_id) @hp += mhp.to_i/5 @dmg_popup = true @popup_ary.push((["AutoRevive","AutoRevive"])) Audio.se_play("Audio/SE/Recovery", 100,100) else add_state(death_state_id) end # if self.state?(89) end # if @hp == 0 end # refresh end # Game_Battler
class Chat < ActiveRecord::Base has_many :messages, dependent: :destroy has_many :chat_users, dependent: :destroy has_many :users, through: :chat_users validates :name, presence: true, length: { maximum: 50 } end
class Discount attr_reader :code attr_reader :product def initialize(code, product, min_quantity) @code = code @product = product @min_quantity = min_quantity end def valid_discount(quantity) if quantity >= @min_quantity return true end return false end end class TwoForOne < Discount def initialize(code, product, min_quantity) super end public def apply_discount(quantity, price) return (quantity / 2.0).ceil * price end end class Bulk < Discount def initialize(code, product, min_quantity, new_price) @new_price = new_price super(code, product, min_quantity) end public def apply_discount(quantity, price) return quantity * @new_price end end
require 'rails_helper' RSpec.describe GroupsController, type: :controller do let!(:group){ create(:group) } let!(:user) { create(:user) } let!(:admin) { create(:admin) } context 'when not logged in user' do context 'get show group' do before{ get :show, params: { id: group.id } } it 'redirects to login page' do should redirect_to login_path end end context 'get index groups' do before{ get :index } it 'redirects to login page' do should redirect_to login_path end end end context 'when logged in user' do before{ @request.session[:user_id] = user.id } context 'is trying to view group' do before{ get :show, params: { id: group.id } } it 'renders template groups/show' do should render_template 'groups/show' end end context 'is trying to remove group' do before{ get :destroy, params: { id: group.id } } it 'redirects to user' do should redirect_to user end end end context 'when admin' do before{ @request.session[:user_id] = admin.id } context 'is trying to view group' do before{ get :show, params: { id: group.id } } it 'renders template groups/show' do should render_template 'groups/show' end it 'assigns group' do expect(assigns(:group)).to eq(group) end end context 'is trying to view groups' do before{ get :index } it 'renders template groups/index' do should render_template 'groups/index' end end context 'is trying to view new group' do before{ get :new } it 'assigns group variable' do expect(assigns(:group)).to be_a_new(Group) end end context 'is trying to create new valid group' do let!(:valid_group_attributes){ attributes_for(:group) } it 'increase number of groups' do expect do post :create, params: { group: valid_group_attributes} end.to change{ Group.count }.by(1) end end context 'is trying to remove group' do let!(:group_to_destroy){ create(:group) } it 'changes groups count by -1' do expect do delete :destroy, params: { id: group_to_destroy.id } end.to change{ Group.count }.by(-1) end end end end
# frozen_string_literal: true require 'json' RSpec.describe 'ReekEnsurance' do it 'does not have reek warnings' do command = 'bin/reek app/* lib/* --config ./.quality/.reek' result = `#{command} --format json` warnings = JSON.parse(result).size message = "Reek #{warnings} warnings, run '#{command}' to show them" expect(warnings).to eq(0), message end end
module Alchemy # Returns alchemys mount point in current rails app. # Pass false to not return a leading slash on empty mount point. def self.mount_point(remove_leading_slash_if_blank = true) alchemy_routes = Rails.application.routes.named_routes[:alchemy] raise "Alchemy not mounted! Please mount Alchemy::Engine in your config/routes.rb file." if alchemy_routes.nil? mount_point = alchemy_routes.path.spec.to_s if remove_leading_slash_if_blank && mount_point == "/" mount_point.gsub(/^\/$/, '') else mount_point end end end
class Product < ApplicationRecord belongs_to :list, primary_key: 'product_id', foreign_key: 'product_id', optional: true require 'open-uri' require 'rakuten_web_service' def self.rakuten_search(user, condition) account = Account.find_by(user: user) search_id = condition[:search_id] if account != nil then if account.rakuten_app_id != nil then app_id = account.rakuten_app_id else app_id = ENV['RAKUTEN_APP_ID'] end end dcounter = 0 RakutenWebService.configure do |c| c.application_id = ENV['RAKUTEN_APP_ID'] end search_condition = Hash.new search_condition = { keyword: condition[:keyword], field: 0 } if condition[:store_id] != nil then search_condition[:shopCode] = condition[:store_id] end if condition[:category_id] != nil then search_condition[:genreId] = condition[:category_id] end min_price = condition[:min_price].to_i max_price = condition[:max_price].to_i if min_price > 0 && max_price == 0 then search_condition[:minPrice] = min_price elsif min_price > 0 && max_price > min_price then search_condition[:minPrice] = min_price search_condition[:maxPrice] = max_price elsif min_price == 0 && max_price > 0 then search_condition[:maxPrice] = max_price end logger.debug(search_condition) results = RakutenWebService::Ichiba::Item.search(search_condition) item_num = results.count num = 0 logger.debug("===============================") logger.debug(item_num) logger.debug(results.has_next_page?) nchecker = true if item_num > 0 then #検索結果からアイテム取り出し res = Hash.new counter = 0 begin nchecker = results.has_next_page? logger.debug(results.has_next_page?) if nchecker == true then logger.debug("-===============================-") next_result = results.next_page end logger.debug("---") checker = Hash.new product_list = Array.new listing = Array.new results.each do |result| url = result['itemUrl'] product_id = result['itemCode'].gsub(':','_') image1 = result['mediumImageUrls'][0] if image1 != nil then image1 = image1.gsub('?_ex=128x128', '') end image2 = result['mediumImageUrls'][1] if image2 != nil then image2 = image2.gsub('?_ex=128x128', '') end image3 = result['mediumImageUrls'][2] if image3 != nil then image3 = image3.gsub('?_ex=128x128', '') end name = result['itemName'] price = result['itemPrice'] category_id = result['genreId'] description = result['itemCaption'] mpn = nil condition = "New" if name.include?('中古') || description.include?('中古') then condition = "Used" end tag_ids = result['tagIds'] tag_info = Array.new brand = nil =begin tag_ids.each do |tag| logger.debug("====== Tag =========") logger.debug(tag) qurl = "https://app.rakuten.co.jp/services/api/IchibaTag/Search/20140222?format=json&tagId=" + tag.to_s + "&applicationId=" + app_id logger.debug(qurl) html = open(qurl) do |f| f.read # htmlを読み込んで変数htmlに渡す end logger.debug(html) group_name = /"tagGroupName":"([\s\S]*?)"/.match(html) if group_name != nil then group_name = group_name[1] if group_name == "メーカー" then brand = /"tagName":"([\s\S]*?)"/.match(html)[1] break end end end logger.debug("========== Access To Rakuten ============") charset = nil code = nil user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100' begin html = open(url, "User-Agent" => user_agent) do |f| charset = f.charset f.read # htmlを読み込んで変数htmlに渡す end code = /<span class="item_number">([\s\S]*?)<\/span>/.match(html) if code != nil then code = code[1] end rescue OpenURI::HTTPError => error logger.debug("--------- HTTP Error ------------") logger.debug(error) end =end jan = nil code = nil if code != nil then if code.length == 13 then jan = code end end if jan != nil then logger.debug("============ Product ===============") search_condition = { keyword: jan, } response = RakutenWebService::Ichiba::Product.search(search_condition) response.each do |info| if info['brandName'] != nil then brand = info['brandName'] end if info['productNo'] != nil then mpn = info['productNo'] end logger.debug(brand) logger.debug(mpn) break end end res = Hash.new res = { shop_id: "1", product_id: product_id, title: name, price: price, image1: image1, image2: image2, image3: image3, jan: jan, part_number: mpn, description: description, category_id: category_id, brand: brand } if checker.key?(product_id) == false && product_id != nil then num += 1 dcounter += 1 product_list << Product.new(res) listing << List.new(user: user, product_id: product_id, shop_id: "1", status: "searching", condition: condition, search_id: search_id) checker[product_id] = name account.update( progress: "取得中 " + num.to_s + "件取得済み" ) if dcounter == 10 then if res != nil then cols = res.keys cols.delete_at(0) cols.delete_at(0) Product.import product_list, on_duplicate_key_update: {constraint_name: :for_upsert_products, columns: cols} List.import listing, on_duplicate_key_update: {constraint_name: :for_upsert_lists, columns: [:status, :condition, :search_id]} account.update( progress: "取得中 " + num.to_s + "件取得済み" ) account = Account.find_by(user: user) if account.status == 'stop' then logger.debug('====== STOP by USER ========= ') account.update( progress: "取得完了(ユーザ中断) 全" + num.to_s + "件取得" ) return end end dcounter = 0 end end end sleep(0.5) if res != nil then cols = res.keys cols.delete_at(0) cols.delete_at(0) Product.import product_list, on_duplicate_key_update: {constraint_name: :for_upsert_products, columns: cols} List.import listing, on_duplicate_key_update: {constraint_name: :for_upsert_lists, columns: [:status, :condition, :search_id]} account.update( progress: "取得中 " + num.to_s + "件取得済み" ) account = Account.find_by(user: user) if account.status == 'stop' then logger.debug('====== STOP by USER ========= ') account.update( progress: "取得完了(ユーザ中断) 全" + num.to_s + "件取得" ) return end end counter += 1 if counter > 29 then break end logger.debug("===========================") logger.debug(nchecker) results = next_result end while nchecker == true end account.update( progress: "取得完了 全" + num.to_s + "件取得" ) end def self.yahoo_search(user, condition) account = Account.find_by(user: user) search_id = condition[:search_id] if account != nil then if account.yahoo_app_id != nil then app_id = account.yahoo_app_id else app_id = ENV['YAHOO_APPID'] end end dcounter = 0 query = condition[:keyword] dcategory_id = condition[:category_id] store_id = condition[:store_id] dnum = 0 (0..19).each do |num| logger.debug(num) offset = 50 * num endpoint = 'https://shopping.yahooapis.jp/ShoppingWebService/V1/itemSearch?appid=' + app_id.to_s + '&condition=new&availability=1&hits=50&offset=' + offset.to_s endpoint2 = 'https://shopping.yahooapis.jp/ShoppingWebService/V1/itemLookup?appid=' + app_id.to_s + "&responsegroup=large" min_price = condition[:min_price].to_i max_price = condition[:max_price].to_i if min_price > 0 && max_price == 0 then endpoint = endpoint + '&price_from=' + min_price.to_s elsif min_price > 0 && max_price > min_price then endpoint = endpoint + '&price_from=' + min_price.to_s endpoint = endpoint + '&price_to=' + max_price.to_s elsif min_price == 0 && max_price > 0 then endpoint = endpoint + '&price_to=' + max_price.to_s end url = endpoint if query != nil then esc_query = URI.escape(query) url = url + '&query=' + esc_query.to_s end if dcategory_id != nil then url = url + '&category_id=' + dcategory_id.to_s end if store_id != nil then url = url + '&store_id=' + store_id.to_s end user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" charset = nil option = { "User-Agent" => user_agent } logger.debug(url) html = open(url, option) do |f| charset = f.charset f.read # htmlを読み込んで変数htmlに渡す end doc = Nokogiri::HTML.parse(html, nil, charset) hits = doc.xpath('//hit') if hits.length == 0 then break end product_list = Array.new category_list = Array.new listing = Array.new chash = Hash.new data = nil hits.each do |hit| title = hit.xpath('./name').text description = hit.xpath('./description').text product_id = hit.xpath('./code').text durl = endpoint2 + "&itemcode=" + product_id charset = nil html2 = open(durl, option) do |f| charset = f.charset f.read # htmlを読み込んで変数htmlに渡す end logger.debug(durl) logger.debug("========== detail =============") doc2 = Nokogiri::HTML.parse(html2, nil, charset) temp = doc2.xpath('//hit') image1 = nil image2 = nil image3 = nil image1 = temp.xpath('./image/medium').text images = temp.xpath('./relatedimages/image') images.each_with_index do |image, i| if i == 0 then image2 = image.xpath('./medium').text elsif i == 1 then image3 = image.xpath('./medium').text end end if image1 != nil then image1 = image1.gsub('/g/', '/n/') end if image2 != nil then image2 = image2.gsub('/g/', '/n/') end if image3 != nil then image3 = image3.gsub('/g/', '/n/') end price = hit.xpath('./price').text category_id = hit.xpath('./category/current/id').text category_name = hit.xpath('./category/current/name').text brand = hit.xpath('./brands/name').text part_number = hit.xpath('./model').text jan = hit.xpath('./jancode').text data = Hash.new data = { product_id: product_id, shop_id: "2", title: title, description: description, image1: image1, image2: image2, image3: image3, brand: brand, jan: jan, part_number: part_number, category_id: category_id, price: price } if title != nil then product_list << Product.new(data) dnum += 1 account.update( progress: "取得中 " + dnum.to_s + "件取得済み" ) if product_id != nil then listing << List.new(user: user, product_id: product_id, shop_id: "2", status: "searching", condition: "New", search_id: search_id) if chash.has_key?(category_id) == false then category_list << Category.new(category_id: category_id, name: category_name, shop_id: "2") chash[category_id] = category_name end end dcounter += 1 if dcounter == 10 then dcounter = 0 if data != nil then cols = data.keys cols.delete_at(0) cols.delete_at(0) account.update( progress: "取得中 " + dnum.to_s + "件取得済み" ) Product.import product_list, on_duplicate_key_update: {constraint_name: :for_upsert_products, columns: cols} List.import listing, on_duplicate_key_update: {constraint_name: :for_upsert_lists, columns: [:status, :condition, :search_id]} Category.import category_list, on_duplicate_key_update: {constraint_name: :for_upsert_categories, columns: [:name]} account = Account.find_by(user: user) if account.status == 'stop' then logger.debug('====== STOP by USER ========= ') account.update( progress: "取得完了(ユーザ中断) 全" + dnum.to_s + "件取得" ) return end end end end end if data != nil then cols = data.keys cols.delete_at(0) cols.delete_at(0) account.update( progress: "取得中 " + dnum.to_s + "件取得済み" ) Product.import product_list, on_duplicate_key_update: {constraint_name: :for_upsert_products, columns: cols} List.import listing, on_duplicate_key_update: {constraint_name: :for_upsert_lists, columns: [:status, :condition, :search_id]} Category.import category_list, on_duplicate_key_update: {constraint_name: :for_upsert_categories, columns: [:name]} account = Account.find_by(user: user) if account.status == 'stop' then logger.debug('====== STOP by USER ========= ') account.update( progress: "取得完了(ユーザ中断) 全" + dnum.to_s + "件取得" ) return end end logger.debug("============ CHECK ================") logger.debug(url) tcheck = /totalResultsReturned="([\s\S]*?)"/.match(html) if tcheck != nil then logger.debug("============ END ================") tcheck = tcheck[1].to_i logger.debug(tcheck) if tcheck < 50 then break end end end account.update( progress: "取得完了 全" + dnum.to_s + "件取得" ) end end
module Humidifier # Dumps an object to CFN syntax module Utils # a frozen hash of the given names mapped to their underscored version def self.underscored(names) names.map { |name| [name, underscore(name).to_sym] }.to_h.freeze end end end
module Router class OSMAdapter def initialize(endpoint = 'http://127.0.0.1:5000/route/v1/driving/') @connection = Faraday.new(url: endpoint) end def call(origin, destination) response = @connection.get("#{to_param(origin)};#{to_param(destination)}") JSON.parse(response.body)['routes'].map do |r| Route.new( # Using map_points from args for now. # Don't know how to interpret legs from osm response. map_points: [origin, destination], distance: r['distance'], duration: r['duration'] ) end end private def to_param(map_point) "#{map_point.long},#{map_point.lat}" end end end
# frozen_string_literal: true RSpec.describe Dry::Types::PrimitiveInferrer, "#[]" do subject(:inferrer) do Dry::Types::PrimitiveInferrer.new end before { stub_const("Types", Dry.Types()) } def type(*args) args.map { |name| Dry::Types[name.to_s] }.reduce(:|) end it "caches results" do expect(inferrer[type(:string)]).to be(inferrer[type(:string)]) end it "returns String for a string type" do expect(inferrer[type(:string)]).to eql([String]) end it "returns Integer for a integer type" do expect(inferrer[type(:integer)]).to eql([Integer]) end it "returns Array for a string type" do expect(inferrer[type(:array)]).to eql([Array]) end it "returns Array for a primitive array" do expect(inferrer[Types.Constructor(Array)]).to eql([Array]) end it "returns Hash for a string type" do expect(inferrer[type(:hash)]).to eql([Hash]) end it "returns DateTime for a datetime type" do expect(inferrer[type(:date_time)]).to eql([DateTime]) end it "returns NilClass for a nil type" do expect(inferrer[type(:nil)]).to eql([NilClass]) end it "returns TrueClass for a true type" do expect(inferrer[type(:true)]).to eql([TrueClass]) end it "returns FalseClass for a false type" do expect(inferrer[type(:false)]).to eql([FalseClass]) end it "returns [TrueClass, FalseClass] for bool type" do expect(inferrer[type(:bool)]).to eql([TrueClass, FalseClass]) end it "returns Integer for a lax constructor integer type" do expect(inferrer[type("params.integer").lax]).to eql([Integer]) end it "returns [NilClass, Integer] from an optional integer with constructor" do expect(inferrer[type(:integer).optional.constructor(&:to_i)]).to eql([NilClass, Integer]) end it "returns Integer for integer enum type" do expect(inferrer[type(:integer).enum(1, 2)]).to eql([Integer]) end it "returns custom type for arbitrary types" do custom_type = Dry::Types::Nominal.new(double(:some_type, name: "ObjectID")) expect(inferrer[custom_type]).to eql([custom_type.primitive]) end it "returns Object for any" do expect(inferrer[type(:any)]).to eql([Object]) end it "returns Hash for a schema" do expect(inferrer[type(:hash).schema(foo: type(:integer))]).to eql([Hash]) end end
class Comment < ApplicationRecord belongs_to :user belongs_to :event has_many :reports include Filterable validates :text, presence: true validates :user_id, presence: true validates :event_id, presence: true scope :filter_by_user_id, -> (user_id) { where user_id: user_id } scope :filter_by_event_id, -> (event_id) { where event_id: event_id } def self.filter_by_params(params) results = self.filter(params.slice(:user_id, :event_id)) if params[:reports] results = results.joins('LEFT JOIN reports ON reports.comment_id = comments.id').where('reports.comment_id IS NULL') end results end end
require 'test_helper' class FotoLojasControllerTest < ActionController::TestCase setup do @foto_loja = foto_lojas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:foto_lojas) end test "should get new" do get :new assert_response :success end test "should create foto_loja" do assert_difference('FotoLoja.count') do post :create, foto_loja: { Id_Local: @foto_loja.Id_Local, binariofoto: @foto_loja.binariofoto, data: @foto_loja.data, nome: @foto_loja.nome } end assert_redirected_to foto_loja_path(assigns(:foto_loja)) end test "should show foto_loja" do get :show, id: @foto_loja assert_response :success end test "should get edit" do get :edit, id: @foto_loja assert_response :success end test "should update foto_loja" do patch :update, id: @foto_loja, foto_loja: { Id_Local: @foto_loja.Id_Local, binariofoto: @foto_loja.binariofoto, data: @foto_loja.data, nome: @foto_loja.nome } assert_redirected_to foto_loja_path(assigns(:foto_loja)) end test "should destroy foto_loja" do assert_difference('FotoLoja.count', -1) do delete :destroy, id: @foto_loja end assert_redirected_to foto_lojas_path end end
require 'logger' require 'spec_helper' require 'sneakers' describe Sneakers::Runner do let(:logger) { Logger.new('logtest.log') } describe "with configuration that specifies a logger object" do before do Sneakers.configure(log: logger) @runner = Sneakers::Runner.new([]) end it 'passes the logger to serverengine' do # Stub out ServerEngine::Daemon.run so we only exercise the way we invoke # ServerEngine.create any_instance_of(ServerEngine::Daemon) do |daemon| stub(daemon).main{ return 0 } end @runner.run # look at @runner's @se instance variable (actually of type Daemon)...and # figure out what it's logger is... end end end
module Admin class CategoryAnswersController < ApplicationController before_action :set_category_replay, only: [:show, :edit, :update, :destroy] # GET /category_answers # GET /category_answers.json def index @category_answers = CategoryReplay.all end # GET /category_answers/1 # GET /category_answers/1.json def show end # GET /category_answers/new def new @category_replay = CategoryReplay.new end # GET /category_answers/1/edit def edit end # POST /category_answers # POST /category_answers.json def create @category_replay = CategoryReplay.new(category_replay_params) respond_to do |format| if @category_replay.save format.html { redirect_to admin_category_replay_path(@category_replay), notice: 'Category replay was successfully created.' } format.json { render :show, status: :created, location: @category_replay } else format.html { render :new } format.json { render json: @category_replay.errors, status: :unprocessable_entity } end end end # PATCH/PUT /category_answers/1 # PATCH/PUT /category_answers/1.json def update respond_to do |format| if @category_replay.update(category_replay_params) format.html { redirect_to admin_category_replay(@category_replay), notice: 'Category replay was successfully updated.' } format.json { render :show, status: :ok, location: @category_replay } else format.html { render :edit } format.json { render json: @category_replay.errors, status: :unprocessable_entity } end end end # DELETE /category_answers/1 # DELETE /category_answers/1.json def destroy @category_replay.destroy respond_to do |format| format.html { redirect_to admin_category_answers_path, notice: 'Category replay was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_category_replay @category_replay = CategoryReplay.find(params[:id]) end # Only allow a list of trusted parameters through. def category_replay_params params.require(:category_replay).permit(:replay_id, :category_id) end end end
require "spec_helper" feature "deleting venues" do let!(:user) { Factory(:confirmed_user, role: 'admin') } let!(:venue) { Factory(:venue) } scenario "deleting a venue as admin" do sign_in_as!(user) visit "/venues" click_link "Wally's" click_button "delete venue information" page.should have_content("Venue information destroyed") page.should_not have_content("Wally's") end end
class FinderTopicService def self.count criteria.where(topic: nil).count end def self.all criteria.all end def self.find(topic_id) criteria.find(topic_id) end def self.find_by_topic(topic, limit=nil, page=nil) finder = criteria.where(topic: topic) finder = finder.limit(limit) unless limit.nil? finder = finder.offset(limit.to_i * page.to_i) unless page.nil? && limit.nil? finder end protected def self.criteria Topic.where(status: :active).order(created_at: :desc) end end
class CreateQuestions < ActiveRecord::Migration def change create_table :questions do |t| t.string :qtag t.string :qtype t.string :qclass t.timestamps end end end
require 'test/unit' require 'yaml' class Load_tests < Test::Unit::TestCase # def setup # end # def teardown # end def test_dump_string_to_string s = YAML.dump('one') assert(s == "--- one\n") end def test_dump_array s = YAML.dump( ['badger', 'elephant', 'tiger']) expected = "--- \n- badger\n- elephant\n- tiger\n" assert(s == expected) end def test_dump_mapping s = YAML.dump( {'one' => 1} ) expected = "--- \none: 1\n" assert(s == expected) end def test_dump_symbol s = YAML.dump( :foo ) expected = "--- :foo\n" assert(s == expected) end def test_number_to_yaml s = 1.to_yaml expected = "--- 1\n" assert(s == expected) end def test_dump_stream s = YAML.dump_stream(0, [1,2,], {'foo'=>'bar'}) expected = "--- 0\n--- \n- 1\n- 2\n--- \nfoo: bar\n" assert(s == expected) end end
require File.dirname(__FILE__) + '/../../spec_helper' describe Mysears::ProductFactory do BRAND_NAME = "Brand Name" PRODUCT_NAME = "Product Name" describe "product title" do it "should be 'brand_name product_name' when both non-blank" do @product_factory = create_product_factory() @product = @product_factory.persist_values! @product.title.should == "#{BRAND_NAME} #{PRODUCT_NAME}" end it "should be brand_name when product_name is blank" do @product_factory = create_product_factory(:product_name => '') @product = @product_factory.persist_values! @product.title.should == BRAND_NAME end it "should be product_name when brand_name is blank" do @product_factory = create_product_factory(:brand_name => ' ') @product = @product_factory.persist_values! @product.title.should == PRODUCT_NAME end it "should should be an error if both product_name and brand_name are nil" do lambda { @product_factory = create_product_factory(:product_name => nil, :brand_name => nil) @product = @product_factory.persist_values! }.should raise_error(RuntimeError) end it "should should be an error if both product_name and brand_name are blank" do lambda { @product_factory = create_product_factory(:product_name => ' ', :brand_name => nil) @product = @product_factory.persist_values! }.should raise_error(RuntimeError) end end def create_product_factory(opts=nil) opts ||= {} default_opts = { :brand_name => BRAND_NAME, :product_name => PRODUCT_NAME, :categorization => ['Miscellaneous'], :partner_key => "partnerkey", :image_url => 'http://www.viewpoints.com/images/header/header_logo_viewpoints.gif' } Mysears::ProductFactory.new default_opts.merge(opts, Source["sears"]) end end
class Admin::AdminsController < ApplicationController before_filter :authorize def show @admin = Admin.first end def new @admin = Admin.new end def create @admin = Admin.new(admin_params) if @admin.save redirect_to admin_path else render 'new' end end private def admin_params params.require(:admin).permit(:name, :avatar, :password, :password_confirmation) end end
class EasyAttendance < ActiveRecord::Base include Redmine::SafeAttributes RANGE_FORENOON = 1 RANGE_AFTERNOON = 2 RANGE_FULL_DAY = 3 belongs_to :easy_attendance_activity belongs_to :user belongs_to :edited_by, :class_name => 'User', :foreign_key => 'edited_by_id' belongs_to :time_entry, :class_name => 'TimeEntry', :foreign_key => 'time_entry_id', :dependent => :destroy validates :user_id, :easy_attendance_activity_id, :arrival, :presence => true validate :easy_attendance_validations attr_accessor :new_arrival, :current_user_ip, :range_start_time acts_as_event :title => Proc.new {|o| "#{o.easy_attendance_activity.name} : #{format_time(o.arrival, false)}" + ( o.departure ? " - #{format_time(o.departure, false)}" : '')}, :url => Proc.new {|o| {:controller => 'users', :action => 'show', :id => o.id}}, :author => Proc.new{|o| o.user}, :datetime => :arrival, :description => Proc.new{|o| } acts_as_activity_provider({:author_key => :user_id, :timestamp => :arrival}) scope :visible, lambda {|*user| } scope :non_working, lambda { where(["#{EasyAttendanceActivity.table_name}.at_work = ?", false]).includes(:easy_attendance_activity) } scope :between, lambda {|date_from, date_to| where(["#{EasyAttendance.table_name}.arrival BETWEEN ? AND ? AND #{EasyAttendance.table_name}.departure BETWEEN ? AND ?", date_from.beginning_of_day, date_to.end_of_day, date_from.beginning_of_day, date_to.end_of_day])} do def sum_spent_time(user_working_time_calendar = nil, return_value_in_hours = false) default_working_hours = user_working_time_calendar.default_working_hours if user_working_time_calendar default_working_hours ||= 8.0 inject(0.0) do |memo, att| hours = att.spent_time || 0.0 memo += round_hours_for_day(hours, default_working_hours, default_working_hours / 2, return_value_in_hours) end end def get_spent_time(default_working_hours, half_working_hours, return_value_in_hours = false) h = {} each do |att| h[att.arrival.to_date] = round_hours_for_day(att.spent_time || 0.0, default_working_hours, half_working_hours, return_value_in_hours) end h end end before_validation :assign_default_activity before_save :set_user_ip before_save :faktorize_attendances after_save :ensure_time_entry, :if => Proc.new {|o| o.easy_attendance_activity_id_changed?} safe_attributes 'arrival', 'departure', 'user_id', 'easy_attendance_activity_id', 'range', 'description' def self.enabled? EasyExtensions::EasyProjectSettings.easy_attendance_enabled == true end def self.round_hours_for_day(hours, default_working_hours = 8.0, half_working_hours = 4.0, return_value_in_hours = false) if hours <= 0.0 return 0.0 else if hours <= half_working_hours if return_value_in_hours return half_working_hours else return 0.5 end else if return_value_in_hours return default_working_hours else return 1.0 end end end end def self.new_or_last_attendance(user=nil) user ||= User.current i = user.get_easy_attendance_last_arrival || self.new i.user ||= user if i.new_record? i.new_arrival = true i.arrival = user.user_time_in_zone else i.new_arrival = false i.departure = user.user_time_in_zone end return i end def self.office_ip_range if self.enabled? plugin_settings = Setting.plugin_easy_attendances ip_str = plugin_settings.try(:value_at, 'office_ip_range') if ip_str.present? return IPAddr.new(ip_str) end end end def project self.time_entry && self.time_entry.project end def arrival=(value) time = nil if value.is_a?(Time) time = value.round_min_to_quarters elsif value.is_a?(String) time = begin; value.to_time.round_min_to_quarters; rescue; end; end # time = time.utc unless time.utc? write_attribute(:arrival, time) end def departure=(value) time = nil if value.is_a?(Time) time = value.round_min_to_quarters elsif value.is_a?(String) time = begin; value.to_time.round_min_to_quarters; rescue; end; end # time = time.utc unless time.utc? write_attribute(:departure, time) end # Je to příchod? Pokud není poslední záznam v db s prázdným odchodem tak to je příchod def arrival? return self.new_arrival end # Odchází uživatel? Aby mohl odejít tak musel přijít tudíž musí existovat last_attendance a je to tedy opak arrival def departure? return !self.arrival? end def morning(time) args = [time.year, time.month, time.day, user.current_working_time_calendar.time_from.hour] if self.user.time_zone Time.use_zone(user.time_zone) do Time.zone.local(*args) end else Time.local(*args) end end def evening(time) return morning(time) + (self.user.working_hours(time.to_date).to_i).hours end def start_date(user=nil) user ||= self.user if user.time_zone return user.time_to_date(self.arrival) elsif ActiveRecord::Base.default_timezone == :local return self.arrival.localtime.to_date else self.arrival.to_date end end def due_date(user=nil) user ||= self.user if self.departure if user.time_zone return user.time_to_date(self.departure) elsif ActiveRecord::Base.default_timezone == :local return self.departure.localtime.to_date else self.departure.to_date end end end def css_classes s = 'easy-attandance' s << " #{self.easy_attendance_activity.color_schema}" return s end def spent_time if self.departure && self.arrival (self.departure - self.arrival) / 1.hour end end def working_time if self.arrival && self.user && self.user.current_working_time_calendar self.user.current_working_time_calendar.working_hours(self.arrival.to_date) end end def after_create_send_mail return if self.easy_attendance_activity.mail.blank? return if self.arrival.nil? || self.departure.nil? EasyMailer.easy_attendance_added(self).deliver end def after_update_send_mail return if self.easy_attendance_activity.mail.blank? return if self.arrival.nil? || self.departure.nil? EasyMailer.easy_attendance_updated(self).deliver end def can_edit?(user=nil) user ||= User.current return (self.user == user && user.allowed_to?(:edit_own_easy_attendances, nil, :global => true)) || user.allowed_to?(:edit_easy_attendances, nil, :global => true) end private def assign_default_activity self.easy_attendance_activity ||= EasyAttendanceActivity.default end def easy_attendance_validations if self.departure && self.arrival self.errors.add(:departure, l(:departure_is_same_as_arrival, :scope => [:easy_attendance])) if self.arrival == self.departure self.errors.add(:arrival, l(:arrival_date_error, :scope => [:easy_attendance])) if self.arrival > self.departure arel = EasyAttendance.arel_table if ea = self.user.easy_attendances.where(arel[:departure].not_eq(nil)).where(arel[:arrival].gt(self.arrival).and(arel[:departure].lt(self.departure)).or(arel[:arrival].lt(self.departure).and(arel[:departure].gt(self.arrival)))).first self.errors.add(:base, l(:arrival_already_taken, :scope => [:easy_attendance])) if ea != self end end end def faktorize_attendances if self.departure && self.arrival && ( (self.departure - self.arrival) > 1.day ) original_departure = self.departure # find first working day if arrival is freeday while !self.user.current_working_time_calendar.working_day?(self.arrival.to_date) self.arrival += 1.day end # set current entity departure to arrival day self.departure = Time.utc(self.arrival.year, self.arrival.month, self.arrival.day, self.departure.hour, self.departure.min) attributes = {:easy_attendance_activity => self.easy_attendance_activity, :user => self.user, :arrival_user_ip => self.arrival_user_ip, :departure_user_ip => self.departure_user_ip, :range => self.range} Redmine::Hook.call_hook(:easy_attendance_faktorie_attendances_before_create, {:easy_attendance => self, :attributes => attributes}) # create next entities (self.arrival + 1.day).to_date.upto(original_departure.to_date) do |day| next unless self.user.current_working_time_calendar.working_day?(day) attributes[:arrival] = Time.utc(day.year, day.month, day.day, self.arrival.hour, self.arrival.min) attributes[:departure] = Time.utc(day.year, day.month, day.day, self.departure.hour, self.departure.min) EasyAttendance.create(attributes) end end end def ensure_time_entry return if self.new_record? if self.easy_attendance_activity.project_mapping? && self.easy_attendance_activity.mapped_project && self.easy_attendance_activity.mapped_time_entry_activity && self.arrival && self.departure te = self.time_entry || self.build_time_entry te.project = self.easy_attendance_activity.mapped_project te.activity = self.easy_attendance_activity.mapped_time_entry_activity te.user = self.user te.easy_range_from = self.arrival te.easy_range_to = self.departure te.hours = (self.departure - self.arrival) / 1.hour te.spent_on = self.arrival.to_date te.comments = self.description te.save! self.update_column(:time_entry_id, te.id) end end def set_user_ip self.arrival_user_ip = self.current_user_ip if !self.current_user_ip.blank? && !self.arrival.nil? && self.arrival_user_ip.blank? self.departure_user_ip = self.current_user_ip if !self.current_user_ip.blank? && !self.departure.nil? && self.departure_user_ip.blank? end end module EasyAttendances class Calendar < Redmine::Helpers::Calendar def events=(events) @events = events @ending_events_by_days = @events.group_by {|event| event.due_date(User.current)} @starting_events_by_days = @events.group_by {|event| event.start_date(User.current)} days = Hash.new{|hash, key| hash[key] = Array.new} @startdt.upto(@enddt) do |day| days[day.cweek] << day end @sorted_events = Hash.new days.each do |week, days| week_events = Hash.new # collect all events in weeek days.each do |day| @sorted_events[day] = EasyAttendances::EasyAttendanceCalendarDay.new(day, ((@ending_events_by_days[day] || []) + (@starting_events_by_days[day] || [])).uniq) #week_events[day] = week_events[day].group_by(&:user).sort_by{|k,v| [v.count, k.name]} end #groupped_week_events = week_events.values.flatten.group_by(&:user_id) # sort every day in week by count of user events in week # days.each do |day| # week_events[day].each do |e| # @sorted_events[day][e.first] = e.last.sort_by(&:arrival) # end # end end end def events_on(day) Array(@sorted_events[day]) end end class EasyAttendanceCalendarDay def initialize(day, events) @day = day @sorted_events = ActiveSupport::OrderedHash.new grouped_events = events.group_by(&:user) ordered_group_events = grouped_events.sort_by{|k,v| [v.count, k.name]} ordered_group_events.each do |a| @sorted_events[a.first] = a.last.sort_by(&:arrival) end end def events @sorted_events end end end
class BookmarkletController < ApplicationController before_filter :find_or_create_link, :only => [ :start, :add ] def index head :ok end def start head :ok end def add head :ok end private def find_or_create_link @link = Link.find_or_create_by_href(params[:url]) end end
require_relative 'wordchain' module Formulator def Formulator.create_sentence(length, subject) iterator = 0 result = [] result << subject.chomp previous_token = subject token = WordChain.bigram_word(previous_token) for _ in 0..length*5 break if token.blank? result << token.chomp earlier_token = previous_token previous_token = token token = WordChain.next_word([earlier_token, previous_token]) if token.blank? || ([false]*5+[true]).sample break if [true, false, false].sample token = WordChain.bigram_word(previous_token) end end result[0] = result[0].titleize "#{result.join(' ')}." end def Formulator.create_sentence_random(subject) return Formulator.create_sentence(3 + rand(8), subject) end end
require_relative 'mandelbrot' require_relative 'mandelbrot_map' require 'bigdecimal' require 'colorize' class Grid attr_accessor :center_x, :center_y, :precision_index, :precision, :step, :width, :height, :map, :mapfile DEFAULT_MAPFILE = 'mapfile' def initialize(x = 0, y = 0, precision_index = 2, width = 16, height = 9, options = {}) if options[:step].nil? if precision_index % 1 != 0 raise "Invalid arguments. Precision Index (#{precision_index}) must be an integer." end @precision_index = precision_index @precision = (precision_index / 3).floor @step = 10 ** (@precision * -1) remainder = precision_index % 3 precise_step = BigDecimal(@step.to_f.to_s) if remainder != 0 if remainder == 1 precise_step *= 0.5 @precision + 0.3 elsif remainder == 2 precise_step *= 0.2 end @precision += remainder * 0.25 end @step = precise_step.to_f else @step = options[:step] end raise "Invalid Render Parameters: Step cannot be great than 1: step = #{@step}" if @step > 1.0 @center_x = nearest_step(x, @step) @center_y = nearest_step(y, @step) @width = width @height = height @mapfile = options[:mapfile] || DEFAULT_MAPFILE @map = {} end def precise_step compare = if @step.class == Rational @step.to_f.to_s elsif @step.class == Float @step.to_s end BigDecimal(compare) end def include?(x, y) in_bounds = x >= x_min && x <= x_max && y >= y_min && y <= y_max on_step = x / step % 1 == 0 && y / step % 1 == 0 in_bounds && on_step end def center [center_x, center_y] end def x_min center = BigDecimal(@center_x.to_s) if width.even? center - (width / 2) * precise_step else center - (width / 2).floor * precise_step end.to_f end def x_max center = BigDecimal(@center_x.to_s) if width.even? center + (width / 2 - 1) * precise_step else center + (width / 2).floor * precise_step end.to_f end def y_min center = BigDecimal(@center_y.to_s) if height.even? center - height / 2 * precise_step else (center - (height / 2).floor * precise_step) end.to_f end def y_max center = BigDecimal(@center_y.to_s) if height.even? center + (height / 2 - 1) * precise_step else center + (height / 2).floor * precise_step end.to_f end def x_range x_max - x_min end def y_range y_max - y_min end def top_left [x_min, y_max] end def bottom_right [x_max, y_min] end def points hash = {} precise_x = BigDecimal(x_min.to_s) precise_y = BigDecimal(y_max.to_s) x = precise_x half_step = @step / 2 while x < x_max + half_step y = precise_y # avoid rounding errors removing/adding an extra row while y > y_min - half_step point = [x.to_f, y.to_f] hash[point] = @map.get point y -= @step end x += @step end hash end def point(x, y) @map[[x,y]] end def number_of_points width * height end def nearest_step(number, step) precise_step = BigDecimal(step.to_f.to_s) ((number / step).round * precise_step).to_f end def to_a @map.map do |point, data| [point[0], point[1], data[0], data[1]] end end def write(mapfile = @mapfile, options = {}) print timestamp + " Updating mapfile: " + "#{@mapfile}".green t0 = Time.now if options[:overwrite] File.write(mapfile, @map.to_a) end t1 = Time.now - t0 puts " (" + "#{t1}".cyan + " seconds)" end def compute_mandelbrot(iterations = 20) if points.size != number_of_points puts "WARNING: Number of points does not match grid size. Expected: #{number_of_points}, got: #{points.size}" # raise 'Grid Error' end puts "Center".cyan + ": " + "(" + "#{center_x}".red + ", " + "#{center_y}".red + "), " + ": " + "#{step}".red + ", " + "Resolution".cyan + ": " + "#{width}x#{height}".red puts "Top Left Corner".cyan + ": (" + "#{x_min}".red + ", " + "#{y_max}".red + ")" + ", " + "Bottom Right Corner".cyan + ": " + "(" + "#{x_max}".red + ", " + "#{y_min}".red + ")" raise 'Missing map data' if @map.nil? puts timestamp + " Analyzing " + "#{number_of_points}".cyan + " points at " + "#{iterations}".red + " iterations..." t0 = Time.now points_left = number_of_points reused = 0 new_points = 0 recompute = 0 checkpoints = (0..99).map do |percent| number_of_points * percent / 100 end puts "0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%" print '[' points.each do |point, data| if data.nil? number = Complex(*point) check = Mandelbrot.new(number, iterations) iterates_under_two = check.bounded_iterates @map.set(point, iterates_under_two, iterations) new_points += 1 else if data[0] == data[1] # iterates_under_two == explored_iterations if data[1] < iterations # recompute this point at higher iterations number = Complex(*point) check = Mandelbrot.new(number, iterations) iterates_under_two = check.bounded_iterates @map.set(point, iterates_under_two, iterations) recompute += 1 else # maximum iterate is under 2 reused += 1 end else # iterates already exceed 2 reused += 1 end end points_left -= 1 # progress if checkpoints.size > 0 && points_left < checkpoints.last print '.' checkpoints.pop end end puts ']' percent_reused = (reused.to_f / number_of_points * 100).round 2 percent_new = (new_points.to_f / number_of_points * 100).round 2 percent_recompute = (recompute.to_f / number_of_points * 100).round 2 t1 = Time.now - t0 puts timestamp + " #{number_of_points}".red + " points analyzed in " + "#{t1.round(3)}".cyan + " seconds" puts "#{reused} points reused (#{percent_reused}%).".green + " #{new_points} new points computed (#{percent_new}%).".cyan + " #{recompute} points recomputed (#{percent_recompute}%).".magenta { reused: reused, new_points: new_points, benchmark: t1} end private def timestamp "[#{Time.now.strftime('%T.%L')}]".magenta end end
class Departments::EmployeesController < ApplicationController # Developer: Marco & Marius # === Callbacks === before_action :set_department, only: [:index, :cut] def index @employees = Employee.where(department_id: @department.id) end def cut set_employees employees_id_array = params[:format].split('/') if employees_id_array.size == 1 @employee = Employee.where(id: employees_id_array) cut_salaries(@employee) else cut_salaries(@employees) end @employees.reload end private def cut_salaries(employees) unless employees.nil? employees.each do |e| e.cut end end end def set_department @department = Department.find(params[:department_id]) end def set_employees @employees = Employee.where(department_id: @department.id) end end
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.integer :price t.text :body t.string :alias, :unique => true t.belongs_to :subcategory t.timestamps end end end
require 'yaml' MESSAGES = YAML.load_file('loan_calculator_messages.yml') def prompt(message) puts ">> #{message}" end def retrieve_input(input_type, valid_input) input = nil loop do prompt(MESSAGES[input_type]) input = gets.chomp break if valid_input?(input) prompt(MESSAGES["#{input_type}_invalid"]) end input end def valid_input?(input) /^\d+$/.match?(input) end def valid_decimal?(amount) amount.to_f.to_s == amount && amount >= 0 end def monthly_apr(rate) rate.to_f/ 100 / 12 end loan_amount = nil apr = nil months = nil prompt(MESSAGES['welcome']) prompt(MESSAGES["welcome2"]) retrieve_input(loan_amount, valid_input?(loan_amount)) prompt(MESSAGES['total_loan_amount'] retrieve_input(apr, valid_apr?(amount)) prompt"Your APR is #{apr}%" loop do prompt(MESSAGES['duration']) months = gets.chomp break if valid_whole?(months) prompt(MESSAGES['duration_invalid']) prompt(MESSAGES['month_equation']) end month_interest = monthly_apr(apr) loan_amount = loan_amount.to_i total = loan_amount * (month_interest / (1 - (1 + month_interest)**(-months.to_i))) total = total.to_f.round(2) prompt"Your initial loan of $#{loan_amount}, at an annual rate of #{apr}% for" prompt"#{months} months will result in a monthly payment of $#{total}."